text:
Q: Android Shared Preferences inside Fragment not working - Kotlin I have spent hours researching and trying to find a solution but in vein. So here comes my first question on stackoverflow. For years I could do without having to ask my own questions because of the vast amount of topics.
Please be kind to me if I do something wrong. I will do my best to enhance in asking questions.
My problem is, that it won't store nor read data from the preferences. It says that they don't exist. I took the sample code from google for the preference screen. Inside there are many fragments. Inside one of those fragments I catch a preference click and want to change a value of one of the other preferences with it.
Following you find my code.
The problem in my opinion lies in the onPreferenceTreeClick of the AlveolPreferencesFragment.
Thanks for all your help and all the help you have given me before not knowing that you did :))
Alveol_Preferences XML

<androidx.preference.PreferenceScreen
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <PreferenceCategory
        app:title="@string/heart_alveol">

        <EditTextPreference
            app:key="latitude"
            app:dialogTitle="@string/latitude_summary"
            app:useSimpleSummaryProvider="true"
            app:title="@string/latitude"
            app:defaultValue="-34.0"/>

        <EditTextPreference
            app:key="longitude"
            app:dialogTitle="@string/longitude_summary"
            app:useSimpleSummaryProvider="true"
            app:title="@string/longitude"
            app:defaultValue="151.0"/>

        <Preference
            app:key="gpsheart"
            app:title="@string/gpsheart"
            app:summary="@string/gpsheart_summary"/>
    </PreferenceCategory>

</androidx.preference.PreferenceScreen>

Class AlveolPreferencesFragment
class AlveolPreferencesFragment : PreferenceFragmentCompat() {

        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {

            setPreferencesFromResource(R.xml.alveol_preferences, rootKey)
        }
        override fun onPreferenceTreeClick(preference: Preference): Boolean {

            return when (preference.key) {
                "gpsheart" -> {

                    var sharedPref : SharedPreferences? = activity?.getPreferences(Context.MODE_PRIVATE)
                    val editor = sharedPref?.edit()
                    editor?.putString("latitude", "Test").apply()

                    val text = sharedPref?.getString("longitude","Longitude doesn't exist")
                    val duration = Toast.LENGTH_SHORT

                    val toast = Toast.makeText(context, text, duration)
                    toast.show()

                    true
                }
                else -> {
                    super.onPreferenceTreeClick(preference)
                }
            }

        }

The AlveolPreferencesFragment class lies inside this
class SettingsActivity : AppCompatActivity()
This was preconfigured by google and I have the assumption this is kind of complicated. But I don't know maybe I'm wrong.
Additional Question
This question comes on top if you want to also help me here.
Inside the OnPreferenceTreeClick I want to get the last known location.
This already works from my code. The only problem is, that I can't seem to put the fusedLocationClient inside the class.
It won't work there.
Because inside this call:
 fusedLocationClient = LocationServices.getFusedLocationProviderClient(activity)

activity returns FragmentActivity?But it needs Activity.
So how can I get my SettingsActivity inside of this FragmentActivity?
Maybe something with companion object?
I have no clue.
Thanks for the help.

A: After some days of searching I finally found the answer myself.
I will post it here, if someone has the same problem.
In Germany we have a saying "Der Teufel steckt im Detail" ;)
Which translates roughly to "The devil is in the details"
Instead of calling this function:
var sharedPref : SharedPreferences? = Activity?.getPreferences(Context.MODE_PRIVATE)

We need to call this function
val sharedPref = PreferenceManager.getDefaultSharedPreferences(context)

Then the rest works.

A: As an update in May 2021, PreferenceManager.getDefaultSharedPreferences appears to have been deprecated.
The Kotlin code below will work and was tested in a Dialogue Fragment:
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)
sharedPref?.edit()?.putInt(YOUR_SHARED_PREF_STRING_INDEX_VALUE, yourValueToStore)

A: create an instance in the fragment like this:

protected val defaultPreferences: SharedPreferences
        get() = PreferenceManager.getDefaultSharedPreferences(activity)

Set value in default shared preferences

defaultPreferences.edit {
            putBoolean("clone_active", false)
        }

get value of default shared preference:

val sharedPrefBooleanFromDefaultPref = defaultPreferences.getBoolean("clone_active", false)


text:
Q: How can I sort values by descending I have a csv file with hosts' ids and ips like this inside
                  Ip    Id1    Id2  Id3  Id4
0         10.10.8.30  18156  10782  NaN  NaN
1       10.10.12.113  10398  18177  NaN  NaN
2        10.10.6.111  10496  18140  NaN  NaN
3         10.10.6.97  18093  10870  NaN  NaN
4         10.10.6.63  10848  18965  NaN  NaN

I whant to sort values (Id1, Id2, Id3, Id4) by descending using pandas, for ex. that's become
                  Ip    Id1    Id2  Id3  Id4
0         10.10.8.30  10782  18156  NaN  NaN
1       10.10.12.113  10398  18177  NaN  NaN
2        10.10.6.111  10496  18140  NaN  NaN
3         10.10.6.97  10870  18093  NaN  NaN
4         10.10.6.63  10848  18965  NaN  NaN

Can anybody help me?

A: If you are using Pandas then this would help Pandas Dataframe Sort

A: Can you please try this :
from pandas import DataFrame

df = DataFrame(data)
sorted = df.sort(['Id1', 'Id2', 'Id3', 'Id4'], ascending=[0])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using Blueprint CSS, how do we style 3 columns, each 300px wide, with 15px margins or paddings in between? The width of the content-area is 960px, with 3 columns, each 300px, so total 900px, and with padding / margin of 15px between columns, which is total 30px,
and finally, to the left of 1st column there should be 15px padding / margin, and to the right of the 3rd column, the same.  So total is also 30px.
900px + 30px + 30px will be 960px.
How to do that in Blueprint / CSS?   This can be done using simple CSS, but the coding standard requires using Blueprint CSS.

A: You can override Blueprint classes, see here:
http://jsfiddle.net/JeaffreyGilbert/aznVd/
I assume you're using Blueprint's grid.css.


text:
Q: Get the number of users in my website - asp.net how can I get how many people registered to my website?
in ASP.NET

A: You're not going to get much better then incrementing in Session_Start and decrementing in Session_End unless you use some other means such as  a database.
When you are authenticating your requests you could update a timestamp in the database to show that the user has been active, and after a given time (say 10-15 minutes), the query thatcollects the number of current users ignores that row in the database (thus decrementing the count).


text:
Q: Required Field Validator with Safari 5.1 I'm using a Required Field Validator (code below) with a Radio Button List within a Wizard to ensure the user selects a value before proceeding to the next step of the wizard. This is working fine with all browsers except for Safari. Even when the user has selected a value from the Radio Button List the Validation Error Message is being shown and not allowing the user to proceed. I cannot figure out why this might be and why it might only be for Safari.
Any suggestions
            <asp:WizardStep ID="WizardStep2" runat="server" Title="Step 2">
            Below are the results of your search, select a publication to continue or search again.

                    <asp:RadioButtonList ID="rbl_publication" runat="server">
                    </asp:RadioButtonList>
            <asp:RequiredFieldValidator ID="pub_list_valid" runat="server"
                ControlToValidate="rbl_publication"
                ErrorMessage="** Please select a publication">** Please select a publication</asp:RequiredFieldValidator>

            <asp:Label ID="lbl_publications_no_data" runat="server"
                style="font-weight: 700"
                Text="Sorry...No publications are available for the selected criteria, please try again."
                Visible="False"></asp:Label>

        </asp:WizardStep>

A: I've tested on safari 5.0.5 and 5.1 (windows) and it works as expected. I'm going to guess that your issue is data related. Are you html encoding the publication titles? If not, then you probably should be.
Hope this helps


text:
Q: Proving that $(\forall\epsilon>0)(\exists n,k\in\mathbb{N})(|\frac{n}{k}-\pi|<\frac{\epsilon}{k})$ Do you have an elementary proof for:
$$(\forall\epsilon>0)(\exists n,k\in\mathbb{N})(|\frac{n}{k}-\pi|<\frac{\epsilon}{k})$$

what is the largest $\delta>1$ such that:
$$(\forall\epsilon>0)(\exists n,k\in\mathbb{N})(|\frac{n}{k}-\pi|<\frac{\epsilon}{k^\delta})$$

A: I have a proof for the first one. Note that $\forall \epsilon>0\,\exists n\in\mathbb{N}\,\exists k\in \mathbb{Z}^+\,\left[\left|\frac{n}{k}-\pi\right|<\frac{\epsilon}{k}\right]$ is equivalent to:
 $$\forall \epsilon>0\,\exists n\in\mathbb{N}\,\exists k\in \mathbb{Z}^+\,[\left|n-k\pi\right|<\epsilon]$$
Let $\epsilon>0$. Let $10^{-r}<\epsilon $ for some $r\in\mathbb{N}$. Now consider the set of numbers $\{k\pi \mid k\in\mathbb{Z}\}$. By the pigeonhole principle, we know that there exist distinct $i,j\in\mathbb{N}$ $(i>j)$ such that $i\pi,j\pi$ have the same first $r$ digits that are on the right of the decimal point. Therefore, $|(i-j)\pi-\lfloor(i-j)\pi\rfloor|<10^{-r}<\epsilon$. Let $n=\lfloor(i-j)\pi)\rfloor$, $k=i-j$  and we get the desired result.

A: For the second question see mathworld


text:
Q: Centering an image with HTML I want to center image with HTML.  I have my image but am not sure how to do it?  I appreciate help.  THANKS.
Here's my code:

A: With the onset of HTML5, you should look to use CSS for image centering.  HTMl5 actually depreciated the align tag.
Try the following CSS code instead:

A: super easy - simply wrap it in a container and give the left and right margins auto width
see:
http://jsfiddle.net/Vc3rY/1/
.container {width: 300px; background: #f2f2f2; margin: 0 auto}

A: An image is an inline-boxe, so text-align:center; on parent should be the basic way to do it.
If you display:block, your image , then it will be margin:auto; and it will be the only one thing on that line ... if no floatting elements ahead in the flow.
(always nice to understand how it worksfrom 101 CSS rules :) )

A:
--YOUR IMAGE INFO--
< /center
Note that this will center you image horizontally to the middle of the page.
If you want to center it vertically or align it to the text you will have to use a different method.


text:
Q: Get attribute from model of selected option I have an employee dropdown that lists all the employees. I want to be able to select an employee and get the address of the employee from the model so that I may display it. the following is the code of my collection_select.
<div class="form-group col-md-2 field">
<%= form.label :employee_id %>
<%= form.collection_select :employee_id, Employee.all, :id, :full_name,{:prompt=>"Select Employee"},{:id=>"emp_select",class:"form-control",:onchange=>"getEmployee();"} %>
</div>

Next is the code I am using to grab the value of the employee that was selected and it does work.
function getEmployee() {
    var selectedVal=$('#emp_select option:selected').val();}

From here what do I do to get the address of the employee that was selected?

A: You will have to retrieve the employee's address via ajax call. Here are the steps:

*

*Define an action in your rails app to return employee's address by json.

*Make an ajax request to that action and get the info needed.

*Render result into view.

For more information, take a look at this link:
https://guides.rubyonrails.org/working_with_javascript_in_rails.html
routes.rb
controller :ajax do
  get 'ajax/get_employee_address/:employee_id', action: :get_employee_address, as: :get_employee_address
end

ajax_controller.rb
class AjaxController < ActionController::Base
  def get_employee_address
    employee = Employee.find(params[:employee_id])

    render json: employee.address.to_json
  rescue ActiveRecord::RecordNotFound
    render json: 'Employee not found', status: 422
  end
end

