text:
Q: How do I get the Broadcom BCM4313 wireless working on an Asus 1015PX? I installed Ubuntu 11.10 on my Asus 1015PX which is certified by Canonical. My WiFi is not working. I read about the BCM4313 troubles and tried

*

*https://help.ubuntu.com/community/WifiDocs/Driver/bcm43xx

*http://www.broadcom.com/support/802.11/linux_sta.php

*I already tried everything in the thread Broadcom BCM4313 working, but terribly slow but nothing worked for me.

and others but nothing helped.
Can anyone give a detailed description point-by-point what he did to get this thing working on an Asus 1015PX?

A: The BCM4313 broadcom wireless card is compatible with the open source brcm80211 driver directly included in the standard kernel or the proprietary broadcom-wl driver that can be installed from the Additional Drivers in Ubuntu. At any point of time, you should only have one of the drivers installed and trying to use it simultaneously will only result in the drivers conflicting each other.
It should be also noted that broadcom-wl has been causing more problems than resolving them and you should probably avoid them altogether if possible.
To answer your problem, I have used the steps provided in this forums thread. This method is more like a workaround for the problem rather than a permanent fix to the issue.
First of all, blacklist the wl, brcm80211 and b43 modules and all its dependencies.
gksudo gedit /etc/modprobe.d/blacklist.conf

After opening the file, add the following to it:
blacklist mac80211
blacklist brcm80211
blacklist cfg80211
blacklist wl
blacklist lib80211_crypt_tkip
blacklist lib80211
blacklist b43

And then, edit the rc.local file:
gksudo gedit /etc/rc.local

And add the following above exit 0:
modprobe brcm80211

This will ensure that the brcm80211 driver module is loaded at the end of the boot process. You might need to call update-initramfs -u to ensure that your changes will be effective after a reboot.

I should probably add the fact that I have BCM4313 wireless driver in my system and I have used these procedures to get it working properly.

References:

*

*https://wiki.archlinux.org/index.php/Broadcom_wireless

*http://linuxwireless.org/en/users/Drivers/b43

*http://linuxwireless.org/en/users/Drivers/brcm80211

*http://ubuntuforums.org/showthread.php?t=1783272

A: I have a HP Pavilion dm4 with a BCM4313. I also had a lot of problems to get it to work in a normal, reliable way. Here is how I finally did solve my problems.

*

*After installing 11.10 64-bit wireless was working but in a very
slow,unreliable way based on the brcmsmac driver in kernel
3.0.0.12-generic. Please take note about the following: The brcmsmac driver was not present in the 11.04 release and the STA driver was working fine in release 11.04. Logically I started to suspect the brcmsmac driver.Before resolving my wifi problems I first installed all updates including the 3.0.0.14-generic kernel. I don't know if this is really necessary in order to make the steps below work.

*Blacklist the bcma and brcmsmac as follows
Open the Terminal (Ctrl+Alt+T) and run this command:
gksu gedit /etc/modprobe.d/blacklist

Add the following lines to this file:
blacklist bcma
blacklist brcmsmac

Save the file and close the text editor.

*Install the STA driver via the "Additional drivers" app. Please remind that you might need to do this via a wired connection since I do believe that blacklisting breaks your brmsmac based wifi connection. Maybe you also need to restart your laptop/netbook after installing the STA driver. I don't remember...

*Try to connect to your wifi network.
I hope this will work for you. Nowadays my wifi connection is fast and reliable.

A: Other people had some trouble with your wifi card; here is another question that it's supposed to be solved:
WiFi is not enabled  in Network Manager with a BCM4313
Here is another question that explains the possible drivers for your hardware and how they work:
How do I get my Broadcom BCM4313 working correctly?

A: Please check:
lspci -nn

Is it's pci.id 14e4:4727?
If so, this may be helpful:
sudo apt-get install linux-headers-generic
sudo apt-get install --reinstall bcmwl-kernel-source
sudo modprobe wl

A: I followed what jokerdino suggested, except I added brcmsmac to rc.local and did not blacklist it.  Then, go into the bios, disable the wireless card (put it on lock), go into the operating system,  restart, go into the bios and unlock it.  Then all the SSIDs started showing up and I was a happy camper.  I did verify that once I added brcmsmac that the network manager started showing wireless settings, but using rfkill I saw the hard lock was on the card, so I reset it.

A: Try the solution here.
http://www.computerandyou.net/2011/05/how-to-solve-no-wireless-networks-in-ubuntu-11-04/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Progress Bar does not work Progress Bar does not work, it appears and disappears immediately
I want to progress bar is work all the time until a request is made, it works only for a moment.Explain to me , what it can be connected , I'm confused now!
Code
class MyAsyncTask extends AsyncTask<Void, Void, Void> {
    ProgressBar loading;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        loading = (ProgressBar) findViewById(R.id.progressBar);
        loading.setVisibility(View.VISIBLE);
    }

    @Override
    protected Void doInBackground(Void... params) {
        VKRequest request = VKApi.audio().get();
        request.executeWithListener(new VKRequest.VKRequestListener() {
            @Override
            public void onComplete(VKResponse response) {
                super.onComplete(response);
                list_music = (VKList) response.parsedModel;
                list = new ArrayList<String>();
                URLlist = new ArrayList<String>();
                for (int i = 0; i < list_music.size(); i++) {
                    list.add(list_music.get(i).title + " - " + list_music.get(i).artist);
                    URLlist.add(list_music.get(i).url);
                }
                array = new ArrayAdapter<String>(VkMusicAct.this,
                        android.R.layout.simple_expandable_list_item_1, list);
                listView.setAdapter(array);
            }

            @Override
            public void onError(VKError error) {
                super.onError(error);
                Toast toastError = Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG);
                toastError.show();
            }
        });
        return null;
    }

    @Override
    protected  void onPostExecute(Void f) {
        super.onPreExecute();
        loading.setVisibility(View.GONE);
    }

}

A: add your progress bar inside  onComplete() method.
see below.
class MyAsyncTask extends AsyncTask<Void, Void, Void> {
    ProgressBar loading;
    Activity activity;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        loading = (ProgressBar) findViewById(R.id.progressBar);
        activity = (Activity) loading.getContext();
        loading.setVisibility(View.VISIBLE);
    }

    @Override
    protected Void doInBackground(Void... params) {
        VKRequest request = VKApi.audio().get();
        request.executeWithListener(new VKRequest.VKRequestListener() {
            @Override
            public void onComplete(VKResponse response) {
                super.onComplete(response);
                list_music = (VKList) response.parsedModel;
                list = new ArrayList<String>();
                URLlist = new ArrayList<String>();
                for (int i = 0; i < list_music.size(); i++) {
                    list.add(list_music.get(i).title + " - " + list_music.get(i).artist);
                    URLlist.add(list_music.get(i).url);
                }
                array = new ArrayAdapter<String>(VkMusicAct.this,
                        android.R.layout.simple_expandable_list_item_1, list);
                listView.setAdapter(array);
                activity.runOnUiThread(new Runnable() {
                                           @Override
                                           public void run() {
                                               loading.setVisibility(View.GONE);
                                           }
                                       }
                        }

                @Override
                public void onError(VKError error) {
                    super.onError(error);
                    Toast toastError = Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG);
                    toastError.show();
                }
            });
            return null;
        }

        @Override
        protected  void onPostExecute(Void f) {
            super.onPreExecute();
        }

    }

A: Use onProgressUpdate to dismiss the dialog. Override onProgressUpdate in your class as:
@Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
               loading.setVisibility(View.GONE);
        }

and in your doInBackground() use it as:
  @Override
  public void onComplete(VKResponse response) {
  super.onComplete(response);
  list_music = (VKList) response.parsedModel;
  list = new ArrayList<String>();
  URLlist = new ArrayList<String>();
     for (int i = 0; i < list_music.size(); i++) {
        list.add(list_music.get(i).title + " - " + list_music.get(i).artist);
      URLlist.add(list_music.get(i).url);
     }
                array = new ArrayAdapter<String>(VkMusicAct.this,
                android.R.layout.simple_expandable_list_item_1, list);
                listView.setAdapter(array);
                publishProgress();
            }


text:
Q: Filling null values in dataset Iam getting this error when Iam filling null values with mean with pandas.
def random_values_fill(feature):
    random_values = data[feature].dropna().sample(data[feature].isnull().sum())
    random_values.index = data[data[feature].isnull()].index
    data.loc[data[feature].isnull(),feature] = random_values

