text:
Q: Django Rest Framework export csv data from models in background Currently, I am using DRF version '3.9.2'. I was doing some CSV export from models synchronously. Sample of the code blocks explained as below:
urls.py
from django.urls import path

urlpatterns = [
    path('api/users-csv-export/', UsersExportAsCSV.as_view())
]

views.py
from rest_framework.views import APIView

def get_users_data():
    queryset = User.objects.only('first_name', 'last_name', 'created_at', 'email', 'gender', 'date_of_birth')
    fields = ['first_name', 'last_name', 'created_at', 'email', 'gender', 'date_of_birth']
    titles = ['First Name', 'Last Name', 'Date Added', 'Email', 'Gender', 'Date of Birth']
    file_name = 'users'
    return queryset, fields, titles, file_name

class UsersExportAsCSV(APIView):
    def get(self, request):
        users = get_users_data()
        data = export_to_csv(queryset=users[0], fields=users[1], titles=users[2], file_name=users[3])
        return data

utils.py
def export_to_csv(queryset, fields, titles, file_name):
    """
    will export the model data in the form of csv file
    :param queryset: queryset that need to be exported as csv
    :param fields: fields of a model that will be included in csv
    :param titles: title for each cell of the csv record
    :param file_name: the exported csv file name
    :return:
    """
    model = queryset.model
    response = HttpResponse(content_type='text/csv')
    # force download
    response['Content-Disposition'] = 'attachment; filename={}.csv'.format(file_name)
    # the csv writer
    writer = csv.writer(response)
    if fields:
        headers = fields
        if titles:
            titles = titles
        else:
            titles = headers
    else:
        headers = []
        for field in model._meta.fields:
            headers.append(field.name)
        titles = headers

    # Writes the title for the file
    writer.writerow(titles)

    # write data rows
    for item in queryset:
        writer.writerow([nested_getattr(item, field) for field in headers])
    return response

As the data grows the request-response cycle becomes heavier. To prevent this request blocking other requests Threading vs Async task which one is preferable? Is there any good idea about optimizing the request-response cycle.
Here the user has to wait until whole the exporting works and download complete. The desired result here is that whenever the user visits the URL then the instant response of "file being generated" and generating and downloading the file in the background.
Any help on this topic will be highly appreciated.

A: I think you can achieve with this
http://www.celeryproject.org/
You can use "shared_task" to complete task for generating the csv file in background and save it to table (for ex: DownloadFileModel) if it already finish. Then you can download it later.Response your current view with redirecting to DetailView (DownloadFileModel record with null value in file field) that you prepared to download the file, if the file is unready just give the description to wait until the file is ready (and you can assign the file to the record).

A: i think, you can use the celery to run async task, it will give the lot of functionality show the progress and when task has been completed.
https://pypi.org/project/django-celery/

from celery import task

def get_users_data():
    queryset = list(User.objects.values_list('first_name', 'last_name', 'created_at', 'email', 'gender', 'date_of_birth'))
    fields = ['first_name', 'last_name', 'created_at', 'email', 'gender', 'date_of_birth']
    titles = ['First Name', 'Last Name', 'Date Added', 'Email', 'Gender', 'Date of Birth']
    file_name = 'users'
    return queryset, fields, titles, file_name

@task
def export_to_csv(queryset, fields, titles, file_name):
    """
    will export the model data in the form of csv file
    :param queryset: queryset that need to be exported as csv
    :param fields: fields of a model that will be included in csv
    :param titles: title for each cell of the csv record
    :param file_name: the exported csv file name
    :return:
    """
    model = queryset.model
    response = HttpResponse(content_type='text/csv')
    # force download
    response['Content-Disposition'] = 'attachment; filename={}.csv'.format(file_name)
    # the csv writer
    writer = csv.writer(response)
    if fields:
        headers = fields
        if titles:
            titles = titles
        else:
            titles = headers
    else:
        headers = []
        for field in model._meta.fields:
            headers.append(field.name)
        titles = headers

    # Writes the title for the file
    writer.writerow(titles)

    # write data rows
    # here you can save the file at particular path
    for item in queryset:
        writer.writerow([nested_getattr(item, field) for field in headers])
    return file_path

class UsersExportAsCSV(APIView):
    def get(self, request):
        users = get_users_data()
        task_id = export_to_csv.delay(queryset=users[0], fields=users[1], titles=users[2], file_name=users[3])
        return task_id

using the task id you can get the result of that

another approach is using djnago-channel, it uses the socket connection you don't need to make pooling request for check task is completed or not

A: To solve my problem, I used the python threading module and to store the file record I used the Redis cache server.
At first, the GET method will check whether the exported file record available in cache or not. If it is available then URL to that file is sent in response. The POST method will generate the file and write it in media/temp and store the record in the cache.
Few changes are made in the code blocks and are explained as below:
views.py
from rest_framework.views import APIView

def get_users_data():
    queryset = User.objects.only('first_name', 'last_name', 'created_at', 'email', 'gender', 'date_of_birth')
    fields = ['first_name', 'last_name', 'created_at', 'email', 'gender', 'date_of_birth']
    titles = ['First Name', 'Last Name', 'Date Added', 'Email', 'Gender', 'Date of Birth']
    return queryset, fields, titles, file_name

class TripHistoryExportAsCSV(APIView):
    file_name = "users_all"
    file_extension = 'csv'

    def post(self, request):
        try:
            queryset = get_users_data()[0]
            fields = get_users_data()[1]
            titles = get_users_data()[2]
            x = threading.Thread(target=export_to_csv, args=(queryset, fields, titles, self.file_name))
            x.start()
            return Response({
                'message': 'CSV file is generating'
            })
        except EmptyResultSet:
            return Response({
                'message': 'Can not create CSV file'
            }, status=status.HTTP_200_OK)

    def get(self, request):
        data = check_export_data_in_cache(self.file_name, self.file_extension)
        if data:
            return Response({
                'url': data.get('report_url')
            })
        else:
            return Response({
                'message': 'Generation of new files required'
            }, status=status.HTTP_204_NO_CONTENT)

utils.py
def nested_getattr(obj, attribute, split_rule='__'):
    """
    This function is responsible for getting the nested record from the given obj parameter
    :param obj: whole item without splitting
    :param attribute: field after splitting
    :param split_rule:
    :return:
    """
    split_attr = attribute.split(split_rule)
    for attr in split_attr:
        if not obj:
            break
        obj = getattr(obj, attr)
    return obj

def export_to_csv(queryset, fields, titles, file_name):
    """
    will export the model data in the form of csv file
    :param queryset: queryset that need to be exported as csv
    :param fields: fields of a model that will be included in csv
    :param titles: title for each cell of the csv record
    :param file_name: the exported csv file name
    :return:
    """
    model = queryset.model
    import os
    from yatruadminbackend.settings import MEDIA_ROOT
    if fields:
        headers = fields
        if titles:
            titles = titles
        else:
            titles = headers
    else:
        headers = []
        for field in model._meta.fields:
            headers.append(field.name)
        titles = headers

    with open(os.path.join(MEDIA_ROOT, f'temp/{file_name}.csv'), 'w', newline='') as file:
        # Writes the title for the file
        writer = csv.writer(file)
        writer.writerow(titles)
        # write data rows
        for item in queryset:
            writer.writerow([nested_getattr(item, field) for field in headers])
        set_cache_for_export_file(file_name, 'csv')

def set_cache_for_export_file(filename, extension):
    generated_date = timezone.now()
    export_file_name = f'{filename}_{extension}'
    record_in_cache = {
        'key': export_file_name,
        'report_url': f'{BACKEND_URL}media/temp/{filename}.csv',
        'generated_on': generated_date
    }
    cache.set(export_file_name, record_in_cache, 300)
    print(cache.get(export_file_name))

def check_export_data_in_cache(file_name, file_extension):
    cache_key = f'{file_name}_{file_extension}'
    print(cache_key)
    if cache.get(cache_key):
        return cache.get(cache_key)


text:
Q: How to run electron-packager offline without internet? I have an Angular project. I want to convert him to Desktop application. For this i use Electron.js.
I can run
electron .

It works fine.
But now i want to make an exe.
For this i want to use electron-packager.
The problem:
I run:
electron-packager . --platform=win32

The error:
getaddrinfo EAI_AGAIN github.com
I understand that electron-packager needs github, but how to solve it?! Again i work offline(with jfrog artifactory) without internet.
Is there another electron package which can do the same without internet? (make an exe)

A: The problem is that electron-packager go to github.com to download electron.js.
So as @Alexander Leithner said to use electronZipDir option. (and also malept in electron channel in Discord)
The solution is simple, when you executed:
npm install electron

