text:
Q: Setting the optimal thresholds for a multiclass random forest and gbt model in pyspark (ml) on an imbalanced dataset Currently a Random Forest Classifier (from Spark ML) has been build on a imbalanced dataset which has the following distribution:
+-------+----------------+
| score | n_observations |
+-------+----------------+
|     0 |         256741 |
|     1 |          13913 |
|     2 |           7632 |
|     3 |          15877 |
|     4 |           3289 |
|     5 |          11515 |
|     6 |           8555 |
|     7 |           2087 |
|     8 |          14226 |
|     9 |           6379 |
+-------+----------------+

As an outcome from a multiclass problem I get the following probability matrix. The probability column gives the probability of an observation being classified as a class. (these are the normalized rawPredicitions from the Random Forest model).
+--------------------+-------------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+
| observation_number | label_score | prob_0  | prob_1  | prob_2  | prob_3  | prob_4  | prob_5  | prob_6  | prob_7  | prob_8  | prob_9  |
+--------------------+-------------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+
|                  0 |           0 |  0,812  |  0,039  |  0,024  |  0,049  |  0,007  |  0,024  |  0,019  |  0,002  |  0,016  |  0,008  |
|                  1 |           7 |  0,419  |  0,050  |  0,032  |  0,092  |  0,018  |  0,083  |  0,080  |  0,013  |  0,132  |  0,082  |
|                  2 |           0 |  0,862  |  0,027  |  0,017  |  0,043  |  0,004  |  0,016  |  0,015  |  0,001  |  0,009  |  0,006  |
|                  3 |           0 |  0,845  |  0,028  |  0,018  |  0,049  |  0,004  |  0,018  |  0,018  |  0,001  |  0,011  |  0,008  |
|                  4 |           6 |  0,445  |  0,051  |  0,034  |  0,095  |  0,017  |  0,080  |  0,079  |  0,012  |  0,115  |  0,073  |
+--------------------+-------------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+

The actual predictions classes are highly skewed towards the majority classes (0 & 8). This is due to the fact that the majority probability is used to assign a class to an observation as can be seen below. Applying an undersampling and an oversampling method does not increase the accuracy of the output from the confusion matrix.
Confusion matrix from the output, also put into table form
However, using these predictions the AUC curves seem quite promising. (average AUC of 0.74). See the plot of the one to many AUC curve per class below:
AUC curves for the different classes (one-to-many)
I am unsure how to retrieve the optimal class from these probabilities. Looking at the AUC there are multiple ways to get the optimal threshold. A solution would be to multiply with the inverse of the prior probability, whilst another would be to fit a linear regression. Another solution could be the pairwise analysis as explained in this paper, however I am not sure how to apply there algorithm precisely. Approximating the multiclass ROC by pairwise analysis
What would be the easiest Spark implementation to obtain some class weighing on the predicted probabilities for the Random Forest (or other tree classifiers)?


text:
Q: How to use Context API in a class component I'm working on a really big project with translations. I used Formspree to handle the forms. I want to translate that as well.
This is the code given by Formspree:
import React, { useContext } from "react";
import { LanguageContext } from "../../../../App";
import './Form.css';

export default class MyForm extends React.Component {
    constructor(props) {
        super(props);
        this.submitForm = this.submitForm.bind(this);
        this.state = {
            status: ""
        };
    }

    render() {
        const { status } = this.state;
        return (
            <form
                onSubmit={this.submitForm}
                action="https://formspree.io/f/********"
                method="POST"
            >
                {/*  */}

                    Name (Required):
                    <input type="text" name="Name" className='form-control mb-3' placeholder='Enter Your Name' required />
                    Email (Required):
                    <input type="email" name="Email" className='form-control mb-3' placeholder='Enter Your Email' required />
                    Message (Required):
                    <textarea type="text" name="Message" className='form-control mb-3' rows={3} placeholder='Tell Us Your Message' required />
                    Phone Number With Country Code (Optional):
                    <input type="text" name="Phone" className='form-control mb-3' placeholder='Enter Your Phone Number' />
                    {status === "SUCCESS" ?
Thanks For Your Message! Your Message Is Successfully Submitted!
 : <button className='submit-contact-btn mt-3 mb-4'>Submit</button>}
                    {status === "ERROR" &&
Oops! There was an error. Please Try Again
}

            </form>
        );
    }

    submitForm(ev) {
        ev.preventDefault();
        const form = ev.target;
        const data = new FormData(form);
        const xhr = new XMLHttpRequest();
        xhr.open(form.method, form.action);
        xhr.setRequestHeader("Accept", "application/json");
        xhr.onreadystatechange = () => {
            if (xhr.readyState !== XMLHttpRequest.DONE) return;
            if (xhr.status === 200) {
                form.reset();
                this.setState({ status: "SUCCESS" });
            } else {
                this.setState({ status: "ERROR" });
            }
        };
        xhr.send(data);
    }
}

It's a mess for me because I don't work with class components I work with functional components.
I was trying to add my context in that file and it shows the exact same error every time.
Here's the error:

I'm trying to put this code there:
const [isBangla, setIsBangla] = useContext(LanguageContext)

I tried putting this line of code many times but the error is same.

A: In your class component, you can define the contextType:
static contextType = LanguageContext;

Then you are able to use it via this.context, for example,
this.context.setIsBangla()

