text:
Q: What does the error "resolve() got an unexpected keyword argument 'replace_conflicting'" mean? When I update certain packages in my Python installation using pip I get
TypeError: resolve() got an unexpected keyword argument 'replace_conflicting'

I get this error for certain packages and not others, and have asked about ways to work around it (ideally while continuing to use pip) in the specific cases where I encounter it; but the question here is what the error means in the first place and what might be the likely cause.
What does this error mean and what could be causing it?

Downloading/unpacking xattr
  Downloading xattr-0.7.5.tar.gz
  Running setup.py (path:/private/tmp/pip_build_root/xattr/setup.py) egg_info for package xattr
    Traceback (most recent call last):
      File "<string>", line 17, in <module>
      File "/private/tmp/pip_build_root/xattr/setup.py", line 67, in <module>
        cmdclass={'build': cffi_build},
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 112, in setup
        _setup_distribution = dist = klass(attrs)
      File "/Library/Python/2.7/site-packages/setuptools/dist.py", line 239, in __init__
        self.fetch_build_eggs(attrs.pop('setup_requires'))
      File "/Library/Python/2.7/site-packages/setuptools/dist.py", line 264, in fetch_build_eggs
        replace_conflicting=True
    TypeError: resolve() got an unexpected keyword argument 'replace_conflicting'
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

  File "<string>", line 17, in <module>

  File "/private/tmp/pip_build_root/xattr/setup.py", line 67, in <module>

    cmdclass={'build': cffi_build},

  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 112, in setup

    _setup_distribution = dist = klass(attrs)

  File "/Library/Python/2.7/site-packages/setuptools/dist.py", line 239, in __init__

    self.fetch_build_eggs(attrs.pop('setup_requires'))

  File "/Library/Python/2.7/site-packages/setuptools/dist.py", line 264, in fetch_build_eggs

    replace_conflicting=True

TypeError: resolve() got an unexpected keyword argument 'replace_conflicting'

A: This is caused by having two different versions of setuptools: one in /System/Library/Frameworks/Python.framework/Versions/2.7 and another in /Library/Python/2.7/site-packages. Somehow, setuptools.dist.Distribution.fetch_build_eggs in  the newer version calls pkg_resources.working_set.resolve from the older version. The old version of resolve doesn't support the replace_conflicting argument.
On my OS X Lion machine, I was able to fix the problem like this:
$ sudo python /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/easy_install.py -U setuptools
$ sudo easy_install -U pip

That is, I used the old version of easy_install to upgrade easy_install and then used that to upgrade pip.
This fixed the problem on my system because it modified sys.path so that the new version of pkg_resources under /Library/Python loaded before the old version which can still be found under /System/Library/Frameworks. An alternative workaround might be to modify sys.path temporarily using the PYTHONPATH environment variable, see the Python manual.


text:
Q: Linux PCIe Endpoint Link Status or Log? Is there a way to view the link status or other information that would give information on the overall status of the connection of a Linux host in endpoint mode?
To clarify, I have a Jetson set to be the endpoint, this is confirmed to be working by using lspci in another Jetson as root port and am able to transfer data. The next step is to connect an FPGA in root port mode to the endpoint Jetson. I need a way, from the Linux endpoint side, to check that a link and/or communication has been established to the FPGA.
I have looked in dmesg and kern.log and all the various entries in /sys and couldn't find anything that gives the info I'm looking for. Something like lspci but for the endpoint side would be ideal.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scrape This Field My code goes into this website and scrapes a field.
The field I want to get is in the right hand side of the page, (the name of the speaker)
The code navigates to the site. I obtained the xpath, and placed it in the code. Yet the output prints blank.
How do I get it to print the speakers name?

from selenium import webdriver
from bs4 import BeautifulSoup
import time

driver=webdriver.Chrome()
url='https://meetinglibrary.asco.org/record/193286'
driver.get(url)
time.sleep(5)

speaker=driver.find_element_by_xpath('/html/body/div[3]/div/main/div/div/div/ml-root/ng-component/ml-record/ml-video/div[2]/div/div/div[2]/div[2]/div[1]/a').text.strip()
print(speaker)

A: The data is loaded from external source via JavaScript. You can use this example how to load the data via requests module:
import json
import requests

url = "https://meetinglibrary.asco.org/record/193286"
api_url = "https://ml-couch.asco.org/records/{id}"
id_ = url.split("/")[-1]

data = requests.get(api_url.format(id=id_)).json()

# uncomment this to print all data:
# print(json.dumps(data, indent=4))

print(data["Role"], data["FullName"])

Prints:
Speaker Marcia Cruz-Correa, MD, PhD


text:
Q: Система отправки почты Здравствуйте, у меня в общем такой вопрос, как правильно отпровлять письмо
в оригинальном коде у гугла написано "Dile*** to: 123@123.ru" А во всех примерах отправки почты просто "To: 123@123.ru"... так как же все-таки правильно :)
A: чет я первый вариант не понял, но правильно отправлять
To: 123@123.ru


text:
Q: Dataset for training text classifier I'm new to data mining and I am trying to build a classifier that is able to classify student theses abstracts into a predefined set of categories under the area of Computer Science, e.g. Machine learning, Image Processing...etc.
I do not have enough classified abstracts to be used as a training dataset so would you please direct me to a dataset that can be used for this particular purpose.

A: You can use the DBLP data (downloadable from http://dblp.uni-trier.de/xml/) to generate a list of publications. Based on conferences/journal you can generate your classes e.g. MLJR is alway Machine Learning.
The abstracts you can acquire using:
https://github.com/arc12/Text-Mining-Weak-Signals/blob/master/Abstract%20Acquisition%20Scripts/DBLP%20XML%20fetch%20abstracts%20.pl


text:
Q: Is there an official list of Doctor Who Companions? Some of the people the Doctor travels with are obviously Companions with a capital C (Rose, Donna, Clara, etc.). For others, it's not so clear whether they count as Companions or just people he picks up for a while, e.g. Jack Harkness, Ashildr, and (in New Who) Sarah Jane. I've seen River Song and Adam Mitchell included in some lists of Companions but not in others. Then there are various people who turn up to have a single adventure with the Doctor for a Christmas special and are never seen again.
Is there an 'official' list of Companions?
Can we say canonically, by any definition of canon, that these characters are Companions and those characters aren't? Or are all the different possible lists of Companions, some much longer than others, equally valid?
Answers based on either New Who or Old Who will be welcomed, if the situation differs between one and the other.

A: Despite canon not really being a concept in Doctor Who, there's generally broad agreement over who "counts" as a Companion. The areas of contention are usually around the short-term companions, and how to distinguish between them and guest actors. The line isn't always so clear.
The closest thing to an "official" word is this list of classic Who companions posted on the BBC website, or this list of all companions. In the interests of archiving (with asterisks next to the contentious ones):
First Doctor

*

*Susan Foreman

*Ian Chesterton

*Barbara Wright

*Vicki

*Steven Taylor

*Katarina

*Sara Kingdom*

*Dodo Chaplet

*Polly

*Ben Jackson

Second Doctor

*

*Jamie McCrimmon

*Victoria Waterfield

*Zoe Heriot

Third Doctor

*

*Brigadier Sir Alistair Gordon Lethbridge-Stewart

*Liz Shaw

*Jo Grant

*Sergeant Benton*

*Captain Mike Yates*

*Sarah Jane Smith

Fourth Doctor

*

*Harry Sullivan

*Leela

*K-9

*Romana (two regenerations)

*Adric

*Nyssa

*Teagan Jovanka

Fifth Doctor

*

*Vislor Turlough

*Kamelion*

*Peri Brown

Sixth Doctor

*

*Mel Bush

Seventh Doctor

*

*Ace

Eighth Doctor

*

*Grace Holloway

Ninth Doctor

*

*Rose Tyler

*Mickey Smith

*Jack Harkness

Tenth Doctor

*

*Martha Jones

*Donna Noble

*Wilfred Mott*

Eleventh Doctor

*

*Amy Pond

*Rory Williams

*River Song

*Clara Oswald

Twelfth Doctor

*

*Bill Potts

*Nardole

Controversies
I asterisked a few names up there; why did I do that?

*

*Sara Kingdom is not always considered a companion; she was very briefly connected to the Doctor, following him purposefully (rather than getting trapped on the TARDIS, which is how he normally meets girls), with a mission to complete, and then dies. Narratively, she had more in common with a guest actor than with a companion

*Sergeant Benton never travelled on the TARDIS, although he did enter it in The Three Doctors, which is more than Captain Yates can say. He's mainly included because the Third Doctor's run didn't involve much TARDIS travel, and Benton was part of the UNIT ensemble cast

*Mike Yates see above

*Although Kamelion fits most reasonable definitions of "companionship", because of technical difficulties with the puppet he only appeared in two episodes: his introduction, and his destruction (and one more, through the magic of archive footage). Though he got somewhat fairer treatment in the novels, you could also make a plausible argument for leaving him off

*Wilfred Mott was an Earth-based recurring character in series 4, but he's not really considered a companion until the two-part "The End of Time"; in that regard he bears more in common with Christmas special one-off "companions", so it feels slightly unfair to count him without counting them

Omissions

*

*In the Night of the Doctor minisode, the Eighth Doctor rattles off a list of names before declaring them "companions" (emphasis mine):

Doctor: Get out. Get out! All of you. Will it hurt?
Ohila: Yes.
Doctor: Good. Charley, C'Rizz, Lucie, Tamsin, Molly. Friends, companions I've known, I salute you. And Cass, I apologise. Physician, heal thyself.
Doctor Who Minisode "The Night of the Doctor"

These characters (except for Cass) never appeared on-screen; they were introduced in the Big Finish audios, which is probably why they weren't in the companion list.
Whether or not you consider Cass a companion is another open question.

*Adam Mitchell, from "Dalek" and "The Long Game"1 is also omitted. Whether or not you consider him a companion is, again, up to you

*Handles, the Cyberman head the Doctor was carrying around in "The Time of the Doctor"

*What about the TARDIS herself? She's been established as (at least) semi-aware since "The Edge of Destruction" in 1964, and has appeared in just about every episode

*The BBC list is notable for not including one-off characters from, among other things, new-Who Christmas specials. It's mainly up to you if you consider these characters to be companions. They serve the same narrative function, but they're also just guest actors

*

*Astrid Perth ("Voyage of the Damned")

*Jackson Lake ("The Next Doctor")

*Christina de Souza ("Planet of the Dead")

*Adelaide Brooke ("The Waters of Mars")

*The Arwells ("The Doctor, the Widow and the Wardrobe")

*Kazran Sardick and Abigail ("A Christmas Carol")

*Craig Owens ("The Lodger" and "Closing Time")

As I mentioned above, Wilf kind of deserves to be on this list; although he has several appearances, he's only ever on the TARDIS in a single (two-part) episode. Though I haven't gone through and checked, I believe he spent less time on the TARDIS than Jackie Tyler did, so make of that what you will.
Definitions
The simplest definition of a companion is this:

Companion. n. Someone who travels with the Doctor on the TARDIS

But it's not a perfect definition:

*

*It includes a broad class of people who we wouldn't normally consider companions; Rigsy, for example

*It excludes some people who we normally would consider companions, like Liz Shaw and Grace Holloway

*It cuts right down the middle on one-off characters. Adelaide Brooke and Kazran Sardick are in; Astrid Perth and Christina de Souza are out.

Okay, let's try a different one:

Companion. n. A character, other than the Doctor, played by an actor whose name appears in the opening credits.

This definition works well enough for the new series (though it excludes Adam, and possibly others), which has had a pretty consistent opening credit scene ("Sleep No More" notwithstanding), but less effective for the old series; the character credits for the old series normally went after the episode, with only the writing credit appearing at the start.
Maybe you could tweak it slightly:

Companion. n. A character, other than the Doctor, played by an actor who gets independent billing in the credits.

A little better, but I picked a random episode from my library and checked the credits; look who this definition includes:

We can't have some upstart Sontaran trying to muscle in on companionship2. That won't work either.
You could make the argument that the companion is meant to be an audience surrogate character, the person who gets technobabble explained to them and who enforces a human morality for audiences to connect with. That's fair enough, I guess, although I'm not sure I'd agree that's a good definition. For the sake of argument, though, that largely excludes Captain Jack, Nardole, and (arguably) River and K-9.
This is starting to give me a headache.
As with most things in Doctor Who canon, a companion is whatever you say it is

1 Nod to Josh for reminding me; Adam was so unremarkable that I completely forgot about him
2 Oh, hello Strax. I didn't see you there


text:
Q: Reading a caller's IP address in WCF (OperationContext is null)? I am validating users using the UserNamePasswordValidator.Validate(string username, string password) and the service is hosting itself (e.g. no IIS).
The problem I have is that if the user fails the validation I want to track the users IP address. This works fine of the user gets validated, because then the OperationContext has been initialized (it is null inside the validate method and not created until later).
Does anyone know how to get the clients IP address either in the validate method or before the validate method has been executed?
Yes, I know about how to get the IP address using RemoteEndpointMessageProperty but like I said, it never get that far if validation fails :-)

