Bash delete a file excluding under a directory or subdirectory containing certain name pattern

Question: The file structure:
|-- ./a
|   |-- ./a/b
|   |   `-- ./a/b/file.json
|   `-- ./a/file.json
|-- ./file.json
|-- ./folder
|   `-- ./folder/file.json
|-- ./guides
|   `-- ./guides/file.json
|-- ./network
|   |-- ./network/file.json
|   `-- ./network/guides
|       `-- ./network/guides/file.json
`-- ./script.sh

6 directories, 8 files

When running the script, it should delete file.json file from every directory excluding the one with a "guides" name.
So the output should give:
|-- ./a
|   `-- ./a/b
|-- ./file.json
|-- ./folder
|-- ./guides
|   `-- ./guides/file.json
|-- ./network
|   `-- ./network/guides
|       `-- ./network/guides/file.json
`-- ./script.sh

6 directories, 4 files

My attempt to write code:
for directory in $(find . -maxdepth 40 -type d)
do
    if [[ ${directory##*/} != "guides" && ${directory##*/} != "." ]]
    then
        find ${directory##*/} -name "*file.json" -type f -delete
    fi
done

INCORRECT output of my code:
|-- ./a
|   `-- ./a/b
|-- ./file.json
|-- ./folder
|-- ./guides
|   `-- ./guides/file.json
|-- ./network
|   `-- ./network/guides
`-- ./script.sh

6 directories, 3 files

However this code does not work as expected.
What's the fix?
EDIT:
./guides/network/file.json file.json in this path should also be deleted.
Comment: Should a file with a path like `./guides/network/file.json` (i.e. one where `guides` is not the immediate parent of the `file.json` file) be deleted?
Comment: [Shellcheck](https://www.shellcheck.net/) finds several problems with the code.
Comment: The fundamental problem is that the `network` directory is neither `guides` nor `.` so a recursive delete is done on it.  (Skipping the recursive delete on `network/guides` doesn't help.)
Comment: @pjh I haven't ran into `./guides/network/file.json` this scenario but if that would be the case of me wanting to delete file.json on such paths, how would the code look like?

Currently, dan's answer is closest and works fine but it does not cover above scenario I think.

Could you please comment the solution?
Answer: find . -type f -name file.json -not -path '*/guides/file.json' -exec rm -f {} +

-path is POSIX find, but it was added after 2004
* in a -path argument can match slashes
rm -v (logging) may be useful if your rm supports it

edit: find and delete all files named file.json, but do not descend any directory named guides:
find . -type d -name guides -prune \
    -o -type f -name file.json -exec rm -f {} +

If the file is a directory is called guides, we use -prune to not descend in to it.
Otherwise, test for a file named files.json, and remove it.
Comment: Thank you. I know this wasnt originally asked but if for the path, `./guides/network/file.json`, I want to delete file.json then?

Could you please add another command?
Comment: See the edit, I think that's what you're looking for.
Answer: Try
find . -type d -name guides -prune -o -type f -name file.json -exec rm -- {} +

See Delete all files except in a certain subdirectory with find for an explanation of why -exec rm ... has to be used instead of -delete.


Errors when trying to create new project or create new app in existing project

Question: On my server is Django 1.9, several months ago i updated it from Django 1.8. And everything works fine until i decided to create new app in existing project:
python manage.py startapp test123

Then i got an error:
/test123/tests.py already exists, overlaying a project or app into an existing directory won't replace conflicting files
So I tried to do this on another projects and still the same. Then I tried to create new project and install new app on it, but when i type this command:
django-admin.py startproject anyproject

I got this error:
CommandError: /var/www/anyproject/manage.py already exists, overlaying a project or app into an existing directory won't replace conflicting files
Then i type this command in the root of existing project:
django-admin runserver

End got error:
Traceback (most recent call last):
  File "/usr/local/bin/django-admin", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2749, in <module>
    working_set = WorkingSet._build_master()
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 446, in _build_master
    return cls._build_from_requirements(__requires__)
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 459, in _build_from_requirements
    dists = ws.resolve(reqs, Environment())
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 628, in resolve
    raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: Django==1.8.3

Then this command:
django-admin.py runserver

Then there was this error:
 File "/usr/local/bin/django-admin.py", line 5, in <module>
    management.execute_from_command_line()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 345, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 195, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 39, in load_command_class
    module = import_module('%s.management.commands.%s' % (app_name, name))
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 16, in <module>
    from django.db.migrations.executor import MigrationExecutor
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 7, in <module>
    from .loader import MigrationLoader
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 10, in <module>
    from django.db.migrations.recorder import MigrationRecorder
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 12, in <module>
    class MigrationRecorder(object):
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 26, in MigrationRecorder
    class Migration(models.Model):
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 27, in Migration
    app = models.CharField(max_length=255)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1072, in __init__
    super(CharField, self).__init__(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 166, in __init__
    self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 55, in __getattr__
    self._setup(name)
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 41, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

After that i uninstall all Django using pip, and then install again. But i still have this errors. Can anybody help me with it? Thanks
Answer: The command to start a new app is startapp, not startproject. startproject is, well, for starting a completely new project, with a new manage.py etc; obviously if you already have a project, you don't want to overwrite those files.
And to run the server - or do anything once the project has been created - you should always use manage.py (or pass the --settings parameter to django-admin, which is effectively what manage.py does).


How to use component on forms?

Question: I got a component from Xamarin's component store and It's available to Android and iOS...
How can I use this component on shared/portable project (forms)?
Or can I join a forms content with a ViewController? I can't understand this :X
I see something called "wrapper" but I don't remember where and I can't find it anymore!
This is my code:
1 -I create an interface in the shared/PCL project
namespace UsingDependencyService
{
    public interface IActionTray
    {
        void ActoinTrayBiulder ();
    }
}

2 - I implement the interface
[assembly: Xamarin.Forms.Dependency (typeof(ActionTray_iOS))]
namespace UsingDependencyService.iOS
{
    public class ActionTray_iOS : IActionTray
    {

        UIActionTray leftTray = new UIActionTray (UIScreen.MainScreen.Bounds);

        public ActionTray_iOS ()
        {
        }

        public void ActoinTrayBiulder ()
        {
            leftTray.trayType = UIActionTrayType.Draggable;
            leftTray.orientation = UIActionTrayOrientation.Left;
            leftTray.tabLocation = UIActionTrayTabLocation.BottomOrRight;
            leftTray.frameType = UIActionTrayFrameType.EdgeOnly;
            leftTray.tabType = UIActionTrayTabType.IconAndTitle;

            // Style tray
            leftTray.appearance.background = UIColor.LightGray;
            leftTray.appearance.frame = UIColor.DarkGray;
            //leftTray.icon=UIActionImage.FromFile ("Images/icon_calendar.png");
            leftTray.title = "Tab";
            leftTray.CloseTray (false);
        }
    }
}

3 - I tried to use it from the shared/PCL project:
    public class MainPage : ContentPage
    {
        public MainPage ()
        {

            DependencyService.Get<IActionTray> ().ActoinTrayBiulder ();

        }
    }
}

It's called...but it don't appear on my view.
How I do it?
Answer: I believe what you're looking for is Xamarin's DependencyService (http://developer.xamarin.com/guides/cross-platform/xamarin-forms/dependency-service/)
You should add the component to your platform-specific project, and then you create the interfaces for accessing them from your Forms project.
Here's some code to explain the process.
First, create an interface in the shared/PCL project
public interface IActionPackAlert
{
    void ShowAlert(string title, string text);
}

We're just gonna do iOS in this example. So in your iOS project you should implement the interface
[assembly: Xamarin.Forms.Dependency (typeof (ActionPackAlert_iOS))]
public class ActionPackAlert_iOS : IActionPackAlert
{
    public void ShowAlert(string title, string text)
    {
        UIActionAlert.ShowAlert (title, text);
    }
}

Great. We're done with the platform specific implementation. Now let's try to use it from the shared/PCL project:
DependencyService.Get<IActionPackAlert>().ShowAlert("Hello from Xamarin Forms", "This was called platform-specifically from the shared project");

Comment: The component the I got from Xamarin's store is a "native component"?
Comment: I've updated the answer. If you're still in doubt what to do, tell me what component you are using, and I'll try to be more specific
Comment: Yeah... I tried to do it.
I'm using the item ActionTray from ActionPack component... Wait.. I'll try a thing
Comment: It wasn't work...

I follow that guid... I try it on shared project:

`public interface IActionTray : ContentView`
`{`
`void ActoinTrayBiulder ();`
`}`

and I get the message:
`Xamarin.Forms.ContentView' in interface list is not an interface.
Comment: Sorry, I did not notice ActionTray. I only saw ActionPack. ActionTray probably needs to be done in your separate native projects only. I don't think it can be done in the shared/PCL project
Comment: I can do something like call a view using conditionals?
Like:
On SharedProject{
#if android:
call a UIViewController from android project
#if IOS
call a UIViewController from iOS StoryBoard;
}
Answer: I suspect that your problem resides in the frame/bounds you are setting for the UIActionTray, and when those bounds are set by the OS?
For what it's worth though, I was able to use the ActionTray with Xamarin.Forms (PCL) using some custom renderers.  Here is an example iOS custom renderer for the ActionTray:
In the Xamarin.Forms PCL project, you'll want a minimum of the following:
public class ActionTrayView : View
{
    public static BindableProperty TrayTypeProperty = BindableProperty.Create((ActionTrayView v) => v.TrayType, ActionTrayType.Draggable);
    public ActionTrayType TrayType
    {
        get
        {
            return (ActionTrayType)GetValue(TrayTypeProperty);
        }
        set
        {
            SetValue(TrayTypeProperty, value);
        }
    }

    public static BindableProperty OrientationProperty = BindableProperty.Create((ActionTrayView v) => v.Orientation, ActionTrayOrientation.Bottom);
    public ActionTrayOrientation Orientation
    {
        get
        {
            return (ActionTrayOrientation)GetValue(OrientationProperty);
        }
        set
        {
            SetValue(OrientationProperty, value);
        }
    }
}

public enum ActionTrayType
{
    ///
    /// When the user taps the ActionTray's DragTab, the tray will snap between its openedPostion and closedPostion.
    /// If the tray is open and the user taps anywhere within its content area, the tray will automatically close.
    ///
    AutoClosingPopup,

    ///
    /// The ActionTray can be dragged by its dragTab between the specified openedPosition and closedPosition
    ///
    Draggable,

    ///
    /// When the user taps the ActionTray's DragTab, the tray will snap between its openedPosition and closedPosition
    ///
    Popup
}

public enum ActionTrayOrientation
{
    ///
    /// The ActionTray is at the bottom of the screen
    ///
    Bottom,

    ///
    /// The ActionTray is on the left side of the screen
    ///
    Left,

    ///
    /// The ActionTray is on the ride side of the screen
    ///
    Right,

    ///
    /// The ActionTray is at the top of the screen
    ///
    Top
}

In your .iOS project, you'll need:
 using System.Drawing;
 using Xamarin.Forms.Platform.iOS;
 using Xamarin.Forms;
 using System.ComponentModel;
 using **YourXamarinFormsPCLProjectReference**;
 using **YourXamarinFormsPCLProjectReference**.iOS;
 using UIKit;
 using System;
 using System.Collections.Generic;
 using CoreGraphics;
 using Appracatappra.ActionComponents.ActionTray;

 [assembly: ExportRenderer(typeof(ActionTrayView), typeof(ActionTrayRendereriOS))]
 namespace **YourXamarinFormsPCLProjectReference**.iOS
 {
  public class ActionTrayRendereriOS : ViewRenderer<ActionTrayView, UIActionTray>
  {
    protected override void OnElementChanged (ElementChangedEventArgs<ActionTrayView> e)
    {
        base.OnElementChanged(e);

        if(e.OldElement == null)
        {
            SetNativeControl(new UIActionTray());

            Control.trayType = GetTrayType(e.NewElement.TrayType);
            Control.orientation = GetTrayOrientation(e.NewElement.Orientation);
        }
    }

    public override void LayoutSubviews ()
    {
        base.LayoutSubviews();
        Control.CloseTray(false);
    }

    private UIActionTrayType GetTrayType(ActionTrayType trayType)
    {
        switch(trayType)
        {
            case ActionTrayType.AutoClosingPopup:
            {
                return UIActionTrayType.AutoClosingPopup;
            }
            case ActionTrayType.Draggable:
            {
                return UIActionTrayType.Draggable;
            }
            case ActionTrayType.Popup:
            {
                return UIActionTrayType.Popup;
            }
            default:
            {
                return UIActionTrayType.Draggable;
            }
        }
    }

    private UIActionTrayOrientation GetTrayOrientation(ActionTrayOrientation orientation)
    {
        switch (orientation)
        {
            case ActionTrayOrientation.Bottom:
            {
                return UIActionTrayOrientation.Bottom;
            }
            case ActionTrayOrientation.Left:
            {
                return UIActionTrayOrientation.Left;
            }
            case ActionTrayOrientation.Right:
            {
                return UIActionTrayOrientation.Right;
            }
            case ActionTrayOrientation.Top:
            {
                return UIActionTrayOrientation.Top;
            }
            default:
            {
                return UIActionTrayOrientation.Bottom;
            }
        }
    }
}

Just insert your project name wherever it says YourXamarinFormsPCLProjectReference and you should be good to go, either in C# directly or xaml (I did it through xaml and the MVVM pattern).  There are a lot of other properties that come with the ActionTab.  If you want to be able to bind to a new property of the ActionTab, the formula is to:

Create a new, corresponding property in your Xamarin.Forms project.
Add this as a BindableProperty to the ActionTrayView class in the Xamarin.Forms project
Tell the custom renderer (ActionTrayRendereriOS in this example) how to handle the property.  You can handle runtime updates by overriding the OnElementPropertyChanged method in the custom renderer.  For the example above, I did not utilize OnElementPropertyChanged because the properties I gave you are set by the ActionTray when it is initialized, not sure if you can change these during the runtime after it has initially loaded (probably could, I just haven't tried that yet)

Hope that helps!

How to use component on forms?


How do I safely handle asyncio event loop handling with Telethon and Telegram Bot?

Question: I'm creating a simple telegram bot in which I'm making use of the telegram bot and telethon api(as I want to retrieve all members in a chat and with the bot api, i can't do this unless all users are admins). I'm able to currently print out the users in a chat successfully.
However when I terminate the script,  I keep getting  RuntimeErrors and warnings on certain telethon API coroutines not being awaited and Runtime errors for closed event loops
I did do some reading up on asyncio: https://medium.com/dev-bits/a-minimalistic-guide-for-understanding-asyncio-in-python-52c436c244ea and added the following code to my main function to run the client. Here's a sample of what it looks like:
from typing import Final
from telethon import TelegramClient, events
from telegram import Update, Bot
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes

TOKEN: Final = <token>
api_id = <api_id>
api_hash = <api_hash>
BOT_USERNAME = <bot_username>
bot = Bot(token=TOKEN)

bot_client = TelegramClient('sessions/session_master', api_id, api_hash).start(bot_token=TOKEN)

async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text('hello, bot starting..')

async def tag_all_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await tag_all(update)

async def tag_all(update: Update):
    group_members = await bot_client.get_participants(update.effective_chat.id)
    for user in group_members:
        if user.username or user.first_name:
            print(f' {user.username or user.first_name}')

if __name__ == '__main__':
    print('Starting bot...')
    app = Application.builder().token(TOKEN).build()

    # Commands
    app.add_handler(CommandHandler('start', start_command))
    app.add_handler(CommandHandler('all', tag_all_command))

    # Messages
    app.add_handler(MessageHandler(filters.TEXT, handle_message))

    # Polling
    print('Polling...')
    app.run_polling(poll_interval=3)
    try:
        bot_client.run_until_disconnected()
    except KeyboardInterrupt:
        bot_client.disconnect()

With the code above , I thought this would safely close the event loop, however whenever I terminate the script in pycharm, I get the following errors below, could someone help me pinpoint my mistake?:
C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\client\telegrambaseclient.py:643: RuntimeWarning: coroutine 'TelegramBaseClient._disconnect_coro' was never awaited
  pass
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
  File "C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\bot.py", line 104, in <module>
    bot_client.run_until_disconnected()
  File "C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\client\updates.py", line 95, in run_until_disconnected
    return self.loop.run_until_complete(self._run_until_disconnected())
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 628, in run_until_complete
    self._check_closed()
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 519, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
sys:1: RuntimeWarning: coroutine 'UpdateMethods._run_until_disconnected' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Task was destroyed but it is pending!
task: <Task pending name='Task-3' coro=<Connection._send_loop() running at C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\network\connection\connection.py:313> wait_for=<Future pending cb=[Task.task_wakeup()]>>
Task was destroyed but it is pending!
task: <Task pending name='Task-4' coro=<Connection._recv_loop() running at C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\network\connection\connection.py:332> wait_for=<Future pending cb=[Task.task_wakeup()]>>
Task was destroyed but it is pending!
task: <Task pending name='Task-5' coro=<MTProtoSender._send_loop() running at C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\network\mtprotosender.py:462> wait_for=<Future pending cb=[Task.task_wakeup()]>>
Task was destroyed but it is pending!
task: <Task pending name='Task-6' coro=<MTProtoSender._recv_loop() running at C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\network\mtprotosender.py:505> wait_for=<Future pending cb=[Task.task_wakeup()]>>
Task was destroyed but it is pending!
task: <Task pending name='Task-7' coro=<UpdateMethods._update_loop() running at C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\client\updates.py:425> wait_for=<Future pending cb=[Task.task_wakeup()]>>
Task was destroyed but it is pending!
task: <Task pending name='Task-8' coro=<UpdateMethods._keepalive_loop() running at C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\client\updates.py:459> wait_for=<Future pending cb=[Task.task_wakeup()]>>
Unexpected exception in the send loop
Traceback (most recent call last):
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\queues.py", line 158, in get
    await getter
GeneratorExit

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\network\connection\connection.py", line 313, in _send_loop
    self._send(await self._send_queue.get())
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\queues.py", line 160, in get
    getter.cancel()  # Just in case getter is not done yet.
    ^^^^^^^^^^^^^^^
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 761, in call_soon
    self._check_closed()
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 519, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <coroutine object Connection._send_loop at 0x000001F8E5CD8740>
RuntimeError: coroutine ignored GeneratorExit
Exception ignored in: <coroutine object Connection._recv_loop at 0x000001F8E5CDC8B0>
Traceback (most recent call last):
  File "C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\network\connection\connection.py", line 350, in _recv_loop
  File "C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\network\connection\connection.py", line 258, in disconnect
  File "C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\helpers.py", line 174, in _cancel
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 761, in call_soon
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 519, in _check_closed
RuntimeError: Event loop is closed
Unhandled error while receiving data
Traceback (most recent call last):
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\queues.py", line 158, in get
    await getter
GeneratorExit

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\network\mtprotosender.py", line 505, in _recv_loop
    body = await self._connection.recv()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\network\connection\connection.py", line 299, in recv
    result, err = await self._recv_queue.get()
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\queues.py", line 160, in get
    getter.cancel()  # Just in case getter is not done yet.
    ^^^^^^^^^^^^^^^
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 761, in call_soon
    self._check_closed()
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 519, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <coroutine object MTProtoSender._recv_loop at 0x000001F8E5CB5B40>
Traceback (most recent call last):
  File "C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\network\mtprotosender.py", line 520, in _recv_loop
  File "C:\Users\Jeevan Mahtani\PycharmProjects\pythonProject\venv\Lib\site-packages\telethon\network\mtprotosender.py", line 428, in _start_reconnect
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 434, in create_task
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 519, in _check_closed
RuntimeError: Event loop is closed
sys:1: RuntimeWarning: coroutine 'MTProtoSender._reconnect' was never awaited
Task was destroyed but it is pending!
task: <Task pending name='Task-20' coro=<Queue.get() running at C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\queues.py:158> wait_for=<Future pending cb=[Task.task_wakeup()]> cb=[_release_waiter(<Future pendi...ask_wakeup()]>)() at C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\tasks.py:421]>
Exception ignored in: <coroutine object Queue.get at 0x000001F8E5CD8E40>
Traceback (most recent call last):
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\queues.py", line 160, in get
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 761, in call_soon
  File "C:\Users\Jeevan Mahtani\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 519, in _check_closed
RuntimeError: Event loop is closed

Process finished with exit code 1

Comment: Telethon can work with bot accounts too, so my recommendation would be to stick with a single library for simplicity.
Answer: telegram package by default is evasive from some aspects, so you need to specify some stuff manually, you have couple issues:

main one is run_polling' close_loop not being set to False, it will close the loop on KeyboardInterrupt too and shutdown without giving chance for telethon to disconnect since they share the same loop.

run_polling also handles KeyboardInterrupt for you, no need for you to have your own try except.

and finally, using telethon's run_until_disconnected is useless and wrong. because run_polling will lock and run the event loop for telethon too. run_until_disconnected was never reached to begin with, until you exit run_polling with a signal. only then then it will run, and lock twice, so you shouldn't use it.

something like this should do:
    print('Polling...')
    try:
        app.run_polling(poll_interval=3, close_loop=False)
    finally:
        bot_client.disconnect()

Comment: This solved my issue. Thank you so much!! I didn't even think do check the run_polling coroutine. But I've learnt something new. Just out of curiosity, how were you able to pinpoint run_polling as the culprit based on the logs I provided?
Comment: since you didn't touch anything related to event loops and don't use asyncio.run in the code, the only thing left was a bad roommate of telethon terminating the shared loop while it exits, I'm more familiar with telethon, and i know that it doesn't stop loops, since the code was fine until the very end at KeyboardInterrupt, the one messing with it had to be run_polling once the try block is reached


Ruby Array Mysteriously Fails?

Question: This fails
require 'rinruby'
r = RinRuby.new(:echo => false)
spreads = []
spreads << 44
spreads << 2
r.assign "test", spreads

/var/lib/gems/2.1.0/gems/rinruby-2.0.3/lib/rinruby.rb:656:in `rescue in assign_engine': Unsupported data type on Ruby's end (RuntimeError)
    from /var/lib/gems/2.1.0/gems/rinruby-2.0.3/lib/rinruby.rb:635:in `assign_engine'
    from /var/lib/gems/2.1.0/gems/rinruby-2.0.3/lib/rinruby.rb:405:in `assign'

This works
require 'rinruby'
r = RinRuby.new(:echo => false)
r.assign "test", [44, 2]

What is going on?? If I print out spreads.class and [44, 2].class they both give an array.
Comment: Your demonstration would be more convincing if you used `=` instead of `||=`. The natural question readers would ask is "Was `spreads` set to something else?"
Comment: Does `spreads == [44, 2]` return `true`?
Answer: Thank you to sawa and Matt for the comments above.  It helped me realize what the problem was.  The above example was simplified to be easier to read on here, but it contained the assumption that my true data in my array wasn't causing a problem.  When I did the test you gave me sawa, I found that it worked, so I saw the problem must be my data.  Then I saw that even though my data looked identical to the sample array's above, it had numbers in BigDecimal format, which rinruby was rejecting.  When I changed those to floats, it worked.
Comment: I won't.  It says I can't accept for another 2 days.

Ruby Array Mysteriously Fails?


Modal box on iPhone no scroll

Question: Hello want to know if i can get some help on this as i have not found anything on the net that will fix this issue, On the iphone the twitter bootstrap modal box when is to big the page has no scroll to get the the footer of the box.
code used

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Submit A Electricity Reading

                Date/Time

                        22 Aug 2012, 9:45AM

                Peak

                    <input style="letter-spacing: 10px;" type="text" id="reading-peak" class="input-medium">

                Off Peak

                    <input style="letter-spacing: 10px;" type="text" id="reading-off-peak" class="input-medium">

            <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
            <button class="btn btn-primary">Lodge Reading</button>

Answer: Fix for this is adding the following css (found on bootstraps github issues)
    @media (max-width: 480px) {

        .modal {
            height: 500px; /* Set a default max height of the modal (adjusted later)*/
            position: fixed; /* Display modal in the centre of your screen */
            overflow-y: scroll; /*  Ensure that the modal is scroll-able */
            -webkit-overflow-scrolling: touch; /* Avoid having to use 2 finger scroll on iOS    */
        }
        .modal.fade.in{
            top: 5px; /* Use more screen real estate */
        }
        .modal-body{
            /* Increase the max height of the modal body to try & avoid both it,
             * and the modal container having scroll bars which results in odd behavior */
            max-height: 2400px;
        }
    }

    /* Now adjust the height so it handles various screen sizes & orientations */
    /* You could make this as granular as you like, or have it more granular at common screen sizes
     * but it should start at the height we set on .modal (i.e. 500px) & work down */
    @media (max-width: 480px) and (max-height: 500px){.modal{ height: 450px}}
    @media (max-width: 480px) and (max-height: 450px){.modal{ height: 400px}}
    @media (max-width: 480px) and (max-height: 400px){.modal{ height: 350px}}
    @media (max-width: 480px) and (max-height: 350px){.modal{ height: 300px}}
    @media (max-width: 480px) and (max-height: 300px){.modal{ height: 250px}}
    @media (max-width: 480px) and (max-height: 250px){.modal{ height: 200px}}
    @media (max-width: 480px) and (max-height: 200px){.modal{ height: 150px}}

Comment: For me only worked as a partial fix. The form is now scrollable, but only on the first show. Once I scroll it once or try to manipulate any form objects inside, the whole thing breaks again. Heh. Thanks for the share tho!
Comment: this didnt solve my particular problem but helped me.  Thanks!
Comment: Similar to @Kirill, this is an _almost_ for me! It works initially, but when I attempt to select a value from a drop down list (which iPhone completely ruins), the bug returns. I assume they're modifying the page elements in a way that reverts this css fix :(
Answer: I believe giving a max-height css property to the parent div (id:electricityModal) might help and give a scroll bar. Choose a height that best suits you. Say something like 250px.
Comment: tried that along did not work after doing alot more searching found a fix.

Modal box on iPhone no scroll


CXF Client in Spring with Basic / NTLM Authentication sent on every request

Question: we connect to a WebService through Apache CXF and Spring.
Now, at a first glance, Basic / NTLM Authentication works as expected.
Though I noticed that the Authorization Headers are sent on each and every request that is done.
The question is, how can I get the CXF Client to only send the Authorization Headers on the first request?
Please note that SESSION_MAINTAIN_PROPERTY is already set to true, so session cookies are saved and sent on the request...
many thanks in advance!
Comment: Ok, right now i implemented an Interceptor to throw away the Authorization-Header if cookies are sent with the request, since then i know that we are already authenticated. But this cant be the actual solution, i guess there must be some property to set in CXF for that behaviour?
Answer: Ok, right now i implemented an Interceptor to throw away the Authorization-Header if cookies are sent with the request, since then i know that we are already authenticated.


Conditional convergence and Riemann's series theorem

Question:
There are tests to determine whether an integral or sum is convergent.
There are test to determine whether an integral or sum is absolutely convergent.

An integral or series is said to be $\mathbf {conditionally \; convergent}$ if it converges, but does not converge absolutely.
$(1) \;$First of all I don't really understand the need to introduce this extra terminology. When you are presented with a certain series or integral, there should be no problem in stating that it is convergent, but not absolutely convergent. In fact that would seem to me the clearest qualification.
$(2) \;$ Secondly I find the qualification "conditionally convergent" vague and suggestive. It seems to imply that only under certain (extra?) conditions the series or integral can be considered convergent; if these (extra?) conditions are not met, the series or sum should in fact be considered non-convergent. However, this is clearly nonsense. Because at this stage we have already established (under generally accepted criteria) that the series or integral is "convergent".
[It sounds to me like the verdict of a court where a defendant is "acquitted" of an alleged crime, but also "conditionally acquitted" of exactly the same crime. What would be the meaning?]
$(3) \;$Thirdly, I have difficulty with the connection between the conditional convergence of a series and Riemann's series theorem. In this theorem the assumption is made that the terms in the series can be shuffled around at liberty. By clever reordering of the terms any result can be obtained. This leads to the conclusion that if an (alternating) series is not absolutely convergent, then the value of the sum is undefined. This is a most curious result, because we have already determined that the series is convergent and its sum has a unique value.
It seems to me that the fallacy resides in the assumption that all the (infinite) terms are available for reordering. But that is not the proper way to look at an infinite sum. One should consider the $L$'s partial sums, and take the limit of $L$ to infinity. The Cauchy method. Since the partial sums are finite, reordering terms is a pointless exercise since it can not affect the sum.
It would appreciate it very much you could comment on the three points above.
EDIT: I accept John Hughes' detailed explanation and I thank him for his efforts.
Answer: You don't like the term "conditionally convergent" because it's redundant -- it can be defined in terms of other things we already have -- and misleading, because it sounds as if we're saying something might be convergent when we know that it IS convergent.
The first is (I think) a not very good reason to dislike a definition. Almost everywhere in mathematics, we can already write out the words of any definition in place of the thing defined, but it turns out to be nice to be able to say "convergent" for a series or "continuous" for a function without writing out lots of deltas and epsilons. The same goes for "compact", and "connected" and lots of other good words. The real reason to quibble with a definition (I believe) is when it doesn't really have any purpose. If you define a function to be "q-nice" if it exactly equals $\cos(x) / x$ on the irrationals, no one else will ever have occasion to use your new term. But "absolutely" and "conditionally" convergent turn out to come up a lot, so giving them names is a good idea.
The second complaint is perfectly legitimate -- you may not like the word chosen to denote the thing. (I personally think that "compact" is a stupid word for the thing it denotes, but I'm in a small minority, alas.)  I share your distaste for "conditionally convergent", but I can't think of a better replacement, and even if I did, it'd be tough to get much traction for it. (Things can change, though: my sense is that the word "codomain" has gained some traction over "range" in the last couple of decades, esp. since "range" was used in various books to denote the codomain, but used to denote the image in other books, so it was pretty confusing already.)
As for the third thing: A series isn't an algebraic expression (although it's often written to resemble one), so we shouldn't expect it to have all the properties that an algebraic expression has (like satisfying the commutative law for addition). Instead, a series is based on a function from the positive integers to the reals (with $i$ being sent to the thing we call $a_i$); such a function is called a "sequence". Associated to the sequence is another sequence, the "partial sums," $s_k = \sum_{i = 1}^k a_i$. That sequence may or may not have a limit.
If you alter a sequence by permuting its terms (i.e., you build a different function $b$ with the same image as the function $a$), the associated sequence of partial sums will be different, and hence might have a different limit.
Riemann's theorem tells you that in certain circumstances, it will not have a different limit -- that the sum of the series with terms $a_i$ turns out to depend solely on the image of the function $a$ rather than on the function itself.
Added post-comments
The claim in the original question, "Since the partial sums are finite, reordering terms is a pointless exercise since it can not affect the sum" is mistaken, as is "Under Cauchy the Riemann shuffle is ineffective. So the trick only works if you drag terms from infinity upfront and/or shift terms towards infinity." (Perhaps I should say of the latter not that it's mistaken, but rather that it makes no sense to me.)
Let me give an example of a shuffled series whose partial-sum sequence is different from that of the original series, which will show that your first statement is false. Let's look at the alternating harmonic series:
$$
1 - \frac{1}{2} + \frac{1}{3} - \ldots.
$$
The partial sums are
$$
1, 1 - \frac{1}{2}, 1 - \frac{1}{2} + \frac{1}{3},
$$
and so on.
Now I'm going to shuffle the part of the series after the first element by the following rule: for $k \ge 2$, move $\frac{1}{2^k}$ so that it appears before $\frac{-1}{2^{k-1} -1}$. I could write this out algebraically, but let me instead write out the first few partial sums, and you'll see the pattern:
\begin{align}
&- \frac{1}{4}\\
&- \frac{1}{4} + 1\\
&- \frac{1}{4} + 1 + \frac{1}{2}\\
&- \frac{1}{4} + 1 - \frac{1}{2} - \frac{1}{8}\\
&- \frac{1}{4} + 1 - \frac{1}{2} - \frac{1}{8} + \frac{1}{3}\\
&- \frac{1}{4} + 1 - \frac{1}{2} - \frac{1}{8} + \frac{1}{3} + \frac{1}{5}\\
&- \frac{1}{4} + 1 - \frac{1}{2} - \frac{1}{8} + \frac{1}{3} + \frac{1}{5} - \frac{1}{6}\\
&- \frac{1}{4} + 1 - \frac{1}{2} - \frac{1}{8} + \frac{1}{3} + \frac{1}{5} - \frac{1}{6} - \frac{1}{16}\\
&- \frac{1}{4} + 1 - \frac{1}{2} - \frac{1}{8} + \frac{1}{3} + \frac{1}{5} - \frac{1}{6} - \frac{1}{16} + \frac{1}{7}
\end{align}
and so on.
If we call the original partial sums $s_k$ and these new sums $t_k$, it's pretty easy to see that $t_k < s_k$ for every $k$, hence that we now have two distinct partial-sum sequences where one is strictly greater than the other. There's no reason, a priori, to claim that $\lim t_k = \lim s_k$. In this particular case, it happens that the limits are indeed equal, because after $2^p$ terms, the difference between $t_k$ and $s_k$ is less than $\frac{1}{2^{p}}$, but this actually requires a little proof.
On the other hand, it also guides us to a re-ordering that does not have this property, and for which the limits are not equal.
Observe that
\begin{align}
&\frac{1}{3} > \frac{1}{4}\\
&\frac{1}{5} + \frac{1}{7} > \frac{1}{4} \\
&\frac{1}{9} + \frac{1}{11} + \frac{1}{13} + \frac{1}{15} > \frac{1}{4} \\
\end{align}
and so on. So if we reorder the sequence to be
\begin{align}
&\frac{1}{3}\\
&\frac{1}{3} + 1 \\
&\frac{1}{3} + 1 - \frac{1}{2} \\
&\frac{1}{3} + 1 - \frac{1}{2} + \frac{1}{5}\\
&\frac{1}{3} + 1 - \frac{1}{2} + \frac{1}{5} + \frac{1}{7} + \frac{1}{9}\\
&\frac{1}{3} + 1 - \frac{1}{2} + \frac{1}{5} + \frac{1}{7} + \frac{1}{9} - \frac{1}{4}
\end{align}
and so on, then the partial sums for this new sequence will always satisfy $t_k >  \frac{1}{4}+ s_k$, so that $\lim t_k \ge \frac{1}{4} + \lim s_k$.
Note that every term of the original series, up to term $k$, is included in the new series (at least by term $2^k$, say), so the two series have the same elements. But their partial sums are nonetheless clearly distinct and have distinct limits. Cauchy doesn't help here because, intuitively speaking, the number of terms you can move can grow as you move out in the series, and that allows you to dominate the Cauchy bounds that you might hope would let you prove the limits are the same.
Further post-comment addition
The OP criticizes my answer above as "dubious," which I'll take not as an insult but as a critique of the definition of "absolutely convergent" as being too generous --- OP seems unhappy about its allowing you to shift forward terms from farther and farther out.
So here's an alternative, which might make a good exercise for an intro analysis course:
We say a permutation $s$ of the positive integers is modest if there's an integer $N$ such that $| s(i) - i | < N$ for every $i$. (Informally, $s$ moves each integer "only a modest distance.")
We say that a convergent series with term sequence $a$ is modestly absolutely convergent if for every modest permutation, $s$, the series with term sequence $b(i) = a(s(i))$ converges to the same sum as does the original series.
Then there's a small theorem: Every convergent series is modestly absolutely convergent.
I leave the proof to the reader, but here's a hint: try to place a bound on the difference between the $i$th partial sums for the two sequences, and show that this difference goes to $0$ as $i$ grows.
This seems to me to capture the thing the OP wanted to say.
The bad news: since "modestly absolutely convergent" turns out to be a synonym for "convergent", we don't really need this definition.
More bad news: even if we did need this definition, showing that a permutation is modest would add considerable complexity to every proof about convergence.
The good news: the OP's intuition, at least when restricted to "modest" permutations, is correct.
Comment: Thank you for your long reply. Under Cauchy the Riemann shuffle is ineffective. So the trick only works if you drag terms from infinity upfront and/or shift terms towards infinity. Big deal. That is like saying that someone who borrows every month $10,000 from the bank is a wealthy man. Actually he is seriously in debt and one day the bank will reclaim the loan.
Comment: That's a fine intuition, but it leads to a false conclusion. You can indeed reorder a series to get a different sum (see my appended example in my answer), using the accepted definition of "sum". But if the series is absolutely convergent, you cannot; that's a rather surprising result, at least to me. I would never have guessed that absolute convergence was the right "secret sauce" to make this work ... but then analysis isn't really my niche (evidently!).
Comment: Thank you very for your post-comments. You show that rearranging terms can lead to a higher value for the sum of the alternating harmonic series. This is accomplished by placing larger and larger groups of positive terms early in the queue. This causes an unbalance between the positive and negative contributions. Still you can continue this method (ad infinitum) because the positive and negative terms considered separately do not converge. So in essence you have an unlimited reservoir to pull the positive values from, required for keeping the algorithm going.
Comment: Having said so, I am still of the opinion that the method is highly dubious. Essentially it comes down to "fast-tracking" or "queue-jumping" either the positive or the negative terms. It would be interesting to stop your algorithm after partial sum number $L = 1000$ has been evaluated. Then check which terms have been included in the sum. Also check that just on the other side of the fence ($L$) that there is an enormous group of negative terms which have been slow-tracked. It should be obvious that something fishy is going on. Much like in a pyramid scheme.
Comment: Exactly right. Informally: "infinity" doesn't work the same way as your bank. :)
Comment: What's dubious is *your intuition about series*, and examples like this are designed to help you understand that some of your preconceived notions are not captured in the carefully crafted definitions that we use. Once again, you may object that we've crafted the wrong definitions, because they don't meet your expectations, but we (I speak boldly for all mathematicians here!) mostly like them. :)
Comment: I've added one further post-comment remark to address your notion of things being "dubious."
Comment: I would think that for any "fair"relation between partial sum number $L$ and maximum swapping index $k$ the Riemann method grinds to a halt and Cauchy wins.
Comment: Interesting case would be: $k = 2 * L$. You then always have a broad zone of width $L$ do your swapping. But I would be confident the pool of positive terms inevitably dries up.
Comment: A small modification of my example shuffles item $i$ by at most $i$ steps, but still has limits differing by at least $1/8$.
Answer: We say "conditionally convergent" if a series converges, but not absolutely, because according to the Riemann theorem we can rearrange the terms so that we sum up all the same terms (just in a different order) and yet the limit of the sum is either non-existent, or equal to $\pm \infty$ (or equal to any desired finite result, but anyways, we say "conditionally convergent" because there are some rearrangements that won't give any convergent sum).
The beauty of absolutely convergent series is that you get the same answer for the sum under any rearrangement of the terms, so the unique sum value is a very definite property of the series. This is not to say that conditionally convergent series are useless. For example, we have $\pi/4 = 1 - 1/3 + 1/5 - 1/7  \ldots$ if the terms are taken in that order, even though the series is only conditionally convergent.


Assign attributes when another is changed

Question: I have a Python Shape class with an attribute called datum. It is a list with two numbers, x and y.
If I do
my_shape = Shape()

Then the datum is given default value: [0,0]
Now, I want to reassign the datum by doing:
my_shape.datum = [3,2]

then my datum is now assigned that list.
But I also have attributes x and y. How do I make x and y automatically update to become the first and second item of the datum list?
I put this in the init
self.x = self.datum[0]
self.y = self.datum[1]

But that only assigns x and y to the initialized values and I can't figure out how to update when self.datum updates.
I'm sorry if this is confusing. Thank you so much for helping this newbie.
-Jason
Answer: You can define x and y as properties:
@property
def x(self):
    return self.datum[0]

@x.setter
def x(self, value):
    self.datum[0] = value

@property
def y(self):
    return self.datum[1]

@y.setter
def y(self, value):
    self.datum[1] = value

This way, x and y are not attributes (and thus the data is stored only once in the datum), but stay usable as such (i.e.: my_shape.x and my_shape.y works as expected).
Comment: Right sorry, copy paste is the enemy... :)
Comment: Thank you, icecrime. This helps a lot.


Send HTTP response using C socket

Question: I`m trying to send HTTP response to browser
char *reply =
"HTTP/1.1 200 OK\n"
"Date: Thu, 19 Feb 2009 12:27:04 GMT\n"
"Server: Apache/2.2.3\n"
"Last-Modified: Wed, 18 Jun 2003 16:05:58 GMT\n"
"ETag: \"56d-9989200-1132c580\"\n"
"Content-Type: text/html\n"
"Content-Length: 15\n"
"Accept-Ranges: bytes\n"
"Connection: close\n"
"\n"
"sdfkjsdnbfkjbsf";

int sd = socket(PF_INET, SOCK_STREAM, 0);

struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(8081);
addr.sin_addr.s_addr = INADDR_ANY;

if(bind(sd,&addr,sizeof(addr))!=0)
{
    printf("bind error\n");
}

if (listen(sd, 16)!=0)
{
    printf("listen error\n");
}

for(;;)
{
    int size = sizeof(addr);
    int client = accept(sd, &addr, &size);

    if (client > 0)
    {
        printf("client connected\n");
        send(client, reply, sizeof(reply), 0);
    }
}

but my browser cant understand this, waits for a long time and then print smth strange. I guess my response is wrong, but I dont know how to fix. Any ideas?
Comment: should use strlen(reply), and add close(client)
Comment: maybe you also need a `\r` "HTTP/1.1 200 OK\r\n"
Answer: sizeof(reply) evaluates to the size of a char *, aka size of a pointer. Use strlen.
send(client, reply, strlen(reply), 0);

Comment: Damn! Stupid mistake. Thanks!

Send HTTP response using C socket


init function TypeError: Cannot read property 'style' of null

Question: No matter how I wrote the code, I received the same message and I've been trying to fix this since last night, but I don't understand why this is bothering me so much.
I get the message that all these lines are wrong
I work according to my course and this code is from a course that works on video and it doesn't work for me, I've tried a lot of changes but it doesn't work.
document.getElementById('dice-1').style.display = 'block';
document.getElementById('dice-2').style.display = 'block';
var scores, roundScore, activePlayer, gamePlaying;

var lastDice;

function init() {
    scores = [0, 0];
    activePlayer = 0;
    roundScore = 0;
    gamePlaying = true;

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';

    document.getElementById('score-0').textContent = '0';
    document.getElementById('score-1').textContent = '0';
    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';
    document.getElementById('name-0').textContent = 'Player 1';
    document.getElementById('name-1').textContent = 'Player 2';
    document.querySelector('.player-0-panel').classList.remove('winner');
    document.querySelector('.player-1-panel').classList.remove('winner');
    document.querySelector('.player-0-panel').classList.remove('active');
    document.querySelector('.player-1-panel').classList.remove('active');
    document.querySelector('.player-0-panel').classList.add('active');
}

document.querySelector('.btn-roll').addEventListener('click', function() {
    if(gamePlaying) {
        var dice1 = Math.floor(Math.random() * 6) + 1;
        var dice2 = Math.floor(Math.random() * 6) + 1;

        document.getElementById('dice-1').style.display = 'block';
        document.getElementById('dice-2').style.display = 'block';
        document.getElementById('dice-1').src = 'dice-' + dice1 + '.png';
        document.getElementById('dice-2').src = 'dice-' + dice2 + '.png';

        if (dice1 !== 1 && dice2 !== 1) {
            roundScore += dice1 + dice2;
            document.querySelector('#current-' + activePlayer).textContent = roundScore;
        } else {
            nextPlayer();
        }
    }
});

document.querySelector('.btn-hold').addEventListener('click', function() {
    if (gamePlaying) {
        scores[activePlayer] += roundScore;

        document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];

        var input = document.querySelector('.final-score').value;
        var winningScore;

        if(input) {
            winningScore = input;
        } else {
            winningScore = 100;
        }

        // Check if player won the game
        if (scores[activePlayer] >= winningScore) {
            document.querySelector('#name-' + activePlayer).textContent = 'Winner!';
            document.getElementById('dice-1').style.display = 'none';
            document.getElementById('dice-2').style.display = 'none';
            document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
            document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
            gamePlaying = false;
        } else {
            nextPlayer();
        }
    }
});

function nextPlayer() {
    activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
    roundScore = 0;

    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';

    document.querySelector('.player-0-panel').classList.toggle('active');
    document.querySelector('.player-1-panel').classList.toggle('active');

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';
}

document.querySelector('.btn-new').addEventListener('click', init);

init();

<!DOCTYPE html>

        <meta charset="UTF-8">
        <link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css">
        <link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
        <link type="text/css" rel="stylesheet" href="style.css">
        <title>Pig Game</title>

Player 1

43

Current

11

Player 2

72

Current

0

            <button class="btn-new">New game</button>
            <button class="btn-roll">Roll dice</button>
            <button class="btn-hold">Hold</button>

            <input type="text" placeholder="Final Score" class="final-score">

/**********************************************
*** GENERAL
**********************************************/

.final-score {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    top: 520px;
    color: #555;
    font-size: 18px;
    font-family: 'Lato';
    text-align: center;
    padding: 10px;
    width: 160px;
    text-transform: uppercase;
}

.final-score:focus { outline: none; }

dice-1 { top: 120px; }
#dice-2 { top: 250px; }

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;

}

.clearfix::after {
    content: "";
    display: table;
    clear: both;
}

body {
    background-image: linear-gradient(rgba(62, 20, 20, 0.4), rgba(62, 20, 20, 0.4)), url(back.jpg);
    background-size: cover;
    background-position: center;
    font-family: Lato;
    font-weight: 300;
    position: relative;
    height: 100vh;
    color: #555;
}

.wrapper {
    width: 1000px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    box-shadow: 0px 10px 50px rgba(0, 0, 0, 0.3);
    overflow: hidden;
}

.player-0-panel,
.player-1-panel {
    width: 50%;
    float: left;
    height: 600px;
    padding: 100px;
}

/**********************************************
*** PLAYERS
**********************************************/

.player-name {
    font-size: 40px;
    text-align: center;
    text-transform: uppercase;
    letter-spacing: 2px;
    font-weight: 100;
    margin-top: 20px;
    margin-bottom: 10px;
    position: relative;
}

.player-score {
    text-align: center;
    font-size: 80px;
    font-weight: 100;
    color: #EB4D4D;
    margin-bottom: 130px;
}

.active { background-color: #f7f7f7; }
.active .player-name { font-weight: 300; }

.active .player-name::after {
    content: "\2022";
    font-size: 47px;
    position: absolute;
    color: #EB4D4D;
    top: -7px;
    right: 10px;

}

.player-current-box {
    background-color: #EB4D4D;
    color: #fff;
    width: 40%;
    margin: 0 auto;
    padding: 12px;
    text-align: center;
}

.player-current-label {
    text-transform: uppercase;
    margin-bottom: 10px;
    font-size: 12px;
    color: #222;
}

.player-current-score {
    font-size: 30px;
}

button {
    position: absolute;
    width: 200px;
    left: 50%;
    transform: translateX(-50%);
    color: #555;
    background: none;
    border: none;
    font-family: Lato;
    font-size: 20px;
    text-transform: uppercase;
    cursor: pointer;
    font-weight: 300;
    transition: background-color 0.3s, color 0.3s;
}

button:hover { font-weight: 600; }
button:hover i { margin-right: 20px; }

button:focus {
    outline: none;
}

i {
    color: #EB4D4D;
    display: inline-block;
    margin-right: 15px;
    font-size: 32px;
    line-height: 1;
    vertical-align: text-top;
    margin-top: -4px;
    transition: margin 0.3s;
}

.btn-new { top: 45px;}
.btn-roll { top: 403px;}
.btn-hold { top: 467px;}

.dice {
    position: absolute;
    left: 50%;
    top: 178px;
    transform: translateX(-50%);
    height: 100px;
    box-shadow: 0px 10px 60px rgba(0, 0, 0, 0.10);
}

.winner { background-color: #f7f7f7; }
.winner .player-name { font-weight: 300; color: #EB4D4D; }

Please help me.
Comment: i updated the post take a look @Bahtiyar
Comment: What is the problem ? what do you mean  " that all these lines are wrong"
Comment: I found . problem is  "init" . check my answer
Comment: Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element)
Answer: I don't see any HTML elements with id="dice-1" nor id="dice-2", which would explain the error you're receiving.
Answer: İn javascript  , remove  init();   or define init function.
try this:
function init() {
    scores = [0, 0];
    activePlayer = 0;
    roundScore = 0;
    gamePlaying = true;

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';

    document.getElementById('score-0').textContent = '0';
    document.getElementById('score-1').textContent = '0';
    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';
    document.getElementById('name-0').textContent = 'Player 1';
    document.getElementById('name-1').textContent = 'Player 2';
    document.querySelector('.player-0-panel').classList.remove('winner');
    document.querySelector('.player-1-panel').classList.remove('winner');
    document.querySelector('.player-0-panel').classList.remove('active');
    document.querySelector('.player-1-panel').classList.remove('active');
    document.querySelector('.player-0-panel').classList.add('active');
}

document.querySelector('.btn-roll').addEventListener('click', function() {
    if(gamePlaying) {
        var dice1 = Math.floor(Math.random() * 6) + 1;
        var dice2 = Math.floor(Math.random() * 6) + 1;

        document.getElementById('dice-1').style.display = 'block';
        document.getElementById('dice-2').style.display = 'block';
        document.getElementById('dice-1').src = 'dice-' + dice1 + '.png';
        document.getElementById('dice-2').src = 'dice-' + dice2 + '.png';

        if (dice1 !== 1 && dice2 !== 1) {
            roundScore += dice1 + dice2;
            document.querySelector('#current-' + activePlayer).textContent = roundScore;
        } else {
            nextPlayer();
        }
    }
});

document.querySelector('.btn-hold').addEventListener('click', function() {
    if (gamePlaying) {
        scores[activePlayer] += roundScore;

        document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];

        var input = document.querySelector('.final-score').value;
        var winningScore;

        if(input) {
            winningScore = input;
        } else {
            winningScore = 100;
        }

        // Check if player won the game
        if (scores[activePlayer] >= winningScore) {
            document.querySelector('#name-' + activePlayer).textContent = 'Winner!';
            document.getElementById('dice-1').style.display = 'none';
            document.getElementById('dice-2').style.display = 'none';
            document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
            document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
            gamePlaying = false;
        } else {
            nextPlayer();
        }
    }
});

function nextPlayer() {
    activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
    roundScore = 0;

    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';

    document.querySelector('.player-0-panel').classList.toggle('active');
    document.querySelector('.player-1-panel').classList.toggle('active');

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';
}
document.querySelector('.btn-new').addEventListener('click', init);

function init(){
}

Answer: I don't see element with id="dice-1" or id="dice-2" in your template (HTML), so the error just means, that element with that id doesn't exist, so it's value is null.


How can I ignore null headers in a .csv file?

Question: How can I ignore null headers in a .csv file?
I have a csv file like this
http://188.8.131.52/~digicelc/gestion/reportes/import/liquidacion/13958642917519.csv

and my code is
data <- read.csv('1.csv',header = T, sep=";")

So R tells me
  more columns than column names

And I don't want to skip the header of the file
thank you!
Comment: Hi, user1532587, and welcome to the site!  Actually, this site is more for statistics questions and not so much for programming questions.  StackOverflow has a lot of R programmers who can answer these questions sometimes better and more quickly than we can, although you may well get an answer here too.
Comment: can you post a link to `1.csv`? there may be something more unique in the file that we're not seeing from the paste
Comment: here's a link
http://188.8.131.52/~digicelc/gestion/reportes/import/liquidacion/13958642917519.csv
Answer: I don't see the same behavior here. R adds default column names and NA to unavailable data.
> data <- read.csv("test.csv", header = TRUE, sep = ";")
> data
  col1      col2      col3       col4          X X.1
1 val1      val2      val3       val4       val5  NA
2 val1      val2      val3       val4       val5  NA

Are you using the latest version?
Comment: this is the actual file
http://220.127.116.11/~digicelc/gestion/reportes/import/liquidacion/13958642917519.csv
Comment: I'm using the actual version, yes
Answer: But the error message tells you exactly what the problem is. you have more columns than column names.
download.file("http://184.108.40.206/~digicelc/gestion/reportes/import/liquidacion/13958642917519.csv", destfile="1.csv")
D1 <- read.csv2("1.csv", skip=1, header=FALSE)
firstlines <- readLines("1.csv", 3)
splitthem <- strsplit(firstlines, ";")
sapply(splitthem, length)
# [1] 28 42 42

So you have 42 data columns (separated by semicolons) but 28 column names (again, separated by column names). How would R know which name you would want to go with which column? ("Computers are good at following instructions, but not at reading your mind." - Donald Knuth).
You need to edit the source file so that each column would have a name or skip the first row and then get the column names form somewhere else.
edit

yes, the idea is to take the first names and then standart variables like V1, V2, or
whatever- Otherwise is there a way to skip those?

Ok then I would just use the above with slight modification:
download.file("http://126.96.36.199/~digicelc/gestion/reportes/import/liquidacion/13958642917519.csv", destfile="1.csv")
D <- read.csv2("1.csv", skip=1, header=FALSE)
header <- strsplit(readLines("1.csv", 3), ";")[[1]]
names(D)[1:length(header)] <- header

Now you have the first 28 variables named, and the rest named V29-V42.
You can "skip" the rest of the names in various ways. If you do as suggested in another answer (Dave) , basically as
names(D) <- header

...  then variables 29-42 will have NA name. This is not a usable name, and you can address these variables only by column number. Or you can do:
names(D)[29:43] <- ""

Now you can't use these names either.
> D[[""]]
NULL

I think it is useful to give them names, as many data frame operations presume names. For example, suppose you have empty names ("" as above) and try to see the first few rows of your data frame:
head(D)
# skipped most of the output, keeping only column 42:
  structure(c("-1", "70", ".5", "70", "266", "70"), class = "AsIs")
1                                                                -1
2                                                                70
3                                                                .5
4                                                                70
5                                                               266
6                                                                70

So when using head, you will see your data frame with funny names. Or another example:
D[1:3,29:31]
                             .1                  .2
1 C_COMPONENTE_LIQ_DESDE_CO 243 LIQUIDACION TOPE CO
2 C_COMPONENTE_LIQ_DESDE_CO 243         RESIDUAL CO
3 C_COMPONENTE_LIQ_DESDE_CO 243         RESIDUAL CO

The first component now is named "", the second one ".1", and the third one ".2". Have a look at a quote from data.frame help file below:

The column names should be non-empty, and attempts to use empty names will have
  unsupported results. Duplicate column names are allowed, but you need to use check.names
  = FALSE for data.frame to generate such a data frame. However, not all operations on
  data frames will preserve duplicated column names: for example matrix-like subsetting
  will force column names in the result to be unique.

Or suppose you add some columns to the beginning of your data frame; if you have col names then you can still address what was previously 29th column as D$V29, but with D[,29] you will get something else.
Probably there are other examples. In other words, you can have "unnamed" columns in a data frame but I don't think it is a good idea. And technically, all columns in a data frame  will always have a name (it can just be "" or NA), so why not have meaningful names? (Even V29 is better than nothing.)
Comment: i.e your question is unclear. do you want to name the first 28 columns of data with the names in the first row?
Comment: yes, the idea is to take the first names and then standart variables like V1, V2, or whatever- Otherwise is there a way to skip those?


How do I take minecraft blocks from nowhere?

Question: I was playing minecraft and a player looked at a block and he suddenly had it in his hand. How did he do that? (He was in creative by the way)
Answer: The Pick Block key, bound to mouse 3 by default (middle mouse button on most mice.) Just look at the block and press whatever Pick Block is bound to, and it'll be in your hand. Of course, you'll need creative mode.
See also, this Minecraft Wiki article
Comment: Well I have a laptop which means I dont have a mouse. Any more advice?
Comment: Set the control in options>controls to something like P.


Apache continually goes down (Ubuntu Server 20.04.2 LTS - Apache 2.4.41)

Question: I hope some kind individual can help.
I'm using a Ubuntu on a Raspberry Pi 4 for PHP development. My development domain is regularly unreachable until I restart Apache. The /var/log/apache2/error.log file is completely empty. An Apache config test is fine.
Does anyone else know what I can check or how to debug this? I totally reinstalled the Pi and it still happens.
Comment: The error log should never be completely empty. It would have the restart messages at the very least. If the log is empty, confirm that Apache has permission to write to the log file. Also check `/var/log/syslog` for any anomalies.
Answer: I fixed it by setting Apache to run as root:root instead of a "normal" user.


Exporting and importing RSA keys

Question: I have created an app that creates a signed XML file.
Microsoft has some straight forward examples it was not that difficult to implement but much is hidden/ encapsulated in the libraries below
System.Security.Cryptography
System.Xml,
System.Security.Cryptography.Xml
I now need to export the public key and put it (the public key) in a second application so it can verify that the signed XML document is genuine.
My second application can then enable/disable various program features based on the contents of the signed XML file.
Microsoft goes on about not exporting the contents of the key container but that is exactly what I think I need to do because in my mind I need to accomplish a couple of things.
One as mentioned above I need to export the public key and then import it into a key container that resides in the application that uses the signed XML file.
Secondly I think I need to export both private and public keys in order to back them up.
Since my application will be distributed with the public key I need to back up the public, the private key and the hashing algorithm in a safe location.
Microsoft goes on about not exporting keys to clear text but I am uneasy/and don't know how to back up the key container and I'm unsure how to look at the thing and know what I want to store is actually in there when I try to view the key container in the debugger it seems to go on forever (some sections appear to repeat recursively??)
Can anyone offer advice on how to export/import RSA keys to a key container and an approach to backing up mykeys or contaner?.
Answer: Open the Microsoft Management Console (mmc.exe), navigate to File -> Add/Remove Snap-in
This dialog will pop up

On the Available snap-ins pick "Certificates"; click Add and choose to add My user account, then click Add again and choose Computer account.
Click OK. Now you find any certificates you'll need and functions to import/export them - both private (if available and exportable), and public.
Comment: Here is the code that creates the RSA encryption keys.
            cspParams = new CspParameters();
            // Create a new RSA signing key and save it in the container.
            cspParams.KeyContainerName = "MY_RSA_KEY";
            rsaKey = new RSACryptoServiceProvider(cspParams);
Comment: Hi esskar
Thnaks for the reply.
Comment: Above should say "Thanks for the reply" the five minute timer is annoying as heck! I will check that out today as soon as I stomp out a couple of fires. I found this article on MSDN called Walkthrough: Creating a Cryptographic Application [link](http://127.0.0.1:47873/help/1-5792/ms.help?method=page&id=ABF48C11-1E72-431D-9562-39CF23E1A8FF&product=VS&productversion=100&locale=en-US&topiclocale=EN-US&topicversion=100&SQM=2)
Comment: Hi Esskar
After a long delay I'm finally back to this task.
I had assumed (maybe incorrectly) that because I had created my RSA keys programmatically I would want to import & export all my certs programmatically.
Comment: After thinking about it a while it makes sense that I would be able/want to import and export my RSA keys via the certmanager snap in for my own education and so it will be in a convenient file format to back up the keys but I would also want to do it programmatically so the user is not required to install a cert as part of the installation so the user will have the public key.
Comment: The code does work to encrypt a signature of my xml file because I can test it i.e. if I make any change to the file it will fail to decrypt the signature.
I also know that the key persists because I can compile and run the program and encrypt the xml file on one day and decrypt the signature on another day it will still work.
So I believe that the constructor RSACryptoServiceProvider if passed a name that already exists in this example "MY_RSA_KEY" will use the existing key and not create a new one each time the program is run.
Comment: If I use the certmanager to export the file what format should I choose?
If I have multiple certs how do I tell them apart if the name I used to create them is nowhere to be found?................... (at least by me)
I am also working on understandingout how to export and import the certs programmatically, if you have any guidance there I would be thrilled to hear about that as well.
Comment: I wish I could figure out how to post my code maintain the formatting

Exporting and importing RSA keys


Prove that $\int_{\mathbb{R}} \frac{1}{(a^2+t^2)(b^2+t^2)} dt= \frac{\pi}{ab(a+b)}$

Question:
Prove that $\int_{\mathbb{R}} \frac{1}{(a^2+t^2)(b^2+t^2)} dt= \frac{\pi}{ab(a+b)}$

For $a,b>0$, the Fourier transform of $f(x) = e^{-a|x|}$ is $\widehat{f}(t) = \dfrac{2a}{a^2+t^2}$.
Otherwise, we have $\int_{\mathbb{R}}\dfrac{1}{(a^2+t^2)^2} dt= \dfrac{\pi}{2a^3} $.
I have to show that $\int_{\mathbb{R}} \dfrac{1}{(a^2+t^2)(b^2+t^2)} dt= \dfrac{\pi}{ab(a+b)}$ ?
I have no idea to do it. Could someone help me ?
Answer: Hint:
$$\frac{1}{(a^2+t^2)(b^2+t^2)}=\frac{1}{b^2-a^2}\left(\frac{1}{a^2+t^2}-\frac{1}{b^2+t^2}\right).$$
Comment: Oh... ! Thank you so much ! :)


Reload UITableView data and scroll down to last selected cell

Question: I have a long list of data to show in a UITableView. One cell of the table contains many things like comments, share and like. Now when user likes a post in the cell it reloadTableData and move to the first one again.For example user have scrolled down to 30 cells and then like 29th cell, it'll reload the data and goes to the top again.So how to make it stays at the same place after reloading the data? Here is my code:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        return imagesArr.count;
}

And for the implmemtation of Like button
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
HomeCell *cellObj = (HomeCell*)[tableView dequeueReusableCellWithIdentifier:@"HomeCell" ];
cellObj.likeBtn.tag=indexPath.row;
[cellObj.likeBtn addTarget:self action:@selector(loveButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
return cellObj;
    }

loveButtonClicked button clicked.
-(void)loveButtonClicked
{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:nil, nil];
    [[RRDataAcessLayer sharedDataAccessLayerManager]sendRequestToFetchHomeData:dict];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
   // hud.labelText = @"Loading Data";

}

Image below will give you an idea. two cells are given and when the heart icon is tapped it reloads to update the value of total love.
Comment: add your code please
Comment: @hasan83 check my updated question.
Comment: add loveButtonClicked code
Comment: If my suggestion worked for you kindly accept my answer also for others to help .. Thanks
Comment: i made a demo application for you share me your email i will send you
Answer:
Saved edited index in variable
Get indexpath for that index
Scroll to table after reoladdata to that index

NSIndexPath* ip = [NSIndexPath indexPathForRow:editedRowNumber inSection:0];
    [self.tableViewTimeline scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:YES];

If your table view has one section you can pass zero if has number of section you have to pass section in which user edit cell

in like button action you can reload cell without scrolling by using both ways while best just reload selected index as suggest @Mhesh
    int selectedIndex=(int) btn.tag;
    int likes = [[self.arrayDataSource objectAtIndex:selectedIndex] intValue]+1;
    [self.arrayDataSource replaceObjectAtIndex:selectedIndex withObject:[NSString stringWithFormat:@"%d",likes]];
    NSIndexPath* ip = [NSIndexPath indexPathForRow:selectedIndex inSection:0];
    /*
    [self.refWeakTableView reloadData];
    [self.refWeakTableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionNone animated:YES];
     */
    [self.refWeakTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:ip]withRowAnimation:UITableViewRowAnimationNone];

and cell for row method set like button tag

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"MyTableViewCell";

    myTableViewCell *cell = (myTableViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"myTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    //    DataSourceModel* dbObject = (DataSourceModel*)[self.arrayDataSource objectAtIndex:indexPath.row];
    cell.myCellLabel.text = [NSString stringWithFormat:@"%@",self.arrayDataSource[indexPath.row]];
    int indexed = (int)indexPath.row;

    cell.btnLike.tag = indexed;

    return cell;
}

Comment: that may solve the problem. but, it shouldn't exist in first place. the tableview should maintain its scroll position. that's the default behaviour on iOS
Comment: then you can use scrollPosition option UITableViewScrollPositionNone
Answer: If action is like affected to one cell then why you reload the whole table, reload the only single cell using below code
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfYourCell, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];

You can change UITableViewRowAnimation.
Comment: this seems logical. Let me give it a try.
Comment: Have you used facebook app? Then how did facebook do this when you like something? The solution you provided might work but there is a lot going on in the app that I can't figure out where to put this code. Because in `cellForRowAtIndexPath` I'm not reloading the data.
Comment: when you like the button and it call function in this function you have to find the indexpath of tableview according to touched like button then write your all logic and at the end of the function write the above code.
Answer: I'd recommend to cache the current selection in didSelectedCellAtIndexPath in your Controller and if you reload the whole table you could scroll to this last cached indexPath with the tableView's methods for scrolling. :)
Answer: You should not reload all table data, but only the rows you want. You can do this by calling this method on tableView  reloadRowsAtIndexPaths(_:withRowAnimation:)
It will reload only desired cells with a desired animation without scrolling to top of table view


Jython SyntaxError (from Java app)

Question: In my Java app I want to use Jython to interpret Python code.
So I initialise Jython as follows:
PySystemState.initialize();
PythonInterpreter jython = new PythonInterpreter();

Then I want to test it like this:
jython.eval("out = ''");
jython.eval("out += 'Test1\n'");
jython.eval("out += 'Test2\n'");
System.out.println(jython.get("out").toString());

However, the first eval line throws this error:
  File "<string>", line 1
    out = ''
       ^
SyntaxError: mismatched input '=' expecting EOF

When I try it with exec instead of eval I get this error:
  File "<string>", line 2
    '
    ^
SyntaxError: no viable alternative at character '''

Any ideas what I am doing wrong here?
PS: I am using jython-2.5.4-rc1
Answer: You'll need to ensure you have the following

Declare an out variable
Because you're using Java, escape special characters such as \\n
Use exec rather than eval

This will produce:
PythonInterpreter jython = new PythonInterpreter();
jython.set("out", new PyString());
jython.exec("out = ''");
jython.exec("out += 'Test1\\n'");
jython.exec("out += 'Test2\\n'");
System.out.println(jython.get("out").toString());

Comment: Can the jython script return a value to the enclosing java program, received as the result of the eval() method?
Answer: You should use exec to execute statements. eval evaluates and returns a PyObject.
Comment: exec does not solve the problem, then I receive the following SyntaxError: no viable alternative at character '''

Jython SyntaxError (from Java app)


Wrapping fibreglass/ rock wool to seal in fibres in acoustic panels (bass traps)

Question: I'm Making acoustic panels to treat my home studio and plan to use mineral wool or fibreglass insulation to do so. Likely Owen's Corning 703 or something marketed as safe insulation like Bradford Sound Soundscreen or Roxul Safe n' Sound. Regardless of how safe salespeople market these fibrous materials I still want to seal in this material, which leads to the questions:

What material can I wrap around the insulation in order to trap the fibrous particles in but still allow sound to pass?
Is there some kind of measurement that I should be looking for such as stitching density?

I can't find any data about the size of the particles for fibreglass or mineral wool. One company uses a material called Micromesh but provides no data about it:
Comment: Have you considered vacuum storage bags / space saver bags? Even without sucking all the air, they should be air tight.
Answer: You would do fine using simple burlap. Given the wavelengths of the signal that must pass through, cotton fibers will pose no problem. They are also considerably smaller than the coarse fibers found in commercial acoustic panels. In fact, any material used as speaker cover would work for your application. Incidentally, fiberglass is a very hard and acoustically very reflective material. You may do better with a panel of dense open cell, soft urethane-based foam; they may be found at a local craft store.
Comment: http://www.engineeringtoolbox.com/particle-sizes-d_934.html provides some information on various particle sizes, and suggests glass wool fibers to be around 1000 microns in size. I'm not able to find a great resource on what size particle burlap will let through (http://cecor.net/sump-sharks-filters/ suggests their filter made out of burlap is blocks >500 microns), but keep in mind that -- unlike with a typical filter -- nothing in a bass trap is actively pushing the fibers through the containing membrane.
Comment: Thanks! Please explain how you arrived at the conclusion burlap is tight enough to not allow glass fibres to pass? Data would be greatly appreciated as I'm trying to source it. FYI your information regarding sound absorption is incorrect. The wavelength of low frequency sounds are in the magnitude of metres. Fortunately it is not the determining factor for whether a material is permeable for sound. The sound absorption coefficients for rock wool and fibre glass are some of the highest per unit weight out of any available material and this is relatively uniform across the frequency spectrum.
Answer: If you didn't buy the 703 yet, check out Applegate's cotton acoustic panels. Since cotton is harmless there's no need to cover them plus they're rigid enough to use completely by themselves with no frame.


Which version of eclipse should i download?

Question: I'd like to learn struts2 with eclipse. Which version of eclipse should i download?
My background is as a c# developer, so i don't really know much at all about java but i'm keen to learn.
I'm looking on the eclipse site http://eclipse.org/downloads/ and i think what i want is one of these, but i'm not sure:

Eclipse for Java EE developers
Eclipse for Java developers
Classic Eclipse

I've done a bit of searching around, and most tutorials seem to assume you've already got everything installed. I'm starting with nothing here.
Answer: Eclipse for Java Developers is sufficient for your needs.  The EE functionality isn't required to use Struts.  I also recommend using Jetty for a web container and Maven for dependency management.
Oh, and you should install the JDK first of course.  Get the latest JDK 6 build.  Not one of the bundles, just the JDK, which is listed below the bundles on this page
Answer: I have found that the Eclipse Java EE version is good for Web stuff.  It knows about WAR files which you will need to actually run your struts code.  The major hurdle is getting all the used libraries placed so they end up in WEB-INF/lib.
Answer: Struts is a web framework built on top of JSP/Servlet API. Get Eclipse for Java EE. It ships with all plugins needed for web development, under each the great WTP and several default appserver plugins. The normal Eclipse version lacks this.
When starting a project, first integrate the appserver in your Eclipse environment through the Servers view (obviously you need to download and install the appserver in question in your platform first, then it's just a matter of pointing its installation path, I can recommend using Apache Tomcat). Then create a Dynamic Web Project, pick the integrated appserver from the list and go ahead! :)
Comment: One thing to note: I struggled for hours today but finally discovered you need to set the 'dynamic web module version' to 2.4 when creating the new project, otherwise it does not work and gives a cryptic error.
Comment: Also found this tutorial is about the only one that worked for me!

http://www.howtodothings.com/computers-internet/how-to-create-struts-2-helloworld-on-eclipse


mod_rewrite and mod_dir collision

Question: I'm edditing my htaccess to internally redirects
just about any URL to a php page handler:
RewriteRule ^images\/ - [L,NS]
RewriteRule ^docs\/ - [L,NS]
RewriteRule ^([A-Za-z0-9\_\-]+)\/?$ pages/pagehandler.php?page=$1 [L,QSA,NS]

this works fine accept that directories that are enteres in the address
bar with no trailing slash for some reason get duplicate query strings,
and for some reason the address bar of the browser changes
for example, if I type the URL:
localhost/movies
if there's a directory called movies in the site root
than the address changes to:
localhost/movies/?page=movies
I guess this is some collision with mod_dir but I don't know
how to overcome it, if I use:
<IfModule mod_dir.c>
   DirectorySlash Off
</IfModule>

Than it works, but I don't want this, I think for some reason the url
is rewritten than mod dir changes it and than it is rewritten again thus
making duplicate query strings,
Any Ideas?
EDIT: I Add a relevant part of the Rewritelog, this is all from one request:
strip per-dir prefix: /opt/lampp/htdocs/movies -> movies
applying pattern '^images\/' to uri 'movies'
strip per-dir prefix: /opt/lampp/htdocs/movies -> movies
applying pattern '^docs\/' to uri 'movies'
strip per-dir prefix: /opt/lampp/htdocs/movies -> movies
applying pattern '^pages\/' to uri 'movies'
strip per-dir prefix: /opt/lampp/htdocs/movies -> movies
applying pattern '^([A-Za-z0-9\_\-]+)\/?$' to uri 'movies'
rewrite 'movies' -> 'pages/pagehandler.php?page=movies'
split uri=pages/pagehandler.php?page=movies -> uri=pages/pagehandler.php, args=page=movies
add per-dir prefix: pages/pagehandler.php -> /opt/lampp/htdocs/pages/pagehandler.php
trying to replace prefix /opt/lampp/htdocs/ with /
strip matching prefix: /opt/lampp/htdocs/pages/pagehandler.php -> pages/pagehandler.php
add subst prefix: pages/pagehandler.php -> /pages/pagehandler.php
internal redirect with /pages/pagehandler.php [INTERNAL REDIRECT]
strip per-dir prefix: /opt/lampp/htdocs/movies/ -> movies/
applying pattern '^images\/' to uri 'movies/'
strip per-dir prefix: /opt/lampp/htdocs/movies/ -> movies/
applying pattern '^docs\/' to uri 'movies/'
strip per-dir prefix: /opt/lampp/htdocs/movies/ -> movies/
applying pattern '^pages\/' to uri 'movies/'
strip per-dir prefix: /opt/lampp/htdocs/movies/ -> movies/
applying pattern '^([A-Za-z0-9\_\-]+)\/?$' to uri 'movies/'
rewrite 'movies/' -> 'pages/pagehandler.php?page=movies'
split uri=pages/pagehandler.php?page=movies -> uri=pages/pagehandler.php, args=page=movies&page=movies
add per-dir prefix: pages/pagehandler.php -> /opt/lampp/htdocs/pages/pagehandler.php
trying to replace prefix /opt/lampp/htdocs/ with /
strip matching prefix: /opt/lampp/htdocs/pages/pagehandler.php -> pages/pagehandler.php
add subst prefix: pages/pagehandler.php -> /pages/pagehandler.php
internal redirect with /pages/pagehandler.php [INTERNAL REDIRECT]

Also the relevant part from the access log:
"GET /movies HTTP/1.1" 301
"GET /movies/?page=movies HTTP/1.1" 200

Answer: Can you change your rewrite rule to:
RewriteRule ^([A-Za-z0-9\_\-]+)/?$ /pages/pagehandler.php?page=$1 [L,QSA,NS]

Note the / before pages.
Comment: Thanks for the effort, I added the relevant parts of the access_log and the Rewrite_log, there's nothing about this in the error_log. all the lines from the rewrite_log I've added are subsequent I didn't remove anything between lines. It seems like mod_rewrite rewrites the URL, than mod_dir redirects with the query string and than mod_rewrite adds the query string again, I guess I can add a rewrite condition that checks if the URL is a directory and doesn't add with a trailing slash and if so it won't add the query string, question is if there's a solution at the configuration level?
Answer: For anyone having this problem, what I did ultimately in disable the Directory Slash:
<IfModule mod_dir.c>
   DirectorySlash Off
</IfModule>

And I used a RewriteRule to 301 Redirect all directory requests than do not end with a /
I guess this is some sort of collision between mod_rewrite and mod_dir
as I primarily thought
Answer:
And I used a RewriteRule to 301 Redirect all directory requests than do not end with a /

I had a similar problem but could not find a solution over mod_rewrite (did not know how to add this slash with a 301 redirect - tried everything).
What I did is to define:
<IfModule mod_dir.c>
   DirectorySlash Off
</IfModule>
ErrorDocument 404 404.php

If now the trailing slash is missed, 404.php is used redirecting the client if the url has no trailing slash now:
<?php
$home="http://".$_SERVER['HTTP_HOST'];
$url=$home.$_SERVER['REQUEST_URI'];
?>

<title><?php echo $_SERVER['REDIRECT_STATUS']; ?></title>
<?php if(!preg_match('/^.+\/$/', $url)) { ?>
<meta http-equiv="refresh" content="0; URL=<?php echo $url; ?>/">
<? } ?>

<?php echo $_SERVER['REDIRECT_STATUS']; ?>

It smells like hell but worksforme ...

mod_rewrite and mod_dir collision


Electrical outlet

Question: I purchased a small freezer and the instructions state to plug it into a three prong outlet. In my garage there is a 2 prong outlet that I use with an adaptor. Is it safe for me to plug the freezer into the 2 prong outlet with an adaptor?
Is it safe if I plugged it into one of those outlet strips?  I would be plugging the strip into the two prong outlet with an adaptor.
Thank you in advance!  E
Answer: One way to do this, that is National Electrical Code compliant. Would be to replace the two prong receptacle, with a GFCI receptacle.  While this does not provide an effective fault current path, it should prevent electrocution in the event of a fault.
Technically to be code compliant, you'll have to stick a "No Equipment Ground" sticker on the GFCI receptacle. There should be one in the box that the GFCI receptacle comes in.
Those three prong adapters that connect to the faceplate screw, do not provide an effective fault current path. And therefore would not allow a fault to be cleared by the breaker.
The "correct" way to do this, would be to install a code compliant grounding conductor and three prong receptacle. Though since the receptacle is in a garage, GFCI protection is required anyway.
NOTES:

Even though most modern devices should work with GFCI devices, some manufacturers still produce equipment that may trip the GFCI.
Answer: Either way you are using your appliance without the grounding conductor required (for safety reasons) by the manufacturer.
Will it work? Yes
Is it safe? Homes were not wired with grounding conductors for many decades
Should you look into alternative grounding methods for your appliance? Yes
The "adapter" you reference is likely equipped with a grounding terminal to facilitate an auxiliary, or supplemental, grounding conductor. You should see if you can run a wire from the terminal to a grounding rod or other suitable appurtenance such as a metal cold water pipe that has an uninterrupted path to the earth.

Some people attach the adapter to the cover plate with the plate screw, assuming this "grounds" the adapter. This is only the case if the receptacle is bonded to a metal box which is grounded, and that is rarely true in a home with 2-prong receptacles.
Comment: Running the grounding conductor to *earth*, does not provide an effective fault current path. Without the fault current path, the breaker will not clear the fault. The grounding conductor must provide a low impedance path back to the *source*, not the *earth*.
Comment: @Iggy I was commenting on this statement "*that has an uninterrupted path to the earth.*".  You don't need a path to **earth**, you need a path to the **source**.
Comment: @Iggy, the earth has NOTHING to do with breakers tripping and clearing faults. The term "ground" is erroneous when it comes to equipment grounding. We call it ground, but it has NOTHING to do with the dirt ground outside. All "grounds" are NOT "direct paths to the earth".  Equipment grounds are direct paths back to THE SOURCE, as Tester101 correctly pointed out.
Comment: @Iggy I think you misunderstand how circuit breakers work, how the grounding system works, and how ground-faults work.
Comment: @Iggy It doesn't care where ground is, it cares about resistance. If your path to ground is high resistance, it can easily have a fault and NOT draw enough current to trip a breaker.
Comment: @Iggy If you have a ground-fault, and no effective fault current path. You'll be crispy bacon before the breaker trips.  Don't believe me, try this: Cut the female end off an extension cord, and expose the hot wire.  Plug in the cord, and carefully take the other end outside.  Now stick the exposed hot wire into the ground.  Does the breaker trip?
Comment: Maybe you need a path to the source for the breaker to trip; that's for fire protection. **Any** available current path to *earth* that has less resistance than a human body will provide some fault current protection for the human who happens to get in the way.
Comment: That's why you provide a current path to **earth** for your antenna, no path to the "source" of the lightning that strikes it.
Comment: Interesting conversation and the group has covered just about everything. A low impedance path back to the source is the purpose of the equipment ground. The only small thing I would add is that the earthing or grounding of an electrical system does have something to do with the "dirt". That is how it got its name. The reason for bonding the equipment grounding system together and then grounding it, is to equalize the voltage potential between all the metal parts and piping systems in a building with each other AND that of the earth around it. It isn't for the operation of the OCPD.
Comment: Hey, I was just going to warn him that people around here think the Circuit Breaker cares where ground is or it won't trip.
Comment: @GrantOh I know & Jimmy had it right. But boy, I tried to explain it here & I got massacred twice. People here, apparently, think a ground has to go through the panel only because if the CB can't see it, then it'll just plain refuse to trip.
Comment: @Tester101 I never said that & Jimmy here didn't say that. We both said to do a proper ground & the CB will do it's thing no problem & that doesn't mean for the whole panel or only from or to the panel. An individual circuit or even outlet will have the same exact perfect CB result.
Comment: I think you misunderstand. All grounds are a direct path to the earth...this discharge is what registers with the CB in order to trip. Only if the CB were replaced with a non-intelligent Fuse would the ground to earth then be pointless & useless. The CB is what makes the grounding to earth effective.
Comment: Then, please explain it. I haven't been in chat yet, so I might need some instruction to get in.

Electrical outlet