Traceback (most recent call last):
  File "C:\Users\PycharmProjects\machine_learning\powerco-cuschurn.py", line 27, in <module>
    random_values_fill(col)
  File "C:\Users\PycharmProjects\machine_learning\powerco-cuschurn.py", line 22, in random_values_fill
    random_values = data[feature].dropna().sample(data[feature].isnull().sum())
  File "C:\Users\PycharmProjects\machine_learning\venv\lib\site-packages\pandas\core\generic.py", line 5343, in sample
    elif frac is None and n % 1 != 0:
  File "C:\Users\PycharmProjects\machine_learning\venv\lib\site-packages\pandas\core\generic.py", line 1534, in __nonzero__
    raise ValueError(
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

What is the mistake here?


text:
Q: No insertion to a MySQL database of scraped data using scrapy I use Scrapy to get data and I want to store them inside a MySQL database. To perform that, I copy and adapt a large part of the code here.
It looks really nice, but there is no way to make it work on my side. The code doesn't make any errors, data are properly scraped but my database is empty.
Here is the code of my pipeline :
class MySQLPipeline(object):

    def __init__(self):
        self.dbpool = dbpool

    @classmethod
    def from_settings(cls, settings):
        dbargs = dict(
            host=settings['MYSQL_HOST'],
            db=settings['MYSQL_DBNAME'],
            user=settings['MYSQL_USER'],
            passwd=settings['MYSQL_PASSWD'],
            charset='utf8',
            use_unicode=True,
        )
        dbpool = adbapi.ConnectionPool('MySQLdb', **dbargs)
        return cls(dbpool)

    def process_item(self, item, spider):
        d = self.dbpool.runInteraction(self._do_upsert, item, spider)
        d.addErrback(self._handle_error, item, spider)
        d.addBoth(lambda _: item)
        return d

    def _do_upsert(self, conn, item, spider):
        guid = self._get_guid(item)
        now = datetime.utcnow().replace(microsecond=0).isoformat(' ')

        conn.execute("""SELECT EXISTS(
            SELECT 1 FROM produits WHERE guid = %s
        )""", (guid, ))
        ret = conn.fetchone()

        if ret:
            conn.execute("""
                UPDATE produits
                SET product=%s, link=%s, price=%s, description=%s, image_urls=%s, image=%s, brand=%s, couleur=%s, gamme=%s, largeur=%s, profondeur=%s, hauteur=%s, longueur=%s, diametre=%s, updated=%s
                WHERE guid=%s
        """, (item['product'], item['link'], item['price'], item['description'], item['image_urls'], item['image'], item['brand'], item['couleur'], item['gamme'], item['largeur'], item['profondeur'], item['hauteur'], item['longueur'], item['diametre'], now, guid))
            spider.log("Item updated in db: %s %r" % (guid, item))
            self.dbpool.commit()
        else:
            conn.execute("""
                INSERT INTO produits (product, link, price, description, image_urls, image, brand, couleur, gamme, largeur, prodonfeur, hauteur, longueur, diametre, updated, guid)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )
        """, (item['product'], item['link'], item['price'], item['description'], item['image_urls'], item['image'], item['brand'], item['couleur'], item['gamme'], item['largeur'], item['profondeur'], item['hauteur'], item['longueur'], item['diametre'], now, guid))
            spider.log("Item stored in db: %s %r" % (guid, item))
            self.dbpool.commit()

    def _handle_error(self, failure, item, spider):
        log.err(failure)

    def _get_guid(self, item):
        return md5(item['link']).hexdigest()

Here is the code of my settings :
ITEM_PIPELINES = {
'Comparito.pipelines.ImagesPipeline':1,
'Comparito.pipelines.MySQLPipeline':300,
}

If someone can help me to understand why it doesn't insert anything in my database, it would be great.
Thank you


text:
Q: Formula for fitting step-wise increasing loan payments into a given term My company is developing a product that helps people project out what-if scenarios for paying down their student loan debt. One of the government options for paying off debt is called the "graduated" program, under which the beginning payment is known, and every two years the required payment increases such that the timeline for payoff fits within a desired term, say 30 years.
We've been unable to find a documented formula for this payment schedule. Does anyone have an idea or starting point?
Example: $100,000 in total debt at 6.5% interest. Desired term is 30 years.
Input variables: total debt, yearly interest rate, desired term
Payment for years 1-2 is always: debt * yearly interest rate / 12
From there the required payment goes up every two years, so years 3-4, 5-6, etc. until the principal balance reaches zero at the end of the desired term (30 years.)
Note: desired term is not always evenly divisible by 2.
Output: What are the required payments for each remaining two year bracket?

A: The loan debt (present value) and the present value of the pay-offs  have to be equal. If the pay-offs increseases every year by the amount of d, then the formula is:
$\text{loan debt}=r\cdot \frac{q^n-1}{i\cdot q^n}\cdot \frac{d}{i}\cdot \left(\frac{q^n-1}{i\cdot q^n}-n\cdot q^{-n} \right)$
i=interest rate
q=1+i
r=amount of pay-off without any change


text:
Q: React Hooks setUser & setUserId not updating state despite correct data output I have a functional component using React hooks. There are quite a few functions that will be running in this component, but one in particular is outputting information correctly but not updating the state as it should.
function StatusDropdown() {
    const [user, setUser] = useState('')
    const [userId, setUserId] = useState('')

    useEffect(() => {
      getUser()
    }, [])

    function getUser() {
        return fetch(url, {
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            }
        }).then(response => response.json())
            .then(jsonUser => {
                setUser(jsonUser.display_name)
                setUserId(jsonUser.id)
                console.log(`userInfo: ${jsonUser.id} & ${jsonUser.display_name}`)
                //This console log returns proper information: userInfo: 7 & Firstname
            })
    }
}

I stripped away the unnecessary code, but whenever the user and userId state get used further in my component, the user returns undefined. I use the user state to pass it as an API call query, but because it ends up returning undefined, the API does not properly filter data about a specific user.
I'm just trying to understand if I'm missing something specifically. Any pointers are greatly appreciated!
EDIT:
Below is the subsequent code that relies on the user information above:
    function getAuxLog(userId) {
        return fetch(`${url}?user=${userId}`, {
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            }
        }).then(response => response.json())
            .then(auxlogJson => {
                setUserAuxLog(auxlogJson)
                setLatestAuxLog(auxlogJson.data[auxlogJson.data.length - 1])
                setAuxLogLoaded(true)
            })
    }

The userId is passed to the API url in order to retrieve a log of activity statuses for a specific user. However, with the userId state not being updated, it can not properly retrieve this logged data.


text:
Q: How to enable 7680 x 4320 resolution with my GTX 1080?
*

*Ubuntu 22.04

*NVIDIA drivers 525

*NVIDIA GTX 1080

*Samsung QN850A    8k

So I realize it's an older card, but I would like to get the 8k going, and the manufacturer specs say this is supported:
https://www.nvidia.com/en-gb/geforce/graphics-cards/geforce-gtx-1080/specifications/
However, when I go into Display Properties, no 8k option is specified.  The list tops out at 4096x2160 (5k I guess?) which looks terrible, so I am currently stuck with 3840x2160.
Update: Have not been able to get 8k off my 1080, even after getting HDMI 2.1 "8k" cables and a not-cheap DisplayPort-to-HDMI converter.  However, the the Samsung does display full 8k from my 3080Ti in a different machine.  Notably though you have to go into Samsung External Device Manager > Input Signal Plus settings and enable this, 8k is not enabled by default for whatever reason.

A: The GTX 1080 only supports 8k output on it's DisplayPort port, not HDMI. There are no DisplayPort inputs on the QN850A, so even though the TV may support 8k input via HDMI, the GTX 1080 would not be able to drive the TV at 8k over HDMI.
You cannot (easily) convert a DisplayPort 8k signal to an HDMI 8k signal. There is also little to suggest that the Samsung QN850A even supports 8k video input anyway, with all of the marketing suggesting 4k to 8k upscaling.
[Edit] Here is the spec page for the TV: https://www.samsung.com/us/televisions-home-theater/tvs/samsung-neo-qled-8k/75-qn800a-neo-qled-8k-smart-tv-2021-qn75qn800afxza/#specs
https://content.syndigo.com/asset/85895d30-38ab-4567-81d2-2c066884c7f3/original.pdf


text:
Q: Parametric equation of line parallel to a plane  The parametric equation of the line is
$$x=2t+1, y=3t-1,z=t+2$$
The plane it is parallel to is
$$x-by+2bz = 6 $$
My approach so far
I know that i need to dot the equation of the normal with the equation of the line = 0
$$n = <1,-b,2b>$$
I would think that the equation of the line is $$ L(t) = <2t+1,3t-1,t+2>$$ but am not sure because it hasn't work out very well so far.
** Solve for b such that the parametric equation of the line is parallel to the plane

A: Perhaps it'll be a little clearer if you write the line as
$$l: (1,-1,2)+t(2,3,1)$$
So now you need the direction vector $\,(2,3,1)\,$ to be perpendicular to the plane's normal $\,(1,-b,2b)\,$ :
$$(2,3,1)\cdot(1,-b,2b)=0\Longrightarrow 2-3b+2b=0....$$


text:
Q: Node Sqlite3 Errors I'm using the sqlite3 package in node and beginning to flush out my REST API. I've decided to create a promise wrapper around the DB calls and in the controllers, use async/await to call those functions and set that return value to a variable. Then, check the variable and set a response object. For the success cases it's working well, found a thing and set the response. Problem is, in SQLITE3 I'm having a hard time checking for errors. I have a basic check for undefined in the DB service which does throw an error if it encounters an error, but that error goes immediately to the CATCH section of the controller and doesn't allow me to wrap it in an API response I'd like to define. These are separate files (controller vs. service). I'm not finding a lot of helpful information on error checking for sqlite3, it's sparse out there. Ideally the service would throw an error which I could then wrap into a standardized response object and send.
------ LOCATION
const getById = async (req, res, next) => {
    response = {};
    try {
        let location = await getLocationById(req.params.id); // <-- IF NO VALUE FOUND, location IS nothing
        if (error) { // <----- THIS IS WHERE I'D LIKE TO CHECK FOR ERRORS.
            response.status = 404;
            response.message = 'Error attempting to get location';
        } else {
            response.status = 200;
            response.message = 'Success';
            response.data = location;
        }
        res.json(response);
    } catch (error) {
        res.json(response);
    }
};

------------ SERVICE
const getLocationById = (id) => {
    return new Promise((resolve, reject) => {
        let sql = 'SELECT * FROM Locations WHERE id = ?;';
        db.get(sql, [id], (error, location) => {
            if (location !== undefined) {
                resolve(location);
            } else {
                reject(new Error('Error attempting to get location by id'));
            }
        });
    });
};

A: You just need to wrap the call to getLocationById() in another try/catch. From there you can decide if you want to wrap or raise the error. If you don't have additional code to add that might throw an error you can remove the outer try/catch. More explanation and suggestions in inline comments:
const getLocationById = (id) => {
  return new Promise((resolve, reject) => {
    const sql = "SELECT * FROM Locations WHERE id = ?;";
    db.get(sql, [id], (error, location) => {
      // check for an error from the db here
      if (error) return reject(error);
      // check for an empty result here and throw your own error
      if (!location) {
        // set a property so we can tell that it wasn't a db error just not found
        const myError = new Error("Error attempting to get location by id");
        myError.notFound = true;
        return reject(myError);
      }
      // otherwise resolve the result
      return resolve(location);
    });
  });
};

const getById = async (req, res, next) => {
  // use const since it is not reassigned, only properties are changed
  const response = {};
  try {
    // code here that might throw an exception
    try {
      // use const if you aren't going to reassign `location`
      const location = await getLocationById(req.params.id);

      // we were able to load the location if we get here
      response.status = 200;
      response.message = "Success";
      response.data = location;
    } catch (error) {
      // maybe check to see if we want to wrap or raise the error
      // maybe call console.log(error) to see the contents
      const doWeWantToWrapTheError = somethingToCheckTypeEtc(error);
      if (doWeWantToWrapTheError) {
        if (error.notFound) {
          // no db errors, just not found
          response.status = 404;
        } else {
          // some kind of db error so set to "internal server error"
          response.status = 500;
        }
        response.message = "Error attempting to get location";
      } else {
        // raise the error to the outer try/catch
        throw error;
      }
    }
    // code here that might throw an exception
    return res.json(response);
  } catch (unexpected) {
    // some other error occurred that was not caught above (unlikely)
    // maybe call console.log(unexpected) to see the contents
    response.error = unexpected.message;
    return res.json(response);
  }
};