Your js code
function getEmployee() {
  var selectedVal=$('#emp_select option:selected').val();
  $.ajax({
    url: '/ajax/get_employee_address/' + selectedVal,
    success: function (address) {
      // Render your address to view
    },
    error: function () {
      // Handle error here or just return nothing
      return null;
    }
  })
}

Note: This ajax endpoint will expose your employee address to outside so be sure to make authentication to prevent leaking info.

A: Add address to option data-attribute:
<%= form.select :employee_id,
  options_for_select(Employee.all.map {
    |e| [e. full_name, e.id, { 'data-address' => e.address  }]
  }),
  { prompt: "Select Employee" },
  { id: "emp_select", class: "form-control", onchange: "getEmployee();" } %>

On change get it with js:
function getEmployee() {
  var selectedVal=$('#emp_select option:selected').data("address");}

And insert it to needed place


text:
Q: How can I open several empty lists at once in R? I'm running a very long for loop with many variables and functions, and need to save the results in lists. Therefore, I want to prepare empty lists before hand.
I can do it like this, but it's ugly and makes me uncomfortable:
df = list()
EV = list()
var = list()
design = list()
contrast = list()
d = list()

Is there a better way? thanks.


text:
Q: Fabric doesn't show latest iPhone App build by Xcode(6.4) My coworker set up the Xcode+Fabric environment before he left, and we have several old build shown in Fabric, which we were able to distribute to team members.
Now I did a new build (say build 21) within Xcode and I'm able to run with iPhone simulator and it indeed shows build 21 there. But when I open fabric from the menu bar I still only see the old build 20.
Is there an additional step I need to do to make build 21 show up within Fabric thus we can distribute this new version?
Many Thanks in advance.


text:
Q: React can't read property. Is it wrong binding? I am trying to build an order list/form with React.
But, after clicking one of products an error occurs:

Cannot read property 'price' of undefined

  13 | totalSum() {
  14 |  this.setState({
> 15 |      total: this.state.total + this.product.price
  16 |  })
  17 | }

Is it wrong binding in constructor ? If yes, could you explain me why?
My code:
import React, { Component } from 'react';
import Summary from './summary';

class ShoppingCard extends Component {
    constructor(props) {
        super(props);
        this.state = {
            total: 0
        }
        this.totalSum = this.totalSum.bind(this);
    }

    totalSum() {
        this.setState = {
            total: this.state.total + this.product.price
        }
    }

  render() {
    return (

        {
            products.map((product) => {
                return (

{product.name} {product.price}$

                );
            })
        }

    );
  }
}

var products = [
    {
        name: "Product 1",
        price: 250
    },
    {
        name: "Product 2",
        price: 70
    },
    {
        name: "Product 3",
        price: 140
    },
    {
        name: "Product 4",
        price: 640
    },
    {
        name: "Product 5",
        proce: 290
    },
]
export default ShoppingCard;

A: setState is a function and not a variable to which you assign a value
Also this.product is not defined in your code, you need to pass the price to totalSum function from the map function like
 totalSum(price) {
    this.setState({
        total: this.state.total + price
    })
 }

render function:

    {
        products.map((product) => {
            return (

{product.name} {product.price}$

            );
        })
    }

P.S. Also I don't see products defined in your map function, I suppose you have defined it before using it.


text:
Q: Asp.net Compressing pages problem I have some pages in my web application that use Ms Ajax (update panel,script manager,...).when I want to add compressing module for my application I get this error :
ASP.NET Ajax client-side framework failed to load.

I searched in the internet and found that compressing has conflict with ms ajax.
Is there any way to solve that?  If I use IIS 7.x can I use compressing with that pages?
thanks

A: You can disable compression by folder or mime type in IIS 7.  To disable compression for a single folder, browser to that folder in IIS, click Compression in the right pane and uncheck the checkmarks for Compress Static Content and Compress Dynamic Content.
This answer will show you how to enable/disable mime types at the server level if you wish to go that route.


text:
Q: failed to installing package webrtcvad in ubuntu Using pip 22.0.4 to install webrtcvad fails with
pip3 install webrtcvad

output:
Collecting webrtcvad
  Using cached webrtcvad-2.0.10.tar.gz (66 kB)
  Preparing metadata (setup.py) ... done
Building wheels for collected packages: webrtcvad
  Building wheel for webrtcvad (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [20 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build/lib.linux-x86_64-3.7
      copying webrtcvad.py -> build/lib.linux-x86_64-3.7
      running build_ext
      building '_webrtcvad' extension
      creating build/temp.linux-x86_64-3.7
      creating build/temp.linux-x86_64-3.7/cbits
      creating build/temp.linux-x86_64-3.7/cbits/webrtc
      creating build/temp.linux-x86_64-3.7/cbits/webrtc/common_audio
      creating build/temp.linux-x86_64-3.7/cbits/webrtc/common_audio/signal_processing
      creating build/temp.linux-x86_64-3.7/cbits/webrtc/common_audio/vad
      x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -DWEBRTC_POSIX -Icbits -I/media/botika/DATA-2/Dhea/dhea_env/include -I/usr/include/python3.7m -c cbits/pywebrtcvad.c -o build/temp.linux-x86_64-3.7/cbits/pywebrtcvad.o
      cbits/pywebrtcvad.c:1:10: fatal error: Python.h: No such file or directory
       #include <Python.h>
                ^~~~~~~~~~
      compilation terminated.
      error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for webrtcvad
  Running setup.py clean for webrtcvad
Failed to build webrtcvad
Installing collected packages: webrtcvad
  Running setup.py install for webrtcvad ... error
  error: subprocess-exited-with-error

  × Running setup.py install for webrtcvad did not run successfully.
  │ exit code: 1
  ╰─> [20 lines of output]
      running install
      running build
      running build_py
      creating build
      creating build/lib.linux-x86_64-3.7
      copying webrtcvad.py -> build/lib.linux-x86_64-3.7
      running build_ext
      building '_webrtcvad' extension
      creating build/temp.linux-x86_64-3.7
      creating build/temp.linux-x86_64-3.7/cbits
      creating build/temp.linux-x86_64-3.7/cbits/webrtc
      creating build/temp.linux-x86_64-3.7/cbits/webrtc/common_audio
      creating build/temp.linux-x86_64-3.7/cbits/webrtc/common_audio/signal_processing
      creating build/temp.linux-x86_64-3.7/cbits/webrtc/common_audio/vad
      x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -DWEBRTC_POSIX -Icbits -I/media/botika/DATA-2/Dhea/dhea_env/include -I/usr/include/python3.7m -c cbits/pywebrtcvad.c -o build/temp.linux-x86_64-3.7/cbits/pywebrtcvad.o
      cbits/pywebrtcvad.c:1:10: fatal error: Python.h: No such file or directory
       #include <Python.h>
                ^~~~~~~~~~
      compilation terminated.
      error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> webrtcvad

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.

A: You are missing the Python headers. You can install them with this command:
#Replace the 3.10 in the below command with your Python version before running.
sudo apt-get install python3.10-dev libpython3.10-dev


text:
Q: When does URL to .csv open or download file? I'm learning some Python pandas and the course uses https://gist.githubusercontent.com/sh7ata/e075ff35b51ebb0d2d577fbe1d19ebc9/raw/b966d02c7c26bcca60703acb1390e938a65a35cb/drinks.csv
Clicking this link opens the actual .csv file contents in my browser and I can read the data into pandas straight away.
However, this doesn't work for https://www.spss-tutorials.com/downloads/browsers.csv. If I click this link, Google Chrome downloads the file rather than show its contents.
Why is this and what can I do about it? I mean, they're both URLs for .csv files, right?

A: You can use requests module with custom HTTP header to download it. For example:
import requests
import pandas as pd
from io import StringIO

url = "https://www.spss-tutorials.com/downloads/browsers.csv"
headers = {
    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:99.0) Gecko/20100101 Firefox/99.0"
}

req = requests.get(url, headers=headers)
df = pd.read_csv(StringIO(req.text))

print(df.to_markdown())

Prints:

screen_resolution
sessions
perc_new_sessions
new_users
bounce_rate
pages_session
avg_session_duration
goal_conversion_rate
goal_completions
goal_value

0
1366x768
2,284
79.60%
1,818
69.40%
1.93
00:02:14
0.00%
0
€0.00

1
1920x1080
2,013
72.28%
1,455
71.93%
2.02
00:02:18
0.00%
0
€0.00

2
1280x1024
1,217
72.14%
878
74.53%
1.9
00:02:05
0.00%
0
€0.00

3
1680x1050
1,052
68.16%
717
74.62%
1.93
00:01:46
0.00%
0
€0.00

4
1440x900
921
77.85%
717
74.05%
1.73
00:01:45
0.00%
0
€0.00

5
1280x800
865
80.00%
692
71.91%
1.76
00:01:37
0.00%
0
€0.00

6
1600x900
737
76.39%
563
72.86%
1.8
00:02:02
0.00%
0
€0.00

7
1920x1200
441
64.85%
286
73.92%
1.87
00:01:55
0.00%
0
€0.00

8
1024x768
192
88.02%
169
73.96%
2.07
00:01:32
0.00%
0
€0.00

9
2560x1440
137
67.15%
92
61.31%
1.86
00:02:02
0.00%
0
€0.00

10
1280x720
134
82.84%
111
66.42%
2.16
00:01:15
0.00%
0
€0.00

11
1536x864
118
78.81%
93
72.03%
1.78
00:01:45
0.00%
0
€0.00

12
320x568
104
84.62%
88
75.00%
1.89
00:01:18
0.00%
0
€0.00

13
768x1024
91
83.52%
76
67.03%
2.66
00:02:11
0.00%
0
€0.00

14
1360x768
70
77.14%
54
74.29%
1.69
00:01:08
0.00%
0
€0.00

15
360x640
70
71.43%
50
77.14%
2.06
00:02:06
0.00%
0
€0.00

16
1600x1200
62
80.65%
50
82.26%
1.32
00:01:22
0.00%
0
€0.00

17
1344x840
56
44.64%
25
53.57%
3.11
00:04:39
0.00%
0
€0.00

18
320x480
51
80.39%
41
72.55%
1.61
00:00:55
0.00%
0
€0.00

19
1093x614
41
80.49%
33
78.05%
1.76
00:01:42
0.00%
0
€0.00

20
1280x768
38
60.53%
23
68.42%
2.63
00:02:41
0.00%
0
€0.00

21
1024x600
35
94.29%
33
85.71%
1.37
00:01:23
0.00%
0
€0.00

...and so on


text:
Q: Making a text area that can be printed to from another class I'm trying to use my program's output text area UI element to print progress and updates for my program rather than using the console output inside of Eclipse. Is a way I could say:
System.out.println(string);

but instead of printing to the console, print to my own text area on the UI. My code looks a little something like this (I've removed my other panel elements to focus more on this):
This is my MainPanel class, where I make the element I want to print to:
public class MainPanel extends JPanel{

    private JTextArea consoleOutput;
    private JButton submitButton;

    public MainPanel(){

        setLayout(null);
        Border border = BorderFactory.createLineBorder(Color.LIGHT_GRAY);
        Font f1 = new Font("Arial", Font.PLAIN, 14);

        consoleOutput = new JTextArea();
        consoleOutput.setBounds(199, 122, 375 , 210);
        consoleOutput.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(3, 4, 0, 0)));
        consoleOutput.setEditable(false);
        consoleOutput.setFont(f1);

        submitButton = new JButton("Get Cards");
        submitButton.setBounds(35, 285, 107, 49);
        submitButton.setFont(f2);

        submitButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            String username = "HenryJeff";
            String password = "Password";
            Cards cards = new Cards();
            cards.openTabs(username,password);
            }
        });
        add(consoleOutput);
        add(submitButton);
        }
}

This is my Cards class:
public class Cards{

