text:
Q: List Comprehension Alternative code for For Loop My code:
a = ['1', '2', '3', '4', '5']
k = 2

# where k is denoting the number of steps of rotations in an array.

for i in range(k):
    a = a[-1:] + a[:-1]

My expected Output:
['4', '5', '1', '2', '3']

How can I write this in List Comprehension?
I've tried this:
a = [a[-1:] + a[:-1] for i in range(k)]

Because I want to use List Comprehension Instead of For Loop.
I've heard that List comprehension is quicker than For Loop.

A: Check out this code: Make some tweaks in your code.
Here logic over which this code work is, take last-kth items in reverse order which is done by condition i <= k and add last-element using a[-1] and for other n-k items, where; n: no of items in a object add directly by help of a[abs(k-i)], here

3-i takes value 0, -1, -2, -3 . . . .
but we want index as 0, 1, 2, 3 for first n-k items so use abs(3-i)
a = ['1', '2', '3', '4', '5']
k = 2
a = [a[-i] if i <= k else a[abs(k+1-i)] for i in range(1, 6)]
print(a)

OUTPUT:
['5', '4', '1', '2', '3']


text:
Q: read a file of records, extract fields into VLA's, using insertion sort, search for user-specified target using binary search, print out result I get the following errors:
search.c: In function 'main':
search.c:44: warning: passing argument 2 of 'fscanf' makes pointer from integer without a cast
    /usr/include/stdio.h:447: note: expected 'const char * restrict' but argument is of type 'int'
search.c: In function 'checkGrades':
search.c:65: warning: comparison between pointer and integer
search.c:65: warning: comparison between pointer and integer
search.c:77: warning: 'return' with no value, in function returning non-void

Im basically a beginner in C so Im not quite sure how to correct these.
here is my entire code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>

#define TNARRAY_MAX  4096
#define LINE_MAX     200
#define FILENAME_MAX 4096
#define NAME_LEN     25
#define ID_LEN       6
#define SCORE_MAX    5

typedef struct
{
    char firstName[NAME_LEN + 1];
    char lastName[NAME_LEN + 1];
    char id[ID_LEN + 1];
    int score[SCORE_MAX];
    char grade;
} STUDENT;

int checkGrades(STUDENT grades[], int maxrecs, FILE* fp);

int main()
{
    char *file_name[30];
    FILE* fp;
    int rc;
    int i;
    int count = 0;
    STUDENT grades[TNARRAY_MAX];

    scanf("%s", file_name);
    fp = fopen("grades.csv", "r");

    if(fp == NULL)
    {
        printf("Error opening file for read.\n\n");
        exit(1);
    }

    fscanf(fp, TNARRAY_MAX, grades);

    //count = checkGrades(grades, TNARRAY_MAX, fp);
    return 0;
}

int checkGrades(STUDENT grades[], int maxrecs, FILE* fp)
{
    char line[LINE_MAX];
    int rc;
    int count = 0;

    while(fgets(line,LINE_MAX, fp) != NULL)
    {
        rc = sscanf(line,
                    "%25[^:]%*c%25[^:]%*c%6s%*c%3d%*c%3d%*c%3d%*c%3d%*c%3d%*c%2c",
                    grades[count].firstName,
                    grades[count].lastName,
                    grades[count].id,
                    &grades[count].score[0],
                    &grades[count].score[1],
                    &grades[count].score[2],
                    &grades[count].score[3],
                    &grades[count].score[4],
                    &grades[count].grade);

        if( (rc != 9) ||
            grades[count].id < 100000 ||
            grades[count].id > 999999 ||
            grades[count].grade < 0 ||
            grades[count].grade > 110 )
        {
            printf("Invalid Record: %s", line);
        }
        else
        {
            count++;
            if(count == TNARRAY_MAX) break;
        }
        printf("NAME: ", grades->firstName);
    }

    return;
}

any help would be appreciated!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Button Programming in a Tab Bar Navigation App I have an application that has 4 views that are toggled by Tab Bar navigation. The first view (Tab bar Item 1) has a button on its view that when clicked, needs to move the user to the 2nd view (Tab bar item #2). What are the steps needed to do such a thing?
Here is a screenshot of the button and as you can see, nothing has been attached yet. Would love to know the best way to hook up this button either through IB or code.
Thanks in advance

A: I'm not sure why you would use a custom button to replicate the functionality of the button in the tab-bar, but in a nutshell what you need to do is:

*

*Link the "Touch Up Inside" outlet to an IBAction method in the view-controller for the first tab-bar item (just click and drag from the circle up to "File's Owner", which should be your view-controller class).

*In the method implementation, simply call [myTabBarController setSelectedViewController: tab2Controller] (alternately you can use [myTabBar setSelectedIndex:1] to do the same thing).

That's all there is to it.

A: You need four IB actions you need to link each button to each action, and each action does the work of changing the screens.

A: Just hook the buttons Touch Up Inside to a method in your Code.
In this method you just do
[tabBarController setSelectedIndex:1]; //Index 1 = 2nd Tab

and it will switch to your 2nd Tab

A: Create an action that you hook up the button preferably on "Touch Up Inside":
In .h file:
- (IBAction)readAboutItButtonTouched:(id)sender;

In .m file:
- (IBAction)readAboutItButtonTouched:(id)sender {

    [self.tabBarController setSelectedIndex:1];
}


text:
Q: Add items to an array without duplicates with using Map object I'm trying to add new values to an array without duplicates.
I'm using Map object to hold the previous array and trying to filter the new array
const [items, setItems] = useState([]);

    const res = () => {
        const map1 = new Map(
            arr.map(obj => {
                return [obj.id, obj];
            })
        );

        setItems([map1, ...data.result.filter(x => x.id !== map1.forEach((val, key) => key))]);
    };

How to accomplish this iteration successfully? Are there other ways with using Map object that would be better in this case?

A:
How to accomplish this iteration successfully?

To test map membership you should not iterate the map. The advantage of a map is that you can check for membership with has. Also, you should not include the map as the first element of the new array, but spread the original arr (or the values of the map):
setItems([...arr, ...data.result.filter(x => !map1.has(x.id)]);

Are there other ways with using Map object that would be better in this case?

You could first join the new data to the array and then extract the unique values from it via a Map:
const res = () => {
    const map1 = new Map(
        data.result.concat(arr).map(obj => {
            return [obj.id, obj];
        })
    );

    setItems([...map1.values()]);
};

Note that data.result is put in front of arr so to ensure that the existing value has precedence when there is a duplicate. If you prefer that the new value would need to overwrite the previous value for the same id, then reverse that order. If you want the old value to remain, and you want the really new elements to occur at the end of the array, then do:
        arr.concat(data.result, arr).map(obj => {
            // ...etc


text:
Q: Elasticsearch spatial search with terms I am running a query on 140+ million documents with spatial data. Purely spatial queries are extremely fast (sub 1s). Adding a wildcard to the same geometry results in the query taking ~10-20s. I expect wildcard queries to take some time, but I want to know if there is a better way to write the query or trick Elasticsearch into filtering the results to only the geometry and then finding wildcard matches. Or, maybe running the spatial query and then running the wildcard on the resulting doc ids? Any ideas which may result in faster results for the end user would be appreciated.
GET parcels/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "wildcard": {
            "name.keyword": {
              "value": "*smith*"
            }
          }
        },
        {
          "bool": {
            "filter": [
              {
                "geo_shape": {
                  "shape": {
                    "shape": {
                      "type": "POLYGON",
                      "coordinates": [
                        [
                          [
                            -81.09980486601305,
                            32.063655184739936
                          ],
                          [
                            -81.09980486601168,
                            32.05639855631687
                          ],
                          [
                            -81.09128330779276,
                            32.05639855631687
                          ],
                          [
                            -81.09128330779276,
                            32.06365489826756
                          ],
                          [
                            -81.09980486601305,
                            32.063655184739936
                          ]
                        ]
                      ]
                    },
                    "relation": "intersects"
                  }
                }
              }
            ]
          }
        }
      ]
    }
  },
  "size": 10000
}