text:
Q: X Unit test not compatible with .net core 2.2 I have web application with .net core 2.2.
I want to test my web application with XUnit or MSUnit but o have problem with it.
The version of the Microsoft.NETCore.App package in XUnit project is 2.1.0 and version of the Microsoft.NETCore.App in api project is 2.2.
I search many hours and do everything that i see but dosent work.
what should i do ?

A: Just Add
<PackageReference Include="Microsoft.AspNetCore.App"/>
To your test project, rebuild and it shall be fine.
Here's a sample of my .csproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>

    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App"/>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
    <PackageReference Include="Moq" Version="4.13.0" />
    <PackageReference Include="xunit" Version="2.4.0" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
  </ItemGroup>

...

</Project>

you can check the issue from this

A: As you cans see on this link, the same issue was opened on Github and seems like no solution is delivered by XUnit. I am using Nunit with my .NET Core v2.2 project and it works fine. To have look at the library you can check this page out. The syntax is very similar to XUnit and I guess it won't take you so long to update your tests. So, I would suggest you to migrate NUnit.


text:
Q: Get list of reference nodes In Maya using Python API I just want to list all the reference nodes on the current Autodesk Maya scene file using python API (only), there is this class called MFileIO in C++ API but that to returns the referenced file name not the reference node but there is no such class in Python API.
Please any suggestions regarding this.
Note: I don't want to use MEL or Python commands only through API.

A: You can use Maya's 'ls' command to list all of the reference nodes in the scene:
import maya.mel as mm
refNodes = mm.eval('ls -type reference')

'refNodes' will contain an array of reference node names.
If you dislike using Maya commands for some reason, you can do it purely through the API as well:
import maya.api.OpenMaya as om
it = om.MItDependencyNodes(om.MFn.kReference)
refNodes = om.MObjectArray()
while not it.isDone():
    refNodes.append(it.thisNode())
    it.next()

'refNodes' will be an MObjectArray containing the MObjects for all of the reference nodes in the scene.


text:
Q: Xcode 7 Beta 4 - Cannot find storyboard every 2nd time I run the project It might be a beta-prerelease-bug in Xcode, but did anyone other experience the same thing?
I clean the project - Run it - Everything's fine.
Then I stop the project - Run it again - just a black screen and this log:
2015-08-03 23:22:30.743 XXXXXXX[12221:2892479] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Could not find a storyboard named 'MainStoryboard' in bundle NSBundle </private/var/mobile/Containers/Bundle/Application/920917A0-44DF-4B5F-91A8-BB669DDF5F0D/XXXXXXXX.app> (loaded)'
*** First throw call stack:
(0x1822542d8 0x193f200e4 0x18728e810 0x186f59edc 0x186f59074 0x186f5770c 0x18aa893c8 0x18220c27c 0x18220b384 0x1822099a8 0x1821352d4 0x186d383d0 0x186d32f40 0x1001ac504 0x1945caa08)
libc++abi.dylib: terminating with uncaught exception of type NSException