    public void openTabs(String username, String password){
         System.out.println(username + ", " + password);
    }

How can I replace the System.out.println(); to print to my text area? I've tried making my Cards class extend my JPanel and have the console text area be made and created in there, and then adding a write to method that writes to the text area but it didn't work. Any help is appreciated!

A: In your MainPanel class
cards.openTabs(username,password,this);

and specify your consoleOutput as non private some default.
Change your Cards class
public class Cards{

public void openTabs(String username, String password, MainPanel panel){
panel.consoleOutput.setText(username + ", " + password);
//now both user name and password will be displayed in text area of MainPanel class.
}

A: You can do that, by creating a bridge between the Document of a JTextArea and a Writer:
public class PlainDocumentWriter extends PlainDocument implements Writer {
    public Writer append(char c) {
        // Note: is thread-safe. can share between threads.
        insertString(getLength(), Char.toString(c), new SimpleAttributeSet());
    }

    public Writer append(CharSequence csq) {
        insertString(getLength(), csq.toString(), new SimpleAttributeSet());
    }

    // etc.
}

Then:
PlainDocumentWriter w = new PlainDocumentWriter();
consoleOutput = new JTextArea(w);
PrintWriter pw = new PrintWriter(w);

And then:
pw.println(username + ", " + password);

Now, anything you write to the PrintWriter will show up in the text area.


text:
Q: Linear recurrence solution to Diophantine equation I have a Diophantine equation of the form:
$$ax^2 + bx + c = y^2, \quad x, y \in \mathbb{Z^+}$$
Is it true that there will always be a linear recurrence formula that generates all the solutions for $x$, of the form:
$$x_n = \alpha_1x_{n-1} + \alpha_2x_{n-2} + \alpha_3,$$
for some constants $\alpha_1, \alpha_2, \alpha_3 \in \mathbb{Z^+}$ (where plugging integers into $n$ generates the next $x$ that solves the Diophantine equation)?
If so, is it possible to prove this?
And if so, is it possible to show how these constants $\alpha_1, \alpha_2, \alpha_3$ are found?

A: I'm afraid this is overly optimistic. Multiplying through by $4a$ and completing the square, you go get a Pell type equation with some constant, and no more $b.$ The real problem is class number. The automorphism group of the Pell quadratic form is well behaved. However, there may be several seed values (pairs) rather than just two, and the rcurrence you describe takes you from one, well, fundamental region (cycle in Conway's topograph 'river') to the next.  Read the first chapter in his Sensual Quadratic Form book and ask him about it.
I drew several topograph pictures for MSE answers, two are at Generate solutions of Quadratic Diophantine Equation . I drew on graph paper so the river is a perfectly straight line. That's life.

A: For a private quadratic form:
$Y^2=aX^2+bX+1$
Using solutions of Pell's equation:  $p^2-as^2=1$
Solutions can be expressed through them is quite simple.
$Y=p^2+bps+as^2$
$X=2ps+bs^2$
$p,s$ - can be any character.

A: Though it is necessary to bring the decisions some pretty simple solutions:
the equation:  $aX^2+bXY+cY^2=f$
If the root of the whole:  $\sqrt{\frac{f}{a+b+c}}$
Then use the solution of Pell's equation:  $p^2-(b^2-4ac)s^2=1$
Solutions can be written:
$Y=((4a+2b)ps\pm(p^2+(b^2-4ac)s^2))\sqrt{\frac{f}{a+b+c}}$
$X=(-(4c+2b)ps\pm(p^2+(b^2-4ac)s^2))\sqrt{\frac{f}{a+b+c}}$
If a root: $\sqrt{fa}$
then the solutions are of the form:
$Y=4ps\sqrt{fa}$
$X=(-2bps\pm(p^2+(b^2-4ac)s^2))\sqrt{\frac{f}{a}}$
Although it should be mentioned, and the equation: $aX^2-qY^2=f$
If the root of the whole: $\sqrt{\frac{f}{a-q}}$
Using equation Pell:  $p^2-aqs^2=1$  solutions can be written:
$Y=(2aps\pm(p^2+aqs^2))\sqrt{\frac{f}{a-q}}$
$X=(2qps\pm(p^2+aqs^2))\sqrt{\frac{f}{a-q}}$
And for that decision have to find double formula.
$Y_2=Y+2as(qsY-pX)$
$X_2=X+2p(qsY-pX)$


text:
Q: How to scroll up and down and swipe using real android devices? Appium version 1.7.1 I'm a newbie in automation and I dont know scripting either, but I'm trying to learn automation and we are using java script. I'm trying to scroll the page up and down for the EULA terms, could someone help me? I'm using appium version 1.7.1.
Could also someone recommend a tutorial using android studio and not eclipse.
Thanks,
me.

A: You can perform scroll / swipe up action with below code:
Dimension size = this.driver.manage ()
    .window ()
    .getSize ();
int startX = size.getWidth () / 2;
int startY = size.getHeight () / 2;
int endX = 0;
int endY = (int) (startY * -1 * 0.5);
TouchAction action = new TouchAction (this.driver);
action.press (startX, startY)
    .moveTo (endX, endY)
    .release ()
    .perform ();

You can tweak the code to perform left, down and right swipe.
As for the tutorial you are looking for, it's not easy to find a good resource. But to help you with Mobile Automation, I've created an open source framework, coteafs-appium which you can easily use to Automate the tests. It uses Appium internally. To understand how to use it, see it's wiki on it's GitHub page.


text:
Q: push changes from pip installed git repo I have a conda environment on a new machine, and a github repo set up which is pip installable. It looks something like this
library_distro
  |
  |->_pycache_
  |
  |->library_name
  |   |
  |   |->modules and stuff...
  |
  |->.giignore
  |
  |->__init__.py
  |
  |->requirements.txt
  |
  |->setup.py

my question is, is there a way to set up a distribution so that it's pip installable, and also if I make modifications to the pip installed library I can push those changes? Right now I have a clone and a pip install. Every time I want to make a change I modify the clone, push the changes, and reinstall the library via pip. I feel like there has to be a cleaner way.

A: phd was right, editable installs are perfect.
In summary, instead of the usual pip install process, an editable install creates a symbolic link to a specific library somewhere on your machine. If you git clone a distribution which is pip installable, you can easily link it to a python via the following command:
pip install -e path/to/SomeProject
naturally, if you modify this command to include the path for pip a specific conda environment, you will have successfully pip installed a cloned repo.
.../envName/bin/pip install -e path/to/SomeProject


text:
Q: How do I get a full stack trace instead of "Unexpected error while processing request" in Rails test environment? When starting my rails server in test environment (rails s -e test), something is rescuing exceptions and outputs instead "Unexpected error while processing request: ...error here...". I get the backtrace in development mode.
Who is it, and how can I disable that? I need the full backtrace, not just the error that was raised!
I'm using Rails 3.2.3, Ruby 1.9.3, rspec, capybara, capybara-webkit

A: Setting config.action_dispatch.show_exceptions = true in test.rb did the trick for me.

A: Read env.rb created by Cucumber:
# By default, any exception happening in your Rails application will bubble up
# to Cucumber so that your scenario will fail. This is a different from how
# your application behaves in the production environment, where an error page will
# be rendered instead.
...
# 1) Tag your scenario (or feature) with @allow-rescue
# 2) Set the value below to true. Beware that doing this globally is not
# recommended as it will mask a lot of errors for you!

Summary:
@allow-rescue
Feature: blah blah blah

Will make the trick.


text:
Q: Why does the computation make sense? An example using Kronecker's Theorem

Just wondering why $\alpha^2+1=0$ in this computation?
I also would like to know what $\langle x^2+1 \rangle$ actually is in the image of the above example. Is it the principal ideal generated by $x^2+1$? ie $x^2+1$ added n times such that n is in $\mathbb{R}$?
Finally why is $(x^2+1)+ \langle x^2+1 \rangle$ zero?

A: I would recommend you to re-read your definitions because your question is about what an ideal presentation and a quotient ring are. Anyway, since you're asking, I will answer you in a general fashion.
First of all, $\langle f(x)\rangle\subseteq k[x]$ is the set of all polynomials of the form $g(x)f(x)$ with $g(x)\in k[x]$, equipped with the usual operations of the polynomial ring (you can think it as the multiples of the polinomial $f(x)$).
Second, the quotient ring $k[x]/\langle f(x)\rangle$ is the quotient induced by the equivalence relation "$g(x)\sim h(x)$ if and only if $g(x)-h(x)\in \langle f(x)\rangle$". Clearly, the equivalence class of $f(x)$ equals the equivalence class of $0$, since $f(x)-0=f(x)=1\cdot f(x)\in \langle f(x)\rangle $.

A: The zero element in the quotient ring $\mathbb{R}[x]/\langle x^2+1\rangle$ is  $0+\langle x^2+1\rangle=\langle x^2+1\rangle$, which the author simply writes as $0$. Now, for any polynomials $f,g\in \mathbb{R}[x]$, we have
$$
f+\langle x^2+1\rangle = g + \langle x^2+1\rangle \iff f-g\in\langle x^2+1\rangle
$$
Since $x^2+1=(x^2+1)-0\in \langle x^2+1\rangle$, we deduce that $x^2+1+\langle x^2+1\rangle=0+\langle x^2+1\rangle$.

A: Back-to-front...
$x^2+1 \in \langle x^2 + 1 \rangle$, so $(x^2 + 1) + \langle x^2 + 1 \rangle = \langle x^2 + 1 \rangle$, which is sent to zero in the quotient $\mathbb{R}[x]/\langle x^2 + 1 \rangle$.
$\langle x^2 + 1 \rangle$ is the ideal generated by $x^2 + 1$ in the ring $\mathbb{R}[x]$.  Since it is singly generated, it is a principal ideal.  Since the degree of $x^2 + 1$ is $2$, all polynomials of degree $2$ or greater in $\mathbb{R}[x]$ are reduced to linear or constant representatives of equivalence classes in $\mathbb{R}[x]/\langle x^2 + 1 \rangle$.
The second display in the yellow box shows that $\alpha^2 + 1 \cong 0 \pmod{\langle x^2 + 1 \rangle}$ in $\mathbb{R}[x]/\langle x^2 + 1 \rangle$.


text:
Q: ElasticSearch Multiple Data Directories, choose where to place the index I'm running ElasticSearch over multiple servers. All servers are equal, all have 2 disks: one SSD, and one HDD. Needless to say, the SSD is faster yet smaller.
I know you can set multiple data directories in ES by added the paths to elasticsearch.yml. But, by default, (from what I've found) ES automatically chooses which data directory to take based on the percentage of disk space available.
Some indices are more important to me than others, say newer ones (those that get queried a lot) need to be on the SSD, and those that will be queried less can be on HDD.
What do I need to do to get this done - if possible at this time?
Add index to path?

A: This is not possible in Elasticsearch. Yes, you can specify multiple data paths, but those cannot be "assigned" to indices.
At the moment, ES will stripe the data on a file level to all the data paths, this means shards will be spread over all the paths:

Path to directory where to store index data allocated for this node.
path.data: /path/to/data
Can optionally include more than one location, causing data to be striped across
  the locations (a la RAID 0) on a file level, favouring locations with most free
   space on creation. For example:
path.data: /path/to/data1,/path/to/data2

In 2.0 on the other hand this will change but you will still not be able to have an index on a data path and another index on another data path.
At the moment, the only solution for your use case is to have SSDs on "hot" nodes and HDDs on "cold" nodes, meaning one ES node with SSD and one ES node with HDD: https://www.elastic.co/guide/en/elasticsearch/guide/current/retiring-data.html#migrate-indices


text:
Q: Flask not working when importing classes from other .py files I am using Flask to create a web app, and am trying to import another class from a .py file in the same directory as my app.py file, but the imports won't work.
To elaborate:
This is my code which works and runs fine.
from flask import Flask
import os

from flask import Flask, request, render_template, redirect, url_for, flash
from flask import send_from_directory
#from moleimages import MoleImages
import random
from werkzeug.utils import secure_filename
from keras.models import load_model
import tensorflow as tf
from keras.models import model_from_json

app = Flask(__name__)

@app.route('/')
def index():
    return 'hi'

if __name__ == "__main__":
    app.run(debug=True)

Now, the second I uncomment 'from moleimages import MoleImages', the command prompt generates no output for the flask app and it terminates.
Terminal images:
Working fine:

now, when I uncomment the moleimages import:

The flask app just terminates itself.
Does anyone know why this is happening? The moleimages file works fine on its own and generates no errors. Here is the moleimages file.
'''
Author@PranavEranki
'''
import numpy as np
from skimage import io
from skimage.transform import resize
import glob
import h5py
import os

'''
This is the helper method for image prep
'''
class MoleImages():
    def __init__(self, dir=None):
        self.dir = dir
        self.size = None

    # Resizing multiple images to a 128 x 128 size
    def resize_bulk(self, wtype, size=(128,128)):
        '''
        Resize Images and create matrix
        Input: size of the images (128,128)
        Output: Numpy array of (size,num_images)
        '''
        self.size = size
        X = []
        image_list = glob.glob(self.dir) #Getting images we need to resize
        n_images = len(image_list)
        most = 2000
        if n_images > most:
            n_images = most
            image_list = image_list[:n_images]
        # Resizing of the images with verbosity
        print('Resizing {} images:'.format(n_images))
        for i, imgfile in enumerate(image_list):
            print('Resizing image {} of {}'.format(i+1, n_images))
            img = io.imread(imgfile)
            img = resize(img, self.size)

            X.append(img)

        return np.array(X)

    def load_test_images(self, dir_b, dir_m):
        X = []
        image_list_b = glob.glob(os.path.join(os.getcwd(), dir_b + '/*.png'))

        n_images_b = len(image_list_b)
        print('Loading {} images of class benign:'.format(n_images_b))
        for i, imgfile in enumerate(image_list_b):
            print('Loading image {} of {}'.format(i+1, n_images_b))
            img = io.imread(imgfile)
            X.append(img)
        image_list_m = glob.glob(os.path.join(os.getcwd(), dir_m + '/*.png'))

        n_images_m = len(image_list_m)
        print('Loading {} images of class benign:'.format(n_images_m))
        for i, imgfile in enumerate(image_list_m):
            print('Loading image {} of {}'.format(i+1, n_images_m))
            img = io.imread(imgfile)
            X.append(img)

        y = np.hstack((np.zeros(n_images_b), np.ones(n_images_m)))

        return np.array(X), y.reshape(len(y),1)

    def load_image(self, filename, size=(128,128)):
        self.size = size
        img = io.imread(filename) #Getting image
        img = resize(img, self.size, mode='constant') * 255 # Resizing image
        if img.shape[2] == 4: #Making sure everything is 3 channels only
            img = img[:,:,0:3]
        return img.reshape(1, self.size[0], self.size[1], 3)

    def save_h5(self, X, filename, dataset):
        '''
        Save a numpy array to a data.h5 file specified.
        Input:
        X: Numpy array to save
        filename: name of h5 file
        dataset: label for the dataset
        '''
        with h5py.File(filename, 'w') as hf:
            hf.create_dataset(dataset, data=X)
        print('File {} saved'.format(filename))

    def load_h5(self, filename, dataset):
        '''
        Load a data.h5 file specified.
        Input: filename, dataset
        Output: Data
        '''
        with h5py.File(filename, 'r') as hf:
            return hf[dataset][:]

    def save_png(self, matrix, dir, tag='img', format='png'):

        # Saving the picture to the directory
        for i, img in enumerate(matrix):
            current_dir = os.getcwd()
            # getting the appropriate filename and directory
            if dir[-1] != '/':
                current_dir = (os.path.join(current_dir, dir + "/"))
                filename = tag + str(i) + '.' + format
            else:
                current_dir = (os.path.join(current_dir, dir))
                filename = tag + str(i) + '.' + format

            # this is some verbosity which I implemented for bug testing - not important
            print('Saving file {}'.format(filename))
            print(current_dir)

            # Making rhe dir benign / malign for data scaled if not present
            if not os.path.exists(current_dir):
                os.makedirs(current_dir)

            # Saving the image to the proper directory
            current_dir = os.path.join(current_dir, filename)

            io.imsave(current_dir, img)

if __name__ == '__main__':
    pass
    #benign = MoleImages()
    #X = benign.load_h5('benigns.h5','benign')

A: If moleimages.py is in the same directory, you may want to change the import to from .moleimages import MoleImages
This way you tell python to load the file with that name from the same folder. Otherwise python is looking for a module named moleimages.
Another way is to use absolute import, but I can't tell you how that would look like without knowing your app hierarchy.
You can read more on relative and absolute imports in PEP 328
Edit: also make sure you have __init__.py in the directory

A: Did you try import .moleimages? You can also create a env variable called PYTHONPATH and set your work directory. This env variable is readable from python.


text:
Q: How to install and import angular 2 '@angular/router'? I'm trying to use @angular/router from this documentation. I tried to install this module using npm: npm install @angular/router --save
And I tried to import this module:
import { ROUTER_DIRECTIVES } from '@angular/router';

I get an error "Cannot find module '@angular/router'"
I looked at node_modules/@angular/router directory. It has 2 directories: angular1 and angular2. Should I import this module using:
import { ROUTER_DIRECTIVES } from '@angular/router/angular2/router.js';

Or this is incorrect module? It has only 3 files in angular2 directory: router.js, router.dev.js, router.min.js

A: https://angular.io/resources/live-examples/quickstart/ts/plnkr.html
You need to add it to your configuration
var routerVer = '@3.0.0-alpha.8'; // lock router version

var  map = {
  'app':                        'app',

  ...
  '@angular/router':            'https://npmcdn.com/@angular/router' + routerVer,
  ...
};


text:
Q: Unusually slow and stuttery NTFS hard drive My dual-boot Ubuntu 18.04 and Windows laptop has begun displaying some unusual behaviour. I have a boot SSD, which is formatted with an ext4 partition and an NTFS partition, and a data hard drive which is entirely NTFS.
The performance of the SSD is fine on both partitions. However, the performance of the hard drive has suddenly nosedived, and is behaving very unusually.
It is taking around five seconds to perform ls or load Nautilus at the root of the hard drive, though if something else is using the drive heavily (such as Steam) I've seen it take as long as one minute, or even hang indefinitely until a restart. Steam also crashes or hangs for long periods of time while downloading games or updates to the drive. At worst, I've had nothing able to access the disk at all, ls hanging indefinitely, and even GNOME Disks crashing when selecting the disk from the side bar.
Crucially, the performance on Windows is absolutely fine. Explorer listings for the drive load almost instantly, as does the dir command. Whatever is happening here must be an issue with my Linux installation.
At one stage, the drive locked up completely and Steam said that there was corrupt data on the disk. I rebooted into Windows and that said the same thing. I ran chkdsk /f E: on the hard drive (where E: is the hard drive's letter in Windows). This found many errors, fixed the corruption, and made a minor performance improvement, but it is still unusually slow.
SMART says that the drive's health is fine, and a GNOME Disks self-test flags no errors.
My /etc/fstab is:
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/nvme0n1p7 during installation
UUID=24348190-099b-4029-a8bd-13e1f91e396c /               ext4    errors=remount-ro 0       1
# /boot/efi was on /dev/nvme0n1p1 during installation
UUID=D816-4C34  /boot/efi       vfat    umask=0077      0       1
/swapfile                                 none            swap    sw              0       0
/dev/disk/by-uuid/3A8294518294138B /mnt/3A8294518294138B auto nosuid,nodev,nofail,x-gvfs-show,defaults,exec,uid=1000,gid=1000 0 0

...where the last line defines the hard drive. (The Windows SSD partition isn't here; I mount that into /media/aaron through Nautilus if I need it.)
How can I diagnose what might be causing this?

A: Does this happen with other hard drives and flash drives, or just the one? For me, all external media (hard drives, flash drives) caused slowdown on Ubuntu 18.04 but worked fine on Windows 10. This persisted on two machines, across three filesystems (UDF, NTFS, and exFat).
I found two pages that were instrumental in fixing this:
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1208993
https://lonesysadmin.net/2013/12/22/better-linux-disk-caching-performance-vm-dirty_ratio/
The solution:
I added these two lines to /etc/sysctl.conf:
vm.dirty_background_ratio = 10
vm.dirty_ratio = 20

and ran sudo sysctl -p. This solution is proposed here as well. It seems to be an issue impacting 64-bit Linux machines with a lot of RAM. If you try this, please let me know if this does (or does not) work for you, in case this is a new issue!


text:
Q: Doctrine - extended entity that uses fields of parent entity as its own I'm trying to find the best solution for a common situation (all examples are simplified).
INTRO
I have a Record entity that holds name field:
/**
 * @ORM\Entity
 */
class Record
{
    /**
     * @ORM\Column(type="string", length=100);
     */
    protected $name;

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Record
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
}

And RecordFile entity that has its own filename field:
/**
 * @ORM\Entity
 */
class RecordFile
{
    /**
     * @ORM\Column(type="string", length=200);
     */
    protected $filename;

    /**
     * Set filename
     *
     * @param string $filename
     *
     * @return RecordFile
     */
    public function setFilename($filename)
    {
        $this->filename = $filename;

        return $this;
    }

    /**
     * Get filename
     *
     * @return string
     */
    public function getFilename()
    {
        return $this->filename;
    }
}

PROBLEM
I want to make processing as follows - create Record entity, set fields, persist it, and than extract RecordFile entity with extended getters that operate on Record fields.
// Record #1
$record = (new Record())
    ->setName('Test')
;

$em->persist($record);
$em->flush();

$recordFile = $em->getRepository('AppBundle:RecordFile')->find(1);

// Returns formatted 'name' field
$recordFile->getName();

RecordFile should use name field (basically, any field) of the Record entity and format it for some purposes.
/**
 * @ORM\Entity
 */
class RecordFile
{
    // ---

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->formatNameField($this->name);
    }

    // ---
}

This RecordFile should in some way extend Record base class, to overwrite it's getters methods, but should still has its own fields and access to the "base" Record entity fields.
TRIED SOLUTIONS
1) Doctrine STI CTI (Inheritance mapping documentation) - but those mappings strictly separate the data, which I basically need in one row.
2) One-To-Many between Record and RecordFile - where record file has custom getters such as:
    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->formatNameField($this->record->name);
    }