A zip file of the binaries of electron are cached in your computer.
The command for electron-packager looks like this:
npm install  -D electron-packager
npx electron-packager  .  -- platform=win32 --electronZipDir=C:/Users/baruc/AppData/Local/electron/Cache/**some long string**

Thats all
Edit 25/7/2021
Theoretically, electron-packager has an option called "download" which you can pass to him a "cacheRoot" or "mirrorOptions" to download the electron.zip file.
By default you dont need to change the cacheRoot, but unfortunately both options of the download didnt work for me.
BTW, mirrorOptions got an object, not a string. So its not clear how to pass an object from the command line.
I saw that in the file artifact-utils.js of the @electron/get library, and there in the function called "mirrorVar" it search a special environment variables or the mirrorOptions which i tell before. If this function wont find them it will take the default which is github.
Solution when you have an artifactory:

*

*Create in your project an .npmrc file and write there:
ELECTRON_MIRROR="http://my mirror site/electron/"
Be aware that it end with back slash.

*Go to package.json file, and there to scripts write:
"pac": "electron-packager -- . --platform=win32"
3.execute it: npm run pac

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rust Snafu Crate: no method named `fail` found for enum `Error` in the current scope I'm trying to use the Snafu crate for some basic error handling. In this case, I'm trying to return an Error when check_value() is given anything but a CustomInputValue::CiFloat. Based on what I was seeing in examples on this page from the docs, I thought this would work:
use snafu::{Backtrace, ResultExt, Snafu, ensure};

#[derive(Debug, Snafu)]
pub enum Error{
    #[snafu(display("Incorrect Type: {:?}"), kind)]
    IncorrectInputType{kind: CustomInputValue},
}

#[derive(Debug, Clone, PartialEq)]
pub enum CustomInputValue{
    CiBool(bool),
    CiInt(i32),
    CiFloat(f64),
}

type Result<T, E = Error> = std::result::Result<T, E>;

fn main(){
    check_value(CustomInputValue::CiFloat(10.0));
}

fn check_value(val: CustomInputValue )->Result<()>{
    match val {
         CustomInputValue::CiFloat(inp)=>inp,
         _=>Error::IncorrectInputType{kind: val}.fail()?
    };
    Ok(())
}

However, this produces the error:
error[E0599]: no method named `fail` found for enum `Error` in the current scope
  --> src/main.rs:24:57
   |
4  | pub enum Error{
   | -------------- method `fail` not found for this
...
24 |                 _=>Error::IncorrectInputType{kind: val}.fail()?
   |                                                         ^^^^ method not found in `Error`

What's causing this error? Do I need to implement a fail function? I don't see anywhere in the docs such a custom fail() function being written for Error, and can't find anything bout requiring a fail() function for Error in the docs.

A: The #[derive(Snafu)] attribute creates "context selectors" for each enum variant. That means that Error::IncorrectInputType refers to the variant, while IncorrectInputType is a generated struct which has the fail() method.
The fix is to use this selector instead of the enum:
match val {
     CustomInputValue::CiFloat(inp) => inp,
     _ => IncorrectInputType { kind: val }.fail()?
       // ^^^^^^^^^^^^^^^^^^ no Error::
};

You can browse the rest of the SNAFU user's guide to know more about the macro.

Also, the kind in the #[snafu(display(...))] attribute is misplaced. It should be a parameter within the display portion:
#[snafu(display("Incorrect Type: {:?}", kind))]
IncorrectInputType { kind: CustomInputValue },


text:
Q: How can any formal system be embedded in a Typographical Number Theory string from Gödel, Escher, Bach? Firstly, I do understand how any formal system can be expressed as numbers rather than other symbols. I also understand that doing this makes any rule of inference a mathematical calculation. I'm also aware that simple sets—like whether a number is prime or not—can be expressed in a TNT string. My confusion comes when we discuss encoding 'any' formal system into TNT. A TNT string seems like it can handle a single rule system, but how can it handle a system with more than one rule? How can we express the rules of a formal system—like the MIU system or Collatz numbers—in a single string? From how I currently see it, the most we could do is make a separate TNT string for each rule of the formal system of interest. But that isn't asking TNT about the original formal system anymore. I hope this makes sense.
Are we adding rules of inference to TNT that reflect the rules of the formal system of interest? Are we adding several propositions into the TNT string? How can MUMON reflect every rule of MIU?


text:
Q: Custom function: Insert object into table I have the following function in my postgres database:
create function my_schema.create_my_book(book my_schema.book) returns my_schema.book as $$
declare
  v_book my_schema.book;
begin
  insert into my_schema.book(title, language) values (book.title, book.language) returning * into v_book;
  return v_book;
end;
$$ language plpgsql volatile;

This way I have to type out all the column names (title, language) and values (book.title, book.language). My book table is quite big so this will blow up my code by a lot, and once I add a column I will have to remember to add it to this function too.
Is there a way to directly insert the whole book my_schema.book object?

A: Yes, here it is. You do not even need plpgsql to do this, plain sql will do (and works faster).
create or replace function my_schema.create_my_book(arg_book my_schema.book)
returns my_schema.book as
$$
  insert into my_schema.book select arg_book.* returning *;
$$ language sql volatile;

I changed the argument's name to arg_book in order to avoid possible ambiguity. And since the type of arg_book is my_schema.book this simple code adapts itself to table mutation and continues to work.
To solve the id issue
create or replace function my_schema.create_my_book(arg_book my_schema.book)
returns my_schema.book as
$$
declare
  v_book my_schema.book%rowtype;
begin
  arg_book.id := nextval('the-id-sequence-name');
  insert into my_schema.book select arg_book.* returning * into v_book;
  return v_book;
end;
$$ language plpgsql volatile;

which is pretty close to your initial function, just dynamic.


text:
Q: Can't use GraphQL in the AEM I added GraphQL  to the bundle in the AEM and it caused bundle start failed.

*

*I have a bundle project and it works fine in the AEM.  Bundle start command : mvn clean install -PautoInstallBundle

    <profile>
        <id>autoInstallBundle</id>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>
        <build>
            <pluginManagement>
                <plugins>
                    <plugin>
                        <groupId>org.apache.sling</groupId>
                        <artifactId>maven-sling-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>install-bundle</id>
                                <goals>
                                    <goal>install</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </pluginManagement>
        </build>
    </profile>

*I add below config to the pom.xml then reinstall bundle and bundle still work fine.

<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java</artifactId>
<version>3.0.0</version>
</dependency>

*I added two demo classes to my project and reinstall bundle. Bundle start failed. GraphQL_SImple.java and User.java can be found in the https://github.com/zhaiqianfeng/GraphQL-Demo/blob/master/java/src/main/java/com/zqf/get_start/GraphQL_Simple.java

*Error message is :

12.07.2018 14:55:17.223 ERROR [qtp1398311933-54244] org.apache.felix.http.jetty %bundles.pluginTitle: Cannot start
  (org.osgi.framework.BundleException: Unable to resolve
  com.mb.graphql.mb-graphql.core [528](R 528.27): missing requirement
  [com.mb.graphql.mb-graphql.core [528](R 528.27)] osgi.wiring.package;
  (osgi.wiring.package=graphql) Unresolved requirements:
  [[com.mb.graphql.mb-graphql.core [528](R 528.27)] osgi.wiring.package;
  (osgi.wiring.package=graphql)])   org.osgi.framework.BundleException:
  Unable to resolve com.mb.graphql.mb-graphql.core [528](R 528.27):
  missing requirement [com.mb.graphql.mb-graphql.core [528](R 528.27)]
  osgi.wiring.package; (osgi.wiring.package=graphql) Unresolved
  requirements: [[com.mb.graphql.mb-graphql.core [528](R 528.27)]
  osgi.wiring.package; (osgi.wiring.package=graphql)]   at
  org.apache.felix.framework.Felix.resolveBundleRevision(Felix.java:4112)
  at org.apache.felix.framework.Felix.startBundle(Felix.java:2118)   at
  org.apache.felix.framework.BundleImpl.start(BundleImpl.java:998)   at
  org.apache.felix.framework.BundleImpl.start(BundleImpl.java:984)   at
  org.apache.felix.webconsole.internal.core.BundlesServlet.doPost(BundlesServlet.java:364)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)   at
  javax.servlet.http.HttpServlet.service(HttpServlet.java:725)   at
  org.apache.felix.webconsole.internal.servlet.OsgiManager.service(OsgiManager.java:563)
  at
  org.apache.felix.webconsole.internal.servlet.OsgiManager$3.run(OsgiManager.java:465)
  at java.security.AccessController.doPrivileged(Native Method)   at
  org.apache.felix.webconsole.internal.servlet.OsgiManager.service(OsgiManager.java:461)
  at
  org.apache.felix.http.base.internal.handler.ServletHandler.handle(ServletHandler.java:85)
  at
  org.apache.felix.http.base.internal.dispatch.InvocationChain.doFilter(InvocationChain.java:79)
  at org.apache.sling.i18n.impl.I18NFilter.doFilter(I18NFilter.java:138)
  at
  org.apache.felix.http.base.internal.handler.FilterHandler.handle(FilterHandler.java:135)
  at
  org.apache.felix.http.base.internal.dispatch.InvocationChain.doFilter(InvocationChain.java:74)
  at
  org.apache.sling.security.impl.ReferrerFilter.doFilter(ReferrerFilter.java:295)
  at
  org.apache.felix.http.base.internal.handler.FilterHandler.handle(FilterHandler.java:135)
  at
  org.apache.felix.http.base.internal.dispatch.InvocationChain.doFilter(InvocationChain.java:74)
  at
  com.adobe.granite.license.impl.LicenseCheckFilter.doFilter(LicenseCheckFilter.java:308)
  at
  org.apache.felix.http.base.internal.handler.FilterHandler.handle(FilterHandler.java:135)
  at
  org.apache.felix.http.base.internal.dispatch.InvocationChain.doFilter(InvocationChain.java:74)
  at
  org.apache.felix.http.sslfilter.internal.SslFilter.doFilter(SslFilter.java:96)
  at
  org.apache.felix.http.base.internal.handler.FilterHandler.handle(FilterHandler.java:135)
  at
  org.apache.felix.http.base.internal.dispatch.InvocationChain.doFilter(InvocationChain.java:74)
  at
  org.apache.felix.http.base.internal.dispatch.Dispatcher.dispatch(Dispatcher.java:128)
  at
  org.apache.felix.http.base.internal.dispatch.DispatcherServlet.service(DispatcherServlet.java:49)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)   at
  org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:812)
  at
  org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:587)
  at
  org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:221)
  at
  org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
  at
  org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
  at
  org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
  at
  org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
  at
  org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
  at
  org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
  at
  org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
  at org.eclipse.jetty.server.Server.handle(Server.java:499)   at
  org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)   at
  org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
  at
  org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544)
  at
  org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
  at
  org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
  at java.lang.Thread.run(Unknown Source)

Is anyone face same issue and know how to fix it?
Thanks

A: I find a way to resolve it. add below config to the maven-bundle-plugin.

<Export-Package>graphql.*</Export-Package>


text:
Q: Embed Windows Media Player in a PyGTK application Is there any way to display videos in a PyGTK application using Windows Media Player? I'm trying to play SopCast streams in a PyGTK application and currently I'm doing that by embedding Internet Explorer and showing an webpage containing a Windows Media Player control, but I need a better way to do this.
Also, I'm wondering if I can access the SopCast's OCX, starting the stream from there and then playing it using VLC (this would be better) by opening the localhost stream which SopCast creates.
Thank you


text:
Q: Loop through tags inside tags in Selenium/Python I am trying to use selenium to loop through a list of properties on a web page and return the property address and auction time. I have the following python code so far and html for the web page below.
I'm able to return the links to every property in the list, but can't seen to return the values I need from the "H4" tags. I think I'm doing something wrong with getting the elements by Xpath but I can't seem to figure it out.
Any help would be greatly appreciated!
HTML:

123 memory-lane

            POWDER SPRINGS, GA 30127, Cobb County

Apr 04, 10:00am

456 memory-lane

            POWDER SPRINGS, GA 30127, Cobb County

March 10, 10:00am

Python (Selenium):
propertyList = browser.find_elements_by_xpath('//div[@data-elm-id="asset_list_content"]')

for element in propertyList:
    propertyLinks = element.find_elements_by_tag_name('a')
    for propertyLink in propertyLinks:
        propertyAddress = propertyLink.get_element_by_xpath('//h4[1]')
        propertyAuctionTime = propertyLink.get_element_by_xpath('//h4[2]')
        print(propertyAddress).text
        print(propertyAuctionTime).text

Output:
propertyAddress = propertyLink.get_element_by_xpath('//h4[1]')
AttributeError: 'WebElement' object has no attribute 'get_element_by_xpath'

A: The error seems to be you are using get_element_by_xpath(), which isn't a valid method. You used find_elements_by_xpath() in your code before that moment, and to find the elements you are looking for you just need to use the method that only finds a single element: find_element_by_xpath().


text:
Q: Garbage-collecting jobject returned from JNI to Java As stated in the answer to this question,

All jobjects created inside a JNI method are local references by default. Whenever a JNI method returns, all local references are automatically released.

In the same time,

When a global reference is no longer needed, it should be deleted by DeleteGlobalRef, otherwise referenced object will never be garbage-collected.

So, in order to return a jobject from JNI back to Java, we need global reference. But in the same time, how can we make it to be eventually garbage-collected on Java side, if DeleteGlobalRef cannot be called from there?


text:
Q: Fatal error in MPI_Bcast: Message truncated, error stack My program crashes after doing MPI_Bcast. Below is the code and the error.
int size_of_simple = 0;

    long long* simple = malloc(50000 * sizeof(long long));
    if (rank == 0) {
        size_of_simple = sieve_of_Eratosthenes(50000, simple);
    }
    MPI_Barrier(MPI_COMM_WORLD);
    long long n = 0;

    while (1) {
        if (rank == 0) {
            printf("Select the number: ");
            fflush(stdout);
            if (scanf("%lld", &n)) {};
        }

        if (rank == 0) {
            sequential_algorithm(n, simple, size_of_simple);
        }

        MPI_Barrier(MPI_COMM_WORLD);

        MPI_Bcast(simple, size_of_simple, MPI_LONG_LONG, 0, MPI_COMM_WORLD);
        MPI_Bcast(&size_of_simple, 1, MPI_INT, 0, MPI_COMM_WORLD); //error

        parallel_algorithm(n, simple, size_of_simple, rank, size);

    }

I also found out that when the first parameter in the sieve_of_Eratosthenes() function is changed, the number of bytes received in the error decreases, what could be the problem?

A: I believe, there are two issues in your code.
First, the program crash is happening happening because rank 0 is sending size_of_simple amount of long variables in MPI_Bcast but all the remaining processes are receiving only data of size "0" (because size_of_simple is 0 in all other processes except rank 0).
    MPI_Bcast(simple, size_of_simple, MPI_LONG_LONG, 0, MPI_COMM_WORLD);

If you put your second MPI_Bcast before the first, it should fix your error.
    MPI_Bcast(&size_of_simple, 1, MPI_INT, 0, MPI_COMM_WORLD); //error
    MPI_Bcast(simple, size_of_simple, MPI_LONG_LONG, 0, MPI_COMM_WORLD);

Secondly, the value of n should also be broadcasted to all the processes from rank 0 before calling parallel_algorithm(), if I understand the logic of the code correctly.
Also, the error message from MPI can help you figure out these kind of errors. It's shown that your buffer size is smaller than received size. So we can infer that, it's definitely the issue either with sending too much data or receiving too less data. Hence, very easy to debug in small programs (personal opinion).


text:
Q: Performance of Class methods vs singleton instance methods In my app, I'm using both strategies:

*

*I have a Utils class, it only has class methods that I call for doing common global methods, like NSString validation, etc.

*I have an app-wide singleton class which I instantiate during app Did Finish Launching, and use this throughout the app to hold global objects / state, perform long-running processes, etc.
My question is, in the terms of performance which approach is better? I'm happy with both the approaches, but I can do an inexpensive, but effortful migration to move all the Utils class methods to instance methods in the app-wide singleton if this would give me performance gains. The Utils methods get called a lot in my app, but I don't really notice any performance penalties in Instruments.
Likewise, I can go the other way and move at least a few of the somewhat general purpose functions I end up adding to the singleton to now be class methods in the Utils class as well.
Does any Objective-C guru have some concrete benchmarks or even strong opinions on which approach is more performant?

A: To start with if you really need to shave those extra few nanoseconds off your Utils C++ functions (potentially inlined) are probably the fastest thing on offer to you.
As to the question of whether class methods or singleton instance methods are more performant I will not claim to know for sure but a quick look at the objective-c runtime shipped with OSX 10.10 shows that _class_getClassMethod calls _class_getInstanceMethod which might lead you to think that instance methods would be faster.
Looking into this further I found that _object_getMethodImplementation calls _class_getMethodImplementation. Which would point to class methods being slightly faster to load.
All this is pretty moot though as in any instance you have 1 or 2 more function pointer accesses. This would only be noticeable if your methods are being called at least millions of times (and at that point optimising your method implementations is probably time better spent).
Stylistically, I agree with what you currently have, using singletons where state is required and class methods where it is not.


text:
Q: CLI filesystem benchmark for random read/write with specified block size I'm in search of a filesystem benchmark utility. I basically want to run a test which should be able to do random reads/writes on a specified drive with a given block size. e.g. a 4K random write on a linux system.

A: Check the Linux Benchmark Suite page. It has links to a bunch of benchmarks, including bonie and bonie++ which can do what you want (and more).
For bonnie++, to change the block size, you might also need to specify the test file size.
usage: bonnie++ [-d scratch-dir] [-s size(MiB)[:chunk-size(b)]]

So bonnie++ ... -s 1g:4k ... should do I/O in 4096 byte chunks.
Also check out iozone. It has a scary number of command line arguments, but r can be used to fix the block size. Check out the documentation to understand the output.

A: These days fio would do that very easily:
fio --name=basic --filename=/mnt/fs/fiotestfile --size=1G --rw=randrw --bs=4k

See the fio documentation for a description of fio's (many) options.


text:
Q: Finding partial derivatives of a function How would I find the partial derivatives of a function $$L(x(t), v(t), t)$$ where x and v are a function of time? I'm trying to derive the Euler-Lagrangian equation, and finding partial derivatives for $$x(t)+s \eta(t)$$ $$v(t)+s \eta(t)$$ of this expression:
$$ \frac{d}{ds} \int_{a}^{b} L(x(t)+s \eta(t),v(t)+s \eta(t),t) \, dt $$
seems too complex at the moment. Any hints? I know that in general, for $$L(x(t),y(t),z(t))$$
$$ \frac{dL}{dt}=\frac{dL}{dx}\frac{dx}{dt}+\frac{dL}{dy}\frac{dy}{dt}+\frac{dL}{dz}\frac{dz}{dt} $$
But how do I apply that to this problem?


text:
Q: Pushing a local branch up to GitHub I have Git configured so that when I run git push, it pushes changes to my GitHub repo. Until now I have only had a master branch.
However, I have now created a local branch and committed to it using:
git checkout -b my_new_branch
git commit

What I would like to do now is push my changes on this branch to GitHub. Do I just do a git push?
When I first set it up I did run:
git config push.default current

A: Depending on your local git settings, if you have a branch checked out that isn't the one you cloned or one that exists where you are trying to push, git will not push your local branch.
Here is the message it provides:

warning: push.default is unset; its implicit value has changed in Git
  2.0 from 'matching' to 'simple'. To squelch this message and maintain the traditional behavior, use:
git config --global push.default matching
To squelch this message and adopt the new behavior now, use:
git config --global push.default simple
When push.default is set to 'matching', git will push local branches
  to the remote branches that already exist with the same name.
Since Git 2.0, Git defaults to the more conservative 'simple'
  behavior, which only pushes the current branch to the corresponding
  remote branch that 'git pull' uses to update the current branch.
See 'git help config' and search for 'push.default' for further
  information. (the 'simple' mode was introduced in Git 1.7.11. Use the
  similar mode 'current' instead of 'simple' if you sometimes use older
  versions of Git)
fatal: The current branch MyLocalBranch has no upstream branch. To push the
  current branch and set the remote as upstream, use
git push --set-upstream origin MyLocalBranch

A: I believe you're looking for git push origin my_new_branch, assuming your origin remote is configured to hit your github repository.

A: If you are really lazy, you can push all local branches by simply using
git push --all

--all
Push all branches (i.e. refs under refs/heads/); cannot be used with
  other <refspec>.

A: If you've configured your git to push to your GitHub master repo, no matter in with branch you are, it will push to your GitHub master repo.
Bear in mind that, if many developers are working in the same repository, you could get a conflict.


text:
Q: How to move the files from Amazon s3 to sftp using shell scripts We have a requirement to automate the process of moving the CSV files from Amazon s3 to sftp server using shell scripts(BASH). Can we achieve this requirement using shell scripting? If yes, can someone help me in sharing the sample code?

A: An SFTP server simply makes local files accessible via the SFTP protocol. Therefore, all you need to do is to copy the files from Amazon S3 to the local disk.
This can be done via the AWS Command-Line Interface (CLI) aws s3 cp command or, better yet, aws s3 sync. This can be called from shell scripts.


text:
Q: Applying scopes in joins I have following models:
class Category < ActiveRecord::Base
  has_many :items
  default_scope where(:enabled => true, :out_of_stock => false)
  scope :enabled, where(:enabled => true)
  scope :out_of_stock, where(:out_of_stock => true)
end

class Item < ActiveRecord:Base
  belongs_to :category
end

I've faced following code duplication, repeating scope conditions across entire project, when using joins:
Category.joins(:offers).where(:items => {:merchant_id => @merchant.id, :enabled => true, :out_of_stock => false})

It would be nice, if applying specified scope in joins will be possible:
Category.joins(:offers).where(:items => {:merchant_id => @merchant.id, :scope => :default})

A: Try using & like this:
Category.joins(:offers, :items) & Item.default.where(:merchant_id => @merchant.id)

I think this is called interpolation. It joins the two queries together, preserving the first one as the base (it return Category objects).


text:
Q: Tiff image in java applet I am trying simple java applet program to display tiff image  as below
import java.applet.Applet;
import java.awt.Graphics;

import javax.swing.ImageIcon;

/* <applet code="Form1" width=100 height=50>
</applet> */
public class Form1 extends Applet
{
     ImageIcon image ;