Then I can clean it and do the same thing all over...
And yes, the storyboard is added correctly. It's also added correctly in the info.plist and I have also tried to remove it and add it again. With the same result.
UPDATE I
Same thing happens in the latest Xcode Beta 5.
UPDATE II
This is the log from the second time I ran it in a simulator.
2015-08-10 12:09:19.552 XXXXX[32346:418981] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Could not find a storyboard named 'MainStoryboard' in bundle NSBundle </Users/johndoe/Library/Developer/CoreSimulator/Devices/9685DA45-378D-48AC-BF8C-0DD2EF24C9B3/data/Containers/Bundle/Application/17882AD9-E024-41A1-9E9B-9DC2C2845EA5/XXXXX.app> (loaded)'
*** First throw call stack:
(
    0   CoreFoundation                      0x00000001116e69b5 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000112927deb objc_exception_throw + 48
    2   UIKit                               0x000000010f4564f7 -[UIStoryboard name] + 0
    3   UIKit                               0x000000010ed9b310 -[UIApplication _loadMainStoryboardFileNamed:bundle:] + 58
    4   UIKit                               0x000000010ed9b664 -[UIApplication _loadMainInterfaceFile] + 260
    5   UIKit                               0x000000010ed99fc9 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1383
    6   UIKit                               0x000000010ed97390 -[UIApplication workspaceDidEndTransaction:] + 188
    7   FrontBoardServices                  0x000000011347b7ac -[FBSSerialQueue _performNext] + 192
    8   FrontBoardServices                  0x000000011347bb1a -[FBSSerialQueue _performNextFromRunLoopSource] + 45
    9   CoreFoundation                      0x0000000111612b21 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    10  CoreFoundation                      0x0000000111608a4c __CFRunLoopDoSources0 + 556
    11  CoreFoundation                      0x0000000111607f03 __CFRunLoopRun + 867
    12  CoreFoundation                      0x0000000111607918 CFRunLoopRunSpecific + 488
    13  UIKit                               0x000000010ed96d2d -[UIApplication _run] + 402
    14  UIKit                               0x000000010ed9b99e UIApplicationMain + 171
    15  Teazr                               0x000000010e78912f main + 111
    16  libdyld.dylib                       0x0000000112ecc92d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

Could it be some kind of Facebook bug in the new SDK?

A: Update Xcode to stable version.

A: Judging from the crash log, it's apparent that Xcode can't find MainStoryboard.storyboard in the App's Bundle. Here are steps I would recommend you take so that the problem ceases.

1: Make sure the storyboard actually exists.
This involves opening Finder, going to the project's directory, and confirming that MainStoryboard.storyboard is, in fact, in the project's folder, it exists, and that it is readable/writable.
If the storyboard doesn't exist, skip to step 3. Otherwise...

2: Remove the reference to MainStoryboard.storyboard from within the Xcode project.
On the file list to the left, click on MainStoryboard.storyboard to select it. Afterwards, hit [Command] + [Delete].
On the alert box asking you whether you want to move the file to the Trash or simply Remove Reference, click Remove Reference.

3: Add the Storyboard back in.
Bring up the dialog to add the storyboard back to the project like so:
File -> Add Files to Project...
Navigate to the project's folder and add MainStoryboard.storyboard back in.

4: Tidy up the project, build, and run again.
Simply clean the project, build it, and try running it again. Twice.

5: Re-install Xcode.
You heard me right. Delete Xcode, and all files it has in the Library, off of your Mac and install it again. This issue might be caused by a screwed-up install, and so you might need to uninstall it and install it again.

A more technical explanation:
The code cannot find MainStoryboard.storyboard, as it appears not to exist in the App's Bundle. To those uneducated about the bundle, it is also known as the "binary." The Bundle is where developers put resources that the app needs to access locally. On build, Xcode (should) put(s) all files that are in the Bundle and makes it a Bundle.
Removing the reference and re-adding it back in should get it to always add it to the bundle, not just on every second run.
If MainStoryboard.storyboard is not readable, or it is not writable, Xcode will not include it in the Bundle.
Why it would only work 50% of the time is weird to me, as Xcode 6 runs every time. Making a brand-new project and running it shouldn't cause errors in the compiler, as every new project is created from a template.
If Xcode isn't executing the code that Apple's Developers put in a template (such as SpriteKit's default "Hello world!" message), then there's something wrong with Xcode. Un-install it and install it again.
To figure out why this problem occurs, more information is needed. Maybe we could show this to Apple and they might be able to fix this information by Xcode 7 GM!


text:
Q: Defining a Datasource Usually we define a datasource like this:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:."/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>

However, how to define a "dataSource" pointing to a NoSQL database like Appengine Datastore?
The idea is to allow the "dataSource" to be passed into a bean that is used for Spring security:
    <authentication-manager>
        <authentication-provider>
            <jdbc-user-service data-source-ref="dataSource" />
        </authentication-provider>
    </authentication-manager>

A: Spring security requires a JDBC data source. Yiou would need to get a JDBC driver for your NoSQL database. AFAIK, Google App Engine Datastore doesn come with a JDBC driver, but there were some attempts to write one, so you can give it a shot.


text:
Q: May I call destructor from move assignement operator? Well I have non-trivial destructor in my class.
May I do something like:
Foo& Foo::operator=(Foo&& from) {
    ~Foo()
    // Copy the stuff and cleanup "from"
}

What I am trying to achieve is to avoid code duplication.
Also, I could write some cleanup function, but if I can call destructor then what for?

A: You could, in principle, call a destructor this way, if you then use placement new to construct the object back into the now-empty space. Something like this:
Foo& Foo::operator=(Foo&& from) {
  void* p = this;
  ~Foo();
  return *(new(p) Foo(std::move(from)));  // calls Foo(Foo&&) constructor
}

There are significant limitations to this approach - see e.g. this answer. For example, it would exhibit undefined behavior if Foo has non-static members of const-qualified or reference type; or if this operator is actually applied to a base class subobject of a class derived from Foo. For this and other reasons, this is not commonly done.


text:
Q: Passing urls to javascript from html On my page I have a section where I would like to pull in various RSS feeds.
I don't want to pull in the feeds using PHP because my page will then be affected by how long it takes to get a response back from each server.
Instead, what I would like to do is put the RSS feed URLs on the page and have Javascript pick them up and pull in the content.
The Javascript side of the solution is no problem but I can't find a solution for passing the URLs from HTML to JS that I'm happy with. Ideally I wanted something like...

    <param name="url" value="/url/of/some/feed">
    <param name="url" value="/url/of/some/other/feed">

but I realise this isn't valid.
Anyone have any nice solutions? (ps. I don't want to write JS in my view files)

A: Use the data attribute, then you can use something like this :

Then you can loop the DOM elements with a class of rss and get the data-url attribute of each - the span could be any HTML element
Nice explanation of on data attributes here
The official HTML5 docs on the custom attributes is here - but they work in any browser in any HTML version - using the getAttribute() method


text:
Q: The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig I have incorporate SpatialIite into a Xcode project which uses a header file from Proj.4, just one header. Both are Xcode projects and have static targets.
I'm trying to migrate from git submodule to Cocoapods. Since static targets seems to be difficult to use with Cocoapods, I just want to have the project built in the usual way. I made podspec for Proj.4. After writing podfile for SpatialLite I got the warnings:
[!] The target `SpatialiteIOS [Debug]` overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig'.
    - Use the `$(inherited)` flag, or
    - Remove the build settings from the target.

[!] The target `SpatialiteIOS [Debug]` overrides the `HEADER_SEARCH_PATHS` build setting defined in `Pods/Pods.xcconfig'.
    - Use the `$(inherited)` flag, or
    - Remove the build settings from the target.

[!] The target `SpatialiteIOS [Debug - Release]` overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig'.
    - Use the `$(inherited)` flag, or
    - Remove the build settings from the target.

[!] The target `SpatialiteIOS [Debug - Release]` overrides the `HEADER_SEARCH_PATHS` build setting defined in `Pods/Pods.xcconfig'.
    - Use the `$(inherited)` flag, or
    - Remove the build settings from the target.

I read this issue but I'm pretty clueless to what the warnings mean and what can I do to fix it.
Additionally problem, when I open the workspace as well as opening SpatiaLite project alone, both are targeted to Mac OSX 64, when it is suppose to be an iOS project. My podfile does say "platform :ios".

A: There is a conflict between your build settings and the default build settings that Cocoapods wants. To see the Cocoapods build settings, view the .xcconfig file(s) in Pods/Target Support Files/Pods-${PROJECTNAME}/ in your project. For me this file contains:
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers" "${PODS_ROOT}/Headers/Commando"
OTHER_LDFLAGS = -ObjC -framework Foundation -framework QuartzCore -framework UIKit
PODS_ROOT = ${SRCROOT}/Pods

If you are happy with the Cocoapods settings, then go to Build Settings for your project, find the appropriate setting and hit the Delete key. This will use the setting from Cocoapods.
On the other hand, if you have a custom setting that you need to use, then add $(inherited) to that setting.

A: The first line of link below saved my day:

To add values to options from your project's build settings, prepend the value list with $(inherited).

https://github.com/CocoaPods/CocoaPods/wiki/Creating-a-project-that-uses-CocoaPods#faq
Also, do not forget to insert this line at the beginning of your pod file:
platform :iOS, '5.0'

A: I added $(inherited) but my project was still not compiling. For me problem was flag "Build for active Architecture only", I had to set it to YES.

A: This definitely works most of the time:
Go to your target Build Settings -> Other linker flags -> double click . Add $(inherited) to a new line.
If you have problem with "...target overrides the GCC_PREPROCESSOR_DEFINITIONS build setting defined in..." then you must add $(inherited) to your target Build Settings -> Preprocessor Macros

A: I've seen these 3 errors for pod command in terminal
pod install

[!] The MY_APP [Debug/Release] target overrides the
  HEADER_SEARCH_PATHS ...
  [!] The MY_APP [Debug/Release] target
  overrides the OTHER_LDFLAGS ...
  [!] The MY_APP [Debug/Release] target
  overrides the GCC_PREPROCESSOR_DEFINITIONS ...

All these 3 errors would be gone by adding $(inherited) to

*

*Header Search Paths

*Other Linker Flags

*Preprocessor Macros

in Project -> Target -> Build Settings
And now the command would run without giving any errors
pod install

A: Just had a similar issue when I ran pod install, I saw the following warnings/errors (related to CLANG_CXX_LIBRARY):
The Error/Warning from Cocoapods
[!] The `Project [Debug]` target overrides the `CLANG_CXX_LIBRARY` build setting defined in `Pods/Target Support Files/Pods/Pods.debug.xcconfig'. This can lead to problems with the CocoaPods installation
    - Use the `$(inherited)` flag, or
    - Remove the build settings from the target.

[!] The `Project [Release]` target overrides the `CLANG_CXX_LIBRARY` build setting defined in `Pods/Target Support Files/Pods/Pods.release.xcconfig'. This can lead to problems with the CocoaPods installation
    - Use the `$(inherited)` flag, or
    - Remove the build settings from the target.

The Fix

*

*Select your Project so you can see the Build Settings.

*Select your Target (AppName under Targets)

*Find C++ Standard Library (It will probably be in BOLD - This means it's overridden).

*Select the Line (So it's highlighted Blue), and press ⌘ + DELETE (Command + Backspace)

The line should not be bolded anymore and if you run pod install the warnings/errors should have disappeared.

Visual Aid

A: In your project, find Target -> Build Settings -> Other Linker Flags, select Other Linker Flags, press delete(Mac Keyboard)/Backspace(Normal keyboard) to recover the setting. It works for me.
Example:
Before

After

A: Xcode Screenshot

Ankish Jain had the answer that worked for me. Here is a screenshot of what to do, as it took me a little bit to find out what exactly to do.
In my case i needed to add $(inherited) to my 'Other Linker Flags' because that is what showed up as Overriding in terminal.

A: If Xcode complains while linking, e.g. Library not found for -lPods, it doesn't detect the implicit dependencies:
Go to Product > Edit Scheme
Click on Build
Add the Pods static library
Clean and build again

A: For me the problem was with my targets tests. I already had the $(inherited) flag in my main app target.
I added it to MyAppTests Other Linker flags. After that when I ran pod install the warning message was gone.

A: do not forget to insert (or unCommanet) this line at the beginning of your pod file:
platform :iOS, '9.0'

that saves my day

A: This happens to me every time I add a pod to the podfile.
I constantly try and find the problem but I just go round in circles again and again!
The error messages range, however the way to fix it is the same every time!
Comment out(#) ALL of the pods in the podfile and run pod install in terminal.
Then...
Uncomment out all of the pods in the podfile and run pod install again.
This has worked for me every single time!

A: When I added the $(inherited) flag to the file in question (in this case it was LIBRARY_SEARCH_PATHS) it led to another error Undefined symbols for architecture arm64: "_swift_getTypeByMangledNameInContextInMetadataState
Changing the following worked and I was able to build:
>LIBRARY_SEARCH_PATHS = (
   "\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"",
-  "\"$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)\"", <--- Change this...
+  "\"$(TOOLCHAIN_DIR)/usr/lib/swift-5.2/$(PLATFORM_NAME)\"", <--- to this
   "\"$(inherited)\"",
> );


text:
Q: Span of similar matrices Given $D=\begin{pmatrix} 3 & 0 \\ 0 & 2\\ \end{pmatrix}$
How can i find the span of all matrices A that are similar to D.
thus $\exists P$  $A=P^{-1}DP$

A: Here are four matrices similar to $D$ which span all of $\mathbb{R}^{2\times 2}$:
$$ \begin{pmatrix} 3 & 0 \\ 0 & 2 \end{pmatrix},
   \begin{pmatrix} 2 & 0 \\ 0 & 3 \end{pmatrix},
   \begin{pmatrix} 3 & 1 \\ 0 & 2 \end{pmatrix},
   \begin{pmatrix} 2 & 0 \\ 1 & 3 \end{pmatrix}  $$
So the span of matrices $A$ similar to $D$ is all of (real) $2\times 2$ matrices.

A: Try using the general definition of an invertible $2\times 2$ matrix for $P$. Then you can invert this matrix and conjugate $D$ with it. The resulting matrix gives you all the matrices $A$.
Note: I don't know if there is a more elegant solution but this definitely works.


text:
Q: How can I make routine timer in Python? I wanna make routine timer in Python. and I use also PyQt5
In summary,
first_step LED1 is on 10 minute
second_step LED1 is off, LED2 is on 5 minute
third_step LED2 is off, LED3 is on 3 minute
and return in first_step.
this routine is do while main Timer is Run.
I using threading.Timer and schedule.
Anyone know better idea, please help me.
Here is my code for timer
ort sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi
import time
import threading
import schedule

class MainUI(QMainWindow):
    def __init__(self):
        super(MainUI, self).__init__()
        loadUi('untitled.ui',self)

        self.setWindowTitle('test')

        self.set_hour = 2
        self.set_minute = 1
        self.set_second = 3

        self.btn_start.clicked.connect(self.timer)
#         self.btn_stop.clicked.connect()

    def timer(self):
        d_time = str(self.set_hour)+':'+str(self.set_minute)+':'+str(self.set_second)

        if self.set_minute >= 0:
            if self.set_second >= 1:
                self.lcd_time.display(d_time)
                self.set_second -= 1
            elif self.set_minute == 0 and self.set_second == 0 :
                self.set_hour -= 1
                self.set_minute += 59
                self.set_second += 59
                self.lcd_time.display(d_time)
            elif self.set_hour == 0 and self.set_minute == 0 and self.set_second == 0:
                self.timer_stop()
            else:
                self.set_minute -= 1
                self.set_second += 59
                self.lcd_time.display(d_time)

        timer = threading.Timer(1,self.timer)
        timer.start()

        def timer_stop(self):
            self.timer.cancel()

app = QApplication(sys.argv)
widget = MainUI()
widget.show()
app.exec_()


text:
Q: ChildEventListener methods not called Firebase I want to add marker in map activity which the position is retrieved from Firebase RealTime Database.
I tried to implement the addChildEventListener() in onCreate() and OnMapReady() methods and also when user signing in but nothing of them worked although there is no errors, I also used the logcat to show location coordinates but its values not showing.
    email = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("email", "");
    password = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("password", "");
    name = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("name", "");
    gender = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("gender", "");
    age = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("age", "");
    mobileNumber = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("mobileNumber", "");
    if (email == "" || password == "" || name == "" || mobileNumber == "" || age == "" || gender == "") {
        startActivity(new Intent(this, WelcomeActivity.class));
        return;
    }

    setContentView(R.layout.activity_maps);
    getSupportActionBar().setTitle(R.string.app_name);

    firebaseAuth = FirebaseAuth.getInstance();
    firebaseSignIn();

    MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
    rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
    rewardedVideoAd.setRewardedVideoAdListener(this);
    rewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());

    MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
    adView = findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);

    findNurseButton = findViewById(R.id.find_nurse);
    findNurseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            findNurseButton.setText("finding nearby nurses");

        }
    });

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    assert mapFragment != null;
    mapFragment.getMapAsync(this);

    getLocationPermission();
    createLocationRequest();
    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

    locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null) {
                return;
            }
            else {
                try {
                    for (Location location : locationResult.getLocations()) {
                        // Update UI with location data
                        // ...
                        sendNurseRequest();
                        lastLocation = location;
                        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                        mMap.animateCamera(CameraUpdateFactory.zoomTo(16f));
                        Log.i("location updates: ", "latitude: " + location.getLatitude() + " ,longitude: " + location.getLongitude());
                        userReference.child("auth id").setValue(userID);
                        userReference.child("latitude").setValue(location.getLatitude());
                        userReference.child("longitude").setValue(location.getLongitude());
                    }
                }
                catch (NullPointerException e) {

                }
            }
        }
    };
    mFusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());

    DatabaseReference nurseRef = FirebaseDatabase.getInstance().getReference().child("nurses available/2");
    nurseRef.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            LatLng latLng = new LatLng(Double.parseDouble(dataSnapshot.child("latitude").getValue().toString()), Double.parseDouble(dataSnapshot.child("longitude").getValue().toString()));
            mMap.addMarker(new MarkerOptions().position(latLng));
            Log.i("latslongs ", "firebase latitude:" + dataSnapshot.child("latitude").getValue() + "firebase longitude" + dataSnapshot.child("longitude").getValue());
        }

        @Override
        public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            LatLng latLng = new LatLng(Double.parseDouble(dataSnapshot.child("latitude").getValue().toString()), Double.parseDouble(dataSnapshot.child("longitude").getValue().toString()));
            mMap.addMarker(new MarkerOptions().position(latLng));
            Log.i("latslongs ", "firebase latitude:" + dataSnapshot.child("latitude").getValue() + "firebase longitude" + dataSnapshot.child("longitude").getValue());

        }

        @Override
        public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            LatLng latLng = new LatLng(Double.parseDouble(dataSnapshot.child("latitude").getValue().toString()), Double.parseDouble(dataSnapshot.child("longitude").getValue().toString()));
            mMap.addMarker(new MarkerOptions().position(latLng));
            Log.i("latslongs ", "firebase latitude:" + dataSnapshot.child("latitude").getValue() + "firebase longitude" + dataSnapshot.child("longitude").getValue());
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.e("database error", databaseError.getMessage());
        }
    });
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
   mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    if (locationPermissionGranted && checkInternet()) {
        getDeviceLocation();
    }
}