A: I've researched this to death all week, and I can't come up with a single blog entry or MSDN article that deals with the issue.
As far as I can tell, you cannot log IP address during the Validate stage.
The only workaround I can suggest is to host in IIS and use the weblogs there, which do log IP address. It's painful, unfortunately, but it may be the only way.

A: If you're hosting in IIS then this becomes much more simple. This chunk of config comes straight from my hosting web project and forces ASP.NET requests to come down the IIS pipeline rather than being dispatched straight to the ASP err bits of IIS.
aspNetCompatibilityEnabled: When this attribute is set to
 true, requests to Windows Communication Foundation (WCF) services
 flow through the ASP.NET HTTP pipeline, and communication over
 non-HTTP protocols is prohibited.
See:    http://msdn.microsoft.com/en-us/library/ms731336.aspx
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

I use the AuthenticationService and make use of the HttpContext to get at all the interesting stuff about the client, much of it is useful for things like ensuring a user isn't logging in from six different subnets as well as playing around with cookies.
Although I think this is applied to the MS AuthenticationService, any other services you have will need this attrib:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
If you want to pursue your non-IIS hosted service route, then I'd see what stuff is available inside the MS API using reflection, poking around on a WCF with the debugger while stopped, unfolding all those Non-public members.
I suppose the problem will be getting a reference to a bit of WCF which is initialized from which to start poking. You might have to register some kind of listener to one of the dispatchers when you setup the service host.
http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.channeldispatcher.aspx
Edit:
Adding this link as my thoughts are that you'd need to get at stuff in WCF that's right down the stack before it gets to your code:
http://blogs.msdn.com/sonuarora/archive/2007/06/11/passing-soap-actions-to-adapter-inbound-handler-for-filtering-type-of-listeners.aspx


text:
Q: Surpress Observer in PHP I am working on a pair of services that will update two systems through REST API calls. The first is for location 1, executing update calls on classes that make use of the observer pattern in php, to trigger an update service. This update service then executes the API call to update location 2.
When location 2 gets an update it will also execute a series of updates. These updates will trigger API calls to location 1.
My problem is that this will continue if I don't terminate it at one end. The easiest way I can think to do that is to suppress the Observer in some way. Is there an easy way to do this? Or for that matter is there a better solution to my problem?


text:
Q: Can't figure out why my the Instagram pictures are not appearing with Instafeed? I'm using Instafeed. I can't figure out why nothing is appearing on the website. I'm helping someone with their blog and they generated their access token.
This is the code I have. Everything is at the end of the body tag. I blocked out the Access Token and the User Id, I heard this info should be shared.

A: Avoid using single quotes inside and outside the same Javascript string.
Try this with double quotes out, and single quotes in:
var feed = new Instafeed({
    get: 'user',
    userId: *********,
    limit:5,
    sortBy:'most-recent',
    accessToken:'*********************',
    template:"

{{likes}}
{{comments}}

",
    resolution:'standard_resolution';
});
feed.run();


text:
Q: eclipse: java.lang.UnsatisfiedLinkError I'm working on javacv project but every time I try to declare a matrix as below:
Mat trainingData = new Mat();

I get this error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: org.opencv.core.Mat.n_Mat()J
at org.opencv.core.Mat.n_Mat(Native Method)
at org.opencv.core.Mat.<init>(Mat.java:447)

And when i search for a solution, i always found that i have to add:
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

But i'm always having the same error.

A: The UnsatisfiedLinkError is thrown at runtime when an application attempts to load a native library and that library does not exist.
It sounds like something went wrong when attaching your library or your library was not set up correctly in your IDE.
See: http://docs.opencv.org/doc/tutorials/introduction/java_eclipse/java_eclipse.html#java-eclipse


text:
Q: How to erase last char in console using backspace, without using space char? I'm trying to implement a console program that has backspace functionality. The console accepts a number of valid commands I've defined. Example:
Input:

Output:

I'm using a switch statement, which checks the current char returned by getchar().
    switch (inChar)
    {
        case '\r':
        case '\n':
        {
            ...
        }

        case 0x18:                      // ^x
        {
            ...
        }

        case 0x08:                     // backspace
        {
            printf("\b \b");
            break;
        }

        default:
        {
            inBuffer[inBufIndx++] = inChar;
            inBuffer[inBufIndx] = 0;
            printf("%c", inChar);       // echo character
        }
    }

The code above gives the appearance of erasing the character, but places a space char. This works for most instances, such as erasing the o off of helo but does not work when erasing the o off helpo. My shell can no longer interpret the command due to the space char that is printed in the place of the o
How can I implement backspace for chars at the end of the inputthat need to be erased?
EDIT: rici is exactly right. I was not removing the char I erased in the console from my inBuffer. The code below gave the desired functionality.
        case 0x08:
        {
            printf("\b \b");
            inBuffer[inBufIndx--] = NULL;
            break;
        }

A: Presumably, you need to remove the character from inBuffer (by decrementing inBufIdx and overwriting the old character with a 0). What the screen shows should be irrelevant.
By the way, the backspace-space-backspace sequence won't work at the right margin

A: @Eugene Sh. answer worked for me, but just without the round braces in my tcsh shell:
printf "\b"


text:
Q: django.db.utils.IntegrityError:
django.db.utils.IntegrityError: The row in table 'main_tutorial' with primary key '1' has an invalid foreign key: main_tutorial.tutorial_series_id contains a value 'tutorial_series_id' that does not have a corresponding value in main_tutorialseries.id.

The above error shows up and cant migrate
These are my models:
    from django.db import models
    from datetime import datetime
    #Create your models here.

    class TutorialCategory(models.Model):
        tutorial_category = models.CharField(max_length=200)
        category_summary = models.CharField(max_length=200)
        category_slug = models.CharField(max_length=200, default=1)

        class Meta:
            #Gives the proper plural name for admin
            verbose_name_plural = "Categories"

        def __str__(self):
            return self.tutorial_category

    class TutorialSeries(models.Model):
        tutorial_series = models.CharField(max_length=200)
        tutorial_category = models.ForeignKey(TutorialCategory, default=1,verbose_name="Category", on_delete=models.SET_DEFAULT)
        series_summary = models.CharField(max_length=200)

        class Meta:
            #Otherwise we get "Tutorial Serie*ss* in admin"
            verbose_name_plural = "Series"

        def __str__(self):
            return self.tutorial_series

    class Tutorial(models.Model):
        tutorial_title = models.CharField(max_length=200)
        tutorial_content = models.TextField()
        tutorial_published = models.DateTimeField("date published", default = datetime.now())
        tutorial_series = models.ForeignKey(TutorialSeries, default=1, verbose_name="Series", on_delete=models.SET_DEFAULT)
        tutorial_slug = models.CharField(max_length=200,default=1)

        def __str__(self):
            return self.tutorial_title

A: You can simply delete all the objects in the main_tutorial table from django shell:

*

*goto command prompt

*python manage.py shell

*from main.models import Tutorial

*Tutorial.objects.all().delete()
(main being the app name here)
This will delete all the objects in the Tutorial table and then makemigrations and migrate and it should work just fine.

A: In your Tutorial model, you are using a default value for the foreign key field ** tutorial_series **. This causes the migration to check if a record in TutorialSeries exists with id=1 but there is no such data present, so the error is occuring.
To avoid the error while migrating, remove the on_delete=models.SET_DEFAULT and default=1 from our fields to make your models as:
class TutorialSeries(models.Model):
    tutorial_series = models.CharField(max_length=200)
    tutorial_category = models.ForeignKey(TutorialCategory,verbose_name="Category")
    series_summary = models.CharField(max_length=200)

    class Meta:
        #Otherwise we get "Tutorial Serie*ss* in admin"
        verbose_name_plural = "Series"

    def __str__(self):
        return self.tutorial_series

class Tutorial(models.Model):
        tutorial_title = models.CharField(max_length=200)
        tutorial_content = models.TextField()
        tutorial_published = models.DateTimeField("date published", default = datetime.now())
        tutorial_series = models.ForeignKey(TutorialSeries, verbose_name="Series", blank=True, null=True) #<--changes
        tutorial_slug = models.CharField(max_length=200,default=1)

        def __str__(self):
            return self.tutorial_title

After this, migrate your models. Then add data to TutorialCategory and TutorialSeries with id=1.
Then revert your models to your initial setup (keeping default=1 and on_delete=models.SET_DEFAULT). Then again run makemigrations and migrate your models. After this, your problem might be solved.

A: Try to delete all the migration files exept __init__.py and also delete db.sqlite3. After that run makemigrations and migrate again

A: I faced the same problem just I am also working with the same. All you got to do is to

just delete "migrations" folder from the "main()" and also the db.sqlite file too.
The error is probably occurring because we have Tutorial already in db
which is not linked to TutorialSeries so.., to make it linked to the
db, make the changes above and then again perform commands.

What I got was:
python manage.py makemigrations

Output:
No changes detected

Next one
python manage.py migrate

Output:
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying sessions.0001_initial... OK

Make sure while performing these commands you have linked Tutorial
with TutorialSeries. And guys making things done this way makes you earlier data lost from the database. Be careful about that.

Have a Nice day & happy coding.