       public void init(){

           image = new ImageIcon("C:/Documents and Settings/inos002827/Desktop/a.tif");
       }

        public void paint(Graphics g){

              g.drawImage(image.getImage(), 0,0,this);

        }

}

But I am getting blank applet.Same is working for jpeg image.

A: For TIFF Support, see Java Advanced Imaging.
From the FAQ

What image file formats are supported?
The codec classes supplied with Java Advanced Imaging 1.1.2_01 support BMP, GIF (read only), FlashPix (read only), JPEG, PNG, PNM, TIFF, and WBMP.

A: From memory, Tiff files are not supported via this means.  You will need to look towards the ImageIO API and probably a third party library.
Oddly enough, a 3 second search of google found this Can't read and write a TIFF image file using Java ImageIO standard library


text:
Q: Convert integers to a Byte array VB.net I have the following Java code working as expected, to convert some numbers to an array of Bytes before writing to a stream.
byte[] var1 = new byte[]{
    (byte)-95,
    (byte)(240 / 256 / 256 % 256),
    (byte)(240 / 256 % 256),
    (byte)(240 % 256),
    (byte)0
};

I need to write the same in VB .net
I tried the following code in VB .net, but no success.
Dim var1(4) As Byte
    var1(0) = Byte.Parse(-95)
    var1(1) = Byte.Parse(240 / 256 / 256 Mod 256)
    var1(2) = Byte.Parse(240 / 256 Mod 256)
    var1(3) = Byte.Parse(240 Mod 256)
    var1(4) = Byte.Parse(0)

Am I doing it wrong.? How to get it done properly..
Thank you.

A: You can convert an integer (32 bit (4 byte)) to a byte array using the BitConverter class.
Dim result As Byte() = BitConverter.GetBytes(-95I)

Dim b1 As Byte = result(0) '161
Dim b2 As Byte = result(1) '255
Dim b3 As Byte = result(2) '255
Dim b4 As Byte = result(3) '255

A: ''' <summary>
''' Convert integer to user byte array w/o any allocations.
''' </summary>
''' <param name="int">Integer</param>
''' <param name="DestinationBuffer">Byte array. Length must be greater then 3</param>
''' <param name="DestinationOffset">Position to write in the destination array</param>
<Runtime.CompilerServices.MethodImpl(Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)>
Public Overloads Shared Sub GetBytes(Int32 As Integer, ByRef DestinationBuffer As Byte(), DestinationOffset As Integer)
    DestinationBuffer(DestinationOffset + 0) = CByte(Int32 And &HFF)
    DestinationBuffer(DestinationOffset + 1) = CByte(Int32 >> 8 And &HFF)
    DestinationBuffer(DestinationOffset + 2) = CByte(Int32 >> 16 And &HFF)
    DestinationBuffer(DestinationOffset + 3) = CByte(Int32 >> 24 And &HFF)
End Sub


text: Q: django export data to excel template I installed django-import-export and it's working fine with export to excel file. But I would like to insert data into prepared excel file because of some macro. It's possible to do like that? And how can I achieve it?