And this is my database

A: DatabaseReference nurseRef = FirebaseDatabase.getInstance().getReference().child("nurses available/2"); // just remove the last child /2

although it's exist as a node but I should remove it from the reference, if anyone can explain it ?
thanks in advance...


text:
Q: Shared Memory Segment of a global Struct in "On demand" Server I have to create for academic purpose an "On-Demand Server" that is based on the TCP protocol. The client each time sends a KEY and a VALUE that I have to store them in a global struct using two functions.
EDIT:
If a client asks for put I have to store in the struct the key and the value that the client send to the server. If the client asks for get I have to search in the struct and return to the client the Value. Since I use fork each time a new client connects and writes/read in the struct it is impossible for the other children(clients) to see the changes that the first on makes in the struct so I had to make the struct visible to every child. But that does not happen for some reason.
Bellow is the code of my attempt.
NOTE: The parameters of functions put() and get() cannot be changed.
My solution does not work and I am trying to find out why! I am very new to "shared memory" things and I hope I can find some help here.

A: I think there is a variety of misunderstandings on how share memory segments works.
1.You are creating shared memory for the struct, but not for the struct's elements. You need also to attach keyvalue.keys and keyvalue.values to a shared memory segment. Remember that in C languge a struct is like a pointer to its elements. So you are creating a memory segment only for this "pointer" (someone can correct me if i am wrong )
2.Every new child process that is being created has its own memory map. So you have to attach manually every new process to this shared memory segments of your struct manually every time. Once you are done you can de-attached the child process. (and here comes your next logic issue)
3.If i get it right, in these line of code
        close(acceptfd);
}//while(1) end

the father is deataching himself from the sharedMemory segment. That will result into new child processes have no shared memory segments to attach to. Since you are creating a server and you want this to run 'forever' , if you want to de-attach father process from the shared memory segment, you can only do it with a system call on SIGINT. So right before CTRL+C, the function of SIGINT manipulation will also deatach the father from the sh.m. segment. If you ain't closing the segment, you can do it manually later through terminal.
Hope i helped somehow!


text:
Q: CentOS 8 vs CentOS 7 End Of Life CentOS 8 EOL date is 31st December 2021, whilst CentOS 7 EOL is 30th June 2024.
This seems a very odd situation to me, where a later release is expiring before an earlier release. Can anyone explain this to me?
I cannot be running EOL systems in 2022 and I don't want to migrate my CentOS 8 servers (which run nginx as a reverse proxy) to CentOS stream.
I'm not too enthusiastic about alternatives such as Rocky Linux either. Perhaps it's an unusual step, but would downgrading to CentOS 7 be a better option to buy some time?

A: CentOS 8 is not a clone of RHEL 8, it's now a rolling release, a sort of testbed.
https://centos.org/distro-faq/
https://www.redhat.com/en/blog/centos-stream-building-innovative-future-enterprise-linux
RHEL 8 is currently free for personal use, so you may as well update to it if you don't want to use its other clones which stick to RHEL packages.

A:
This seems a very odd situation to me, where a later release is expiring before an earlier release. Can anyone explain this to me?

CentOS 8 expairing before CentOS 7, as per decision of its governing body from RedHat, in favour of CentOS Stream.
CentOS (2004) was orignially a community project which rebuilt RHEL packages removing RH trademark parts and community supported, a downstream of RHEL. In 2014, RH acquired CentOS trademark and website and started to directly back the project.

*

*CentOS 8 was released in 2019-09-24. Originally CentOS 8 had full-update upto 2025 and maintainance update upto 2029. It was cut short to 2021-12-31.

*CentOS 7 was released in 2014-07-07. It has full-update upto 2020-08-06 and mainatinance update upto 2024-06-30.

Why the life was cut short because RH released CentOS Stream which is a rolling release distro, which will be updated prior to RHEL, essentially its upstream. Not everyone is happy to know that their server OS will be testbed to someone else. Official statement, emphasis mine:

CentOS Linux is a rebuild of Red Hat Enterprise Linux (RHEL). As such, it is downsteam from RHEL. CentOS Linux release version numbers reflect the date of the RHEL release on which they are based. For example, CentOS 8.2105 is a rebuild of RHEL 8.3, which released in May of 2021.
CentOS Stream, on the other hand, is the upstream, public development branch for RHEL. Specifically, CentOS Stream 8 is the upstream for the next minor release of RHEL 8, CentOS Stream 9 for the next minor release of RHEL 9, and so on.

What's the future ?
There are three possible replacement for CentOS, all are downstream to RHEL:

*

*Rocky Linux ( June 2021) is a new community-maintained distro which is intended to replace CentOS, leaded by the original developer of CentOS. Rocky Linux 8 is intended to be supported upto 2029. Basically CentOS with new name but not fully-fledged.

*AlmaLinux (March 2021) is also started for same intention, maintained by CloudLinux, a company which also has a commercial offering CloudLinux OS. Their FAQ says "CloudLinux is committed to supporting AlmaLinux until 2029".

*Oracle Linux (2006), maintained by Oracle, with optional commercial support. It is not intended to replace CentOS, but should work.


text:
Q: Most efficient way to look for files in a directory tree that match a regular expression I am writing a little app that will enable users to specify a regular expression that will specify what files to copy to a location. The expression might look something like this:
\w\:\/rootFolderOne\/subFolderTwo/\w+/fileName\d+.mpg

So my question is how do I efficiently find all files on a drive that match this pattern?
I have to load the contents of each folder one by one. I could just traverse the directory tree and load every folder in the whole file system and then compare each file's entire path with the regular expression.
This would be very wasteful as loading the contents of rootFolderTwo or even subFolderThree would not provide any valid results.
At the root level how do I know to load rootFolderOne but not rootFolderTwo?

A: Most efficient way?  I really don't know in AIR.  Maybe with an ANE you'd get a better result.   With pure AIR though, this is all I can think of:
(It could be very slow, so using a worker thread is highly advised)
    private var expression:RegExp;  //to store you regex for the search
    private var matchedFiles:Vector.<File>; //store your matched files

    public function Main()
    {
        expression = /\btest(er | ing | ed | s)?\b/; //anything with the word test/tester/testing/tests in it

        matchedFiles = new Vector.<File>();
        //scanFolder(new File("file:///C://")); //windows C drive,  replace this with whatever is most approprite for your camera card path.
        scanFolder(File.documentsDirectory); //for testing purposes I'm just going to scan the documents directory

        trace(matchedFiles.length + " files found");
    }

    private function scanFolder(file:File):void {
        if (!file.exists) return; //if the directory doesn't exist, exit this function

        var files:Array = file.getDirectoryListing(); //list of all files in directory
        var f:File;
        for (var i:int = 0; i < files.length; i++ ) { //loop thorugh all files
            f = files[i];
            if (f.isDirectory) {
                scanFolder(f); //if directory, scan it
            }else{
                //if it matches the regex, put it the matched array
                if (expression.test(f.name)) matchedFiles.push(f);
            }
        }
    }


text:
Q: Linux, netstat : how to display the owner of programs using ports? I'm getting crazy with the command netstat.
In the man we can read that, in the output of Active Internet Connections (TCP, UDP, raw) we should have :

User : The username or the user id (UID) of the owner of the socket.

But when I do
netstat -natp

my output doesn't show any owner (or UID)
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:4713            0.0.0.0:*               LISTEN      2159/pulseaudio
(...)

and I don't see any option in the man to display the owner of the PID.
There is the --numeric-users  option, but it doesn't change anything.
Is there something I'm missing? Or there is something wrong with netstat ?
Is there another way to get this information?
Thanks for your help :)

A: Alternatively, you could use lsof -i which shows you the user.
COMMAND     PID    USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
httpd     32500  apache    4u  IPv6   14390      0t0  TCP *:http (LISTEN)
httpd     32501  apache    4u  IPv6   14390      0t0  TCP *:http (LISTEN)
httpd     32502  apache    4u  IPv6   14390      0t0  TCP *:http (LISTEN)
httpd     32503  apache    4u  IPv6   14390      0t0  TCP *:http (LISTEN)

A: Use netstat -natpe.
From the man page:
-e, --extend
 Display additional information.  Use this option twice for maximum detail.

As clear as mud.
Which will add two columns, User and Inode to the display.
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       User       Inode      PID/Program name
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN      100        13119      1901/mysqld


text:
Q: How Should I Configure Memory for Multiple Instances of SQL Server? We have a set of SQL Server instances (2008 R2) that run on the same virtual server.  Each instance represents a stage in our development cycle (Dev/Test/Stage/etc.).  The instances all need to be online at any given time, but load tends to be isolated to one instance as a time, depending on where we are in the release lifecycle.
SQL Server seems to grab and hold whatever amount of memory we set as the max.  What I'd like to know if there is any way of configuring the instances to be "smart" about memory consumption so they are not blocking each other from getting memory when needed.

A: SQL Server will use as much memory as you can throw at it (pretty much), and it is always advisable to set a limit on every instance.  The default setting is 2147483647MB.
Depending on your usage and own unique circumstances, your settings may vary, but normally a good starting point is to set the max server memory between 75 and 90 percent, depending on how much RAM you have.  Glenn Berry share a good indication a few years back HERE.
If you have multiple active instances on a server, you might have to share the resources between them, for e.g. if you have 32GB of RAM with 3 instances, you should assign around 9500MB to each instance.  When you are using just one instance at a time, the others will not release the RAM they are using.  You could free up their RAM by stopping the service.
When you have other applications / services running, the amount of memory might have to be adjusted to accommodate them.


