text:
Q: LocalJumpError (Ruby on Rails) I have searched/Googled around but I'm struggling with the following problem.
I am building a Rails 2.3.2 application and one of the requirements is to calculate the median of an array of results.  I am using code for calculating the median from the Ruby Cookbook but keep running in to a problem with receiving an error 'LocalJumpError - no block given' when I attempt to find the median of an array where there are an odd number of members.
The example code in my view is as follows:
<%= survey_response.median([6,4,5,4,4,2]) %>

Then in survey_response.rb model the methods are as follows:
def mean(array)
  array.inject(array.inject(0) { |sum, x| sum += x } / array.size.to_f)
end

def median(array,already_sorted=false)
  return nil if array.empty?
  array = array.sort unless already_sorted
  m_pos = array.size / 2
  return array.size % 2 == 1 ? array[m_pos] : mean(array[m_pos-1..m_pos])
end

The error is caused when the median method refers back to the mean method to get the media of an odd total of items in the array.  I just can't figure out why I get that error or indeed how to fix it - so I'd hugely appreciate any help/guidance/laughing anybody could offer me!
Thanks
Simon

A: Lis looks like it's due to you using a fractional index into the array. Try replacing:
m_pos = array.size / 2

with:
m_pos = (array.size / 2).ceil
Also, try changing your mean function to this:
def mean(array)
  array.inject(0) { |sum, x| sum += x } / array.size.to_f
end

A: Better code:
def mean(array)
  array.inject { |sum, n| sum + n } / array.length.to_f
end

def median(array)
  return nil if array.empty?
  array.sort!
  middle = array.length / 2
  (array.length % 2 == 1) ? array[middle] : mean([array[middle-1], array[middle]])
end

puts median([5,11,12,4,8,21]) # => 9.5

A: That mean method looks horribly botched. Try this:

def mean(array)
  a.inject(0) { |sum,x| sum += x } / a.size.to_f
end


text:
Q: Redux Toolkit - I can't update Slice state? I wanna update the state and tried few ways to do that, but I can't.
First, I got a problem with fetching state, as a result, I got proxy, not a state.
That is fixed by the current() function by the redux toolkit.
Next, where I have a problem is mutation main slice state.
Here is a reducer for mutating.
reducers: {
    setUser: (state, payload) => {
      console.log("before", current(state)); //init state
      state.currentUser = {
        ...state.currentUser,
        loggined: true,
      };
      console.log("after", current(state)); // here I have new state but...

    },
    clearUser: (state) => {},
  },

As a result, as a second console log, I got to state what I want, when I want to change a page or just want to do something with new data in the state, by  useSelector() redux function, as a result, I got old, not changed state.
Why has this happened?
Example of Slice state:
initialState: {
    currentUser: {
      loggined: false,
      isAdmin: false,
      jwt: false,
    },
  },

Thanks!

A: Reducers of createSlice use immer:

This object will be passed to createReducer, so the reducers may safely "mutate" the state they are given.

So you can either return a new object that is the new state or "mutate" it and not return it, from createReducer

you need to ensure that you either mutate the state argument or return a new state, but not both.

So you can do:
setUser: (state, payload) => {
  //state here is an immer draft, do not use that to copy current state
  console.log("before", current(state)); //init state
  state.currentUser.loggined = true;
  //not returning anyting
},

Not sure how you'd return a new state based on the old one since ...state makes a copy of the immer draft and not of the state. Can't even find examples of doing this unless it's an array.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flash AS2 getting button with dynamic action into movieClip class Note this has to be done in ActionScript 2 due to my audience player restricted to flash player 8.
I'm trying to build a simple class that extends the base Movieclip class.
I'm then applying this class to a movieclip in the library using the properties panel and giving it the class name in there. That much is working fine, and I'm able to use my class and methods etc. on that object after I've attached the movieclip tot he stage using attachMovie. What I can't seem to get to work is the button that I have within the movieclip. Originally I had a button set up within the library movieclip, however I can't seem to target that within my class. What I would like to do is simply set up a simple getURL type of thing within the button, but it doesn't seem to work.
I tried just assigning the onMouseDown handler within the class rather than a button, and that did work, but happened wherever I clicked on the stage rather than just over the graphic area. This had the effect of triggering all the other handlers on any other instances of the class that I had on the stage, so they all fire off at once. However, using onRollOver and onRollOut did work as I expected.
I've also tried setting up another button in the library and using this.attachMovie with my class to attach it, but I still can't seem to get a handle for it.
I've created a very simple test script to try and illustrate what I'm trying to do:-
class Test extends MovieClip {

    public function Test() {
        // constructor code
        this.attachMovie("theButton" , "myButton" , _root.getNextHighestDepth() )
        this.myButton.onMouseDown = clickMe;
        this._x = Math.random() * 800;
        this._y = Math.random() * 400;
    }

    public function clickMe() {
        trace("I have been clicked"+this._name);
    }

}

So, the question is, how do I attach (or have present in the movieclip) a button, that I can provide an onMouseDown or onMouseUp type handler for that button that will only work if I click on the actual button? What am I doing wrong here ... I've tried loads of different ideas, but nothing seems to be working. Remember it's AS2 not AS3. Thanks.

A: Three points:

*

*Remember, attachMovie returns a reference to the newly
attached movieclip; use this to your advantage.

*Also, onRelease is the preferred way, it is most associated with a
click, see this SO post "What is the difference between the
onMouseUp/Down and onPress/Release events in Flash?".

*Lastly, when getting the next highest depth (with
getNextHighestDepth), remember each MovieClip has its own depth
system (even though, internally there is a single global one), so
always find the depth relative to the MC you're attaching too. Since
attachMovie is being called on this, then getNextHighestDepth
should be called on this.
Updated Code:
class Test extends MovieClip {
    public function Test() {
        var btn = this.attachMovie("theButton" , "myButton" , this.getNextHighestDepth() );
        // "bnt" is now the button instance, while "this" is still the Test mc
        btn.onRelease = btn.onReleaseOutside = this.clickMe; // i roped in onReleaseOutside, but this might not be necessary
        this._x = Math.random() * 800;
        this._y = Math.random() * 400;
    }
    public function clickMe() {
        trace("I have been clicked"+this._name);
    }
}


text:
Q: Trying to access a list I've filled up in form 1 on form 2 but the list is empty? So let me start of by saying I'm extremely new to coding ( followed a course about general programming logic ) and am now messing around with c# winforms. I'm trying to create the game charades in c# winforms and have gotten pretty far already. My form 1 handles all the game setup ( number of players, naming the players, etc ... ), I have a "player" class to create objects and learn myself OOP which seems to be the general way to go with C# from what I've read. However now that I'm trying to work on form 2 it seems the list from the "player" class I've filled up in form 1 is empty when I try to access it on form 2.
Quick rundown on what I'm doing;
-Form 1 loads by default and I put in the number of players and name each player which I then add to a list through a method created in the "player" class.
-Once all players have been named form 1 closes and form 2 opens ( found a bit of code online to get this to work by making a bool switch, when it's set to true it'll execute some code in program.cs to do "Application.run(form2)" so the program can stay active when closing form 1 and showing form 2.
-On form 2 I'm trying to access the list from the "player" class which I can do without a problem by creating a new object of the "player" class in form 2 and creating a method that gets the list from that class, but when I do it's completely empty.
here's the code from form 1, form 2 and player class.
form1 :
    using System;
using System.Security.Cryptography.X509Certificates;
using System.Windows.Forms;

namespace Pictionary
{
    public partial class Form1 : Form
    {
        public bool Form2Loaded { get; set; }
        private int aantalKliks = 0;
        private int aantalSpelers = 0;

    public Spelers speler1 = new Spelers();
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void pictionaryTitle_Click(object sender, EventArgs e)
    {

    }

    private void buttonSpelregels_Click(object sender, EventArgs e)
    {
        MessageBox.Show(
            $"1 - Kies of iedereen voor zichzelf speelt of in teams.{Environment.NewLine}2 - Geef de namen van de spelers in of een team naam per team.{Environment.NewLine}3 - Er word een speler of team gekozen om het woord uit te beelden. Druk op de knop om het woord zichtbaar/onzichtbaar te maken. Druk op de start knop om de ronde te beginnen.{Environment.NewLine}4 - De andere spelers/team hebben 60 seconden de tijd om het woord te raden. Kies de juist optie om de punten toe te voegen.{Environment.NewLine}5 - Druk op de knop stop spel om het spel te stoppen en de punten te laten zien.",
            "Spelregels");
    }

    private void buttonFreeforall_Click(object sender, EventArgs e)
    {
        flowLayoutPanel1.Show();
        buttonBack.Show();
        buttonTeams.Hide();
        buttonFreeforall.Hide();
        buttonSpelregels.Hide();
    }

    private void buttonBack_Click(object sender, EventArgs e)
    {
        flowLayoutPanel1.Hide();
        buttonBack.Hide();
        buttonTeams.Show();
        buttonFreeforall.Show();
        buttonSpelregels.Show();
        radioButton2.Checked = false;
        radioButton3.Checked = false;
        radioButton4.Checked = false;
        radioButton5.Checked = false;

    }

    private void radioButton2_CheckedChanged(object sender, EventArgs e)
    {
        flowLayoutPanel1.Hide();
        buttonBack.Hide();
        textBox1.Show();
        buttonAddName.Show();
        aantalSpelers = 2;
    }

    private void radioButton3_CheckedChanged(object sender, EventArgs e)
    {
        flowLayoutPanel1.Hide();
        buttonBack.Hide();
        textBox1.Show();
        buttonAddName.Show();
        aantalSpelers = 3;
    }

    private void radioButton4_CheckedChanged(object sender, EventArgs e)
    {
        flowLayoutPanel1.Hide();
        buttonBack.Hide();
        textBox1.Show();
        buttonAddName.Show();
        aantalSpelers = 4;
    }

    private void radioButton5_CheckedChanged(object sender, EventArgs e)
    {
        flowLayoutPanel1.Hide();
        buttonBack.Hide();
        textBox1.Show();
        buttonAddName.Show();
        aantalSpelers = 5;
    }

    private void buttonAddName_Click(object sender, EventArgs e)
    {
        if (textBox1.Text == "" || textBox1.Text == "Speler Toegevoegd!")
        {
            MessageBox.Show("Naam mag niet blanco zijn!");
        }

        else
        {
            switch (aantalKliks)
            {
                case 0:
                    speler1.naamSpeler = textBox1.Text;
                    speler1.SpelerNaarLijst();
                    break;

                case 1:
                    speler1.naamSpeler = textBox1.Text;
                    speler1.SpelerNaarLijst();
                    break;

                case 2:
                    speler1.naamSpeler = textBox1.Text;
                    speler1.SpelerNaarLijst();
                    break;

                case 3:
                    speler1.naamSpeler = textBox1.Text;
                    speler1.SpelerNaarLijst();
                    break;

                case 4:
                    speler1.naamSpeler = textBox1.Text;
                    speler1.SpelerNaarLijst();
                    break;

            }

            textBox1.Text = "Speler Toegevoegd!";

            aantalKliks = aantalKliks + 1;
        }
        if (aantalKliks == aantalSpelers)
        {
            this.Close();
            Form2Loaded = true;

        }
    }
}

}
form 2
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Pictionary
{
public partial class Form2 : Form

#region generatedCode

{
    public Spelers speler1 = new Spelers();

    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {

    }

    private bool buttonSwitch = false;

    private void buttonToggleWord_Click(object sender, EventArgs e)
    {
        buttonSwitch = !buttonSwitch;

        if (buttonSwitch == true)
        {
            labelWoord.Text = "Woord: test";

        }

        else
        {
            labelWoord.Text = "Woord: ";
        }
    }

}
#endregion

}
player class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pictionary
{
public class Spelers
{
    //Attributes
    public string naamSpeler;
    public List<string> spelerLijst = new List<string>();

    //constructors

    //methods
    public void SpelerNaarLijst()
    {
        spelerLijst.Add(naamSpeler);
    }``

}

}
Any help and even some explanation as to why it's not working is greatly appreciated !


text:
Q: How to convert Razor Page to String in Controller Just want to ask on how to convert the whole Razor page(.cshtml) into string in Controller.
i have a created an Action Template below:
public ActionResult Template()
    {
        return View();
    }

and in the page it shows below:

        Test1 #           : Value1

        Test2                 : Value2

        Test2             : Value3

        Test3 :           : Value4

        Test4             : Value5

        Test5 Change      : Value6

how do i convert that into string?


text:
Q: Getting error Use of uninitialized value $col2 in hash element at lol.pl line 13, <$f2> line 1 I made a program to filter out the rows containing a value from a text file...i am getting this error

Use of uninitialized value $col2 in hash element at lol.pl line 13,
   line 1.

use strict;
use warnings;
my %keys;
open( my $f1, '<', 'jump.txt' ) or die("Cannot open jump.txt: $!");
while (<$f1>) {
    chomp;
    $keys{$_} = 1;
}
close($f1);
open( my $f2, '<', 'sym.txt' ) or die("Cannot open sym.txt: $!");
while (<$f2>) {
    my ( undef, $col2, undef ) = split( ' ', $_ );
    print if ( $keys{$col2} );
}
close($f2);

jump.txt:
a
b
c

sym.txt:
a   1
b   2
c   3
d   4
e   5

desired output:
a   1
b   2
c   3

A: When you use warnings (as you should) you will get a warning when you try to use an uninitialized variable:
perl -wE 'my $x; say $x'

Output:
Use of uninitialized value $x in say at -e line 1.

In a list assignment, extra values are silently ignored and if you have too many variables, the extras get the value undef.
perl -wE 'my ($x, $y) = (2); say $y'

Output:
Use of uninitialized value $y in say at -e line 1.

In your case, it is likely that the problem is this line:
my(undef, $col2, undef) = split(' ', $_);

If split returns only a single item (or zero items), $col2 will be undefined.
See also documentation on "List value constructors" in perldata
Edit:
To get the desired output (seems like you need $col1 and not $col2):
my $col1  = (split(' ', $_))[0];
print if $keys{$col1};


text:
Q: how to redirect page in server uses header <?php
     }
      else
      {
         $uname=$_POST['uname'];
            $password=$_POST['pass'];
          require('connect.php');
        global $pdo;
             $stmt=$pdo->prepare("select name,pass from admin where name=?");
             $stmt->bindparam(1,$uname);
              $stmt->execute();
               $row=$stmt->fetch(PDO::FETCH_ASSOC);
              if($row['name']==$uname and $row['pass']==$password)
        {
        $_SESSION['user']=$uname;
        $host  = $_SERVER['HTTP_HOST'];
                     $uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/');
                       $extra = 'principal.php';
                    header("Location: http://$host$uri/$extra");

        }
        else
        {
        echo"your password and username incorrect";
         header('Location:http://localhost/adminp.php');
        }
          unset ($pdo);
          }
             ob_end_flush();
                  ?>