A: Try using on_delete = models.CASCADE without a default parameter.

A: I was dealing with the same issue. I deleted everything inside migrations except _init__.py and also the sqlite database. Then ran- py -3.7 manage.py makemigrations, then after that, py -3.7 manage.py migrate. Then it worked!

A: I had this issue a while ago.
The above answer maybe correct but it didnt work for me because
-im using postgres, i cant just delete the database
-migration files were commited in git.
My situation was, I have 004 migration file but i cant run it because of IntegrityError.
I checked the file, and i saw it was in operation list.
The first item of list is migrations.CreateModel and the second was migrations.AddField
here are my steps:

*

*I commented the second item in list, only the CreateModel is remaining.

*then run the migrate

*open the django admin page and add it manually the missing id
you can add it also in database editor or update statement.

*uncomment the AddField section and rerun the migrate.

A: from django.db import models
from datetime import datetime

class TutorialCategory(models.Model):
    tutorial_category = models.CharField(max_length=200)
    category_summary = models.CharField(max_length=200)
    category_slug = models.CharField(max_length=200)

    class Meta:
        verbose_name_plural = "Categories"

    def __str__(self):
        return self.tutorial_category

class TutorialSeries(models.Model):
    tutorial_series = models.CharField(max_length=200)
    tutorial_category = models.ForeignKey(TutorialCategory, verbose_name="Category", on_delete=models.CASCADE, blank=True, null=True)
    series_summary = models.CharField(max_length=200)

    class Meta:
        verbose_name_plural = "Series"

    def __str__(self):
        return self.tutorial_series

class Tutorial(models.Model):
    tutorial_title = models.CharField(max_length=200)
    tutorial_content = models.TextField()
    tutorial_published = models.DateTimeField('date published', default=datetime.now)

    tutorial_series = models.ForeignKey(TutorialSeries, verbose_name="Series", on_delete=models.CASCADE, blank=True, null=True)
    tutorial_slug = models.CharField(max_length=200, default=1)

    def __str__(self):
        return self.tutorial_title

Try this, it's work for me.
But remember, you will need to type this code before you have done "python3 manage.py makemigrations" and "python3 manage.py migrate"

A: The following answer was been posted on the Django tutorial comments of sentdex by nice folks namely: "Kevin di" and "JOSEPH Blessingh". The recommendation helped me and worked like charm:
There is a file  " db.sqlite3 " in your working directory, you can open it with any database management tools that supports SQLite type.
following the steps:

*

*For example, " DB Browser for SQLite ", you can Google and download it.

*Opening the " db.sqlite3 " file, navigate to the  Tables.

*Find the main_tutorial table. (Maybe you used another table name in the previous lessons, use your table name.)

*Delete record from the table: main_tutorial.

*Try python manage.py migrate again.

The meaning of Delete Record from the table can be explained as:
- Click main_tutorial
- Then you might see a tab with the name Browse Data
- Click it and you will see your records
-  Press Ctrl + Left Mouse button on the number on the left hand side column to select all the rows
- Delete them using right click


text:
Q: Create a link in backend to a frontend page I would link to create a link to a frontend page inside a backend module.
Using:
<f:link.page pageUid="40" >Link</f:link.page>

Doesn't work. It generates a link to the current backend module.
Any solution ?

A: This is a very long story but the gist is: it is not possible to create FE links in BE/CLI context without a lot of workarounds and dummy objects/values.
If possible you should use solutions like pagepath which generate URLs for an eID script which performs the actual URL generation on demand.

A: Since TYPO3 v9 you can use the following lines of code:
use TYPO3\CMS\Core\Site\SiteFinder;
use TYPO3\CMS\Core\Site\Entity\Site;
use TYPO3\CMS\Core\Routing\PageRouter;

$siteFinder  = GeneralUtility::makeInstance(SiteFinder::class);
$site = $siteFinder->getSiteByPageId($pageId);
$router = $site->getRouter();
$frontendUrl = (string) $router->generateUri($pageId);

Thanks to Benni Mack @ TYPO3Camp Mitteldeutschland


text:
Q: refering to Templates c++ Considering Template Class
when do we have to refer explicitly to template, and when the compiler "understands that we meant it"
considering the following occurences:
1) function return value & arguements
2) variable declaration inside function
3) namespace SomeClass<T>:: vs. SomeClass::
Is there any rule? I saw sometimes the use is of:
SomeClass

and sometimes: SomeClass<T>
and I didn't get the rule

A: Class template parameters may only be omitted inside the implementation of that class, where they implicitly add the appropriate template specifiers to the class and when referring to a non-dependent base class (non-dependent as in "does not reuse any template arguments"). For example:
template<typename T, typename U>
class C { /* here C is the same as C<T, U> */ };

template<typename T>
class C<void, T> { /* here C is the same as C<void, T> */ };

template<>
class C<void, void> { /* here C is the same as C<void, void> */ };

template<typename> struct Base { };

struct DerivedA : Base<void>
{ /* here Base is the same as Base<void> */ };

template<typename T>
struct DerivedB : Base<T>
{ /* here Base is invalid, since Base<T> depends on a template argument */ };

Function templates may have their template parameters omitted, if they can be deduced from their arguments:
template<typename T>
void f(T f);

f(3); // equivalent to f<int>(3) if no other overload exists

Additionally, there are default template arguments, which leads to something really funky:
template<typename T = void>
class D
{
    // Here D is D<T>, but D<> is D<void> instead!
};

A: The standard describes all scenarios in [temp.local]:

*

*Like normal (non-template) classes, class templates have an injected-class-name (Clause 9). The injected-class-name can be used as
  a template-name or a type-name. When it is used with a
  template-argument-list, as a template-argument for a template template-parameter, or as the final identifier in the
  elaborated-type-specifier of a friend class template declaration, it refers to the class template itself. Otherwise, it is equivalent to
  the template-name followed by the template-parameters of the class
  template enclosed in <>.

*Within the scope of a class template specialization or partial specialization, when the injected-class-name is used as a type-name,
  it is equivalent to the template-name followed by the
  template-arguments of the classtemplate specialization or partial
  specialization enclosed in <>.
[ Example:
template<template<class> class T> class A { };
template<class T> class Y;
template<> class Y<int> {
  Y* p;                             // meaning Y<int>
  Y<char>* q;                       // meaning Y<char>
  A<Y>* a;                          // meaning A<::Y>
  class B {
    template<class> friend class Y; // meaning ::Y
  };
};

—end example ]

This only works inside the class template (i.e. the scope of the injected-class-name), and only if the name is accessed from a corresponding scope:

When the normal name of the template (i.e., the name from the
  enclosing scope, not the injected-class-name) is used, it always
  refers to the class template itself and not a specialization of the
  template. [ Example:
template<class T> class X {
  X* p;             // meaning X<T>
  X<T>* p2;
  X<int>* p3;
  ::X* p4;         // error: missing template argument list
                   // ::X does not refer to the injected-class-name
};

—end example ]

And for base classes, where the base is not dependent:

A lookup that finds an injected-class-name (10.2) can result in an
  ambiguity in certain cases (for example, if it is found in more than
  one base class). If all of the injected-class-names that are found
  refer to specializations of the same class template, and if the name
  is used as a template-name, the reference refers to the class
  template itself and not a specialization thereof, and is not
  ambiguous.  [ Example:
template <class T> struct Base { };
template <class T> struct Derived: Base<int>, Base<char> {
  typename Derived::Base b;             // error: ambiguous
  typename Derived::Base<double> d;     // OK
};

—end example ]

We can modify the example slightly to show what would be valid:
template <class T> struct Base { };
template <class T> struct Derived: Base<char> {
  typename Derived::Base b;             // Ok: b refers to Base<char>
};


text:
Q: How to fill missing value with different ways in python? I have a dataset that has a number of numerical variables and a number of ordinal numeric variables. to fill missing value  I want to  use mean for numerical variables and use the median for the ordinal numeric variables. With the following code, each of them is created separately and is not collected in a database.
df = [['age', 'score'],
 [10,1],
 [20,""],
 ["",0],
 [40,1],
 [50,0],
 ["",3],
 [70,1],
 [80,""],
 [90,0],
[100,1]]

df = pd.DataFrame(data[1:])
df.columns = data[0]

df = df[['age']].fillna(df.mean())
df = df[['score']].fillna(df.median())

A: pandas.DataFrame.fillna accepts dict with keys being column names, so you might do:
import pandas as pd
data = [['age', 'score'],
 [10,1],
 [20,None],
 [None,0],
 [40,1],
 [50,0],
 [None,3],
 [70,1],
 [80,None],
 [90,0],
[100,1]]

df = pd.DataFrame(data[1:], columns=data[0])

df = df.fillna({'age':df['age'].mean(),'score':df['score'].median()})
print(df)

output
     age  score
0   10.0    1.0
1   20.0    1.0
2   57.5    0.0
3   40.0    1.0
4   50.0    0.0
5   57.5    3.0
6   70.0    1.0
7   80.0    1.0
8   90.0    0.0
9  100.0    1.0

Keep in mind that empty string is different than NaN, latter might be created using python's None.

A: First replace empty strings to missing values and then replace mising values per columns:
df = df.replace('', np.nan)
df['age'] = df['age'].fillna(df['age'].mean())
df['score'] = df['score'].fillna(df['score'].median())

print (df)
     age  score
0   10.0    1.0
1   20.0    1.0
2   57.5    0.0
3   40.0    1.0
4   50.0    0.0
5   57.5    3.0
6   70.0    1.0
7   80.0    1.0
8   90.0    0.0
9  100.0    1.0

You can also use DataFrame.agg for Series of aggregate values and pass to DataFrame.fillna:
df = df.replace('', np.nan)

print (df.agg({'age':'mean', 'score':'median'}))
age      57.5
score     1.0
dtype: float64

df = df.fillna(df.agg({'age':'mean', 'score':'median'}))
print (df)
     age  score
0   10.0    1.0
1   20.0    1.0
2   57.5    0.0
3   40.0    1.0
4   50.0    0.0
5   57.5    3.0
6   70.0    1.0
7   80.0    1.0
8   90.0    0.0
9  100.0    1.0


text:
Q: How do I make UITableViewCells same height on iPhone 6/6 plus? My current app uses a UITableView, where I use the heightForRowAtIndexpath method to return the same height for every cell.
When I tried the Yo app, the height was the same on both a 4s and a 6 plus, just wider (obviously). However in my app, the rows got "taller" when I tried it on the 6 plus. How do I keep the heights the same. This also extends to other UI elements. All buttons etc, are all taller/wider despite being statically defined (in an amount of pixels as opposed to the percentage of the screen).

A: Problem is that you don't support new iPhones sizes in xcode. You need to add new launch images for iPhone 6 and iPhone 6Plus. In xcode Image.xcassets, find you launch images. Select images for iOS 8, You should see image placeholders for Retina HD 5.5 and Retina HD 4.7. When you add those images your app will no longer scale to fit the screen on new iPhones.
(You may also use xib to render splash screen as dasdom suggested.)


text:
Q: How do I fix "Permission denied" when I try to run an external Perl script? system("logscr.ply ");