text:
Q: Related rates problem - how a beam from a laser moves across the wall The problem:
Let $\theta$ be the angle between the laser and the horizontal line which is at a 90 degree angle at the wall(see drawing). The laser point moves at a pace of 1cm/sec vertically on the wall between 45 degrees, and -45 degrees(-45 when the laser pointer is under the horizontal line). The laser is located 500 cm from the wall.
a) Find an expression for $\theta(t)$ for how $\theta$ measured in degrees must change with respect to time.
b) At the start, the laser moves from $\theta$ = -45 degrees, and moves to 45 degrees by the end. How long does it take for the laser to move from -45 degrees to 45 degrees?
c) what is the angle-velocity of $\theta'(t)$ ? Measured in degrees.
d) What is the angle-velocity when the laser pointer passes the midpoint of the wall?

Ok, so far I've drawn the problem, and dx/dt is 1cm/s, correct?
I'm having trouble solving a), but I think I have b) solved:
b) = tan 45 * 500 = 1 * 500 = 500. So x is 500cm long between 0 degrees and 45 degrees. Taking it from -45 to 45 means 500*2 = 1000cm, correct? This means the laser should use 1000 seconds, or 16 minutes and 40 seconds to go from -45 degrees to 45 degrees.
c) Now I guess I have to find $d\theta/dt$?
Am I on the right track, or have I misunderstood?
So finding $d\theta/dt$, I tried:
tan$\theta$ = x/500
sec^2$\theta$*$d\theta/dt$ = 1/500 * dx/dt
$d\theta/dt$ = 1/500 * (1/sec^2 $\theta$) * dx/dt
$d\theta/dt$ = 1/500 * cos^2 $\theta$ * dx/dt
= 1/500 * cos^2(500/1000) * 1 # since dx/dt = 1
= 0.769 rad.
0.769 rad * 180/pi = approx 0.088 degree/sec. Is this correct?

A: You are not too far off. Let's start with a):assuming the laser moves from bottom to the top once (it's not clear what happens after it reaches the top), we can express $x=-500+t, 0 \le t \le 1000$; we can also express $\tan \theta=\frac{x(t)}{500}, \theta(t)=\frac{180^\circ}{\pi}\arctan \frac{-500+t}{500}$
You are correct about b).
To find $\theta'(t)$, you can simply take a derivative of expression obtained in a).
$\theta'(t)=\frac{180^\circ}{500\pi}\frac{500^2}{500^2+(-500+t)^2}$, $\theta'(500)=\frac{180^\circ}{500\pi}$. Your way would also work but for some reason you used $\cos^2 \frac{500}{1000}$ whereas $\theta$ is clearly zero at the midpoint.


text:
Q: Losing  Text value from ViewState for dynamically added control I am adding controls to a page programatically in the code behind. I add an asp:Label and set it's Text value. I add an asp:TextBox and set it's Text value. Both Text values are returned in the Response and displayed in the browser. All fine so far.
The user performs an action that causes a postback. I re-load the dynamically added asp:Label and asp:TextBox. When the Response is returned to the browser, only the asp:TextBox Text value is displayed. The asp:Label Text value is not.
If I inspect the HTML I can see the asp:Label control (rendered as an HTML span tag) but no value.
How can I get the code to automatically re-load the Text value of an asp:Label on each postback? Why is the behaviour different for an asp:Label and an asp:TextBox? I do not want to have to manually re-set the Text value on each postback.
Here is some code similar to what I am doing (placeHolderNameplates is an asp:PlaceHolder control on the aspx page):
    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    If Not Page.IsPostBack Then
        Dim lbl As Label = New Label()
        lbl.ID = "xxx1"
        lbl.Text = "yo"
        placeHolderNameplates.Controls.Add(lbl)

        Dim tb As TextBox = New TextBox
        tb.ID = "xxx2"
        tb.Text = "yoyo"
        placeHolderNameplates.Controls.Add(tb)

    Else
        Dim lbl As Label = New Label()
        lbl.ID = "xxx1"
        placeHolderNameplates.Controls.Add(lbl)

        Dim tb As TextBox = New TextBox
        tb.ID = "xxx2"
        placeHolderNameplates.Controls.Add(tb)

    End If

A: What you need to do is add the control to the placeholder before setting the values, so it should be
Dim lbl As Label = New Label()
placeHolderNameplates.Controls.Add(lbl)
lbl.ID = "xxx1"
lbl.Text = "yo"
See these posts for details:
http://www.yakkowarner.com/2008/01/aspnet-dynamic-controls-and-viewstate.html
http://codebetter.com/jefferypalermo/2004/11/25/key-to-ensuring-dynamic-asp-net-controls-save-viewstate-level-300/

Before they are added to the page, they have not initialized themselves.  When a dynamic control is added to another control, the new control plays catch-up to get to the stage that the parent control is in.  For instance, if in your Page_Load, you add a textbox, it will play catch-up and go through its Init and Load phases.  This is important beceause it will start tracking its viewstate.  Values added before it is tracking viewstate won't make it to viewstate and will be lost on PostBack.

A: It seems like dynamically created controls won't be added to the ViewState automatically. The TextBox Control retains it's value however because of it's nature of being rendered to a <input type="text" value="xyz" /> html element.
Have a look at this article:
http://www.codeproject.com/Articles/3684/Retaining-State-for-Dynamically-Created-Controls-i

A: Hey check thsi site MSDN
You have to add your control with following event( so viewstate maintain automaticly)
override protected void OnInit(EventArgs e)

example of Add Dynamic control
http://support.microsoft.com/kb/317794/en-us


text:
Q: When I specify x has type a, why does Haskell try to infer it has type a0? Sometimes I'll specify something's type in a signature as, say, a, and GHC will respond that it can't deduce that its type is a0. Is there a single reason this happens, or a number of different possible reasons? Sometimes I solve it, sometimes not; I'm hoping for a unified theory.
Here's a short example. (To see this code including comments explaining what it's trying to do, see here.)
{-# LANGUAGE MultiParamTypeClasses
           , AllowAmbiguousTypes
           , FlexibleInstances
           , GADTs #-}

type SynthName = String

data Synth format where
  Synth :: SynthName -> Synth format

data MessageA format where
  MessageA :: String -> MessageA format
data MessageB format where
  MessageB :: String -> MessageB format

class (Message format) a where
  theMessage :: a -> String
instance (Message format) (MessageA format) where
  theMessage (MessageA msg) = msg
instance (Message format) (MessageB format) where
  theMessage (MessageB msg) = msg

play :: Message format m => Synth format -> m -> IO ()
play (Synth name) msg =
  print $ name ++ " now sounds like " ++ theMessage msg

That produces the following error.
riddles/gadt-forget/closest-to-vivid.hs:38:42: error:
    • Could not deduce (Message format0 m)
        arising from a use of 'theMessage'
      from the context: Message format m
        bound by the type signature for:
                   play :: forall format m.
                           Message format m =>
                           Synth format -> m -> IO ()
        at riddles/gadt-forget/closest-to-vivid.hs:36:1-54
      The type variable 'format0' is ambiguous
      Relevant bindings include
        msg :: m (bound at riddles/gadt-forget/closest-to-vivid.hs:37:19)
        play :: Synth format -> m -> IO ()
          (bound at riddles/gadt-forget/closest-to-vivid.hs:37:1)
      These potential instances exist:
        instance Message format (MessageA format)
          -- Defined at riddles/gadt-forget/closest-to-vivid.hs:30:10
        instance Message format (MessageB format)
          -- Defined at riddles/gadt-forget/closest-to-vivid.hs:32:10
    • In the second argument of '(++)', namely 'theMessage msg'
      In the second argument of '(++)', namely
        '" now sounds like " ++ theMessage msg'
      In the second argument of '($)', namely
        'name ++ " now sounds like " ++ theMessage msg'
   |
38 |   print $ name ++ " now sounds like " ++ theMessage msg

A: Message is a multi-parameter typeclass.  In order to determine which instance to use, there needs to be a concrete choice for a and for format.  However, the method
theMessage :: a -> String

doesn't even mention format, so we have no way of figuring out which concrete type to use to find an instance of Message.  The ambiguous type error you presumably got was about this (but that can be a tricky error message, I don't blame you for just enabling the extension).
The quick fix is to manually specify the format variable using ScopedTypeVariables and TypeApplications (or adding a Proxy format argument to theMessage).
play :: forall format m. Message format m => Synth format -> m -> IO ()
play (Synth name) msg =
    print $ name ++ " now sounds like " ++ theMessage @format msg

However, the Message class raises a red flag as a misuse of typeclasses.  It's not always bad, but whenever you see a class whose methods all have types like
:: a -> Foo
:: a -> Bar

i.e. they take a single a in contravariant position, it's likely that you don't need a typeclass at all.  It's often cleaner to transform the class into a data type, like so:
data Message format = Message { theMessage :: String }

wherein each method becomes a record field.  Then concrete types that you instantiated, such as your MessageA, get "demoted" to functions:
messageA :: String -> Message format
messageA msg = Message { theMessage = msg }

Whenever you would have passed an a with a Message constraint, just pass a Message instead.  a dissolves into nothingness.
After you do this factoring you might be noticing that a lot of what you have written is sort of tautological and unnecessary.  Good!  Remove it!

A: When type checking code involving polymorphic bindings, the type inference engine creates fresh type variables for each use of the binding.
Here's a concrete example:
show () ++ show True

Now, we know that show :: Show a => a -> String. Above the first call to show chooses a ~ (), the second one chooses a ~ Bool. Wait! That looks as a contradiction since () and Bool are distinct types, so they can not be both equal to a. Is that it?
Nah, it is not a contradiction... it looks clear that each call of show can make its choice of a independently. During type inference this is done, roughly, as follows.
For each call we generate a fresh type variable, by renaming universally quantified type variables in the polymorphic type at hand
-- for the first call
show :: Show a0 => a0 -> String
-- for the second call
show :: Show a1 => a1 -> String

Then, we simply pick a0 ~ () and a1 ~ Bool and we are done. The user never realized that this was going on under the hood.
In case there is a type error, however, the freshly generated variables can be reported to the user, revealing a piece of the underlying inference algorithm. For instance
show []

Here, two polymorphic values are used, so we generate fresh variables for both.
[] :: [a0]
show :: Show a1 => a1 -> String