header for redirect page not working
in my local host code(header('Location:mypage.php') working fine but in server is not working

A: you have to use ob_start(); at top of the code and ob_flush(); at the bottom of your code.
then use header code as follow -
header('Location:adminp.php');

A: remove the echo statement above the header tag,
and please mention the error in your question .. if you get the error like header already sent then you remove the echo statement otherwise you try java script method like
 else
        {
        echo"your password and username incorrect";
        ?>
        <script>
          window.location='admin.php';
       </script>
   <?php
        }


text:
Q: Creating multiple page application using react I have created SPA using react and hence my address bar does not change when I move to another view.Kindly help in changing the address bar. News feed Code is
import React from 'react';
import axios from 'axios';
import Stories from './Stories';
export default class NewsFeed extends React.Component {
    constructor(props) {
        super(props);
        this.state = { feed: [], showPopUp: false, showStoryPopUp: false, readArr: [], importantArr: [], counterArr: [], deleteArr: [] };
        this.handleClose = this.handleClose.bind(this);
        this.handleCreateFeed = this.handleCreateFeed.bind(this);
        this.handlePost = this.handlePost.bind(this);
        this.handleCreateStories = this.handleCreateStories.bind(this);
    }
    componentWillMount() {
        let self = this;
        axios.get('src/rest/feed.json')
            .then(function (response) {
                let counterArr = self.state.counterArr;
                let readArr = self.state.readArr;
                let deleteArr = self.state.deleteArr;
                for (let item of response.data) {
                    counterArr.push(0);
                    readArr.push(false);
                    deleteArr.push(false);
                }
                self.setState({ feed: response.data });
            })
            .catch(function (error) {
                console.log(error);
            });
    }
    changeImportant(index) {
        let arr = this.state.importantArr;
        arr[parseInt(index)] = !arr[parseInt(index)];
        this.setState({ importantArr: arr });
    }
    changeReadFlag(index) {
        let arr = this.state.readArr;
        arr[parseInt(index)] = !arr[parseInt(index)];
        this.setState({ readArr: arr });
    }
    decrement(index) {
        let arr = this.state.counterArr;
        arr[parseInt(index)] = arr[parseInt(index)] - 1;
        this.setState({ counterArr: arr });
    }
    handleDelete(index) {
        let arr = this.state.deleteArr;
        arr[parseInt(index)] = !arr[parseInt(index)];
        this.setState({ deleteArr: arr });
    }
    increment(index) {
        let arr = this.state.counterArr;
        arr[parseInt(index)] = arr[parseInt(index)] + 1;
        this.setState({ counterArr: arr });
    }
    handlePost(header, description,broker) {
        // console.log(document.querySelector("#title-input").value,document.querySelector("#description-input").value)
        let tempObj = { imgsrc: "images1.jpg" };
        // tempObj.header = document.querySelector("#title-input").value;
        // tempObj.description = document.querySelector("#description-input").value;
        tempObj.header = header;
        tempObj.description = description;
        tempObj.broker = broker;
        let tempArr = this.state.feed;
        tempArr.push(tempObj);
        let counterArr = this.state.counterArr.push(0);
        this.setState({ showStoryPopUp: false });
    }
    handleClose() {
        this.setState({ showPopUp: false, showStoryPopUp: false })
    }
    handleCreateFeed() {
        this.setState({ showPopUp: true });
    }
    handleCreateStories() {
        this.setState({ showStoryPopUp: true });
    }

    render() {
        return (

                {this.state.showStoryPopUp ? <Stories handlePost={this.handlePost} handleClose={this.handleClose} /> : null}
                {this.props.userType === 'admin' ? <button id="story-btn" type="button" className="btn btn-primary fixed-cls fa fa-pencil" style={{ display: this.state.showPopUp || this.state.showStoryPopUp ? 'none' : 'inline-block' }} onClick={this.handleCreateStories} >  Create Stories</button> : null}

                {this.state.feed.map((feed, index) => {
                    return (

{feed.header}

                        {feed.description}

 0 ? "vote-cls upvote" : "vote-cls downvote"}>
                                        {this.state.counterArr[index]}

                                <button id="read" className="btn btn-success fa fa-pencil" onClick={this.changeReadFlag.bind(this, index)}> Read </button>
                                <button id="delete" className="btn btn-danger fa fa-trash-o" onClick={this.handleDelete.bind(this, index)}> Delete </button>
                                <button className="btn btn-primary fa fa-exclamation" onClick={this.changeImportant.bind(this, index)}> Important </button>

)
                })}

        );
    }

}

stoies code is
import React from 'react';

export default class Stories extends React.Component {
    constructor(props) {
        super(props);
        this.handleClose = this.handleClose.bind(this);
        this.handlePost = this.handlePost.bind(this);

    }
    handleClose() {
        this.props.handleClose();
    }
    handlePost(){
        let header = document.querySelector("#title-input").value;
        let description = document.querySelector("#description-story-input").value;
        let broker = document.querySelector("#broker-input").value;
        this.props.handlePost(header,description,broker);
    }

    render() {
        return (

Create Stories

                                Title

                                <input type="text" id="title-input" />

                                Description
                             <textarea rows="4" cols="50" id="description-story-input"></textarea>

                                Broker
                             <input type="text" id="broker-input" />

                                Ticker
                             <input type="text" id="ticker-input" />

                                Category
                             <input type="text" id="category-input" />

                                Direction
                             <input type="number" min="-2" max="2" defaultValue="0" id="direction-input" />

                                Rating
                             <input type="number" min="-5" max="5" defaultValue="0" id="rating-input" />

                                Score
                             <input type="number" min="-4" max="4" defaultValue="0" id="score-input" />

                                Trade Price
                             <input type="text" id="trade-price-input" />

                                Pre Trade Price
                             <input type="text" id="pre-trade-input" />

                                Attachment
                             <input type="file" id="attachment-input" />

                                Links
                             <input type="text" id="links-input" />

                                Percentage Change
                             <input type="text" id="percentage-change-input" />

                                Tags
                             <input type="text" id="tag-input" />

                            <button onClick={this.handlePost}  id="post-btn" type="button" className="btn btn-primary fa fa-envelope" > Post</button>

);
    }

}

login code is
    import React from 'react';
    import axios from 'axios';