text:
Q: Error using string array in C I am trying to create an array of strings, and print it. Sounds easy, but nothing works for me.
First try was:
int main(){

char ls[5][3]={"aba","bab","dad","cac","lal"};
printf("Das hier: %s", ls[1]);

return 0;
}

But the output is:
Das hier: babdadcaclal a

Even if it should only be:
bab

Next try was after some searches, using:
char* ls[5][3]=.....

instead. This prints:
Das hier: pP@

I was searching for this problem about one day, and I guess, that the problem could be my compiler, but I am not sure about that...
Hope that someone knows what to do, because I am out of ideas. I am using the gcc compiler, if this somehow matters.

A: This "bab" is a string with an invisible termination '\0' at the end, i.e. of size 4.
To fix, change to
char ls[5][4]={"aba","bab","dad","cac","lal"};

Then, to improve maintainability, use the proposal from David C. Rankins comment,
to make an implicitly sized array of TLAs:
char ls[][4]={"aba","bab","dad","cac","lal"};

To use that, use this variable for setting up loops:
size_t n;
n = sizeof ls / sizeof *ls;

A: Strings in C are null-terminated it means that you need one more byte at the end of the character array to mark it's termination. otherwise you cannot find where the string actually ends.
For example,
If I have string "aba" it would be like that at the memory:
'a','b','a','\0'
So you should define you're array as:
char ls[5][4]={"aba","bab","dad","cac","lal"};


text:
Q: CryptographicException: Bad PKCS7 padding. Invalid length 82 Trying to implement Encryption/Decryption.. the way is to serialize the data into a JSON and then encrypting that JSON to save it. sometimes, it works without any issue while sometimes I get this bad padding error. is there anything that I am missing? tried switching to Rijndael but getting a similar exception.
Save/Load Mechanics
public static void SaveGameJson()
{

    Debug.Log("TRYING TO SAVE THE GMAE THROUGH Json File");
    SaveManager data = new SaveManager();

    string jsonData = JsonUtility.ToJson(data); // encrypting the json data..
//    string jsonData = JsonConvert.SerializeObject(data); // encrypting the json data..

    string encryptedJsonData = EncryptionRijndael.Encrypt(jsonData);
    WriteToFile(JsonfileName, encryptedJsonData);
    Debug.LogError("Json data Saved: " + jsonData);
    Debug.LogError("Json Encrypted data: " + encryptedJsonData);
}

public static SaveManager LoadGameJson()
{
    string path = GetFilePath(JsonfileName);
    Debug.Log("TRYING TO LOAD THE GMAE THROUGH FILE");

    if (File.Exists(path))
    {
        string encryptedJsonData = ReadFromFile(JsonfileName); // reading encrypted data from json Encrypted file
        string jsonData = EncryptionRijndael.Decrypt(encryptedJsonData); // decrypting json data from encrypted string
        Debug.LogError("Json data Load: " + jsonData);
        Debug.LogError("Encrypted Data: " + encryptedJsonData);
        SaveManager data = JsonUtility.FromJson<SaveManager>(jsonData);
        //SaveManager data = JsonConvert.DeserializeObject<SaveManager>(jsonData);

        return data;
    }
    else
    {
        Debug.LogError("save file not found on:" + path);
        return null;
    }
}

Additional Function
    static void WriteToFile(string fileName, string json) {

    string path = GetFilePath(fileName);

    FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate);
    using (StreamWriter writer = new StreamWriter(fileStream)) {
        writer.Write(json);
    }
}

Encryption
public static string Encrypt(string strPlain)
{
    string password = strPassword;
    if (!useSecure)
        return strPlain;

    try
    {
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();

        Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, GetIV(), Iterations);

        byte[] key = rfc2898DeriveBytes.GetBytes(8);

        using (var memoryStream = new MemoryStream())
        using (var cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(key, GetIV()), CryptoStreamMode.Write))
        {
            memoryStream.Write(GetIV(), 0, GetIV().Length);

            byte[] plainTextBytes = Encoding.UTF8.GetBytes(strPlain);

            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cryptoStream.FlushFinalBlock();

            return Convert.ToBase64String(memoryStream.ToArray());
        }
    }
    catch (Exception e)
    {
        Debug.LogWarning("Encrypt Exception: " + e);
        return strPlain;
    }
}

Decryption
 public static string Decrypt(string strEncript)
 {

    string password = strPassword;

    if (!useSecure)
        return strEncript;

    try
    {
        byte[] cipherBytes = Convert.FromBase64String(strEncript);

        using (var memoryStream = new MemoryStream(cipherBytes))
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] iv = GetIV();
            memoryStream.Read(iv, 0, iv.Length);

            // use derive bytes to generate key from password and IV
            var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, iv, Iterations);

            byte[] key = rfc2898DeriveBytes.GetBytes(8);

            using (var cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
            using (var streamReader = new StreamReader(cryptoStream))
            {
                string strPlain = streamReader.ReadToEnd();
                return strPlain;
            }
        }
    }
    catch (Exception e)
    {
        Debug.LogWarning("Decrypt Exception: " + e);
        return strEncript;
    }
}

JSON getting saved

Loading JSON from encrypted string

PS: it seems like the encryption is working fine in the logs but when it tries to decrypt the string, it throughs this exception. Is there any better option for this?


text:
Q: Messed up newest kernel, how to fix it? So I was doing the regular apt updates and decided to do a little clean-up on the boot partition. Anyway, during that "clean-up", I managed to mess up the newest kernel and now when I boot it, it seems that the only most basic drivers are working. The login screen loads up slowly, like it's printing from top to down, the laptop touchpad and wifi don't work, and the whole system is rather laggy.
Luckily, I had 2 older kernels up so I booted up from the GRU menu the second one where everything works perfectly fine.
I tried running the:
sudo apt-get install --reinstall linux-image-5.15.0-46-generic
(-46 being the latest), rebooted again but to no prevail. Still the same issue. I am not an expert Linux user so I really don't have any ideas what to do here.
That is, I can only assume it's only the kernel.
These are the images I have on my system:
rc  linux-image-5.13.0-52-generic              5.13.0-52.59~20.04.1                        amd64        Signed kernel image generic
rc  linux-image-5.15.0-41-generic              5.15.0-41.44~20.04.1                        amd64        Signed kernel image generic
rc  linux-image-5.15.0-43-generic              5.15.0-43.46~20.04.1                        amd64        Signed kernel image generic
ii  linux-image-5.15.0-46-generic              5.15.0-46.49~20.04.1                        amd64        Signed kernel image generic
ri  linux-image-unsigned-5.11.0-46-generic     5.11.0-46.51~20.04.1                        amd64        Linux kernel image for version 5.11.0 on 64 bit x86 SMP
ii  linux-image-unsigned-5.13.0-52-generic     5.13.0-52.59~20.04.1                        amd64        Linux kernel image for version 5.13.0 on 64 bit x86 SMP
ii  linux-image-unsigned-5.15.0-43-generic     5.15.0-43.46~20.04.1                        amd64        Linux kernel image for version 5.15.0 on 64 bit x86 SMP

Also, what's the difference between the linux-image and linux-image-unsigned ?
It's not that I don't want to troubleshot this myself, as most of us like it. But I am kinda limited with my time right now and I am a bit scared to mess with kernels as it could mess up my boot to the point I can't use the system.
edit: I was thinking of upgrading to 22.04 LTS, where I have 2 questions regarding that idea:

*

*will that fix my issue?

*regarding the same issue, will this upgrade make things worse?


text:
Q: DataGridView SelectedRows returns null I don't get why the SelectedRows.ToString() returns something null even when I look at the Documentation of Microsoft.
So here's my code :
DataGridViewRow row = dgvTransaction.SelectedRows[0];
string tempcid = row.Cells[0].ToString();
dbop.delete_command(String.Format("DELETE FROM CERAMIC WHERE CERAMIC_ID = '{0}'",tempcid));

Is there anything wrong here? the DataGridView source is a DataSet from database though and I have changed the selection mode to full row selection also.
I've been searching for the question on stack overflow about selected rows and none of them answered my question. maybe a little bit of answer would help me ^^
EDIT 1
save changes of DataGridView to database
That helps me, thanks mate

A: Edited my code to
DataGridViewRow row = dgvTransaction.SelectedRows[0];
string tempcid = row.Cells[0].Value.ToString();
dbop.delete_command(String.Format("DELETE FROM CERAMIC WHERE CERAMIC_ID = '{0}'",tempcid));

dgvTransaction.Rows.RemoveAt(row.Index);
dgvTransaction.Refresh();

and it works. thanks


text:
Q: Microsoft Word Hangs During A Find Using Styles When searching for styles in a Word document, a search for styles sometimes hangs after finding only the first occurrence, and enters an endless loop. This happens mostly within tables, even if there are occurrences later in the same cell. It never happens when searching for text. Is that a bug? How is it worked around?
Public Sub FindOccurences()
    On Error GoTo MyErrorHandler

    Dim i As Long: i = 0
    Dim findRange As Range
    Set findRange = ActiveDocument.Range

    With findRange.Find
        findRange.Find.ClearFormatting

        'findRange.Find.Text = "the" 'Never hangs searching for text
        findRange.Find.Style = ActiveDocument.Styles("text.10")

        Do While .Execute(Forward:=True) = True
            findRange.HighlightColorIndex = wdTurquoise
            i = i + 1

            DoEvents
        Loop
    End With

    MsgBox "Done. Found times: " & i

    Exit Sub

MyErrorHandler:
    MsgBox "FindOccurences" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
End Sub

A: I tried this code and ended up with an infinite loop, even though my document does not have any tables.  I think the problem is that the while loop condition you use is constructed for a linear search of the word document, and that styles are not searched in a linear fashion, but rather iterated through some type of collection data structure.


text:
Q: How to select resistor for emitter follower when driving speaker?

simulate this circuit – Schematic created using CircuitLab
The objective is to drive 1 watt into the speaker. R1 represents the output impedance of the previous common collector stage.
Here's what I think I know:

*

*1 watt into 4 ohms means 2V RMS or 2.8V peak.

*If the beta of Q1 is something like 70 then the input impedance of the emitter follower is something like 700--pretty low.

*In the quiescent state C1 is charged and the current through the speaker is zero.

*When the voltage rises to +2.8V, 700mA (2.8V/4 ohms) goes to SPKR1. (Confused about whether it all goes to SPKR1, seems like some must go through R2.)

*When the voltage falls to -2.8V, 700mA gets pulled back through SPKR1 and must be sunk through R2.

The problem in a sentence is that R2 is too high to sink the current coming back from SPKR1 when the voltage is low. If the emitter voltage is about 6V then when it swings -2.8V to 3.2V, R2 will sink only 320mV. So the returning current causes the emitter voltage to rise, turning off Q1 and creating a flat spot at the bottom of the waveform.
If I decrease R2, then the input impedance drops and it's hard to maintain the voltage swing. Also, the quiescent current increases and I start needing a big heat sink for Q1.
My question is: is there a process for determining a value for R2 that can meet the objective of driving 1 watt into the speaker, or is this just a waste of time?