But it feels kind of hackish, without direct extension of base class.
A really hope that someone would look into this (probably, in some way esoteric) problem.


text:
Q: In Rails, what is the difference using "has_many with belongs_to" vs "has_many with has_one"? For example, in
class Student < ActiveRecord::Base
  has_many :awards
end

class Awards < ActiveRecord::Base
  belongs_to :student
end

the above should be the correct usage, but what if we use
class Student < ActiveRecord::Base
  has_many :awards
end

class Awards < ActiveRecord::Base
  has_one :student
end

doesn't the above also make possible student.awards as an array of Award objects, and award.student as a Student object which is the recipient of the award, so works the same way as the method at the top of post?

A: has_one is used in case of a one-to-one relationship, not in one-to-many relationships.
Correct use of has_one:
class Student < ActiveRecord::Base
  has_one :id_card
end

class IdCard < ActiveRecord::Base
  belongs_to :student
end

A: The two examples are not equivalent.
has_many and belongs_to work as a pair where there is a 'many to one' relationship.
In the database this would look like:
**Students**
Name
Email
...

**Awards**
Name
student_id  <-- !IMPORTANT!
...

Each Student has many awards hence has_many :awards
Each Award 'belongs to' a Student hence belongs_to :student
Notice that the belongs_to is applied to the table with the foreign key student_id.  This is important.
OK - so what happens where there is a 'one to one' relationship?
If each student could only have a single award then the database tables could  look exactly the same but the model should not be able to return a collection of items.
This is where we need the has_one declaration.  This would be applied to the Student model in this case.  Why?  Because the relationship is the same in both directions but Active Record needs to know where to find the foreign key.
If the database tables were the other way around with each Student having an award_id then the Student would get the belongs_to and the Award would get the has_one.
Hope that makes it clear?
It does seem a little odd to be that a student could 'belong to' an award if you use natural language.  But that is how the rails active record domain specific language is written.
It gets even more unnatural sounding when you look at the 'many to many' relationship with 'has_many_and_belongs_to'.  Here there is a joining table which site between your main tables like
students_awards
student_id
award_id