export default class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = { login: false, userName: '', password: '' ,isValid : true};
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleChangeUserName = this.handleChangeUserName.bind(this);
        this.handleChangePassword = this.handleChangePassword.bind(this);
    }
    handleSubmit() {
        let self = this;

        axios.get('src/rest/login.json')
            .then(function (response) {
                response.data.map((user)=>{
                    if(user.userName === self.state.userName && user.password === self.state.password ){
                        self.props.setLogin( true,user.role);
                        self.setState({isValid :true })
                    }else{
                        self.setState({isValid :false })
                    }
                });
            })
            .catch(function (error) {
                console.log(error);
            });
    }
    handleChangeUserName(event){
        this.setState({userName : event.target.value});
    }
     handleChangePassword(event){
        this.setState({password : event.target.value});
    }

    render() {
        return (

Login

Invalid username or password

                    <input className="col-md-6" type="text" placeholder="User ID/Email" onChange={this.handleChangeUserName}/>

                    <input className="col-md-6" type="password" placeholder="Password" onChange={this.handleChangePassword} />

SUBMIT

        );
    }

}

All three have same address.

A: I'm not sure how you are navigating without routes unless you are showing/hiding components.  You could look into implementing the hash router


text:
Q: ID process making HTTP request My firewall is detecting my ubuntu server calling a URL on port 80 sporadically. I'd like to ID the process making the callout, but the connection is always gone by the time I can run a netstat.
A lot of the usual network tools (iptables, tcpdump) seem to only catch the traffic, not the process.
I would like a way to catch this process calling out so I can ID it and put a stop to it or understand why it's doing it (it's calling fortnitecontent-website-prod07.ol.epicgames.com, which makes zero sense to me as it's the mediaserver with no games being played on it).
Thanks!


text:
Q: Como agregar un boton de impresion a un reporte personalizado ya existente Odoo v11 cree hace un tiempo un reporte personalizado en el modulo de contabilidad un reporte personalizado.. que funciona bastante bien.. ahora lo que me gustaria hacer es agregarle un button en el header como el que tiene por defecto pero que este relacionado con mi reporte personalizado
<report
        id="account_invoices"
        model="account.invoice"
        string="Factura pre-impresa"
        report_type="qweb-pdf"
        name="custom_report_module.report_custom_template"
        file="custom_report_module.report_custom_template"
        attachment_use="True"
        attachment="(object.state in ('open','paid')) and
            ('INV'+(object.number or '').replace('/','')+'.pdf')"
    />

Asi es como llamo a mi reporte que aparece en la lista desplegable, despues lo que intento es agregarle el button pero simplemente no me funciona
<record id="account_invoices_button" model="account.invoice">
        <field name="name">account.invoice.form</field>
        <field name="model">account.invoice.form</field>
        <field name="inherit_id" ref="custom_report_module.report_custom_template"/>
        <field name="arch" type="xml">
            <button name="check_confirm_bank" position="after">
                <button name="print_bank_statement" string="Print Statement" type="object" help="Print in Pdf"/>
            </button>
        </field>

    </record>

Alguna ayuda???


text:
Q: Prove true in natural numbers (Peano Arithmetic) While reviewing old exercise sheets, I have found this question and am having difficulties understanding some of the logic:
Let $\mathbb{N}$(natural numbers) be a model for Peano Arithmetic, that means $\mathbb{N}$$\vDash$PA. Choose which of the following sentences are true in $\mathbb{N}$.
(a) $\lnot$$\exists$x((sx=0)$\to$(0=s0)) $\to$ (($\lnot$$\exists$x(sx=s0))$\to$(0=s0))
(b) (($\lnot$$\exists$x(sx=s0))$\to$(0=s0)) $\to$ $\lnot$$\exists$x((sx=s0)$\to$(0=s0))
(c) (($\exists$x(sx=0))$\to$(0=s0)) $\to$ $\exists$x((sx=s0)$\to$(0=s0))

For (a) I would say that it is true in $\mathbb{N}$, because if you set $\color{red}{x=0}$ then you get $\lnot$$\exists$x((s$\color{red}{0}$=0)$\to$(0=s0)) which is true. Then the second part of the implication I would also set x=0 again and in the end that part ends up also being true, so we have True implies True, hence (a) is true in $\mathbb{N}$.
For (b) I would start off by letting x=0 so then I would get (($\lnot$$\exists$x(s0=s0)) , which is false, and I can see that (0=s0) is also false, so False to False, hence first part of the implication is True.
Now this is is where i have run into some confusion. My professor had solved the second part of the implication by setting $\color{red}{x=s0}$,so we then have, $\lnot$$\exists$x((s$\color{red}{s0}$=s0)$\to$(0=s0)) , and this part would be false, so all together True to False, hence (b) is false in $\mathbb{N}$.
I can not understand the logic behind setting x=s0 in (b). Why is that allowed, when in (a) we didn't do that.
It would be greatly appreciated, if someone could please explain this and also provide some guidance for (c).

A: For (b) :

$[¬∃x(sx=s0) → (0=s0)] → ¬∃x[(sx=s0)→(0=s0)]$

the "strategy" of you teacher is to prove it false showing that the antecedent is true and the consequent false.
But the RHS conditional is negated; thus we want that both the LHS : $¬∃x(sx=s0) → (0=s0)$ and the un-negated part of the RHS : $∃x((sx=s0)→(0=s0))$ are true.

i) Consider the LHS; it has $0=s0$ in the consequent, and this is always false (it means : $1=0$).
So, we have to find a value for $x$ such that the antecedent of the LHS conditional : $¬∃x(sx=s0)$ is false.
But $¬∃x(sx=s0)$ is false, because we can find some value for $x$ such that $sx=s0$ is true... it is enough to choose $0$ as value for $x$.
Thus, it is true that "there are values for $x$ such that $sx=s0$ holds", and so the negation of this sentence, i.e. $¬∃x(sx=s0)$ is false.

ii) Conider now the RHS; we want that the un-negated formula : $∃x((sx=s0)→(0=s0))$ is true.
So, the question is : can we find a value $n$ for $x$ such that : $(sn=s0)→(0=s0)$ is true ?
Again, we have the false consequent : $(0=s0)$; thus, in order to "verify" the conditional, we need a value $n$ for $x$ such that $(sn=s0)$ is false.
Now it is enough to choose $1$ (as our $n$) as value for $x$ and we have : $2 \ne 1$, i.e. :

$\lnot (ss0=s0)$;

this shows that "there are values for $x$ such that $sx=s0$ does not hold", i.e. $sx=s0$ is false for some value of $x$.
Summing up, we can find a value for $x$ such that $(sx=s0) \rightarrow (0=s0)$ is : $False \rightarrow TRUE$, i.e. $TRUE$, and so the sentence $∃x[(sx=s0) \rightarrow (0=s0)$ is true.

For (c), taking into account that in $\mathbb N$ $(0=s0)$ is false, we can rewrite it as :

$(∃x(sx=0) → FALSE) → ∃x((sx=s0) → FALSE)$.

Now, it is quite simple to find its truth value : $∃x(sx=0)$ is false in $\mathbb N$, because $0$ is not the successor of any number. Thus, we have :

$(FALSE → FALSE) → ∃x((sx=s0) → FALSE)$, i.e.
$TRUE → ∃x((sx=s0) → FALSE)$.

Now, in order to have it true, we need a true consequent, and so we have to check if we can "verify" $∃x((sx=s0) → FALSE)$. Again, the only way to "verify" it is to find a value for $x$ such that $(sx=s0) → FALSE$ is true, i.e.  we have to find a value for $x$ such that $(sx=s0)$ is false.
So, it is enough to choose $1$ and we have a value for $x$ such that $(sx=s0) → FALSE$ is true, i.e. $∃x((sx=s0) → FALSE)$ is true in $\mathbb N$, and also the complete formula is.


text:
Q: How to interpret best score from GridSearch? I train different classifiers with different set of data and I need to understand how can I properly measure effectiveness of classifier.
Here's my code:
iris = load_iris()

param_grid = {
    'criterion': ['gini', 'entropy'],
    'max_depth': np.arange(4, 6)
}

tree = GridSearchCV(DecisionTreeClassifier(), param_grid)
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target)

tree.fit(X_train, y_train)
tree_preds = tree.predict(X_test)
tree_performance = accuracy_score(y_test, tree_preds)

print 'Best params: ', tree.best_params_
print 'Best score: ', tree.best_score_
print 'DecisionTree score: ', tree_performance

Question is, what actually is a best score from GridSearchCV? And how it differs from results used in accuray_score function?
As I understand, accuracy_score takes classes of test set and compares it with results predicted by algorithm. The result is the percentage of properly classified items. But what is best_score_?
These two values are different and an example output from my script looks like this:
Best score:  0.955357142857
DecisionTree score:  0.947368421053

A: GridSearchCV does not take into account your test set (looking closely, you'll see that you don't pass your test set in tree.fit()); the score it reports, best_score_, comes from a cross-validation (CV) in your training set. From the docs:

best_score_ : float
Mean cross-validated score of the best_estimator

This score itself (0.955 in your example) is the mean value of the score in each one of the (default, since you have not specified the cv argument) 3 CV folds.
Your accuracy_score, on the other hand, comes from your test set.
That clarified, it should be obvious that these two numbers are not the same; on the other hand, and provided that both the CV procedure and the train-test split have been performed correctly, they should not be much different, too, which is arguably your case here.


text:
Q: A little confusion about compactness and connectedness This question may be a bit simple or even naive for some people but it indeed confuses me for a long time. Thank you all if you provide any explanation.
I know concepts: compactness means any open cover have finite subcover, which is equivalent to closed and bounded; connectedness means there's no disjoint decomposition by two nonempty open sets. However, I have no idea how they play roles in particular cases. I read many theorems that require compact and connected topology but there's no any mention in their proofs.
The situation occurs frequently, as far as I concern, in differential geometry and multivariable calculus (vector fields). Could anyone explain to me how they involve in mathematics? A few examples are better welcomed.
Please let me give some examples

*

*Why do we consider compact Lie group in differential geometry? What role does compact here play here?

*Why do we require compactness of manifold when we consider de Rham cohomology?

A: The prototypical examples are:

*

*A continuous real function on a compact subset of the real line attains a maximum. This is Weierstrass's extreme value theorem.

*A continuous real function on a connected subset of the real line attains every value between two values. This is the intermediate value theorem.
In topological terms, these are stated thus:

*

*The image of a continuous function on a compact space is compact.

*The image of a continuous function on a connected space is connected.
What is sometimes confusing is that the prototypical examples are usually both stated for closed intervals and these are exactly the compact connected subsets of the real line.
However, even in the real line, a set may be compact without being connected, as in $[0,1] \cup [2, 3]$, and a set may be connected without being compact, as in $(0,1)$.

A: A classic result in Differential Geometry is that $\mathbb R$ and $\mathbb R^2$ are not homeomorphic. If you take a single point out of $\mathbb R$ you break it into two disconnected pieces. If you take a single point out of $\mathbb R^2$ you still have one connected piece.
If you haven't yet covered homeomorphisms, it doesn't matter, it's a simple way of seeing that the two spaces have a different "type".
None the less, with respect, lhf's answer does cover two fundamental theorems in calculus that show the importance of compactness and connectedness.
Cohomolgy is a pretty vast subject. Open coverings play a significant role. If you can have finite covers then counting the intersections of the covering sets is well defined. There are examples, though, where compactness is not required. Paracompactness enables you to have locally finite combinations of intersecting covering sets.
The aspect of compactness that is often important is completeness which is why we go to a lot of trouble having equivalent definitions of compactness. The unit ball in a separable infinite dimensional Hilbert space is not compact so you have to find special subsets that are compact. The open covering definition is useful but maybe doesn't highlight the main reason why we need it in some contexts.