The error I get is this:
Can't exec "logscr.ply": Permission denied at eal.ply line 3

Why am I getting the error, and how do I fix it?

A: Without knowing any more details, there could be a variety of reasons:

*

*Your example code states you're trying to execute "logscr.ply ". The space character at the end might be parsed as part of the file name. This should yield a file-not-found error, though.

*The protection bits for the called script might not allow for direct execution. Try chmod u+x logscr.ply from your command prompt.

*The folder containing logscr.ply might not be accessible to you. Make sure you have both read and execute permission on it (try chmod u+r,u+x folder-name).

*The called script might not recognize itself as a Perl script, try system("perl logscr.ply");.

*There might be a file with the same name somewhere earlier in your $PATH. Use absolute paths in your call to prevent this (system("perl /some/path/logscr.ply");), don't rely on your $PATH variable.

A: What platform/OS is this?
Probably logscr.ply just does not have execute permissions set. On Linux/Unix e.g. you should do
chmod u+x logscr.ply

then try again.
Note: This assumes you are the owner of logscr.ply. If not, adjust accordingly.


text:
Q: capturing `echon` messages displayed from `job_start()` I am writing some tests for a Vim plugin to ensure that certain behavior is done correctly. This plugin uses echon in addition to echohl to display messages.
Is there any native VimScript command I can use to detect what is currently displayed as part of the echon message?
In Vim versions earlier than 8, before the async support, I was able to capture the string from echon by using redir and calling the plugin directly. With Vim 8 and having the plugin using job_start with a handler for close_cb the echon is done asynchronously, and I am no longer able to catch it with redir.
The echon call is simple:
    redraw
    let message = "Unable to parse output. If using a plugin that alters the default output, consider disabling it. See :Pytest session"
    let length = strlen(message) + 1
    hi YellowBar ctermfg=black ctermbg=yellow guibg=#e5e500 guifg=black
    echohl YellowBar
    echon message . repeat(" ",&columns - length)
    echohl

Ideally, I would like to have a way of ensuring that this message is displayed, regardless of the async behavior. I am considering enabling a debug or testing setting to also send the message to echom, but that defeats a bit the purpose of really ensuring that the actual echon is displayed.


text:
Q: Is it possible to devise a subtraction algorithm that does not first compare the inputs? Obviously, any competent programming language has built-in subtraction. However, say you needed to implement a custom subtraction algorithm (say, to handle very large numbers). If you are using the borrowing method, you would have to first compare the inputs to determine if the result will be negative, and if so, you switch the order of the subtraction. I am curious if it is possible to write an algorithm that does not need this comparison/operand swapping?
Further, could such an algorithm be more efficient than compare-first, which in the worst case would have to compare every place value?
*I am aware that one could use complements, but this limits the size of permitted inputs (assuming finite representation size).

A: If you are implementing bignums, then you can combine the comparison and the subtraction so that you only look at each "limb" once, except for one. (The word "limb" comes from the Gnu MP library but it is also used elsewhere to mean the same thing.)
First, you scan from the big end of the longer number until you find a nonzero limb or you reach thr length of the smaller number. In the first case, you know that the longer number is bigger and you also know the position of its most significant limb. (If you have adopted the convention that numbers always have a nonzero most-significant limb then you can skip this step.)
Suppose now that you didn't prove the the longer number is bigger, so you know are at the same position in both numbers. Continue scanning both numbers until you find a difference. At this point, you know which number is bigger and you also know the position of the most significant limb of the larger number.
So now you know which number is bigger, and you can do the normal borrowing algorithm from the low-order ends of the numbers, stopping when you reach the high-order limb which you previously identified.
Since the two scans stop at the same place, you don't look at any limb more than once, exvept the high-order limb which stopped the first scan.

Whether it is actually worthwhile to implement this hack is something you would have to decide. The complication may not be justfiable. But it is possible.


text:
Q: How to send a BufferedReader to JSP page? I'm doing the code below sending a BufferedReader object to a JSP page via setAttribute, but this is not working because in JSP when printing it it just prints the last line of the file. How can I send it to the JSP?
file = new FileReader("C://file.txt");
BufferedReader save = new BufferedReader(file);

while ((sCurrentLine = save.readLine()) != null) {
    request.setAttribute("dfTargetDevice", sCurrentLine);
}

Any help would be very appreciated!

A: The code you posted just keeps setting the dfTargetDevice attribute to whatever it reads, so when it hits the last line that's the value which it stays at. Read all data into a StringBuilder, and set the attribute's value to that.
StringBuilder builder = new StringBuilder();

while ((sCurrentLine = save.readLine()) != null) {
    builder.append(sCurrentLine).append('\n');
}

request.setAttribute("dfTargetDevice", builder.toString());


text:
Q: What is the significance of single and double quotes in environment variables? I defined some environment variables in my .profile like this:
MY_HOME="/home/my_user"

but the variable does not seem to evaluate unless I strip off the quotes and re-source the file.  I believe the quotes are necessary if there will be spaces, and single quotes are used if escapes are not desired.  Can someone clarify the significance of single and double quotes in variable definitions?  How about front-ticks and back-ticks?

A: I think you're confused about terminology.
An "environment variable" is merely a shell variable that any child processes will inherit.
What you're doing in your example is creating a shell variable. It's not in the environment until you export it:
MY_HOME="/home/my_user"
export MY_HOME

puts a variable named "MY_HOME" in almost all shells (csh, tcsh excepted).
In this particular case, the double-quotes are superfluous. They have no effect. Double-quotes group substrings, but allows whatever shell you use to do variable substitution.  Single-quoting groups substrings and prevents substitution. Since your example assignment does not have any variables in it, the double-quotes could have appeared as single-quotes.
V='some substrings grouped together'  # assignment
X="Put $V to make a longer string"    # substitution and then assignment
Y=`date`                              # run command, assign its output
Z='Put $V to make a longer string'    # no substition, simple assignment

Nothing is in the environment until you export it.

A: Shell variables vs. environment variables
MY_HOME="/home/my_user" sets the shell variable called MY_HOME. Shells are programming languages, and have variables (also called parameters). After this assignment, you can use the value of the
variable, e.g. with echo "$MY_HOME".
Shell variables are an internal shell concept. When that shell instance terminates, MY_HOME is forgotten. What every program knows about and transmits to its children is environment variables.
Inside the shell, environment variables and shell variables work in very similar ways. What actually happens is that all environment variables that the shell inherits from its parent become shell variables. Conversely, a shell variable that is defined in a shell script will become an environment variable if you export it.
export MY_HOME="/home/my_user"

More details you can skip on first reading
The reason why shell variables don't automatically become environment variables is partly that a script might accidentally use a variable name that's meaningful to a program that it launches, and partly just historical.
Some very old shells required export to be used each time you changed a variable name, but all modern shells keep track of assignments for environment variables, so that the following snippet echoes bar:
myvar=foo
export myvar
myvar=bar
env | grep '^myvar='

Also, some very old shells required separate commands for myvar=foo and export myvar, but all modern shells understand export myvar=foo.
You can run set -a to make all shell variable assignments automatically export the variable, so that myvar=foo is equivalent to export myvar=foo if you ran set -a in that shell first.
On quoting
Quoting is mostly orthogonal. If the value you're assigning to the variable doesn't contain any characters that are special to the shell, you don't need any quotes. If there are special characters, you need to protect them with single quotes or double quotes or backslashes or a combination thereof. This goes for both the plain myvar=value syntax and the export utility.
There is one difference between the assignment syntax and the export syntax. The shell expands the results of variable substitutions $foo further, performing field (word) splitting and pathname expansion (globbing). This means that if the value of myvar is hello  *, then echo $myvar prints hello followed by a single space followed by the list of files in the current directory. This is almost never desirable, hence the general principle to always use double quotes around variable substitutions (unless you know that you need pathname expansion or field splitting): echo "$myvar". In the case of a simple assignment, othervar=$myvar in fact reliably copies the value of myvar to othervar, because globbing and word splitting are inhibited in assignments (because they create multiple words, but a single word is expected). This dispensation does not apply to export, however. So if you want to remember a simple rule, just always use double quotes around variable substitutions.


text:
Q: JS. Convert format date I have date in this format:
var date:

Fri May 31 2013 17:41:01 GMT+0200 (CEST)

How to convert this to: 31.05.2013
?

A: EDIT: This answer is good if you've to handle dates and times often. Maybe it's what you're looking for. It made my work much easier. It's worth a look. If it's just about this simple task, don't load a new script.
I recomment moment.js: http://momentjs.com/
Simple coded example:
var date = new Date("Fri May 31 2013 17:41:01 GMT+0200 (CEST)");
var date_str = moment(date).format("DD.MM.YYYY");
alert(date_str);

Try it:
http://jsfiddle.net/bvaLt/

A: function convertDate(str){
  var d = new Date(str);
  return addZero(d.getDate())+"."+addZero(d.getMonth()+1)+"."+d.getFullYear();
}

//If we have the number 9, display 09 instead
function addZero(num){
  return (num<10?"0":"")+num;
}

convertDate("Fri May 31 2013 17:41:01 GMT+0200 (CEST)");

A: Without a formatter, go for:
('0' + date.getDate()).slice(-2) + '.' +
('0' + (date.getMonth() + 1)).slice(-2) + '.' +
date.getFullYear()

A: If d is a Date Object (and not a string representing the date) you may use this approach
var d = new Date();

("0" + d.getDate()).slice(-2) + "." +
("0" + (d.getMonth() + 1)).slice(-2) + "." +
d.getFullYear();

otherwise, if you have a string, as a first step just pass it into the Date constructor as argument
var d = new Date("Fry May 31...");


text:
Q: Python3 _io.TextIOWrapper error when opening a file with notepad I am stuck from a couple of days on an issue in my micro Address Book project. I have a function that writes all records from a SQLite3 Db on file in order to open in via OS module, but as soon as I try to open the file, Python gives me the following error:
Error while opening tempfile. Error:startfile: filepath should be string, bytes or os.PathLike, not _io.TextIOWrapper

This is the code that I have to write records on file and to open it:
        source_file_name = open("C:\\workdir\\temp.txt","w")
        #Fetching results from database and storing in result variable
        self.cur.execute("SELECT id, first_name, last_name, address1, address2, zipcode, city, country, nation, phone1, phone2, email FROM contacts")
        result = self.cur.fetchall()

        #Writing results into tempfile
        source_file_name.write("Stampa Elenco Contatti\n")
        for element in result:
            source_file_name.write(str(element[0]) + "|" + str(element[1]) + "|" + str(element[2]) + "|" + str(element[3]) + "|" + str(element[4]) + "|" + str(element[5]) + "|" + \
                str(element[6]) + "|" + str(element[7]) + "|" + str(element[8]) + "|" + str(element[9]) + "|" + str(element[10]) + "|" + str(element[11]) + "\n")

        #TODO: Before exiting printing function you MUST:
        # 1. filename.close()
        # 2. exit to main() function
        source_file_name.close()
        try:
            os.startfile(source_file_name,"open")
        except Exception as generic_error:
            print("Error while opening tempfile. Error:" + str(generic_error))
        finally:
            main()