In this situation neither the Students nor the Awards table have a foreign key but both will carry the has_many_and_belongs_to :other_table declaration.  Both tables are able to join to multiple rows of the other.  Each Student can have more than one Award.  Each Award can be applied to many Students.
The has_one declaration is only used where there is a 'one-to-one' relationship and the table it applies to does not have the foreign key.


text:
Q: Highlight same words in text files in Eclipse Is there any option to highlight same words in text files in Eclipse. I know that eclipse is highlighting java code.
But can we also enable somehow highlighting of same words in text files?
The same function is in Notepad++. If we select some word it will highlight all the same words in the whole file.


text:
Q: Syncing Uncontained Objects with AlwaysOn Availability Groups In setting up our HA environment (AlwaysOn AG), I came across the add-in ssms_2012_ag_addin_setup.exe that I got from SQLSkills. http://www.sqlskills.com/blogs/jonathan/synchronize-availability-group-logins-and-jobs/
This is very helpful in tackling the challenge of syncing the uncontained objects from the primary to secondary replicas. This add-in does not include the sync of operators, alerts or credentials. It also does not account for the need to allow any SQL job to execute on failover ONLY. I can add the following to the first job-step to accomplish this.
DECLARE @ServerName NVARCHAR(256) = @@SERVERNAME
 DECLARE @RoleDesc NVARCHAR(60)

SELECT @RoleDesc = a.role_desc
 FROM sys.dm_hadr_availability_replica_states AS a
 JOIN sys.availability_replicas AS b
 ON b.replica_id = a.replica_id
 WHERE b.replica_server_name = @ServerName

IF @RoleDesc = 'PRIMARY'

BEGIN

— Job Step Logic

END

ELSE
 EXEC msdb..sp_stop_job –Job Name

Do you have any better solutions to automating these needs when using AwaysOn Availability Groups as a HA solution.

A: Native functionality, no.
AlwaysOn Availability Groups have the containment of database.  Server objects (Agent jobs, logins, alerts, etc.) just simply don't play a HADR role with availability groups.
Whenever you run into the need to ensure that server-level objects exist on all replicas, or that they only execute on [particular_replica] then you will have to have this custom logic.


text:
Q: Rough classification of Peano Curves By Peano curve I mean a continuous map from the unit interval that fills the unit square in $\mathbb R^2$.
In the paper:
Shchepin, E. V.; Bauman, K. E., Minimal Peano curve, Proc. Steklov Inst. Math. 263, 236-256 (2008); translation from Tr. Mat. Inst. Steklova 263, 251-271 (2008). ZBL1201.37061.
the authors mention the square to linear ratio, defined for a Peano curve $p:[0,1]\rightarrow[0,1]\times [0,1]$, as: $$\sup_{t_1,t_1\in[0,1]} \frac{|p(t_1)-p(t_2)|^2}{|t_1-t_2|}.$$
They prove that there exists a unique, up to isometry, regular diagonal Peano curve of fractal genus 9 that maps a unit interval onto a unit square and whose square-to-linear ratio is less than  6.
My question is:
Are there properties such as the square-to-linear ratio that can be used to classify Peano curves up to isometry or some weaker class of transformations?
Discrete properties that separate Peano curves into disjoint categories like whether they are self-crossing or not would also interesting.


text:
Q: Regular Expression to match numeric OR specific word I am trying to create a regular expression that handles 0-9 * or basically \d* but also include the or (|) with an expression to handle a specific word. So the idea im shooting for should be this
\d*|[Word]
The reason i need this to happen is i have a filter textbox with my validator applied to it to prevent bogus data being entered, but the trick is i have the default text of the textbox set to what is to be entered into the box, such as "Enter Account." I need the regular expression to handle \d* for the account number validation and the | part of the expression to allow the default text of the textbox to pass validation. I do checking on the back end so this default text wont break the app. I have 3 filter boxes where i'll be using this expression..if possible.

A: You basically have it, but lose the [], which indicate character classes:
^\d*|word$

Also, you should anchor your validation expressions with ^ and $.


text:
Q: What is wrong with White Background for a DockedCell? Bug introduced in V10.4 or earlier and persists through V11.3