To typecheck, we need a1 ~ [a0], so we end up with (after some context reduction, which does not matter now):
[] :: [a0]
show :: Show a0 => [a0] -> String

Good, we no longer have a1 around. But what about a0? We do not have found any specific value for a0. Indeed, we can not do that, since the code does not contain anything to force that choice: a0 remains an ambiguous type at the end.
This happens because [] can create a list of any type, while show can take a list of any type as input (as long as its element type is showable). But these constraints do not tell us what the type should be!
Concluding, the code is ambiguous, so we have to fix it by telling GHC what type we choose. Any of these would be fine
show ([] :: [Int])   -- choose a0 ~ Int
show ([] :: [Bool])  -- choose a0 ~ Bool
show ([] :: [Char])  -- choose a0 ~ Char

In your code
play :: Message format m => Synth format -> m -> IO ()
play (Synth name) msg =
  print $ name ++ " now sounds like " ++ theMessage msg

there is nothing which forces theMessage msg to use the same format which appears in the type of play. It is perhaps "obvious" to you that it should be, but it is not the only possible choice.
Choosing the same format is tricky here since your class has ambiguous types. This could still be used by turning on TypeApplciations and AmbiguousTypes, but something tells me that your design might be wrong, so I am a bit cautious here to suggest a solution. What you are trying to achieve? Why does the type of the Message not mention format in any way?


text:
Q: Mongo user exist validation I am trying to perform a sign up form into Mongo Node.js and Express.js. I have already completed the task which inserts a document into users collection for a new user. But I need to create a validation if a user exist based on username or email as keys.
For example I am submitting a user:
{  "_id": {    "$oid": "62ac54c4cd1c80d0e8e2f68a"  },  "firstName": "test",  "lastName": "test",  "email": "test@test.com",  "password": "test",  "username": "test"}
If I try to sumbit the same creds in the sign up form, my API completely crashes with error code:
db.collection(...).exists is not a function

Note: I am using mongoose
Code:
app.post("/login", async (req, res) => {
    const firstName = req.body.firstName;
    const lastName = req.body.lastName;
    const email = req.body.email;
    const password = req.body.password;
    const username = req.body.username;

    var data = {
        "firstName": firstName,
        "lastName": lastName,
        "email": email,
        "password": password,
        "username": username
    }

    console.log(data);

    let userExist = await db.collection('users').exists({ "username": username, "email": email })
    console.log(userExist);

    if (userExist) {
        console.log("User already exists");
        return res.render('login');
    } else {
        db.collection('users').insertOne(data, function (err, collection) {if (err) throw err;});
    }
    res.render('login', { 'data': data });
});

Any ideas?

A: I see you are trying to find  if user exists in the collection via two fields which are username and email.
With mongoose you could actually do it in many ways and the most better approach is to define your model, https://mongoosejs.com/docs/models.html
If you want to stick with your case then you could try this:
db.collection('users').find({ "username": username, "email": email })


text:
Q: $L^2(a_1,b_1;H_0^1(a_2,b_2))\subset L^2(a_1,b_1;L^2(a_2,b_2))$ and Convergence Let $[a_1,b_1]\times[a_2,b_2]\subset\mathbb{R}^2$.  Suppose $$u_n\rightharpoonup u\,\,\,\text{ weakly in } L^2(a_1,b_1;L^2(a_2,b_2))$$ and $$\{u_n\}\text{ is bounded in }L^2(a_1,b_1;H_0^1(a_2,b_2)).$$  Can we conclude $$u_n\rightharpoonup u\,\,\,\text{ weakly in } L^2(a_1,b_1;H_0^1(a_2,b_2))$$ and why?
Notation:
$\bullet\,\,\, L^p(\Omega;X)=\left\{u:x\in\Omega\to u(x)\in X\,\big|\,\displaystyle\int_\Omega\|u(x)\|^p_{X}\,dx<\infty\right\}$
$\bullet\,\,\, f_n\rightharpoonup f$ weakly in $E$ if $\langle \phi,f_n\rangle_{E',E}\to\langle\phi,f\rangle_{E',E}$ for all $\phi\in E'$, where $E'$ denotes the dual of Banach space $E$

A: Yes. We have that $u_n \rightharpoonup w$ in $L^2(H^1_0)$ for some $w$ since $u_n$ is bounded uniformly in that space. Now to identify $w$ as $u$ simply pass to the limit in the integration by parts identity equation
$$(u_n, \partial_{x_i} \varphi)_{L^2(L^2)} = -(\partial_{x_i} u_n, \varphi)_{L^2(L^2)}$$
where $\varphi(x,t) = \psi(t) \phi(x)$ with $\psi \in C_c^\infty(a_1,b_1)$ and $\phi \in C_c^\infty(a_2,b_2)$, and then use the Reymond du-Bois lemma.


text:
Q: IsNumeric/IsError returns an error I'm quite new to VBA and working on a custom function (which will be used for more complicated purposes in the future - that is the reason for which I want to do this using VBA instead of standard formulas) whose task should be to get the date from the cell and specify its position (i.a. row number) within the column (e.g. column A).
This simple task I have solved by the following procedure:
Function TempRowNumber(OrgDate)
    TempRowNumber = WorksheetFunction.Match(OrgDate, Range("A:A"), 0)
End Function

It works well, of course. However the problem is, that it may happen that the date entered into function is not included in the range. In this case, the function should search for the latest entered date, before that date.  As in this range the dates are always sorted chronologically, I planned to construct an error checking formula (as an condition) and the appropriate loop.
The problem is, that if I write a formula like this:
=ISERROR(MATCH(C23;A:A;0))

it's all good (the formula returns TRUE if the date from cell C23 is found within the column A, and FALSE if the date is not found). But if try to rewrite this formula into VBA procedure, i.a.:
Function FindDate(OrgDate)

FindDate = IsError(WorksheetFunction.Match(OrgDate, Range("A:A"), 0))

End Function

the custom function returns #VALUE! error if the date is not found (and FALSE if it's not).
Below I attach a snapshot about what I describe.

Have you any idea what should I do? Thanks in advance.

A: I don't know the reason behind it but this works:
Function FindDate(Orgdate)
    FindDate = IsError(Application.Match(Orgdate, Range("A:A"), 0))
End Function

Logically it should work the same way as WorksheetFunction.Match and can be evaluated by IsError the same way but I've tried it and I'm getting the same result as yours.


text:
Q: how to pass useState state value to useReducer initialstate I want to pass a value from useState state value to useReducer initialstate.
const [item, setItem] = useState([]);

const initialState = {
    menuOpen: true,
    promoOpen: false,
    couponOpen: false,
    cartOpen: false,
    orderOpen: false,
    orderAmount: 1,
    filteredItem: item,
  };

const [state, dispatch] = useReducer(reducer, initialState);

const fetchUrl = async () => {
    const resp = await fetch(url);
    const respData = await resp.json();
    const item = respData.item;
    const category = respData.category;
    const promo = respData.promo;
    setItem(item);
    setCategory(category);
    setPromo(promo);
    setFilterItem(item);
  };

But when I do console.log(state.filteredItem), I got an empty array so I assume that it didn't pass the value to the initialState. Is there a way for me to pass a useState state value to useReducer initialState value?
Thanks before

A: What you are trying to do here will not work.  The initial state of the reducer is just that -- the INITIAL state.  It will use the value of initialState from the very first render, before your items has been updated with the fetch results.  Changes to the variable initialState will not effect the reducer after it has already been created.  You have to dispatch an action to store the items in your reducer.

A: const [item, setItem] = useState([]);
You declared your state with an empty array therefore that's what filteredItem shows. If you've set your state later on, in order to change it in the reducer I think you need to use dispatch function.


text:
Q: ffmpeg: Add multichannel audio stream (ac3 to aac) I want my first audio stream to be stereo (by default) and my second to be multichannel (5.1 surround) in my .mp4 video.
There's no problem in replacing the stereo audio stream, but when I try to add a 5.1 multichannel audio stream to the video, ffmpeg does only take the first two channels (front left and right speakers). All other channels are silent. How do I add ALL the channels to my second audio stream?
Here's what I got so far:
ffmpeg -i video.mp4 -i multichannel.ac3 -map 0 -map 1 -c:v copy -c:a aac -strict -2 result.mp4

Here's what my console outputs:
c:a aac -strict -2 result.mp4
ffmpeg version 2.2.2 Copyright (c) 2000-2014 the FFmpeg developers
  built on May 22 2014 19:56:44 with gcc 4.8.2 (GCC)
  configuration: --disable-static --enable-shared --enable-gpl --enable-version3 --disable-w32threads --enable-avisynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libcaca --enable-libfreetype --enable-libgme --enable-libgsm --enable-libilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-librtmp --enable-libschroedinger --enable-libsoxr --enable-libspeex --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvo-aacenc --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-decklink --enable-zlib
  libavutil      52. 66.100 / 52. 66.100
  libavcodec     55. 52.102 / 55. 52.102
  libavformat    55. 33.100 / 55. 33.100
  libavdevice    55. 10.100 / 55. 10.100
  libavfilter     4.  2.100 /  4.  2.100
  libswscale      2.  5.102 /  2.  5.102
  libswresample   0. 18.100 /  0. 18.100
  libpostproc    52.  3.100 / 52.  3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'video.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    title           :
    artist          :
    encoder         : Lavf55.33.100
  Duration: 01:00:39.61, start: 0.033333, bitrate: 10521 kb/s
    Stream #0:0(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p(tv), 1920x1080 [SAR 1:1 DAR 16:9], 10382 kb/s, 30.01 fps, 60 tbr, 30k tbn, 59.94 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 128 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
[ac3 @ 00f7d080] Estimating duration from bitrate, this may be inaccurate
Input #1, ac3, from 'multichannel.ac3':
  Duration: 01:00:39.58, start: 0.000000, bitrate: 640 kb/s
    Stream #1:0: Audio: ac3, 48000 Hz, 5.1(side), fltp, 640 kb/s

Does my problem have anything to do with 5.1(side) given above? Do I have to change this?

A: Your ffmpeg is 7 years old. Much has changed since then. You're wasting your time using such an old version. See the links to already compiled builds on FFmpeg Download and get a new version.
Then run:
ffmpeg -i video.mp4 -i multichannel.ac3 -map 0 -map 1 -c copy output.mp4

A: The OP is trying to get an AAC audio, and since the original stream is AC3, he is getting an AC3 stream in this mp4 output.
If he really wants AAC, he should run:
ffmpeg -i video.mp4 -i multichannel.ac3 -map 0 -map 1 -c:a aac output_with_aac.mp4