Frankly I don't understand what this error means, in my previous code snippets I've always handled text files without issues, but I realize this time it's different because I am picking my stream from a database. Any ideas how to fix it?
Thanks in advance, and sorry for my english...

A: Your problem ultimately stems from poor variable naming. Here
source_file_name = open("C:\\workdir\\temp.txt","w")

source_file_name does not contain the source file name. It contains the source file itself (i.e., a file handle). You can't give that to os.startfile(), which expects a file path (as the error also says).
What you meant to do is
source_file_name = "C:\\workdir\\temp.txt"
source_file = open(source_file_name,"w")

But in fact, it's much better to use a with block in Python, as this will handle closing the file for you.
It's also better to use a CSV writer instead of creating the CSV manually, and it's highly advisable to set the file encoding explicitly.
import csv

# ...

source_file_name = "C:\\workdir\\temp.txt"

with open(source_file_name, "w", encoding="utf8", newline="") as source_file:
    writer = csv.writer(source_file, delimiter='|')

    source_file.write("Stampa Elenco Contatti\n")

    for record in self.cur.fetchall():
        writer.writerow(record)

    # alternative to the above for loop on one line
    # writer.writerows(self.cur.fetchall())


text:
Q: Want six instances of command prompt window to be running at any point of time unless all the 100 commands are completed @echo off
setlocal EnableDelayedExpansion
set maxInstances=6
rem Delete all cmd instance files
del cmdInstance?.txt 2>NUL
for /F "tokens=*" %%x in (C:\Users\phare\Desktop\Batch\Post.txt) do (
   rem Mimic commandline
   echo cmd /K "cd Desktop\Batch" ^> %%x BatchStartTime=%date:~7,2%_%date:~3,3%_%date:~10,4%_%time:~0,2%_%time:~3,2%> C:\Users\phare\Desktop\Batch\log.txt
   rem Perform command
   call :WaitForNextInstance
   echo This instance started at !time! > cmdInstance!nextInstance!.txt
   Start "" "cmd /C call %%x & del cmdInstance!nextInstance!.txt"
   echo/
)
goto :EOF
:WaitForNextInstance
rem Review active instances and get the first available one
for /L %%i in (1,1,%maxInstances%) do if not exist cmdInstance%%i.txt set "nextInstance=%%i" & exit /B
echo cmd /K "cd Desktop\Batch" ^>
rem Delay some time (10 seconds in this example) and repeat
ping -n 11 localhost >NUL
goto WaitForNextInstance

A: This topic is interesting! You need that a monitor program continually review the active cmd.exe processes and start the next one when needed. Of course, this program waste some CPU time, so you must carefully choose a delay in the loop that check if one of the six processes ends: if this delay is very short, the monitor process waste a lot of CPU time; if this delay is very large, it may takes too much time between one of the six processes ends and the next one starts.
You may check the number of active cmd.exe instances via tasklist and filter the output, but it is much easier to create a file for each active cmd.exe instance that will be deleted when the instance ends.
EDIT Response to the comments: "incremental execution" and start time and end time of the entire execution added.
@echo off
setlocal EnableDelayedExpansion

rem Delete all cmd instance files
del cmdInstance*.txt 2>NUL

rem Report start time
echo BatchStartTime=%date:~7,2%%date:~3,3%%date:~10,4% @ %time:~0,2%%time:~3,2% > C:\Users\phare\Desktop\Batch\log.txt

rem Set starting number of concurrent instances
set maxInstances=1

for /F "tokens=*" %%x in (C:\Users\phare\Desktop\Batch\Post.txt) do (
   rem Mimic commandline
   echo cmd /K "cd Desktop\Batch" ^> %%x
   rem Perform command
   call :WaitForNextInstance
   echo This instance started at !time! > cmdInstance!nextInstance!.txt
   Start "" "cmd /C call %%x & del cmdInstance!nextInstance!.txt"
   echo/
)

rem Wait for all active instances end
call :WaitAllInstancesEnd
rem Report end time and terminate
echo BatchEndTime=%date:~7,2%%date:~3,3%%date:~10,4% @ %time:~0,2%%time:~3,2% > C:\Users\phare\Desktop\Batch\log.txt
goto :EOF

:WaitForNextInstance
rem Review active instances and get the first available one
for /L %%i in (1,1,%maxInstances%) do if not exist cmdInstance%%i.txt set "nextInstance=%%i" & exit /B
rem Current maxInstances reached: wait for all previous instances end
call :WaitAllInstancesEnd
rem Increment number of maxInstances and repeat
set /A maxInstances+=1
goto WaitForNextInstance

:WaitAllInstancesEnd
rem Check if any instance is still active
set "anyInstance="
for /L %%i in (1,1,%maxInstances%) do if exist cmdInstance%%i.txt set anyInstance=true
if not defined anyInstance exit /B
rem Delay some time (10 seconds in this example) and repeat
ping -n 11 localhost >NUL
goto WaitAllInstancesEnd

Please, post the result...


text:
Q: How to get the selected custom options of a item in wishlist? I need to retrieve the selected custom options of the item in the wishlist. I tried the following code.
$item = Mage::getModel('wishlist/item')->load($wishlist_item_id);

$options = $item->getProductOptions();

//$options = $item->getOptions();
print_r( $options);die();

but it shows empty array. How to retrieve the selected options of the wishlist item?

A: Try this,
<?php
    $wishlist = Mage::getModel('wishlist/wishlist')->load($wishlist_id);
    $items = Mage::getResourceModel('wishlist/item_collection')->addWishlistFilter($wishlist);
    foreach ($items as $item){
        $options = $this->helper('catalog/product_configuration')->getOptions($item);
        print_r($options);
    }
?>


text:
Q: Safe way to automount VeraCrypt container without showing password? I have a Raspberry Pi 4 (4GB) running Nextcloud on it. Because all my data and backups are saved on external USB drives I will encrypt them with a VeraCrypt container. Mounting and dismounting the container with VeraCrypt is working fine.
I would like to mount my VeraCrypt container after booting. In my opinion there are two ways to do that:

*

*Manually mount the Container after every boot via commandline and manually enter the container password, PIM, etc.

*Automatically mount the container via script

I would prefer the second solution but then I have to provide the password somehow. I could run the command
veracrypt /media/backup/test.hc /media/backup/test/ --password=test --pim=20 -k "" --protect-hidden=no

at startup but the password would be visible in the autostart file... (you could remove the sd card from the raspberry and just read out the password from the command above)
So my question is:
Is there a reasonably safe way to automount my VeraCrypt container without making the decryption password visible and without manually typing the password?

A: I had a remotely similar problem: I put a server in the garage so that external backups are stored in a location remote from the house. (Should the house burn down, a backup would be in the remote garage.) The volumes on the backup server were encrypted with VeraCrypt. The password was stored on the main server in the house. When the backup server booted, it connected to the main server, fetched the password (into RAM) and unlocked the VeraCrypt volumes with that. If the server from the garage was stolen and booted, the password (on the main server) would not be available and the VeraCrypt volumes remained locked. So a thief could only access the data when fiddling with the backup server while it was still connected to the LAN - an unlikely thing in my case.
So - if you store the password elsewhere on your LAN and outside of the Pi, you should be ok when a thief steals the Pi, the boot-SD or the attached drives.


text:
Q: Is it possible for an Apple Watch to get data directly from a Web Server without having an iPhone as an intermediary? I'm creating an app that wants to get a JSON file (or any data) from a local web server (MAMP) without having an iPhone that communicate with the server, parse the file and eventually sends the data to the Apple Watch via WatchConnectivity.
Is it possible? Is there any API I could use?
I've seen that the apps preinstalled on the watch can get data from the Web even with the iPhone turned off relaying only on the Wifi connectivity: for example the Apple's map app.
Thank you!

A: Yes.  As long as the watch has a network connection, via WiFi, cellular or through Bluetooth to its paired phone then you can use networking features, such as URLSession to fetch web content.
Even if the watch does piggyback off the phone's network connection, it doesn't require you to send data "through" the companion app.
As of watchOS 6.0, watch apps don't need a phone companion app; they can be stand-alone.


text:
Q: Android Studio - Navigation between activities I may be doing a very dumb mistake somewhere, and this question may seem really silly, but, i can't figure out the reason why this is happening.
I have a HomeActivity with an ImageView and when I click on it, i need to go to a DummyActivity(created for purpose of testing). The DummyActivity has a textview with text, "this is a dummy page". But, the screen just doesn't display anything.
I am a newbie with Android Studio, but, i guess it doesn't relate to it.
Here is my code:
ImageView onClick in HomeActivity:
 mImageView1 = (ImageView) findViewById(R.id.imageview_1);
 mImageView1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Log.d("HomeActivity", "ImageView 1 Clicked");
            //startActivity(new Intent(HomeActivity.this, MainActivity.class));
            startActivity(new Intent(HomeActivity.this, DummyActivity.class));
        }
    });

DummyActivity onCreate():
public class DummyActivity extends AppCompatActivity{

@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
    super.onCreate(savedInstanceState, persistentState);
    setContentView(R.layout.activity_dummy);
}
}

activity_dummy.xml
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is a dummy page"
        android:textAppearance="?android:attr/textAppearanceLarge" />
   </LinearLayout>

AndroidManifest.xml
 <activity
        android:name=".DummyActivity"
        android:label="DummyActivity"></activity>

The logcat displays, "ImageView 1 Clicked", but nothing after that. No errors, nothing. What am i doing wrong here?
Update: Changed backgroundColor for LinearLayout and textColor for the TextView, but the changes are not reflecting. The preview in Android Studio is showing the layout just fine, but, the screen on device is just blank as before, with black background.

Not sure why?

A: You have overriden wrong onCreate() method. Use this one instead:
public class DummyActivity extends AppCompatActivity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, persistentState);
        setContentView(R.layout.activity_dummy);
    }
}

A: Are you sure you want to change the activity?
In my App i use only one Activity but multiple fragments (see Dialogfragment). My Activty acts like a manager class for all other fragments and fragment transitions.
In your case i would create an "homeFragment" and add button callbacks like
private void buttonSwitchToDummy()
{
    HomeActivity act = (HomeActivity) getActivity();
    act.replaceFragment(act.mDummyFragment);
}

Adding this to HomeActivity
public void replaceFragment(Fragment fragment, boolean deleteBackStack)
{
    if(fragment==null)
        return;
    FragmentManager fm = getSupportFragmentManager();
    if(deleteBackStack)
    {
        // deletes the complete backstack and set fragment
        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }
    FragmentTransaction transaction = fm.beginTransaction();
    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack so the user can navigate back
    transaction.replace(R.id.fragment_container, fragment);
    transaction.addToBackStack(null);
    // Commit the transaction
    transaction.commit();
}


text:
Q: How to attach battery wires that got detached from this circuit board? Not an electrical person (at all!), but looking for some guidance as I feel this could be an easy fix.

This piece belongs to a kid's camera that only works when it's plugged via USB. When you unplug, it turns off. When I unscrewed I noticed that the black and red wires were not attached to the B+ B-