SetOptions[
  EvaluationNotebook[]
, DockedCells -> Flatten @ {
    Cell[
      BoxData @ ToBoxes[Framed[InputForm@#, Background -> White]]
    , CellFrameMargins -> 15
    , CellMargins -> {{0, 0}, {0, 0}}
    , Background -> #
    ] & /@ {
      Inherited, Red, GrayLevel[1.], None, GrayLevel[.99], Blue
    }}
]

Apparently you can not have White Background for a DockedCells.
And if you do not obey they will take your margins, too!

Any reasonable explanation?
Notice the None case is documented:

If Background->None is set, then the margins are only applied if a CellFrame is present. If the cell frame is not drawn on all sides, then the margin will only be applied to the sides with a frame setting.

V11.2 Win7

[CASE:3975061] was created

A:
[...] It does appear as though DockedCells cannot have White as their Background specification. I have filed a report with our developers regarding this incorrect limitation so that they may investigate and look to address the issue in a future release. [...]
- WRI Support

The workaround is to use 'almost' white:
SetOptions[EvaluationNotebook[]
, DockedCells -> Cell[
    BoxData @ ToBoxes[Framed[InputForm@GrayLevel[.999]]]
  , CellFrameMargins -> 15
  , CellMargins -> {{0, 0}, {0, 0}}
  , Background -> GrayLevel[.999]
  ]
]


text:
Q: How to use else-if condition in a view in SQL server? I know that an if condition can be achieved using the CASE statement:
CASE
    WHEN <condition>
        x
    ELSE
        z
END

but how to do that for an else-if condition?
Something like this (pseudo code):
CASE
    WHEN <condition>
        x
    ELSE-IF <condition>
        y
    ELSE
        z
END

My code as of now:
CREATE VIEW [dbo].[v_myview1]
AS
    SELECT
        ci.aDate, ci.Currency, ci.lim, ci.LimitUS,
        pa.Date as AmtDate,
        pa.Payment as AmtPayment,
        CASE
            WHEN (ci.aDate - pa.Date) < 0 THEN ci.LimitUS
            --ELSE IF
            --WHEN (ci.lim - pa.Payment) < 0 THEN 'a'
            ELSE 'b'
        END AS Estimate,
    FROM
        dbo.Amt pa
    JOIN
        dbo.CrInfo ci ON ci.pr_key = pa.pr_key
    JOIN
        dbo.rates tr ON rt.Currency = ci.Currency
    WHERE
        ci.mk = 2

A: You can use the second case like this:
CASE
WHEN (ci.aDate - pa.Date) < 0 THEN  ci.LimitUS
WHEN (ci.lim - pa.Payment) < 0 THEN 'a'
ELSE 'b'


text:
Q: PyQt / Qt, tableview with custom delegate to use ellipsis for text overflowing cell Without custom delegate everything works fine:

But my tableview shows search results and part of the text needs to be bold to indicate where it matches the searched query.
Once I use the delegate to get html tags working, the text that overflows cells is not cliped and replaced with ellipsis:

Heres my delegate:
class HTMLDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
    super().__init__()
    self.doc = QTextDocument(self)

def paint(self, painter, option, index):
    painter.save()

    options = QStyleOptionViewItem(option)
    self.initStyleOption(options, index)

    self.doc.setHtml(options.text)
    options.text = ""

    style = QApplication.style() if options.widget is None \
        else options.widget.style()
    style.drawControl(QStyle.CE_ItemViewItem, options, painter)

    ctx = QAbstractTextDocumentLayout.PaintContext()

    if option.state & QStyle.State_Selected:
        ctx.palette.setColor(QPalette.Text, option.palette.color(
                             QPalette.Active, QPalette.HighlightedText))

    textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options)
    #textRect.adjust(0, 0, 0, 0)
    painter.translate(textRect.topLeft())
    self.doc.documentLayout().draw(painter, ctx)

    painter.restore()

def sizeHint(self, option, index):
    return QSize(self.doc.idealWidth(), self.doc.size().height())

also if I would add line
self.doc.setTextWidth(option.rect.width())

it would cut the text to the other line(I increased row height to show it):

A: painter.setClipRect(textRect.translated(-textRect.topLeft()))

I thoughtI had it in my delegate, its in all other answers around here, well it does the clipping correctly, though no fancy ellipsis, but thats ok I guess.
I assumed previously that theres just some value that I have to enable to get clipping ellipsis, but I am starting to see that it could be considerably more complicated than that, that I might actually need to edit the text itself depending on area rectangle -  vs text width taken and adjust on every column resize or some stuff
oh, how I wish they would just make option to enable html rich text with the default delegate


text:
Q: xaml path data for arrow I have trying to draw simple "up" arrow by this code:
    <Canvas Width="500" Height="500">
            <Path Height="120" Width="120" StrokeThickness="1" Stroke="Red" Data="M 60,60 L 60,0 L 50,10 L 60,0 L 70,10"/>
    </Canvas>

And I don't see symmetric arrow on my screen.
I want to understand this "magic".

A: You have created a Path that is 120x120.  Coordinate 0,0 is the upper-left corner.
M 60, 60  ->  Move to the very center of the Path object x=60,y=60
L 60,0 -> Draw a Line from the last coordinate (60,60) to x=60,y=0 (straight up)
L 50,10 -> Draw a Line from the last coordinate (60,0) to x=50,y=10 (to the left 10 and down 10)
L 60, 0 -> Draw a Line from the last coordinate (50,10) to x=60, y=0 (retrace your line up and to the right by 10 each)
L 70,10 ->  Draw a Line from the last coordinate (60,0) to x=70,y=10 ( to right 10 and down 10)

The reason that it is not symmetrical is because you are backtracking along the left arm of the arrow.  This adds a join at that point, and essentially adds more to the line there because of your stroke thickness.
You can fix that like this:
        <Path Height="120" Width="120"
                    StrokeThickness="1" Stroke="Red" Data="M 60,60 L 60,0 L 50,10 M60,0 L70,10"/>


text: Q: How to programmatically fill a Textbox and then click a button in another application I want to write a program in Java to access another application's window to do some jobs automatically. Exactly, I want my program automatically click a special menu in that program and after opening a window (which has three textbox and two button), fill out two or three textboxes and then click Add button. I want to enter a long list of information automatically to this program.


text:
Q: How to manage 3D arrays in agent-based models with R? I am building an agent-based model with R but I have memory issues by trying to work with large 3D arrays. In the 3D arrays, the first dimension corresponds to the time (from 1 to 3650 days), the second dimension defines the properties of individuals or landscape cells and the third dimension represents each individual or landscape cell. At each time step (1 day), each 3D array is filled using several functions. Ideally, I would like to run my ABM over large landscapes (for example, 90000 cells) containing a large number of individuals (for example, 720000). Actually, this is impossible because of memory issues.
Currently, the 3D arrays are defined at initialization so that data are stored in the array at each time step. However, to fill one 3D array at t from the model, I need to only keep data at t – 1 and t – tf – 1, where tf is a duration parameter that is fixed (e.g., tf = 320 days). Here an example of one model function that is used to fill one 3D array (there are 3 duration parameters):
    library(ff)
    library(magrittr)
    library(dplyr)
    library(tidyr)
    library(gtools)

    ## Define parameters
    tf1 <- 288
    tf2 <- 292
    tf3 <- 150

    ## Define 3D array
    col_array <- c(letters[seq( from = 1, to = 9 )])
    s_array <- ff(-999, dim=c(3650, 9, 2500), dimnames=list(NULL, col_array, as.character(seq(1, 2500, 1))),
                              filename="s_array.ffd", vmode="double", overwrite = t) ## 3th dimension = patch ID

    ## Define initial array
    initial_s_array <- matrix(sample.int(100, size = 2500*9, replace = TRUE), nrow = 2500, ncol = 9, dimnames=list(NULL, col_array))

   ## Loop over time
    line <- 1
    for(t in 1:3650){
      print(t)
      s_array[t,c("a", "b", "c", "d", "e", "f", "g", "h", "i"),] <- func(v_t_1 = ifelse((t - 1) >= 1, list(s_array[(t - 1),,]), NA)[[1]],
                                                                         v_t_tf1_1 = ifelse((t - tf1 - 1) >= 1, list(s_array[(t - tf1 - 1),,]), NA)[[1]],
                                                                         v_t_tf2_1 = ifelse((t - tf2 - 1) >= 1, list(s_array[(t - tf2 - 1),,]), NA)[[1]],
                                                                         v_t_tf3_1 = ifelse((t - tf3 - 1) >= 1, list(s_array[(t - tf3 - 1),,]), NA)[[1]],
                                                                         v_t_0 = initial_s_array, columns_names = col_array)
      line <- line + 1
    }

    func <- function(v_t_1, v_t_tf1_1, v_t_tf2_1, v_t_tf3_1, v_t_0, columns_names){

      ## Data at t-1
      dt_t_1 <- (ifelse(!(all(is.na(v_t_1))),
                        list(v_t_1 %>%
                               as.data.frame.table(stringsAsFactors = FALSE) %>%
                               dplyr::mutate_all(as.character)), NA))[[1]]

      ## Data at t-tf1-1
      dt_t_tf1_1 <- (ifelse(!(all(is.na(v_t_tf1_1))),
                             list(v_t_tf1_1 %>%
                                    as.data.frame.table(stringsAsFactors = FALSE) %>%
                                    dplyr::mutate_all(as.character)), NA))[[1]]

      ## Data at t-tf2-1
      dt_t_tf2_1 <- (ifelse(!(all(is.na(v_t_tf2_1))),
                             list(v_t_tf2_1 %>%
                                    as.data.frame.table(stringsAsFactors = FALSE) %>%
                                    dplyr::mutate_all(as.character)), NA))[[1]]

      ## Data at t-tf3-1
      dt_t_tf3_1 <- (ifelse(!(all(is.na(v_t_tf3_1))),
                             list(v_t_tf3_1 %>%
                                    as.data.frame.table(stringsAsFactors = FALSE) %>%
                                    dplyr::mutate_all(as.character)), NA))[[1]]

      ## Format data at t-1
      dt_t_1_reshape <- (ifelse(!(all(is.na(dt_t_1))),
                                list(dt_t_1 %>%
                                       dplyr::rename(ID = Var2) %>%
                                       tidyr::spread(Var1, Freq) %>%
                                       dplyr::select(ID, columns_names) %>%
                                       dplyr::arrange(match(ID, mixedsort(colnames(v_t_1))))), NA))[[1]]

      ## Format data at t-tf1-1
      dt_t_tf1_1_reshape <- (ifelse(!(all(is.na(dt_t_tf1_1))),
                                     list(dt_t_tf1_1 %>%
                                            dplyr::rename(ID = Var2) %>%
                                            tidyr::spread(Var1, Freq) %>%
                                            dplyr::select(ID, columns_names) %>%
                                            dplyr::arrange(match(ID, mixedsort(colnames(v_t_tf1_1))))), NA))[[1]]

      ## Format data at t-tf2-1
      dt_t_tf2_1_reshape <- (ifelse(!(all(is.na(dt_t_tf2_1))),
                                     list(dt_t_tf2_1 %>%
                                            dplyr::rename(ID = Var2) %>%
                                            tidyr::spread(Var1, Freq) %>%
                                            dplyr::select(ID, columns_names) %>%
                                            dplyr::arrange(match(ID, mixedsort(colnames(v_t_tf2_1))))), NA))[[1]]

      ## Format data at t-tf3-1
      dt_t_tf3_1_reshape <- (ifelse(!(all(is.na(dt_t_tf3_1))),
                                     list(dt_t_tf3_1 %>%
                                            dplyr::rename(ID = Var2) %>%
                                            tidyr::spread(Var1, Freq) %>%
                                            dplyr::select(ID, columns_names) %>%
                                            dplyr::arrange(match(ID, mixedsort(colnames(v_t_tf3_1))))), NA))[[1]]

      ## Retrieve data
      a_t_1 <- (ifelse((!(all(is.na(dt_t_1_reshape)))), list(as.numeric(dt_t_1_reshape[,c("a")])), list(v_t_0[,c("a")])))[[1]]
      d_t_1 <- (ifelse((!(all(is.na(dt_t_1_reshape)))), list(as.numeric(dt_t_1_reshape[,c("d")])), list(v_t_0[,c("d")])))[[1]]
      g_t_1 <- (ifelse((!(all(is.na(dt_t_1_reshape)))), list(as.numeric(dt_t_1_reshape[,c("f")])), list(v_t_0[,c("f")])))[[1]]

      a_t_tf1_1 <- (ifelse(!(all(is.na(dt_t_tf1_1_reshape))), list(as.numeric(dt_t_tf1_1_reshape[,c("a")])), 0))[[1]]
      d_t_tf2_1 <- (ifelse(!(all(is.na(dt_t_tf2_1_reshape))), list(as.numeric(dt_t_tf2_1_reshape[,c("d")])), 0))[[1]]
      g_t_tf3_1 <- (ifelse(!(all(is.na(dt_t_tf3_1_reshape))), list(as.numeric(dt_t_tf3_1_reshape[,c("f")])), 0))[[1]]

      b_t_1 <- (ifelse((!(all(is.na(dt_t_1_reshape)))), list(as.numeric(dt_t_1_reshape[,c("b")])), list(v_t_0[,c("b")])))[[1]]
      e_t_1 <- (ifelse((!(all(is.na(dt_t_1_reshape)))), list(as.numeric(dt_t_1_reshape[,c("e")])), list(v_t_0[,c("e")])))[[1]]
      h_t_1 <- (ifelse((!(all(is.na(dt_t_1_reshape)))), list(as.numeric(dt_t_1_reshape[,c("h")])), list(v_t_0[,c("h")])))[[1]]

      b_t_tf1_1 <- (ifelse(!(all(is.na(dt_t_tf1_1_reshape))), list(as.numeric(dt_t_tf1_1_reshape[,c("b")])), 0))[[1]]
      e_t_tf2_1 <- (ifelse(!(all(is.na(dt_t_tf2_1_reshape))), list(as.numeric(dt_t_tf2_1_reshape[,c("e")])), 0))[[1]]
      h_t_tf3_1 <- (ifelse(!(all(is.na(dt_t_tf3_1_reshape))), list(as.numeric(dt_t_tf3_1_reshape[,c("h")])), 0))[[1]]

      ## Define discrete equations
      a_t <- round(0.4*a_t_1 + 0.5*a_t_tf1_1)
      b_t <- round(0.5*b_t_1 + 0.6*b_t_tf1_1)
      c_t <- a_t + b_t
      d_t <- round(0.7*d_t_1 + 0.7*d_t_tf2_1)
      e_t <- round(0.9*e_t_1 + 0.4*e_t_tf2_1)
      f_t <- d_t + e_t
      g_t <- round(0.3*g_t_1 + 0.2*g_t_tf3_1)
      h_t <- round(0.5*h_t_1 + 0.1*h_t_tf3_1)
      i_t <- g_t + h_t

      ## Update the values
      dt_array <- as.matrix(cbind(a_t, b_t, c_t, d_t, e_t, f_t, g_t, h_t, i_t))
      ## print(dt_array)

      ## Build the output matrix
      dt_array <- t(dt_array)

      return(dt_array)

    }

The function "func" takes as argument data at t – 1 and t – tf – 1 providing one 3D array "s_array". The function returns a data frame that is used to fill the 3D array.
I think that I could reduce the first dimension of my arrays by keeping only data at t – 1 and t – tf – 1 (rather than keep data at each time step from 1 to 3650 days). However, I don't know how to manage these new 3D arrays in the ABM at each time step (i.e., how to initialize the 3D arrays and to only store data at t – 1 and t – tf – 1)?
Edit:
    I have tested the example with 90000 observations for the 3rd dimension. The number of rows (i.e., 3650) in each array is too large.
> s_array <- ff(-999, dim=c(3650, 9, 90000), dimnames=list(NULL, col_array, as.character(seq(1, 90000, 1))),
+               filename="s_array.ffd", vmode="double", overwrite = TRUE)
Error in if (length < 0 || length > .Machine$integer.max) stop("length must be between 1 and .Machine$integer.max") :
  missing value where TRUE/FALSE needed
In addition: Warning message:
In ff(-999, dim = c(3650, 9, 90000), dimnames = list(NULL, col_array,  :
  NAs introduced by coercion to integer range

Is there a way to reduce the number of rows and apply the function that is used to fill the arrays ?

A: The reason I said that R probably isn't ideal is because of its copy-on-modify semantics,
so every time you change something in any array/matrix/data frame,
a copy must be made.
I think R can do some clever things with its memory management,
but still.
Using ff to avoid having all time slices in RAM at the same time is probably indeed advantageous,
but your code is probably changing storage formats far too often,
juggling data structures back and forth.
I think I packed the logic in a couple R6 class
(along with some improvements),
maybe it can get you started with improving your code's memory usage:
suppressPackageStartupMessages({
  library(R6)
  library(ff)
})

SArray <- R6::R6Class(
  "SArray",
  public = list(
    time_slices = NULL,

    initialize = function(sdim, sdimnames) {
      self$time_slices <- lapply(1L:sdim[1L], function(ignored) {
        ff(NA_real_, vmode="double", dim=sdim[-1L], dimnames=sdimnames[-1L])#, FF_RETURN=FALSE)
      })

      names(self$time_slices) <- sdimnames[[1L]]
    }
  )
)

`[.SArray` <- function(s_array, i, j, ...) {
  s_array$time_slices[[i]][j,]
}

`[<-.SArray` <- function(s_array, i, j, ..., value) {
  s_array$time_slices[[i]][j,] <- value
  s_array
}

dim.SArray <- function(x) {
  c(length(x$time_slices), dim(x$time_slices[[1L]]))
}

ABM <- R6::R6Class(
  "ABM",
  public = list(
    s_array = NULL,
    tf1 = NULL,
    tf2 = NULL,
    tf3 = NULL,

    initialize = function(sdim, sdimnames, tfs) {
      self$tf1 <- tfs[1L]
      self$tf2 <- tfs[2L]
      self$tf3 <- tfs[3L]

      self$s_array <- SArray$new(sdim, sdimnames)
    },

    init_abm = function(seed = NULL) {
      set.seed(seed)
      sdim <- dim(self$s_array)
      s_init <- matrix(sample.int(100L, size = 6L * sdim[3L], replace=TRUE),
                       nrow=6L, ncol=sdim[3L],
                       dimnames=list(c("a", "b", "d", "e", "g", "h"),
                                     as.character(1:sdim[3L])))

      self$a(1L, s_init["a", ])
      self$b(1L, s_init["b", ])
      self$c(1L)
      self$d(1L, s_init["d", ])
      self$e(1L, s_init["e", ])
      self$f(1L)
      self$g(1L, s_init["g", ])
      self$h(1L, s_init["h", ])
      self$i(1L)

      private$t <- 1L

      invisible()
    },

    can_advance = function() {
      private$t < dim(self$s_array)[1L]
    },

    advance = function(verbose = FALSE) {
      t <- private$t + 1L
      if (verbose) print(t)

      self$a(t)
      self$b(t)
      self$c(t)
      self$d(t)
      self$e(t)
      self$f(t)
      self$g(t)
      self$h(t)
      self$i(t)

      private$t <- t

      invisible()
    },

    # get time slice at t - tf - 1 for given letter
    s_tf = function(t, tf, letter) {
      t_tf_1 <- t - tf - 1L

      if (t_tf_1 > 0L)
        self$s_array[t_tf_1, letter, ]
      else
        0
    },

    # discrete equations

    a = function(t, t_0) {
      if (t < 2L) {
        t <- 1L
        t_1 <- t_0
        t_tf_1 <- 0
      }
      else {
        t_1 <- self$s_array[t - 1L, "a", ]
        t_tf_1 <- self$s_tf(t, self$tf1, "a")
      }

      self$s_array[t, "a", ] <- round(0.4 * t_1 + 0.5 * t_tf_1)
      invisible()
    },

    b = function(t, t_0) {
      if (t < 2L) {
        t <- 1L
        t_1 <- t_0
        t_tf_1 <- 0
      }
      else {
        t_1 <- self$s_array[t - 1L, "b", ]
        t_tf_1 <- self$s_tf(t, self$tf1, "b")
      }

      self$s_array[t, "b", ] <- round(0.5 * t_1 + 0.6 * t_tf_1)
      invisible()
    },

    c = function(t) {
      if (t < 1L) stop("t must be positive")
      a_t <- self$s_array[t, "a", ]
      b_t <- self$s_array[t, "b", ]
      self$s_array[t, "c", ] <- a_t + b_t
      invisible()
    },

    d = function(t, t_0) {
      if (t < 2L) {
        t <- 1L
        t_1 <- t_0
        t_tf_1 <- 0
      }
      else {
        t_1 <- self$s_array[t - 1L, "d", ]
        t_tf_1 <- self$s_tf(t, self$tf2, "d")
      }

      self$s_array[t, "d", ] <- round(0.7 * t_1 + 0.7 * t_tf_1)
      invisible()
    },

    e = function(t, t_0) {
      if (t < 2L) {
        t <- 1L
        t_1 <- t_0
        t_tf_1 <- 0
      }
      else {
        t_1 <- self$s_array[t - 1L, "e", ]
        t_tf_1 <- self$s_tf(t, self$tf2, "e")
      }

      self$s_array[t, "e", ] <- round(0.9 * t_1 + 0.4 * t_tf_1)
      invisible()
    },

    f = function(t) {
      if (t < 1L) stop("t must be positive")
      d_t <- self$s_array[t, "d", ]
      e_t <- self$s_array[t, "e", ]
      self$s_array[t, "f", ] <- d_t + e_t
      invisible()
    },

    g = function(t, t_0) {
      if (t < 2L) {
        t <- 1L
        t_1 <- t_0
        t_tf_1 <- 0
      }
      else {
        t_1 <- self$s_array[t - 1L, "g", ]
        t_tf_1 <- self$s_tf(t, self$tf3, "g")
      }

      self$s_array[t, "g", ] <- round(0.3 * t_1 + 0.2 * t_tf_1)
      invisible()
    },

    h = function(t, t_0) {
      if (t < 2L) {
        t <- 1L
        t_1 <- t_0
        t_tf_1 <- 0
      }
      else {
        t_1 <- self$s_array[t - 1L, "h", ]
        t_tf_1 <- self$s_tf(t, self$tf3, "h")
      }

      self$s_array[t, "h", ] <- round(0.5 * t_1 + 0.1 * t_tf_1)
      invisible()
    },

    i = function(t) {
      if (t < 1L) stop("t must be positive")
      g_t <- self$s_array[t, "g", ]
      h_t <- self$s_array[t, "h", ]
      self$s_array[t, "i", ] <- g_t + h_t
      invisible()
    }
  ),
  private = list(
    t = NULL
  )
)

max_t <- 10
abm <- ABM$new(c(max_t, 9, 2500),
               list(NULL, letters[1:9], as.character(1:2500)),
               c(288L, 292L, 150L))

abm$init_abm()

while (abm$can_advance()) {
  abm$advance(TRUE)
}

anyNA(abm$s_array[])
# FALSE

Some of the functions under discrete equations encapsulate the logic for initialization when t < 2L.
The SArray class separates the 3D array into a list of 2D arrays to work around the .Machine$integer.max limit.


text:
Q: Converting a string with underscores to TitleCase Given this string:
  "EMAIL_LOG"
I want to convert it to:
  EmailLog
I have this code that does do the job:
private static string TitleCaseConvert(string title)
{
    CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
    TextInfo textInfo = cultureInfo.TextInfo;
    title = title.Replace("_", " ").ToLower();
    title = textInfo.ToTitleCase(title);
    title = title.Replace(" ", "");
    return title;
}

I was just wondering if there was a better suggestion to do this conversion or one that was more elegant perhaps?
Thanks.

A: You could use Split() to split on the _ characters and StringBuilder to reconstruct the output string.  This should perform better because you are using StringBuilder instead of constructing new strings everytime:
private static string ToPascalCase(string input)
{
    if(input == null)
    {
        throw new ArgumentNullException("input");
    }

    TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo;

    var sb = new StringBuilder();
    foreach(var part in input.Split('_'))
    {
        sb.Append(textInfo.ToTitleCase(part.ToLower()));
    }

    return sb.ToString();
}

Note that I am using the CultureInfo.CurrentCulture static property.  I think it more accurately describes what you want...
Fiddle here

A: What about doing it in one statement, like this:
private static string TitleCaseConvert(string title)
{
   return new CultureInfo("en").TextInfo.ToTitleCase(title.ToLower().Replace("_", " ")).Replace(" ", "");
}

A: If you're after raw performance, you could operate directly on a char array:
private static string TitleCaseConvert(string title)
{
    int wordStart = 0;

    char[] result = new char[title.Length];
    int ri = 0;
    for (int i = 0; i < title.Length; ++i)
    {
        if (title[i] == '_')
        {
            wordStart = i + 1;
        }
        else if (i == wordStart)
        {
            result[ri++] = Char.ToUpper(title[i]);
        }
        else
        {
            result[ri++] = Char.ToLower(title[i]);
        }
    }

    return new String(result, 0, ri);
}

Otherwise, a StringBuilder implementation will probably be shorter and more readable.

A: You could toss Regex.Replace() at this thing to pick out the first character, dump the underscore, and capitalize it.
title = Regex.Replace("this_is_a_test", @"(^|_)([a-z])", m =>  m.ToString().Replace("_","").ToUpper());

A: Alternative using Microsoft.VisualStudio :
var title = Strings.StrConv("EMAIL_LOG", VbStrConv.ProperCase).Replace("_", "");

Using Humanizer library :
var title = "EMAIL_LOG".ToLower().Pascalize();

A: You have the _.camelCase function in any library as lodash.
_.camelCase("EMAIL_LOG") // "emailLog"

We add (also from lodash) the _.upperFirst function to put the first character in uppercase.
_.upperFirst( _.camelCase("EMAIL_LOG") ) // "EmailLog"

Camel Case

Camel case is the practice of writing compound words or phrases such
  that each word or abbreviation in the middle of the phrase begins with
  a capital letter, with no intervening spaces or punctuation.

Lodash

Lodash is a JavaScript library which provides utility functions for
  common programming tasks using the functional programming paradigm.


text:
Q: case statement only reaching the default case echo "Choose one or All"
        read -n1 $sel
        echo "value of $sel
        case $selection in
        o|O) echo "inside O";;
        a|A) echo "inside A";;
        *) echo "this is default"
        ;;
        esac;

