text:
Q: Select box shows no value when binding form component Selectbox only shows default value but not other value from component.I am trying to show the accType value in selectbox.Am i doing something wrong? I am new to angular. Please help.
Component:
import { Component, OnInit } from '@angular/core';
import { AccType } from '../models/accType';

@Component({
  selector: 'app-account-form',
  templateUrl: './account-form.component.html',
  styleUrls: ['./account-form.component.css']
})
export class AccountFormComponent implements OnInit {

    accTypes = [
        { id: "S", name: "Supplier" },
        { id: "C", name: "Customer" }
    ];

    ngOnInit() {

        console.log("AccType",this.accTypes);
  }

}

Html:

Create new Account

<form #f="ngForm" (ngSubmit)="submit()">

        Account Name

            <input type="text" class="form-control" name="accountName" required>

Please provide account name

        Account Type

            <select class="form-control" [(ngModel)]="accType.id">
                <option value="">Select Accout Type</option>
                <option *ngFor="let accType of accTypes" [ngValue]="accType"> {{accType.name}} </option>
            </select>

</form>

A: <select [(ngModel)]="selected" name="status" placeholder="select" (ngModelChange)="onOptionsSelected()">
        <option *ngFor="let sta of accTypes" [ngValue]="sta.id">{{sta.name}}</option>
    </select>

  {{filtered|json}}

/*************** ts file ***************/
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
 selected:any = 'S';
filtered :any;
    accTypes = [
        { id: "S", name: "Supplier" },
        { id: "C", name: "Customer" }
    ];

constructor() {

        }

onOptionsSelected() {
 console.log(this.selected);
    }
}


text:
Q: Moving animation from Java to XML is inconsistent I have an animation that I wrote using Java and would like to move it to an xml resource. However, the end result of the image is slightly larger and does not return to it's normal size when using a resource animation.
I've tried using percentages for scale but that results in a much larger size... I'm banging my head here.
Java animation
public void animateClickView(final ImageView view) {
    ScaleAnimation scaleAnimation = new ScaleAnimation(0.0f, 1.2f, 0.0f, 1.2f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

    AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);

    AnimationSet animation = new AnimationSet(true);
    animation.addAnimation(alphaAnimation);
    animation.addAnimation(scaleAnimation);
    animation.setDuration(300);
    animation.setFillAfter(true);

    animation.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            ScaleAnimation scaleAnimation = new ScaleAnimation(1.3f, 1.0f, 1.3f, 1.0f,
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

            scaleAnimation.setDuration(250);
            view.startAnimation(scaleAnimation);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });

    view.startAnimation(animation);
}

Resource animation
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator"
    android:fillAfter="true"
    android:shareInterpolator="true"
    android:duration="300">

    <scale
        android:fromXScale="0.0"
        android:toXScale="1.2"
        android:fromYScale="0.0"
        android:toYScale="1.2"
        android:pivotX="50%"
        android:pivotY="50%" />

    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />

    <scale
        android:startOffset="301"
        android:fromXScale="1.2"
        android:toXScale="1.0"
        android:fromYScale="1.2"
        android:toYScale="1.0"
        android:pivotX="50%"
        android:pivotY="50%" />

</set>