I remember seeing the black wiree near the B- one and the red wire near the B+ one, but I'm not sure if they go underneath the letters in those silver things or on the right/left side of the letters. How would I get them to stay? I read hot glue is a way I attempted with the black wire tape but that didn't work.

A: The normal convention is red goes to B+, black to B-
You can and should use a voltmeter to verify that the red wire is positive and black negative, in the rare case that someone didn't follow the convention.
In the photo the large pad where they connected one of the wires is connected to the pad marked B-
They probably just connected it there because it was a little easier than soldering to the smaller B- pad, and it's the same circuit trace.
You need to remove the old solder and bits of broken off wire from the board and resolder the wires to the pads, make sure the wires are trimmed down and make a nice clean solder joint. If you've got someone experienced to do it for you they should know what to do.
I've circled where the wires were connected.

A: Using black wires for minus and red for plus is a very long and well known tradition in the electrical community.  (these aren't cables, that word means multiple wires in a common plastic, rubber or other sleeve).
The way these were previously attached and may be attached again by an experienced person is to use an electronics soldering iron to melt the blob of "tin" (actually a mixture of tin and another metal), putting the already tin-covered wire end into the blob and allowing the blob to harden again, all in a matter of 1 to 5 seconds for each blob.  But for quickly trying it out, you can purchase packs of 10 colored wires with small "crocodile clamps" on the ends that can be clamped onto the blob at one end and the battery wires at the other, experts often use these to test out things first.  "crocodile clamps" are intentionally sharp to cut through thin layers of "dirt" on the metal.
To further ease this soldering process, it is normal to simultaneously apply a "flux" chemical to the blob.  "flux" is a chemical that dissolves surface "dirt" on the metal blob and metal conductors, thus letting the metal flow more freely.  Electronics flux can be purchased separately, but the most common way (in electronics) is to purchase a roll of unused "tin" thread, that is actually hollow with an appropriate amount of semi-solid flux rosin in a hollow space inside.  Thus when the fresh tin is melted onto the connection, the flux rosin melts and mixes with the freshly melted "tin".
The most common "tin" for soldering such small electronics is 1mm thick or even thinner.  The traditional (but somewhat toxic) "tin" mixture is 63% actual tin mixed with 37% lead (which is the toxic part).  This mixture melts at a lower, more practical temperature and hardens into a nice blob that doesn't tend to grow "whiskers" of metal that can short to other metal connections in the device after years in outer space (NASA worries about that).  More modern devices, especially those legal to sell as toys, use lead-free metal mixtures, such as 96.5% tin and about 3% copper and/or silver.  Shops (online or real world) specializing in selling parts for electronic hobby and repair generally stock 2 or more ready made types, the safe ones will loudly advertise themselves as "lead free".
To do the melting, a tool called a "soldering iron" is used.  Historically, this was a pointy piece of actual iron, covered in layer of "tin solder" and mounted in a handle (to not burn your hand as much).  The iron would be heated over an open fireplace until hot enough, then quickly moved to the puddle or other item to be melted.  Modern soldering irons are hollow and contain an electrical heater inside that can heat them as high as about 500 degrees C (900 degrees F), but it is usually enough to set a lower heat level, as the tin mixture will often melt at slightly over 200 degrees C (400 F) and then a few dozen more degrees are needed to actually heat up the wires and other metal parts.  Fancy "soldering irons" are connected to a thermostat and can be set within 10 to 20 degrees margin.  But there are also simpler "thermally balanced" irons where the heat escaping into the air around the tip will balance out the capacity of the electrical heater to keep the tip at a useful temperature (usually the temperature for tin/lead mixture, but it is quite possible they now make them for tin/silver/copper mixtures).  For the small blobs in the photo, I would recommend a balanced iron with an 18 to 30 W heater, or a thermostatically regulated iron with a 40 to 70 W heater (that is turned off half the time).  Whichever you buy, make sure the tips are cheap and easy to replace, as they wear out, especially for beginners, but even professionals will use up a lot of tips, and the holders in which you put the burning hot iron will often have a place to store a few spares.
The practical process is somewhat easily learned, and there are many online videos showing how it is done, with helpful narrators explaining what to do etc.  For example, the look of the "dried" blob will be somewhat different depending if it was done at the right speed or not (doing it a the wrong speed or with the wrong amount of flux will result in a weak connection called a "cold solder join", even if the problem isn't too low a temperature).  If this is someones favorite toy, practice the skill first on some pieces of thin electrical wire from the same shop, learning the basics takes a few days of practice.
Other tools needed for a simple job like that:

*

*Small pliers with thick plastic handles to not burn yourself.

*Small side cutters to cut wires and other excess metal.

*A cheap wet sponge (like for kitchen cleaning) to clean the tip of the hot iron.

*A big bucket of ice cold water for when you burn your hand, scar usually disappears after a few weeks of pain.

*A fireproof work surface such as a ceramic table, a 1 sq foot concrete paving tile, or an old dinner plate.

*An old coffee mug to hold hot items (such as the soldering iron) without causing a fire.


text:
Q: Simplest way to position HTML table column left What is the simplest way to position a tables columns to the left?  I.e. prevent columns from justifying across the total width of the table:
Good
| A | B                          |

Bad
| A              | B             |

A: Without JS (setting the first td width to content length) you would need to set the width of the first td with CSS.
Something like:

A	B

Would achieve what you are after. A would be a set width and B would naturally fill the rest.


text:
Q: Transaction query already complete, run with DEBUG=knex:tx when I work with japa test runner adonisJs 5 my test failed and got this error:
× Uncaught exception

   Transaction query already complete, run with DEBUG=knex:tx for more info

     1  completedError
       node_modules/knex/lib/execution/transaction.js:396

     2  anonymous
       node_modules/knex/lib/execution/transaction.js:362

     3  Client_MySQL2.trxClient.query
       node_modules/knex/lib/execution/transaction.js:358

     4  Runner.query
       node_modules/knex/lib/execution/runner.js:123

     5  ensureConnectionCallback
       node_modules/knex/lib/execution/internal/ensure-connection-callback.js:13

     6  Runner.ensureConnection
       node_modules/knex/lib/execution/runner.js:300

     7  Runner.run
       node_modules/knex/lib/execution/runner.js:30

     8  QueryRunner.executeQuery
       node_modules/@adonisjs/lucid/build/src/QueryRunner/index.js:78

I don't know why I get this error in some of my tests
in some of i don't
japa test runner adonisJs 5

A: I encountered the same issue and the issue for me was a missing await on a database call that returned a promise in one of my assertions,
so by the time the response was returned the global transaction in the test suite had already been rolled back
Once I added the await, the error was resolved, so I suggest you double check any async calls in your tests which you may not be awaiting a response for.


text:
Q: Flutter BottomNavigationBar stackoverflow i'm starting with Flutter and i'm struggling with the navigationBar, if i add the body i keep getting a stackOverflow.
If i don't add the body everything is fine.
Error:
    The following StackOverflowError was thrown building DefaultTextStyle(debugLabel: (englishLike body1 2014).merge(blackMountainView bodyText2), inherit: false, color: Color(0xdd000000), family: Roboto, size: 14.0, weight: 400, baseline: alphabetic, decoration: TextDecoration.none, softWrap: wrapping at box width, overflow: clip):
Stack Overflow

The relevant error-causing widget was:
  Scaffold Scaffold:file:///Users/salvatorelafiura/git/energy_flutter/lib/screen/main.dart:104:12
When the exception was thrown, this was the stack:
#0      new Uint8List (dart:typed_data-patch/typed_data_patch.dart:2201:3)
#1      _createTables.<anonymous closure> (dart:core/uri.dart:3872:60)
#2      new _GrowableList.generate (dart:core-patch/growable_array.dart:133:28)

Code of the current widget, 3 screens one bottomNavigation.
Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widgetTitle.elementAt(selectedIndex)),
            actions: <Widget>[
              IconButton(
                icon: const Icon(
                  Icons.logout,
                  color: Colors.white,
                ),
                onPressed: () {
                  signOut();
                },
              )
            ],
          ),
          body: Center(
            child: IndexedStack(index: selectedIndex, children: tabPages),
          ),
          bottomNavigationBar: BottomNavigationBar(
            items: const <BottomNavigationBarItem>[
              BottomNavigationBarItem(icon: Icon(Icons.home), label: "Pratica"),
              BottomNavigationBarItem(icon: Icon(Icons.mail), label: "Messages"),
              BottomNavigationBarItem(icon: Icon(Icons.person), label: "Profilo"),
            ],
            currentIndex: selectedIndex,
            onTap: onItemTapped,
            backgroundColor: Colors.white,
            fixedColor: Colors.blue,
            selectedLabelStyle: const TextStyle(color: Colors.red, fontSize: 20),
            unselectedFontSize: 16,
            selectedIconTheme:
                const IconThemeData(color: Colors.blue, opacity: 1.0, size: 30.0),
            unselectedItemColor: Colors.grey,
            unselectedLabelStyle: const TextStyle(fontSize: 18, color: Colors.pink),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        );
      }

A: Create a Separate Class "Bottom" and Place the whole code of your Bottomnavigationbar inside that class then at every Screen just Call inside the Scaffold like:
bottomNavigationBar: Bottom();

Then Declare your int selectedIndex = 0; Globally
it will works fine.
Modify the Given code:
import 'package:flutter/material.dart';

int _selectedIndex = 0;

class Bottom extends StatefulWidget {
  @override
  _BottomState createState() => _BottomState();
}

class _BottomState extends State<Bottom> {
  @override
  Widget build(BuildContext context) {
    return BottomNavigationBar(

        showSelectedLabels: true, // <-- HERE
        showUnselectedLabels: true,
        backgroundColor: Color(0xff38547C),
        type: BottomNavigationBarType.fixed,
        currentIndex: _selectedIndex,
        selectedItemColor: Color(0xFF1C2834),
        unselectedItemColor: Colors.white,
        items: [
          BottomNavigationBarItem(
            icon: const Icon(
              Icons.home,
            ),
            label: "Home",
          ),
          BottomNavigationBarItem(
            icon: ImageIcon(
              AssetImage("assets/images/ball.png"),
            ),
            label: "Matches",
          ),
          BottomNavigationBarItem(
              icon: const Icon(
                Icons.live_tv,
              ),
              label: "Live"),
          BottomNavigationBarItem(
              icon: Icon(
                Icons.poll,
              ),
              label: "Ranking"),
          BottomNavigationBarItem(
              icon: Icon(
                Icons.more_horiz,
              ),
              label: "More"),
        ],
        onTap: (int index) {
          setState(() {
            _selectedIndex = index;
          });
          if (_selectedIndex == 0) {
            var route =
                MaterialPageRoute(builder: (BuildContext context) => Home());
            Navigator.of(context).push(route);
          } else if (_selectedIndex == 1) {
            var route =
                MaterialPageRoute(builder: (BuildContext context) => Matches());
            Navigator.of(context).push(route);
          } else if (_selectedIndex == 2) {
            var route =
                MaterialPageRoute(builder: (BuildContext context) => Live());
            Navigator.of(context).push(route);
          } else if (_selectedIndex == 3) {
            var route =
                MaterialPageRoute(builder: (BuildContext context) => Ranking());
            Navigator.of(context).push(route);
          } else if (_selectedIndex == 4) {
            var route =
                MaterialPageRoute(builder: (BuildContext context) => More());
            Navigator.of(context).push(route);
          }
        });
  }
}