our settings for the index:
{
...
"analysis": {
    "normalizer": {
        "search_normalizer": {
            "filter": [
                "uppercase"
            ],
            "type": "custom"
         }
     }
},
"number_of_shards": 8,
"number_of_replicas": 1,

mapping for the 'name' field:
"name": {
    "type": "text",
    "fields": {
        "keyword": {
            "type": "keyword",
            "normalizer": "search_normalizer"
        }
    }
},

Running ES 7.10. (5 nodes each with 8GB RAM)
Not searching by wildcard is not an option.
Any help is appreciated.

A: Using a wildcard search with a prefix wildcard (as in *smith*) on a keyword field is a performance killer!
If you absolutely need this kind of functionality, you need to leverage the new wildcard field type which is meant exactly for this kind of use.
So you can either add another sub-field or change the keyword sub-field to a ?wildcard` sub-field.
You can see how it works under the hood in the blog article where the wildcard field was described when it came out.


text:
Q: Using TMB to take a weighted mean over posteriors First off, I'm brand new to TMB, and fairly new to working with SPDE models as well.
I would like to combine posteriors from several SPDE models using a weighted mean (weights reflecting the variance in each posterior). Is this possible to do in TMB?
Thanks


text:
Q: Cannot set prototype of SpeechSynthesisVoice manually This question is somewhat for understanding the prototype get-set.
I've a scenario where I need to map the SpeechSynthesis supported voice to Google Translation API supported language codes.
For example,

Now, I can do the same by either fetching the voices runtime or by storing the voice and hard-coding the mapping in some method in javascript.
If I go for runtime approach, I need to call getVoice() in speechSynthesis.onvoiceschanged = () => {} and then map the numbers, which gets called in every voice change event. So, I want to go for hard-coding one.
Now, when I store the mapping array in a variable and call it by index, I get the SpeechSynthesisVoice Object, just like what we do in getVoices()[index].
Further, If I set this object value to speechSynthesis.voice, I get an error:
Uncaught TypeError: Failed to set the 'voice' property on 'SpeechSynthesisUtterance': The provided value is not of type 'SpeechSynthesisVoice'.

This is due to mis-match of prototype of the manually stored object value.
For example,
1. SpeechSynthesisVoice object:

2. Manually stored value of SpeechSynthesisVoice object:

To resolve, this I've fetched the proto of the SpeechSynthesisVoice object using getVoice(), and then set it to a variable and further, set this variable to my manual mapped object.
Like,
Get:
voicePrototype = getVoices()[9].__proto__;

Set:
voices[index].SpeechSynthesisVoice.__proto__ = voicePrototype;

And, it gets set, as in below screenshot:

I've also tried through Object.setPrototypeOf() and got the same result.
Now, again when I want to set this object to speechSynthesis.voice, I still get the same error, although my prototype matches.
Can anyone, please advise, if its possible to set the object proto likewise and use it? Thanks in advance.


text:
Q: Scanning other barcodes additional than QR code using Android's Mobile Vision API Using the barcode detector for mobile vision api, i notices that there are problems scanning formats that are not QR codes.
Im using the latest version of play services (10.2.1), and the barcode generator im using was build like the following:
BarcodeDetector detector = BarcodeDetector.Builder(appContext).build()
Here i have the screenshot for the issue.
screenshot for scanning barcode
Best regards,


text:
Q: "error adding symbols: DSO missing from command line" while compiling g13-driver I'm trying to compile the download received here: https://code.google.com/p/linux-g13-driver/ by running make but I'm receiving errors that to me, after searching on the web, look like they're the programmers fault but here they are:
g++ c-source/G13.o c-source/G13Action.o c-source/Macro.o c-source/MacroAction.o c-source/Main.o c-source/Output.o c-source/PassThroughAction.o -o Linux-G13-Driver  -lusb-1.0
/usr/bin/ld: c-source/Main.o: undefined reference to symbol 'pthread_kill@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
make: *** [Linux-G13-Driver] Error 1

If anyone has any ideas please help I really want to get this running

A: Edit the lines as shown below in the makefile and it should compile:
FLAGS    = -L /lib64
LIBS     = -lusb-1.0 -l pthread


text:
Q: Replacing Fragment Inside of ViewPager Opens the Fragment in ViewPager Dimensions Fragment A contains ViewPager which has Fragment B. Fragment B contains a RecyclerView and clicking on its items, opens Fragment C.
Open Fragment C (implemented by Fragment B)
private void openItemPage(long id) {
        Fragment a2Fragment = CompanyPageFragment.newInstance(id);
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();

        // store the Fragment in stack
        transaction.addToBackStack(null);
        transaction.replace(R.id.container, a2Fragment).commit();
    }

Fragment A Layout
<LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingTop="15dp">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:background="@drawable/top_bottom_border"
            app:tabBackground="@android:color/transparent"
            app:tabIndicatorHeight="0dp"
            app:tabMode="fixed">
        </android.support.design.widget.TabLayout>

        <ir.barandeh.android.views.NonSwipeableViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:overScrollMode="never"/>
    </LinearLayout>

Fragment B Layout
<RelativeLayout android:id="@+id/container"
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

    <android.support.v4.widget.ContentLoadingProgressBar
        android:id="@+id/contentLoading"
        style="?android:attr/android:progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:overScrollMode="never"
            android:paddingEnd="10dp"
            android:paddingStart="10dp">

        </android.support.v7.widget.RecyclerView>

    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>

Fragment C Layout
<RelativeLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="?android:attr/windowBackground">

            <android.support.v4.widget.NestedScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fillViewport="true"
                app:layout_behavior="@string/appbar_scrolling_view_behavior">

                <ir.barandeh.android.views.NonSwipeableViewPager
                    android:id="@+id/pager"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:overScrollMode="never"/>
            </android.support.v4.widget.NestedScrollView>

    </RelativeLayout>

The problem is, Fragment C content is shown inside of the ViewPager not whole Fragment A layout.

A:
You're trying to programmatically replace a LinearLayout, while also
  expecting it to have the hard-coded children. This won't work. You
  should use a FrameLayout for your FragmentTransaction that is also a
  child of your layout_root.

Quoted from https://stackoverflow.com/a/18885196/3749773. Thanks to Paul Burke
Another mistake was calling getChildFragmentManager() from Fragment B but I had to call it from Fragment A. Thanks to frozenkoi


text:
Q: Why do different actors play different versions of Spider-Man? First came the Spider-Man series starring Tobey Maguire.
Now he's played by Andrew Garfield (in The Amazing Spider-Man).
Why didn't they just make a new generation, such as the first Spider-Man's son?

A: The reason for the different actors is because it is a different universe. The two movie series are based on two separate Spiderman story lines. In which the characters are very different including the different love interest, Mary Jane for Spiderman's original universe and Gwen Stacy in the Amazing Spiderman. The characters sometimes overlap but they do not interact in the same way in the different universes.

A: My guess is that it's basically a matter of focus testing and wanting to stick to what the average film goer is familiar with.
The general population knows that historically speaking, Peter Parker is Spider-Man. This fact changes in the comics, but the average man-on-the-street - if they know Spider-Man's identity will likely say Peter.
When The Amazing Spider-Man was released, many viewers (like my mother) who didn't follow the production or the trailers closely, went in not understanding that the film was a reboot of the franchise, despite it not being hidden or denied by the studio at all. They just assumed that it was a new Spider-Man and that it must be a continuation of the Raimi/Maguire movies.
To begin a new franchise - with the same titular character and a different identity would only confuse the average viewer.
Studios also run the risk of confusing or upsetting fans or people vaguely familiar with the characters.
Take the examples of Kingpin, Nick Fury or even Perry White. Historically, all three are white males in the comics. Many fans were outraged that Michael Clarke Duncan was chosen to play Kingpin, or that Lawrence Fishburne was chosen to play Perry White. There was even confusion as to just why Nick Fury was being played by Samuel L Jackson - even though the Ultimate version of Nick Fury was based on him.
In the end, while literally taking a character to a whole new generation, it can be more trouble than its worth financially - and that's all the studios care about.

A: The reason there are different characters playing Spider-man because they are completely different imaginings of it.
Think about this, in Toby's Spiderman series Spider-man was able to shoot web from his palms.
Now in the comic books he never had this ability until I believe it was well into the comic book series.
The new series is a remake of the Spiderman franchise trying to follow in a closer path to the comic book, hence why Andrew creates the webshooters like in the comic book.
Anytime you see a movie about a Superhero or comic in general and they change actors it's most likely because they are doing a complete and separate story than the previous one.
Same thing happened with The Hulk and The Incredible Hulk, two completely different imaginings of the Hulk with different actors.


text:
Q: Do Salesforce developers use Git? How? Do Salesforce developers use Git? If they do, how does their development cycle look?
How do they  import projects?  Do they do that manually like "create zip - deploy using Ant"? Or maybe there is a closer connection between Salesforce and GitHub, for example?
For example, I want deploy a project from GitHub. Some installed packages are used in it and I don't know which exactly. I can see only namespaces. How can I solve that? And generally what steps should I perform to accomplish deployment?

A: I presented two sessions at Dreamforce last year on the development and release workflow we've built at the Salesforce Foundation for our own development projects.  We've released all the code (build scripts, automation scripts, etc) as open source with the intention of building a community of Salesforce developers facing similar challenges.
The best overview available is the video of the sessions themselves.  The first is an overview of the whole process and the second is a more hands on demo of wrapping the process around an existing project in GitHub:

*

*Automating the Impossible: End to End Team Development for ISVs

*Reusable Build Scripts for Managed Package Development
The challenge in using GitHub for Salesforce development is connecting the two.  I'd argue that the most important thing to get right from the beginning is good build scripts that can automate the different types of deployments you'll need to do from GitHub to a Salesforce org.
You didn't specify if you are building managed packages or not so I'll give the caveat that our process is currently designed for use in managed package development.
As for your question about handling dependencies on other packages, that is something our process was built to handle.  We have a single file in the root of the repository that specifies the namespace and version of each required packages.  The build scripts use this file to automatically install the correct version of the packages as part of the build:
https://github.com/SalesforceFoundation/Cumulus/blob/dev/version.properties

A: There is eclipse plugin for git. You can use that to interact with your git repo.
Other option is you can use command prompt to interact with git and Eclipse with SFDC. Here is great blog that tell you all the required steps to interact with git using command propmt.
On high level here are steps for you:
1) Fork the new brach and get the code in your work space
2) Add the Upstream origin to your local Git repository
3) Go into the Force.com IDE, create a new Force.com project.
4) When the system prompts you for which metadata components you want to install, select the none
    option
5) Now you will see the code in your work space which you branched from Master
6) In order to push your changes, you will need to first add them.
7) and the finally push them to Master.

A: As for me, I was trying to use Git plugin for Eclipse. I didn't like how it works.
I ended up with separate folder where project is for Eclipse, and separate Git folder. After I finish implementation, I copy files from Eclipse's folder to Git's.
Need to get changes from Git? Copy from Git's to Eclipse's and refresh project in Eclipse.
I don't deal with packages. They already in place after I create a project in Eclipse.

A: Yes you can use github integration in salesforce projects. If you are using Eclipse Force.com IDE, you can see more information for the eGit plugin.
More Info: Git version control with Eclipse (EGit)
The plugin can be used for both deployment to git as well as fetching from a remote branch. Refer the provided link

A: There are 3 sets of questions. I am not sure if I can answer the last one.

*

*Salesforce developers do use Git, either through in-house repositories or online repository hosts such as Github, Bitbucket etc.  The following blog post goes into details of a typical development cycle:
http://blog.deadlypenguin.com/blog/2014/07/21/using-git-with-salesforce-and-distributed-teams/

*Projects that develop for the force.com platform often use a combination of Force.com Migration Tool (FMT)  or Eclipse and Ant build scripts to automate fetching from Git branches and deploy to target environments. One could also set up a continuous integration (CI) infrastructure, especially if the project is structured as short sprints. Here is an excellent article on how to setup Jenkins as a CI provider for Salesforce:
https://developer.salesforce.com/blogs/developer-relations/2013/03/setting-up-jenkins-for-force-com-continuous-integration.html

A: We have apps like AutoRABIT in appexchange which does give automatic support to version control. i.e. Automatically fetches changes from salesforce and commits to version control(Git,SVN etc..)
  The following are the sample screenshots from this app.

Thanks,
Naveen.

A: You can refer this blog article as well to understand how we can use Salesforce developement with Git using Eclipse plugin.


text:
Q: compare two multidimension and associative arrays and get the difference I need to compare two arrays like this
// currently in our database
$firstArr = array(
        ["id"=>1, "another_id"=>1],
        ["id"=>2, "another_id"=>4],
        ["id"=>5, "another_id"=>9]
);

// currently fetched from csv-files
$secondArr = array(
        ["id"=>6, "another_id"=>3],
        ["id"=>2, "another_id"=>7],
        ["id"=>1, "another_id"=>1]
);

The first array represents the data that is currently in our database, meanwhile the second one  represents the data that is delivered from an csv-file.
In order to not delete the whole data from the database, I need to compare the two array's. If the csv-file offers data that is not in the database, I want to input these data sets. If the database includes data that is not in the csv-file, I want to remove them from the database.
I come up with a solution that works for a small amount of data in the arrays:
$new_to_database = array();
foreach($secondArr AS $arr){
    $in_database = array_filter(array_map(function($el) use ($arr){
        if($el['id'] == $arr['id'] && $el['another_id'] == $arr['another_id']){
            return $el;
        }
    }, $firstArr));

    if(count($in_database) === 0){
        $new_to_database[] = $arr;
    }
}

var_dump($new_to_database);   // input later on
// array(2) { [0]=> array(2) { ["id"]=> int(6) ["another_id"]=> int(3) } [1]=> array(2) { ["id"]=> int(2) ["another_id"]=> int(7) } }

The problem is that each array includes round about 5000 data sets. As a result the script takes far to long and I get the error that the execution time of 360 seconds is exceeded.
How can I solve this? I guess the algorithm should be way more efficient.

A: You can index each array by the id and then compute the difference in the keys:
// Get items that are in CSV but not in database
$new = array_diff_key(array_column($csv, null, 'id'), array_column($db, null, 'id'));

// Get items that are in database but not in CSV
$del = array_diff_key(array_column($db, null, 'id'), array_column($csv, null, 'id'));

Here's a DEMO using two simple arrays of 50,000 items each.
That's short and sweet but you may not want to run the array_column multiple times:
$csv = array_column($csv, null, 'id');
$db  = array_column($db, null, 'id');

// Get items that are in CSV but not in database
$new = array_diff_key($csv, $db);

// Get items that are in database but not in CSV
$del = array_diff_key($db, $csv);

To compare the entire array contents (this will work if you add more than just id and another_id), you can map each array and serialize into a string representation and compare.  Note that the order of the elements matters as well:
// Get items that are in CSV but not in database
$new = array_map('unserialize',
                 array_diff(array_map('serialize', $csv), array_map('serialize', $db)));

// Get items that are in database but not in CSV
$del = array_map('unserialize',
                 array_diff(array_map('serialize', $db), array_map('serialize', $csv)));

On the DEMO site this one worked for 40,000 array items but not 50,000.  This will depend on your resources and php.ini settings.

There's also an array_intersect_key and array_intersect if you want to see what is the same in each array.

A: You are doing a lot of loops. foreach, array_filter and array_map use a lot of time.
$new_to_database = array_udiff($secondArr, $firstArr, function ($s, $f) {
    if ($s['id'] == $f['id'] && $s['another_id'] == $f['another_id']) {
        return 0;
    } else {
        return -1;
    }
});

This gives the results you need with less iterations.


text:
Q: Help troubleshooting an unstable 595 shift register Summary
I am looking for help troubleshooting a couple of shift registers that seem to be unstable in a digital wall clock that I've built back when I was active in this stack, back in 2014.
More than fixing the clock, I'd like to learn how to troubleshoot and identify problems with shift registers when they show signs of instability, preferably using an oscilloscope.
The Device Under Test (DUT)
The clock being troubleshot is this one below.

In the picture above, it's displaying the right time and date - 16:22 (4:22PM) on 23/04/22 (04/23/22) - at the time the picture was taken, obviously :D
It used to work fine until the two first digits (the ones displaying the hour above - 16) started to flicker like in the animated GIF below.

The (sub-optimal, noob level) Design
For reasons, I didn't want to multiplex the digits, so I designed the clock so that every segment on every digit was driven by a separate port on a shift register. Each 7-segment display digit is driven by a combination of a 595 shift register and a Darlington pair from a ULN2003. The registers are then daisy-chained together in a total of 10 "modules" to drive all 10 digits. The whole clock is controlled by an ATMega328P-PU MCU.
Below are the schematics of the three boards that make up the design (one controller and two digit driver boards). Please bear in mind that it is a very sub-optimized design made by a hobbyist with archaic (pre-1950) building capabilities, who thought himself electronics (mostly from this very own stack!!). It's not designed to be mass produced or even to exist beyond this single prototype.

The schematics above is for the control board. It contains the microcontroller and other modules (like a serial RS-232 driver, the real-time clock IC and battery cell, a 434MHz radio signal receiver for the remote control etc.). This is connected to two other boards that contain the shift registers and Darlington pair ICs. They are connected through connectors JP1 and JP2, which have short cables connecting them. Their schematics are below.

The schematic above is used to control the 4 larger 7-segment digits that display the time of day, and are placed on top of the clock. There's another similar board that controls the lower 6 digits, that show the date (similar schematics, which I don't have, just with 2 extra digit driver modules.)
More details about the desing:

*

*The 7-segment display digits are 12V commom-cathode (CC). They are connected to VIN and their low side is driven through ULN2003, which in turn are driven by the 595 shift registers; The digits are connected to the pairs of connectors on the top of the 2nd schematics, through connectors SV1+SV2 (digit 1), SV3+SV4 (digit 2), and so on...

*There's a 5V rail (converted down from the 12V rail using an LM7805 linear voltage regulator) to power the control board and its various ICs (MCU, RTC, radio receiver etc) and the display drivers (shift registers); Not much current is drawn from the LM7805, so there's no heating issues that I could foresee;

*All ten 595's are daisy-chained (the ones glitching are the last ones in the chain). They are all driven by the same MCU pair of ports: clock and latch;

*each board has its own serial in, 5V rail and enable signals; the latter are connected to PWM ports to control segment intensity;

*All 595's have their decoupling ceramic 100nF cap (famous 104 cap) placed near their VCC pin (GND pin is on the other side of the package, unfortunatelly);

The Boards
Below are some pictures of all the boards.

Troubleshooting So Far
The problem, as seen in the short film above, is a glitch on two of the digits, namely, those driven by IC5+IC6+SV5+SV6 and IC7+IC8+SV7+SV8, on the second schematics. Those are the last ones in the shift register chain.
I do own a 70MHz Agilent entry level oscilloscope, but I don't know exactly what to probe to find the problem. I looked at all the signals (serial in/out, clock, enable, latch) and rails (GND, 5V, 12V), but no luck. Everything seems to be ok, except for a large ripple (500mV) that I detected on the 5V rail near the shift register VCC pins. They spikes are in sync with the clock (or latch, I don't remember, sorry).
Not being able to determine what is causing the problem, I've tried the following specific fixes to the boards, without any results:

*

*I replaced the glitching 595 and ULN2003, to no avail;

*I replaced the LM7805 voltage regulator and both of its capacitors;

*I switched the order of the 2 daughter boards to check if the problem was with the last registers in the chain. This messed up the digits displayed, but the same digits (two upper left ones) continued to glitch regardless of the order in the register chain;

*Replaced the decoupling cap on IC7 and moved it closer to VCC, because it was farther away from it originally;

The Questions
My main question is whether there's a way to generically troubleshoot a chain of shift registers to fix these kinds of glitches. Where should I put the scope probes on? Is a 500mV ripple on the 5V rail powering the registers too much?
Second question is how to fix my specific problem, described above. What else should I try? Where else should I probe, to check for problems? If you want me to probe any particular points in the boards, I can edit the question and include scope shots if that would help.
Third and last question, could it be that the clock and latch signals are exceeding the fan out of the respective MCU ports? Could this be the problem? How do I check with a scope? Should I break them down to control two sets of five digits separately?
It's really nice to get back here after so many years and meet some friends again. I hope to hear from you really soon.
Thanks for reading!!!

A: Without specific knowledge of your circuit and especially how your setup was to determine 500 mV ripple, this number caught my attention.
If you have a very large area formed by your ground lead from your probe going somewhere else on the board, several cm away, this may just be an artifact from bad probing. If you on the other hand have very good setup, this is a very high figure of 10 % ripple.
While 4.5 V is not enough to put your circuits out of Vcc spec, you will have a plethora of other effects which will degrade your signal integrity. For a clocked system, this is even worse.
I do see in your schematic that you have ceramic decoupling capacitors for some of your ICs, but no value stated in the schematic. Ideally, you want at least 100 nF as close to the Vcc and GND pins of each IC as possible. To make matters worse, a two layer board with lots of though holes for your components will degrade your ground plane a lot due to less capacitance and more inductance.
As a first step, add more decoupling, at least one 100 nF for each IC.
Ideally, move to SMD components in order to not penetrate the ground plane. Even better would be a four layer design with an unbroken ground layer.
Here is an example I borrowed from https://www.reddit.com/r/AskElectronics/comments/ttbcg2/question_about_decoupling_capacitor_with_ic/?utm_source=share&utm_medium=ios_app&utm_name=iossmf:

The vias will connect to a ground plane below the top layer.

A: Two major culprits I've found are crosstalk and as you've suggested, fan-out on the CLK predominantly. Crosstalk can be mitigated in your case by separating the wires whereas if you'd used a flat cable, then you'd need to have gnd circuits interspersed between the signals.
Adding buffers like 74HC125 or 74HC244 to provide better drive of the clk signal should improve your situation. Also consider ground bounce, so ensure your gnd wiring is heavy enough a wired to a common star point if possible.
How to debug? This can be tricky due to what the others have commented. Ground bounce can confuse the situation depending on where your scope ground lead is connected. There's ringing, crosstalk and setup/hold timing. The setup/hold timing gets worse the further along the chain you go.

*

*Ground bounce - put the scope ground lead at the driver end. Probe the gnd at each of the sub-boards. You hope that the amount of bounce is < 1V. Less is better.

*Cross talk. Scope the clock and the data lines. If the clock glitches when the data changes, that is probably cross talk. It is also possible your latch signal induces a glitch onto the clk.

*Setup and hold timing. Scope your clock and data lines. The data should be stable for the require time before the clock edge and held for the required time after the clock edge. Refer to the HC595 datasheet for the actual times.

A: For years I've always had problems with the 595. I've tried different decoupling caps and filtering on control lines.... just about everything suggested by everyone in this article.
The main issue with the 595 is the Serial Clock. I eventually found that the changing the clock SLEW RATE solved everything. It seemed that the data been clocked would be out by a bit or 2.
I ran the Clock from the SPI port on the microcontroller at 1MHz. A simple LOW PASS RC filter on the Clock solved everything. At 1MHz I used a 1K resistor with a 22pF cap to ground. The Filter slows the SPI Clock pulse (t=RC) enough for the 595 Clock circuitry to correctly interpret the Signal correctly.
I will never again use the 595 due to the clock issue but this simple fix resolved older boards I had. Also the 595 is a noise detector, If you running the circuit from the same mains supply where large machinery is active it will affect it. Best stay away from 595, its great for a quick fix for small hobby projects (home use) but terrible in industrial applications.


text:
Q: Where does the last parameter of the 'read' function in Linux kernel code point to? In the read function prototype,
ssize_t read(struct file *filp, char __user *buff,size_t count, loff_t *offp);

where does the parameter offp point to?
What I understand from the below write function is that the parameter ppos points to the top of the data available in deviceBuffer[], which is a global buffer in kernel space. Correct me if I am wrong.
How does this apply to read function ?
    static ssize_t mcspi_write(struct file *filp, const char *buff, size_t length, loff_t *ppos)

    {

    int maxbytes; /* maximum bytes that can be written */
    int bytes_to_write;
    int bytes_written = 0;
    //int i;

    maxbytes = BUFFER_SIZE - *ppos;
    if(maxbytes < length)
        bytes_to_write = maxbytes;
    else
        bytes_to_write = length;
    bytes_written = bytes_to_write - copy_from_user(deviceBuffer + *ppos, buff, bytes_to_write);
    /*
       for(i = 0; i < 1024; i++)
       {
       printk(KERN_INFO "deviceBuffer[%d] = %x\n", i, deviceBuffer[i]);
       }
     */
    printk(KERN_INFO "%s: %d bytes copied from user space\n", DEVICE_NAME, bytes_written);
    *ppos += bytes_written;

    return bytes_written;
}


text:
Q: Database model for different range of prices for products I am trying to design a database for prices of metal rods. The metal rods are priced based on the following logic.

*

*If the bar is made of iron it is priced per kg.

*If the bar is made of steel it is priced per kg.

*If the bar is made of aluminum it's price is based on the length.

*Potentially new ways to price a rod.

The problem I am having is how to link the material to a price with the consideration of the two types of pricing rules, by weight or by a range.
For example this is how I would "draw" the table, all the prices are completely made up.
+-----------+------------------+
| Material  | Price            |
+-----------+------------------+
| Iron      | $0.5             |
+-----------+------------------+
| Steel     | $0.8             |
+-----------+------------------+
| Aluminium |+--------+-------+|
|           || Length | Price ||
|           |+--------+-------+|
|           || 100mm  | $10   ||
|           || 200mm  | $18   ||
|           || 500mm  | $35   ||
|           || 1000mm | $50   ||
|           |+--------+-------+|
+-----------+------------------+

I am using MySQL.
I am very new to SQL so I do not know where to even begin with this. I'm stuck because I don't now how to break down the one-to-one and one-to-many in the same column. with the additional requirement.

A: For an extendable design you could have:
metal, unit_type_id, units, price
Iron, 1, 1, 0.5
Steel, 1, 1, 0.8
Aluminium, 2, 100, 10
Aluminium, 2, 200, 18

with another table unit_type
id, type
1, weight (kg)
2, length (mm)

A: this model should go for every new type or price changes. You can also extend it to manage old prices history
idMaterial    material  idPriceType
-----------------------------------
1              iron        1
2              steel       1
3              alu         2

idPriceType   name     unit
---------------------------------
1             weight   kg
2             length   mm

idMaterial  price    unitForPrice
---------------------------------
1           0.5      1
2           0.8      1
3           10       100
3           18       200
3           35       500
3           50       1000


text:
Q: Gerar mais de um PDF em memória e exporta-lo em um arquivo compactado Atualmente o código abaixo exporta e compacta o PDF um por vez e preciso exportar vários PDF em um arquivo compactado
public ActionResult PDFTodosMesAtual(ProcessamentoRegistros _processamento)
        {
            try
            {
                string _nomeArquivo = string.Empty;

                //AQUI RETORNO UM LISTA DE DOCUMENTOS HTML QUE SERÁ CONVERTIDO EM PDF
                IEnumerable<ProcessamentoRegistros> _todosHtmlMesAtual = _IRepositorio.ObterTodosHTMLMesAtual();

                if (_todosHtmlMesAtual != null)
                {
                    //TENTEI FAZE ALGO ASSIM, MAS SEM SUCESSO:
                    //foreach (var item in _todosHtmlMesAtual)

                        #region :: converte arquivo html para pdf ::
                        _nomeArquivo = "Documento_Fiscal_" + DateTime.Now.ToString().Replace(" ", "_").Replace("/", "_").Replace(":", "_") + ".zip";
                        MemoryStream file = null;
                        var pechkin = Factory.Create(new GlobalConfig());
                        var _pdf = pechkin.Convert(new ObjectConfig()
                                                    .SetLoadImages(true).SetZoomFactor(1)
                                                    .SetPrintBackground(true)
                                                    .SetScreenMediaType(true)
                                                    .SetCreateExternalLinks(true)
                                                    .SetIntelligentShrinking(true).SetCreateInternalLinks(true)
                                                    .SetAllowLocalContent(true), item.DocumentoHtml.ToString());
                        file = new MemoryStream();
                        file.Write(_pdf, 0, _pdf.Length);

                        byte[] arquivo = _pdf;
                        #endregion

                        #region :: compacta e faz o download do arquivo pdf ::
                        using (var compressedFileStream = new MemoryStream())
                        {
                            using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false))
                            {
                                var zipEntry = zipArchive.CreateEntry("documento.pdf");
                                using (var originalFileStream = new MemoryStream(file.ToArray()))
                                {
                                    using (var zipEntryStream = zipEntry.Open())
                                    {
                                        originalFileStream.CopyTo(zipEntryStream);
                                    }
                                }
                            }
                            return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = _nomeArquivo };//return RedirectToAction("Index", "Documento");
                        }
                        #endregion

                }
                else
                {
                    return RedirectToAction("Index", "Documento");
                }
            }
            catch (Exception ex)
            {
                ViewBag.MsgErro = string.Format("Download não efetuado! " + ex.Message.ToString());
                return RedirectToAction("Index", "Documento");
            }
        }

Iniciei esse post aqui inserir a descrição do link aqui com créditos do Geroge Wurthmann

A: O código é bem parecido com o dessa resposta.
Importante dizer que você está utilizando System.IO.Compression para compressão nativa com C#.
Assim deverá funcionar no seu código:
public ActionResult PDFTodosMesAtual(ProcessamentoRegistros _processamento)
{
    try
    {
        string _nomeArquivo = string.Empty;

        //AQUI RETORNO UM LISTA DE DOCUMENTOS HTML QUE SERÁ CONVERTIDO EM PDF
        IEnumerable<ProcessamentoRegistros> _todosHtmlMesAtual = _IRepositorio.ObterTodosHTMLMesAtual();

        if (_todosHtmlMesAtual != null)
        {
            #region :: converte arquivo html para pdf ::
            List<byte[]> meusPDFs = new List<byte[]>();
            foreach (var item in _todosHtmlMesAtual)
            {
                _nomeArquivo = "Documento_Fiscal_" + DateTime.Now.ToString().Replace(" ", "_").Replace("/", "_").Replace(":", "_") + ".zip";
                MemoryStream file = null;
                var pechkin = Factory.Create(new GlobalConfig());
                var _pdf = pechkin.Convert(new ObjectConfig()
                                            .SetLoadImages(true).SetZoomFactor(1)
                                            .SetPrintBackground(true)
                                            .SetScreenMediaType(true)
                                            .SetCreateExternalLinks(true)
                                            .SetIntelligentShrinking(true).SetCreateInternalLinks(true)
                                            .SetAllowLocalContent(true), item.DocumentoHtml.ToString());
                file = new MemoryStream();
                file.Write(_pdf, 0, _pdf.Length);
                meusPDFs.Add(_pdf);
            }

            #endregion

            #region :: compacta e faz o download do arquivo pdf ::
            using (var compressedFileStream = new MemoryStream())
            {
                //Informações sobre o GetEncoding: https://msdn.microsoft.com/en-us/library/system.text.encodinginfo.getencoding(v=vs.110).aspx
                Encoding nomeArquivoEncoding = Encoding.GetEncoding(850);
                //Cria um arquivo ZIP e armazena na memória (memory stream) com enconding 850
                using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false, nomeArquivoEncoding))
                {
                    int i = 1; //Só uso essa variável para dar nome diferente pra todos PDFs
                    foreach (var pdf in meusPDFs)
                    {
                        //Criar uma entrada para cada anexo a ser "Zipado"
                        var zipEntry = zipArchive.CreateEntry("MeuPDF"+i);

                        //Pegar o stream do anexo
                        using (var originalFileStream = new MemoryStream(pdf))
                        {
                            using (var zipEntryStream = zipEntry.Open())
                            {
                                //Copia o anexo na memória para a entrada ZIP criada
                                originalFileStream.CopyTo(zipEntryStream);
                            }
                        }
                        i++;
                    }
                }
                return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "MeusPDFs_" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".zip" };
            }
            #endregion

        }
        else
        {
            return RedirectToAction("Index", "Documento");
        }
    }
    catch (Exception ex)
    {
        ViewBag.MsgErro = string.Format("Download não efetuado! " + ex.Message.ToString());
        return RedirectToAction("Index", "Documento");
    }
}

Não testei o código acima, mas o trecho importante pra você, é o de compactar vários PDFs em um único ZIP. Essa parte abaixo que faz isso:
using (var compressedFileStream = new MemoryStream())
{
    //Informações sobre o GetEncoding: https://msdn.microsoft.com/en-us/library/system.text.encodinginfo.getencoding(v=vs.110).aspx
    Encoding nomeArquivoEncoding = Encoding.GetEncoding(850);
    //Cria um arquivo ZIP e armazena na memória (memory stream) com enconding 850
    using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false, nomeArquivoEncoding))
    {
        int i = 1; //Só uso essa variável para dar nome diferente pra todos PDFs
        foreach (var pdf in meusPDFs)
        {
            //Criar uma entrada para cada anexo a ser "Zipado"
            var zipEntry = zipArchive.CreateEntry("MeuPDF"+i);

            //Pegar o stream do anexo
            using (var originalFileStream = new MemoryStream(pdf))
            {
                using (var zipEntryStream = zipEntry.Open())
                {
                    //Copia o anexo na memória para a entrada ZIP criada
                    originalFileStream.CopyTo(zipEntryStream);
                }
            }
            i++;
        }
    }
    return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "MeusPDFs_" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".zip" };
}


text:
Q: Unable to access the classes from a custom swift framwork in iOS I have created a swift framework which contains Obj C classes, and I am trying to use it in my demo app (written in obj c) using development Pods (local cocoa pods), I could able to import the Headers, and I could able to call the methods which are in the framework, but I am getting the following error while compiling the demo app
Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_ClassName", referenced from:
      objc-class-ref in ViewController.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

How do I resolve this? any suggestion would be appeciated
Updates: Define Module is set to YES in framework's build settings, Under Packaging


text:
Q: where (and what) is the error - java cipher i am making a cipher, and for some reason it gives me these errors after i input the text:
enter string to be encrypted:
hello world
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
    at chipher.cipher.encrypt(cipher.java:21)
    at chipher.cipher.main(cipher.java:9)

this is my code:
package chipher;
import java.util.Scanner;
public class cipher {
public static int x;
public static int y;
public static Scanner jon = new Scanner(System.in);
    public static void main(String[] args) {
        System.out.println("enter string to be encrypted: ");
        encrypt(jon.nextLine());
        }

public static void encrypt(String tocipher){
    double lngth = tocipher.length();
    tocipher.toLowerCase();
    char[] mynamechars = tocipher.toCharArray();
    char[] alphabet = new char[]{'a', 'b', 'c', 'd' , 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
for(int i = 0; i<lngth;)
    for(int x = 0; x<26;){
        y = x + 1;
if(mynamechars[i] == alphabet[x]){
    mynamechars[i] = alphabet[y];
}
i++;
x++;
}
    String text = String.valueOf(mynamechars);
    System.out.println(text);
}
}

i don't know what is going on and i am just learning java so it may be something basic, so just bear with me here.

A: You are doing
mynamechars[i]

upto 25 th index and it seems the input you entered is just 10 character long

A: You've got two errors. Your first one is due to the way you wrote the for loops and your lack of indentation:
for (int i = 0; i < lngth;) {
    for (int x = 0; x < 26;) {
        y = x + 1;

        if (mynamechars[i] == alphabet[x]) {
            mynamechars[i] = alphabet[y];
        }

        i++;
        x++;
    }

    String text = String.valueOf(mynamechars);
    System.out.println(text);
}

You increment i in the inner loop along with x. You should be incrementing it outside of that loop:
for (int i = 0; i < lngth; i++) {
    for (int x = 0; x < 26; x++) {
        y = x + 1;

        if (mynamechars[i] == alphabet[x]) {
            mynamechars[i] = alphabet[y];
        }
    }

    String text = String.valueOf(mynamechars);
    System.out.println(text);
}

Then there's the problem with y.
x ranges from 0 to 25, so y will range from 1 to 26. alphabet doesn't have an element with an index of 26 (that's the 27th letter), which causes your error.
You either have to check for that case manually:
if (mynamechars[i] == alphabet[x]) {
    if (y == 26) {
        y = 0;
    }

    mynamechars[i] = alphabet[y];
}

Or get rid of y completely and use the modulo operator to wrap around to the beginning:
if (mynamechars[i] == alphabet[x]) {
    mynamechars[i] = alphabet[(x + 1) % alphabet.length];
}

A: Add a System.out.println above y = x + 1; and you should get the meaning of the exception :)


text:
Q: Creating a new Awkward array from indices The problem I am facing is to create a new array from a set of indices. Namely, I have a set of particles and jets, for each jet there is a list of indices of which particles belong to the given jet.
    import awkward as ak
    import vector

    particles = ak.Array({
        "mass": ak.Array([1, 2, 3, 4, 5]),
        "px": ak.Array([1, 2, 3, 4, 5]),
        "py": ak.Array([1, 2, 3, 4, 5]),
        "pz": ak.Array([1, 2, 3, 4, 5]),
    })

    particles_p4 = vector.awk(ak.zip({
        "mass": particles["mass"],
        "x": particles["px"],
        "y": particles["py"],
        "z": particles["pz"]
    }))

    jet = ak.Array({
        "constituents": ak.Array([[1, 2, 4, 5], [3]]),
        "energy": ak.Array([1.2, 3.4])
    })

What I would like to get is for each jet the particle_p4 values in a new array like so:
<Array [[{x: 1, y: 1, z: 1, ... z: 4, tau: 4}]] type='2 * var * {"x": int64, "y"...'>

where the first element of that would be:
<Array [{x: 1, y: 1, z: 1, ... z: 5, tau: 5}] type='4 * {"x": int64, "y": int64,...'>

Doing this with a for loop is trivial, however I have the notion that this can be done in a more efficient way with the tools available in Awkward array.
Bonus: What about even more nested arrays, for example where each event has multiple jets?

A: First, I think you mean you have
jet = ak.Array({
    "constituents": ak.Array([[0, 1, 3, 4], [2]]),
    "energy": ak.Array([1.2, 3.4])
})

because I'd expect the "constituents" indexes to be 0-based, not 1-based. But even if it is 1-based, just start by subtracting 1.
>>> jet.constituents - 1
<Array [[0, 1, 3, 4], [2]] type='2 * var * int64'>

The biggest problem here is that these indexes are nested one level deeper than the particles_p4 that you want to slice. You want the 0, 1, 3, 4, and also the 2, in your jet.constituents to be indexes in the not-nested list, particles_p4.
If we just arbitrarily flatten them (axis=-1 means to squash the last/deepest dimension):
>>> ak.flatten(jet.constituents, axis=-1)
<Array [0, 1, 3, 4, 2] type='5 * int64'>

these indexes are exactly what you'd need to apply to particles_p4. Here, I'm using the current (2.x) version of Awkward Array, so that I can use .show(), but the integer-array slice works in any version of Awkward Array.
>>> particles_p4[ak.flatten(jet.constituents, axis=-1)].show(type=True)
type: 5 * Momentum4D[
    x: int64,
    y: int64,
    z: int64,
    tau: int64
]
[{x: 1, y: 1, z: 1, tau: 1},
 {x: 2, y: 2, z: 2, tau: 2},
 {x: 4, y: 4, z: 4, tau: 4},
 {x: 5, y: 5, z: 5, tau: 5},
 {x: 3, y: 3, z: 3, tau: 3}]

If we take that as a partial solution, all we need to do now is put the nested structure back into the result.
ak.flatten has an opposite, ak.unflatten, which takes a flat array and adds nestedness from an array of list lengths. You can get the list lengths from the original jet.constituents with ak.num. Again, I'll use axis=-1 so that this answer will generalize to deeper nestings.
>>> lengths = ak.num(jet.constituents, axis=-1)
>>> lengths
<Array [4, 1] type='2 * int64'>

>>> rearranged = particles_p4[ak.flatten(jet.constituents, axis=-1)]
>>> rearranged
<MomentumArray4D [{x: 1, y: 1, z: 1, tau: 1}, ..., {...}] type='5 * Momentu...'>

>>> result = ak.unflatten(rearranged, lengths, axis=-1)
>>> result.show(type=True)
type: 2 * var * Momentum4D[
    x: int64,
    y: int64,
    z: int64,
    tau: int64
]
[[{x: 1, y: 1, z: 1, tau: 1}, {x: 2, ...}, ..., {x: 5, y: 5, z: 5, tau: 5}],
 [{x: 3, y: 3, z: 3, tau: 3}]]

For the bonus round, if all of the above arrays (particles_p4 and jet) were arrays of lists, where each list represents one event, rather than an array representing one event, then the above would hold. I'm taking it as a given that the length of the particles_p4_by_event is equal to the length of the jet_by_event arrays, and the values of jet_by_event.constituents are indexes within each event in particles_p4_by_event (not global indexes; each event should restart at zero). That is, all of your arrays agree on how many events there are, and each event is handled individually, with no cross-over between events.


text:
Q: Windows 10 Universal App SQLite I'm currently trying to port a working Windows 8 JavaScript app to a Windows 10 UAP app. In my Windows 8 app, I heavily used this SQLite wrapper and library: https://github.com/doo/SQLite3-WinRT. However, after adding SQLite3-WinRT to my Windows 10 UAP app as per the setup instructions in the readme of the repo, I get a "WinJS is not defined" error coming from the SQLite3.js source file that I added to my /js directory in the app (the way it works fine in the windows 8 app). Am I doing something wrong here, or wild this SQLite3-WinRT not work with Win 10 UAP and is there some better way of using SQLite in a JavaScript Windows 10 UAP app? Thanks a lot!

A: I tried using https://github.com/doo/SQLite3-WinRT on Windows 10 and found VS2015 Community Edition couldn't even load the project. Every time I tried to load it, VS would hang with "unloading project" showing in the status bar. Killing it via task manager was the only way out.
I found this sample app which implements SQLite in a Universal App. This compiles and runs fine for me on Windows 10, although I did have to update the references to SQLite 3.8.4.3 with the version I had, SQLite 3.8.11.1

*

*Download and unzip Universal JavaScript SQLite Sample

*Open in Visual Studio

*Click on the "Shared App" project group

*Expand "SQLite.Windows" > "References"

*Remove the reference to "SQLite.WinRT81, Version=3.8.4.3

*Right-click > "Add Reference"

*From Windows 8.1 > Extensions, select "SQLite for Windows Runtime (Windows 8.1)

*Expand "SQLite.WindowsPhone" > "References"

*Remove the reference to "SQLite.WP81, Version=3.8.5

*Right-click > "Add Reference"

*From Windows 8.1 > Extensions, select "SQLite for Windows Runtime (Windows 8.1)

*Compile

A: If you are looking for a step by step procedure, you can take a look at this post.
You can use it with:

*

*Windows 10: SQLite for Universal App Platform

*Windows Phone 8.1: SQLite for Windows Phone 8.1

*Windows 8.1: SQLite for Windows Runtime (Windows 8.1)

After setting up the packages and extensions, you are able to create the database and the models classes using:
using System.IO;
using System.Threading.Tasks;
using SQLiteModernApp.DataModel;
using SQLite.Net.Async;
using System;
using SQLite.Net;
using SQLite.Net.Platform.WinRT;

namespace SQLiteModernApp.DataAccess
{
    public class DbConnection : IDbConnection
    {
        string dbPath;
        SQLiteAsyncConnection conn;

        public DbConnection()
        {
            dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Sample.sqlite");

            var connectionFactory = new Func<SQLiteConnectionWithLock>(() => new SQLiteConnectionWithLock(new SQLitePlatformWinRT(), new SQLiteConnectionString(dbPath, storeDateTimeAsTicks: false)));
            conn = new SQLiteAsyncConnection(connectionFactory);
        }

        public async Task InitializeDatabase()
        {
            await conn.CreateTableAsync<Department>();
            await conn.CreateTableAsync<Employee>();
            await conn.CreateTableAsync<EmployeeDepartment>();
        }

        public SQLiteAsyncConnection GetAsyncConnection()
        {
            return conn;
        }
    }
}

Now you can create a CRUD, following the example:
using System.Collections.Generic;
using System.Threading.Tasks;
using SQLite.Net.Async;
using SQLiteModernApp.DataAccess;
using SQLiteModernApp.DataModel;
using SQLiteNetExtensionsAsync.Extensions;

namespace SQLiteModernApp.Repository
{
    public class EmployeeRepository : IEmployeeRepository
    {
        SQLiteAsyncConnection conn;

        public EmployeeRepository(IDbConnection oIDbConnection)
        {
            conn = oIDbConnection.GetAsyncConnection();
        }

        public async Task InsertEmployeeAsync(Employee employee)
        {
            await conn.InsertOrReplaceWithChildrenAsync(employee);
        }

        public async Task UpdateEmployeeAsync(Employee employee)
        {
            await conn.UpdateWithChildrenAsync(employee);
        }

        public async Task DeleteEmployeeAsync(Employee employee)
        {
            await conn.DeleteAsync(employee);
        }

        public async Task<List<Employee>> SelectAllEmployeesAsync()
        {
            return await conn.GetAllWithChildrenAsync<Employee>();
        }

        public async Task<List<Employee>> SelectEmployeesAsync(string query)
        {
            return await conn.QueryAsync<Employee>(query);
        }
    }
}


text:
Q: How to get element from HTML (Angular) I have a little problem, I want to create a form using Angular :
here is my HTML :
<form [formGroup]="requeteForm" (ngSubmit)="ajouter()" *ngIf=" tables!= null">

            {{col}}
            <input type="text" class="form-control" id="{{col}}" formControlName="{{col}}">

</form>

As you can see the formControlName take a variable, the problem is how can I get the variable to init the formGroup ?
For exemple :
this.requeteForm = this.formBuilder.group(
            {
              {{col}}: ['', Validators.required], //It's just an exemple about what I want to do

            }
        );

UPDATE
I want to bring in some more information :
I fact what I want to do is to create a form to add parameters in my dataBase the thing is I get all the columns's name in an Array so I have colonne[nom, number] that are the name of my colums.
The problem is that they don't have a "title" like {id : 1, name : 'Tom'} so I the formBuilder I can't use nom and number since it will change is the table change... I have tried using a for in this.colonne but the syntaxe is wrong for the formBuilder TT Another problem is how to get the information of the input since I won't be able to call them using particular name...
Hope you can help me ^^ Thank you

A: You have to use FormArray which contains FormControl.
Try like this :
requestForm: FormGroup;

colonne = [
  { id: 1, name: "Name 1" },
  { id: 2, name: "Name 2" },
  { id: 3, name: "Name 3" },
  { id: 4, name: "Name 4" },
];

get cols() {
  return this.requestForm.get("cols") as FormArray;
}

constructor(private formBuilder: FormBuilder) {
  this.requestForm = this.formBuilder.group({
    cols: new FormArray(this.colonne.map(col => new FormGroup({
      item: new FormControl(col.name)
    })))
  });
}

ajouter() {

}

Then in your HTML
<form [formGroup]="requestForm" (ngSubmit)="ajouter()">

  <ng-container formArrayName="cols">

      <ng-container [formGroupName]="i">
        <input formControlName="item" />
      </ng-container>

  </ng-container>
</form>

This code is not tested so maybe you will have to adjust. You have a whole example here : https://netbasal.com/angular-reactive-forms-the-ultimate-guide-to-formarray-3adbe6b0b61a
UPDATE
I've made a working StackBlitz (without ajouter() function) here : https://stackblitz.com/edit/angular-ivy-wympwa?file=src/app/app.component.ts

A: You can use a FormArray or a FormGroup. You choice one or another according the data you need.
//If you create a FormGroup is because you need a data like
{
   name1:"Peter"
   surname:"Smith"
}
//If you create a FormArray of FormControls is because you need a data like
[
   "Peter","John"
]
//If you create a FormArray of FormGroup is because you need a data like
[
   {name:"Peter",surname:"Smith"},
   {name:"John",surname:"Jhon"}
]

If we want create a FormGroup according an array of columns you need create a FormGroup empty and use addControl, e.g.
const columns=["name","surname"]
const form=new FormGroup({})  //create an empty formGroup
columns.forEach(x=>{
   form.addControl(x,new FormControl()) //add a FormControl to the formGroup
})

Note:recently @Raru ask about a dynamic form builder in this SO


text:
Q: Linear regression analysis with categorical feature Regression algorithms working fine on represented as numbers. It's quite clear how to do regression on data which contains numbers and predict output. However I need to do regression analysis on data that contains categorical feature. I have a csv file which contains two columns install-id and page-name both are object type. I need to give install-id as input and page-name should be predicted as output. Below is my code. Please help me in this.
import pandas as pd
data = pd.read_csv("/Users/kashifjilani/Downloads/csv/newjsoncontent.csv")
X = data["install-id"]
Y = data["endPoint"]
X = pd.get_dummies(data=X, drop_first=True)
from sklearn import linear_model
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = .20, random_state = 40)
regr = linear_model.LinearRegression()
regr.fit(X_train, Y_train)
predicted = regr.predict(X_test)

A: For the demonstration, let's say, you have this dataframe where IQ and Gender are input features. Target variable is Test Score.
|   Student |   IQ | Gender   |   Test Score |
|----------:|-----:|:---------|-------------:|
|         1 |  125 | Male     |           93 |
|         2 |  120 | Female   |           86 |
|         3 |  115 | Male     |           96 |
|         4 |  110 | Female   |           81 |
|         5 |  105 | Male     |           92 |
|         6 |  100 | Female   |           75 |
|         7 |   95 | Male     |           84 |
|         8 |   90 | Female   |           77 |
|         9 |   85 | Male     |           73 |
|        10 |   80 | Female   |           74 |

Here, IQ is numerical and Gender is a categorical feature. In the preprocessing step, we'll apply simple imputer on the numerical and one-hot-encoder on the categorical feature. You can use sklearn's Pipeline & ColumnTransformer feature for that. Then you can use your model of choice to train and predict easily.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn import linear_model

# defining the data
d = {
    "Student": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    "IQ": [125, 120, 115, 110, 105, 100, 95, 90, 85, 80,],
    "Gender": [
        "Male",
        "Female",
        "Male",
        "Female",
        "Male",
        "Female",
        "Male",
        "Female",
        "Male",
        "Female",
    ],
    "Test Score": [93, 86, 96, 81, 92, 75, 84, 77, 73, 74],
}

# converting into pandas dataframe
df = pd.DataFrame(d)

# setting the student id as index to keep track
df = df.set_index("Student")

# column transformation
categorical_columns = ["Gender"]
numerical_columns = ["IQ"]

# determine X
X = df[categorical_columns + numerical_columns]
y = df["Test Score"]

# train test split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, random_state=42, test_size=0.3
)

# categorical pipeline
categorical_pipe = Pipeline([("onehot", OneHotEncoder(handle_unknown="ignore"))])

# numerical pipeline
numerical_pipe = Pipeline([("imputer", SimpleImputer(strategy="mean")),])

# aggregating both the pipeline
preprocessing = ColumnTransformer(
    [
        ("cat", categorical_pipe, categorical_columns),
        ("num", numerical_pipe, numerical_columns),
    ]
)

rf = Pipeline(
    [("preprocess", preprocessing), ("classifier", linear_model.LinearRegression())]
)

# train
rf.fit(X_train, y_train)

# predict
predict = rf.predict(X_test)

This shows,
>> array([84.48275862, 84.55172414, 79.13793103])

A: I think here we have to remember the assumptions of Regression model. since we are trying to predict/identify trend between Independent Variable(X) and dependent variable(y).
- linearity separable
- Independent variable have restricted multicollinearity.
- Homoscedasticity
As given in your example you have only one independent variable, and to summarize trend between X and y both should be linear.
suppose for an example you have given a task to predict Total-Travel time of the trip. and your data-set has following variables
IV - Miles Traveled, NoOfDeliveries, GasPrice and City
DV - Traveltime
Here you can see it is a mixture of Numerical(Miles Traveled, GasPrice) + categorical variables(NoOfDeliveries, City). now you have to encode these categorical variables to numbers (in order to work with regression analysis) and predict the output.
To encode the categorical variables to Binary format we are using 2 objects from sklearn library here
- LabelEncoder and OneHotEncoder.
Please follow the below links to know more about how to deal with
Categorical variables
Please find the below link to know more about Dummy variable Trap
Please find the below link to know more about building simple Linear regression model


text:
Q: Am I @localhost or @computer-5? Why is bash shell sometimes saying I'm at @localhost while other times it says I'm at @computer-5?

A: Some DHCP servers (and clients) are configured to assign a hostname just like an IP address.  In these cases the computer's hostname does in fact change to e. g. computer-5 (until it gets a lease assigning a different name, or the lease is relinquished).  localhost will still work for the loopback interface, but the DHCP-assigned hostname will (or should) resolve to the DHCP-assigned address specifically.


text:
Q: is it possible to execute trigger from php code I taking url from user and getting text of that url using
$data=file_get_content($url)

I am extracting title, image url from this $data. And storing into table urlrecord and show it in div D1 on front end.
after that I perform processing on $data which takes little time which gives me result $x and $y. (x and y i am not going to show in D1)
x and y also I have to store in urlrecord table.
If I perform processing on $data to get x and y before then showing url content in front end ie D1 will be delayed.
So what I want is:
After storing URL content into table, I perform $data processing. And storing the $x and $y into same table.
bottomline is I dont want to reflect $data processing to get x,y to affect in show url content on front end.
Can some one think optimal scenario here?

A: I think you can create a cronjob to do the $data processing.
For example, there's a flag column in table urlrecord, default to 1, and the cronjob will scan the table every 5 mins, "select * from urlrecord where flag=1", calculate x and y, and update the flag to 2.


text:
Q: Why are my manual PCA reconstructions not matching python's sklearn's reconstructions? I was trying to check my implementation of PCA to see if I understood it and I tried to do PCA with 12 components on the MNIST data set (which I got using the tensorflow interface that normalized it for me). I obtained the principal components given by sklearn and then made reconstructions as follow:
pca = PCA(n_components=k)
pca = pca.fit(X_train)
X_pca = pca.transform(X_train)
# do manual PCA
U = pca.components_
my_reconstruct = np.dot(  U.T , np.dot(U, X_train.T) ).T

then I used the reconstruction interface given by sklearn to try to reconstruct as follow:
pca = PCA(n_components=k)
pca = pca.fit(X_train)
X_pca = pca.transform(X_train)
X_reconstruct = pca.inverse_transform(X_pca)

and then checked the error as follow (since the rows are a data point and columns features):
print 'X_recon - X_my_reconstruct', (1.0/X_my_reconstruct.shape[0])*LA.norm(X_my_reconstruct - X_reconstruct)**2
#X_recon - X_my_reconstruct 1.47252586279

the error as you can see is non-zero and actually quite noticeable. Why is it? How is their reconstruction different from mine?

A: I see a couple of issues:

*

*The dot product should be X_pca.dot(pca.components_). PCA factorizes your X_train matrix using SVD:
Xtrain = U·S·Vᵀ.
Here, pca.components_ corresponds to Vᵀ (a (k, n_features) matrix), not U (an (n_datapoints, k) matrix).
The sklearn implementation of PCA is quite readable, and can be found here. I also wrote a  pure numpy example in this previous answer.

*Did you center X_train by subtracting the mean value for each column before doing the fitting?
The PCA class automatically centers your data and stores the original mean vector in its .mean_ attribute. If the mean vector for your input features was nonzero then you would need to add the mean to your reconstructions, i.e. my_reconstruct += pca.mean_.


text:
Q: C# How to modularly fill a list with floating point values via user input, calculate sum and average Mind you, I come from a C++ background and the instructor I have should be called an assignment proctor AT MOST. No instruction or guidance whatsoever. Now, is it possible that some kind person could assist me and help me figure out what I'm doing wrong and then explain(In durr durr language)how to fix it so that it compiles??? Here is the code and the errors. Got it down from 22 but these last 9 are killing me and it's now 3 a.m.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace P1_Wilson
{
 class P1_Wilson
  {

    float sum;
    float aver;
    int counter;
    static float FillNumber()//Declaration of method utilized to fill an array/list of                              floating point numbers.
     {
       int counter = 0;
       List<float> floatlist = new List<float>();
       char sentinel;
       Console.WriteLine("I would like you to now input a few floating point numbers.\n                           Enter q to quit.");
       Console.WriteLine("You have the option to quit now.\nWould you like to continue? \nEnter q to quit.");
       sentinel = char.Parse(Console.ReadLine());
        while (sentinel != 'q')
         {
          Console.WriteLine("You have the option to quit now.\nWould you like to  continue?\nEnter q to quit.");
          sentinel = char.Parse(Console.ReadLine());
          Console.WriteLine("Then please input a floating point number.");
          floatlist[counter] = float.Parse(Console.ReadLine(floatlist[counter]));
          counter++;
          return floatlist;
          return counter;
         }

     }
    static float CalcSum(List<float> floatlist, int counter)//Declaration of method  used to add all entered numbers together and calculate the total sum.
     {
      for (; counter >= 0; counter--)
       {
        float sum = sum + floatlist[counter];
       }
       return sum;
     }
    static float CalcAver(float sum, float aver, int counter)//Declaration of method used to calculate the average of numbers entered.
     {
      aver = sum / counter;
      return aver;
     }

    static void Main()//Where execution of program begins. Introduces user to program. Prompts for user input and calls all subservient methods.
     {
      FillNumber();
      CalcSum();
      CalcAver();
      Console.WriteLine("The total number of floating point numbers entered is:" +  counter);
      Console.WriteLine("The total sum is:" + sum);
      Console.WriteLine("The average of the numbers entered is:" + aver);
      Console.ReadLine();
     }
  }
}

These are my errors: 9
Error 1 No overload for method 'ReadLine' takes 1 arguments
Error 5 No overload for method 'CalcSum' takes 0 arguments
Error 6 No overload for method 'CalcAver' takes 0 arguments
Error 2 Cannot implicitly convert type 'System.Collections.Generic.List' to 'float'
Error 3 An object reference is required for the non-static field, method, or property 'P1_Wilson.P1_Wilson.sum'
Error 8 An object reference is required for the non-static field, method, or property 'P1_Wilson.P1_Wilson.sum'
Error 7 An object reference is required for the non-static field, method, or property 'P1_Wilson.P1_Wilson.counter'
Error 9 An object reference is required for the non-static field, method, or property 'P1_Wilson.P1_Wilson.aver'
Error 4 'sum' conflicts with the declaration 'P1_Wilson.P1_Wilson.sum'
I apologize if my one lame attempt at humor served more to anger instead of to kindly engender chuckles.

A: Read your error messages one by one and fix them, for example :

*

*Error 1 No overload for method 'ReadLine' takes 1 arguments
This error message is not ambiguous, specifically when Visual Studio should point you to the exact point in code where it occurs.
In that case it is :
Console.ReadLine(floatlist[counter]);

Please try to fix your errors one by one by carefully reading the error messages (and googling them if needs be) and come back if you struggle with a specific error or if you would like a code review when the code is running.


text:
Q: Getter on the instance of a javascript function itself to enable docstrings. Is it possible? The utopic goal:
str = "hello"
str.doc = "this is a string"
console.log(str) //prints 'hello'
console.log(str.doc) //should prints the docstring

However, strings are immutable and this above is not possible.
How I tried to workaround:
str = new String("hello")
str.doc = "this is a string"
console.log(str) //prints the string object but not 'hello'
console.log(""+str) //prints "hello"
console.log(str.doc) //correctly prints the docstring

As you can see, only when .valueOf() or .toString() is called, you get the raw string. The goal is to get the string when it's directly called.
Another tempt of workaround (in coffescript, for shortness: 3 lines vs ~15)
class Configuration
    constructor: (@value, @doc) ->
    @::valueOf = -> @value

This is pretty similar to new String(). It just prototypes the valueOf() method on the object. The problem is the same as above. You cannot directly console.log(str) to prints the raw string and both use console.log(str.doc)
The question:
Is it possible in some way to achieve this, without have to refactor my whole codebase ?

A: You can prototype String. See fiddle
// String.prototype.__defineGetter__("doc", function() { return "test" }); //deprecated

Object.defineProperty(String.prototype, "doc", {
  get: function doc() {
    return "this is a string";
  }
});
console.log("this is a string".doc);

A: I don't condone this, but you could override console.log, so that it calls valueOf on any String arguments:
var oldConsoleLog = console.log;
console.log = function ( ) {
    oldConsoleLog.apply( console, [].map.call( arguments, function ( arg ) { return arg instanceof String ? arg.valueOf() : arg; } ) );
};

A: As stated in the comments, I'll go for a bit of refactoring replacing the variables like str with str + "" and so using new String(), not really clean but seems to be the only quick workaround. In fact, the optimal solution would be to simply use a singleton like the following:
config = {
    mySetting: {
        value: "settingValue",
        docstring: "my doc string"
    }
}

And where necessary use it with: config.mySetting.value
But that would be to do a lot of refactoring of a complex app, not a priority for now. Thank you all for your responses!


text:
Q: Bootstrap Form border gradient By default, clicking on a Bootsrap Form will display a gradient of color on the borders.

Is there a way to modify the bootsrap.css or bootsrap.js to display an other color for the gradient?
Here is a Fiddle with the example on the picture above: https://jsfiddle.net/bb61c412/122/
And the code:

#form-default {
  margin-top: 50px;
  width: 300px;
}
#form-green {
  border: 1px solid #000000;
  margin-top: 50px;
  width: 300px;
}
<link rel="stylesheet" type="text/css" href="https://bootswatch.com/bower_components/bootstrap/dist/css/bootstrap.min.css" />

<div class="form-group">

  <select id=form-default name="Form1" class="form-control">
    <option value="0">Form1</option>
    <option value="1">Option2</option>
    <option value="2">Option3</option>
  </select>

  <select id=form-green name="Form2" class="form-control">
    <option value="0">Form2</option>
    <option value="1">Option2</option>
    <option value="2">Option3</option>
  </select>

</div>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

A: As seen in this answer..
Change Bootstrap input focus blue glow
Override the .form-control:focus blue glow..
.form-control:focus {
      border-color: #FF0000;
      box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(255, 0, 0, 0.6);
}

Updated fiddle: https://jsfiddle.net/bb61c412/123/

A: You simply need to override this bit of CSS by bootstrap:
.form-control:focus {
    border-color: #66AFE9;
    box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.075) inset, 0px 0px 8px rgba(102, 175, 233, 0.6);
}

The blue part of the gradient is rgba(102, 175, 233, 0.6), so change it to whatever you want.

A: .form-control:focus, .form-control:active, .form-control:hover {
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset, 0 0 8px rgba(0, 0, 0, 0.6);
    outline: 0 none;
}

A: This will alter the border color. The box-shadow changes the gradient portion. Adding :focus makes it occur only when you have it selected.
#form-default:focus {
  box-shadow: 0 0 5px green;
  padding: 3px;
  margin: 5px;
  border: 1px solid red;
}

A:  .form-control
  {
   border-color: rgba(126, 239, 104, 0.8) !important;
   box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset, 0 0 8px rgba(126, 239, 104, 0.6) !important;
   outline: 0 none !important;
  }
 .form-control:hover
  {
     border-color: blue !important;
  }

A: change the  .form-control:focus blue glow..
.form-control:focus{
webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(102,175,233,0.6);
box-shadow: inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(102,175,233,0.6);
}
to change above color code


text:
Q: mutt & mutt_oauth.py - mutt_account_getoauthbearer: Command Returned Empty String I am trying to setup the Mutt terminal email client with an Exchange 365 email account. I am using mutt_oauth.py in order to facilitate the OAuth flow.
I have followed the instructions in the README but am running into an issue. When I load mutt, it tries to login but returns the following error:
mutt_account_getoauthbearer: Command returned empty string

Here is the output of mutt -d 5:
[2022-10-19 13:49:59] Mutt/2.2.7 (2022-08-07) debugging at level 5
[2022-10-19 13:49:59] In mutt_reflow_windows
[2022-10-19 13:49:59] In mutt_reflow_windows
[2022-10-19 13:49:59] In mutt_reflow_windows
[2022-10-19 13:49:59] In mutt_reflow_windows
[2022-10-19 13:49:59] Reading configuration file '/opt/homebrew/Cellar/mutt/2.2.7/etc/Muttrc'.
[2022-10-19 13:49:59] parse_attach_list: ldata = 0x1047c9e90, *ldata = 0x0
[2022-10-19 13:49:59] parse_attach_list: added */.* [9]
[2022-10-19 13:49:59] parse_attach_list: ldata = 0x1047c9ea0, *ldata = 0x0
[2022-10-19 13:49:59] parse_attach_list: added text/x-vcard [7]
[2022-10-19 13:49:59] parse_attach_list: added application/pgp.* [2]
[2022-10-19 13:49:59] parse_attach_list: ldata = 0x1047c9ea0, *ldata = 0x600001d588d0
[2022-10-19 13:49:59] parse_attach_list: skipping text/x-vcard
[2022-10-19 13:49:59] parse_attach_list: skipping application/pgp.*
[2022-10-19 13:49:59] parse_attach_list: added application/x-pkcs7-.* [2]
[2022-10-19 13:49:59] parse_attach_list: ldata = 0x1047ca300, *ldata = 0x0
[2022-10-19 13:49:59] parse_attach_list: added text/plain [7]
[2022-10-19 13:49:59] parse_attach_list: ldata = 0x1047c9ea0, *ldata = 0x600001d588d0
[2022-10-19 13:49:59] parse_attach_list: skipping text/x-vcard
[2022-10-19 13:49:59] parse_attach_list: skipping application/pgp.*
[2022-10-19 13:49:59] parse_attach_list: skipping application/x-pkcs7-.*
[2022-10-19 13:49:59] parse_attach_list: added message/external-body [4]
[2022-10-19 13:49:59] parse_attach_list: ldata = 0x1047ca308, *ldata = 0x0
[2022-10-19 13:49:59] parse_attach_list: added message/external-body [4]
[2022-10-19 13:49:59] Reading configuration file '/Users/jlcarveth/.mutt/muttrc'.
[2022-10-19 13:49:59] Using default IMAP port 143
[2022-10-19 13:49:59] Using default IMAPS port 993
[2022-10-19 13:49:59] Setting $hostname
[2022-10-19 13:49:59] getdnsdomainname(): localdomain
[2022-10-19 13:49:59] $hostname set to "JLCM2.localdomain"
[2022-10-19 13:49:59] Reading imap://outlook.office365.com/INBOX...
[2022-10-19 13:49:59] Looking up outlook.office365.com...
[2022-10-19 13:49:59] Connecting to outlook.office365.com...
[2022-10-19 13:49:59] Connected to outlook.office365.com:143 on fd=7
[2022-10-19 13:49:59] imap_cmd_step: grew buffer to 512 bytes
[2022-10-19 13:49:59] 7< * OK The Microsoft Exchange IMAP4 service is ready. [***OMITTED***]
[2022-10-19 13:49:59] IMAP queue drained
[2022-10-19 13:49:59] 7> a0000 CAPABILITY
[2022-10-19 13:49:59] 7< * CAPABILITY IMAP4 IMAP4rev1 LOGINDISABLED STARTTLS SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
[2022-10-19 13:49:59] Handling CAPABILITY
[2022-10-19 13:49:59] 7< a0000 OK CAPABILITY completed.
[2022-10-19 13:49:59] IMAP queue drained
[2022-10-19 13:49:59] 7> a0001 STARTTLS
[2022-10-19 13:49:59] 7< a0001 OK Begin TLS negotiation now.
[2022-10-19 13:49:59] IMAP queue drained
[2022-10-19 13:49:59] ssl_load_certificates: loading trusted certificates
[2022-10-19 13:49:59] mutt_ssl_starttls: Error loading trusted certificates
[2022-10-19 13:49:59] ssl_verify_callback: checking cert chain entry /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert Global Root CA (preverify: 1 skipmode: 0)
[2022-10-19 13:49:59] ssl_verify_callback: checking cert chain entry /C=US/O=DigiCert Inc/CN=DigiCert Cloud Services CA-1 (preverify: 1 skipmode: 0)
[2022-10-19 13:49:59] ssl_verify_callback: checking cert chain entry /C=US/ST=Washington/L=Redmond/O=Microsoft Corporation/CN=outlook.com (preverify: 1 skipmode: 0)
[2022-10-19 13:49:59] ssl_verify_callback: hostname check passed
[2022-10-19 13:49:59] TLSv1.2 connection using TLSv1.2 (ECDHE-RSA-AES256-GCM-SHA384)
[2022-10-19 13:50:00] 7> a0002 CAPABILITY
[2022-10-19 13:50:00] 7< * CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
[2022-10-19 13:50:00] Handling CAPABILITY
[2022-10-19 13:50:00] 7< a0002 OK CAPABILITY completed.
[2022-10-19 13:50:00] IMAP queue drained
[2022-10-19 13:50:00] imap_authenticate: Trying method oauthbearer
[2022-10-19 13:50:00] SASL local ip: 192.168.1.248;55042, remote ip:52.96.88.162;143
[2022-10-19 13:50:00] External SSF: 256
[2022-10-19 13:50:00] mutt_sasl_cb_authname: getting user for outlook.office365.com:143
[2022-10-19 13:50:00] imap_auth_sasl: oauthbearer unavailable
[2022-10-19 13:50:00] imap_authenticate: Trying method xoauth2
[2022-10-19 13:50:00] Authenticating (XOAUTH2)...
[2022-10-19 13:50:00] mutt_account_getoauthbearer: Command returned empty string
[2022-10-19 13:50:02] mutt_index_menu[827]: Got op 99
[2022-10-19 13:50:02] q: unknown command
[2022-10-19 13:50:03] mutt_index_menu[827]: Got op 177
[2022-10-19 13:50:03] Closing connection to outlook.office365.com...
[2022-10-19 13:50:03] 7> a0003 LOGOUT
[2022-10-19 13:50:03] 7< * BYE Microsoft Exchange Server IMAP4 server signing off.
[2022-10-19 13:50:03] Handling BYE
[2022-10-19 13:50:03] 7< a0003 OK LOGOUT completed.
[2022-10-19 13:50:03] IMAP queue drained
[2022-10-19 13:50:03] mutt_buffer_pool_free: 10 of 10 returned to pool

I am unsure how to resolve this error. My tokens seem to be valid when I run python3 mutt_oauth.py my@email.com.tokens --verbose --test, as the tokens are printed and no issues.
My ~/.mutt/muttrc is quite simple:
set imap_user="***OMITTED***"
set folder="imap://outlook.office365.com/"
#set imap_pass='***OMITTED***'
set smtp_url = "smtp://${imap_user}@smtp.office365.com:587/"
set imap_authenticators="oauthbearer:xoauth2"
set imap_oauth_refresh_command="/Users/jlcarveth/mutt_oauth.py \
    --quiet ${imap_user}.tokens"
set smtp_authenticators='${imap_authenticators}'
set smtp_oauth_refresh_command=${imap_oauth_refresh_command}
set spoolfile=+INBOX

# Store message headers locally to speed things up
set header_cache=~/.cache/mutt
set message_cachedir=~/.cache/mutt

# Allow mutt to open an IMAP connection passively
unset imap_passive

set imap_keepalive = 300

mutt v 2.2.7

A: This line here
set imap_oauth_refresh_command="/Users/jlcarveth/mutt_oauth.py \
--quiet ${imap_user}.tokens"

${imap_user}.tokens is not an absoule path. My guess is that is your issue. Try adding the full path to your tokens file there.


text:
Q: Django custom User not registering with Admin I've followed the documentation at https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#substituting-a-custom-user-model, but for some reason things still aren't working for me. I can create and login to User accounts, but for some reason I can't view them with the admin. This leads me to believe they're not being registered correctly, but as said before, I've followed the documentation on how to do that:
sign_up/models.py
from django.contrib.auth.models import AbstractUser

# Create your models here.
class User(AbstractUser):
    pass

sign_up/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from .models import User

# Register your models here.
admin.register(User, UserAdmin)

site/settings.py
# define custom user model
AUTH_USER_MODEL = 'sign_up.User'

I've also tried deleting my database and migrations and reapplying them, but this still isn't helping.

A: not this
admin.register(User, UserAdmin)

but this
admin.site.register(User, UserAdmin)


text:
Q: Setup.py inside installed module For a directory structure like the following, I haven't been able to make xy an importable package.
xy
├── __init__.py
├── z
│   ├── __init__.py
│   └── stuff.py
└── setup.py

If the setup.py were a directory up, I could use
from setuptools import setup
setup(name='xy',
      packages=['xy'])

but short of that, no combination of package_dir and packages has let me import xy, only import z. Unfortunately, moving the setup.py a directory up isn't really an option due to an excessive number of hard-coded paths.

A: See the following answer for ideas how to use package_dir and packages to help with such projects: https://stackoverflow.com/a/58429242/11138259
In short for this case here:
#!/usr/bin/env python3
import setuptools
setuptools.setup(
    # ...
    packages=['xy', 'xy.z'],
    #packages=setuptools.find_packages('..')   # only if parent directory is otherwise empty
    package_dir={
        'xy': '.',
    },
)


text:
Q: Is there a term for the "maximum layer size" of an XML document? XML document depth is the length of the maximum path from the root element to a leaf.
Is there a word to describe the "breadth" of the document, by which I mean the maximum number of children of a single node?
So, in the document:
<A>
 <B>
  <C></C>
  <C></C>
 </B>
 <B>
  <C></C>
  <C></C>
  <C></C>
  <C></C>
  <C></C>
 </B>
</A>

that number would be 5 (because there are five children to the second B element and that's the largest number in the document.

A: I've heard the term "fan-out"; one can talk of the average fan-out or the maximum fan-out. But I wouldn't use the term without explaining what you mean by it.

A: Breadth could work. I would also consider 'Branching Factor' to follow tree nomenclature.

A: It's called  Depth.
I don't know if it is an official term, but that is what most people call it.


text:
Q: From Excel to Outlook: how to do the link especially with files such as PDF First a few words of context:
In my company we always have to attach 3 PDF files when it comes to sending an e-mail (by Outlook) to a client regarding a product. Sometimes when we speak about several products, we have to send even more PDF files. Hopefully some files are redundant because they are "family" of products but still it's really a mess.
Then I got the idea of creating an excel sheet with the list of all the products and all the associated PDFs to send. The idea is to tick the box of which files we want to send then click on the big email icon and all the chosen documents will be already attached to an e-mail in Outlook. After that all you have to do is to write the name of the client and you're done: send it!.
Having an idea is great but implementing it is better. That's where my Excel and VBA skills are lacking.
Here are the questions:
1.how to assign a pdf files to a "box"
2.how to create the link from Excel to an email in Outlook by simply clicking on the mail icon so that all chosen documents are attached in the email?
Here are the pictures that will help you understand the issue.

A: Your approach is almost right, but off a bit.  Please see the link below.  You should find your answer there.
http://www.rondebruin.nl/win/s1/outlook/amail6.htm


text:
Q: Newlines entered in Firefox not dislplaying in SQR Report Let's say I have a text field here named "Description". In the Description field, I entered the following text:
This is line 1.
This is line 2.
This is line 3.
When I input these text to the Description field using IE or Chrome and run the SQR process, the description is displayed correctly including the newlines. But when I enter the same description using Firefox (v35.0.1 btw), the description is being printed in the report like this:
This is line 1. This is line 2. This is line 3.
I am sure that in my SQR there are no procedures that strip off the newlines (because it is working with IE and Chrome). I have also validated backend that the description has newlines.
Using the data entered in Firefox, I also tried running the report in IE and Chrome, but the newlines are still not displaying.
Can you tell me why is this happening? Is there a difference between the newlines used by IE, Chrome, and Firefox?

A: This is a known issue, google firefox textarea newline.
Firefox represents an newline as linefeed character ascii(10) whereas internet explorer as a combination of carriage return character and linefeed character ascii(13) ascii(10).
To ensure the data is saved in the way it's required for your further processes, you could add component record peoplecode, SavePreChange:
/* Newline is Char13)+Char(10) */
YOUR_REC.YOUR_FLD.Value = Substitute(
                            Substitute(YOUR_REC.YOUR_FLD.Value,
                                       Char(13) | Char(10),
                                       Char(10)),
                            Char(10),
                            Char(13) | Char(10));