A: As to why one often cares about compact Lie groups and, more generally, compact spaces, one answer (of many!) is that functions on compact spaces are "well-behaved", in the sense that the function cannot grow without bound and cannot oscillate wildly.
This becomes relevant when one wishes to use analytical tools, such as Hodge-de Rham theory, index theorems, etc., to study properties of the underlying topological space (usually manifold). On a compact manifold ($M$), one needn't worry about the behavior of functions as they tend to infinity: every $C^\infty$ function is bounded and has finite mass, hence is $L^p$ for each $p\in[1,\infty]$.
For (semisimple) Lie groups in particular, compact Lie groups are very "nice". They admit unit-mass bi-invariant measures ("Haar measure") and every irreducible representation is finite-dimensional. Non-compact Lie groups, on the other hand, have much subtler representation theory. For instance, there is a continuous series of irreducible representations of $SL(2,\mathbb{R})$ acting on $C^\infty(\mathbb{H}^2)$.


text:
Q: Pytest mock: how to patch an import statement inside a function I have a function which imports a module inside a function. Something like following snippet
def parse_file(self, filename):
    if(filename.endswith("json"):
         import custom_json_parser   # <--- How to patch this.?
         return custom_json_parser.extract_file(filename)

For following reasons I have to patch it,

*

*I don't have custom_json_parser in my environment

*Or I don't want to unit test it again while I am unit testing parse_file function

How can we patch such dynamically imported modules.?
I am looking for something like the following snippet. (the following snippet is just pseudocode & not correct syntax wise & would give exception)
@patch("file_name.parse_file.custom_json_parser", autospec=True)
def test_parse_file(self, patch_custom_json_parser)
    . . .

Edit:
The import statement in a module can be easily patched. But what I am struggling though is the import statement inside a function. When a function imports a module, it will not be imported as a global module and will only reside in the local memory of the function.


text:
Q: Would it be faster / using less memory to return in each case of if else? Recently I got a code example (see code #1) in my CS study and I try to elicit if my second version of the code would be faster or using less memory.
Do you have an answer for my question?
// Code #1
double f(double b, double x)
{
    double s;
    if (x == 0.0)
        s = 1.0;
    else
        s = sin(x)/x;
    return s + b;
}

// Code #2
double f(double b, double x)
{
    // I thought this would be faster and using less memory due to
    // not declaring a new double
    if (x == 0.0)
        return 1.0 + b;
    else
        return sin(x)/x + b;
}

Thank you guys for your help.

A: It depends on the compiler and optimization flags. In general both codes will give the same outcome.

A: I have generated assembly of both cases.
Case 1:
        push    rbp
        mov     rbp, rsp
        sub     rsp, 48
        movsd   QWORD PTR [rbp-24], xmm0
        movsd   QWORD PTR [rbp-32], xmm1
        pxor    xmm0, xmm0
        ucomisd xmm0, QWORD PTR [rbp-32]
        jp      .L2
        pxor    xmm0, xmm0
        ucomisd xmm0, QWORD PTR [rbp-32]
        jne     .L2
        movsd   xmm0, QWORD PTR .LC1[rip]
        movsd   QWORD PTR [rbp-8], xmm0
        jmp     .L4
.L2:
        mov     rax, QWORD PTR [rbp-32]
        mov     QWORD PTR [rbp-40], rax
        movsd   xmm0, QWORD PTR [rbp-40]
        call    sin
        divsd   xmm0, QWORD PTR [rbp-32]
        movsd   QWORD PTR [rbp-8], xmm0
.L4:
        movsd   xmm0, QWORD PTR [rbp-8]
        addsd   xmm0, QWORD PTR [rbp-24]
        leave
        ret
.LC1:
        .long   0
        .long   1072693248

Case 2:
        push    rbp
        mov     rbp, rsp
        sub     rsp, 32
        movsd   QWORD PTR [rbp-8], xmm0
        movsd   QWORD PTR [rbp-16], xmm1
        pxor    xmm0, xmm0
        ucomisd xmm0, QWORD PTR [rbp-16]
        jp      .L2
        pxor    xmm0, xmm0
        ucomisd xmm0, QWORD PTR [rbp-16]
        jne     .L2
        movsd   xmm1, QWORD PTR [rbp-8]
        movsd   xmm0, QWORD PTR .LC1[rip]
        addsd   xmm0, xmm1
        jmp     .L4
.L2:
        mov     rax, QWORD PTR [rbp-16]
        mov     QWORD PTR [rbp-24], rax
        movsd   xmm0, QWORD PTR [rbp-24]
        call    sin
        divsd   xmm0, QWORD PTR [rbp-16]
        addsd   xmm0, QWORD PTR [rbp-8]
.L4:
        leave
        ret
.LC1:
        .long   0
        .long   1072693248

There is no difference.So, there is no speed optimization between them. So, code optimization depends on compiler.

A: Only declaring variable is not only thing that occupy memory.
int a = 1 + 2;
int b = 3;
int c = a + b;

This code will take same value as bellow code
int c = 1 + 2 + 3;

Because at the end processor will take one operation at a time in single core.
Second code add two number and hold it in stack and then take third number to add in result of first two number.

A: Short answer: don't worry about it!
Long answer:
sin will take by far the most time in this function, so a couple of additional instructions, if any, will not have any noticeable effect.
Though when in doubt, look at the generated code.
With GCC 6.3 on x86_64, the first version uses 1 more register (xmm2) but the optimizer is able to reorder instructions better.
Version 1:
        ucomisd xmm1, QWORD PTR .LC1[rip]
        movapd  xmm2, xmm0
        jp      .L5
        movsd   xmm0, QWORD PTR .LC0[rip]
        je      .L7
.L5:
        movapd  xmm0, xmm1
        sub     rsp, 24
        movsd   QWORD PTR [rsp+8], xmm2
        movsd   QWORD PTR [rsp], xmm1
        call    sin
        movsd   xmm1, QWORD PTR [rsp]
        movsd   xmm2, QWORD PTR [rsp+8]
        add     rsp, 24
        divsd   xmm0, xmm1
        addsd   xmm0, xmm2
        ret
.L7:
        addsd   xmm0, xmm2
        ret

Version 2:
        ucomisd xmm1, QWORD PTR .LC0[rip]
        jp      .L2
        je      .L10
.L2:
        sub     rsp, 24
        movsd   QWORD PTR [rsp], xmm0
        movapd  xmm0, xmm1
        movsd   QWORD PTR [rsp+8], xmm1
        call    sin
        movsd   xmm1, QWORD PTR [rsp+8]
        divsd   xmm0, xmm1
        addsd   xmm0, QWORD PTR [rsp]
        add     rsp, 24
        ret
.L10:
        addsd   xmm0, QWORD PTR .LC1[rip]
        ret

So how much is the difference in performance between these two versions? Only a performance test can tell for sure (but my guess is you won't see any difference).


text:
Q: Difference between SelectItem[] manufacturerOptions and List manufacturerOptions May be a stupid question,If I use List<SelectItem> instead of SelectItem[], the datatable filtering showcase doesn't work at all in primefaces datatable filtering example
In the Showcase TableBean.java, This works
private SelectItem[] manufacturerOptions;
manufacturerOptions = createFilterOptions(manufacturers);

But If I use
List<SelectItem> manufacturerOptions:
manufacturerOptions = createFilterOptions(manufacturers);

Filter doesn;t work
XHTML
<p:column id="manufacturerColumn" filterBy="#{car.manufacturer}"
                headerText="Manufacturer" footerText="exact"
                filterOptions="#{tableBean.manufacturerOptions}"
                filterMatchMode="exact">
            <h:outputText value="#{car.manufacturer}" />
        </p:column>

A: Sounds like <p:column> only supports arrays and no lists. So it is either simply not supported or a bug. You should report this to the PrimeFaces team.


text:
Q: TCP/IP Socket Programming Static Web IP between Dynamic IP I am confused about TCP/IP Socket Programming. I know the internet protocols but in theory...
I am explaining my problem (what i need )
I have a server working on X.X.X.X IP Adress. And it always listens to Y PORT.
When i want to connect that server on MY PC, i have no problem because i wrote the ip adress (X.X.X.X) and the port (Y) and my PC connects..
When i connect to server server keeps my ip adress and my local ip adress.. After that connection is end.
Here is my problem starting...
As i sad my server knows my local PC informations. How can i connect to my local PC on server my web server and sent TCP or UDP packets ? I did port forwarding on my modem but i dont want it. When i did port forwarding there is no problem but i dont want it ...
Thanks for replies and sorry for my engislih if i have mistakes .

A: If a router/NAT sits between your server and an outside client, you MUST use port forwarding on the router.  The outside client will NOT be connecting to your server's private LAN IP/Port directly, it will be connecting to the router's public WAN IP/Port instead.  So the router needs to know to forward inbound packets to that IP/Port to the server's private LAN IP/Port.
A client running on your local PC is able to connect to the server because they are both on the same LAN side of the router, so the connection is direct and does not go through the router's WAN.  That is not the case for clients that are on the WAN side of the router.


text:
Q: Boundedness of functional In the setting of $2\pi$-periodic $C^1$ functions (whose Fourier series converge to themselves), and given a linear functional $D:C^1_{\text{per}}\to\mathbb R$ satisfying $\sup_{n}|D(e^{inx})|<\infty$ I would like to show that $D$ is continuous (or equivalently, bounded).
Attempt
The supremum condition seems it should imply boundedness, but I'm not managing to formalise that and keep running into a circular argument. For example, by contradiction, let's assume a series $\{f_n\}$ where $\|f_n\|=1$ such that $D(f_n) > n^2$, then taking $\frac {f_n}n$ which has norm $\frac 1n$ we have $D(\frac {f_n}n) > n$ which is a contradiction if $D$ is continuous, but that's what we're trying to prove...
Cheers.
Edit
I think in $L^2$ the hypothesis is wrong since we can construct a sequence
\begin{align}
f_1 &= e_1 \\
f_2 &= \frac 1 {\sqrt 2}e_1 + \frac 1{\sqrt 2}e_2 \\
&\ \vdots \\
f_n &= \sum_{k=1}^n \frac 1{\sqrt n}e_k
\end{align}
So $\|f_n\|_2^2 = 1$ but if $D(e_k)=M$ (which satisfies our bound condition) we have $D(f_n) = \frac {nM}{\sqrt n}\to \infty$
In light of the failure of the $L^2$ norm, I suppose the $C^1$ norm $\|f\|_\infty+\|f'\|_\infty$ is the focus here.

A: I will use complex Fourier series for ease of writing; everything works the same for real series.  Suppose $f\in C^1_{\rm per}$, $f(x)=\sum c_n e^{i n x}$. Since  $f'$ is continuous, it belongs to $L^2$. The Fourier series of $f'$ is $f'(x)=\sum inc_n e^{i n x}$. By Parseval's identity, $$\sum n^2 |c_n|^2 = (2\pi)^{-1} \int_0^{2\pi} |f' |^2 \le \|f\|_{C^1}^2\tag{1}$$
Let $D$ be a   functional from the problem. Define $b_n=D(e^{inx})$. The sequence $(b_n)$ is bounded. From the Cauchy-Schwarz, for every integer $N$,
$$\sum_{0<|n|\le N} b_n c_n \le \sup|b_n| \sum_{n\ne 0} |c_n| \le
\sup|b_n| \sqrt{\sum_{n\ne 0} n^{-2}}\sqrt{\sum_{n\ne 0} n^{ 2 }|c_n|^2}
\le C \|f\|_{C^1} $$
Since $b_0c_0$ is also controlled by $\|f\|_{C^1}$, the operator $D$ is bounded  on trigonometric polynomials. Since trigonometric polynomials are dense in $C^1_{\rm per}$, the restriction of $D$ to polynomials uniquely extends to a bounded operator on $C^1_{\rm per}$.

A: This is not true.  The functions $\{e^{inx}\}$ do not span $C^1_{\text{per}}$; indeed, no countable set can.  So using the axiom of choice, one can show the existence of a linear functional that vanishes on all the $e^{inx}$ but is not continuous.
You can't tell whether a linear functional is continuous by looking at a proper subspace, even if that subspace is dense.
You can, however, show that there exists a unique continuous linear functional $D_1$ such that $D_1(e^{inx}) = D(e^{inx})$ for every $n$.  Is that what you want?


text:
Q: Overlapping Isotope images when adding images I have been struggling to get Isotope to work. I have an application where after clicking a button I load some more images by getting their URLs from JSON. The issue I am having is that when I add the images to the 'galleryContainer' div (my div that I am holding all the images in) the images overlap. That or nothing happens and the whole page seems to freeze. Apparently this is a frequent problem but I still have not been able to get it working for my project. I try to use 'imagesLoaded' but it never seems to work for me.
Here is the relevant code:
// Get more images and add them to the galleryContainer
function getMoreImages() {
  for (var i = 0; i < 3; i++) {
    var newImage = $('

');
    var x = Math.floor((Math.random() * 750) + 750);
    var y = Math.floor((Math.random() * 750) + 750);

    newImage.append($(''));
    $container.append(newImage).imagesLoaded(function() {
      $container.isotope('appended', newImage);
    });
  }
}

Here is a (JSFiddle)[http://codepen.io/dirtshell/pen/emdjGv] demonstrating my problem.
It is totally possible that I am simply making a simple mistake JS wise (like not using the imagesLoaded plugin correctly), since I am sort of new to it.
Thanks =)

A: One issue is that your codepen is using isotope v2 but your js and CSS are for isotope v1.5.
You need imagesLoaded to prevent the overlap  but it is not included as part of isotope v2 as it was in v1.5. You need to load it separately.
Is the  getMoreImages() function what you are actually using on your site to load new images?
Also there is no longer "animationOptions" in isotope v2:
This
 animationOptions: {
    duration: 750,
    easing: 'linear',
    queue: false
  }

is now this:
transitionDuration: '0.4s'

and in v2, you can remove any v1.5 isotope CSS
ADDENDUM
Here is an update to you Codepen
here is the relevant code (altered):
var $container = $('.galleryContainer');

// Initialize isotope on window load and image load
$(window).load(function() {
$container.isotope({
  itemSelector: '.objects',
  masonry: {
  columnWidth: 780
},
  transitionData: '0.4s'
});
});

 // Get more images and add them to the galleryContainer
 $('.loadButton').on( 'click', function() {
 var x = Math.floor((Math.random() * 750) + 750);
 var y = Math.floor((Math.random() * 750) + 750);
 for (var i = 0; i < 3; i++) {
 var newImage = $('

');
  }

 $container.append(newImage).imagesLoaded(function() {
  $container.isotope('appended', newImage);
 });
 });


text:
Q: how to get preceding and subsequent row when row matches boolean condition in postgres How do I get my sql result to display the preceding and subsequent row when where is_selected=true ?

Result I am trying to get:
alphabet_letter  | is_selected
-----------------+-------------
 C               | f   --row preceding boolean match1
 D               | t   **--boolean match1**
 E               | f   --row following boolean match1
 H               | f   --row preceding boolean match2
 I               | t   **--boolean match2**
 J               | f   --row following boolean match2

Here is my table and data:
create table letters (alphabet_letter text, is_selected boolean);
insert into letters values('A', false);
insert into letters values('B', false);
insert into letters values('C', false);
insert into letters values('D', true);
insert into letters values('E', false);
insert into letters values('F', false);
insert into letters values('G', false);
insert into letters values('H', false);
insert into letters values('I', true);
insert into letters values('J', false);

My table looks like this:
alphabet_letter  | is_selected
-----------------+-------------
 A               | f
 B               | f
 C               | f
 D               | t
 E               | f
 F               | f
 G               | f
 H               | f
 I               | t
 J               | f

A: Try the following:
WITH rns AS
  (
    SELECT *, ROW_NUMBER() OVER (ORDER BY alphabet_letter) rn
    FROM letters
  )
SELECT DISTINCT D.alphabet_letter, D.is_selected
FROM
rns T
JOIN rns D
  ON T.rn IN (D.rn, D.rn+1, D.rn-1)
WHERE T.is_selected
ORDER BY d.alphabet_letter

See a demo
Or you may use EXISTS as the following:
WITH rns AS
  (
    SELECT *, ROW_NUMBER() OVER (ORDER BY alphabet_letter) rn
    FROM letters
  )
SELECT D.alphabet_letter, D.is_selected
FROM rns D
WHERE EXISTS(SELECT 1 FROM rns T WHERE T.is_selected AND T.rn IN (D.rn, D.rn+1, D.rn-1))
ORDER BY D.alphabet_letter

See a demo

A: Maybe your can use Lag and lead method to achieve.
https://www.postgresqltutorial.com/postgresql-window-function/postgresql-lead-function/
https://www.postgresqltutorial.com/postgresql-window-function/postgresql-lag-function/
 with cte as
(
    select alphabet_letter
            , is_selected
            , lag(alphabet_letter, 1) OVER (ORDER BY alphabet_letter) AS PrevValue
            , lead(alphabet_letter, 1) OVER (ORDER BY alphabet_letter) AS NextValue
        From letters
)
select PrevValue alphabet_letter
    From cte
    where is_selected = true
union
select alphabet_letter
    From cte
    where is_selected = true
union
select NextValue
    From cte
    where is_selected = true
order by alphabet_letter


text:
Q: Flutter Flare Teddy : I am Not able to Figure out how i can able to use Teddy | TrackingTextInput _controller and My controller both in TextField I have Extracted My TextWidget using like this To achieve my Custom UI TextField but not able to figure out where i can use Teddy _controller !? (because i am using my controller for input and password... to get and use it.)
Code...
In My Login Page..
TrackingTextInput(customTextWid: CustomTextWid(focusNode: _focusNode, controller: _controller, workSansSemiBold: workSansSemiBold, envelope: _envelope, emailAddress: emailAddress)),
In trackingtext_input.dart
@override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.only( top: 20.0, bottom: 20.0, left: 25.0, right: 25.0), child: widget.trackBuildWid);
added customTextWid Parameter and succefully able to use and Show UI in app by returning my custom widget in Parameter in build of trackingtext_input.dart,
but how and where i need to use Teddy _controller to animate Teddy !
I am Trying to implement in this Login UI
https://github.com/huextrat/TheGorgeousLogin
Any clue or help will be highly Appreciated !
Thanks in Advance !

A:
Just Use _teddyController, don't get confuse with _textController.


text:
Q: SQLite-net Table<>() method call performance I am using SQLite-net library with Xamarin and I have a question.
Which call is better or faster?
var item = sQLiteConnection.Table<User>().FirstOrDefault(e => e.Id == myobject.Id);

Or
var item = sQLiteConnection.Table<User>().Where(e => e.Id == myobject.Id).FirstOrDefault();

A: Either is fine.
They both run lazily - if the source list has a million items, but the tenth item matches then both will only iterate 10 items from the source.
Performance should be almost identical and any difference would be totally insignificant.
but
I started getting "The wait operation timed out." using Where(query).FirstOrDefault() on a large dataset. When I changed it to FirstOrDefault(query) I stopped seeing it
The difference I get when I compare the two approaches is working out to be 1ms for over 150,000 items (not 1ms for each item, it's 1ms for all 150,000). So based on that your 500 x 1,000 items query that's about 0.003ms per day. It's not significant
but I personally prefer  FirstOrDefault(query)

A: I would suggest you to use
var item = sQLiteConnection.Table<User>().FirstOrDefault(e => e.Id == myobject.Id)

It return the first element of matching condition.

But
var item = sQLiteConnection.Table<User>().Where(e => e.Id == myobject.Id);

This will bring you a collection of data that matches your condition.
so until it iterate your end of your collection it will do this.
UsingWhere(e => e.Id == myobject.Id).FirstOrDefault(); after the where your fetch first element after the iteration. This is additional overhead.
Considering the readability always be less verbose.
See FirstOrDefault vs Where


text:
Q: What is jQuery(document) vs. $(document) I don't get what jQuery(document) is here.  I thought you always used $(document)
see here in his examples: http://sorgalla.com/projects/jcarousel/

A: It's like <? versus <?php: one is a shorthand version that may be vulnerable to conflicts.

A: The $ is just a shortcut for JQuery.

A: There is no difference. $ is shorthand for jQuery. Sometimes $ is disabled as it may conflict with other Javascript libraries you are using. It is otherwise identical.

A: jQuery is just the long-hand way of invoking jQuery.  You might want to do this if you are using it in noConflict mode or internally in a plugin to make sure you are using jQuery's $ function instead of another framework's.

A: jQuery uses $(). Prototype uses $(). AFAIK Mootools uses $(). If that was the end of it, it would be impossible to use any combination of the three. So responsible frameworks provide a way to disable $() to avoid conflicts and use something else instead. In jQuery's case, that's jQuery().
jQuery() is recommended over $() for use in jQuery plugins, so they keep functioning if you do  disable $().

A: jQuery(document) and  $(document) both are alternative


text:
Q: Sveltekit - Access session from lib I'm using Sveltekit with Typescript. In $lib folder, I have an api.ts file.
After login, I'm writing JWT token to session and wanted to use it in api.ts file. But I'm getting an error.
I'm following this example:
 sveltejs / realworld
// login.svelte

import { session } from "$app/stores";

// After login...

$session.accessToken = response.accessToken;

// api.ts

import { session } from "$app/stores";

// Before sending request...

if ($session.accessToken) {
    // Add Bearer token to header...
}

Error: Cannot find name '$session'. Did you mean 'session'?ts(2552)
Why this $session thing works in .svelte file, but not in .ts file?
How can I access accessToken in session from .ts?
Thanks.

Edit
api.ts code:
import { get as getStore } from "svelte/store";
import { session } from "$app/stores";

const base = "https://localhost:44300";

async function send(method: string, path: string, data?: unknown) {
  const opts = {
    method,
    headers: {},
    body: ""
  };

  if (data) {
    opts.headers["Content-Type"] = "application/json";
    opts.body = JSON.stringify(data);
  }

  const { accessToken } = getStore(session);

  if (accessToken) {
    opts.headers["Authorization"] = `Bearer ${accessToken}`;
  }

  return fetch(`${base}${path}`, opts)
    .then((r) => r.text())
    .then((json) => {
      try {
        return JSON.parse(json);
      } catch (err) {
        return json;
      }
    });
}

export function get<T>(path: string): Promise<T> {
  return send("GET", path);
}

export function post<T>(path: string, data: unknown): Promise<T> {
  return send("POST", path, data);
}

export function put<T>(path: string, data: unknown): Promise<T> {
  return send("PUT", path, data);
}

export function del<T>(path: string, data: unknown): Promise<T> {
  return send("DELETE", path, data);
}

A: I want to add to the answer (but can't comment - lack of reput', so if it's inappropriate edit the actual answer to add the info, thanks); to Efe Erdogru and Raul Gomez:
The last line:
const { accessToken } = get(session);

cannot be at the top-level of the ts file. Do it in a function called from your Svelte file initialization block, so that at that point, the session is initialized.

A: $session is a svelte-specific syntax used to reactively access a store value. For one-time value access in a typescript file, use the get function:
import { get } from 'svelte/store';
import { session } from "$app/stores";

const { accessToken } = get(session);

If you need a reactive solution, use session.subscribe instead.


text:
Q: Arraylist passing to another activity for adding objects in that activity returning 1st activity displaying them My first activity in which i have ArrayList initialized and that must be passed to custom array-adapter for adding objects to that array list. here is my first activity.
public class OrderSummary extends AppCompatActivity {

    ArrayList<Order> orderItems= new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lview);

        OrderAdapter orderArrayAdapter = new OrderAdapter(this,orderItems);
        ListView listView = (ListView) findViewById(R.id.satya);
        listView.setAdapter(orderArrayAdapter);

    }

    public ArrayList<Order> getorderItem() {
        return this.orderItems;
    }
}

Second activity custom adapter where I adding objects to ArrayList<custom class>. The elements are added on button click.
    final Button buttonName = (Button)

    listItemView.findViewById(R.id.listitems_addcart);
        if ( currentPosition != null ) {
            buttonName.setText(currentPosition.getButtonnName());
            buttonName.setOnClickListener(new View.OnClickListener() {
              private int index;
              Context context = getContext();

              @Override
              public void onClick(View v) {
                  if ( currentPosition.getCount() == 0 ) {

                     Order o = new Order(currentPosition.getmPrice(), currentPosition.getmItemName(), currentPosition.updateCount());
                      obj.getorderItem().add(o);
                      index = obj.getorderItem().indexOf(o);
                      Toast.makeText(context, "The" + currentPosition.getmItemName() + currentPosition.getCount() + "  no has been added", Toast.LENGTH_SHORT).show();
                  } else {
                     Toast.makeText(context, " " + currentPosition.getmItemName() + obj.getorderItem().get(index).updateQuantity() + "  no has been added", Toast.LENGTH_SHORT).show();

                  }
              }
          }
       );
       ...
    }

I used getter method for passing ArrayList to the custom adapter.
My output must be when i open the first activity it must show  the data that was added using button click i properly initialized all the intents.
My full custom adapter code used to display the content in listView.
import java.util.ArrayList;

import static satya_mydream.srkrcanteen.R.layout.word_items;

//custom word adapter used to display and hanndle the row_iem

class WordAdapter extends ArrayAdapter<Word> {
    private  OrderSummary obj = new OrderSummary();

    WordAdapter(Activity context, ArrayList<Word> items) {

        super(context, 0, items);
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        // Check if the existing view is being reused, otherwise inflate the view
        View listItemView = convertView;
        if ( listItemView == null ) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    word_items, parent, false);
        }

        // Get the {@link AndroidFlavor} object located at this position in the list
        final Word currentPosition = getItem(position);

        // Find the TextView in the list_item.xml layout with the ID version_name

        // Find the TextView in the list_item.xml layout with the ID version_number
        final TextView itemTextView = (TextView) listItemView.findViewById(R.id.listitems_item);
        // Get the version number from the current AndroidFlavor object and
        // set this text on the number TextView

        if ( currentPosition != null ) {
            itemTextView.setText(currentPosition.getmItemName());
        }

        TextView dollarTextView = (TextView) listItemView.findViewById(R.id.listitems_dollor);
        // Get the version number from the current AndroidFlavor object and
        // set this text on the number TextView

        if ( currentPosition != null ) {
            dollarTextView.setText(currentPosition.getdollar());
        }

        final Button buttonName = (Button) listItemView.findViewById(R.id.listitems_addcart);
        if ( currentPosition != null ) {
            buttonName.setText(currentPosition.getButtonnName());
            buttonName.setOnClickListener(new View.OnClickListener() {
                                             private int index;

               `enter code here`                               Context context = getContext();

                                              @Override
                                              public void onClick(View v) {
                                                  if ( currentPosition.getCount() == 0 ) {

                                                     Order o = new Order(currentPosition.getmPrice(), currentPosition.getmItemName(), currentPosition.updateCount());
                                                      obj.getorderItem().add(o);
                                                      index = obj.getorderItem().indexOf(o);
                                                      Toast.makeText(context, "The" + currentPosition.getmItemName() + currentPosition.getCount() + "  no has been added", Toast.LENGTH_SHORT).show();
                                                  } else {
                                                     Toast.makeText(context, " " + currentPosition.getmItemName() + obj.getorderItem().get(index).updateQuantity() + "  no has been added", Toast.LENGTH_SHORT).show();

                                                  }
                                              }

                                          }

            );
        }
        TextView priceTextView = (TextView) listItemView.findViewById(R.id.list_items_price);

            if ( currentPosition != null )
                priceTextView.setText(currentPosition.getmPrice()+"");

        /*Find the ImageView in the list_item.xml layout with the ID list_item_icon
        ImageView iconView = (ImageView) listItemView.findViewById(R.id.list_item_icon);
         Get the image resource ID from the current AndroidFlavor object and
         set the image to iconView
        iconView.setImageResource(currentAndroidFlavor.getImageResourceId());

         Return the whole list item layout (containing 2 TextViews and an ImageView)
         so that it can be shown in the ListView */
        return listItemView;
    }

}


text:
Q: How to center mixed size images when genetering a gif from these images using Python? It is possible to generate a gif from a number of images with Python (such as imageio or PIL Image.save ). However, when the sizes of these images are different, how to make all the images align to the center of the gif using Python? The following code could not implement this:
imgList = []

for image in glob.glob(f'{dirName}/*'):
    imgList.append(imageio.imread(image))

imageio.mimsave(f'./{dirName}.gif', imgList)


text:
Q: Injective maps on cohomology and Kahler manifolds Compact Kahler manifolds have the property that surjective maps induce injections on cohomology with coefficents in $\mathbb{Q}$ (That is, if $X,Y$ compact Kahler, then a surjective map $\phi: X \rightarrow Y$ induces injections $\phi^*: H^i(Y, \mathbb{Q}) \rightarrow H^i(X, \mathbb{Q})$ for all $i$, [Voisen, Hodge Theory I, p 177]).
Question: I'm wondering if I should think of this as a property of compact Kahler manifolds, or as an instance of something more general. For example, can the Kahler condition be replaced with a more general class of manifolds (not dropping the compactness hypothesis). Perhaps one that includes not just complex manifolds but maybe a few manifolds of odd (topological) dimension? I know that if we require that $\dim X = \dim Y$ then the fact above is true more generally just for compact oriented manifolds, for formal reasons.

A: Suppose one has compact symplectic manifolds $(X,\omega), (Y,\sigma)$, and a map $f:X\to Y$ such that $f^\ast\sigma=\omega$ (if $f$ is also a diffeomorphism, then this map is a symplectomorphism, but I'm not sure the terminology in this case). Then $f^\ast: H^*(Y;\mathbb{Q})\to H^\ast(X;\mathbb{Q})$ will be injective. If $dim Y=2k$, then $\sigma^k\neq 0\in H^{2k}(Y)$ is a fundamental class, and $dim X=2n \geq 2k$, then $\omega^n\neq 0\in H^{2n}(X)$. So $f^\ast(\sigma^k)= \omega^k \neq 0 \in H^{2k}(X)$.
Now, consider $\alpha \in H^j(Y)$. By Poincare duality, there exists $\beta\in H^{2k-j}(Y)$ such that $\alpha\cup \beta = \sigma^k$. Then $f^\ast(\alpha\cup \beta)=\omega^k\neq 0$, so $f^\ast \alpha\neq 0$.

A: In order to have this property it is sufficient to require that $\phi^{-1}(y)$ is a non-zero cycle in $H_*(X,\mathbb Q)$, where $y$ is a generic point in $Y$. This holds indeed when $X$ and $Y$ are Kahler.
Let me give an example showing that this does not work when $X$ and $Y$ are just complex.
Example. Let $X$ be a Hopf surface $X=(\mathbb C^2\setminus 0)/\mathbb Z$ where $\mathbb Z$ is acting on $\mathbb C^2$ by multiplication by (say) $2$. Then there is a fibration $\phi\colon X\to \mathbb CP^1=Y$. This fibration comes  from the standard $\mathbb C^*$-action on $\mathbb C^2$. Now  $\phi^{-1}(y)$ is null-homlogous.


text:
Q: Is there an Excel WORKDAY.INTL function equivalent in Javascript/Googlescript Is there a way to find the nth workday from the current month? I know that google sheet has the function WORKDAY.INTL to get the date of the workday specified in the parameters
= WORKDAY.INTL(start_date, work_days, [weekends],[holidays])

Is there a way to write a Javascript or a google script function that does the same function as the above formula?
For example, to find the 3rd workday date of the current month.

A: Adding what Marios said in the comments but as an answer so it has more visibility.
Google Apps Script does not have such utility. The way of doing it is using JavaScript. There is already some answers in the JavaScript tag (for example this one).


text:
Q: Changing Nativescript Listview `onItemTap` background color? I have a ListView  :

This is the markup :
<ListView   [items]="items " class="list-group" (itemTap)="onItemTap($event)"  >
    <ng-template  let-item="item" let-i="index" let-odd="odd" let-even="even"  >

    </ng-template>
</ListView>

However - when I click an item - nothing happens with the background-color. ( i'm expecting to have some indication of being tapped).
I've already have this code (which does execute when I tap )
  onItemTap($event)
    {
        var lbl = $event.view.getViewById("lbl" + $event.index);
        console.log(lbl.text);
    }

BTW
If it was a button instead of label - I could've done :
.row:highlighted{
    background-color:#00A3FF;
}

But as you can see - I'm using Label.
Question
How can I highlight the label's background color when tapped ?

A: If you want you could do something with the touch event

then in your components class
highlight(label:Label, $event:TouchGestureEventData){
       if ($event.action === TouchAction.down) {
            label.backgroundColor = // on touch background color
        }
        if ($event.action === TouchAction.cancel || $event.action === TouchAction.up) {
            label.backgroundColor = // on back to original color
        }
}


text:
Q: The cast to value type 'Double' failed because the materialized value is null CODE:
double cafeSales = db.InvoiceLines
    .Where(x =>
        x.UserId == user.UserId &&
        x.DateCharged >= dateStart &&
        x.DateCharged <= dateEnd)
    .Sum(x => x.Quantity * x.Price);

ERROR:
The cast to value type 'Double' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
WHAT I HAVE SEEN ALREADY:
The cast to value type 'Int32' failed because the materialized value is null
The cast to value type 'Decimal' failed because the materialized value is null
WHAT I HAVE TRIED:
double cafeSales = db.InvoiceLines
    .Where(x =>
        x.UserId == user.UserId &&
        x.DateCharged >= dateStart &&
        x.DateCharged <= dateEnd)
    .DefaultIfEmpty()
    .Sum(x => x.Quantity * x.Price);

And:
double? cafeSales = db.InvoiceLines
    .Where(x =>
        x.UserId == user.UserId &&
        x.DateCharged >= dateStart &&
        x.DateCharged <= dateEnd)
    .Sum(x => x.Quantity * x.Price);

Neither of these work. I know the cause of the problem is that there are no rows in that table for the UserId I am passing in. In that case, I would prefer Sum() just returned a 0 to me. Any ideas?

A: You can check if the collection has any correct results.
double? cafeSales = null;
var invoices = db.InvoiceLines
    .Where(x =>
        x.UserId == user.UserId &&
        x.DateCharged >= dateStart &&
        x.DateCharged <= dateEnd
    )
    .Where(x => x.Quantity != null && x.Price != null);
if (invoices.Any()) {
    cafeSales = invoices.Sum(x => x.Quantity * x.Price);
}

A: Best Solution
double cafeSales = db.InvoiceLines
                     .Where(x =>
                                x.UserId == user.UserId &&
                                x.DateCharged >= dateStart &&
                                x.DateCharged <= dateEnd)
                     .Sum(x => (double?)(x.Quantity * x.Price)) ?? 0;

A: I know this is a bit old but just in case it helps anyone.
@Matt I guess the DefaultIFEmpty() method should work for you just in case you pass a default value for the column that you are applying Sum onto. This method has some overloads which you might want to check and I suggest type-casting if overloads do not support your requirement.
 (query).DefaultIfEmpty(0)

A: This should do the trick (you may have to remove one of the conditions if either Quantity or Price are not nullable):
var cafeSales = db.InvoiceLines
    .Where(x =>
        x.UserId == user.UserId &&
        x.DateCharged >= dateStart &&
        x.DateCharged <= dateEnd &&
        x.Quantity != null &&
        x.Price != null);

double cafeSalesTotal = 0;

if (cafeSales.Any())
{
    cafeSalesTotal = cafeSales.Sum(x => x.Quantity * x.Price);
}

A: join sim in ctx.EF.Collaterals on new { id = ini.cam.id, Type = 0 } equals new
{ id = sim.CampaignId == null ? new Guid() : sim.CampaignId, sim.Type }
into tempcoll
from sim in tempcoll.DefaultIfEmpty()

This solution works.Actually You need to use ternary operator to check the value and insert Guid if null in the second column and in the second table.and it will work.
"The cast to value type 'Double' failed because the materialized value is null" will be solved
Thanks

A:  var cafeSales = db.InvoiceLines
.Where(x =>
    x.UserId == user.UserId &&
    x.DateCharged >= dateStart &&
    x.DateCharged <= dateEnd)
.Sum(x => x.Quantity * x.Price);

double i;
if(cafeSales==null) ? i=0 : i=(double)cafeSales.First();

A: The solutions above didn't work for me. My problem was similar. I was sure that no rows were being returned but Sum behaves in some strange way. So I decided to add a check just before calling the lambda expression where I check for count property of rows returned by the lambda. If it is greater than zero, then I call the sum expression. That worked for me.

A: .NET 4.0, Nullable has a "GetValueOrDefault()" method.
So if you cast the query to Nullable, then you can end up with the correct Type when complete.
This method will also generate the correct single SQL SELECT SUM query and is faster than other solutions that return the entire recordset to later sum via linq
decimal result = ((decimal?)query.Where(w => w.Customer =="ABC").Sum(s =>  (decimal?)s.Amount)).GetValueOrDefault();


text:
Q: Weird return values to IPN since about a week ago We use fields called "item_name" and "item_number" in integration with PayPal to convey the details of the ordered product.
Recently I've been seeing PayPal transactions return "Shopping cart" in item_name, rather than the string that was posted to PayPal in that field.
This behavior is inconsistent, I have logs that show 5 transactions with 1, 4 and 5 having the missing item_name, and 2 and 3 having the old item_name without any issues whatsoever.
I've tried to find out whether item_name was deprecated but it appears to be still active, as per https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNandPDTVariables/
We are not using shopping cart, we're using PayPal Payments Standard. Our PayPal send code is:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" name="PayPal">
<input type="hidden" name="item_name" value="<?=$item_name; ?>">
<input type="hidden" name="item_number" value="<?=$item_number; ?>">

The item_name and item_number can be seen at the top of the PayPal pages the user sees next.
Could someone from PayPal please explain why is there this inconsistency in the behavior, and whether it's a problem with PayPal or a forerunner of change I wasn't aware of?
Thank you in advance for your help!
Maciek

A: We also starting experiencing this problem on 8/19/2017. Item_name = "Shopping Cart" Here are others reporting this problem:
https://www.paypal-community.com/t5/About-Payments/item-name-changed-to-quot-Shopping-Cart-quot-in-IPN/td-p/1290682


text:
Q: Jetpack Compose Combo box with dropdown In order to practice Jetpack Compose I wanted to create a MultiComboBox component for later use. It's basically standard ComboBox that allows to pick multiple options. Something like below:

I did prepare a piece of code that IMO should work fine and generally it does, but there's one case when it doesn't and I cannot figure it out what's wrong.
Here's my code:
data class ComboOption(
    override val text: String,
    val id: Int,
) : SelectableOption

interface SelectableOption {
    val text: String
}

@Composable
fun MultiComboBox(
    labelText: String,
    options: List<ComboOption>,
    onOptionsChosen: (Set<ComboOption>) -> Unit,
    modifier: Modifier = Modifier,
    selectedIds: Set<Int> = emptySet(),
) {
    var expanded by remember { mutableStateOf(false) }
    // when no options available, I want ComboBox to be disabled
    val isEnabled by rememberUpdatedState { options.isNotEmpty() }
    var currentlySelected by remember(options, selectedIds) {
        mutableStateOf(options.filter { it.id in selectedIds }.toSet())
    }
    ExposedDropdownMenuBox(
        expanded = expanded,
        onExpandedChange = {
            if (isEnabled()) {
                expanded = !expanded
                if (!expanded) {
                    onOptionsChosen(currentlySelected)
                }
            }
        },
        modifier = modifier,
    ) {
        val selectedSummary = when (selectedIds.size) {
            0 -> ""
            1 -> options.first { it.id == selectedIds.first() }.text
            else -> "Wybrano ${selectedIds.size}"
        }
        TextField(
            enabled = isEnabled(),
            modifier = Modifier.menuAnchor(),
            readOnly = true,
            value = selectedSummary,
            onValueChange = {},
            label = { Text(text = labelText) },
            trailingIcon = {
                ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded)
            },
            colors = ExposedDropdownMenuDefaults.textFieldColors(),
        )
        ExposedDropdownMenu(
            expanded = expanded,
            onDismissRequest = {
                expanded = false
                onOptionsChosen(currentlySelected)
            },
        ) {
            for (option in options) {
                DropdownMenuItem(
                    text = {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Checkbox(
                                checked = option in currentlySelected,
                                onCheckedChange = { newCheckedState ->
                                    if (newCheckedState) {
                                        currentlySelected += option
                                    } else {
                                        currentlySelected -= option
                                    }
                                },
                            )
                            Text(text = option.text)
                        }
                    },
                    onClick = {
                        val isChecked = option in currentlySelected
                        if (isChecked) {
                            currentlySelected -= option
                        } else {
                            currentlySelected += option
                        }
                    },
                    contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,
                )
            }
        }
    }
}

When I pick options and then dismiss the combo by clicking somewhere outside of it - it works fine. The problem is with onExpandedChange. currentlySelected inside of that lambda is always the same as first value of selectedIds. So for example, when no options are preselected it always calls onOptionsChosen with empty set, hence regardless of what I select - it always sets empty value. Any ideas why it happens an how can it be fixed?

A: You can use:
@Composable
fun MultiComboBox(
    labelText: String,
    options: List<ComboOption>,
    onOptionsChosen: (List<ComboOption>) -> Unit,
    modifier: Modifier = Modifier,
    selectedIds: List<Int> = emptyList(),
) {
    var expanded by remember { mutableStateOf(false) }
    // when no options available, I want ComboBox to be disabled
    val isEnabled by rememberUpdatedState { options.isNotEmpty() }
    var selectedOptionsList  = remember { mutableStateListOf<Int>()}

    //Initial setup of selected ids
    selectedIds.forEach{
        selectedOptionsList.add(it)
    }

    ExposedDropdownMenuBox(
        expanded = expanded,
        onExpandedChange = {
            if (isEnabled()) {
                expanded = !expanded
                if (!expanded) {
                    onOptionsChosen(options.filter { it.id in selectedOptionsList }.toList())
                }
            }
        },
        modifier = modifier,
    ) {
        val selectedSummary = when (selectedOptionsList.size) {
            0 -> ""
            1 -> options.first { it.id == selectedOptionsList.first() }.text
            else -> "Wybrano ${selectedOptionsList.size}"
        }
        TextField(
            enabled = isEnabled(),
            modifier = Modifier.menuAnchor(),
            readOnly = true,
            value = selectedSummary,
            onValueChange = {},
            label = { Text(text = labelText) },
            trailingIcon = {
                ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded)
            },
            colors = ExposedDropdownMenuDefaults.textFieldColors(),
        )
        ExposedDropdownMenu(
            expanded = expanded,
            onDismissRequest = {
                expanded = false
                onOptionsChosen(options.filter { it.id in selectedOptionsList }.toList())
            },
        ) {
            for (option in options) {

                //use derivedStateOf to evaluate if it is checked
                var checked = remember {
                    derivedStateOf{option.id in selectedOptionsList}
                }.value

                DropdownMenuItem(
                    text = {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Checkbox(
                                checked = checked,
                                onCheckedChange = { newCheckedState ->
                                    if (newCheckedState) {
                                        selectedOptionsList.add(option.id)
                                    } else {
                                        selectedOptionsList.remove(option.id)
                                    }
                                },
                            )
                            Text(text = option.text)
                        }
                    },
                    onClick = {
                        if (!checked) {
                            selectedOptionsList.add(option.id)
                        } else {
                            selectedOptionsList.remove(option.id)
                        }
                    },
                    contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,
                )
            }
        }
    }
}