text:
Q: Cant find variable - parameter add function with firestore Im a novice in react native, Im trying to retrieve the email of the User connected (emailUser), to add it in the collection Tasks in firestore
Im getting the error "Can't find the variable emailUser" when Im trying to add it in the firestore database
addTask=async(task,categ)=>{
    var useruid=firebase.auth().currentUser.uid;
    await firebase.firestore().collection("Users").doc(useruid).get().then(documentSnapshot=>{
      const emailUser=documentSnapshot.data().email;
      console.log("email = " + emailUser)
    })
    try{
        await firebase.firestore().collection("Tasks").where('task','==',task).where("User",'==',useruid).get().then(documentSnapshot=>{
        {
          console.log('Task exists : ',documentSnapshot.docs.length>0)}
          if(documentSnapshot.docs.length>0)
          {
            alert('This task already exists')}
          else
          {
            firebase.firestore().collection('Tasks').add({User:emailUser,task:task,category:categ})
            .then(alert('Task added!'));
            this.setState((state,props)=>
            ({
              tasks:[...state.tasks,task],
            }),()=>{
            console.log(this.state);
          });
      }
    })
  }
  catch(error)
  {
    console.log("error = "+error)
  }
}

A: You can't use userEmail out of then callback you need do some changes on your code please try like this
addTask = async (task, categ) => {
  var useruid = firebase.auth().currentUser.uid;
  const docSnap = await firebase
    .firestore()
    .collection('Users')
    .doc(useruid)
    .get();

  const emailUser = docSnap.data().email;

  try {
    await firebase
      .firestore()
      .collection('Tasks')
      .where('task', '==', task)
      .where('User', '==', useruid)
      .get()
      .then((documentSnapshot) => {
        {
          console.log('Task exists : ', documentSnapshot.docs.length > 0);
        }
        if (documentSnapshot.docs.length > 0) {
          alert('This task already exists');
        } else {
          firebase
            .firestore()
            .collection('Tasks')
            .add({ User: emailUser, task: task, category: categ })
            .then(alert('Task added!'));
          this.setState(
            (state, props) => ({
              tasks: [...state.tasks, task],
            }),
            () => {
              console.log(this.state);
            },
          );
        }
      });
  } catch (error) {
    console.log('error = ' + error);
  }
};