A: As you know, the peak AC input signal for delivering any particular power into any particular speaker load is:
$$V_\text{P}=\sqrt{2\:R\:P}$$
In your case, with \$1\:\text{W}\$ and \$R_\text{SPKR}=4\:\Omega\$, this works out to \$V_\text{P}=2.83\:\text{V}\$ and \$I_\text{P}=710\:\text{mA}\$.
Also, your capacitor needs to have a low impedance relative to the speaker, so let's say about \$400\:\text{m}\Omega\$ for the capacitor. If you decide that \$f=200\:\text{Hz}\$ is the lowest frequency you want to handle, this suggests a capacitance of \$2\:\text{mF}\$. A bit larger than you show. Let's also assume you set the capacitance, appropriately.

In general, you want the BJT to be operating with a collector current dynamic range of less than 5:1. (That's about \$42\:\text{mV}\$ variation of \$V_\text{BE}\$.) This means that your minimum emitter current should be  \$I_{\text{E}_\text{MIN}}\ge \frac{1}{2}\left[I_\text{P}+\frac{V_\text{P}}{R_\text{E}}\right]=\frac{1}{2}\frac{V_\text{P}}{R_\text{E}\vert\vert R_\text{SPKR}}\$. In your circuit's case, this means \$I_{\text{E}_\text{MIN}}\ge 495\:\text{mA}\$. Whatever you decide for \$I_{\text{E}_\text{MIN}}\$ is your choice, though. That's just a recommendation.
Once you have that value, and I'm picking \$I_{\text{E}_\text{MIN}}=500\:\text{mA}\$, you can work out that the quiescent emitter voltage needs to be \$V_{\text{E}_\text{Q}}\ge R_\text{E}\left(I_\text{P}+I_{\text{E}_\text{MIN}}\right)+V_\text{P}\$. In your case, this means \$V_{\text{E}_\text{Q}}\ge 14.83\:\text{V}\$. I'm picking \$V_{\text{E}_\text{Q}}= 15\:\text{V}\$. (Your BJT's base will have to be driven with a quiescent voltage that is one \$V_\text{BE}\$ higher.)
(You could skip the steps shown above and simply compute \$V_{\text{E}_\text{Q}}\ge \frac{3}{2}V_\text{P}\left(1+\frac{R_\text{E}}{R_\text{SPKR}}\right)\$ and get the same answer. Note that the larger the ratio of \$\frac{R_\text{E}}{R_\text{SPKR}}\$ the higher the quiescent emitter voltage needs to be.)
The BJT's collector voltage should be at least \$2\:\text{V}\$ higher than the quiescent voltage plus the peak. So that tells you the rail you'll need, at minimum.

Just did a quick run on the basis of above analysis, except that I didn't bother working out the \$V_\text{BE}\$ for the BJT. I just set the DC bias for the input signal as shown. Close enough.

Spice reports the power in the speaker at \$1.0043\:\text{W}\$ and the RMS voltage across the speaker as \$V_\text{SPKR}=2.0043\:\text{V}_\text{RMS}\$. Not bad for shooting from the hip, so to speak.
Sadly, Spice also reports that the power for the BJT here is about \$3.9\:\text{W}\$ and for \$R_\text{E}\$ is \$20.7\:\text{W}\$. This ignores all the driver stuff that would normally have to back up this output section and would only increase the power dissipation. But in round numbers this means burning off about \$25\:\text{W}\$ in a circuit that will deliver \$1\:\text{W}\$ to the speaker. (Which is a good thing, I suppose, if you own a lot of stock with your local power company. You'll get some of your cost back in dividends.)

My question is: is there a process for determining a value for R2 that
  can meet the objective of driving 1 watt into the speaker, or is this
  just a waste of time?

You can work this backwards. Given that your \$V_\text{CC}=12\:\text{V}\$, then find that \$R_\text{E}\le 2.5\:\Omega\$. (From: \$R_\text{E}\le R_\text{SPKR}\left(\frac{2}{3}\frac{V_\text{CC}-V_\text{P}-2\:\text{V}}{V_\text{P}}-1\right)\$.)

FINAL NOTES
Here is an LTspice schematic that can be used to program up and test out any particular crazy-minded class-A amplifier of this kind. I've used a particular BJT in it that can handle some current -- but feel free to change it. Other than that, the specs are hopefully clear. Make some changes and run it.
Aside from setting up the desired power and load values, only one of the two -- either \$R_\text{E}\$ or else V_\text{CC}\$ -- can be set, as the other one is then determined by that choice. So set exactly one of them, not both. The other must be set to zero.

The .ASC file follows here to save time having to write up the above schematic, by hand.
Version 4
SHEET 1 880 680
WIRE 96 80 96 48
WIRE 32 128 -32 128
WIRE -32 160 -32 128
WIRE 96 192 96 176
WIRE 176 192 96 192
WIRE 288 192 240 192
WIRE 96 224 96 192
WIRE 288 224 288 192
WIRE -32 272 -32 240
WIRE 96 336 96 304
WIRE 288 336 288 304
FLAG 96 336 0
FLAG 288 336 0
FLAG 96 48 Vcc
FLAG -32 272 0
FLAG 288 192 Vspkr
SYMBOL npn2 32 80 R0
SYMATTR InstName Q1
SYMATTR Value D44H11
SYMBOL res 80 208 R0
SYMATTR InstName RE
SYMATTR Value {REV}
SYMBOL cap 240 176 R90
WINDOW 0 0 32 VBottom 2
WINDOW 3 32 32 VTop 2
SYMATTR InstName C1
SYMATTR Value {CV}
SYMBOL res 272 208 R0
SYMATTR InstName Rspkr
SYMATTR Value {LOAD}
SYMBOL voltage -32 144 M0
WINDOW 123 0 0 Left 2
WINDOW 39 0 0 Left 2
SYMATTR InstName V1
SYMATTR Value SINE({VQ+.7} {VPEAK} 1k)
TEXT 152 32 Left 2 !V99 Vcc 0 {VCCV}
TEXT 152 56 Left 2 !.tran 0 .1 0 100n
TEXT -392 -112 Left 2 !* INPUT SPECIFICATIONS\n.param POWER={1}\n.param LOAD={4}\n.param FMIN={200}
TEXT -392 376 Left 2 !* INTERMEDIATE CALCULATIONS\n.param VPEAK={sqrt(2*POWER*LOAD)}\n.param VQ=if({RE+.5},{3/2*VPEAK*(1+RE/LOAD)},{VCC-VPEAK-2})\n.param REV={LOAD*(2/3*VQ/VPEAK-1)}\n.param VCCV={VQ+VPEAK+2}\n.param CV={5/pi/FMIN/LOAD}
TEXT 48 -112 Left 2 !* SET ONLY ONE OF THESE TO NON-ZERO VALUE\n.param RE={0}\n.param VCC={20}
TEXT -232 -184 Left 2 ;CRAZY-MINDED CLASS-A OUTPUT STAGE AMPLIFIER


text:
Q: XML serialization with boost (left of '.serialize' must have class/struct/union) I have the two classes BaseTolerance and ImageProcessingTask. I get the error Message: 'error C2228: left of '.serialize' must have class/struct/union'.
If the line (in ImageProcessingTask)
        ar & make_nvp("ToleranceToMeasure", tolerance_to_measure_);

is commented out, the error message disappears.
#include <boost/archive/xml_oarchive.hpp>

class BaseTolerance
{
private:
    friend class boost::serialization::access;

template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
    using boost::serialization::make_nvp;
    ar & make_nvp("ToleranceName", tolerance_name_);
}

    char* tolerance_name_;
    public:
    BaseTolerance();
    ~BaseTolerance();

    char* GetToleranceName();
    void SetToleranceName(char* name);
};

and
#include "GeometricTolerance.h"

class ImageProcessingTask
{
    BaseTolerance *tolerance_to_measure_;

    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        using boost::serialization::make_nvp;
        ar & make_nvp("ToleranceToMeasure", tolerance_to_measure_);
    }
public:
    ImageProcessingTask();
    ~ImageProcessingTask();

    BaseTolerance *GetToleranceToMeasure();
    void SetToleranceToMeasure(BaseTolerance *tolerance);
};

A: The error actually came from trying to serialize char*, once i saw that, i switched to std::string, as proposed in Direct boost serialization to char array


text:
Q: Can't there be more than one fixed points in a contraction? or none? I was going through the contraction mapping theorem in my book where it says, that if $\phi: G\to G$ is a contraction, then $\phi$ has a unique fixed point $\alpha$ on $G$.
Sequence {$x_n$}, $x_{n+1} = \phi(x_n) $ for $n=0,1,2...$ converges to $\alpha$ with
$$|x_n - \alpha |\leq\frac{\lambda^n }{1- \lambda} |x_1 - x_0|  $$ for n=1,2,3,4....
Can a contraction have only a unique fixed point? Cannot there be multiple fixed points? Like this?

Or cannot it have any fixed points at all?

A: Yes, a contraction has a unique fixed point.  Proof:  Let $d(\cdot,\cdot)$ be our distance function (which is absolute value on the real numbers, but works in more general settings).
Assume $\phi$ is a contraction and $a,b$ are both fixed points.  Let $0<k<1$ be our contraction constant. Then $d(g(a),g(b))<k\cdot d(a,b)$,  since it's a contraction,  but $g(a)=a,g(b)=b$,  so $d(g(a),g(b))=d(a,b)$,  hence $d(a,b)<k\cdot d(a,b)$, which is only possible if $d(a,b)=0$,  hence $a=b$.

A: If you have two fixed points $a,b$, you have $\phi(a)=a, \phi(b)=b$, so $|\phi(a)-\phi(b)|=|a-b|$, violating the requirement of a contraction that $|\phi(a)-\phi(b)| \lt |a-b|$

A: If $a'$ and $a$ are fixed points, then $d(f(a'),f(a))=d(a',a)<\lambda d(a',a)$ with $0<\lambda <1$, which implies that $d(a,a')=0$ and hence $a=a'$.

A: A contraction mapping can never have more than one fixed point: if $a,b$ are both fixed points, then $d(a,b)=d(f(a),f(b))\leq \lambda d(a,b)$. This is only possible if $d(a,b)=0$.
On the other hand, by Banach fixed-point theorem, any contraction mapping of a complete metric space into itself has a fixed point. The proof is fairly straightforward: for any $x$, successive applications of the contraction to $x$ yield a Cauchy sequence, which converges by completeness, and by continuity the limit must be a fixed point.
The hypothesis of completeness is necessary, for example consider the map $x\mapsto x/2$ on $(0,1)$ with standard metric. It is a contraction mapping without any fixed points. Of course, there is a fixed point in the completion, namely $0$.

A: You seem to be a bit confused about how to think of a contraction as a line on a graph.  Let's assume that we are looking for a contraction on $[0,1]$, though we could use any complete subset of the reals (or even the real line itself.
Intuitively, we have:

*

*The line $y=x$ plotted on $[0,1]$ (so $x,y\in[0,1]$).

Then a curve corresponding to a contraction is one such that:

*

*The curve corresponds to a function $y=f(x)$ for $0\le x\le1$.

*The curve's $x$ and $y$ values never leave the square $[0,1]\times[0,1]$ - in other words, we always have $0\le x\le1,0\le y\le1$.

*The slope of the curve is bounded above by some fixed constant $\lambda<1$.

Then the curve has a unique intersection with $y=x$; i.e., there is a unique point such that $x=f(x)$.  For example:

Of course, we don't require the curve to be differentiable in general, so it might not always make sense to talk about the 'slope' of the curve, but that's what you should have in mind.
Your curves don't count as contraction mappings - the first one has slope greater than $1$ at some points, and the second leaves the square given by $0\le x\le1,0\le y\le1$, which is not allowed


text:
Q: Pyspark SQL: How to make a new value that comes from a value of column plus another column name? I'm trying to get a new value that comes from a value of column plus another column name.
For instance, given this:
+----+---+----+----+
|base|  1|   2|   3|
+----+---+----+----+
|  10| AA|  aa|  Aa|
|  20| BB|  bb|  Bb|
|  30| CC|  cc|  Cc|
+----+---+----+----+

I'd like to get this:

          +---------+----+
          | new_base|   v|
          +---------+----+
10 + 1 -> |       11|  AA|
10 + 2 -> |       12|  aa|
10 + 3 -> |       13|  Aa|
20 + 1 -> |       21|  BB|
20 + 2 -> |       22|  bb|
20 + 3 -> |       23|  Bb|
30 + 1 -> |       31|  CC|
30 + 2 -> |       32|  cc|
30 + 3 -> |       33|  Cc|
          +---------+----+

NOTE: I'm coding in Spark 2.4

A: We can use explodefunction to solve it.
# Importing requisite functions.
from pyspark.sql.functions import array, col, explode, struct, lit

# Creating the DataFrame
df = sqlContext.createDataFrame([(10,'AA','aa','Aa'),(20,'BB','bb','Bb'),(30,'CC','cc','Cc')],['base','1','2','3'])
df.show()
+----+---+---+---+
|base|  1|  2|  3|
+----+---+---+---+
|  10| AA| aa| Aa|
|  20| BB| bb| Bb|
|  30| CC| cc| Cc|
+----+---+---+---+

Writing a function to explode the DataFrame.
def to_explode(df, by):

    # Filter dtypes and split into column names and type description
    cols, dtypes = zip(*((c, t) for (c, t) in df.dtypes if c not in by))
    # Spark SQL supports only homogeneous columns
    assert len(set(dtypes)) == 1, "All columns have to be of the same type"

    # Create and explode an array of (column_name, column_value) structs
    kvs = explode(array([
      struct(lit(c).alias("key"), col(c).alias("val")) for c in cols
    ])).alias("kvs")

    return df.select(by + [kvs]).select(by + ["kvs.key", "kvs.val"])

Applying the function below. Since the created column new_base has a decimal, as by default it was of type double, so we explicitly convert it to integer to avoid having every number suffixed by .0
df = to_explode(df, ['base'])
df = df.withColumn('new_base',col('base')+col('key'))\
       .select(col('new_base').cast(IntegerType()),'val')
df.show()
+--------+---+
|new_base|val|
+--------+---+
|      11| AA|
|      12| aa|
|      13| Aa|
|      21| BB|
|      22| bb|
|      23| Bb|
|      31| CC|
|      32| cc|
|      33| Cc|
+--------+---+
df.printSchema()
root
 |-- new_base: integer (nullable = true)
 |-- val: string (nullable = true)

A: Another typical case using reduce function:
from functools import reduce
from pyspark.sql.functions import col

cols = df.columns[1:]

df_new = reduce(lambda d1,d2: d1.union(d2),
    [ df.select((col('base') + int(c)).astype('int').alias('new_base'), col(c).alias('v')) for c in cols ]
)

df_new.show()
+--------+---+
|new_base|  v|
+--------+---+
|      11| AA|
|      21| BB|
|      31| CC|
|      12| aa|
|      22| bb|
|      32| cc|
|      13| Aa|
|      23| Bb|
|      33| Cc|
+--------+---+


text:
Q: Asymptotic approximation of Fisher information matrix for small Gaussian perturbation Let
$$
X=Y/a+b+\epsilon Z,
$$
where $Y\sim\operatorname{Poisson}(\lambda)$ and $Z\sim\mathcal N(0,1)$ are independent.  Also define $\theta=(\lambda,a,b,\epsilon)$. The Fisher information matrix
$$
I_X(\theta)=-\mathsf E(\nabla_\theta^2\log f_X(X|\theta))
$$
is very complicated; however, the joint information
$$
I_{X,Y}(\theta)=-\mathsf E(\nabla_\theta^2\log f_{X,Y}(X,Y|\theta))
$$
is very simple.  Comparing numerical calculations of the incomplete-data information $I_X$ to the explicit expression for the complete-data information $I_{X,Y}$ shows that $I_{X,Y}$ provides an excellent approximation to $I_X$ as $\epsilon$ becomes small.
Can it be shown that
$$
I_X(\theta)\sim I_{X,Y}(\theta)=\begin{bmatrix}
\frac{1}{\lambda } & 0 & 0 & 0 \\
 0 & \frac{\lambda ^2+\lambda }{a^4 \epsilon ^2} &
   -\frac{\lambda }{a^2 \epsilon ^2} & 0 \\
 0 & -\frac{\lambda }{a^2 \epsilon ^2} & \frac{1}{\epsilon ^2}
   & 0 \\
 0 & 0 & 0 & \frac{2}{\epsilon ^2} \\
\end{bmatrix}
$$
as $\epsilon\to 0^+$?
We have by the properties of logarithms the chain rule for information
$$
I_X(\theta)=I_{X,Y}(\theta)-I_{Y|X}(\theta),
$$
so this would amount to showing $I_{Y|X}$ is negligible in comparison to $I_{X,Y}$ for small $\epsilon$.

Additional Information:
The density for $X$ can be expressed by integrating the joint density $f_{X,Y}(x,y)$ over the (discrete) variable $Y$ yielding
$$
f_X(x|\theta)=\sum_{k=0}^\infty\underbrace{\frac{e^{-\lambda}\lambda^k}{k!}\phi(x;b+k/a,\epsilon^2)}_{f_{X,Y}(x,k|\theta)}.
$$
Here, $\phi$ is the Gaussian probability density parameterized in terms of mean and variance.
The characteristic function of $X$ is also quite simple and inverting the characteristic function yields (after a few applications of Euler's identity)
$$
f_X(x|\theta)=\frac{1}{\pi}\int_0^\infty\exp(\lambda(\cos(t/a)-1)-\epsilon^2t^2/2)\cos((b-x)t+\lambda\sin(t/a))\,\mathrm dt.
$$
As we can see, no simplification occurs when considering the log of the density function for $X$. When evaluating $[I_X(\theta)]_{i,j}-\mathsf E(\partial_{\theta_i}\partial_{\theta_j}\log f_X(X|\theta_1,\theta_2,\theta_3,\theta_4))$, when inevitably end up with an integral containing a term with $f_X$ in the denominator, which is intractable.


text:
Q: Memory-efficient way to truncate large array in Matlab I have a large (multi-GB) array in Matlab, that I want to truncate¹.  Naively, I thought that truncating can't need much memory, but then I realised that it probably can:
>> Z = zeros(628000000, 1, 'single');
>> Z(364000000:end) = [];
Out of memory. Type HELP MEMORY for your options.

Unless Matlab does some clever optimisations, before truncating Z, this code actually creates an array (of type double!) 364000000:628000000.  I don't need this array, so I can do instead:
>> Z = Z(1:363999999);

In this case, the second example works, and is fine for my purpose.  But why does it work?  If Z(364000000:end) = 0 fails due to the memory needed for the intermediate array 364000000:628000000, then why does not Z = Z(1:363999999) fail due to the memory needed for the intermediate array 1:363999999, that is larger?  Of course, I don't need this intermediate array, and would be happy with either a solution that truncates my array without having any intermediate array, or, failing that, if Matlab optimises a particular method.

*

*Is there any way to truncate an array without creating an intermediate indexing array?

*If not, is either of the aforementioned methods more memory-efficient than the other (it appears ot is)?  If so, why?  Does Matlab really create intermediate arrays in both examples?

¹Reason: I'm processing data but don't know how much to preallocate.  I make an educated guess, often I'm allocating too much.  I choose chunk size based on available memory, because splitting in fewer chunks means faster code.  So I want to avoid any needless memory usage.  See also this post on allocating by chunk.

A: I ran both examples on a machine with 24GB of RAM with profile('-memory','on');.  This profiler option will show memory allocated and freed on each line of code.  These are supposed to be gross not net amounts. I checked with a simple function that has net 0 free and alloc and it reported the gross amounts. However, it seems likely that builtin commands with no .m code to back them do not give fine-grained memory reporting to the profiler.
I ran a couple tests for the following code:
% truncTest.m
N = 628000000;
M = 364000000;

clear Z
Z = zeros(N,1,'single');
Z(M:end) = [];
Z(1) % just because

clear Z
Z = zeros(N,1,'single');
Z = Z(1:M);
Z(1)

For what they are worth, the memory profiling results for this N and M are:

Well, both lines look the same in terms of memory allocated and freed.  Maybe that's not the whole truth.
So, out of curiosity I decreased M to 200 (just 200!) without changing N, did profile clear and reran.  Profiling claims:

Interestingly, Z=Z(1:M); is practically instantaneous now, and Z(M:end)=[]; is a little faster. Both free about 2.4GB of memory, as expected.
Finally, if we go the other direction and set M=600000000;:

Now even Z=Z(1:M); is slow, but about twice as fast as Z(M:end)=[];.
This suggests:

*

*Z=Z(1:M); just grabs the indicated elements, stores them in a new buffer or temporary variable, releases the old buffer and assigns the new/temporary to the array Z. I was able to make my weaker 4GB machine go from 2.45 seconds to thrashing the page file for 5 minutes just by increasing M and leaving N alone. Definitely prefer this option for small M/N, probably in all cases.

*Z(M:end)=[]; always rewrites the buffer, and execution time increases with M too.  Actually always slower, and seems to increase exponentially, unlike Z=Z(1:M);.

*Memory profiling does not give fine-grained information about these builtin operations and should not be misinterpreted as giving a total of memory freed and allocated over the commands execution, but rather a net change.

UPDATE 1: Just for fun I timed the tests at a range of values of M:

Clearly more informative than the profiling.  Both methods are not no-ops, but Z=Z(1:M); is fastest, but it can use almost double the memory of Z for M/N near 1.
UPDATE 2:
A relatively unknown feature called mtic (and mtoc) were available in 32-bit Windows prior to R2008b.  I still have it installed on one machine, so I decided to see if that provides any more insight, with the understanding that (a) much has changed since then and (b) it's a completely different memory manager used in 32-bit MATLAB.  Still, I reduced the test size to N=128000000; M=101000000; and had a look. First, feature mtic for Z=Z(1:M-1);
>> tic; feature mtic; Z=Z(1:M-1); feature mtoc, toc

ans =

      TotalAllocated: 808011592
          TotalFreed: 916009628
    LargestAllocated: 403999996
           NumAllocs: 86
            NumFrees: 77
                Peak: 808002024

Elapsed time is 0.951283 seconds.

Clearing up, recreating Z, the other way:
>> tic; feature mtic; Z(M:end) = []; feature mtoc, toc

ans =

      TotalAllocated: 1428019588
          TotalFreed: 1536018372
    LargestAllocated: 512000000
           NumAllocs: 164
            NumFrees: 157
                Peak: 1320001404

Elapsed time is 4.533953 seconds.

In every metric (TotalAllocated, TotalFreed, NumAllocs, etc.), Z(M:end) = []; is less efficient than Z=Z(1:M-1);.  I expect it is possible to discern what is going on in memory by examining these numbers for these values of N and M, but we'd be guessing about an old MATLAB


text:
Q: .htaccess pretty URLs are not working I'm trying to use pretty URLs on my site, and I don't know too much about htaccess, but after some search I ended up with this:
RewriteEngine On
RewriteRule ^([a-z]+)\/([0-9]+)\/?$ content.php?action=$1&id=$2 [NC]

I'm trying to change this:

mysite.com/cms/content.php?action=content&id=80

into:

mysite.com/cms/content/80

But somehow it's not working and what I get is a blank screen and a 404 error,
Failed to load resource: the server responded with a status of 404 (Not Found) --in-- /cms/files/plugin/tinymce/tinymce.min.js

About the 404 error: It should load a .js file from mystie.com/files/plugin/tinymce/tinymce.min.js -- not -- mystie.com/cms/files/plugin/tinymce/tinymce.min.js
My htaccess file is in the root folder. Am I doing something wrong?
I think the server did not read my .htaccess file. How do I find out the issue?

A: You have /cms/ in your URL before the rest, so you need to change RewriteRule to something like this:
RewriteRule ^cms/([a-z]+)\/([0-9]+)\/?$ content.php?action=$1&id=$2 [NC]

Also, I hope you are aware that .htaccess can not work on some servers (like nginx or some custom ones), and even on Apache servers there can be mod_rewrite disabled.

A: RewriteEngine On
RewriteRule ^/cms/([a-z]+)/([0-9]+)$ content.php?action=$1&id=$2 [NC]

Remove escape slashes \

A: My guess is that your scripts and styles are being linked to via relative URLs. Because the old URL is /cms/content.php the URI base is /cms/ and your relative links all resolved to be under /cms/, which I assume is what you want.
However, when you change your links to /cms/content/1234, the URI base becomes /cms/content/ and all relative links will use this as its base, and since "content" isn't even a real folder, all those links will 404, and you won't load any of your CSS content or scripts.
Either change your links to absolute URLs or specify a URI base in the header of your pages (inside the <head> </head> tags):
<base href="/cms/" />

A: You need to place this rule in /cms/.htaccess:
RewriteEngine On
RewriteBase /cms/

RewriteRule ^([a-z]+)/([0-9]+)/?$ content.php?action=$1&id=$2 [NC,L,QSA]

Then you need add this in the <head> section of your page's HTML: <base href="/" /> so that every relative URL is resolved from that URL and not the current page's relative URL.

A: You need to make sure to include the subfolder if your htaccess is in the root.
Try this rule.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^cms/([a-z]+)/([0-9]+)/?$ /cms/content.php?action=$1&id=$2 [NC,L]

Also a blank screen usually means a PHP error.


text:
Q: C# foreach in List - for removing elements I feel stupid for asking this but I am struggling to quite understand foreach. Say for example that I am making a book repository app, with a Book class as well as an Inventory class. The Inventory class has a removeBook method that removes a book from the inventory. The parameter for the method would be an int bookID. I am thinking I should use foreach to accomplish this. I understand the most basic use of foreach but I can not figure out how to use it to basically select a specific bookID that is a parameter in the method. Could someone help point me in the right direction?
Here's a code snippet, I know the method is wrong:
List<Book> Books = new List<Book>
{
    new Book{ bookID = 5, Name = "Moby Dick", Price = 20.00 },
    new Book{ bookID = 2, Name = "50 Shades of Grey", Price = 0.99 }
};

public void removeBook(int bookID)
{
    foreach (var bookID in Books)
    {
        Products.Remove(book);
    }
}

A: So if you want to remove a book from a list you would not necessarily use a foreach loop. Simplest way would be to use the RemoveAll function on List.
public void RemoveBook(int bookId) =>
    Books.RemoveAll(book => book.Id == bookId);

A: Removing a thing from a collection isn't what foreach is for - it's for performing some operation on every value in the collection. If you want to remove a book with a specific id, you could use a regular for loop:
// in Inventory class having List<Book> Books,
// assuming Book has a public int Id property
public void RemoveBook(int bookId) {
    for (int i = 0; i < this.Books.Count; i++) {
        if (this.Books[i].Id == bookId) {
            this.Books.RemoveAt(i);
            return;
        }
    }
}

If there are any duplicates for some reason (there shouldn't be - IDs should be unique) and you wanted to remove all books with given ID, this code should do it:
public void RemoveBooks(int bookId) {
    // iterating from the end of the array
    // to prevent skipping over items
    for (int i = this.Books.Count - 1; i >= 0; i--) {
        if (this.Books[i].Id == bookId) {
            this.Books.RemoveAt(i);
        }
    }
}

EDIT: fixed the code, thanks to Gerardo Grignoli

A: foreach wont work if you are iterating over the same list so use for loop or linq instead
MSDN

The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.

private void RemoveBookFromInventory(int bookID)
{
    foreach(Books book in listOfBooks)
    {
         if(book.bookID == bookID)
         {
            listOfBooks.Remove(book); //wont work
         }
    }

    for(int i=0;i<listOfBooks.Count();i++)
    {
        if (listOfBooks[i].bookID == bookID)
            listOfBooks.Remove(listOfBooks[i]);
    }
}

A: If you have
List<Thing> things = ....

Then in a foreach like this
foreach (Thing theThing in things)
{
   // do something with "theThing"
}

the foreach loops through all items in the things list and executes that block of code (between the { }) for each consecutive value, which is stored in the theThing variable (and is of type Thing).
You can replace Thing theThing with var theThing, for the exact same result.

A: As others have implied, you can't really change the contents of a list while iterating through it with a for loop, as that would change the data structure you are working on.
There are several other ways to solve this though. I personally like solutions in this style, where you fetch the index of the book first, and then remove it in a separate step afterwards:
var bookID = 2;

int? index = Books
              // Generate a list of book- and position- pairs:
              .Select((book, pos) => new {book, pos})
              // First matching pair (or null):
              .FirstOrDefault(set => set.book.bookID == bookID)?
              // If NULL was not returned, get the index property:
              .pos;

// Removal is only attempted if a matching book was found:
if(index.HasValue){
    Books.RemoveAt(index.Value);
}


text:
Q: React: Unexpected token return I am new to React and I have this following code:
render() {
        return (

                <form>
                    <input type="text" name="texte" value={this.state.value} onChange={this.handleChange} />
                    <input type="submit" value="Valider" onClick={this.update} />
                </form>
                var list = this.state.liste.map(function(elt) {
                    return
{elt}

                });

{list}

        );
    }

I have a syntax error:
Unexpected token return
{elt}

                 ^

I don't understand why...
Thanks for any help!

A: Restructure your code like this:
render() {

var list = this.state.liste.map(function(elt) {
                    return
{elt}

                });
        return (

                <form>
                    <input type="text" name="texte" value={this.state.value} onChange={this.handleChange} />
                    <input type="submit" value="Valider" onClick={this.update} />
                </form>

{list}

        );
    }

or
render() {
        return (

                <form>
                    <input type="text" name="texte" value={this.state.value} onChange={this.handleChange} />
                    <input type="submit" value="Valider" onClick={this.update} />
                </form>

{this.state.liste.map(function(elt) {
                    return
{elt}

                });}

        );
    }

You can't add code inside the JSX syntax without {}


text:
Q: Installing php5 package with Ubuntu - which PHP version? I have a Ubuntu server running apache2 and have installed php5 with
apt-get install php5 php-pear

and some other packages packages; php5-mysql, for example.
I'm a little confused as to which version of PHP the Ubuntu php5 package ships with. I'd like to be running the latest version of PHP at all times (currently 5.4.15). If I compile PHP from source on my server would that cause issues updating down the line? What's the best option here? Also, any tutorials for how to compile PHP, as I'm not 100% sure what I'm doing! But I'd like to give it a go.
I'm running Ubuntu 13.04 raring.
I'm new to sysadmin and server management, so it's more than likely I've missed a key piece of the puzzle here.
Any help greatly appreciated, Thanks!

A: apt-get install php5 installs  php version 5.4.6-1ubuntu1.2
you can check your php version with php -v
running whatever ships with the repository is normally fine for me, exceptions to this would be if there are severe or critical security holes found in php or there is a new feature that you MUST have the moment it gets released.
but if you really want to, you can keep track with the latest or even have multiple versions of php on your machine. It is possible and it wont destroy your set up, you just have to jump through a few more hoops. more info on multiple php installations here
Now, back to compiling php, you can go here for instructions. Though a bit old, they should still work. But you should also probably take a look at this.


text:
Q: Pass props to image url but also use objectFit React newbie here,
I want to pass image url as props for backGround image but also want to apply css on image to "fill".
I got how to pass for inline css
 style={{ backgroundImage: "url(" + props.imgURL + ")" }}

I dunno how to apply css for this. I want to apply objectFit:fill
maybe
style={{ backgroundImage: "url(" + props.img + ")"  objectFit="fill"}}lol
(OR IS THERE A WAY TO PASS PROPS TO STYLESHEET. )
{HELP}

A: Try this bud
style={{backgroundImage: `url(${props.imgURL})`}}

I'd try and steer away from inline styling if possible, the only time I would ever use it is for background images, just target the element in CSS to add the object-fit property :)
Also for future reference, this is a template literal. You can find a more info on it from MDN here

A: Because you're dealing with an object you need to separate key-value pairs with a comma. The other problem is that object-fit doesn't work if you use the backgroundImage style property to set the image instead of using src. So I recommend using backgroundSize: 'contain' instead.
<img
  style={{
    backgroundImage: `url(${imgUrl})`,
    backgroundSize: 'contain',
  }}
  width="400"
  height="400"
/>

The image needs to have a width and height. Change my example to fit your needs.


text:
Q: Check if a datetime field is equal to Date.today I'm trying to check if an assignment's due_date (datetime data type) is equal to Date.today. The logic I need help with is the 'due_date: Date.today' section. Thanks in advance.
@student_assignments = StudentAssignment.joins(:assignment).where(assignments: { due_date: Date.today })

A: .where("DATE(assignments.due_date) = ?", Date.today)

A: Here is a possible solution :
{ due_date: (Date.today.beginning_of_day..Date.today.end_of_day) }

A: To compare with a datetime column you need to have a DateTime object. However if you compare a for equity with DateTime.now.beginning_of_day it will only match assignments with are due at 00:00.
Instead if you want assigments that are due today you could do:
StudentAssignment.joins(:assignment)
         .where(assignments: {
            due_date: DateTime.now.beginning_of_day..DateTime.now.end_of_day
         })

You can create a named scope:
class Assignment < ActiveRecord::Base
  scope(:due_today) -> {
    where(due_date:DateTime.now.beginning_of_day..DateTime.now.end_of_day )
  }
end


text:
Q: Is message property on Error propertyIsEnumerable? What is the correct result of the following? Do any of the ECMA standards specify this? My current Chrome 14.0.835.186m thinks false and Firefox 3.6.22 thinks true.
(new Error()).propertyIsEnumerable("message")

This is extra annoying because Chrome used to think true as well, and now I have broken code because of this change.

A: I can't find in the ECMAScript 5 spec where it is required either way (doesn't mean it isn't there), but it does appear to be configurable, so you can do this:
Object.defineProperty( Error.prototype,'message',{enumerable:true});

console.log( Error.prototype.propertyIsEnumerable('message') ); // true

or this:
var err = new Error('a message');

Object.defineProperty( err,'message',{enumerable:true});

console.log( err.propertyIsEnumerable("message") );  // true

A: propertyIsEnumerable doesn't return true for 'built-ins' like:
Error.prototype.message or Array.prototype.length
Enumerable properties are those set directly on the object itself as defined in section 15.2.4.7 of ECMA 262, which can be downloaded here
For example:
> var arr = [];
> arr.propertyIsEnumerable("length")
false
> arr.kudos = 55;
55
> arr.propertyIsEnumerable("kudos")
true
> var err = new Error("some message");
> err.propertyIsEnumerable("message")
false
> err.Something = { };
{}
> err.propertyIsEnumerable("Something")
true

the propertyIsEnumerable method is meant to determine what can be used in a for..in loop.
For example:
> for(var key in arr) { console.log(key); }
kudos
> for(var key in err) { console.log(key); }
Something

Are you using propertyIsEnumerable instead of hasOwnProperty?
> err.hasOwnProperty("message")
true
> arr.hasOwnProperty("length")
true

Here are some other examples: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable
My assumption for the reason these used to work is that these browsers are ramping up for ECMAScript 5 compliance.
Edit:
If you need all properties including non-enumerable properties, you can use Object.getOwnPropertyNames(obj).  Here's an example that copies non-enumerable properties to another object.
> var err = new Error("Some message");
> var copy = { };
> Object.getOwnPropertyNames(err).forEach(function(key) {
... copy[key] = err[key];
... });
> copy
{ stack: 'Error: Some message\n    at repl:1:11\n    at Interface.<anonymous> (r
epl.js:168:22)\n    at Interface.emit (events.js:67:17)\n    at Interface._onLin
e (readline.js:153:10)\n    at Interface._line (readline.js:408:8)\n    at Inter
face._ttyWrite (readline.js:585:14)\n    at ReadStream.<anonymous> (readline.js:
73:12)\n    at ReadStream.emit (events.js:70:17)\n    at onKeypress (tty_win32.j
s:46:10)',
  message: 'Some message',
  arguments: undefined,
  type: undefined }
> copy instanceof Error
false
> err instanceof Error
true

See here: https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects#section_2

A: The correct result is false because the message property of Error is inherited (I think from the prototype).


text:
Q: Top record per each foreign key in MySQL I have a table in MySQL which has following columns
Table - Reviews
Review_Id
Business_Id
Title
Description
Useful_Count

A particular business_id (foreign key) can have many reviews. What I want is to extract this information from DB given a set of business Ids

*

*Total review count for each business Id

*The top review (title and description mainly) for each business Id (Top review would be the one having highest number of useful_counts.

Is it possible to get both the information using a single SQL query?

A: *

*select count(business Id) as total from reviews group by business Id

A: Try this:
SELECT r.Business_Id, t.c AS 'Number of Reviews',
    r.Title, r.Description, t.max_useful_count
FROM Reviews r
JOIN (SELECT Business_Id, COUNT(Business_Id) AS c,
        MAX(Useful_Count) AS max_useful_count
      FROM Reviews
      WHERE r.Business_Id IN (...)
      GROUP BY Business_Id) as t
  ON r.Business_Id = t.Business_Id
  AND r.Useful_Count = t.max_useful_count


text:
Q: javascript sort key value pair on frequency in different array I would like to store product information in a key, value array, with the key being the unique product url. Then I would also like to store the visit frequency of each of these products. I will store these objects as window.localStorage items, but that's not very important.
The thing I had in mind was two key value arrays:
//product information
prods["url"] = ["name:product_x,type:category_x,price:50"]
//product visits frequency
freq["url"] = [6]

Then I would like to sort these prods based on the frequency.
Is that possible?
Hope you guys can help! Thanks a lot

A: Well you seem to have made several strange choices for your data format/structure. But assuming the format of the "prod" is beyond your control but you can choose your data structure, here's one way to do it.
Rather than two objects both using url as a key and having one value field each I've made a single object still keyed on url but with the product and frequency information from each in a field.
Objects don't have any inherent order so rather than sorting the table object I sort the keys, your "url"s ordered by ascending frequency.
To show that it's sorted that way I print it out (not in the same format).
For descending frequency, change data[a].freq - data[b].freq to data[b].freq - data[a].freq

var data = {
  "url": {
    prod: "name:product_x,type:category_x,price:50",
    freq: 6
  },
  "url2": {
    prod: "name:product_y,type:category_y,price:25",
    freq: 3
  }
};

var sorted = Object.keys(data).sort((a, b) => data[a].freq - data[b].freq);

console.log(sorted.map(k => [data[k].freq, k, data[k].prod]));

There's more than one way to format the data, which would change the shape of the code here.

A: maybe something like this:
var prods = [
    {url:1, val:[{name:'a',type:'x',price:60}]},
    {url:2, val:[{name:'b',type:'x',price:30}]},
    {url:3, val:[{name:'c',type:'x',price:50}]},
    {url:4, val:[{name:'c',type:'x',price:20}]},
    {url:5, val:[{name:'c',type:'x',price:10}]},
    {url:6, val:[{name:'c',type:'x',price:40}]}
];

var freq = [
    {url:1, freq:6},
    {url:2, freq:3},
    {url:3, freq:5},
    {url:4, freq:2},
    {url:5, freq:1},
    {url:6, freq:4}
];

prods.sort(function (a, b) {
  var aU = freq.filter(function(obj) {
    return obj.url === a.url;
  });

  var bU = freq.filter(function(obj) {
    return obj.url === b.url;
  });

  if (aU[0].freq > bU[0].freq) {
    return 1;
  }
  if (aU[0].freq < bU[0].freq) {
    return -1;
  }

  return 0;
});


text:
Q: How do I refer to an object in a window whose Accessibility Inspector description is " (sheet) [NSPanel]" in Applescript? Image of my accessibility inspector
I am writing a script that will run a microsoft office installation DMG and click continue and so on and on until the program is installed. I have been successful in navigating the buttons I need to press until I reached the Agree button. Accessibility Inspector says " (sheet) [NSPanel]" when I click on this button. How can I refer to this object? is it possible at all?
tell application "Finder"
    set myFolder to container of (path to me) as alias
end tell

tell application "Finder"
    open document file "Microsoft_Office_16.16.19021001_Installer.pkg" of myFolder
end tell
if application "Installer" is running then
    tell application "Installer"
        activate
    end tell
    tell application "System Events"
        tell process "Installer"
            click button "Continue" of window "Install Microsoft Office for Mac"
            click button "Continue" of window "Install Microsoft Office for Mac"
            click button "Agree" outline "" of window "Install Microsoft Office for Mac"
        end tell
    end tell
end if

Image of my accessibility inspector


text:
Q: Can I call a 'normal' static method from an Async API Controller method relatively new to WebAPI and Async so please bear with me....
I have a WebAPI application with a number of operations in it.  Essentially, these call SQL Server stored procedures.
It has been working fine, but I am looking to make it more efficient and robust by converting the methods to be Async.
Let me show one methed - as they are all similar....
OLD Version
[System.Web.Http.HttpGet]
public A_Class MyAPIMethod(Guid b)
{
    using (SqlConnection DB = new SqlConnection(this.dbConnString))
    {
        return MyStaticHelper.A_Static_Method(DB, b);
    }
}

New Version (Async I think & hope)
[System.Web.Http.HttpGet]
public async Task<A_Class> MyAPIMethodAsync(Guid b)
{
    var db = new SqlConnection(this.dbConnString);
    try
    {
        var Result = await Task.Run(() => MyStaticHelper.A_Static_Method(db, b));
        return Result;
    }
    finally
    {
        db.Dispose();
    }
}

I think that bit is OK - I am just not sure what, if anything I need to do to my static helper method.
Do I need to convert that to be Async?
I have made calls to this and it all seems to work OK - I could just do with a sanity check please.
Any advise appreciated....
Static Helper Method....
public static A_Class A_Static_Method(SqlConnection dbConn, Guid A_Param)
{
    SqlDataReader reader = null;
    try
    {
        try
        {
            if (dbConn.State != ConnectionState.Closed) dbConn.Close();

            using (var cmd = new SqlCommand("MyStoredProc", dbConn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@sp_Param", SqlDbType.UniqueIdentifier).Value = A_PAram

                dbConn.Open();
                reader = cmd.ExecuteReader();

                var A_Class = StaticFunctionToGetInstanceOfClassFromResults( reader );
                A_Class.rc = 1;
                return A_Class
            }
        }
        catch (Exception)
        {
            //server error
            return new A_Class(A_ClassError.beApiError);
        }
    }
    finally
    {
        if (reader != null) reader.Close();
        dbConn.Close();
    }
}

A: No, the approach is wrong. In general, you should avoid Task.Run (and any other method that queues work to the thread pool) on ASP.NET.
Instead of starting from the controller and working "down", you should start at the lowest level and work up. That is, first examine your static method and determine if there are any naturally-asynchronous operations. These are generally I/O. Two jump immediately out to me: opening the database connection and retrieving results from a query (and it's likely that StaticFunctionToGetInstanceOfClassFromResults has more). You should call those with await first, and then allow async to grow naturally towards your controller (the compiler will guide you).
Also, as @StephenBrickner commented, you might want to take a step back and determine whether async will help you. I have an article on async ASP.NET that covers the primary considerations. In particular, if your backend won't scale (e.g., if it's a single SQL server instance, not something like Azure SQL), then there's (usually) no point in making your web server scale.

A:
var Result = await Task.Run(() => MyStaticHelper.A_Static_Method(db, b));

Passes work to a new thread. Releases the old thread. Waits on result in new thread. Now a thread can carry on where this left off.
This could be useful if you were running several such tasks simultaneously, but you're spending effort to relieve a thread by having a thread do stuff. That's all cost and no gain.
Where async wins is:

*

*You have more than one async operation at the same time.

*You have an async operation that is using asynchronous I/O so that the calling thread is released entirely.

The second is the more important, especially in web terms.
Let's consider your "helper" method first. There are calls in that that have truly async equivalents, and so we can create a truly async version:
public static async Task<A_Class> AStaticMethodAsync(SqlConnection dbConn, Guid A_Param)
{
  try
  {
    if (dbConn.State != ConnectionState.Closed) dbConn.Close();

    using (var cmd = new SqlCommand("MyStoredProc", dbConn))
    {
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.Add("@sp_Param", SqlDbType.UniqueIdentifier).Value = A_PAram

      await dbConn.OpenAsync();
      using(SqlDataReader reader = await cmd.ExecuteReader())
      {
        var A_Class = StaticFunctionToGetInstanceOfClassFromResults( reader );
        A_Class.rc = 1;
        return A_Class
      }
    }
  }
  catch (Exception)
  {
    //server error
    // Why are you wrapping an exception instead of just passing it up the stack? This is weird.
    return new A_Class(A_ClassError.beApiError);
  }
}

Two notes:

*

*I replaced your use of try…finally around the SqlDataReader with a more normal using.

*Presumably StaticFunctionToGetInstanceOfClassFromResults calls Read() on the datareader and then builds an object based on that. You could add an async version that calls await ReadAsync() and then use var A_Class = await StaticFunctionToGetInstanceOfClassFromResultsAsync(reader) here for even better asynchronous behaviour.

Now that we've an async method, your controller can be:
[System.Web.Http.HttpGet]
public async Task<A_Class> MyAPIMethodAsync(Guid b)
{
  using (SqlConnection DB = new SqlConnection(this.dbConnString))
  {
    return await MyStaticHelper.AStaticMethodAsync(DB, b);
  }
}

And it truly benefits from asynchronous behaviour.