text:
Q: NSURLSession with upload stream - subclassing NSInputStream - com.apple.NSURLConnectionLoader exception Basic task
I have some multiplatform library which is using some C++ stream interface. I have to use this stream interface to upload data by NSURLSession. My implementation should work on OS X and iOS (currently I'm testing on OS X)
What I did
Task looks quite simple and I was sure I will implement this quite fast.
I have configured NSURLSession which is working fine if I'm using NSURLRequest with simple NSData.
I'm trying to use stream like this:
        NSURLSessionDataTask *dataTask = [m_Private.session uploadTaskWithStreamedRequest: request];
        HTTPDownoadTaskProxy *dataTaskProxy = [HTTPDownoadTaskProxy new];
        // store data to properly handle delegate
        dataTaskProxy.coreTask = dataTask;
        dataTaskProxy.cppRequest= req;
        dataTaskProxy.cppResponseHandler = handler;
        dataTaskProxy.cppErrorHandler = errorHandler;

        m_Private.streamedDataTasks[dataTask] = dataTaskProxy;

        [dataTask resume];

So far so good. According to documentation of uploadTaskWithStreamedRequest I should receive notification from delegate and I do receive it:
- (void)URLSession: (NSURLSession *)session
              task: (NSURLSessionTask *)task
 needNewBodyStream: (void (^)(NSInputStream *bodyStream))completionHandler
{
    HTTPDownoadTaskProxy *proxyTask = self.streamedDataTasks[task];
    CppInputStreamWrapper *objcInputStream = [[CppInputStreamWrapper alloc] initWithCppInputStream:proxyTask.cppRequest.GetDataStream()];
    completionHandler(objcInputStream);
}

Now I should receive calls in subclass of NSInputStream which is in my case CppInputStreamWrapper, and also it is quite simple:
@implementation CppInputStreamWrapper

- (void)dealloc {
    NSLog(@"%s", __PRETTY_FUNCTION__);
}

- (instancetype)initWithCppInputStream: (const std::tr1::shared_ptr<IInputStream>&) cppInputStream
{
    if (self = [super init]) {
        _cppInputStream = cppInputStream;
    }
    return self;
}

#pragma mark - overrides for NSInputStream
- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len {
    return (NSInteger)self.cppInputStream->Read(buffer, len);
}

- (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len {
    return NO;
}

- (BOOL)hasBytesAvailable {
    return !self.cppInputStream->IsEOF();
}

#pragma mark - this methods are need to be overridden to make stream working
- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop
                  forMode:(__unused NSString *)mode
{}

- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop
                  forMode:(__unused NSString *)mode
{}

#pragma mark - Undocumented CFReadStream Bridged Methods
- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop
                     forMode:(__unused CFStringRef)aMode
{}

- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop
                         forMode:(__unused CFStringRef)aMode
{}

- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags
                 callback:(__unused CFReadStreamClientCallBack)inCallback
                  context:(__unused CFStreamClientContext *)inContext {
    return NO;
}

@end

So I'm using workaround needed when subclassing NSInputStream.
Problem
Now this should work. But I'm not receiving any call of methods of CppInputStreamWrapper (except for my call when construction object).
No errors no warning are reported, nothing!
When I've added exception breakpoint I'm catching
thread #8: tid = 0x155cb3, 0x00007fff8b770743 libobjc.A.dylib`objc_exception_throw, name = 'com.apple.NSURLConnectionLoader', stop reason = breakpoint 1.1

This comes from thread com.apple.NSURLConnectionLoader which I didn't create.
I'm totally puzzled and have no idea what else I can do.
Update
I've used code form link in comment which is hosted on github.
Now at least some parts of my class are invoked by framework, but I see strange crash.
Crash is located in this method:
- (BOOL)_setCFClientFlags:(CFOptionFlags)inFlags
                 callback:(CFReadStreamClientCallBack)inCallback
                  context:(CFStreamClientContext *)inContext {

    if (inCallback != NULL) {
        requestedEvents = inFlags;
        copiedCallback = inCallback;
        memcpy(&copiedContext, inContext, sizeof(CFStreamClientContext));

        if (copiedContext.info && copiedContext.retain) {
            copiedContext.retain(copiedContext.info);
        }

        copiedCallback((__bridge CFReadStreamRef)self, kCFStreamEventHasBytesAvailable, &copiedContext); // CRASH HERE
    } else {
        requestedEvents = kCFStreamEventNone;
        copiedCallback = NULL;
        if (copiedContext.info && copiedContext.release) {
            copiedContext.release(copiedContext.info);
        }

        memset(&copiedContext, 0, sizeof(CFStreamClientContext));
    }

    return YES;

}

Crash is EXC_BAD_ACCESS (when running tests on OS X). when I see this code everything looks fine. It should work! self is pointing to proper object with retain count 3 so I have no idea why it is crashing.

A: Undocumented private bridging API is not the only problem in custom NSInputStream implementation especially in the context of CFNetworking integration. I'd like to recommend to use my POSInputStreamLibrary as basic building block. Instead of implementing a lot of NSInputStream methods and supporting async notifications you should implement much simpler POSBlobInputStreamDataSource interface. At least you can look at POSBlobInputStream to consult what kind of functionality you should implement to support NSInputStream contract completely.
POSInputStreamLibrary is used in the most popular Russian cloud storage service Cloud Mail.Ru and uploads >1M files per day without any crashes.
Good luck and feel free to ask any questions.

A: I see you do have implementations of the undocumented CFReadStream bridge methods -- that is one of the more common issues.  However... note the comment in the NSStream.h header for the NSStream class:
// NSStream is an abstract class encapsulating the common API to NSInputStream and NSOutputStream.
// Subclassers of NSInputStream and NSOutputStream must also implement these methods.

That means you also need to implement -open, -close, -propertyForKey:, -streamStatus, etc. -- every method that is declared on NSStream and NSInputStream, basically.  Try calling -open yourself in your code (which NSURLConnection will eventually do) -- you will get the idea since it should crash right there.  You will probably need at least some minimal status handling so that -streamStatus does not return NSStreamStatusNotOpen after -open is called, for example.  Basically, every concrete subclass needs to implement the entirety of the API.  It's not like a normal class cluster where just a couple of core methods need to be overridden -- even the -delegate and -setDelegate: methods must be implemented (the superclass does not have instance variable storage for it, I'm pretty sure).
AFNetworking has an internal AFMultipartBodyStream which has the minimal implementations needed -- you can see that example inside AFURLRequestSerialization.m.  Another code example is HSCountingInputStream.


text:
Q: How to open a function from dylib? I have added a c++ library .dylib to my objective c cocoa os x app. When I am trying call a function that I wrote into .dylib with my .header class I can't compile because I get the errors. In c+++ project all is correct, but into objective c no.
My viewController:
 #import "myHeader.mm"
@implementation ViewController

- (void)viewDidLoad {
     [super viewDidLoad];

    // Do any additional setup after loading the view.

    mean(5.8, 5.8);
}

My class header:
 #ifdef __cplusplus
extern "C" {
#endif

//void donothing(void);
//double mean(double x, double y);
double mean(double x, double y);

#ifdef __cplusplus
}
#endif

The errors are:
Undefined symbols for architecture x86_64:
  "_mean", referenced from:
      -[ViewController viewDidLoad] in ViewController.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
How can solve this? What is the correct form to add .dylib to my project?
Thanks!


text:
Q: Как протестировать web сайт/приложение, используя unittest? Как протестировать web сайт/приложение, используя unittest? Какие модули использовать? Желательно с примерами кода такого теста?
import unittest

class test_website(unittest.TestCase):
    def test_website(self):
        self.assertEqual(website('http://example.org/category/page'),
            'Ответ от сервера')

A: Сначала нужно разобраться с матчастью: какие тесты нужны, для чего, тесты чего именно. Я бы посоветовал прочитать вводную статью про тестирование на Хабре, раздел про тестирование из Гайд ту Питон и раздел про тесты из документации к Джанго – это не займёт больше часа, а понимания должно добавить значительно.
За примерами тестов можно сходить на Гитхаб. Например, посмотреть на тесты в сорцах mosowpython.ru.


text:
Q: How to Email Screen in ASP.Net/MVC I have an application that is made up of 10+ related ascx files that we use to display our data on the users browser using the Html.RenderPartial helper.
I need to email the data that is a duplicate of what is on screen.  I would like to be able to get the generated html without having to do a screen scrape.
Are there any suggestions as to how to do this?  I'm just trying to keep from duplicating the work.

A: In regular asp.net you can override the Render() and provide your own HtmlWriter to intercept the rendered html before copying it to the HtmlWriter that was passed in.
I don't know off the top of my head how you'd intercept this in MVC, but I'm sure you'll be able to do it - especially if you make a new HttpModule in the pipeline to pre-post process the output stream.

A: http://www.brightmix.com/blog/renderpartial-to-string-in-asp-net-mvc/ has a good solution for rendering a View to a string so you can send it in email.
/// Static Method to render string - put somewhere of your choosing
public static string RenderPartialToString(string controlName, object viewData)
{
     ViewDataDictionary vd = new ViewDataDictionary(viewData);
     ViewPage vp = new ViewPage { ViewData = vd };
     Control control = vp.LoadControl(controlName);

     vp.Controls.Add(control);

     StringBuilder sb = new StringBuilder();
     using (StringWriter sw = new StringWriter(sb))
     {
         using (HtmlTextWriter tw = new HtmlTextWriter(sw))
         {
             vp.RenderControl(tw);
         }
     }

     return sb.ToString();
}