However, it always print value of $sel is default. The case statement is always reaching the default value and it is not reaching other cases. What might be the issue?


text:
Q: R: Combine Factors Dynamically I want to do the following:

*

*Open a dataset.

*Get the factor levels for a dependent variable

*Loop through the factor levels

*Create a new temporary column for a new dependent variable factor

*For each level, change all other level names to "other" and insert in new column

*Run some analyses (I know what to do here once factor levels recoded).

I don't know how to do point 5 above (and I have spent some time researching)
indf <- read.csv(".\\datafiles\\jobDescription\\nouns-categorical_R1.csv")

majorAsFactor <- levels(as.factor(indf$Major0))

for(i in majorAsFactor)
{
  printToLog(i)
  Major1 <- vector("character")
  indf["Major1"] <- Major1

}

A: Well, I found the answer by changing my google search to "recoding factors". Sometimes it's all in finding the right keywords.
The answer is as follows:
  indf$Major1[indf$Major0==i] <- as.character(i)
  indf$Major1[indf$Major0!=i] <- "OTHER"


text:
Q: How can I change Joomla3.9 subform min/max values in php or javascript? I have a Joomla (version 3.9.4, important for the subform, but as a newby I cannot add create the Joomla3.9 tag) form with field with type set to 'list' and a subform with min and max, both set to '6'. The subform has 1 field type 'calendar'.
So I see the list (with 3 options) and the subform with 6 datepicker items.
Now what I want is to change the min and max based on the option of the list. How can I do that? In PHP? Or in Javascript?
I tried looking for the min/max values in the DOM using Javascript/jQuery to find data-minimum and data-maximum, but then the items have already been generated, so that's too late.
Here's the form.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<form>
    <fieldset>
        <field name="type" type="list" default="" label="type" >
            <option value="0">Type A</option>
            <option value="1">Type B</option>
            <option value="2">Type C</option>
        </field>
        <field
            name="dates"
            type="subform"
            required="true"
            label="Dates"
            multiple="true"
            min="6"             <= This is what I want to change based on what was selected in the list
            max="6"             <= This is what I want to change based on what was selected in the list
        >
            <form>
                <field
                    name="date"
                    type="calendar"
                    label="Date"
                    default=""
                />
            </form>
        </field>
    </fieldset>
</form>

And here's the php part to render it:
<?php
defined('_JEXEC') or die('Restricted access');

JHtml::_('behavior.tooltip');
JHtml::_('behavior.formvalidation');
JHtml::_('formbehavior.chosen', 'select');
?>
<form action="<?php echo JRoute::_('index.php?option=com_mycom&view=types&layout=edit&id='.(int) $this->item->id); ?>" method="post" name="adminForm" id="edit-form" class="form-validate" enctype="multipart/form-data">
    <fieldset>
        <?php echo $this->form->getField('type')->renderField(); ?>
        <?php echo $this->form->getField('dates')->renderField(); ?>
    </fieldset>
</form>

I'm investigating 2 paths:
1. Subclass the subform adding controls to change min/max. Not sure if this can work as the user changing the type happens after php has generated the form. So this can only work if I then also reload after every change to the type. Don't like that, and breaks the default Joomla form behaviour.
2. Add Javascript code to then show the appropriate number of datepickers based on the type option selected. Something similar to, or extension of, the showon behaviour. Not there yet. Any pointers/help is much appreciated.

A: There is no proper way in Joomla to do this.
For users to add or remove date pickers don't set the min/max values, let them create as many as they need to manually, as by default provided in Joomla subforms

A: It can do in the Model, method getForm
$form->setFieldAttribute( 'dates', 'min', 'your value' );


text:
Q: How to disable Warnings for includes folders? I have to use some library, and have no power to change it or care about it,
EveryTime i compile a HUGE number of warnings popup. Useless things like