text:
Q: Detect and Report typedef Errors... What's This Doing? I was reading about making code more portable by using fixed-width integers. I found this article which helped explain things, and at the end it suggests using this anonymous union to detect and report typedef errors:
static union
{
    char   int8_t_incorrect[sizeof(  int8_t) == 1];
    char  uint8_t_incorrect[sizeof( uint8_t) == 1];
    char  int16_t_incorrect[sizeof( int16_t) == 2];
    char uint16_t_incorrect[sizeof(uint16_t) == 2];
    char  int32_t_incorrect[sizeof( int32_t) == 4];
    char uint32_t_incorrect[sizeof(uint32_t) == 4];
};

I'm a little lost and I was hoping someone could explain what this is doing?

A: If any of those equality checks result in false that union will have a field with an array size of 0, which isn't allowed and will result in a compiler error.

A: It's abusing the compiler, that's what it's doing.
Basically the sizeof(type) == num is being evaluated at compile time, and it's going to produce either a 0 or a 1 (false or true). If it's 0 (which none of them should be), it produces a compiler error, since you can't declare an array of size zero.
But as mentioned, this is quite abusive of the compiler, and most sane build environments would ensure the typedefs are correct for you (autoconf for example has built-in macros for this kind of stuff).


text:
Q: ORA-00932: inconsistent datatypes: expected - got CLOB in union query I have some Oracle query where i need to use CLOB_AGG function because when i used string_agg i got string buffer error (more than 4000 characters).
The problem is that when i use query separately it works but when i do the union.
I get:

inconsistent datatypes: expected - got CLOB error.

SELECT
  A.EVENT_ID,
  clob_agg(CAL.CALENDAR_DT) AS CALENDAR_DAYS
FROM
  TABLE1 A,
  CALENDAR CAL
WHERE
AND CAL.EVENT_ID(+) = A.EVENT_ID
GROUP BY
  A.EVENT_ID
UNION
SELECT
  B.SUB_EVENT_CD,
  CLOB_AGG(CALSUB.CALENDAR_DT) AS CALENDAR_DAYS
FROM
  TABLE1 A,
  TABLE1 B,
  RSS_CALENDAR CALSUB
WHERE
AND A.EVENT_ID             = B.EVENT_ID
AND CALSUB.SUB_EVENT_ID(+) = B.SUB_EVENT_ID
GROUP BY
  A.EVENT_ID,
  B.SUB_EVENT_ID

A: There were a few issues with your code. You needed a UNION ALL rather than a UNION and you had two AND's straight after a WHERE.
I have also replaced your joins with standard notation explicit joins rather than using join operators.
SELECT A.EVENT_ID, clob_agg(CAL.CALENDAR_DT) AS CALENDAR_DAYS
FROM TABLE1 A
LEFT OUTER JOIN CALENDAR CAL ON CAL.EVENT_ID = A.EVENT_ID
GROUP BY A.EVENT_ID
UNION ALL
SELECT B.SUB_EVENT_CD, CLOB_AGG(CALSUB.CALENDAR_DT) AS CALENDAR_DAYS
FROM TABLE1 A
INNER JOIN TABLE1 B ON A.EVENT_ID = B.EVENT_ID
LEFT OUTER JOIN RSS_CALENDAR CALSUB ON CALSUB.SUB_EVENT_ID = B.SUB_EVENT_ID
GROUP BY A.EVENT_ID, B.SUB_EVENT_ID


text:
Q: HotSwapping Java classes in IntelliJ causes tomcat to restart Our company switched recently from Eclipse to IntelliJ(UE).
In Eclipse I had no problems hot swapping small Java class changes into the running tomcat. In IntelliJ however when I click "Update classes and resources" I get the notification that e.g. "1 class reloaded", and a few seconds after that the tomcat server restarts automatically. Nobody else at the company is experiencing that kind of problem and I'm pretty sure I use the same configuration they do.
How do I get true Hot Swap?
Further info :
IDE - IntelliJ IDEA 13.0.2
OS - Fedora 19

Thank you.


text:
Q: Java program to reverse words in a string I want only one space in output between every word no matter how much spaces between the words in input. But in following code spaces in output between love and java same as input spaces.
public class Main {
    public static void main(String[] args) {
        String s = "I love       java programming.";

        String ss[] = s.split(" ");
        for (int i = ss.length - 1; i >= 0; i--) {
            System.out.print(ss[i] + " ");
        }
    }
}

Output:--
programming. java       love I

A: I completely agree with @Johannes Kuhn.
The problem is, the filter you passed to the method split detects only single spaces.
This can be solved easily by passing correct regex expression to detect multiple spaces and dots and the end of the sentence.
Have a look at the following implementation:
public class Main {

    public static void main(String[] args) {
        String s = "I love       java programming.";

        String ss[] = s.split("[\\.| ]+");
        for (int i = ss.length - 1; i >= 0; i--) {
            System.out.print(ss[i] + " ");
        }
    }
}

PS: You can use "[ ]+" if dots doesn't matter to you.

A: Small variation using StringBuilder and Lambdas
import java.util.Arrays;

class Main {

  public static void main(String ... args) {

    var s = "I love     java programming";
    var r = new StringBuilder();
    var parts = s.split("\\s +");
    Arrays.asList(parts).forEach(r::append);
    System.out.println(r.reverse().toString());

  }
}

Output: gnimmargorp avajevol I
Repl


text:
Q: Get only one paragraph from post through RSS I googled and googled try to find something relevant but no luck.
I'm setting up a 'daily tips' campaign for a client and I have to use RSS to do it.
In more detail I use MailChimp and I create a RSS-Driven campaign.
On the other side in the blog of the website there are daily scheduled posts.
I'm trying to find a way to only get the first paragraph of the each post to give it to MailChimp and include it in the email.
So that the structure ends up like this:
Post title
Post's first paragraph
Read more link
Any ideas?

A: I don't think this is possible within Mailchimp  directly, but you you might try FeedsAPI if you have a specific feed, even perfect if it's a not so popular feed since they can create specific extraction patterns for cases like this, it's however a paid service.


text:
Q: ProGuard with JavaCPP - Loader warnings I've built a fat jar of the tesseract basic example of 7.9 MB (see also this SO question). Now I want to shrink its size using ProGuard. Using this standard gradle task with the addition of keep 'class org.bytedeco.javacpp.** {*;}' and dontwarn 'org.bytedeco.javacpp.**' works just fine (7.6 MB jar size) but I get a lot of warnings when running the jar:
Warning: Loader.putMemberOffset(): java.lang.ClassNotFoundException: org.bytedeco.tesseract. ...
Warning: Loader.putMemberOffset(): java.lang.ClassNotFoundException: org.bytedeco.leptonica. ...

(following this guide leads to the same result).
I can prevent these warnings by keeping tesseract and leptonica too:
keep 'class org.bytedeco.tesseract.** {*;}'
keep 'class org.bytedeco.leptonica.** {*;}'

which results in a minimally larger jar (7.7 MB), but as the program seems to work OK with the warnings I was wondering if there's another way, e.g. by keeping not everything from org.bytedeco.
It's a really petty issue, but maybe there's an easy solution for it (the additional 0.1 MB is not a problem at all, just trying to get a little better understanding of javacpp, which is a really great library).


text:
Q: Connection between minimal polynomial of $\cos(2\pi/k)$ and Euler's totient function Background
I'm a recreational mathematician whose formal math education is only to pre-university level. I'm very much a self-learner and I particularly like (elementary) number theory.
I was investigating a problem originally asked on Twitter, which was

For each $k$, is there always an $N$ for which the integers less than and coprime to $N$ sum to $kN$? $(k,N\in\mathbb{N})$

The answer to this is no, and it turns out that if Euler's totient function, $\phi(n)$, never has value $2k$, then there is no such $N$ for $k$. The missing values for $k$ are given in http://oeis.org/A079695.
In the comments to sequence A079695 it's stated that "Because the degree of the minimal polynomial of $\cos(2\pi/k)$ is $\phi(k)/2$, the degree can never be a number in this sequence."
I'm familiar with cosine and totient, of course, but not familiar with minimal polynomials. I did a little research on minimal polynomials, but I don't at all understand why a trigonometric function should have any connection to a function, $\phi(n)$, that is essentially about divisibility of positive integers. So...
Question
Is there a straightforward way to explain why these two functions (cosine and totient) are connected via minimal polynomials?


text:
Q: Bundle custom session manager store in webapp archive (Tomcat 9) I am trying to add a custom Store for the PersistentManager in Tomcat 9.0.69.
It works no problem by adding my JAR with custom Store to the tomcat/lib directory and specifying a PersistentManager with my custom Store in the context.xml which is bundled with my webapp (META-INF/context.xml). However, I need to avoid adding the JAR to the tomcat/lib directory as this will be deployed in a PaaS environment without write access to that directory.
Ideally I would like to include the JAR containing my custom Store in the webapp WEB-INF/lib alongside its other libraries, and have some way of getting Tomcat to find it when setting up the session manager. As I understand it, by default Tomcat does not find it as it is setting up the session manager in the context of its own ClassLoader, not in the context of the application ClassLoader.
I found a StackOverflow answer which seems to suggest this is achievable by specifying some sort of ClassLoader using a <Loader> element in context.xml but I have no clue where to start with that, and the answer was for Tomcat 7 so I am unsure if it would still be true.


text:
Q: indexpath.row showing index 0 every time So the problem is , in my cellForRowAtIndexPath method everytime indexpath.row is "0" only. And to confirm I have printed the counter with "count". But  everytime it is showing 0 and my whole table is allocated with same values. Don't know what's wrong. Please someone help .
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [arr_Max count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

-(UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableViewCell";
    count=(int)indexPath.row;

    NSLog(@"%d",count);
    SimpleTableViewCell *cell = (SimpleTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    cell.label.text=[NSString stringWithFormat:@"%@",[arr_Max objectAtIndex:count] ];
    return cell;
}

A: Your code is error, the correct code is as follows:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:    (NSInteger)section
{
    return [arr_Max count];
}

A: Most likely your tableView delegate method numberOfRowsInSection is returning a bad number of rows.
Ensure that this required delegate method,
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

is returning a valid number - usually the number of elements in your datasource.

A: You have update your code with following and other part will remain unchanged:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [arr_Max count];
}

A: It seems you have number or rows = 1 (from numberOfRowsInSection).
So eachtime, when your tableview delegate fires method, it returns 1 rows only.
could you please explain more about ur problem.
For my understanding, you should go on like this code.
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
return [arr_Max count];
}

Then probably you will get the count value based upon your array contents.
please comment if it is ok or any query regarding this.