A: To consume a context inside class component, you can assign a contextType to read the current context. Using contextType lets you consume the nearest current value of that Context type using this.context. You can reference this in any of the lifecycle methods including the render function.
So, you can write:
export default class MyForm extends React.Component {
  static contextType = LanguageContext // assign static contextType
    constructor(props) {
      //....
    }

Now, you can access context values using this.context (which will be an array as [isBangla, setIsBangla] for your example) in MyForm component.
Note that, you can not use useContext hook in a class component as react-hooks can only be used in Functional Components.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Are all continuum systems limits of microscopic descriptions? Many PDEs modeling nature are derived by reduced-order models of many-body descriptions, most famously the Navier-Stokes equations from the Chapman-Enskog expansion of the Boltzmann equation as well as related notions in stochastic processes, e.g. the relationship between the Langevin and Fokker-Planck equations. Moreover, in statistical mechanics we have the moment method which in general gives us a procedure for coarse-graining by making assumptions on the form of higher statistical moments.
Meanwhile at the macroscopic scale, we have various characterizations of PDE as elliptic, hyperbolic, parabolic, etc. which are statements about the structure of the equations themselves (eg. operator polynomials), and rather hard to characterize in general.
In an effort to better understand general PDEs, I'm interested in a reverse question to the one central to statistical mechanics; are there general procedures for determining microscopic descriptions of which a particular macroscopic model is a continuum limit?
Is it possible to obtain a better understanding of continuum solutions by examining corresponding dynamics on a "fine-grained" description?

A: In physics there is something called universality, which basically means that in many cases, the details of the microscopic model get washed out when we look at the system as a continuum. As an example, think of a random walk on a square lattice or on a hexagonal lattice. In both cases, the continuum behavior looks like diffusion, is symmetric in all directions (so that the symmetry of the lattice disappears) and the only difference, if at all, is in the specific value of the diffusion coefficient. So no, typically there is not a unique way to unmash the potatoes. Having said that, there are ways to extract a microscopic model given a continuum model. As you have observed, it is similar to moving from the Fokker-Planck equation to the Langevin equation: interpret the diffusion term in the equation as coming form a microscopic random walk, the first order derivative as an external force and the "self" terms (not containing derivatives) as interactions between the random walkers.
The main point of universality is that microscopic behaviors with the same symmetry (as you can see, lattice symmetry is not necessarily a relevant one) will map into the same macroscopic behaviors up to the values of the coefficients.


text:
Q: How to prove there always exists a two variables or one variable equation corresponding to a curve drawn on a 2D plane? How to prove there always exists a two variables or one variable equation corresponding to a curve drawn on a 2D plane?
For example, a circle 's equation is $x^2+y^2=r^2$.

A: Since Victor didn't specify what he means by "a curve drawn ...", I'll assume that
this is a parametric curve $p = \gamma(t)$, $0 \le t \le 1$, with $\gamma: [0,1] \to \mathbb R^2$ continuous.  The image $C = \gamma([0,1])$ is then a compact set in the plane, and $F(p) = \text{dist}(p, C)$ (i.e. the distance from $p$ to $C$) is a continuous function on $\mathbb R^2$ such that $C = \{p: F(p) = 0\}$, i.e.
$F(p)= 0$ can be taken to be the "equation" of the curve.


text:
Q: Check Database for username or password OledDb Connection I'm trying to check a database that i have connect to my program for user name and password i have my query made but how would i go about checking it against a table.
    private void button1_Click(object sender, EventArgs e)
    {
        Menu m1 = new Menu();
        string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=UserAccounts.accdb; Persist Security Info=False;";
        OleDbCommand cmd = new OleDbCommand("Select * from UserAccounts where Username = " +userBox.Text + " and Password] = " + Password.Text + "");
        using (OleDbConnection conn = new OleDbConnection(connectionString))
        {
            try
            {
                conn.Open();
                this.Hide();
                m1.Show();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
    }

A: You're pretty close already, let's just modify it a little bit:
private void button1_Click(object sender, EventArgs e)
{
    Menu m1 = new Menu();
    string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=UserAccounts.accdb; Persist Security Info=False;";
    using (OleDbConnection conn = new OleDbConnection(connectionString))
    {
        try
        {
            conn.Open();
            using (OleDbCommand cmd = new OleDbCommand("Select * from UserAccounts where Username = @Username and Password = @Password"))
            {
                cmd.Parameters.AddWithValue("@Username", userBox.Text);
                cmd.Parameters.AddWithValue("@Password", Password.Text);

                using (OleDbDataReader r = cmd.ExecuteReader())
                {
                    if (r.HasRows)
                    {
                        // do something here
                    }
                }
            }
            this.Hide();
            m1.Show();
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
        }
    }
}

A: If you simply want to check if a username and password exists you could do like this
public bool IsValid(string username, string password)
        {
            string connectionString = @"...connectionstring";

            string SQL = "SELECT * FROM UserAccounts where [Username]='" + username + "' and [Password]='" + password + "'";

            OdbcConnection conn = new OdbcConnection(connectionString);

            OdbcCommand cmd = new OdbcCommand(SQL);
            cmd.Connection = conn;

            conn.Open();

            OdbcDataReader reader = cmd.ExecuteReader();

            if (reader.HasRows)
            {
                return true;
            }

            return false;
        }


text:
Q: How do I create directory from the user input when using bash script The flow user need to follow when running the script

*

*get input from user

*check if directory exist

*if directory exist display message and ask for new directory

*else create directory

Current code:
read -p "enter directory "  DIR

if [ -d "$DIR" ]; then
    echo "directory $DIR already exist"
    sleep 1
elif [ ! -d "$DIR" ]; then
    mkdir -p $DIR
    echo "creating $DIR"
else
    mkdir -p $DIR
    echo "creating $DIR"
fi

The question is: How to optimise above code?

A: With the explanations you provided, here is what I understand:
while true; do
    read -p "enter directory "  DIR

    if [ -d "$DIR" ]; then
        echo "directory $DIR already exist"
        sleep 1
    else
        mkdir -p $DIR
        echo "creating $DIR"
        break
    fi
done

If you don't need to exit when creating the directory, just remove the break.


text:
Q: Invalid LngLat object: (NaN, NaN) in react js , "Mapbox" The project concept is to get geolocation and showing Mapbox map using API...
import ReactDOM from "react-dom";
import React, { useRef, useEffect } from "react";
import { geolocated } from "react-geolocated";
import mapboxgl from "mapbox-gl";
import fetchFakeData from "./api/fetchFakeData";
import Popup from "./components/Popup";
import "./App.css";

mapboxgl.accessToken ="pk.eyJ1IjoiamFja3Nvbi1rYXNpIiwiYSI6ImNrbzdsaDJvNTFvc3Eycm9pdTRxYmRxZjUifQ.BzA0w0U7lP0Ka3FcKkI_1Q";

const App = (props) => {
const mapContainerRef = useRef(null);
const popUpRef = useRef(new mapboxgl.Popup({ offset: 15 }));

// initialize map when component mounts
useEffect(() => {
const map = new mapboxgl.Map({
  container: mapContainerRef.current,
  // See style options here: https://docs.mapbox.com/api/maps/#styles
  style: "mapbox://styles/mapbox/streets-v11",
  center: [props.lat, props.long],
  zoom: 12.5
});

// add navigation control (zoom buttons)
map.addControl(new mapboxgl.NavigationControl(), "bottom-right");

map.on("load", () => {
  // add the data source for new a feature collection with no features
  map.addSource("random-points-data", {
    type: "geojson",
    data: {
      type: "FeatureCollection",
      features: []
    }
  });

// now add the layer, and reference the data source above by name
  map.addLayer({
    id: "random-points-layer",
    source: "random-points-data",
    type: "symbol",
    layout: {
      // full list of icons here: https://labs.mapbox.com/maki-icons
      "icon-image": "bakery-15", // this will put little croissants on our map
      "icon-padding": 0,
      "icon-allow-overlap": true
    }
  });
});

map.on("moveend", async () => {
  // get new center coordinates
  const { lng, lat } = map.getCenter();
  // fetch new data
  const results = await fetchFakeData({ longitude: lng, latitude: lat });
  // update "random-points-data" source with new data
  // all layers that consume the "random-points-data" data source will be updated automatically
  map.getSource("random-points-data").setData(results);
});

// change cursor to pointer when user hovers over a clickable feature
map.on("mouseenter", "random-points-layer", (e) => {
  if (e.features.length) {
    map.getCanvas().style.cursor = "pointer";
  }
});

// reset cursor to default when user is no longer hovering over a clickable feature
map.on("mouseleave", "random-points-layer", () => {
  map.getCanvas().style.cursor = "";
});

// add popup when user clicks a point
map.on("click", "random-points-layer", (e) => {
  if (e.features.length) {
    const feature = e.features[0];
    // create popup node
    const popupNode = document.createElement("div");
    ReactDOM.render(<Popup feature={feature} />, popupNode);
    // set popup on map
    popUpRef.current
      .setLngLat(feature.geometry.coordinates)
      .setDOMContent(popupNode)
      .addTo(map);
  }
});

// clean up on unmount
return () => map.remove();
}, []); // eslint-disable-line react-hooks/exhaustive-deps

return

};

export default geolocated({
positionOptions: {
enableHighAccuracy: false
},
userDecisionTimeout: 5000
})(App);

class Gps extends React.Component {
constructor() {
super();

this.state = {
  latitude: "",
  longitude: ""
};

this.getMyLocation = this.getMyLocation.bind(this);
}

componentDidMount() {
this.getMyLocation();
}

getMyLocation() {
const location = window.navigator && window.navigator.geolocation;

if (location) {
  location.getCurrentPosition(
    (position) => {
      this.setState({
        latitude: position.coords.latitude,
        longitude: position.coords.longitude
      });
    },
    (error) => {
      this.setState({
        latitude: "err-latitude",
        longitude: "err-longitude"
      });
    }
  );
}}

render() {
const { latitude, longitude } = this.state;

return (

    <App lat={latitude} long={longitude} />

);
}
}

please see this link "codesandbox" : https://codesandbox.io/s/determined-river-7dt0h?file=/src/App.js
props didn't work.
see this lines:

*

*center: [props.lat, props.long]

*<App lat={latitude} long={longitude}  / >
screenshot

A: The Problem
The Lat and Lng were initialized to an empty string, but the center property is expecting an array of numbers.
Solution
In Gps component, initialize the lat and long state values to a number as opposed to an empty string
this.state = {
  latitude: 38.8951,
  longitude: -77.0364
};

A: In my case, I was using it for web and the issue was causing because of the height of the div in which I was rendering map component. When I set the minHeight for that div, it worked fine for me.


text:
Q: can't override material ui 5's drawer root's style I am trying to build a sidebar by material ui's drawer for my application. but I am not able to overwrite drawer root's width, it is still 0 so flex box(Stack) can't arrange its children as expected. an example has been created on sandbox https://codesandbox.io/s/interesting-tharp-dp3mif?file=/src/App.js:71-397.
the 'bbb' is expected to be on the right side of the drawer. I have tried to use MuiDrawer-root and MuiDrawer-docked to set its width, neither of them works.
 export default function App() {
  return (
    <Stack direction="row">
      <Drawer
        variant="permanent"
        open
        sx={{
          "& .MuiDrawer-root": { width: 200, zIndex: -1 },
          "& .MuiDrawer-paper": { width: 200, zIndex: -1 }
        }}
      ></Drawer>

bbb

    </Stack>
  );
}

A: You are currently writing & .class, which means you want to access a child with that className, but that's not the case here. The current element has that className, so you want to write &.class instead, so do this fix and it should work:
-     "& .MuiDrawer-root": { width: 200, zIndex: -1 },
+     "&.MuiDrawer-root": { width: 200, zIndex: -1 },


text:
Q: How can I get more detail about ASP.NET app restarts than HostingEnvironment.ShutdownReason? I'm troubleshooting restarts in an ASP.NET application. The application is restarting about 20 times a day. I'm logging using the log4net library. Following advice from this question,   I have the application logging the reason for the shutdown from HostingEnviornment.ShowdownReason inside the Application_End() event in Global.asax. I also log when the application starts up in the Application_Start() event.
After running the logs for several days, I've found that when a shutdown is actually logged, the reason for the restart is always HostingEnvironment. But the shutdown is not always logged. I know that because I can see Application_Start() log events that don't have a corresponding Application_End() event.
What would cause the hosting environment to restart my application? Is there a way to get more specific information about why it decided to trigger the restart? Does the fact that the shutdown event is not always logged shed any light on what may be causing the restarts?
UPDATE
I'm still struggling with this. Links from around the web seem to indicate that using WinDbg/SOS.dll/ADPlus.vbs will be necessary to track down the cause of this issue. But between learning how to use these tools and figuring out how to correctly interpret the results, it seems to come with a very steep learning curve. I'm kind of still hoping there is something out there that can help me track down the cause of the restarts without resorting to disassembling CLR code. Does anyone have any other tools or tricks that can help me with this?


text:
Q: Binding image based on database id I'm using SQLite and I have table which contains table with fields: id and name
In my project I have folder graphics/pictures and there my pictures are named like: 1.png, 2.png etc.
I save all records into ObservableCollection and then I set this as a source to my ListBox.
Is there any chance to bind that photos to each item on the list based on id from table and the name of picture in folder?
I have tried smth like Source="graphic/pictures/{Binding id}.png but that seems to be bad way.

A: I am not sure if it works (and not able to try right now) but you could use StringFormat (http://msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.stringformat.aspx) or a converter (http://msdn.microsoft.com/en-us/library/system.windows.data.binding.converter.aspx) that returns the full path

A: Try to have a class with image as string
      public class Img
       {
        public string thumb { get; set; }
       }

In Code:
   for (i = 0; i < observablecollection.Length; i++)
    {
    Img sqlimage = new Img()
    {
    thumb = "/PhoneApp1;component/images/" + observablecollection[i].Id + ".jpg"
    };

    listbox1.Items.Add(sqlimage);
    }

  <ListBox  Name="listBox1" Width="Auto" HorizontalAlignment="Left" ItemsSource="{Binding Img}" DataContext="{Binding}"  HorizontalContentAlignment="Left" VerticalContentAlignment="Stretch" >
      <ListBox.ItemTemplate>
          <DataTemplate>
<StackPanel Name="ContentGrid" Grid.Row="0" Height="Auto" Orientation="Vertical" Width="Auto">
   <Image Height="165" HorizontalAlignment="Left" VerticalAlignment="Top" Width="175" Source="{Binding thumb}"/>
</StackPanel>
  </DataTemplate>
     </ListBox.ItemTemplate>
       </ListBox>


text:
Q: filtering a file by columns I have a unix question. I have a file that looks like this:
AAAA    0   1   2   2   0

BBBBB   2   2   2   2   2

CCCCC   1   1   0   1   1

DDDD    0   0   0   0   0

EEEEE   2   2   0   2   2

The file has many thousands of rows like this (and is also tab-delimitated). The first column of the file is a name and the 2nd thru 6th columns are the data. It is the info in the 2nd-6th column that is important. I need to output all of the lines in which the 2nd-6th columns have no more than 1 0(zero). For example, I would want the output to look like this:
BBBBB   2   2   2   2   2

CCCCC   1   1   0   1   1

EEEEE   2   2   0   2   2

I have been trying to do this in as simple a method as possible and have tried the following awk command:
awk 'BEGIN{out!=0;}{if($2!=0)out++;if($3!=0)out++;if($4!=0)out++;if($5!=0)out++;if($6!=0)out++;if (out>=4)print;}'

But, when I try this, it just gives me the original input file. I am not sure what is wrong, or if I am even taking a correct approach. Any help would be appreciated.

A: The mistake you are doing is not resetting the out variable for each record, and instead initializing it just once in the BEGIN block. (You are also mistakenly initializing that using a "not equals".)
awk '{out = 0; if($2!=0) out++; if($3!=0) out++; if($4!=0) out++; if($5!=0) out++; if($6!=0) out++; if(out>=4) print}'

A: One way using perl:
perl -ne 'print if(tr/0/0/ <= 1)' file.txt

I'm assuming the names on each line don't contain numbers (specifically 0) and that they do not exceed one digit in length. Also, if you add the -i flag, you can make the changes in-file.

A: awk '
  {
    nzero=0
    for (fld = 2; nzero <= 1 && fld <= 6; fld++) {
      if ($fld == 0) nzero++
    }
    if (nzero <= 1) print
  }
' filename

A: much simpler way to do this is :
awk '{count=0;for(i=2;i<=NF;i++){if($i~/0/)++count;}if(count <=1)print}' file1

tested below:
> cat file1
AAAA    0       1       2       2       0
BBBBB   2       2       2       2       2
CCCCC   1       1       0       1       1
DDDD    0       0       0       0       0
EEEEE   2       2       0       2       2
sEEEE   2       0       0       0       2
> awk '{count=0;for(i=2;i<=NF;i++){if($i~/0/)++count;}if(count <=1)print}' file
BBBBB  2 2 2 2 2
CCCCC  1 1 0 1 1
EEEEE  2 2 0 2 2
>

A: Assuming that the columns conforms to a particular format can be dangerous. Below is an easy solution using the 0,1 properties of Boolean variables:
awk '($2==0) + ($3==0) + ($4==0) + ($5==0) + ($6==0) <2' file.txt


text:
Q: I want to compare two multidimational array or json String I have two json string, i have convert that string into array when i am sending request via curl.
now my problem is i want to send another request if my string is updated.
i have used array_diff but it's giving me error "Notice: Array to string conversion" because its multidimensional.
my json strings are:
{"toy":["cycle","doll"],"accessory":["tv"]}

and second one is
{"toy":["cycle","cat","rabit"],"accessory":["tv","spekers"]}

how do i differentiate beetween this and get value if its not in another array.
my converted two array is like this
Array

(
    ['toy'] => Array
    (
        [0] => cycle,
        [1] => doll
    ),
    ['accessory'] => Array
    (
        [0] => tv
    )
);
Array
(
    ['toy'] => Array
    (
        [0] => cycle,
        [1] => cat,
        [2] => rabit
    ),
    [accessory] => Array
    (
        [0] => tv,
        [1] => spekers
    )
);

A: here is solution i have found
public function arrayRecursiveDiff($aArray1, $aArray2) {
    $aReturn = array();

    foreach ($aArray1 as $mKey => $mValue) {
        if (array_key_exists($mKey, $aArray2)) {
            if (is_array($mValue)) {
                $aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);
                if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
            } else {
                if ($mValue != $aArray2[$mKey]) {
                    $aReturn[$mKey] = $mValue;
                }
            }
        } else {
            $aReturn[$mKey] = $mValue;
        }
    }

    return $aReturn;
}

http://php.net/manual/de/function.array-diff.php


text:
Q: Версия файла в InnoSetup Добрый день!
Подскажите пожалуйста, как в скрипте InnoSetup указать версию файла для создаваемого инсталлятора?
Версию продукта указываю так:
AppVersion={#MyAppVersion}
А версия файла в скомпилированном файле остаётся пустой:

A: Вместо
AppVersion={#MyAppVersion}

используйте
#define MyAppVersion GetFileVersion('Ваша_аппликация.exe')
VersionInfoVersion={#MyAppVersion}


text:
Q: Is there any tutorial for Rails 3.2 that covers assigning an admin attribute to a user? Disclaimer: I'm using Rails 3.2. Specifically, in the Rails 3 in Action book:
The User model does have attr_accessible attr_accessible :email, :password, password_confirmation, :remember_me
The User model NOT have :admin listed, therefore it can't be mass-assigned to as part of params[:user].

The form_for block inside app/views/admin/users/_form.html.erb sets up a checkbox element to
allow an admin to set a user as an admin:

`     <%= f.check_box :admin %>
      <%= f.label :admin, "Is an admin?" %>

The app/controllers/admin/users_controller.rb
@user = User.new(params[:user])
@user.admin = params[:user][:admin] == "1"
if @user.save

The line @user.admin = params[:user][:admin] == "1" should set the admin attribute to true, but generates mass-assignment errors which prevent me from changing the @user.admin attribute to true.

I can set the admin attribute to true without mass-assigning via the console, along with defining a method in the User model:
def make_admin
  self.admin = true
end

This accomplishes the same thing, nothing fancy.
How do I get the admin attribute assigned to TRUE for the user to work using a view & controller via the checkbox?
Is there a way to remove or separate the admin parameter from params[:user][:admin])?

A: Commenting out the config.active_record.mass_assignment_sanitizer = :strict line in the development.rb file moved me forward.

A: It's a bad idea to comment the mass assignement protection.
Why don't you add :admin to the list of attr_accessible if you want it to be mass assigned ?
And for information, when you type this :
@user = User.new(params[:user])
@user.admin = params[:user][:admin] == "1"
if @user.save

It's not the @user.admin = ... which throw a mass assignment error, but the line User.new(params[:user])
Anyway, if you want to retrieve the value of the checkbox, but don't want to mass-assign it, try this :
admin = params[:user].delete(:admin)
@user = User.new(params[:user])
@user.admin = admin == "1"
if @user.save

Don't forget to re-enable the mass assignment protection ;)


text:
Q: Need Powershell script to get all public IP addresses with attached resource name, Resource group, in all subcriptions In our organization, there are about 4,000 subscriptions. So I need a powershell script to get all public IP addresses with attached resource name, in excel or csv format.
Used below scripts but its only showing IP address:
az login

$Subscriptions = Get-AzSubscription

foreach ($sub in $Subscriptions) { az network public-ip list --subscription $sub.Name --query "[?ipAddress!=null]|[?contains(ipAddress, '$IP')].[ipAddress]" --output table }

A:
Get all public IP addresses with attached resource name, Resource group, in all subscriptions:

Use azure PowerShell command Get-AZPublicIpAddress:
 Get-AzPublicIpAddress | Export-Csv -Path /home/pathxxxx/new.csv | format-table

Get resourcegroup, resource as well as creation data etc fields as shown:

Set subscription using below script if needed for a specific subscription:
$subsscriptions = Get-AzSubscription
foreach ($subscription in $subscriptions) {
    Write-Host "$subscription.Name"
$SelectSub = Select-AzSubscription -SubscriptionName $subscription.Name
}
#Add code here as per the requirement#

Exported output to excel sheet using export-CSV powershell command:


text:
Q: Error message in MemberShip method Hello I have been having trouble with this for a while now. I added twelve textbox
in the code behind(XXX.aspx.cs). i get message error for this line:
      Membership.CreateUser(HttpUtility.HtmlAttributeEncode(sFirstName.Trim()),
                 HttpUtility.HtmlAttributeEncode(sLastName.Trim()),

Why i'm getting this is the message: overload for method 'CreateUser' takes 12 arguments.
I like to mention that before i had 5 textbox and it's worked well. Now, after i added 5 textbox, i'm getting the message above.

A: Membership.GetUser has several overloads. It seems as if you want to use the one with two parameters for username and password.
But your code snippet above shows a comma at the end which suggests that you have more parameters or at least that it's not compiling code.
This should work:
Membership.CreateUser(
  HttpUtility.HtmlAttributeEncode(sFirstName.Trim()),
  HttpUtility.HtmlAttributeEncode(sLastName.Trim()));


text:
Q: what is the relationship between MSS and congestion window A TCP connection is using an MSS=500 bytes. Which of the following could be a realistic/valid value for the congestion window during its operation?
Can anyone tell me how to compute the result?

A: So like a realistic/valid value of the congestion window should be a integer multiple times of the maximum segment size(MSS).
Click here to see image
According to this image, the congestion window size increase exponentially, which means * 2 every time. For example, if your MSS is 500 bytes, possible congestion window size should be 500, 1000, 2000, 4000 and something like these.
Hope it's helpful. Cheers!


text:
Q: Wordpress Problem: Redirects login/logout Problem session_tokens disappear after logout I have Redirects Issue in WordPress. After updating to the new Version Wordpress 5.2.2. Every time I try to login, the Site is redirecting me again to the login page. I find out that the session_tokens in the database/table wp_usermeta is deleting everytime after logout.
What I already tried and how I found the Bug

*

*Clearing Browser Cookies and Cache

*Restore Default .htaccess file

*Deactivating Themes and Plugins

*Deleted Themes and Plugins and reinstalled everything

All this steps above did not help, then I observed my wp_usermeta table and found, that the session_tokens was missing!
Session_tokens: I found out that the session_tokens to the database wp_usermeta was everytime disappearing after logout. If I do insert it manuel thru sql again in the database, then it works for one time and I can login again. After logout it disappears again. So I need everytime to put it again in the DB if I want to login to my wordpress admin site.
sql: INSERT INTO wp_usermeta (umeta_id, user_id, meta_key, meta_value) VALUES ('965', '1', 'session_tokens', NULL);
I know now what the Problem is, but I have no Idea how to fix it? It has to do something with logout?
Sorry: for my grammatical, not perfect English!
Redirect URL: https://www.example.de/blog/wp-login.php?redirect_to=https%3A%2F%2Fwww.example.de%2Fblog%2Fwp-admin%2F&reauth=1

A: here is code for redirect logout user to the homepage. add this to function.php
add_action('wp_logout','auto_redirect_after_logout');

function auto_redirect_after_logout(){

  wp_redirect( home_url() );
  exit();

}


text:
Q: Linq Query from textboxes that might be empty (Coalesce) I need to know if there is any way to coalesce this fields :
String Field1
Integer Field2
When user input is nothing on the textboxes, I need this query to ignore the values
but I dont know how to achieve it.
I used Nothing, default nullable value for integer using:
Dim nullInt As Integer?
        nullInt.GetValueOrDefault()

With no luck.
Dim veh As wsTarificador.Class1() =
    (From m In vehiculos
     Where m.Field1= IIf(String.IsNullOrEmpty(txtCaballos.Text), nothing, txtCaballos.Text) _
     And m.Field2=Convert.ToInt32(IIf(String.IsNullOrEmpty(txtPuertas.Text), nothing, txtPuertas.Text))
    Select m).ToArray

A: Try something like this
Dim veh As wsTarificador.Class1() =
    (From m In vehiculos
     Where (String.IsNullOrEmpty(txtCaballos.Text) OrElse m.Field1 = txtCaballos.Text) _
     AndAlso (String.IsNullOrEmpty(txtPuertas.Text) OrElse m.Field2=Convert.ToInt32(txtPuertas.Text))
    Select m).ToArray


text:
Q: Javascript promise not populating response I thought I understood promises until this happened. I know there are ALOT of similar questions on SO but after going through many many and redoing promises this simple problem is not getting solved. I have been reading and trying but cannot find out how to fix this without using a callback function and not using a .then
const searchResponse = await performSearch(options);
if (searchResponse.error) {
    response.error = searchResponse.error;
}
else {
    response = orchestrateShareClassSearchResponse(searchResponse['data']);
}
return Promise.resolve(response);

The problem is searchResponse['data'] is always sent as an empty object and the result from performSearch ( async function performSearch) is not populated. I also tried await searchResponse['data'] but to no avail.
Sometimes a something tiny can really bug. Does anyone have any ideas besides using callbacks ?
I am posting the performSearch as well although didn't wan't to complicate the problem:
export async function performSearch(options, callingMethod: string, callback?: Function): Promise<IActionResponse<ISearchEntityResponse>> {
    const baseSearchRequest = Object.assign({}, BASE_SEARCH_REQUEST, options);
    let response = <IActionResponse<ISearchEntityResponse>>{};
    let searchResponse;// = await performSearch(options);
        const io = require('socket.io-client');
        const socket = io.connect();
        socket.on('connect', function (data) {
            console.log('CONNECTED TO CLIENT SOCKET');

            socket.emit('fetchShareClasses', null);
            socket.on('fetchShareClasses', async function (searchResponse) {
                console.log('sNullOrUndefined(searchResponse)::', isNullOrUndefined(searchResponse));
                if (searchResponse === null) {

                    searchResponse = await fetch(ENDPOINTS.fund.searchEntity, generateRequest('POST', baseSearchRequest)).then(function (searchResponse) {

                        console.log('NULL recieved do call to get DATA');
                        socket.emit('fetchShareClasses', searchResponse);
                    });
                }
                else {
                    console.log('fetchShareClasses CLIENT REACHED');
                    response = searchResponse;

                }
            });
        });
        return Promise.resolve(response);
}


text:
Q: How to change a list of values into variables? I have a list {E, {p, ϕ}}, and I need values E, p, and ϕ such that I can later on do operations with them (like ArcCos[p], etc.). I will be repeatedly generating the values in the list, as a list, so doing this by-hand is not an option. How do I get them out of the list?

A: Let:
list = {a, {b,c}};

This will give you element "a":
list[[1]]

This will give you elements {b,c}:
list[[2]]

This will give you "b" straight away:
list[[2, 1]]


text:
Q: How to go from VBA Scripting Dictionary to Table Object I am heavily using scripting dictionaries in one of my VBA classes and the end goal is to output all the dictionary information into a table. Is there any quick way to have a single row table created from the dictionary?
My previous attempts have all been to try outputting the dictionary data into a pre-made empty table but I feel like there must be a way to create the table as I unload the dictionary.
Thanks!

A: There's no method that creates a Table from a Dictionary as far as I'm aware. So you'd need to convert the dictionary items to some other data container. Tim Williams' suggestion of the variant array would be the easiest way to do it.
I don't want to be the kill-joy here, but are Dictionaries the right choice for you? If you're going to create lists that will ultimately populate a Table, then you might consider using a Recordset as your 'list' object instead of a Dictionary. Tables have been designed to work with Recordsets so many of the coding tasks have been simplified for you. For example, you'd only need one line of code to create and populate the Table. If you can be bothered to amend all of your dictionaries, then this might be a route for you to go.
The code below shows you how it can work. I've included a brief function that converts a Dictionary to a one row Recordset, but I'd look at using Recordsets throughout.
Public Sub RunMe()
    Dim d As Object
    Dim rs As Object
    Dim rng As Range

    'Some dummy dictionary data
    Set d = CreateObject("scripting.Dictionary")
    With d
        .Add "Hdr " & .Count, "Dummy Item #1"
        .Add "Hdr " & .Count, "Dummy Item #2"
        .Add "Hdr " & .Count, "Dummy Item #3"
        .Add "Hdr " & .Count, "Dummy Item #4"
    End With

    'Convert dictionary to recordset.
    'Note: not needed if you re-wrote your code
    'to have your lists as recordsets.
    Set rs = DicToRs(d)

    'Set destination range for table.
    Set rng = Sheet1.Range("A1")

    'Create the table.
    Sheet1.ListObjects.Add(xlSrcQuery, rs, , , rng).Refresh

    'Remember to close the recordset.
    rs.Close

End Sub
Private Function DicToRs(d As Object) As Object
    Const adVarChar As Long = 200
    Dim rs As Object
    Dim v As Variant

    Set rs = CreateObject("ADODB.Recordset")

    With rs
        For Each v In d.Keys
            .Fields.Append CStr(v), adVarChar, 255
        Next
        .Open
        .AddNew
        For Each v In d.Keys
            .Fields(CStr(v)) = d(v)
        Next
        .Update
    End With

    Set DicToRs = rs

End Function


text:
Q: Erro ao instalar - NuGet - Unable to connect to the remote server Meu Nuget não estava conseguindo baixar nenhum pacote e eu não conseguia ver os pacotes instalados no  Manager Package, então pesquisei um pouco e resolvi desinstalar e instalar novamente.
O problema começa quando tento reinstalar o nuget, logo que começa a fazer o donwload eu recebo o  seguint erro:

The extension could not be installed because of the following error:
  Unable to connect to the remote server

Eu tentei

*

*Limpar o HTTP-PROXY

*Tentei retirar a tag <system.net></system.net> do arquivo devenv.exe.config

*Deletar o .suo
Mas infelizmente nada resolveu, se alguém tiver alguma ideia de como resolver ficarei grato.

A: Eu consegui resolver este erro baixando  direto do site do Nuget e instalando manualmente.
Lembrando que a Api do Nuget estava instável na época em que tive este problema.


text:
Q: airmon-ng: ls: cannot access '/sys/class/ieee80211/': No such file or directory Background:
I am running the latest version of Kali Linux in a vmware workstation and I have a Cisco AE2500 wifi usb which works as a wifi adapter in Windows 10.  Unfortunately, when i run the airmon-ng command, I receive
ls: cannot access '/sys/class/ieee80211/': No such file or directory.
I have tried every possible solution from 10+ forums and different google searches to fix this problem.  Common solutions which fixed the problem for other individuals have yet been unsuccessful.  Solutions include:
1) apt-get update && apt-get upgrade && apt-get dist-upgrade -y
2) The forum solution to download backports driver (4.4.2-1) and make defconfig-b43, compiled, installed, rebooted
3) The forum solution to download synaptic and then manually upgrade the bcm43xxx drivers
4) Airmon-ng forum
5) Vmware tools update
6) apt-get install kali-linux-wireless
7) installation of all wifi firmware drivers for both 80211, broadcom, atheros and intel chips.
and numerous others...
lsusb:
root@sandbox:~# lsusb
Bus 001 Device 003: ID 04e8:6863 Samsung Electronics Co., Ltd GT-I9500 [Galaxy S4] / GT-I9250 [Galaxy Nexus] (network tethering)
Bus 001 Device 002: ID 13b1:003a Linksys AE2500 802.11abgn Wireless Adapter [Broadcom BCM43236]
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 004: ID 0e0f:0008 VMware, Inc.
Bus 002 Device 003: ID 0e0f:0002 VMware, Inc. Virtual USB Hub
Bus 002 Device 002: ID 0e0f:0003 VMware, Inc. Virtual Mouse
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

iwconfig:
root@sandbox:~# iwconfig
usb0      no wireless extensions.

lo        no wireless extensions.

eth0      no wireless extensions.

But yet when I use airmon-ng:
root@sandbox:~# airmon-ng
ls: cannot access '/sys/class/ieee80211/': No such file or directory

PHY Interface   Driver      Chipset

(Please note airmon-ng check kill does nothing to modify this error message)
Please help... any suggestions are welcome.
Another line of questioning pertinent to fixing this problem is located here: https://unix.stackexchange.com/questions/306865/changing-a-driver-on-a-device-plugged-in-by-usb

A: If you are using a USB wifi adapter then do the following:
1) In the VirtualBox menu go to Devices > USB > select your wifi adapter
2) Wait as windows will install this virtualbox usb device and it will configure with your Kali Linux. At this point you will lose internet connection on the host machine (Windows in my case)
3) type in 'iwconfig' into the Linux terminal and you should see your wlan0 listed. success!


text:
Q: Splitting an image into 4 pieces using python JES How do I split an image in JES? I am a new IT student and i just need a guide how to go about it, I have tried def splitImage(filename):
and I loaded the program but its coming up with an invalid syntax. I am not sure what am doing wrong


text:
Q: Rails: string to attribute with Dirty I'm writing this in a callback:
def push_changed_values_to_vars
  template_variables.each do |var|
    attr_name = var.name.downcase.underscore.to_s
    next unless User.method_defined?(attr_name) && attr_name.changed
    var.update_attribute(:text, send(attr_name))
  end
end

But I'm getting an undefined method 'changed' for "address":String error. I've included ActiveModel::Dirty in the model.  How can I send the attr_name to the model to check whether it had been changed?

A: Solved with this:
next unless User.method_defined?(attr_name) && changed.include?(attr_name)

Easy.


text:
Q: How to find if pandas dataframe has "NA" values in html code? The dataframe variable has "NA" value if data is not written into it.
If a table has 'NA' values like this table display in web page  then table shouldn't appear on webpage. The table is fetched from python dataframe 'resourse_usage' from the server
And the html code written is here
Help me out here that how can I manipulate the python variable in html code so that the table isn't displayed if it has entire row with "NA" values

A: Assuming you have loaded the data into dataframe called df, you can use df = df.dropna() to keep only the rows without any NaN values (so if there is even one column with a NaN in a row, the row will still be dropped). If instead, you only want to drop rows where the entry for every column in each row is NaN, then you can use df = df.dropna(thresh=df.shape[1]).


text:
Q: How to complete data in a SAS table? I have a table in SAS and it looks like this:
The primary key is Name-Surname.
Row   Name       Surname      Country       Sec    Salary
1     Foo         Bar          SP            1      1500
2     Foo         Bar          SP            2
3     Foo         Bar                        3      1500
4     Foo1        Bar1                       1      2000
5     Foo1        Bar1         IT            2      2000
6     Foo1        Bar1         IT            3      2000
7     Foo1        Bar1         IT            4
8     Foo2        Bar2         PO            1
8     Foo2        Bar2                       2       850
9     Foo2        Bar2                       3
10    Foo2        Bar2         PO            4

It has empty fields, how can I fill it so that they are as in the table below?
Row   Name       Surname      Country       Sec    Salary
1     Foo         Bar          SP            1      1500
2     Foo         Bar          SP            2      1500
3     Foo         Bar          SP            3      1500
4     Foo1        Bar1         IT            1      2000
5     Foo1        Bar1         IT            2      2000
6     Foo1        Bar1         IT            3      2000
7     Foo1        Bar1         IT            4      2000
8     Foo2        Bar2         PO            1       850
8     Foo2        Bar2         PO            2       850
9     Foo2        Bar2         PO            3       850
10    Foo2        Bar2         PO            4       850

Thank you.

A: Assuming your data is sorted by Name and Surname and you want to take over values only from lines with the same name and surname,
For each combination of name and surname read in all data twice.
data want;
    set have (in=first_visit) have (in=second_visit);
    by Name Surname;

The first visit remember the Country and Salary from the lines it is filled in.
In case different non missing values exist, put a warning in the log.
    if first_visit then do;
        if first.Surname then do;
            _Country = Country;
            _Salary = Salary;
        end;
        else do;
            if missing(_Country) then _Country = Country;
            else if _Country ne Country and not missing(Country) then put
                'WARNING: different values:' Country= ' and ' _Country
                ' for ' Name= Surname=;

            if missing(_Salary) then _Salary = Salary;
            else if _Salary ne Salary and not missing(Salary) then put
                'WARNING: different values:' Salary= ' and ' _Salary
                ' for ' Name= Surname=;
        end;
    end;

The second visit, fill in the blanks with the values retained from the first visit. (Note that we don't need the variable second_visit, but it is easier to understand if I define it anyway.)
    else do; * this is the _second_visit ;
        if missing(Country) then Country = _Country;
        if missing(Salary) then Salary = _Salary;
    end;

To make this work, we must explicitly retain the temporary values, because SAS initialises all variables for each observation by default. (I started all their names with _, because I can then refer them with a wildcard, but that only works if you put the retain statement after the creation of the variables.)
    retain _:;

As the retained values have no further use, drop them from the result. _(Note that first_visit and second_visit are also dropped, because of the way we defined them.)_
    drop _:;
run;

A: A DOW loop can to process the by groups to identify the 1st non-missing value which is then to be used as the imputation value.
data have; input
Row   Name $     Surname  $   Country $     Sec    Salary; datalines;
1     Foo         Bar          SP            1      1500
2     Foo         Bar          SP            2      .
3     Foo         Bar          .             3      1500
4     Foo1        Bar1         .             1      2000
5     Foo1        Bar1         IT            2      2000
6     Foo1        Bar1         IT            3      2000
7     Foo1        Bar1         IT            4      .
8     Foo2        Bar2         PO            1      .
8     Foo2        Bar2         .             2       850
9     Foo2        Bar2         .             3      .
10    Foo2        Bar2         PO            4      .
;

data want;
  do _n_ = 1 by 1 until (last.surname);
    set
      have (obs=0 rename=(country=_1st_country salary=_1st_salary))
      have
    ;
    by name surname;
    if missing(_1st_country) then if not missing(country) then _1st_country = country;
    if missing(_1st_salary ) then if not missing(salary ) then _1st_salary  = salary;
  end;

  do _n_ = 1 to _n_;
    set have;
    if missing(country) then country = _1st_country;
    if missing(salary ) then salary  = _1st_salary;
    OUTPUT;
  end;

  drop _1st:;
run;


text:
Q: how to read latest file in directory using javascript? I have a device that upload data every day. The data store in json format and file name using date format (ex: 20181002.json) and a new file will be added to the same folder every day (20181003, 20181004 and so on) for a month and a new folder will be created by device every month.
I want to display the latest data in a table without selecting the filename every day. Is there a way to do that?

This is the filepath I used.
xhr.open('GET', 'database/Dabung/2018/10/20181002.json');
xhr.send();


text:
Q: How can I auto mount an SMB share on KDE + Arch Linux? (re: kio-fuse?) I'm using a Steam Deck which runs Arch Linux and KDE Plasma.  It has a read-only filesystem (for system files) but does include kio-fuse (5.0.1).
What's the best practice to automatically mount an SMB share in KDE Plasma/Arch Linux?
Do I need to add to the /etc/fstab or is there a better method?  Can the Dolphin file manager automatically add this for me?

A: If you just want to access the files from dolphin, you can right click (or whatever the steam deck calls right click) in empty space of the places tab -> add entry -> enter smb://server/directory/

If you want other applications to have access to the smb share (e.g., my use case being obsidian note taking syncing my notes), I'm in the process of setting up kiofuse. I currently use this command to mount:
dbus-send --session --print-reply --type=method_call \                                         ✔
      --dest=org.kde.KIOFuse \
             /org/kde/KIOFuse \
             org.kde.KIOFuse.VFS.mountUrl string:smb://server/directory

Still working on an automatic and permanent solution but works for now.
If you go down this route I'd suggest reading the documentation of kiofuse, but I'd avoid it if the dolphin network share works just fine.


text:
Q: How to avoid instanceof in copy constructor for inherited java clasess I am writing a copy constructor for cloning an object. When a class has a refernce to an object which is further inhertited by few other classes.
class Person
{
    String name;
    Address address;
 }

class HomeAdress extends Address
{
}
class OfficeAdress extends Address
{
}

Now in copy constructor for Person, to decide which Address object is to be instiated I have to use instanceof.
public Person(Person p)
{
    name = p.name;
    if(p.address instanceof HomeAddress)
    {
        address = new HomeAddress((HomeAddress) address);
    }else if(p.address instanceof OfficeAddress)
    {
        address = new OfficeAddress((OfficeAddress) address);
    }
}

So the basic problem with this as when new type of address is added to the model. I will have to add a check for the same in Person copy constructor. Is there way to avoid instanceof  check to instantiate correct address object. Can I use refelction to avoid  instanceof  from the code?

A: You should delegate the responsibility for copying the address to the Address class. Whether you implement Cloneable or not, put a clone() method in Address, and then you can (if you need custom handling) override it in each specific Address subclass. Then in your Person copy constructor you just need:
this.address = p.address.clone();

A: First, I guess it is a typo:
address = new HomeAddress((HomeAddress) p.address);

Second, instead of casting the object, you can define a copy() method in Address class, (could be) abstract:
abstract class Address {
    abstract Address copy ();
}

And you implement the method in each of the subclasses of Address, then you can call it in the constructor of Person:
public Person(Person p)
{
    name = new String(p.name);
    address = p.address.copy();
}


text:
Q: Firestore query documents startsWith a specific character Is it possible to query a firestore collection to get all document that starts with a specific character? For example if I have a collection "Items" that contains:

I want for example only the document starting with I
I don't know how modify the query , the method charAt[0] is not recognized:
return itemRef
      .doc(this.itemsId)
      .collection("october")
      .where(firebase.firestore.FieldPath.documentId().charAt[0], "==", randomChar)

A: From the top of my head, if interested in the letter "I":
var lower = 'I';
var upper = String.fromCharCode(lower.codeUnitAt(0) + 1);

itemRef
      .doc(this.itemsId)
      .collection("october")
      .where(firebase.firestore.FieldPath.documentId() ">=", lower)
      .where(firebase.firestore.FieldPath.documentId() "<", upper)

Not sure, what happens in case of the letter Z.


text:
Q: What are the power requirements of the SNES Classic? The description I see on most online retailers for Nintendo's bundle of nostalgia includes something like:

Note that an AC adapter for the USB cable is required to play the system but is not included in the packaging.

Now, there's an "official" one for around a quarter of the price of the console, but is this necessary?
Would a phone charger plug work? A bog standard powered USB hub? The USB port on my television?

A: As mentioned on arstechnica

Even though the Super NES Classic Edition is rated for five watts, it
  only draws 2.3W from the provided USB adapter. The USB Micro power
  cord can be plugged in to any sufficiently powerful source, including
  a laptop or the USB power outputs on many modern TVs.

This basically means that you do not need to buy the official charger and most, if not any charger would work.


text:
Q: Why does my ip-route-add fail silently? I'm trying to configure host A to use a remote Linux server B as the router to Internet. A's eno50332208 has ip address 172.16.100.131. The interface used as gateway on B has address 172.16.100.128.
I use command ip route add default via 172.16.100.128 dev eno50332208. But after executing it, nothing changed in routing table. There is no error output in terminal either.
Before the command, ip route has only one-line output:
172.16.100.0/24 dev eno50332208  proto kernel  scope link  src 172.16.100.131

Why could ip route command fail silently? How can I view the logs/enforce debug info?

A: If you see a bunch of NetworkManager messages in syslog, NetworkManager overmanaging your connections (running scripts which revert your route changes or re-establishing the connection).
Kill NetworkManager (killall /usr/sbin/NetworkManager) and try again


text:
Q: merge sort not working when copying the result of merge operation directly to auxiliary array Here is the code which i am using for merge sort
#include<stdio.h>
#include<stdlib.h>

int merge(int *arr,int *b,int low,int mid,int high)
{
    int i,j,k;
    i = low;
    j = mid+1;

//  printf("low: %d mid: %d high: %d\n",low,mid,high);
    for(k=low;k<=high;k++)
    {
        b[k] = arr[k];
    }
    k = low;
    while((i <= mid) && (j <= high))
    {
        if(b[i] <= b[j])
        {
            arr[k++] = b[i++];
        }
        else
        {
            arr[k++] = b[j++];
        }
    }
    while(i<=mid)
        arr[k++] = b[i++];
    while(j<=high)
        arr[k++] = b[j++];
}

int merge_sort(int *arr,int *b,int low,int high)
{
    int mid;
    if(low<high)
    {
        mid = (low)+(high - low)/2;
        merge_sort(arr,b,low,mid);
        merge_sort(arr,b,mid+1,high);
        merge(arr,b,low,mid,high);
    }
    return 0;
}

int temp_merge(int *arr,int *b,int low,int mid,int high)
{
    int i,j,k;
    i = low;
    j = mid+1;
    k = low;

    while((i <= mid) && (j <= high))
    {
        if(arr[i] <= arr[j])
        {
            b[k++] = arr[i++];
        }
        else
        {
            b[k++] = arr[j++];
        }
    }
    while(i<=mid)
        b[k++] = arr[i++];
    while(j<=high)
        b[k++] = arr[j++];
}

int temp_merge_sort(int *arr,int *b,int low,int high)
{
    int mid;
    if(low<high)
    {
        mid = (low)+(high - low)/2;
        temp_merge_sort(arr,b,low,mid);
        temp_merge_sort(arr,b,mid+1,high);
        temp_merge(arr,b,low,mid,high);
    }
    return 0;
}

int main()
{
    int a[100],b[100],i;
    a[0] = 34;
    a[1] = 3;
    a[2] = 14;
    a[3] = 4;
    a[4] = 25;
    a[5] = 67;
    a[6] = 11;
    a[7] = 8;
    a[8] = 12;
    a[9] = 1;
    printf("contents of array a\n");
    for(i=0;i<10;i++)
        printf("%d ",a[i]);
    printf("\n");
    merge_sort(a,b,0,9);
    printf("after using merge_sort function\n");
    printf("contents of auxillary array b\n");
    for(i=0;i<10;i++)
        printf("%d ",b[i]);
    printf("\n");
    printf("contents of array a\n");
    for(i=0;i<10;i++)
        printf("%d ",a[i]);
    printf("\n");
    a[0] = 34;
    a[1] = 3;
    a[2] = 14;
    a[3] = 4;
    a[4] = 25;
    a[5] = 67;
    a[6] = 11;
    a[7] = 8;
    a[8] = 12;
    a[9] = 1;
    printf("contents of array a after reassigning values\n");
    for(i=0;i<10;i++)
        printf("%d ",a[i]);
    printf("\n");
    temp_merge_sort(a,b,0,9);
    printf("after using temp_merge_sort function\n");
    printf("contents of auxillary array b\n");
    for(i=0;i<10;i++)
        printf("%d ",b[i]);
    printf("\n");
    printf("contents of array a\n");
    for(i=0;i<10;i++)
        printf("%d ",a[i]);
    printf("\n");
}

I got the following output for this code
contents of array a
34 3 14 4 25 67 11 8 12 1
after using merge_sort function
contents of auxillary array b
3 4 14 25 34 1 8 11 12 67
contents of array a
1 3 4 8 11 12 14 25 34 67
contents of array a after reassigning values
34 3 14 4 25 67 11 8 12 1
after using temp_merge_sort function
contents of auxillary array b
34 3 14 4 25 67 11 8 12 1
contents of array a
34 3 14 4 25 67 11 8 12 1

Initially I filled array with some numbers. Then I called the function merge_sort. This function recursively calls itself until low less than high. Then merge operation is performed on sub arrays. That is implemented in the function merge in which first elements of original array are copied to auxiliary array and then merge operation is performed. This is working fine and the resulting sorted numbers will be stored in original array.
After that I am refilling the original array with unsorted values and calling the function temp_merge_sort function. This is similar to merge_sort function except that in this merge operation is performed by temp_merge function. In this function instead of copying original array values from low to high to auxiliary array I directly performed merge operation on contents of original array and copied the result to auxiliary array. This is not working fine and contents of auxiliary array remain same as original array unsorted. I don't understand where I made mistake. Could anyone please help out ???
-Thank you

A: At each pass, you are putting the "sorted" elements in b; but since your code is assuming that the elements in arr are becoming more and more sorted, the operation you are performing isn't doing anything useful (because you would need to copy the sorted elements from b back into arr, or rely on the increasingly sorted b as the source of the data which is further sorted).
There is no "one line" solution I can think of given your current code - but that is in essence the problem you have.


text:
Q: custom chapter title I'm using a template and it displays the chapter title like this picture
(a big number for the chapter and the title of the chapter)
I need it to display the word "chapter" too
any idea how to do it??
thank you in advance


text:
Q: Cisco ASA-5505 Port Forwarding I have a Cisco ASA-5505 firewall, which is currently configured to share our internet connection and do NAT for my LAN, as well as forward port 443 to an internal machine.
I need to forward port 2222 to a second internal machine, and I'm running into a bit of trouble. My understanding is that typically packets are forwarded to a machine with a rule like:
static (inside,outside) [Public IP] [Internal IP] netmask 255.255.255.255

However, when I try to add two of these rules, they conflict with each other.
I tried adding port-specific rules like this instead:
static (inside,outside) tcp interface 443 [internal IP 1] 443 netmask 255.255.255.255
static (inside,outside) tcp interface 2222 [internal IP 2] 2222 netmask 255.255.255.255

But then both ports were filtered (as per nmap from a remote machine).
My access-list rules currently look like this:
access-list outside-in line 1 extended permit tcp any host [public IP] eq 443
access-list outside-in line 2 extended permit tcp any host [public IP] eq 2222

Can anyone provide me a working set of static and access-list rules that will forward port 443 to one machine, and port 2222 to a different machine?
EDIT: I should mention that, unfortunately, the only access I have to this ASA is via telnet - I can't use ASDM.

A: FIrst, there can be some discrepancies based on what level of code you are running...
There's a difference betweeen your old static NAT rule and the new rules that would be required to split up the ports from a single WAN IP to multiple internal IPs.
You can get the details from Cisco on how to do this here: http://www.cisco.com/en/US/docs/security/asa/asa84/configuration/guide/nat_objects.html
Youtube can also help visual learners..see here:
http://www.youtube.com/watch?v=ZvjrN9lYtsI

A: In your static rules, don't use interface. Use your public IP instead.


text:
Q: API for storing binary blobs I'm doing some moderately low-level programming of an embedded device that has some NVRAM we plan to use for retaining values between runs of a program. We'd like to abstract the operations into an API over a driver or talking to a daemon.  This is lower-level than the serialization semantics I've seen here and there.  Basically we want a process or function to be able to reserve some space (with some name or other identifier), store a value (arbitrary byte sequence) in that reserved space, retrieve the value later, and surrender the reservation if it no longer needs to use it.  This feels a lot like malloc, write, read, and free.  I'm tempted to implement nvAlloc() (or something) and so on. Or am I missing something obvious?  Maybe security: another process getting a handle and accessing or corrupting the value.

A: It seems http://pramfs.sourceforge.net/ and normal file system access are the right answer.


text:
Q: Is it possible to filter Pandas DataFrame column if column is a list? import pandas as pd

dafr = pd.DataFrame({'a': [1,2,3], 'b': [[1,2,3],[2,3,4],[3,4,5]]})

I try to do something like:
dafr[dafr['b'].isin(2)]

which should return rows that has lists: [1,2,3] & [2,3,4].
I wonder if this is possible?

A: isin returns whether the column value is in what you pass.  You want to check if what you pass is in the column value.
As far as I know there is no direct shortcut for this, but you can do it using map:
>>> dafr[dafr.b.map(lambda x: 2 in x)]
    a          b
0  1  [1, 2, 3]
1  2  [2, 3, 4]

A: dafr[dafr['b'].apply(lambda x: 2 in x)]

A: If you stored b as column of tuples rather than column of lists, afr[dafr['b'].apply(lambda x: 2 in x)]
will execute quite fast.


text:
Q: how to prevent of duplicating records in mysql insertion queries? i always in inserting data into a mysql table i use a select for that data before inserting to avoid duplicate records and if the query return null then i insert record.
but i think maybe it is not a professional way to do this job.
would you let me the ways you do?

A: if the reason you don't wish to use primary keys, or unique indexes is because of the error this will generate (which is an issue if you are inserting multiple rows on a single query), you can use the following syntax
insert ignore into [tablename] () VALUES ()

You can also use ON DUPLICATE KEY UPDATE as in to update certain fields as well.
insert into [tablename] () VALUES () ON DUPLICATE KEY UPDATE

for more information, have a look at http://dev.mysql.com/doc/refman/5.1/en/insert.html

A: You can try the following example. I would suggest you to try this first in your testing environment then you can implement this in your actual scenario.

Follow the below steps:

Step 1: create a table

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `email` varchar(50) NOT NULL,
  `password` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Step 2: Run this query multiple times and check that only one row is inserted

INSERT INTO `student` ( `name`, `age`)
SELECT `name`, `age` FROM `student`
WHERE NOT EXISTS (SELECT 1
    FROM `student`
    WHERE `name` = 'manish'
    AND `age` = '23'
    );

A: The "professional" way to do this will be using a primary key constraint.

A: $qry="INSERT username INTO users";
if(!mysql_query($qry))
{
  if(mysql_errno()=1062)
  {
    echo 'Unique costraint violation!';
  }
  else
  {
    //other error
  }
}


text:
Q: What does 'turn on' mean exactly in this context? The dialogue is about a mole who would provide them secret information about the inner circle.

– I don't buy it. Didn't you tell me yourself, nobody turns on
  al-Qaeda?
– The Jordans have worked him for a year, dinners, money. They
  convinced him... it's his patriotic duty to turn on al-Qaeda, and
  get rich doing it.

(Film: Zero Dark Thirty - United States, 2012)

A: I haven't seen the film, but from the context I can guess that it means "to betray". "To turn on someone" means "to betray (someone)": "He turned on me" means "He betrayed me" (he was "with" me and now he is "against" me, and thus he "turned" on me).
(Note that this should not be confused with "to turn someone on" which means "to arouse"...)


text:
Q: Comparing a PrintWriter to another PrintWriter I have two PrintWriters:
PrintWriter pw1 = new PrintWriter("testPrint.txt");
PrintWriter pw2 = new PrintWriter("testPrint.txt");

I want to to check if both of them print to the same file, but comparing with
pw1.equals(pw2)

or
Objects.equals(pw1, pw2)

doesn't work. Also, instead of String with a path to file I want to be able to check if PrintWriters like those two print to the same place in general:
PrintWriter pw1 = new PrintWriter(System.out, true);
PrintWriter pw2 = new PrintWriter(System.out, true);

Is there a way to do that?

A: No, not from two Print writers as you have written it. In general, having two writers writing to the same destination is a problem you should avoid. Instead, if you want multiple sources writing to the same file, use one PrintWriter and a queue of messages to be written.
You may also want to check out FileChannel, which can be locked. See: can we open multiple FileWriter stream to the same file at the same time?

A: There's no way from the outside to check a PrintWriter's underlying stream. There is an out member variable but it's a protected property only accessible by subclasses.

protected Writer out

The underlying character-output stream of this PrintWriter.

Even if you had access to this field, though, it still wouldn't be as easy as comparing two instances. The two underlying writers could be different objects that write to the same place. That is exactly what will happen when you use the PrintWriter(String) constructor from your first example:
package java.io;

public class PrintWriter extends Writer {
    // ...

    public PrintWriter(String fileName) throws FileNotFoundException {
        this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
             false);
    }

    // ...
}

It would create two BufferedWriters, which would point to distinct OutputStreamWriters, which would point to distinct FileOutputStreams. It's turtles all the way down.


text:
Q: WordPress title image My WordPress Blog consists of the following snippet:
<?php
    $images = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');
    if (count($images) > 0) { ?>

       <a href="<?php the_permalink(); ?>"><img src="<?php bloginfo('template_directory') ?>/javascript/timthumb.php?src=<?php echo $images[0]; ?>&h=320&w=630&zc=1" alt="<?php the_title();?>"  />

    <?php }
?>

This displays a title image (featured image) on top of the actual content and uses timthumbb to resize it. All is fine here, however it shows a broken img src if there is no defined featured image. Is there a way to edit this in order to only display the image if there is actually one present?

A: I used this and it works fine:
// get the ancestors
$familyTree = get_ancestors($post->ID, 'page');
array_unshift($familyTree, $post->ID); //add the current page to the beginning of the list

// loop through the family tree until you find a result or exhaust the array
$featuredImage = '';
foreach ($familyTree as $family_postid) {
    if (has_post_thumbnail($family_postid)) {
        $featuredImage = get_the_post_thumbnail($family_postid, 'full');
        // the 'full' argument tells WordPress not to re-size the image to thumbnail dimensions
        break;
    }
}

// if the page has a featured image then show it
echo ($featuredImage ? $featuredImage : "");

it also applies the featured image to child pages unless the child page has it's own featured image, not sure if you want that but shouldn't be too difficult to not show anything if there is no featured image.

A: Try using this logic

<?php

    if($images[0]!='')
    {

           <a href="<?php the_permalink(); ?>"><img src="<?php bloginfo('template_directory') ?>/javascript/timthumb.php?src=<?php echo $images[0]; ?>&h=320&w=630&zc=1" alt="<?php the_title();?>"  />

    }

    ?>

A: if there is only one image, you can use
if ($images[0]!='') {

A: You can use the function has_post_thumbnail() to check whether the post has a featured image or not.
Usage:

    $images = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');
    if (count($images) > 0) { ?>

       <a href="<?php the_permalink(); ?>"><img src="<?php bloginfo('template_directory') ?>/javascript/timthumb.php?src=   <?php echo $images[0]; ?>&h=320&w=630&zc=1" alt="<?php the_title();?>"  />

    <?php }
} ?>


text:
Q: About cycles and the values in the range of a permutation function Let $f = \{(x_1 y_1), (x_2 y_2), \ldots, (x_n y_n)\}$ be a permutation. A cycle of $f$ is given by $g = (1, f(1), f^2(1), f^3(1) \ldots)$. When counting permutations, we usually drop $1$ and count lists of the form $h = (y_1, y_2, \ldots,y_n).$
For example, let $(123)$ be a cycle which is $(231)$ if put in the form of $h$ above. Does it mean $g$ and $h$ are equal/same cycle?

A: $g$ and $h$ are the same permutation.  You can see by writing both out in the form of $f$.


text:
Q: merging two queries together via mysql I want to merge two queries together, but I do not know how!
First query:
SELECT tablesite.name,
           tablesite.family,
           job_list.job_name,
           tablesite.phone_number
           FROM  tablesite
           INNER JOIN relation
           on tablesite.id_user=relation.user_id
           INNER JOIN job_list
           on relation.job_id=job_list.job_id

I have jobs in this query.

Second query:
SELECT tablesite.name,
       tablesite.family,
       tablesite.phone_number,
       COUNT(action.service_provider_id)
       FROM tablesite
       LEFT JOIN action
       ON tablesite.id_user=action.service_provider_id
       AND action.vote !='' AND action.customer_comment =''
       GROUP BY name, family, phone_number

Result of this table is this:

i have COUNT(action.service_provider_id)  when  COUNT(action.service_provider_id) in second query

after merging these two tables, the result have to like this:
i made this with paint :p :D

used tables

tablesite:

action:

relation:

job_list:

sasha tried this:

A: The results of both queries can be combined like this:
CREATE TEMPORARY TABLE t1 (KEY(name,family,phone_number)) SELECT tablesite.name,
               tablesite.family,
               job_list.job_name,
               tablesite.phone_number
               FROM  tablesite
               INNER JOIN relation
               on tablesite.id_user=relation.user_id
               INNER JOIN job_list
               on relation.job_id=job_list.job_id;
SELECT ts.name,
           ts.family,
           ts.phone_number,t1.job_name,
           COUNT(action.service_provider_id)
           FROM tablesite ts JOIN t1 USING(name,family,phone_number)
           LEFT JOIN action
           ON ts.id_user=action.service_provider_id
           AND action.vote !='' AND action.customer_comment =''
           GROUP BY name, family, job_name, phone_number;

It is possible to avoid the use of the temporary table using a sub-query, but it would run into issues if the result set is large due to the lack of join key in the sub-query result.


text:
Q: how to embed XHTML in XML without DOCTYPE, CDATA or escapes? Is there any way embed XHTML entity references into XML text without the DOCTYPE DTD declaration?  The DOCTYPE line is causing problems on the java server it's targeting.
Escaping the &; sequence isn't acceptable, nor is embedding in CDATA.  The references need to be validated.
Is is possible to reference the DTD from the schema definition instead of the XML data file.
More broadly speaking, what is the common practice for embedding XHTML (or at least entity references) in XML and having that validated?
One potential solution is to convert the entire XHTML 1.0 DTD to a schema, but this doesn't sound like the best idea.

A: Have you tried a DOCTYPE without PUBLIC or SYSTEM identifiers?
You can either add the ENTITY declarations directly to the internal subset:
<!DOCTYPE foo [
<!ENTITY nbsp   " ">
<!ENTITY copy   "©">
<!ENTITY laquo  "«">
<!ENTITY reg    "®">
<!ENTITY deg    "°">
<!ENTITY plusmn "±">
<!ENTITY sup2   "²">
<!ENTITY sup3   "³">
<!ENTITY frac14 "¼">
<!ENTITY frac12 "½">
<!ENTITY frac34 "¾">
]>
<foo/>

or you can use a parameter entity to point to an external file/files that have your ENTITY declarations:
<!DOCTYPE foo [
<!ENTITY % ents SYSTEM "xhtml-lat1.ent">
%ents;
]>
<foo/>

A: The XML is not well formed if you have entity references other than the 5 pre-defined ones, and don't have a doctype.
You simplify things greatly if you use numeric character references rather than named entity references so use
  instead of
Either by modifying the original generation if you control that, or just expanding the entities by using any xml parser or a simple text replace using perl or equivalent. You can get full list of the html(5) entity set in dtd or json or other formats here http://www.w3.org/2003/entities/2007/


text:
Q: Receiving MMS in android and show it in my application as ListView i am developing an application that should receive MMS from Specific Number.and
and i found this code but it is give me a nothing,just hello world TextView
any Help will appriacte it
    package com.wzx.andapp.shh;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.text.MessageFormat;
    import android.app.Activity;
    import android.content.ContentResolver;
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.net.Uri;
    import android.os.Bundle;
    import android.telephony.SmsMessage;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.widget.ListView;
    import android.widget.TextView;

    public class MmsReaderActivity extends Activity {
    private final Uri CONTENT_URI_PART = Uri.parse("content://mms/part"); // ²ÊП½¼þ±í

    private static final String MSG_ID_STR = "mid=%1$s";

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            long msg_id = this.getIntent().getLongExtra("msg_id", 0);
            // final LayoutInflater inflater = LayoutInflater.from(this);
            // final ViewGroup v = (ViewGroup) inflater.inflate(
            // R.layout.mms_item_detail, null);
            setContentView(R.layout.mms_item_detail);

            ViewGroup listview = (ViewGroup) findViewById(R.id.mmsdetaillist);
            // Uri uri = Uri.parse("content://mms/");
            // String selection = "_id = " + msg_id;
            // Cursor mcursor = getContentResolver().query(uri, null, selection,
            // null,
            // null);

            Cursor cursor = getContentResolver().query(CONTENT_URI_PART, null,
                            String.format(MSG_ID_STR, msg_id), null, null);

            if (cursor.moveToFirst()) {
                    do {
                            String partId = cursor.getString(cursor.getColumnIndex("_id"));
                            String type = cursor.getString(cursor.getColumnIndex("ct"));
                            if ("text/plain".equals(type)) {
                                    String data = cursor.getString(cursor
                                                    .getColumnIndex("_data"));
                                    String body;
                                    if (data != null) {
                                            // implementation of this method below
                                            body = getMmsText(partId);
                                    } else {
                                            body = cursor.getString(cursor.getColumnIndex("text"));
                                    }
                                    TextView t = new TextView(this);
                                    t.setText(body);
                                    listview.addView(t);
                            } else if ("image/jpeg".equals(type)
                                            || "image/bmp".equals(type) || "image/gif".equals(type)
                                            || "image/jpg".equals(type) || "image/png".equals(type)) {
                                    Bitmap bitmap = getMmsImage(partId);
                                    ImageView iv = new ImageView(this);
                                    iv.setImageBitmap(bitmap);
                                    listview.addView(iv);
                            }
                    } while (cursor.moveToNext());
            }
            cursor.close();

      }

       public void getAllMms() {
            Uri uri = Uri.parse("content://mms/");
            String selection = null;// "_id = " + mmsId;
            Cursor cursor = getContentResolver().query(uri, null, selection, null,
                            null);
            String[] temp = cursor.getColumnNames();
            for (int i = 0; i < temp.length; i++)
                    System.out.println(i + ":" + temp[i]);
            cursor.close();
    }

    /**
     *
     */
    // _id is the ID of the message. Captain obvious to the rescue? Not really.
    // This ID can be used to retrieve detailed information using either
    // content://sms or content://mms.
    // date no explanation needed.
    // thread_id is the ID of the conversation
    // body The content of the last SMS on this conversation.
    // If it's an MMS, even if it has a text part, this will be null.

    public void getSmsMms() {
            // usually, when you call query and want to return all columns you can
            // pass null as the projection parameter. However, you can not do that
            // with this provider, so that's why I'm using *
            ContentResolver contentResolver = getContentResolver();
            final String[] projection = new String[] { "*" };
            Uri uri = Uri.parse("content://mms-sms/conversations/");
            Cursor cursor = contentResolver
                            .query(uri, projection, null, null, null);
            String[] temp = cursor.getColumnNames();
            for (int i = 0; i < temp.length; i++)
                    System.out.println(i + ":" + temp);

    }

    public void getMms(String mmsId) {
            Uri uri = Uri.parse("content://mms/");
            String selection = "_id = " + mmsId;
            Cursor cursor = getContentResolver().query(uri, null, selection, null,
                            null);
    }

    public void getAllText(String mmsId) {
            String selectionPart = "mid=" + mmsId;
            Uri uri = Uri.parse("content://mms/part");
            Cursor cursor = getContentResolver().query(uri, null, selectionPart,
                            null, null);
            if (cursor.moveToFirst()) {
                    do {
                            String partId = cursor.getString(cursor.getColumnIndex("_id"));
                            String type = cursor.getString(cursor.getColumnIndex("ct"));
                            if ("text/plain".equals(type)) {
                                    String data = cursor.getString(cursor
                                                    .getColumnIndex("_data"));
                                    String body;
                                    if (data != null) {
                                            // implementation of this method below
                                            body = getMmsText(partId);
                                    } else {
                                            body = cursor.getString(cursor.getColumnIndex("text"));
                                    }
                            }
                    } while (cursor.moveToNext());
            }

    }

    public String getMmsText(String id) {
            Uri partURI = Uri.parse("content://mms/part/" + id);
            InputStream is = null;
            StringBuilder sb = new StringBuilder();
            try {
                    is = getContentResolver().openInputStream(partURI);
                    if (is != null) {
                            InputStreamReader isr = new InputStreamReader(is, "UTF-8");
                            BufferedReader reader = new BufferedReader(isr);
                            String temp = reader.readLine();
                            while (temp != null) {
                                    sb.append(temp);
                                    temp = reader.readLine();
                            }
                    }
            } catch (IOException e) {
            } finally {
                    if (is != null) {
                            try {
                                    is.close();
                            } catch (IOException e) {
                            }
                    }
            }
            return sb.toString();
    }

    public void getAllImg(String mmsId) {
            String selectionPart = "mid=" + mmsId;
            Uri uri = Uri.parse("content://mms/part");
            Cursor cPart = getContentResolver().query(uri, null, selectionPart,
                            null, null);
            if (cPart.moveToFirst()) {
                    do {
                            String partId = cPart.getString(cPart.getColumnIndex("_id"));
                            String type = cPart.getString(cPart.getColumnIndex("ct"));
                            if ("image/jpeg".equals(type) || "image/bmp".equals(type)
                                            || "image/gif".equals(type) || "image/jpg".equals(type)
                                            || "image/png".equals(type)) {
                                    Bitmap bitmap = getMmsImage(partId);
                            }
                    } while (cPart.moveToNext());
            }

    }

    public Bitmap getMmsImage(String _id) {
            Uri partURI = Uri.parse("content://mms/part/" + _id);
            InputStream is = null;
            Bitmap bitmap = null;
            try {
                    is = getContentResolver().openInputStream(partURI);
                    bitmap = BitmapFactory.decodeStream(is);
            } catch (IOException e) {
            } finally {
                    if (is != null) {
                            try {
                                    is.close();
                            } catch (IOException e) {
                            }
                    }
            }
            return bitmap;
    }

    public String getAddressNumber(int id) {
            String selectionAdd = new String("msg_id=" + id);
            String uriStr = MessageFormat.format("content://mms/{0}/addr", id);
            Uri uriAddress = Uri.parse(uriStr);
            Cursor cAdd = getContentResolver().query(uriAddress, null,
                            selectionAdd, null, null);
            String name = null;
            if (cAdd.moveToFirst()) {
                    do {
                            String number = cAdd.getString(cAdd.getColumnIndex("address"));
                            if (number != null) {
                                    try {
                                            Long.parseLong(number.replace("-", ""));
                                            name = number;
                                    } catch (NumberFormatException nfe) {
                                            if (name == null) {
                                                    name = number;
                                            }
                                    }
                            }
                    } while (cAdd.moveToNext());
            }
            if (cAdd != null) {
                    cAdd.close();
            }
            return name;
    }

    /**
     * Mark a single SMS/MMS message as being read or not.
     *
     * @param context
     *            - The current context of this Activity.
     * @param messageID
     *            - The Message ID that we want to alter.
     *
     * @return boolean - Returns true if the message was updated successfully.
     */
    public static boolean setMessageRead(Context context, long messageID,
                    boolean isViewed) {
            try {
                    if (messageID == 0) {
                            return false;
                    }
                    ContentValues contentValues = new ContentValues();
                    if (isViewed) {
                            contentValues.put("READ", 1);
                    } else {
                            contentValues.put("READ", 0);
                    }
                    String selection = null;
                    String[] selectionArgs = null;
                    context.getContentResolver().update(
                                    Uri.parse("content://mms/" + messageID), contentValues,
                                    selection, selectionArgs);
                    return true;
            } catch (Exception ex) {
                    return false;
            }
    }

   }

Thanks in advance. I REALLY NEED HELP PLEASE

A: try changing the following line:
Cursor cursor = getContentResolver().query(CONTENT_URI_PART, null, String.format(MSG_ID_STR, msg_id), null, null);
to:
Cursor cursor = getContentResolver().query(uri, null,
            null, null, null);


text:
Q: Angular 2 AOT vs JIT payload comparison I'm pretty new to Angular 2, so correct me if I'm inaccurate.
My understanding of Angular 1 vs 2 when it comes to compiler:
In Angular 1 the compiler is more general and dynamic, meaning that dirty checking code is a single code running over different components. However for performance sake in Angular 2, every component will get compiled to a generated code that handles bindings and dirty checking for that specific component. It means that depending on the component template, more specifically number of bindings, the generated code becomes larger.
When we use JIT, this is not important as this code doesn't go through the network and is generated in browser. But when using AOT it's going to be transferred from the server.
The problem (possibly):
When the application is small, AOT will definitely result in smaller payload as the compiler is not going to be shipped to browser. But as the application grows, I assume this difference starts to decrease and maybe become inverted (does it?!). But I don't have a quantitative sense of it. Is it going to be a real issue for medium or large scale applications?

A: To answer the question "But as the application grows, I assume this difference starts to decrease and maybe become inverted (does it?!)" :
Yes it does, on a very large app the difference can be seen.
I asked a similar question on the webpack starter github, to quote the answer :

You might notice that the main file and chunk files are larger in build:prod:aot then in build:prod, this is perfectly normal since AOT produces more code.
  The total amount is less in AOT since the compiler is not part of the bundle, you can see it in the size of the vendor bundle.
  This also means that as your application grow, AOT will yield larger code since you add more AOT generated code but the compiler size is constant.
  The angular team is working on reducing the emitted code, one of the upcoming feature for this is a new View Engine that will reduce bundle size but will slightly effect performance (it's always a tradeoff)

Still, the apps starts way faster with AOT than JIT.
Please see the issue, it seems the angular2 team is aware of this and plan on reducing this behavior.
https://github.com/AngularClass/angular2-webpack-starter/issues/1520
The issue to track on angular2 team side : https://github.com/angular/angular/issues/14013
UPDATE : Now live with Angular 4 https://github.com/angular/angular/blob/master/CHANGELOG.md#view-engine

We've made changes under to hood to what AOT generated code looks like. These changes should reduce the size of the generated code for your components by more than half in some cases. Read the Design Doc for the View Engine updates.

A: The solution is to actually manage correctly AOT, with LazyLoading.
To really give an answer, there will be problems, but now we have the tools to manage them. Lazy Loading is a solution that we could not apply to AngularJS easily.
Check out this link, that is really well made and covers the whole subject about modules, contexts, and compilation :
http://blog.angular-university.io/angular2-ngmodule/
You can also combine both and get the best of it :
http://blog.assaf.co/angular-2-harmony-aot-compilation-with-lazy-jit-2/


text:
Q: Android / Nexus 7 throwing IOException for Geocoder.getFromLocationName() I'm trying to use Geocoder.getFromLocationName() and although the same search string works fine on these actual devices:

*

*Nexus 1 (2.3.6)

*Samsung Galaxy SIII (4.0.4)

*Galaxy Nexus (4.1.1)

on my Nexus 7 (4.1.1), the method throws a "Service not available" IOException
Here is the simplified code:
Geocoder geocoder = new Geocoder(mContext);
List<Address> addressFromSearch = geocoder.getFromLocationName("10918", 1);

I've also tried each device using mobile data and wifi-only and they all work fine. So far the only device/OS that does not work is the Nexus 7. I've also checked Geocoder.isPresent() -- and it returns true.
Any thoughts on what I may be missing?

A: After the OTA-Update for Galaxy Nexus to 4.1.2 this problem is solved finally. It was a bug regarding the Android version 4.1.1

A: I also get this issue on samsung galaxy tab 2 android 4.0.4, I'm going to see if theres an update but definitely I'm up voting the issue.
Looks like there is a work around for my device!
If you reboot your machine on the samsung galaxy tab 2...it actually starts working!...thats what I call a work around!


text:
Q: Not getting the correct location of search control in tableview on iPhone 4s I am using CGPoint to get the location of the control in tableview with indexPath. It is working fine with iPhone 5, iPhone 6, and iPhone 6s, but it's not giving proper coordinate with iPhone 4s. Please provide solution where I am wrong.
I am using following code:
-(BOOL)searchBarShouldBeginEditing:(CustomSearchBar *)searchBar
{
    CGRect cellRect =[self.tblFormDetail rectForSection:searchBar.indexPath.section];

    CGPoint origin=[self.tblFormDetail convertPoint:cellRect.origin fromView: self.tblFormDetail];
    CGPoint originView=[self.view convertPoint:cellRect.origin fromView: self.tblFormDetail];

    NSLog(@"origin from tbl %f",origin.y);
    NSLog(@"origin from view %f",originView.y);

    pointScroll=self.tblFormDetail.contentOffset;

    pointSizeScroll=self.tblFormDetail.contentSize;
    [self.tblFormDetail setContentSize:CGSizeMake(self.tblFormDetail.frame.size.width,pointSizeScroll.height+originView.y)];

    [self.tblFormDetail setContentOffset:CGPointMake(0, origin.y)animated:NO];
}


text:
Q: how to use django related_name I have two models named Meeting and MeetingMember like this :
 class Meeting(models.Model):
      title = models.CharField(max_length=255)
      description = models.TextField()

 class MeetingMember(models.Model):
     CHOICES = [
         ("A", "Accepted"),
         ("R", "Rejected"),
         ("I", "Invited" ),
         ("H", "Host"),
     ]

     status = models.CharField(max_length=9, choices=CHOICES, default="I")
     meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE, related_name="members")
     email = models.EmailField(blank=True)

I need to write a query that first gets all the records in MeetingMeember model which belong to the current logged in user like this :
meetingmembers  = MeetingMember.objects.filter(email = request.user.email)

then i need to the get all the info from the meetings belongs to the  MeetingMeember (the second queryset should be Meeting object)
i have studied about related_name but still can't figure out how can i write this.

A: You can filter with:
Meeting.objects.filter(
    members__email=request.user.email
)
to retrieve all the Meetings for which the email of the logged in user is a member.
If you work with the Member model, you can use .select_related(…) [Django-doc] to retrieve the Meeting object in the same query, then for some_member, you can access the related Meeting (and info with) some_member.meeting without making an extra query:
meetingmembers = MeetingMember.objects.filter(
    email=request.user.email
).select_related('meeting')

for member in meetingmenbers:
    print(member.meeting)

A: The related_name attribute specifies the name of the reverse relation from the Meeting model back to MeetingMember model.
If you have MeetingMember object like meeting_member and your related_name is 'members' then
meeting_member.members.all() to get all instances of your Meeting model that have a relation to object.

A: According to your design an Meeting object belongs to multiple MeetingMember objects and you can access them using related name members like metting_obj.members.all() and an MeetingMember object belongs to a single Meeting object and you can assess using the attribute meeting like metting_member_obj.metting
you can retrieve all Meeting objects belongs to MeetingMember objects as following:
meeting_objs = [meeting_member.meeting for meeting_member in meetingmembers]