`


text:
Q: order hierarchical data into a tree using ROW_NUMBER or does it have to be done with a loop? I have a set of hierarchical data that I'm hoping to get into the right format without using a loop. Maybe it's a long day and I just don't see how to do it.
When it starts the data looks like this:
(row = row ID, par = parent row ID, lev = level, has_child is obvious, had to do that or edit the space between all those numbers!)
row par lev has_child
1   NUL 0   1
2   1   1   1
3   1   1   1
4   1   1   1
5   1   1   1
6   1   1   0
148 2   2   0
149 2   2   1
145 3   2   0
146 3   2   1
9   4   2   0
11  4   2   0
12  4   2   0
13  4   2   0
14  4   2   0
15  4   2   0
16  4   2   0
17  4   2   0

I'd like it to be in a parent, child, child, child, ... order. So that all the children of a parent are shown before the next parent is started. Like this:
Parent
  |
   --- child L1
       |
       ---- child L2
       |
       ----- child L2
           |
           ---- child L3
       |
       ----- child L2
  |
  ---- child L1

It seems like I should be able to accomplish this using ROW_NUMBER(), but I've been messing with it for a good half hour with no luck. Do I have to do this in a loop?

A: You can't with ROW_NUMBER(). You need to use a recursive CTE and create a synthetic sort order by composing the full parent path:
declare @table table (row int, par int, lev int, has_child bit);

insert into @table
select 1, NULL, 0, 1
union all select 2,   1,   1,       1
union all select 3,   1,   1,       1
union all select 4,   1,   1,       1
union all select 5,   1,   1,       1
union all select 6,   1,   1,       0
union all select 148, 2,   2,       0
union all select 149, 2,   2,       1
union all select 145, 3,   2,       0
union all select 146, 3,   2,       1
union all select 9,   4,   2,       0
union all select 11,  4,   2,       0
union all select 12,  4,   2,       0
union all select 13,  4,   2,       0
union all select 14,  4,   2,       0
union all select 15,  4,   2,       0
union all select 16,  4,   2,       0
union all select 17,  4,   2,       0;

with cte_anchor as (
  select row, par, 0 as lev, cast(row as varchar(max)) as wbs
     from @table
     where par is null)
, cte_recursive as (
  select row, par, lev, wbs
  from cte_anchor
  union all
  select  t.row, t.par, r.lev+1 as lev
    , r.wbs + '.' + cast(t.row as varchar(max)) as wbs
  from @table t
  join cte_recursive r on t.par = r.row)
select * from cte_recursive
order by wbs

A: I have an example on this question (which is more complicated, but you'll get the idea)
SQL Server Tree Hierarchy and Nested Sets with Duplicate Record ids


text:
Q: How to hash aggregated results in postgresql incrementally without concatenating everything first I want to calculate a hash (sha256) of as set of results, I know how to do to it:
SELECT digest( string_agg(id_,':'), 'sha256') from mytable order by id_;

It works but it first concatenates all records and finally calculate the hash. I want it to be incremental to avoid possible memory problems with large datasets (millions of rows), something like:
SELECT digest_agg(id_, ':', 'sha256') from mytable order by id_;

Ensuring that the hash is calculated incrementally row by row on the way.

A: Ok, I have finally coded a c extension for this. I post it here in case it would be useful for someone.
/* ------- OS Includes ------------ */
#include <stdio.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>

/* ----- PostgreSQL Includes -------*/
#include "postgres.h"
#include "fmgr.h"
#include "funcapi.h"
#include "utils/builtins.h"
#include "utils/memutils.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
PG_MODULE_MAGIC;

typedef struct sha256_state
    {
    SHA256_CTX* sha256;
    bool has_data;
    } SHA256_STATE;

/* --------- Prototypes ---------- */
void _PG_init(void);
void _PG_fini(void);
Datum dv_sha256_agg_sfunc(PG_FUNCTION_ARGS);
Datum dv_sha256_agg_final(PG_FUNCTION_ARGS);
SHA256_STATE* sha256_init(void);
void sha256_update(SHA256_STATE* state, char* string, int32 string_size);
void sha256_final(SHA256_STATE* state, char outputBuffer[65]);

/* ------ Version1 convention ---- */
PG_FUNCTION_INFO_V1(dv_sha256_agg_sfunc);
PG_FUNCTION_INFO_V1(dv_sha256_agg_final);

// -----------------------------------------------------------
// Implementations
// -----------------------------------------------------------

void _PG_init(void) {/* Do nothing */}
void _PG_fini(void) {/* Do nothing */}

Datum dv_sha256_agg_sfunc(PG_FUNCTION_ARGS) {

    SHA256_STATE* state;
    bool is_first = PG_ARGISNULL(0);
    text* string;
    int32 string_size;
    char* data;
    char SEP[] = {'\n'}; // Hardcoded separator (can be improved)

    if (is_first) {
        // First iteration: Create the state
        state = sha256_init();
    }
    else {
        // Next iterations: Restore the state
        state = (SHA256_STATE*) PG_GETARG_POINTER(0);
    }

    if (PG_ARGISNULL(1)) {
        PG_RETURN_POINTER(state);
    }

    // Get current chunk
    string = PG_GETARG_TEXT_PP(1);
    string_size = VARSIZE_ANY_EXHDR(string);
    data = VARDATA_ANY(string);

    // Add separator
    if (state->has_data) {
        sha256_update(state, SEP, 1);
    }

    // Update state
    sha256_update(state, data, string_size);
    state->has_data = true;

    // Updated state
    PG_RETURN_POINTER(state);

}

Datum dv_sha256_agg_final(PG_FUNCTION_ARGS) {
    SHA256_STATE* state;
    char out[65];
    text* hash = (text*) palloc(65 + VARHDRSZ);
    if (PG_ARGISNULL(0)) {
        PG_RETURN_NULL();
    }
    else {
        state = (SHA256_STATE*) PG_GETARG_POINTER(0);
        sha256_final(state, out);
        SET_VARSIZE(hash, 65 + VARHDRSZ);
        memcpy(VARDATA(hash), out, 65);
        PG_RETURN_TEXT_P(hash);
    }
}

SHA256_STATE* sha256_init() {
    SHA256_STATE* state = (SHA256_STATE*) palloc(sizeof(SHA256_STATE));
    state->sha256 = (SHA256_CTX*) palloc(sizeof(SHA256_CTX));
    SHA256_Init(state->sha256);
    state->has_data = false;
    return state;
}

void sha256_update(SHA256_STATE* state, char* string, int32 string_size) {
    SHA256_Update(state->sha256, string, string_size);
}

void sha256_final(SHA256_STATE* state, char outputBuffer[65]) {
    int i;
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_Final(hash, state->sha256);
    for(i = 0; i < SHA256_DIGEST_LENGTH; i++) {
        sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
    }
    outputBuffer[64] = 0;
}

The aggregate definition:
CREATE FUNCTION dv_sha256_agg_sfunc(state internal, input text)
RETURNS internal AS 'MODULE_PATHNAME',
'dv_sha256_agg_sfunc'
LANGUAGE C VOLATILE;

CREATE FUNCTION dv_sha256_agg_final(state internal)
RETURNS text AS 'MODULE_PATHNAME',
'dv_sha256_agg_final'
LANGUAGE C VOLATILE;

CREATE AGGREGATE dv_sha256_agg(input text) (
    SFUNC = dv_sha256_agg_sfunc,
    STYPE = internal,
    FINALFUNC = dv_sha256_agg_final
);

Test:
select
    dv_sha256_agg(id_::text),
    encode(digest(string_agg(id_::text,E'\n'),'sha256'),'hex')
from
    generate_series(1,100) id_(id_);

Result
                          dv_sha256_agg                           |                              encode
------------------------------------------------------------------+------------------------------------------------------------------
 4187fe63fa78d8b4333e6ffc9122e0273ddf90251ced32e1e5b398639c193c87 | 4187fe63fa78d8b4333e6ffc9122e0273ddf90251ced32e1e5b398639c193c87
(1 row)

Notes:

*

*Separator is hardcoded as \n

*Null values are ignored

A: In PostgreSQL you can create your own aggregate function using CREATE AGGREGATE. That way you can write digest_agg yourself.
The challenge is to come up with a good state transition function (SFUNC) that combines the aggregate of the previous values with the next value.

A: It is possible to implement such a function yourself. Without touching any C code, I wrote one up in plperlu.  It is memory efficient, but horrifically slow.  If you want it fast, you will probably need to code it up in C.  I suspect that the getstate and putstate functions have had no performance consideration whatsoever, as they weren't intended to be used in loops like this.
CREATE LANGUAGE plperlu;
CREATE FUNCTION public.sha256_final(state text) RETURNS bytea
    LANGUAGE plperlu
    AS $_X$
use Digest::SHA;
my $sha=Digest::SHA->new(256);
if (defined $_[0]) { $sha->putstate($_[0])};
$sha->add($_[1]);
return encode_bytea($sha->digest());
$_X$;
CREATE FUNCTION public.sha256_sfunc(state text, input text) RETURNS text
    LANGUAGE plperlu
    AS $_X$
use Digest::SHA;
my $sha=Digest::SHA->new(256);
if (defined $_[0]) { $sha->putstate($_[0])};
$sha->add($_[1]);
return $sha->getstate();
$_X$;

CREATE AGGREGATE public.perl_sha256(input text) (
    SFUNC = public.sha256_sfunc,
    STYPE = text,
    FINALFUNC = public.sha256_final
);

--The built in sha256 on pre-aggregate gives the same answer...
select sha256(string_agg::bytea) from (select string_agg(id_::text,'') from generate_series(1,101) id_(id_)) foobar;

--- ...as my own streaming aggregate.
select perl_sha256(id_::text) from generate_series(1,101) id_(id_);

Of course you have to make sure rows are delivered in the correct order.  And I didn't implement the ':' delimiter from string_agg, just ''.


text:
Q: ordinary differential equation of third order using substitution How one can solve ODE in the following form?
$$y''' y +(y'')^{2} =0$$
It looks like some kind of substitution. I did try some substitution but they were useless.
thanks in advance.

A: With reference to http://eqworld.ipmnet.ru/en/solutions/ode/ode0503.pdf,
Let $u=\left(\dfrac{dy}{dx}\right)^2$ ,
Then $\dfrac{du}{dx}=2\dfrac{dy}{dx}\dfrac{d^2y}{dx^2}$
$\dfrac{du}{dy}\dfrac{dy}{dx}=2\dfrac{dy}{dx}\dfrac{d^2y}{dx^2}$
$2\dfrac{d^2y}{dx^2}=\dfrac{du}{dy}$
$2\dfrac{d^3y}{dx^3}=\dfrac{d}{dx}\left(\dfrac{du}{dy}\right)=\dfrac{d}{dy}\left(\dfrac{du}{dy}\right)\dfrac{dy}{dx}=\mp\sqrt u\dfrac{d^2u}{dy^2}$
$\therefore\mp y\sqrt u\dfrac{d^2u}{dy^2}+\dfrac{du}{dy}=0$
$\dfrac{d^2u}{dy^2}=\pm\dfrac{1}{y\sqrt u}\dfrac{du}{dy}$
Which reduces to a generalized Emden-Fowler equation of the form http://science.fire.ustc.edu.cn/download/download1/book%5Cmathematics%5CHandbook%20of%20Exact%20Solutions%20for%20Ordinary%20Differential%20EquationsSecond%20Edition%5Cc2972_fm.pdf#page=362
WLOG, just consider $\dfrac{d^2u}{dy^2}=\dfrac{1}{y\sqrt u}\dfrac{du}{dy}$
The general solution is $\begin{cases}u=\dfrac{1}{t^2}\\y=\pm C_2e^{\int\frac{dt}{t^3\left(-\frac{1}{t}-\frac{1}{2t^2}+C_1\right)}}\end{cases}$
$\begin{cases}\left(\dfrac{dy}{dx}\right)^2=\dfrac{1}{t^2}\\y=\pm C_2e^{\int\frac{dt}{C_1t^3-t^2-\frac{t}{2}}}\end{cases}$
$\begin{cases}\dfrac{dy}{dx}=\pm\dfrac{1}{t}\\y=\pm C_2e^{\int\frac{dt}{C_1t^3-t^2-\frac{t}{2}}}\end{cases}$
$\begin{cases}\dfrac{\dfrac{dy}{dt}}{\dfrac{dx}{dt}}=\pm\dfrac{1}{t}\\y=\pm C_2e^{\int\frac{dt}{C_1t^3-t^2-\frac{t}{2}}}\end{cases}$
$\begin{cases}\dfrac{dx}{dt}=\pm\frac{C_2}{C_1t^2-t-\frac{1}{2}}e^{\int\frac{dt}{C_1t^3-t^2-\frac{t}{2}}}\\y=\pm C_2e^{\int\frac{dt}{C_1t^3-t^2-\frac{t}{2}}}\end{cases}$
$\begin{cases}x=\pm\int\frac{C_2}{C_1t^2-t-\frac{1}{2}}e^{\int\frac{dt}{C_1t^3-t^2-\frac{t}{2}}}~dt+C_3\\y=\pm C_2e^{\int\frac{dt}{C_1t^3-t^2-\frac{t}{2}}}\end{cases}$


text:
Q: SelectCount by Three options ObjectDataSource I need a count for the GetUsers but I have 3 different calculations either by alpha, search and byEmail parameters what can I do in this situation for my ObjectDataSource SelectCount method
public class Users
{
    public IList<MembershipUser> GetUsers(string alpha, string search, bool byEmail, int startRowIndex, int maximumRows)
    {
        IList<MembershipUser> users = null;

        if (alpha != null && search == null)
        {
            users = Membership.GetAllUsers().Cast<MembershipUser>().Where(x => x.UserName.StartsWith(alpha) == true).ToList();
        }
        else if (search != null && !byEmail)
        {
            users = Membership.FindUsersByName(search).Cast<MembershipUser>().Skip(maximumRows * startRowIndex).Take(maximumRows).ToList();
        }
        else
        {
            users = Membership.FindUsersByEmail(search).Cast<MembershipUser>().Skip(maximumRows * startRowIndex).Take(maximumRows).ToList();
        }

        return users;

    }

    public int GetUserCount()
    {

    }

Updated C#:
    public IEnumerable<MembershipUser> GetUsers(string alpha, string searchBy, string searchText, int startRowIndex, int maximumRows)
    {
        var users = Membership.GetAllUsers().Cast<MembershipUser>();

        if (alpha != null && string.IsNullOrEmpty(searchBy))
        {
            users = users
                .Where(x => x.UserName.StartsWith(alpha, StringComparison.OrdinalIgnoreCase))
                .Skip(maximumRows * startRowIndex)
                .Take(maximumRows).ToList();
        }
        else if (searchBy == "User Name" && !string.IsNullOrEmpty(searchText))
        {
            users = users.Where(x => x.UserName == searchText)
                .Skip(maximumRows * startRowIndex)
                .Take(maximumRows).ToList();
        }
        else if (searchBy == "Email" && !string.IsNullOrEmpty(searchText))
        {
            users = users.Where(x => x.Email == searchText)
                .Skip(maximumRows * startRowIndex)
                .Take(maximumRows).ToList();
        }
        else
        {
            users = null;
        }

        return users;

    }

A: Something like the following should work:
public int GetUserCount(string alpha, string search, bool byEmail, int startRowIndex, int maximumRows)
{
    var users = Membership.GetAllUsers().Cast<MembershipUser>();

    if (alpha != null && search == null)
    {
        users = users.Where(x => x.UserName.StartsWith(alpha) == true);
    }
    else if (search != null && !byEmail)
    {
        users = users.FindUsersByName(search).Cast<MembershipUser>();
    }
    else
    {
        users = users.FindUsersByEmail(search);
    }

    return users.Count();
}

I would be more comfortable with this approach if FindUsersByName and FindUsersByEmail returned objects related to IEnumerable<T> so you could depend on the lazy nature of LINQ, but in this case it doesn't matter since you're doing a count. I'd recommend some form of Select to limit the fields being queried over, but in your second two cases, they'll pull all results anyway so it would be without benefit 2/3 possible situations. If you find that more often than not the query is done by UserName then it would probably be worth adding there.


text:
Q: Prove or disprove if $\sum_{n=1}^{\infty} a_n $ converges, then $\sum_{n=1}^{\infty} \frac{\left | a_n \right |}{n}$ also converges I'm homelearning calculus and trying to prove or disprove the following problem:

If $\sum_{n=1}^{\infty} a_n $ converges, then $\sum_{n=1}^{\infty}
\frac{\left | a_n \right |}{n}$ also converges.

However, I'm not sure how I would prove or disprove the statement. Could you help me?
Thanks

A: It doesnt'work, take $a_n=\frac{(-1)^n}{\log n}$, then $\sum a_n$ converges but $\sum\frac{|a_n|}{n}=\sum\frac{1}{n\log n}$ diverges.

A: If a series is absolutely convergent, then it is convergent. But converse is not true. Because $\ \sum_{n=1}^{\infty} \dfrac{(-1)^{n+1}}{n}$ is convergent but $\ \sum_{n=1}^{\infty} \dfrac{{1}}{n}$ is not.


text:
Q: Dell PowerEdge 1800 Hangs at boot after Dell PERC Sata RAID Controller Successfully POSTs Server crashed one night. I rebooted, now it hangs just after the SATA RAID Controller successfully POSTs.
This unit has a RAID 5 array, but I haven't pulled a recent enough backup of the data on it to feel comfortable, so I simply can't break the array in any way.
Questions:
-First off, what are my options for troubleshooting this without affecting my array?
-Second, can I replace the RAID card without losing my array informatoin?
-Third, how do I back up or transport the array to another machine / card without data loss if I need to?
Thanks for any help you can provide
EDIT:
I finally got past the hang by disabling the Boot BIOS (telling the card not to act as a boot device) and for the first time I was able to get into the RAID utility (Ctrl + A) to see the status of my array. DEGRADED. So now I'm trying to identify which drive failed in the 3 drive array.
Essentially the Boot BIOS being enabled was preventing me from accessing the RAID config BIOS while the drives were connected. I had to disconnect the drives, disable the boot BIOS, reconnect the drives, then I was finally able to get into the config BIOS to see that I had a dregraded array.
QUESTIONS:

*

*How do I identify which drive failed? The array status screen doesn't seem to indicate which drive is causing the degradation. I'm verifying each drive with the BIOS utility right now, but I'm wondering if there's an easier way that doesn't take hours and hours.

*I have the option to rebuild a failed array with the (Ctrl + R) Rebuild tool in the BIOS. Is this an option for a DEGRADED array as opposed to a FAILED array, as the tool was designed for? What are the risks?

*Why didn't my array boot with a single drive failure? RAID 5 should have kicked in and allowed the system to recover and boot on 2 drives.

*If it had multiple drive failures, then why is the array DEGRADED instead of FAILED?

A: Dell Warranty Check: Perhaps the until is still covered under warranty?

A: Options for Troubleshooting:
 Try to determine if the error is with the server or the Raid.
 Check Bios for changes//correct boot device.
 Check Raid Bios for correct information (memory, # of hdd, raid level)
 Try booting to another media (cdrom, usb, network)
 Remove raid card and drives from system then see if the system boots
2nd: The raid configuration information should be stored on the drives and the controller. You may have to "accept the new configuration" to continue either in the bios or during boot.
3rd: Move the drives and RAID card to the new box, provided your OS can handle the change in hardware or its another Dell 1800.
4th: Moving the array to another card typically does not work unless the new card is the same make and model of RAID controller. You may have to "accept the new configuration" to continue either in the bios or during boot.