A: As I see it, your two Java animations cannot be translated into a single XML animation because they are different in their settings (for example one calls setFillAfter(true) and one doesn't). Rather you will have to have as many XML animations as you have Java animations and you will have to connect these animations in the same fashion as you connect the Java animations - through a listener.
So you have two XML animations, called anim1 and anim2. Here is anim1:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fillAfter="true"
    android:interpolator="@android:anim/linear_interpolator"
    android:shareInterpolator="true">

    <scale
        android:fromXScale="0.0"
        android:fromYScale="0.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.2"
        android:toYScale="1.2" />

    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />
</set>

And here is anim2:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="250"
    android:interpolator="@android:anim/linear_interpolator">

    <scale
        android:fromXScale="1.3"
        android:fromYScale="1.3"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.0"
        android:toYScale="1.0" />
</set>

And you will connect them in Java like this:
Animation animation1;
animation1 = AnimationUtils.loadAnimation(getApplicationContext(),
                R.anim.anim1);
animation1.setAnimationListener(new Animation.AnimationListener() {
    @Override
    public void onAnimationStart(Animation animation) {}

    @Override
    public void onAnimationEnd(Animation animation) {
        Animation animation2;
        animation2 = AnimationUtils.loadAnimation(getApplicationContext(),
                        R.anim.anim2);
        view.startAnimation(animation2);
    }

    @Override
    public void onAnimationRepeat(Animation animation) {}
});
view.startAnimation(animation1);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How would you check multiple RichTextboxes containing multiple lines for unique and or duplicate lines How would you check multiple RichTextboxes containing multiple lines for unique and or duplicate lines.  I've figured out how to loop through the richTextboxes and get the data, but I'm struggling on the logic to see if it's unique.  My apologies if code is as clear as mud.
List<string> DistinctItems = new List<string>();
List<string> DupilcatedItems = new List<string>();
List<string> FirstItemsList = new List<string>();
List<string> CompareItemsList = new List<string>();
int ElementIndex = 0;

foreach (RichTextBox c in tableLayoutPanel1.Controls)
{
    if (c.Text != null)
    {
        FirstItemsList.Add(c.Text.Replace("\n", Environment.NewLine).ToString());

        if (CompareItemsList.Count == 0)
        {
            //Have to add the first batch
            foreach (string str in FirstItemsList)
            {
                txtMixerTextBox.AppendText(str);
                txtDistinctItems.AppendText(str);
                DistinctItems.Add(str);
                ElementIndex++;
            }

            CompareItemsList.Add(c.Text.Replace("\n", Environment.NewLine).ToString());

            if (CompareItemsList.Count() > 0)
            {
                //OK we've gone through the first set
                foreach (string s in CompareItemsList)
                {
                    if (DistinctItems.Contains(s))
                    {
                        //It's a duplicate see if it's in the duplicate list
                        if (DupilcatedItems.Contains(s))
                        {
                            //OK it's in the list we don't have to add it
                            //See if it's in the textbox
                            if (!txtDuplicateItems.Text.Contains(s))
                            {
                                //OK it's not in the textbox let's add it
                                txtDuplicateItems.AppendText(s);
                            }
                        }
                    }
                    else
                    {
                        //It's not there so add it
                        DupilcatedItems.Add(s);
                        //now see if it's in the Distinct Textbox
                        if (!txtDistinctItems.Text.Contains(s))
                        {
                            //add it
                            txtDistinctItems.AppendText(s);
                        }
                        txtMixerTextBox.AppendText(s);
                    }
                }
            }
        }
    }
}

A: Use String.Split.
For example:
foreach (RichTextBox c in tableLayoutPanel1.Controls)
{
    if (!c.Text.IsNullOrWhiteSpace)
    {
        string[] lines = c.Text.Split('\n');
        string[] uniqueLines = GetUniqueLines(lines);//Some line-uniqueness checking algorithm
        c.Text = String.Join('\n',uniqueLines)
    }
}

A: This is what I did to get the results I was after.  Looping through the RichTextboxes as noted above, I wrote the list to a file, stripped out the blank lines (where they came from I haven't the foggiest), read the file into a new list and then got the distinct list from there.  I think the blank lines may have been messing me up, or it might have been the fact that I was looping through the strings in the list (again) thus giving myself duplicates.  I'll likely get hammered for it, but it worked for me.
        List<string> SortingList = new List<string>();

    using (StreamReader r = new   StreamReader("DistinctItemsNoBlankLines.txt"))
                        {
                        string line;
                        while ((line = r.ReadLine()) != null)
                            {
                                SortingList.Add(line);
                            }

                        }

   List<string>DistinctSortingList = SortingList.Distinct().ToList();

        foreach (string str in DistinctSortingList)
        {

        int index = 0;
            while ( index < DistinctSortingList.Count() -1)
            {
            if (DistinctSortingList[index] == DistinctSortingList[index + 1])
                DistinctSortingList.RemoveAt(index);
            else
                index++;
            }
        }
         txtDistinctItems.Lines = DistinctSortingList.ToArray();


text:
Q: Adjacency List Model vs Nested Set Model for MySQL hierarchical data? There are two ways to work with hierarchy data in MySQL:

*

*Adjacency List Model

*Nested Set Model

A major problem of the Adjacency List Model is that we need to run one query for each node to get the path of the hierarchy.
In the Nested Set Model this problem does not exist, but for each added node is necessary to give a MySQL UPDATE on all others left and right value.
My hierarchical data is not static data, such as product categories of e-commerce. Are constant registration of users in hierarchical sequence.
In my application, while there are many constants users registration, I also need to get the hierarchical path until reach the first node in the hierarchy.
Analyzing my situation, which of the two alternatives would be best for my application?

A: The Nested Set Model is nowdays not commonly used in databases, since it is more complex than the Adiacency List Model, given the fact that it requires managing two "pointers" instead of a single one. Actually, the Nested Set Model has been introduced in databases when it was complex or impossible to do recursive queries that traversed a hierarchy.
From 1999, standard SQL include the so called Recursive Common Table Expressions, or Recursive CTE, which makes more simple (and standardized!) to make queries that traverse recursive path within a hierarchy with any number of levels.
All the major DBMS systems have now included this feature, with a notably exception: MySQL. But in MySQL you can overcome this problem with the use of stored procedures. See, for instance, this post on StackOverflow, or this post on dba.stackexchange.
So, in summary, these are my advices:

*

*If you can still decide which DBMS use, consider strongly some alternatives: for instance, if you want to stick with an open source database, use PostgreSQL, use the Adiacency List Model, and go with Recursive CTEs for your queries.

*If you cannot change the DBMS, still you should go with the Adiacency List Model, and use stored procedures as those cited in the references.

UPDATE
This situation is changing with MySQL 8, which is currently in developement and which will integrate Recursive CTEs, so that from that version the Adiacency List Model will be more simple to use.


text:
Q: What do the different Boot Options mean? (i.e. acpi=off, noapic, nolapic, etc) I've been having issues installing 11.04 on my new laptop, the solution was to enable any of these boot options:

*

*acpi=off

*noapic

*nolapic
But, what do these options actually do?
What sort of problems are there in enabling them?
i.e. can they cause hardware problems (like fans not running causing system overheating).

A: In general, such boot parameters are not needed unless there is a problem with your BIOS and how it handles these standards, or it just might be old enough where these standards were not fully implemented properly.
ACPI (Advanced Configuration and Power Interface) is a standard for handling power management. Older systems may not support ACPI full, so sometimes it helps to give the kernel a hint to not use it. "acpi=off"
APIC (Advanced Programmable Interrupt Controller) is a kind of feature found on newer systems. The "local" version is called "LAPIC". What this controller can do is be set up to generate and handle interrupts, a signal the hardware uses to pass messages. Again, some implementations of APIC can have problems on older system, and so it is useful to disable it. "noapic" and "nolapic".
Sometimes the APIC is working, but it slows things down by getting in the middle of messages being passed around. This can mess with audio and video processing, for example. Folks might disable it for that reason as well.

A: no problem for the hardware I think, as setting those functions off doesn't actually turn them off, but sets who implements them - 'off' in bios would mean that would be the kernel
what actually impacts the cooling fans I think was 'noapm' or 'apm=off' (advanced power management), but turning that off would mean cooling fans work in full speed all the time, as the 'advanced' part is actually slowing them down when system cool enough
setting those things permanently was doen by writing them in the grub file in /etc/default (usually) and after that rebuilding grub with 'update-grub' or 'grub-mkconfig' (grub2 instead of grub might be needed sometimes) depending on the system
generally it goes like 'the smaller the laptop - the bigger probability it will need them and more of them' ;)
pnpbios=off might also help (it's for plug n play)


text:
Q: scroll down to the next youtube video I have a Wordpress page with Youtube videos. When the video is finished, I want to make it scroll to the next div with the class no problem. The HTML looks like this:

//somthing on html and in the next //

.... and about 10 or 20 posts like this pro page

It works OK when I tried a test using alert('done');, but I don't want it to alert something. I want it to scroll to the next div with the class. I found a lot of code from jQuery, but I can not get it to work. Maybe for someone it is easy, but I am new in the Javascript world. Here is my Javascript:
function onPlayerStateChange(event) {
   if (event.data == YT.PlayerState.ENDED){

  }
}

A: First figure out the y position of the element you want to scroll to and then use window.scrollTo:
  var y = document.getElementById('playerxcC3UQl3V').getBoundingClientRect().y
    + window.scrollY
  window.scrollTo(0, y);


text:
Q: read and remember file line by line in python I have some data list that I have to read line by line and then parse with regexp that extracts useful data from me:
now the code looks like:
counter = 0 # first line of the file

with open(data) as f:
    for line in f:
        counter += 1
        f.readlines()[counter]
        ...
        name = re.search(r'(?<=-)\d.*?(?=\s)', line)
        ...

So now line has the first line of the text file and I can apply some regexp on it to extract the data, the main problem is that it does not seem to work as expected, I know that the solution is not elegant, but what I need is:

*

*Have a single line remembered in a variable untill next iteration

*Check if there is the end of the file and then exit

*all file's lines can't be parsed at once

*Posible size of text file is not known
I feel bad about my solution because it is not pytonish at all and there are possible further problems in case I will have to handle large amount of data. I really searched a lot and have found nothing useful for my case.

A: When you do for line in f you are iterating through the file line by line, so you don't need anything other than that in your case. For example:
with open(data) as f:
    for line in f:
        line = line.rstrip() # <- use this if you want to get rid of new line character
        name = re.search(r'(?<=-)\d.*?(?=\s)', line)
        # your code

This will also stop the loop and close the file when it reaches end of file so you don't need to worry about that.


text:
Q: C# WPF DataGrid. Index was out of range. Must be non-negative and less than the size of the collection. Parameter 'index' I'm learning to create a C# WPF Desktop Application. I wanted to retrieve the data from database and paste into the datagrid. I managed to retrieve some of the data and the error as title said appeared.
This is the XAML code for the datagrid.
<DataGrid Grid.Row="1" x:Name="scenarioDataGrid" CanUserSortColumns="True" IsReadOnly="True" AutoGenerateColumns="True" Grid.ColumnSpan="3" Margin="53,40,53,10" Grid.RowSpan="3">
                <DataGrid.Columns>
                    <DataGridTextColumn x:Name="scenarioNumberColumn" Binding="{Binding scenarioNum}" Header="No." Width="50" IsReadOnly="True"/>
                    <DataGridTextColumn x:Name="scenarioNameColumn" Binding="{Binding scenarioName}" Header="Scenario Name" Width="*" IsReadOnly="True"/>
                    <DataGridTextColumn x:Name="scenarioDateColumn" Binding="{Binding scenarioDate}" Header="Date" Width="*" IsReadOnly="True"/>
                </DataGrid.Columns>
            </DataGrid>

This is the scenario class I created
public class ScenarioData
        {
            public int scenarioNum { get; set; }
            public string? scenarioName { get; set; }
            public string? scenarioDate { get; set; }
        }

Then this is the code that I used to retrieve the data from database and paste it in the datagrid
                conn.Open();
                string sql = "SELECT COUNT(scenarioID) OVER () AS 'Num', scenarioName AS 'Scenario Name', scenarioDate AS 'Scenario Date' FROM tbl_scenario";
                SqlCommand cmd = new SqlCommand(sql, conn);

                SqlDataReader dr = cmd.ExecuteReader();

                if(dr.Read())
                {
                    int dataCount = Convert.ToInt32(dr["Num"].ToString());
                    List<ScenarioData> dataForDatagrid = new List<ScenarioData>();

                    while (dr.Read())
                    {
                        dataForDatagrid.Add(new ScenarioData()
                        {
                            scenarioName = dr["Scenario Name"].ToString(),
                            scenarioDate = dr["Scenario Date"].ToString(),
                        });
                    }

                    for (int j = 0; j < dataCount; ++j)
                    {
                        scenarioDataGrid.Items.Add(new ScenarioData()
                        {
                            scenarioNum = j+1,
                            scenarioName = dataForDatagrid[j].scenarioName,
                            scenarioDate = dataForDatagrid[j].scenarioDate,
                        });
                    }

This is the database in SSMS Database View
This is what I got when running the code Executed code result
Much appreciate if someone can point out which part I'm doing it wrongly. Thank you in advance.

A: This is because

*

*the first dr.Read() is consuming the first record from the reader, so you are populating just the second and the third records to dataForDatagrid

*dataCount value is 3, so inside the for loop you will be asking for dataForDatagrid[2], which is not exist!
Moreover, you can get rid off the dataCount at all..
List<ScenarioData> dataForDatagrid = new List<ScenarioData>();

while (dr.Read())
{
    dataForDatagrid.Add(new ScenarioData()
    {
        scenarioName = dr["Scenario Name"].ToString(),
        scenarioDate = dr["Scenario Date"].ToString(),
    });
}

for (int j = 0; j < dataForDatagrid.Count ; ++j)
{
    scenarioDataGrid.Items.Add(new ScenarioData()
    {
        scenarioNum = j+1,
        scenarioName = dataForDatagrid[j].scenarioName,
        scenarioDate = dataForDatagrid[j].scenarioDate,
    });
}

Or you just get rid of the intermediate dataForDatagrid collection:
int j = 0;

while (dr.Read())
{
    scenarioDataGrid.Items.Add(new ScenarioData()
    {
        scenarioNum = ++j,
        scenarioName = dr["Scenario Name"].ToString(),
        scenarioDate = dr["Scenario Date"].ToString(),
    });
}

If for any reason you need the dataForDatagrid collection, do this:
List<ScenarioData> dataForDatagrid = new List<ScenarioData>();
int j = 0;

while (dr.Read())
{
    dataForDatagrid.Add(new ScenarioData()
    {
        scenarioNum = ++j,
        scenarioName = dr["Scenario Name"].ToString(),
        scenarioDate = dr["Scenario Date"].ToString(),
    });
}

scenarioDataGrid.ItemsSource = dataForDatagrid;


text:
Q: Xamarin android carry id from one activity to the next I am using xamarin android to pull rest data from an api. I deserialise the data and display it in a list like so private void
ParseAndDisplay(JsonValue json)
        {
            var lstData = FindViewById<ListView>(Resource.Id.listView1);
            List<Team> list_teams = new List<Team>();
            RootObject objs = JsonConvert.DeserializeObject<RootObject>(json.ToString());
            foreach (var obj in objs.teams)
            {
                var id = obj._links.self.href;
                var indexOfLastBackSlash = id.LastIndexOf("/") + 1;
                id = id.Substring(indexOfLastBackSlash);

                Team team = new Team();
                team.name = obj.name;
                list_teams.Add(team);
                var slist = new List<string>();
                foreach (Team t in list_teams)
                {
                    string s = t.name;
                    slist.Add(s);
                }
                var data = new string[] { };
                data = slist.ToArray();
                lstData.Adapter = new ArrayAdapter(this, Resource.Layout.listViewTemplate, data);
                //lstTeams.Visibility = ViewStates.Visible;
                //ListView lstTeams = FindViewById<ListView>(Resource.Id.lstTeams);
                //ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, Convert.ToInt32(list_teams));
                // ListAdapter = new ArrayAdapter
            }

I want to select a team from the list and display more detail on them and I will need the id for this. How can I select an item and carry these details across?


text:
Q: Regex issue in Python printing entire URL I am trying to pull all the urls that contain "https://play.google.com/store/" and print the entire string. When I run my current code, it only prints "https://play.google.com/store/" but I am looking for the entire URL. Can someone point me in the right direction? Here is my code:
import pandas as pd
import os
import requests
from bs4 import BeautifulSoup
import re

URL = "https://www.pocketgamer.com/android/best-tycoon-games-android/?page=3"
page = requests.get(URL)
soup = BeautifulSoup(page.text, "html.parser")

links = []
for link in soup.findAll("a", target="_blank"):
    links.append(link.get('href'))

x = re.findall("https://play.google.com/store/", str(links))
print(x)

A: re.findall just returns the part of the text that matches the regex, so all you are getting is the https://play.google.com/store/ that is in the regex. You could modify the regex, but given what you are searching is a list of links, it's easier to just check if they start with https://play.google.com/store/. For example:
x = [link for link in links if link.startswith('https://play.google.com/store/')]

Output (for your query):
[
 'https://play.google.com/store/apps/details?id=com.auxbrain.egginc',
 'https://play.google.com/store/apps/details?id=net.kairosoft.android.gamedev3en',
 'https://play.google.com/store/apps/details?id=com.pixodust.games.idle.museum.tycoon.empire.art.history',
 'https://play.google.com/store/apps/details?id=com.AdrianZarzycki.idle.incremental.car.industry.tycoon',
 'https://play.google.com/store/apps/details?id=com.veloxia.spacecolonyidle',
 'https://play.google.com/store/apps/details?id=com.uplayonline.esportslifetycoon',
 'https://play.google.com/store/apps/details?id=com.codigames.hotel.empire.tycoon.idle.game',
 'https://play.google.com/store/apps/details?id=com.mafgames.idle.cat.neko.manager.tycoon',
 'https://play.google.com/store/apps/details?id=com.atari.mobile.rctempire',
 'https://play.google.com/store/apps/details?id=com.pixodust.games.rocket.star.inc.idle.space.factory.tycoon',
 'https://play.google.com/store/apps/details?id=com.idlezoo.game',
 'https://play.google.com/store/apps/details?id=com.fluffyfairygames.idleminertycoon',
 'https://play.google.com/store/apps/details?id=com.boomdrag.devtycoon2',
 'https://play.google.com/store/apps/details?id=com.TomJarStudio.GamingShop2D',
 'https://play.google.com/store/apps/details?id=com.roasterygames.smartphonetycoon2'
]


text:
Q: Streaming a file off a server I am trying to stream the recorded audio from my raspberry pis to my desktop computer which handles pocketsphinx phenomenally. I can pipe the audio using
arecord -D plughw:1,0 -r 16000 -f S16_LE  | ssh -C user@192.168.86.101 sox - test.wav
And then run it using
pocketsphinx_continuous -dict ~/4568.dic -lm ~/4568.lm -infile ~/test.wav
But once it reaches the end of the file, it stops, even though the file is still writing. Is there a way to keep it open?

A: Use named pipe instead of a regular file. Also you can file an issue at github.com/cmusphinx/pocketsphinx requesting that pocketsphinx_continious should be able to read from stdin. And of course you're welcome to submit such a patch.

A: To anyone else finding this,
arecord -D plughw:1,0 -r 16000 -f S16_LE | ssh -C user@192.168.86.101 pocketsphinx_continuous -infile /dev/stdin
is how to do it


text:
Q: Preserve which page I was on before logging out Angular 6 Is there a way to preserve which page I was on before logging out and be redirected to that same page and not a default homepage after login.

A: There are two ways you can achieve it.

*

*Save the page/route name in the database and retrieve it on login.

*Save the page/route name in local storage and retrieve it on login.

In your login component then check if there was a value in local storage or database:
If YES: route to page you were on before login out.
this.router.navigate(['your page before logout']);

If No: route to the default page.


text:
Q: Show a class Over button click using Jquery I want to show a div on button click and after that it should get closed on another button click.
Right now I am able to toggle between hiding and showing a div. But instead I want it not to  toggle but remain there itself until i click close button.I am new to J Query. Can somebody please help

$('.trigger, .slider').click(function() {
  $('.slider').toggleClass('close');
});
.slider {
  position: absolute;
  width: 1000px;
  height: 100vh;
  margin-top: -304px;
  overflow: hidden;
  background-color: aliceblue;
  transition: all 1s;
}

.slider.close {
  top: 100vh;
  height: 0;
}

            College

            Value 1

            Value 2

            Value 3

            Value 4

            Location

            Value 1

            Value 2

            Value 3

            Value 4

With this Iam able to bring a div up from hidden.But whenever i click on any part of slider div,it gets closed due to toggleClass
I just want to show the div and let it remain there until i click close button
Thanks in adavance.

A: Instead of using toggle, simply set a different event handler to each of the different buttons.
Each button has a different and specific action, so they only need to either add a class, or remove a class.
$('.trigger.open').on('click', function() {
    $('.slider').removeClass('close');
});
$('.trigger.close').on('click', function() {
    $('.slider').addClass('close');
});

Also, you will need to set the proper classes to the different buttons so the JS code will be able to select them properly.
<button type="button" class="trigger open">Click to open</button>
<button type="button" class="trigger close">Click to close</button>


text:
Q: XCode 4.5, Facebook SDK 3.1 implementation resulting in "...selected destination does not support the architecture ..." error Presently getting the following error:
Cannot run on the Selected Destination
The selected destination does not support the architecture for which the selected software is built.  Switch to a destination that supports that architecture in order to run the selected software
This started happening after adding the new Facebook SDK to my project (adding the framework, adding -lsqlite3.0 to my Other Linker Flags build setting.
I've tried rebooting my computer; I've tried it on a different app (one of the one facebook instructs you to make to demonstrate the Login) and no matter what I do, I always get this error. Looked around on SO and found nothing that seemed to pertain to me.
Any ideas?

A: did you add the entire facebooksdk folder? if so it has an info.plist file in it, delete that file and you should be fine.
xcode gets confused when there are multiple info.plist files in a project

A: I have found the issue, if you install the FacebookSDK and you add the resources folder to get the facebook image buttons there is a Info.plist file. XCodes goes weird with this info.plist file. I have deleted it, made a clean and now it works perfect :)
The best option is to move the project to other path. Adding and removing the libsql3.0 from lib dependencies sometimes works too.

A: There are a few different things that I have seen cause this error. Like already mentioned, make sure that the architecture defined in the build settings are correct for the project & any static libraries you're using.
One thing that causes this that I've run into quite a few times is that the "Product Name" specified in either the project or one of the targets build settings does not match the target name.
For example:
If you have a project named "MyProject" and you have a target named "SomeTarget", in the build settings for "SomeTarget", the Product Name (under "Packaging") has to be "SomeTarget". If it's not, for whatever reason, you will get this error.
We have a project at my work which we run a script on to change various things on so we can package apps separately depending on what we need to do. Whenever we add a new configuration to the script, if we don't add the part to change the product name we get this error every time.
Don't know if that will help your particular problem, but I thought I'd mention it just in case.


text:
Q: What does "This tweet was manufactured in a facility that also processes triggers." mean? The following tweet is from Paul Graham https://twitter.com/paulg/status/664170540559564800. Is he speaking about the brains ability to process interruptions while tweeting?

A: As HotLicks notes, the phrasing is that of the warning on some food packaging:  "XXX product was manufactured in a facility that also processes YYY."  If you're allergic to peanuts but not almonds, and XXX="almond butter" an YYY="peanuts," then you might want to avoid this brand of almond butter that might be slightly contaminated with peanuts.
Triggers is shorthand for "trigger warnings," a label used by the politically correct to warn people that some material might offend them.  From what I can tell, Paul Graham is opposed to the use of trigger warnings, so his tweet means that people who are in favor of them might be upset at his opposition.


text:
Q: Proving perpendicularity Let $ABC$ be a triangle. Let $I$ be its inscribed circles' center. Let $D$ be the intersection point of lines $AI$ and $BC$. The perpendicular bisector of $AD$ intersects with $BI$ in $E$.
Thesis:
$$
ED\perp CI
$$
How to prove that using synthetic euclidean geometry?

A: The key is to show that $A,B,D,E$ are cyclic. To show this let the angle bisector of $\angle B$ cut the circumcircle of $\triangle ABD$ at $E^{'}$. Then, since $\angle ABE^{'}=\angle DBE^{'}$, we have $AE^{'}=DE^{'}$. Therefore the perpendicular bisector of $AD$ passes through $E^{'}$. Hence $E^{'}$ is the same as $E$, that is $A,B,D,E$ are cyclic as we desired.
The remaining part is trivial.
Let $P$ be the intersection of $DE$ and $CI$ and $F$ the midpoint of $AD$.
Using the cyclicity we've just proven,
$$\angle AED=\pi-\angle ABD=2(\angle DAC+\angle ICA)$$
Because$ \triangle AED$ is isosceles, it's obvious that $\square PEFI$ is cyclic and the conclusion follows.


text:
Q: Installing conda on Colab I want to install a library on colab to use GPU capabilities. This library can only be installed via conda. How to do this without getting errors such as: File "/usr/local/bin/conda, line 7, in  from conda.cli import main ModuleNotFoundError: No module named 'conda'. Thanks

A: Here's an example how to install faiss using conda.
!wget -c https://repo.anaconda.com/miniconda/Miniconda3-4.5.4-Linux-x86_64.sh
!chmod +x Miniconda3-4.5.4-Linux-x86_64.sh
!bash ./Miniconda3-4.5.4-Linux-x86_64.sh -b -f -p /usr/local
# can change to another channel or package
!conda install -q -y --prefix /usr/local -c pytorch faiss-cpu
import sys
sys.path.append('/usr/local/lib/python3.6/site-packages/')
import faiss


text:
Q: How to rename filnames stored as tibble/dataframe using dplyr I have the following data frame which contains a list of files.
library(tidyverse)
dat <- structure(list(source_file = structure(c("data/monroe_20180214/180131 WT PB d5/PB x10_01.tif",
"data/monroe_20180214/180131 WT PB d5/PB x10_02.tif", "data/monroe_20180214/180131 WT PB d5/PB x10_03.tif",
"data/monroe_20180214/180131 WT PB d5/PB x10_04.tif", "data/monroe_20180214/180131 WT PB d5/PB x10_05.tif",
"data/monroe_20180214/180131 WT PB d5/PB x10_06.tif"), class = c("fs_path",
"character"))), .Names = "source_file", row.names = c(NA, -6L
), class = c("tbl_df", "tbl", "data.frame"))

dat
#> # A tibble: 6 x 1
#>   source_file
#>   <chr>
#> 1 data/monroe_20180214/180131 WT PB d5/PB x10_01.tif
#> 2 data/monroe_20180214/180131 WT PB d5/PB x10_02.tif
#> 3 data/monroe_20180214/180131 WT PB d5/PB x10_03.tif
#> 4 data/monroe_20180214/180131 WT PB d5/PB x10_04.tif
#> 5 data/monroe_20180214/180131 WT PB d5/PB x10_05.tif
#> 6 data/monroe_20180214/180131 WT PB d5/PB x10_06.tif

What I want to do is to create second column new_filename by replacing the first two directory paths with new path pooled/ and replace whitespace with ., backslash with __. How can I achieve that?
The desired result is
  source_file                                         new_filename
1 data/monroe_20180214/180131 WT PB d5/PB x10_01.tif  pooled/180131.WT.PB.d5__PB.x10_01.tif
2 data/monroe_20180214/180131 WT PB d5/PB x10_02.tif  ...
3 data/monroe_20180214/180131 WT PB d5/PB x10_03.tif  .etc.
4 data/monroe_20180214/180131 WT PB d5/PB x10_04.tif
5 data/monroe_20180214/180131 WT PB d5/PB x10_05.tif
6 data/monroe_20180214/180131 WT PB d5/PB x10_06.tif

A: With gsub() from string you can do it as well
     dat %>% mutate(new_var = gsub("data/monroe_20180214", "pooled", source_file),
+                new_var = gsub(" ", ".", new_var),
+                new_var = gsub("/", "_", new_var),
+                new_var = gsub("pooled_", "pooled/", new_var))
# A tibble: 6 x 2
                                         source_file                              new_var
                                               <chr>                                <chr>
1 data/monroe_20180214/180131 WT PB d5/PB x10_01.tif pooled/180131.WT.PB.d5_PB.x10_01.tif
2 data/monroe_20180214/180131 WT PB d5/PB x10_02.tif pooled/180131.WT.PB.d5_PB.x10_02.tif
3 data/monroe_20180214/180131 WT PB d5/PB x10_03.tif pooled/180131.WT.PB.d5_PB.x10_03.tif
4 data/monroe_20180214/180131 WT PB d5/PB x10_04.tif pooled/180131.WT.PB.d5_PB.x10_04.tif
5 data/monroe_20180214/180131 WT PB d5/PB x10_05.tif pooled/180131.WT.PB.d5_PB.x10_05.tif
6 data/monroe_20180214/180131 WT PB d5/PB x10_06.tif pooled/180131.WT.PB.d5_PB.x10_06.tif

A: One liner:
paste0("pooled/",chartr(" /", "._",(sub("^(?:[^\\/]*\\/){2}","",dat$source_file))))

#[1] "pooled/180131.WT.PB.d5_PB.x10_01.tif"
#[2] "pooled/180131.WT.PB.d5_PB.x10_02.tif"
#[3] "pooled/180131.WT.PB.d5_PB.x10_03.tif"
#[4] "pooled/180131.WT.PB.d5_PB.x10_04.tif"
#[5] "pooled/180131.WT.PB.d5_PB.x10_05.tif"
#[6] "pooled/180131.WT.PB.d5_PB.x10_06.tif"

Here we first replace the part with first two occurrence of / with empty strings(""), then use chartr function from base R to replace spaces with dot (.) and forward slash (/) with underscore (_) and then paste the string with pooled/.
The regex for sub part has been taken from here.
Adding this in dplyr call :
dat %>%
 mutate(new_filename =paste0("pooled/", chartr(" /", "._",
                            (sub("^(?:[^\\/]*\\/){2}", "", source_file))))) %>%
 select(new_filename)

#new_filename
#  <chr>
#1 pooled/180131.WT.PB.d5_PB.x10_01.tif
#2 pooled/180131.WT.PB.d5_PB.x10_02.tif
#3 pooled/180131.WT.PB.d5_PB.x10_03.tif
#4 pooled/180131.WT.PB.d5_PB.x10_04.tif
#5 pooled/180131.WT.PB.d5_PB.x10_05.tif
#6 pooled/180131.WT.PB.d5_PB.x10_06.tif


text:
Q: Getting the results of a variable length prepared statement in MySQLi I writing an accounting website which has quite a few MySQL statements in it. To prevent SQL injection I use prepared statements for any data which is put in by the user.
In order to prevent having to write the steps of preparing and binding statements I have the following function:
function executeSql($mysqli,$query_string,$params=null,$paramtypes=null){
    $nr_params=strlen($paramtypes);
    $query_type = substr($query_string,0,3);
    $stmt = $mysqli->prepare($query_string);
    $queryParams[] = $paramtypes;
    $counter=1;
    if($nr_params>1){
        while($counter<=$nr_params){
             $queryParams[$counter]=&$params[$counter-1];
             $counter++;
        }
    } else {
        $queryParams[1]=&$params;
    }
    // Actual binding of the statement. Taking into account a variable numbers of '?' in the query string.
    call_user_func_array(array($stmt,'bind_param'),$queryParams);
    // Execution of the statement
    $stmt->execute();
    // Part where i'd like to have a substitute for:
    $result = $stmt->get_result();
    return $result;
    }

In the last part I'd like to return the result because then using the result I can treat each row. The problem is that the mysqlnd driver is not installed on the production server so the function $stmt->get_result() cannot be used. I tried to bind the result into variables but then again, every query returns a different number of columns.
Anyone has an idea how to tackle this?
So in summary (in response to the comments):
How can I retrieve a results object of an executed MySQLi statement while I cannot use $stmt->get_result();
Kind regards,
EJG
PS I know the code is not flawless, e.g. if strings are used as variables to bind to the statement but that is easily fixed.
UPDATE:
I came across the function $stmt->result_metadata(); Although supposedly the function name suggests only the meta data the php documentation states that:
"If a statement passed to mysqli_prepare() is one that produces a result set, mysqli_stmt_result_metadata() returns the result object"...


text:
Q: delay loading of library in Shiny after UI appears, but before actually needed If I call a package, like library(tidyverse), in global.R it adds approx. 2 seconds to the initial launch of app on shinyapps.io. Note that this appears to be the case if no one has used the app recently (but not when there are concurrent users).
I don't need that package until an observeEvent is executed.
I can put the library(tidyverse) inside the observeEvent, but then that takes 2 seconds when time is of essence.
Can I load libraries just after the UI finishes loading but before the observeEvent?
Something like: if shiny app is idle (flushed?), then load a package?

A: Below is one way to do it that relies on onFlushed, but I'd like to see if someone finds something better (like using invalidatelater as mentioned in the
comments above).
I'm not sure what onFlushed does, but here's what the documentation says:
"onFlushed registers a function that will be called after Shiny flushes the reactive system."

I think that a flush means that all the other reactives are "resolved." In my case, the UI appears far quicker and allows user input BEFORE tidyverse is loaded, which makes the app more responsive to begin with.
Put the below in the server:
values <- reactiveValues(finished.init = FALSE)

session$onFlushed(function() {
  values$finished.init <- TRUE
 })

observe({
  req(values$finished.init)
  library(tidyverse)
  #any other libraries you'd like to load after initial flush
  })


text:
Q: React Native setState add's last item of the array So i got a setState named items const [items, setItems] = React.useState([]);
My Items Array Structure
[{
  "id": "0.625240011345925",
  "item_name": "Item 23",
  "item_price": "23",
  "item_qty": "1"
}, {
  "id": "0.735657461482515",
  "item_name": "Item 4",
  "item_price": "30",
  "item_qty": "1"
}, {
  "id": "0.287635530963835",
  "item_name": "Item 2",
  "item_price": "56",
  "item_qty": "1"
}]

Main Function
    const AddItemToBill = (navigation) => {
    navigation.navigate('AddItemToBill', {
        onReturn: (itemArray) => {
            const array = itemArray;
            for (let i = 0; i < array.length; i++) {
                const element = array[i];
                setItems([...items, element]);
                console.log('Items: ' + JSON.stringify(array))
            }
        }, navigation
    })
};

Check issue in below Gif

A: React setState is asynchronous. Updated state is only available on the next render cycle. So adding multiple items in a for loop would only result in the last item being updated.
Rules of hooks -
Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns.
Correct way is to build a new intermediate array & update state once -
const array = itemArray;
const newState = []; // array to hold the final state
for (let i = 0; i < array.length; i++) {
    const element = array[i];
    // update the array for the final state
    // DO NOT UPDATE STATE HERE
    newState.push(element);
    console.log('Items: ' + JSON.stringify(array))
}
// update state ONCE outside forloop
setItems([...items, newState]);

A: As you are looping for getting all the elements, you can just spread directly itemArray
 onReturn: (itemArray) => {
                setItems(prev => ([...prev, ...itemArray]));
            }

Also used prev and not items state directly as a safety that it will always be called with the last value of the array in case a user make two quick interactions in a row


text:
Q: How to get address of cell which calls a VBA Functions in a Excel sheet Is there a function to get the address of a cell which call a VBA function ?
I used "Application.ActiveCell.Address" , but found that this method is not a correct way to get the address of calling cell.
e.g: If we have excel sheet with saved VBA functions, Once you reopen the sheet, the above method will not work.
please help
nimo

A: You can use Application.Caller, but you would probably be best to pass the cell to the function.
   With Application.Caller
        CallerRows = .Rows.Count
        CallerCols = .Columns.Count
        CallerAddr = .Address
   End With

See: http://www.cpearson.com/excel/WritingFunctionsInVBA.aspx
To pass the cell:
 =SomeFunction(A1)

Where the code has:
SomeFunction(r)


text:
Q: Evalutating $\lim \limits_{ x \to \infty} (x+1)^k - (x)^k$ , given $0I Tried evaluating as follows but got stuck with the uncertainty $(  0·\infty  ) $
What I did was :
$\lim \limits_{ x \to \infty} (x+1)^k - (x)^k = \lim \limits_{ x \to \infty} (x)^k·(\frac{(x+1)^k}{(x)^k} - 1)  = \lim \limits_{ x \to \infty} (x)^k·((\frac{x+1}{x})^k - 1) = $
$\lim \limits_{ x \to \infty} (x)^k·((1+\frac{1}{x})^k - 1) $
$\lim \limits_{ x \to \infty} (x)^k·(e^{ln(1+\frac{1}{x})^k} - 1)  = (e^{k·ln(\lim \limits_{ x \to \infty}(1+\frac{1}{x})} - 1) ·\lim \limits_{ x \to \infty} (x)^k = (e^{k·ln(1)} - 1) ·\infty $ = $(e^{0} - 1) ·\infty  = (1 - 1) ·\infty $ = \
⇒ $0 ·\infty $
( I Also Tried using the Squeeze theorem but all upper functions I tried went to $\infty$  )
➔ Using $k=\frac{1}{2}$ and then $\lim \limits_{ x \to \infty} \sqrt{(x+1)} - \sqrt{(x)}$ :
I found that  $\lim \limits_{ x \to \infty} \frac{1}{\sqrt{(x+1)} + \sqrt{(x)}}$ = $\lim \limits_{ x \to \infty} \frac{1}{\infty} = 0$ ,
However , I'm struggling to do the same algorithm with  $\lim \limits_{ x \to \infty} \sqrt[q]{(x+1)} - \sqrt[q]{(x)}$ : Assuming $k=\frac{1}{q} $ ; $q \in (\mathbb{R}^+/ 0)$
(meaning  $\lim \limits_{ x \to \infty} (x+1)^k - (x)^k$  = $\lim \limits_{ x \to \infty} \sqrt[q]{(x+1)} - \sqrt[q]{(x)}$)
I would love to get some help on how to evalutate the limit !

A: You can just rewrite the expression and use L'Hôpital's rule:
$$
\lim_{x\to +\infty}\left((x+1)^k-x^k\right)=\lim_{x\to +\infty}\dfrac{(1+1/x)^k-1}{1/x^k}=\lim_{x\to +\infty}\dfrac{(-k/x^2)(1+1/x)^{k-1}}{-k x^{-k-1}}=\lim_{x\to +\infty}(x+1)^{k-1} = 0
$$

A: Use Taylor polynomial:  as $h \to 0$, we have $(1+h)^k = 1+kh+o(h)$.
As $x\to\infty$,
$$
(x+1)^k = x^k\left(1+\frac{1}{x}\right)^k = x^k\left(1+\frac{k}{x}+o(1/x)\right) = x^k+kx^{k-1}+o(x^{k-1})
\\
(x+1)^k - x^k = kx^{k-1}+o(x^{k-1})
$$
Now $k<1$ so $k-1 < 0$ and thus $\lim_{x\to\infty} x^{k-1} = 0$.
Conclude
$$
(x+1)^k - x^k \to 0\quad\text{ as }x\to\infty
$$
or more pricisely
$$
(x+1)^k - x^k \sim kx^{k-1}\quad\text{ as }x\to\infty
$$
Example:
$$
\sqrt{x+1}-\sqrt{x} \sim \frac{1}{2\sqrt{x}}\quad\text{ as }x\to\infty
$$


text:
Q: How can I get the string between repeated DYNAMIC html tags in a string using javascript? (No regex unless its the only way!) As a mean to explain I am not posting the gigantic string I have (which contains dynamic html tags and are auto-generated with unique id). I want to get the text between every tag that says "
... comment...
" using anything excep Regex, and in my case ill have a string of 20 repeated tags by getting the outerHTML. I have an example below:
var str = "

You have to try their special sushi rolls like acevichado or patrullero. They have great selections of sushi and other dishes.

All you can eat sushi fir $20 ($24 including tax)! Christian, our server, was wonderful and attentive.

The place was good, also the waiters, but definitely sushi is the best in town
for my opinion, even with the few options of it in this place. I will be there soon again.

";

What I want is the 3 comments I have in my example so I use the code for 20:
- You have to try their special sushi rolls like acevichado or patrullero. They have great selections of sushi and other dishes.

- All you can eat sushi fir $20 ($24 including tax)! Christian, our server, was wonderful and attentive.

- The place was good, also the waiters, but definitely sushi is the best in town for my opinion, even with the few options of it in this place. I will be there soon again.

I tried making my own code but the text or tags in between are not taken off since it detects the tag I preset, example: "THE WHOLE STRING AFTER THE TAG IM LOOKING FOR +
... comment...
" and I only want ...comment... part.
The code I made is below:
var temp = "
');
    var res2 = res.indexOf(temp) + 1;
    var resultado = null;

     if (res2 < res.length && res2 != -1) {
         resultado = res[ res2 ]; // gets the next one
    }

    alert(resultado);

A: This is pretty trivial, assuming the comments will always be wrapped in a node with class partial_entry:
var commentNodes = document.getElementsByClassName('partial_entry');
var comments = [];
for (var i = 0; i < commentNodes.length; i++) {
  comments.push(commentNodes[i].innerText);
}

A: You could use a for loop that loops through every single character until it sees , then stores every character until it sees
It probably isn't the best way, and won't work if there's other tags inside the p. But it works.

var text = "
This text should show up
"
var seenBeginTag = false;
var seenEndTag = false;
var output = [];

for (var i = 0; i < text.length; i++)
{
  if (seenBeginTag && seenEndTag) {
    if (text[i] == '<')
    {
      seenBeginTag = false;
      seenEndTag = false;
    }
    else {
      output.push(text[i]);
    }
  }
  else if (seenBeginTag) {
    if (text[i] == '>')
    {
      seenEndTag = true;
    }
  }
  else if (text[i] == '<') {
    if (text[i+1] == 'p') {
      seenBeginTag = true;
    }
  }
}

console.log(output.join(''));


text:
Q: cannot import name 'colored' from 'termcolor' I'm trying to use termcolor in python3 using termcolor tutorial but i can't import colored from termcolor
from termcolor import colored
text = colored("Hello world", "green")
print(text)

it giving me
E:\>python termcolor.py
Traceback (most recent call last):
  File "termcolor.py", line 1, in <module>
    from termcolor import colored
  File "E:\termcolor.py", line 1, in <module>
    from termcolor import colored
ImportError: cannot import name 'colored' from 'termcolor' (E:\termcolor.py)


text:
Q: How to set the cache for the built-in SimplePie feed parser? I'm using the built-in SimplePie, AKA fetch_feed(), to retrieve a feed, and I want to be able to adjust the cache time from an admin menu. SimplePie itself is well documented, but not so much the WordPress implementation of it.
Any thoughts on the best way to set the cache duration?

A: Cache duration value (defaults to 43200 seconds) is set when feed object is generated and passed through wp_feed_cache_transient_lifetime filter with additional argument being feed URL.
This allows to conveniently filter it both globally and for specific feeds.
See fetch_feed() source for this and other hooks you can use to modify its behavior.

A: To elaborate on Rarst's solutuion. I've been using the following to great success:
add_filter( 'wp_feed_cache_transient_lifetime', create_function( '$a', 'return 3600;' ) );

This sets the feed cache at one hour and should be placed immediately after the feed.php include.


text:
Q: Remove an array from a setlist if count above x I am currently using an std::set<uintptr_t> list to store unique pointers in it. This list gets bigger with the time and when this list reaches x amount of entries it should delete the first entry, the other entries should move down one and make room for a new entry.
For example:
if (list.count >= 20)
{
    list.remove[0]; //remove the first entry from the list?
}

I know this code doesn't work but just for the logic so you know what I mean. Also the first entry would be empty then, would it be possible to move all other entries one down so the [0] entry isn't empty anymore?

A: You can get the iterator of your first element in your list with list.begin()
if (list.count >= 20)
{
    list.erase(list.begin()); //remove the first entry from the list
}


text:
Q: jQuery Datatables options (buttons, search, etc.) not working in Bootstrap 4 tabs

$(document).ready(function () {
    $('.datatable').DataTable({
        responsive: true,
        dom: 'Blfrtip',
              buttons: [
                  'copy', 'csv', 'excel', 'print'
              ]
    });

    $('a[data-toggle="pill"]').on('shown.bs.pill', function (e) {
        $($.fn.dataTable.tables(true)).DataTable()
           .columns.adjust()
           .responsive.recalc();
    });
});

<link href="https://cdn.datatables.net/v/bs4-4.1.1/jszip-2.5.0/dt-1.10.22/b-1.6.5/b-html5-1.6.5/b-print-1.6.5/r-2.2.6/datatables.min.css" rel="stylesheet"/>

                       -

                                        First

                                        Second

                                        Third

                        Name
                        Position
                        Office
                        Age
                        Start date
                        Salary

                        Tiger Nixon
                        System Architect
                        Edinburgh
                        61
                        2011/04/25
                        $320,800

                        Garrett Winters
                        Accountant
                        Tokyo
                        63
                        2011/07/25
                        $170,750

                        Ashton Cox
                        Junior Technical Author
                        San Francisco
                        66
                        2009/01/12
                        $86,000

                        Name
                        Position
                        Office
                        Age
                        Start date
                        Salary

                        George Nixon
                        System Architect
                        Edinburgh
                        61
                        2011/04/25
                        $320,800

                        Garrett Winters
                        Accountant
                        Tokyo
                        63
                        2011/07/25
                        $170,750

                        Ashton Cox
                        Junior Technical Author
                        San Francisco
                        66
                        2009/01/12
                        $86,000

                        Name
                        Position
                        Office
                        Age
                        Start date
                        Salary

                        Beatrice Nixon
                        System Architect
                        Edinburgh
                        61
                        2011/04/25
                        $320,800

                        Garrett Winters
                        Accountant
                        Tokyo
                        63
                        2011/07/25
                        $170,750

                        Ashton Cox
                        Junior Technical Author
                        San Francisco
                        66
                        2009/01/12
                        $86,000

I am trying to use jQuery Datatables with Bootstrap 4 tabs.  Each tab will show a different datatable.  My JavaScript and jQuery are pretty weak.  I originally had four tables on my page visible at once and this code worked:
$(document).ready(function() {
      $('.datatable').DataTable( {
          dom: 'Blfrtip',
          buttons: [
              'copy', 'csv', 'excel', 'print'
          ]
      } );
  } );

When I switched to tabs and some of the datables were on closed tabs (hidden), it fails.  The first tab has the buttons, number of items per page, and search, but none of the other tabs do.  I looked at these two links: Scrolling and Bootstrap tabs and Hidden initialisation.  I believe that I have to do something like this:
$(document).ready(function() {
      $('a[data-toggle="pill"]').on( 'shown.bs.tab', function (e) {
          $.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
      } );
      $('.datatable').DataTable( {
          dom: 'Blfrtip',
          buttons: [
              'copy', 'csv', 'excel', 'print'
          ]
      } );
  } );

But that doesn't do it, and I'm lost.  Can some kind person point me in the right direction?
Thanks--
Al
I don't think this is a duplicate question (Or I don't understand the other post).  I looked at the suggested post; it addresses problems with column widths.  That is not my problem.  Basically, just the table in my first tab is being treated as a datatable complete with my options and buttons.  All of the subsequent tabs behave as if they are ordinary tables.  Ensuring that I was using responsive and setting 'responsive: true' didn't do anything to help my problem.  I am presuming that this is an initialization problem due to the subsequent tabs being hidden when the page is loaded.  As I indicated earlier, when all of the tables were displayed (unhidden) on load, they all behaved properly.  thx.
I've inserted a code snippet, but I'm afraid that in the sandbox it works correctly with the buttons and options :( (though it does have issues with the column widths).  I will have to keep playing with my code and see if I can get something to fail in a sandbox.  I was hoping I was doing something obviously wrong, but...
OK.  I have done some further testing.  I am trying to do this tabbed page in a Django app.  If I put the code from the snippet here into a page in my Django app, it works fine except for the column widths.

*

*If I replace the hard coded table in the first tab with template code
looping through one of my queries, it continues to work correctly,
and the other two (still hard coded) tabs show all of the options.

*If I replace the hard coded table in the second tab with different
(but similar) template code looping through another query, the datable
options, etc. disappear in both the second and third tabs.

*If I replace the hard coded table in the second tab with the same
template code (with the query loop) from the first tab, the datatable
options continue to show properly (though the column widths still
mess up).
I am referring to all the tables with a class of 'datatable'.  Do I need to use an id instead for each of my tables that I want rendered as a datatable?  While similar, each table (there are five) has different columns and some have a different number of columns.  Would I have to repeat this code for each of my tables with an id instead of a class?
$(document).ready(function () {
$('.datatable').DataTable({
    responsive: true,
    dom: 'Blfrtip',
          buttons: [
              'copy', 'csv', 'excel', 'print'
          ]
});

Thanks!


text:
Q: ¿Cómo sustituir en una cadena todas las expresiones contenidas en un array? A ver si alguien experto me puede ayudar con este problema:
Me gustaría sustituir una cadena por determinadas expresiones contenidas en un array (si éstas coinciden con la cadena). Lo estoy haciendo así, pero se me repite la cadena (porque está en el bucle for que uso para recorrer el array):
expresiones = ['naranja limones', 'fresa frambuesa'];

frase = 'naranja limones fresa frambuesa';

function sustituye(fr, expr){
   for(i=0;i<expr.length;i++){
      if(fr.includes(expr[i])==true){
         y = fr.replace(expr[i], expr[i].split(' ').join('-'));
         document.write(y);
      }
   }
}

sustituye(frase, expresiones);

Quiero obtener esto:
naranja-limones fresa-frambuesa
pero me sale esto:
naranja-limones fresa frambuesanaranja limones fresa-frambuesa

A: Hola tienes un pequeño fallo en las sustituciones pues el split parte la expresión validada y reemplazas una parte de ella. Adicionalmente, el modo como usas los nombres hace que las asignaciones de sustitución no sean claras.
Te voy a ofrecer una variante del código muy elemental que hace la sustitución correcta:

function sustituye(fr, expr){
    var reemplazo;
    // Uso un ciclo sin índices que me parece más cómodo porque
    // en este caso los índices carecen de uso.
    for(let buscar of expr){
        // Crea la variable de sustitución
        reemplazo = buscar.replace(' ', '-');
        // Verifica si hay o no coincidencia
        if(fr.includes(buscar)==true){
            // Si la hay hace el reemplazo
            fr = fr.replace(buscar, reemplazo);
        }// cierra validación
    }// cierra ciclo for
    // devuelve la cadena modificada
    return fr;
}//cierra la función sustituye
expresiones = ['naranja limones', 'fresa frambuesa'];
frase = 'naranja limones fresa frambuesa';
console.log(sustituye(frase, expresiones));


text:
Q: Elementor video opacity For all of you that used Elementor as Wordpress plugin, are you able to adjust video background opacity? I know that picture background is able to do that, but not goes to video.
I was trying to put Title and some short Paragraph description on my video, if I was able to lower my video opacity.
Any help is appreciated :D

A: You can set opacity of background video in Background Overlay option. You can check in below image.


text:
Q: Rails4 model ignores parent_id on 'create' action I have Subcategories which belong to Categories. My app saves (build) all my Subcategories under Subcategory with id = 1, even though my code seems to be ok and it is not supposed to do that:
Subcategories controller:
    def create
      @category = Category.find_by(params[:id])
      @subcategory = @category.subcategories.build(subcategory_params)
      if @subcategory.save
        flash[:success] = "added subcategory"
        redirect_to admin_categories_url
      else
        render :new
      end
    end

...

    private

      def subcategory_params
        params.require(:subcategory).permit(:name, :category_id)
      end

Subcategory.rb
class Subcategory < ActiveRecord::Base
  belongs_to :category
  has_many :products

  validates :name, presence: true
  validates :category_id, presence: true
end

Form:

Add a subcategory

<%= form_for [@category, @subcategory] do |f| %>
  <%= f.text_field :name, placeholder: "Name" %>
  <%= f.submit "Add a subcategory" %>
<% end %>

router:
resources :categories do
    resources :subcategories
  end

URL:
Adding a new subcategory to category with id = 3
http://localhost:3000/categories/3/subcategories/new

Logs:
Started POST "/categories/1/subcategories" for 127.0.0.1 at 2014-04-16 16:04:47 +0400
Processing by SubcategoriesController#create as HTML
  Parameters: {"utf8"=>"✓", authenticity_token"=>"74U3VyAN6NqEjhkuHGNHnPda/yzpc+dIcn2xBJ6Zi2A=", "subcategory"=>{"name"=>"A name"}, "commit"=>"Add subcategory", "category_id"=>"1"}
  User Load (0.2ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
  Category Load (0.2ms)  SELECT  "categories".* FROM "categories"  WHERE "categories"."id" = $1 LIMIT 1  [["id", 1]]
   (0.1ms)  BEGIN
  SQL (0.2ms)  INSERT INTO "subcategories" ("category_id", "created_at", "name", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["category_id", 1], ["created_at", "2014-04-16 12:04:47.151729"], ["name", "A name"], ["updated_at", "2014-04-16 12:04:47.151729"]]
   (0.8ms)  COMMIT

Id is 1
What can be the problem here?
Update
When doing
@category = Category.find_by(params[:category_id])

this error comes up:
ERROR:  argument of WHERE must be type boolean, not type integer
LINE 1: SELECT  "categories".* FROM "categories"  WHERE (1) LIMIT 1

If doing
@category = Category.find(params[:category_id])

problem presists

A: In your create action you are picking up the id of the subcategory, not the category.  Change it to:
def create
  @category = Category.find(params[:category_id])
  ...

The same change to setting @category needs to be made in the new method too so that category_id comes back as 3 in the params from the view.  Of course this duplication can be also DRYed up using a helper method in the controller.
To see the difference in the id, you can use rake routes and you should see something like:
new_category_subcategory   GET   /categories/:category_id/subcategories/new   subcategories#new

This shows you that it expects the parameter category_id for the id of the category.

A: Look at your parameters it consist category_id not id
 Parameters: {"utf8"=>"✓", authenticity_token"=>"74U3VyAN6NqEjhkuHGNHnPda/yzpc+dIcn2xBJ6Zi2A=", "subcategory"=>{"name"=>"A name"}, "commit"=>"Add subcategory", "category_id"=>"1"}

#=>   "category_id"=>"1"
   Category.find_by(category_id: params[:category_id])

So you need to do
 def create
  @category = Category.find_by(category_id: params[:category_id])
  @subcategory = @category.subcategories.build(subcategory_params)
  if @subcategory.save
    flash[:success] = "added subcategory"
    redirect_to admin_categories_url
  else
    render :new
  end
end


text:
Q: PostgreSQL - Merge/Join Tables With Different Effective Dates I have two dimensional tables in an SCD Type 2 format that I would like to merge. The second table contains additional rows relevant to the eventual structure of the first table.
First table (foo):
| employee_id | location_id | team_id | date_effective | date_expired |
|-------------|-------------|---------|----------------|--------------|
| 40          | 1           | 6       | 20180101       | 20190331     |
| 40          | 2           | 6       | 20190331       | 99991231     |

Second table (bar):
| team_id | manager_id | date_effective | date_expired |
|---------|------------|----------------|--------------|
| 6       | 15         | 20180301       | 20180630     |
| 6       | 27         | 20180630       | 99991231     |

Desired output after merging:
| employee_id | location_id | team_id | manager_id | date_effective | date_expired |
|-------------|-------------|---------|------------|----------------|--------------|
| 40          | 1           | 6       | NULL       | 20180101       | 20180301     |
| 40          | 1           | 6       | 15         | 20180301       | 20180630     |
| 40          | 1           | 6       | 27         | 20180630       | 20190331     |
| 40          | 2           | 6       | 27         | 20190331       | 99991231     |

I know how to join the two tables by dates, but not how to efficiently generate the extra row(s) necessary in the output. Here is my current code:
with foo as (
select *
from
(values (40,1,6,20180101,20190331),(40,2,6,20190331,99991231))t(employee_id, location_id, team_id, date_effective, date_expired)
)

,bar as (
select *
from
(values (6,15,20180301,20180630),(6,27,20180630,99991231))t(team_id, manager_id, date_effective, date_expired)
)

select *
from foo f
left join bar b on f.team_id = b.team_id
    and ((f.date_effective between b.date_effective and b.date_expired)
    or (b.date_effective >= f.date_effective and b.date_effective < f.date_expired))

I know I could achieve the results by expanding each table to individual days and do some window functions, but I was wondering if there was a more efficient way.
Thanks in advance!

A: A possible solution is to find distinct dates across both foo and bar for team_id and join back to foo and bar.
with foo as (
select *
from
(values (40,1,6,20180101,20190331),(40,2,6,20190331,99991231))t(employee_id, location_id, team_id, date_effective, date_expired)
)
,bar as (
select *
from
(values (6,15,20180301,20180630),(6,27,20180630,99991231))t(team_id, manager_id, date_effective, date_expired)
)
,dist as (
select date_effective, team_id
from foo
union
select date_effective, team_id
from bar
)
select *
from dist d
left join foo f on d.team_id = f.team_id and d.date_effective >= f.date_effective and d.date_effective < f.date_expired
left join bar b on d.team_id = b.team_id and d.date_effective >= b.date_effective and d.date_effective < b.date_expired
order by 1

A: I would attempt the problem by creating a cte for the before range where one of the SCD table has data but the other does not, and an overlapping range, where both tables have data. Similarly, if I had a situation where 1 table stopped recording historical information after a certain time, I would create an after range.
Then taking the union of the before & overlapping ctes, we arrive at the desired output.
WITH foo(employee_id, location_id, team_id, date_effective, date_expired) AS ( VALUES
  (40,1,6,'2018-01-01'::TIMESTAMP,'2019-03-31'::TIMESTAMP),
  (40,2,6,'2019-03-31','9999-12-31')
)
, bar(team_id, manager_id, date_effective, date_expired) AS( VALUES
  (6,15,'2018-03-01'::TIMESTAMP,'2018-06-30'::TIMESTAMP),
  (6,27,'2018-06-30','9999-12-31')
)
, overlapping AS (
SELECT
  team_id
, employee_id
, location_id
, manager_id
, GREATEST(foo.date_effective, bar.date_effective) date_effective
, LEAST(foo.date_expired, bar.date_expired) date_expired
FROM foo JOIN bar USING (team_id)
WHERE tsrange(foo.date_effective, foo.date_expired) && tsrange(bar.date_effective, bar.date_expired)
)
, before AS (
SELECT
  team_id
, employee_id
, location_id
, NULL::INTEGER manager_id
, MIN(foo.date_effective) date_effective
, MIN(bar.date_effective) date_expired
FROM foo
LEFT JOIN bar USING (team_id)
GROUP BY team_id, employee_id, location_id
HAVING NOT EXISTS (SELECT FROM overlapping WHERE overlapping.date_effective = MIN(foo.date_effective) AND overlapping.team_id = foo.team_id)
)
SELECT * FROM before
UNION ALL
SELECT * FROM overlapping
ORDER BY 5

This gives the output:
team_id employee_id location_id manager_id  date_effective  date_expired
      6          40           1       NULL      2018-01-01    2018-03-01
      6          40           1         15      2018-03-01    2018-06-30
      6          40           1         27      2018-06-30    2019-03-31
      6          40           2         27      2019-03-31    9999-12-31


text:
Q: SWIG Use numpy.int64 as int for c++ function I am trying to use SWIG to generate a python wrapper and I am running into an issue where I am unable to use numpy data types with my c++ functions. I have boiled it down to a fairly minimal example:
my_cpp_function.h:
int foo(int x_i, int y_i);

my_cpp_function.cpp:
#include "my_cpp_function.h"

int foo(int bar, int baz){
    return bar + baz;
}

my_cpp_function.i:
%module my_cpp_function

%{
    #include "my_cpp_function.h"
%}

%include "my_cpp_function.h"

Compiled as follows:
$ g++ -std=c++11 -c my_cpp_function.cpp
$ swig -c++ -python my_cpp_function.i
$ g++ -std=c++11 -c -fPIC my_cpp_function_wrap.cxx -I/usr/include/python3.5 -I/usr/lib/python3.5
$ g++ -std=c++11  -shared -Wl,-soname,_my_cpp_function.so -o _my_cpp_function.so my_cpp_function.o my_cpp_function_wrap.o

Then in python3:
>>> from my_cpp_function import foo
>>> foo(1,2)
3
>>> import numpy as np
>>> test = np.array([1,2])
>>> foo(test[0], test[1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: in method 'cost', argument 1 of type 'int'
>>> foo(test[0].item(), test[1].item())
3

So it seems to be unhappy with the numpy.int64. I have seen that there is a numpy.i for using numpy with SWIG but I can't figure out how to use it in this case? Maybe I don't even need it, I'm not sure. Any help would be appreciated!


text:
Q: Azure SQL Database sys.resource_stats :: LAST_VALUE(storage_in_megabytes) I'm creating a query that allows me to dig into the logs of the last 2 weeks of an Azure SQL Server:
DECLARE @StartDate date = DATEADD(day, -30, GETDATE()) -- 7 Days

SELECT DISTINCT
   MAX(database_name) AS DatabaseName
  ,MAX(sku) AS PlatformTier
  ,max(storage_in_megabytes) AS StorageMB
  ,MIN(end_time) AS StartTime
  ,MAX(end_time) AS EndTime
  ,CAST(AVG(avg_cpu_percent) AS decimal(4,2)) AS Avg_CPU
  ,MAX(avg_cpu_percent) AS Max_CPU
  ,(COUNT(database_name) - SUM(CASE WHEN avg_cpu_percent >= 40 THEN 1 ELSE 0 END) * 1.0) / COUNT(database_name) * 100 AS [CPU Fit %]
  ,CAST(AVG(avg_data_io_percent) AS decimal(4,2)) AS Avg_IO
  ,MAX(avg_data_io_percent) AS Max_IO
  ,(COUNT(database_name) - SUM(CASE WHEN avg_data_io_percent >= 40 THEN 1 ELSE 0 END) * 1.0) / COUNT(database_name) * 100 AS [Data IO Fit %]
  ,CAST(AVG(avg_log_write_percent) AS decimal(4,2)) AS Avg_LogWrite
  ,MAX(avg_log_write_percent) AS Max_LogWrite
  ,(COUNT(database_name) - SUM(CASE WHEN avg_log_write_percent >= 40 THEN 1 ELSE 0 END) * 1.0) / COUNT(database_name) * 100 AS [Log Write Fit %]

FROM sys.resource_stats
WHERE start_time > @StartDate
GROUP BY database_name

The problems arrive in the line max(storage_in_megabytes) AS StorageMB because it is taking the Maximum value of the last 2 weeks. That doesn't represent the current database size.
I would like  to use LAST_VALUE but I don't know how to as there is no row_number().
Otherwise some:
SELECT TOP 1 storage_in_megabytes
    ,*
FROM sys.resource_stats
ORDER BY end_time DESC

In the select but that too needs to be aggregated by something.
I'm a bit lost...

A: You can use a correlated TOP 1 subquery to get the current storage size like below. This example also groups by the database attributes that are not aggregated (database_name and sku).
DECLARE @StartDate date = DATEADD(day, -30, GETDATE()) -- 7 Days

SELECT
   database_name AS DatabaseName
  ,sku AS PlatformTier
  ,(SELECT TOP 1 storage_in_megabytes FROM sys.resource_stats AS rs2 WHERE rs2.database_name = rs1.database_name ORDER BY rs2.start_time DESC)  AS StorageMB
  ,MIN(end_time) AS StartTime
  ,MAX(end_time) AS EndTime
  ,CAST(AVG(avg_cpu_percent) AS decimal(4,2)) AS Avg_CPU
  ,MAX(avg_cpu_percent) AS Max_CPU
  ,(COUNT(database_name) - SUM(CASE WHEN avg_cpu_percent >= 40 THEN 1 ELSE 0 END) * 1.0) / COUNT(database_name) * 100 AS [CPU Fit %]
  ,CAST(AVG(avg_data_io_percent) AS decimal(4,2)) AS Avg_IO
  ,MAX(avg_data_io_percent) AS Max_IO
  ,(COUNT(database_name) - SUM(CASE WHEN avg_data_io_percent >= 40 THEN 1 ELSE 0 END) * 1.0) / COUNT(database_name) * 100 AS [Data IO Fit %]
  ,CAST(AVG(avg_log_write_percent) AS decimal(4,2)) AS Avg_LogWrite
  ,MAX(avg_log_write_percent) AS Max_LogWrite
  ,(COUNT(database_name) - SUM(CASE WHEN avg_log_write_percent >= 40 THEN 1 ELSE 0 END) * 1.0) / COUNT(database_name) * 100 AS [Log Write Fit %]

FROM sys.resource_stats AS rs1
WHERE start_time > @StartDate
GROUP BY database_name, sku
ORDER BY database_name, sku;


text:
Q: pyqt: how to put a border frame around a widget I'm making some changes to an existing PyQt project.  The UI was created with Qt Designer.
The relevant part is a QWidget that displays text. I'm trying to put margins around the text. I'd think the simplest way to do this would be to put a border around the QWidget whose background color is the same as the QWidget's background (white).
The QWidget is on a QFrame.  I'd like to put a white border inside the QFrame and around the edge of the QWidget.  The closest I've come is to put short vertical and horizontal spacers around the QWidget, but that displays the underlying grey QFrame. I can't figure out how to make that white. I'd prefer leaving the frame grey and just add a white border around the QWidget.
Any pointers would be be appreciated.
EDIT:
The ui file:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>EbookViewer</class>
 <widget class="QMainWindow" name="EbookViewer">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>920</width>
    <height>774</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>E-book Viewer</string>
  </property>
  <property name="windowIcon">
   <iconset resource="../../../../resources/images.qrc">
    <normaloff>:/images/viewer.png</normaloff>:/images/viewer.png</iconset>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QGridLayout" name="gridLayout_2">
    <item row="0" column="0">
     <widget class="QSplitter" name="splitter">
      <property name="orientation">
       <enum>Qt::Horizontal</enum>
      </property>
      <widget class="QTreeView" name="toc">
       <property name="focusPolicy">
        <enum>Qt::WheelFocus</enum>
       </property>
      </widget>
      <widget class="QFrame" name="frame">
       <property name="frameShape">
        <enum>QFrame::StyledPanel</enum>
       </property>
       <property name="frameShadow">
        <enum>QFrame::Raised</enum>
       </property>
       <layout class="QGridLayout" name="gridLayout">
        <item row="0" column="0" colspan="2">
         <widget class="QWidget" name="view_bg" native="true">
          <property name="sizePolicy">
           <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
            <horstretch>0</horstretch>
            <verstretch>0</verstretch>
           </sizepolicy>
          </property>
          <property name="minimumSize">
           <size>
            <width>0</width>
            <height>0</height>
           </size>
          </property>
          <property name="styleSheet">
           <string notr="true">background:white</string>
          </property>
          <layout class="QGridLayout" name="gridLayout_3">
           <property name="leftMargin">
            <number>200</number>
           </property>
           <property name="topMargin">
            <number>30</number>
           </property>
           <property name="rightMargin">
            <number>200</number>
           </property>
           <property name="bottomMargin">
            <number>30</number>
           </property>
           <item row="0" column="0">
            <widget class="DocumentView" name="view" native="true">
             <property name="minimumSize">
              <size>
               <width>0</width>
               <height>0</height>
              </size>
             </property>
            </widget>
           </item>
          </layout>
         </widget>
        </item>
        <item row="0" column="2">
         <widget class="QScrollBar" name="vertical_scrollbar">
          <property name="orientation">
           <enum>Qt::Vertical</enum>
          </property>
         </widget>
        </item>
        <item row="1" column="1">
         <widget class="QScrollBar" name="horizontal_scrollbar">
          <property name="orientation">
           <enum>Qt::Horizontal</enum>
          </property>
         </widget>
        </item>
        <item row="2" column="1" colspan="2">
         <widget class="QFrame" name="dictionary_box">
          <property name="frameShape">
           <enum>QFrame::StyledPanel</enum>
          </property>
          <property name="frameShadow">
           <enum>QFrame::Raised</enum>
          </property>
          <layout class="QHBoxLayout" name="horizontalLayout">
           <item>
            <widget class="QWebView" name="dictionary_view">
             <property name="minimumSize">
              <size>
               <width>0</width>
               <height>150</height>
              </size>
             </property>
             <property name="url">
              <url>
               <string>about:blank</string>
              </url>
             </property>
            </widget>
           </item>
           <item>
            <widget class="QToolButton" name="close_dictionary_view">
             <property name="toolTip">
              <string>Close dictionary</string>
             </property>
             <property name="text">
              <string>...</string>
             </property>
             <property name="icon">
              <iconset resource="../../../../resources/images.qrc">
               <normaloff>:/images/window-close.png</normaloff>:/images/window-close.png</iconset>
             </property>
            </widget>
           </item>
          </layout>
         </widget>
        </item>
       </layout>
      </widget>
     </widget>
    </item>
   </layout>
  </widget>
  <widget class="QToolBar" name="tool_bar">
   <property name="sizePolicy">
    <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
     <horstretch>0</horstretch>
     <verstretch>0</verstretch>
    </sizepolicy>
   </property>
   <property name="windowTitle">
    <string>toolBar</string>
   </property>
   <property name="movable">
    <bool>true</bool>
   </property>
   <property name="iconSize">
    <size>
     <width>32</width>
     <height>32</height>
    </size>
   </property>
   <property name="floatable">
    <bool>false</bool>
   </property>
   <attribute name="toolBarArea">
    <enum>LeftToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
   <addaction name="action_back"/>
   <addaction name="action_forward"/>
   <addaction name="separator"/>
   <addaction name="action_open_ebook"/>
   <addaction name="action_copy"/>
   <addaction name="action_font_size_larger"/>
   <addaction name="action_font_size_smaller"/>
   <addaction name="action_table_of_contents"/>
   <addaction name="action_full_screen"/>
   <addaction name="separator"/>
   <addaction name="action_previous_page"/>
   <addaction name="action_next_page"/>
   <addaction name="separator"/>
   <addaction name="action_bookmark"/>
   <addaction name="action_reference_mode"/>
   <addaction name="separator"/>
   <addaction name="action_preferences"/>
   <addaction name="action_metadata"/>
   <addaction name="separator"/>
   <addaction name="action_print"/>
  </widget>
  <widget class="QToolBar" name="tool_bar2">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
   <addaction name="action_find_next"/>
   <addaction name="action_find_previous"/>
  </widget>
  <action name="action_back">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/back.png</normaloff>:/images/back.png</iconset>
   </property>
   <property name="text">
    <string>Back</string>
   </property>
  </action>
  <action name="action_forward">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/forward.png</normaloff>:/images/forward.png</iconset>
   </property>
   <property name="text">
    <string>Forward</string>
   </property>
  </action>
  <action name="action_next_page">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/next.png</normaloff>:/images/next.png</iconset>
   </property>
   <property name="text">
    <string>Next page</string>
   </property>
  </action>
  <action name="action_previous_page">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/previous.png</normaloff>:/images/previous.png</iconset>
   </property>
   <property name="text">
    <string>Previous page</string>
   </property>
  </action>
  <action name="action_font_size_larger">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/font_size_larger.png</normaloff>:/images/font_size_larger.png</iconset>
   </property>
   <property name="text">
    <string>Font size larger</string>
   </property>
  </action>
  <action name="action_font_size_smaller">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/font_size_smaller.png</normaloff>:/images/font_size_smaller.png</iconset>
   </property>
   <property name="text">
    <string>Font size smaller</string>
   </property>
  </action>
  <action name="action_table_of_contents">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/chapters.png</normaloff>:/images/chapters.png</iconset>
   </property>
   <property name="text">
    <string>Table of Contents</string>
   </property>
  </action>
  <action name="action_metadata">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/dialog_information.png</normaloff>:/images/dialog_information.png</iconset>
   </property>
   <property name="text">
    <string>Metadata</string>
   </property>
  </action>
  <action name="action_open_ebook">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/document_open.png</normaloff>:/images/document_open.png</iconset>
   </property>
   <property name="text">
    <string>Open ebook</string>
   </property>
  </action>
  <action name="action_find_next">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/arrow-down.png</normaloff>:/images/arrow-down.png</iconset>
   </property>
   <property name="text">
    <string>Find next</string>
   </property>
   <property name="toolTip">
    <string>Find next occurrence</string>
   </property>
   <property name="shortcut">
    <string>F3</string>
   </property>
  </action>
  <action name="action_copy">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/edit-copy.png</normaloff>:/images/edit-copy.png</iconset>
   </property>
   <property name="text">
    <string>Copy to clipboard</string>
   </property>
  </action>
  <action name="action_preferences">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/config.png</normaloff>:/images/config.png</iconset>
   </property>
   <property name="text">
    <string>Preferences</string>
   </property>
  </action>
  <action name="action_reference_mode">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/lookfeel.png</normaloff>:/images/lookfeel.png</iconset>
   </property>
   <property name="text">
    <string>Reference Mode</string>
   </property>
  </action>
  <action name="action_bookmark">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/bookmarks.png</normaloff>:/images/bookmarks.png</iconset>
   </property>
   <property name="text">
    <string>Bookmark</string>
   </property>
  </action>
  <action name="action_full_screen">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/page.png</normaloff>:/images/page.png</iconset>
   </property>
   <property name="text">
    <string>Toggle full screen</string>
   </property>
  </action>
  <action name="action_print">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/print.png</normaloff>:/images/print.png</iconset>
   </property>
   <property name="text">
    <string>Print</string>
   </property>
  </action>
  <action name="action_find_previous">
   <property name="icon">
    <iconset resource="../../../../resources/images.qrc">
     <normaloff>:/images/arrow-up.png</normaloff>:/images/arrow-up.png</iconset>
   </property>
   <property name="text">
    <string>Find previous</string>
   </property>
   <property name="toolTip">
    <string>Find previous occurrence</string>
   </property>
   <property name="shortcut">
    <string>Shift+F3</string>
   </property>
  </action>
 </widget>
 <customwidgets>
  <customwidget>
   <class>QWebView</class>
   <extends>QWidget</extends>
   QtWebKit/QWebView
  </customwidget>
  <customwidget>
   <class>DocumentView</class>
   <extends>QWidget</extends>
   calibre/gui2/viewer/documentview.h
   <container>1</container>
  </customwidget>
 </customwidgets>
 <resources>
  <include location="../../../../resources/images.qrc"/>
 </resources>
 <connections/>
</ui>

A: Put your QWidget inside another QWidget with its background set to the same colour.
You can then use the layout of the parent QWidget to adjust the width of the margin on each side (this can all be done within Qt Designer).
EDIT
Here are the steps to take in Qt Designer to achieve this:

*

*Select the frame widget containing the text widget and break its layout.

*Add a new QWidget to the frame widget (you could name it
"borderWidget").

*Set the background colour of the border widget using the styleSheet
property in the Property Editor: e.g. background-color: white. (nb: it might help if you temporarily set this to a contrasting colour so you can more easily see what's going on).

*Drag and drop the text widget onto the border widget.

*Select the border widget and set it's layout (e.g. "Lay Out in a
Grid").

*Select the frame widget and set it's layout (e.g. "Lay Out in a
Grid").

*Select the border widget. Go to the Layout section in the Property
Editor. There you will see properties like layoutTopMargin,
layoutLeftMargin, etc which can be used to adjust the size of the
border.


text:
Q: can not connect to mongo db using the provided credentials in docker-compose file I have the following docker-compose file:
version: '3.7'
services:
  mongo_db:
    image: mongo:latest
    environment:
       MONGO_INITDB_ROOT_USERNAME: root
       MONGO_INITDB_ROOT_PASSWORD: root
       MONGO_INITDB_DATABASE: shopdata
    ports:
      - 27017:27017
    volumes:
      - mongoData:/data/db

volumes:
  mongoData:
    driver: local

Whenever I try to connect to the database using : mongo -u root -p root, it says authentication failed. I provided the username and password provided in the docker-compose file.
root@5da5f04acd42:/# mongosh "mongodb://172.20.0.2:27017" --username root --authenticationDatabase shopdata
Enter password: ****
Current Mongosh Log ID: 63312c3decdb99f84e6039e4
Connecting to:      mongodb://<credentials>@172.20.0.2:27017/?directConnection=true&authSource=shopdata&appName=mongosh+1.5.0
MongoServerError: Authentication failed.

Is there anything I am missing? I just need to connect using the default username and password passed in the docker-compose.

A: To connect using mongosh, you need to specify authenticationDatabase ( admin for username/password, $external for x509 auth). You will be prompt for password.
mongosh "mongodb://127.0.0.1:27017" --username root --authenticationDatabase admin

To connect to a MongoDB instance requires authentication, use the --username and --authenticationDatabase command-line options. mongosh prompts you for a password, which it masks as you type. - https://www.mongodb.com/docs/mongodb-shell/connect/


text:
Q: OpenEdge 4GL REST Service : computing temp table values creating errors I have a progress 4gl rest webservice. The Create method accepts a dataset from which I extract its underlying temp table
METHOD PUBLIC VOID Createprices(INPUT-OUTPUT DATASET dsprices):
        DEFINE VARIABLE hT AS HANDLE.
        ht = DATASET dsprices:GET-BUFFER-HANDLE(TEMP-TABLE ttprices:NAME).
        ht = ht:DEFAULT-BUFFER-HANDLE.
        PreTransactionValidate(INPUT-OUTPUT TABLE-HANDLE ht).

I then pass the temp-table buffer to another method (pretransactionvalidate) where I compute the values for a couple of fields.
The PretransactionValidate method with dummy values being assigned -
METHOD  PUBLIC VOID PreTransactionValidate( INPUT-OUTPUT table-handle ttprices):
FOR EACH ttprices:
ASSIGN
            ttprices.PricesId  = NEXT-VALUE(SeqPricesId)
            ttprices.AddedDate = TODAY
            ttprices.AddedTime = TIME.
END.

Calling the PretransactionValidate method causes my Create Method to fail. If I comment out the call, I can successfully create a record. I'm a Progress newbie and can't find much material on the net, so any help would be worth trying.
Cheers

A: In your Createprices method, ht is assigned to the handle of a buffer, but your procedure PreTransactionValidate expects a dataset handle.
As both methods are in the same compile unit (class), it's not required to pass the temp-table as a parameter anyway. Temp-tables are (unfortunately) always class-global in the ABL.
If both methods would be in different compile units, you could pass the temp-table directly:
<some_object_reference>:PreTransactionValidate (INPUT-OUTPUT TABLE ttprices).


text:
Q: Next JS You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file i have this bug with Next JS
    ./node_modules/react-player/es6/ReactPlayer.jsx
Module parse failed: Unexpected token (140:8)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|       const { light, playIcon, previewTabIndex, oEmbedUrl } = this.props
|       return (
>         <Preview
|           url={url}
|           light={light}

Thank You