: warning C4350: behavior change: 'std::auto_ptr<_Ty>::auto_ptr(std::auto_ptr_ref<_Ty>)
  throw()' called instead of 'std::auto_ptr<_Ty>::auto_ptr(std::auto_ptr<_Ty> &) throw()'

I want to complete disable Warnings to this specific library. |But still want to have warnings to my own code. Is it possible in Visual Studio 2010 ?

A: #pragma warning is one option, though it's probably only feasible if you use precompiled headers or have very few source files in your own project.
#pragma warning (push)
#pragma warning (disable : 4350)
#include <third/party/headers/in/question.h>
#pragma warning (pop)

A: Create your own header file ( like "your_ABCD.h" ) with the below code.
// In your_ABCD.h
#pragma once
#pragma warning (disable : 4350)
#include <their_ABCD.h>
#pragma warning (default : 4350)

Then, you can include "your_ABCD.h" instead of "their_ABCD.h" file.


text:
Q: Get maximum video resolution with getUserMedia I'm trying to get highest video resolution as possible through JS navigator.getUserMedia. I know about constraints, but don't know how to choose right in my case.
The problem is looks like there is no way to say "I want a video at maximum resolution". So instead I'm trying to say "I want video not less than very big resolution".
When I'm trying minWidth: 1600, Chrome returns me 1280×720 video (highest possible for my camera, I think). But what if user has camera with higher resolution? So I'm asking for minWidth: 2048 video, and Chrome returns only 640×480.
var constraints = {
  video: {
    optional: [
    {minWidth: 2048}
    ]
  }
};

This is online example: http://jsbin.com/kibeza/1/watch?js,output
And there is actual problem: Chrome doesn't know math. It think what 1600 is greater than 2048. I can't ask for video "not less than 100500", because in this case I'll get standard low resolution. I cant ask video "not less than some reasonable small resolution", because there can be users with higher resolution and I want to get higher resolution.

A: Still I haven't found any good API to get maximum video resolution with getUserMedia.
But here I am sharing my idea to get maximum supported video resolution of the connected device using Binary Search algorithm and it's working great.
Here are the steps to do this job,

*

*Store some standard resolutions in an Array, maintaining ascending
order .

*Set leftIndex = 0 and rightIndex = size of resolution array.

*Check midIndex = (left+right)/2 resolution supported or not, and
modify left and right based on the result.

Here I am sharing my implementation:
var ResolutionsToCheck = [
                {width: 160, height:120},
                {width: 320, height:180},
                {width: 320, height:240},
                {width: 640, height:360},
                {width: 640, height:480},
                {width: 768, height:576},
                {width: 1024, height:576},
                {width: 1280, height:720},
                {width: 1280, height:768},
                {width: 1280, height:800},
                {width: 1280, height:900},
                {width: 1280, height:1000},
                {width: 1920, height:1080},
                {width: 1920, height:1200},
                {width: 2560, height:1440},
                {width: 3840, height:2160},
                {width: 4096, height:2160}
            ];

var left = 0;
var right = ResolutionsToCheck.length;
var selectedWidth;
var selectedHeight;
var mid;

function FindMaximum_WidthHeight_ForCamera()
{
    console.log("left:right = ", left, ":", right);
    if(left > right)
    {
        console.log("Selected Height:Width = ", selectedWidth, ":", selectedHeight);
        return;
    }

    mid = Math.floor((left + right) / 2);

    var temporaryConstraints = {
        "audio": true,
        "video": {
            "mandatory": {
            "minWidth": ResolutionsToCheck[mid].width,
            "minHeight": ResolutionsToCheck[mid].height,
            "maxWidth": ResolutionsToCheck[mid].width,
            "maxHeight": ResolutionsToCheck[mid].height
            },
        "optional": []
        }
    }

    navigator.mediaDevices.getUserMedia(temporaryConstraints).then(checkSuccess).catch(checkError);
}

function checkSuccess(stream)
{
    console.log("Success for --> " , mid , " ", ResolutionsToCheck[mid]);
    selectedWidth = ResolutionsToCheck[mid].width;
    selectedHeight = ResolutionsToCheck[mid].height;

    left = mid+1;

    for (let track of stream.getTracks())
    {
        track.stop()
    }

    FindMaximum_WidthHeight_ForCamera();
}
function checkError(error)
{
    console.log("Failed for --> " + mid , " ", ResolutionsToCheck[mid],  " ", error);
    right = mid-1;

    FindMaximum_WidthHeight_ForCamera();
}

Just call function FindMaximum_WidthHeight_ForCamera(). When operation will be completed then maximum video resolution will be stored in selectedWidth and selectedHeight variables. Here I am also attaching console output for my device:
//Console Output
left:right =  0 : 17
Success for -->  8   Objectheight: 768width: 1280__proto__: Object
left:right =  9 : 17
Failed for --> 13   Objectheight: 1200width: 1920__proto__: Object   NavigatorUserMediaError
left:right =  9 : 12
Success for -->  10   Objectheight: 900width: 1280__proto__: Object
left:right =  11 : 12
Failed for --> 11   Objectheight: 1000width: 1280__proto__: Object   NavigatorUserMediaError
left:right =  11 : 10
Selected Height:Width =  1280 : 900

I have tested this implementation using Chrome Version 57.0.2987.110 (64-bit) and Logitech, Inc. Webcam C270. But I think this solution should work in each scenario. Thank You.

A: Use:
var constraints = {
    video: {
        width: { ideal: 4096 },
        height: { ideal: 2160 }
    }
};

This will make the browser use the maximum resolution available, up to 4K. Works in Chrome 63, Edge 41 and Firefox 58.
Citing MDN regarding the use of ideal:

An ideal value, when used, has gravity, which means that the browser
  will try to find the setting (and camera, if you have more than one),
  with the smallest fitness distance from the ideal values given.

A: I agree with homm, his approach works fine: https://jsfiddle.net/evpozdniakov/c84ksucw/
var getUserMediaPrefixed,
    videoStream,
    videoTag;

setGumPrefix();

if (!getUserMediaPrefixed) {
    logMessage('Sorry, your browser doesn\'t support getUserMedia interface');
}
else {
    runCamera();
}

function dealWithStream(stream) {
    videoStream = stream;

    if (!videoTag) {
        videoTag = document.createElement('video');
        videoTag.addEventListener('resize', videoEventListener);
    }

    videoTag.src = window.URL.createObjectURL(stream);
    videoTag.play();
}

function handleError(e) {
    if (e.name == 'PermissionDeniedError') {
        logMessage('It looks like you\'ve denied access to the camera.');
    }
    else if (e.name == 'SourceUnavailableError') {
        logMessage('It looks like your camera is <b>used</b> by another application.');
    }
    else {
        logMessage('The camera is unavailable. The error message is: ' +e.message);
    }
}

function logMessage(msg) {
    var p = document.createElement('p');

    p.innerHTML = msg;

    document.getElementById('output').appendChild(p);
}

function runCamera() {
    var constraints = {
        audio: false,
        video: {
            optional: [
                {minWidth: 320},
                {minWidth: 640},
                {minWidth: 800},
                {minWidth: 900},
                {minWidth: 1024},
                {minWidth: 1280},
                {minWidth: 1920},
                {minWidth: 2560}
            ]
        }
    };

    navigator[getUserMediaPrefixed](constraints, dealWithStream, handleError);
}

function setGumPrefix() {
    if (navigator.getUserMedia) {
        getUserMediaPrefixed = 'getUserMedia';
    }
    else if (navigator.webkitGetUserMedia) {
        getUserMediaPrefixed = 'webkitGetUserMedia';
    }
    else if (navigator.mozGetUserMedia) {
        getUserMediaPrefixed = 'mozGetUserMedia';
    }
    else if (navigator.msGetUserMedia) {
        getUserMediaPrefixed = 'msGetUserMedia';
    }
}

function videoEventListener() {
    if (videoTag.videoWidth) {
        logMessage('Best captured video quality in your browser is ' +videoTag.videoWidth+ '×' +videoTag.videoHeight);

        // stop stream
        videoStream.stop();
        videoTag.src = '';
    }
}

In my case, Opera and Chrome offer max resolution 1280×720.
Firefox gives 640×480 by default, but you can improve his resolution as well up to 1280×720. Here you go:

A: You can check this utility to check the available resolutions of your devices:
https://webrtchacks.github.io/WebRTC-Camera-Resolution/
It is useful for troubleshooting purposes.
Hope you find it interesting!

A: You can always use applyConstraints() combined with getCapabilities() on the track.
Honza Kalfus' answer claims chrome now handles the ideal prop right for resolution. I didn't test that, but Chrome 83 still screws up ideal value for frameRate and simply wont start the video if outside of the capable range... so I hope this helps someone.
stream = await navigator.mediaDevices.getUserMedia({ video: { width: 100, height: 100, frameRate: { min: 8, max:60 }, facingMode: 'environment' } });
track = stream.getTracks()[0];
var frIdeal = 35;
constrs = track.getConstraints();
frCap = track.getCapabilities().frameRate;
if (frCap && "min" in frCap && "max" in frCap) {
  constrs.frameRate = Math.max(frCap.min, Math.min(frCap.max, frIdeal));
  track.applyConstraints(constrs);
}

this will give me 30hz if that is the maximum (Chrome83).
see also the MDN docs

A: APIs and standards have changed since these answers were posted so I will post my current solution to the max-res GUM problem. I've tried the "scanning" solutions, even binary search etc., all have resulted in a crashing webpage on mobile devices (e.g. iPhone iPad) while desktop browsers showed more resilience.
This is what I currently do to get max resolution (use advanced: [ and multiple width: { exact: s):

const video = $("#video")[0]

const constraints = {
  audio: false,
  video: {
    advanced: [
      { width: { exact: 2560 } },
      { width: { exact: 1920 } },
      { width: { exact: 1280 } },
      { width: { exact: 1024 } },
      { width: { exact: 900 } },
      { width: { exact: 800 } },
      { width: { exact: 640 } },
      { width: { exact: 320 } }
    ]
  }
};

$(document).ready(() => {
  navigator.mediaDevices
    .getUserMedia(constraints)
    .then((mediaStream) => {
      window.stream = mediaStream;
      video.srcObject = mediaStream;
    })
    .then(() => {
      return new Promise((resolve) => {
        video.onloadedmetadata = resolve;
      });
    })
    .then(async () => {
      console.log('Ready to work');
    })
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video id="video" autoplay muted playsinline />

A: I still don't know correct answer, but I do the following:
video: {
  optional: [
    {minWidth: 320},
    {minWidth: 640},
    {minWidth: 1024},
    {minWidth: 1280},
    {minWidth: 1920},
    {minWidth: 2560},
  ]
}

While single minWidth: 2560 expression resets resolution to default, series of minWidth expression make browser always takes maximum resolution on tested hardware.

A: I had varied success with defining ideal dimensions and trying to force the 'back' camera.
$video = document.getElementById('video')

//declare ideal values
var constraints = {
    audio: false,
    video: {
        width: { ideal: 1280 },
        height: { ideal: 1024 },
        facingMode: "environment"
    }
};

// enumerate devices and select the first camera (mostly the back one)
navigator.mediaDevices.enumerateDevices().then(function(devices) {
    for (var i = 0; i !== devices.length; ++i) {
        if (devices[i].kind === 'videoinput') {
            console.log('Camera found: ', devices[i].label || 'label not found', devices[i].deviceId || 'id no found');
            videoConstraints.deviceId = { exact: devices[i].deviceId }
        }
    }
});

//first up the stream
navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
    $video.srcObject = stream;
    // log the real size
    console.log($video.videoWidth, $video.videoHeight);
}).catch(function(err) {
    console.log(err.name + ': ' + err.message);
});