text:
Q: Best practices to keep your computer(s) backed up efficiently? I'm looking for a cheap and efficient strategy to keep my personal computers and laptops backed up.
For example, currently I take a snapshot of my desktop once a week with Ghost and place the image on my external hard drive.  Is this enough?  Do you have any other suggestions?

A: Here's my home backup strategy:

*

*Most files are stored on a Linux file server that my Windows machines connect to.

*All my music, video, & images live on a Windows machine that gets backed up to the Linux file server.

*The Linux file server is backed up to an external hard drive

*About 75% of my data is backed up remotely using Jungle Disk.

*All of my remote websites & databases are backed up to my home machines using rsync & mysqldump over ssh.

All of the above happens twice a day.
The end result is that any of my computers can die, my webhost can disappear, or my house can burn down and I'll suffer minimal to no permanent data loss.
The important thing to think is "If this thing dies/breaks/goes away, what will I lose?".  Then think it about every source of data you have.

A: Of course 'cheap' depends on the readers' view...
I'm using a Dlink DNS-323 NAS (equipped with 2x 1TB drives in RAID1) in combination with BackupPc, which is actually a 'gui' around Rsync.

A: You could also backup the ghost image to a on-line backup service.  There are several companies, some which offer free accounts as a starting point.

*

*IDrive - free option

*Mosy - free option

*ADrive - free option

*Carbonite

*Livedrive

*Jungle Disk with Amazon S3

*SquirrelSave

A: This isn't a strategy for backing up a whole computer (I use WHS and Time Machine for that), but for critical files, I use Dropbox.  It automatically synchronizes files across different computers, plus they get backed up and versioned online.  Free for up to 2 gigs, pay for up to 50GB.  This is the first online file sych tool or service I've found that just works.  Simple, no hassles, set it up and you're done.  I love it.

A: I'd recommend setting up freenas on an old machine with lots of disk space and using an automated rsync program.
Using rsync you are only copying changes between the last version and current over the network, so it's pretty fast.

A: This may not qualify as "cheap" and is windows specific but the Windows Home Server is working very well for me.  I'm backing up several machines and I have 3 months of back ups to choose from if things go wrong.  I have the HP Media Smart version and I'm extremely happy with it.  Here is a link to a review by Scott Hanselman.
Prior to getting the home server I was taking snapshots and ghosts and had a bunch of scripts that kept data redundant.  All of this was very prone to human or otherwise error.

A: In general I think making backups as automatic as possible will ensure that you always get the level of backup you need.  You also want some level of redundancy both on-site and off-site.  If the data doesn't exist in two places at once, then it really doesn't exist.
I would recommend the following approaches for maximum redundancy:
Duplicate your important data locally
This can be done using a couple of methods

*

*Mirror your drive(s) automatically with RAID-1

*Automatically clone your drive(s) using an rsync style backup script, or other application (TimeMachine, Carbon Copy Cloner, etc).  I would also prefer a backup application which does rolling snapshots (like Apple's Time Machine or rsnapshot)

*Store all your important data on a dedicated NAS with some sort of dynamically expandable RAID (like a Drobo, or a NetGear ReadyNAS.  Use an application (like those listed in method 2) to automatically copy data from your various systems and drives to the NAS on at least a daily basis

Backup your important data offsite
I would recommend using a 'cloud' based backup solution that is automatic.  These include:

*

*Mozy

*Carbonite

*Backblaze
These services automatically upload unlimited data to their servers for $4.95 a month.  Some of these services even give you 30 days of snapshots so you can get back to data you accidentally deleted.
Mirror your system drive
If you really want to get crazy paranoid about losing your data, I would also mirror your system drive daily using a mirroring tool like TrueImage, CarbonCopyCloner, SuperDuper.  This will give you an exact copy of your system drive, so if your drive fails, you can just pop in the cloned drive and pick up where you left off.  No time wasted rebuilding your system, installing old applications, etc.

A: Home backup strategy:

*

*Photos, Music, Scans on Main Desktop are backed up using Time Machine connected to External USB Hard Drive

*Videos and large files (e.g. MSDN Downloads) are kept on 1TB RAID5 NAS (NAS will send alert if hard drive is lost)

*Photos, Music, Scans on Main Desktop are backed up a few times a week using Jungle Disk Plus.

I recently had my Main Desktop HDD die and was able to bring everything back in about a day.

A: Mozy works at home or at work, but I've found the best part is that my gf doesn't have to do anything to get it to work.  I installed it and now I know her compy is being backed up all the time.

A: I have a linux machine and two windows machines that I need to be backed up.  I have two 500GB external hard drives formatted to an ext3 file system and have the linux machine run a script that mounts the drive, runs rsnapshot, and unmounts the drive.
Rsnapshot is basically a smart way of using rsync to do efficient backups.  I have an rsync daemon running as a service on each of the windows machines (thanks to cygwin) and the rsnapshot process on the linux box connects to that.
You could probably do the same thing using a windows machine as the backup device (rsnapshot is available via cygwin) however rsnapshot makes heavy use of hard links, which is something I'm not confident of with an NTFS file system. YMMV.

A: My home backup strategy utilises a set of daily or weekly backups using backupninja and rdiff-backup to an external disk to keep 60 days worth of incremental backups.
I have another disk offsite that I occasionally bring home and rsync with off the onsite backup disk.
I also use unison to sync various directories between my desktop and laptop.  Not a backup as such, but a useful extra copy to have.

A: I have a Mac and a PC on the same network. I periodically run Folder Synchronizer (by SoftoBe) on my Mac, which talks to the shared drives on my PC, and copies the data. Time Machine does the rest.
I consider Time Machine my "house on fire" drive.  All I need to take with me is that external drive. (Well... the wife and kid too.)

A: My personal strategy is to run a full system backup and store the data on a portable USB hard drive every couple of weeks.  I let the backup run overnight, and the portable drive is taken to work with me and put in a secure location there so it is off-site from my home computer.  If the house burns down or the computer is stolen, the data is still safe.  The other key to any backup solutions is to make sure you can actually restore files.  Periodically test this to ensure your data is recoverable.  Once a month I select a handful of random files to restore just to make sure the data is recoverable.  If you don't mind a monthly fee, there are a large number of online backup providers who will keep your files synchronized with their service in near real-time to ensure everything is always as up-to-date as possible.  I prefer having my own copy around where I can get at it any time, and I prefer the files to not be in a live state all the time in case I need to roll back a week or so.

A: Similar to Huppie, I use a RAID 1 on two 1 TB disks in a "toaster enclosure", which allows for the possibility of off-site storage.
I also encrypt my backup, using cryptsetup in my case. On top of that, I also use LVM volumes; this allows each computer's backup to be on a separate volume. (Each computer can then back up to the volume that concerns them, and avoid the possibility of clobbering other computers' backups.)
The actual backup process is a simple rsync (rsync -av --delete --inplace ...).

A: For photos and video specifically I see flickr as an off-site backup.
I have nearly 40 GB of personal photos and videos, the largest part of my home backups. For off-site backups, my flickr pro account is very cost effective. ($25/year)
Still looking for a cost-effective off-site solution for "regular" backups.

A: I have a lot of data and its in terms of videos and audio data and best way of backing up to me is to have 2 hard disk backups and 1 dvd backup of the most important data. And 1 hard disk back and 1 dvd backup of lesser important data
I use Acronis True Image instead of Norton Ghost as i find it to be a much better interface and its a more reliable software to use as i have faced corruption of backups with Norton Ghost but this is from my own personal experience.
Its not a very cheap solution but then ultimately its the data that counts, alternatively you could also buy a cheap unlimited hosting account and store your data there too, but then the security of the server is up to you, though i wouldn't trust my important data online

A: I backup a Hyper-V server. Because the machine is a Dell Vostro, it lacks RAID drives etc.
What I do is use backupassist to backup the host and all VMs (I'm adding more VMs to the server, but some aren't too critical so soon it will be some of the entire VMs) to my  USB drive (I lack ESATA, too).
I'm also deploying the same VMs to a cloud server service, so I will have two layers of protection (both the VMs at home and on the cloud service are synced).

A: Mine is setup as follows:
I have a webserver with about 8 websites on a shared server with GoDaddy, my laptop, wifes laptop, and a spare laptop.
Spare laptop uses Server2003 (previously XP Pro) and is always on. It has logmein installed so i can access files if i dont have my laptop.

*

*I do not save any work on my laptop and I am slowly convincing my wife to do the same

*Other option is to use EverydayAutobackup to backup both wifes and my laptop to SpareLaptop - problem is they are not always on - maybe I can run it when logging on?

*All work/pics/etc is saved in MyDocuments on the Spare W2003 Laptop.

*This is backed up every six hours using EverydayAutoBackup

*Backup goes to F: on Spare Laptop (USB HD)

*Thinking of buying a second USB HD called G: and will mirror F: > G: every alternative 6 hours so if either breaks suddenly, we can immediately recover data and buy new USB HD to replace broken.

*W2003 laptop backs up my websites' databases every day using a scheduled task on a batch file - mysqldump to a location im mydocuments (which will plug into my system and be backed up to F: and mirrored to G..eventually)

TODO:

*

*Backup the files on webserver to My docs on home laptop - any ideas? Can i schedule an ssh task?

*Either buy another USB HD called G: OR mirror F: to an offsite location (or both)

*Both sounds good so offsite location is only for extreme circumstances.

*Also need to think of security...What happens if someone takes F or G and plugs into their PC - are there any secure USB HDs out there?

A: I personaly use Paragon Software Drive Backup, now called Backup & Recovery 10 Suite.
It allows for hotfiles backup, that is, files that are currently in use are also backed up while you're working! So no data loss!
It also can backup the whole partition live partition while working, if working, and make it pretty simple to recover in case of data loss or other problems with your computer.
It's available for both Windows and Mac (they have different names for Mac, thought: Software for MAC


text:
Q: Update SQL Server 2000 to SQL Server 2008: Benefits please? I'm looking for the benefits of upgrading from SQL Server 2000 to 2008.
I was wondering:

*

*What database features can we leverage with 2008 that we can't now?

*What new TSQL features can we look forward to using?

*What performance benefits can we expect to see?

*What else will make management go for it?

And the converse:

*

*What problems can we expect to encounter?

*What other problems have people found when migrating?

*Why fix something that isn't (technically) broken?

We work in a Java shop, so any .NET / CLR stuff won't rock our world. We also use Eclipse as our main development so any integration with Visual Studio won't be a plus. We do use SQL Server Management Studio however.
Some background:
Our main database machine is a 32bit Dell Intel Xeon MP CPU 2.0GHz, 40MB of RAM with Physical Address Extension running Windows Server 2003 Enterprise Edition. We will not be changing our hardware. Our databases in total are under a TB with some having more than 200 tables. But they are busy and during busy times we see 60-80% CPU utilisation.
Apart form the fact that SQL Server 2000 is coming close to end of life, why should we upgrade?
Any and all contributions are appreciated!

A: Besides all the features MatthewPK mentions, I also really like:

*

*Common Table Expressions (CTE) (which I find extremely helpful) - see Using Common Table Expressions, SQL Server CTE Basics or SQL Server 2005 Common Table Expressions for more details

*Ranking functions like ROW_NUMBER, RANK, DENSE_RANK and NTILE - see Ranking Functions (on MSDN) or New Ranking Functions in SQL Server 2005 for more details

*OUTPUT clause in SQL statements to output information about e.g. rows you've deleted with the DELETE statement, or updated with your MERGE statement - see the SQL Server Books Online for more details.
I'm taking care of an old SQL Server 2000 solution, and boy, how many times have I missed those features!

A: There are a number of reasons to make the migration, I'm sure.
My favorites are:
New DATE datatype (no more having to format strings to compare timestamped dates)
New Spatial Data types (geometry, geography)
New MERGE statement is great for upserts or any other "if exists" type logic
FILESTREAM gets you out of the blob problems (enforced DB integrity on filesystem directories!)
IMHO, from a developer's perspective, the most important upgrade is the TVP
The only shortfall I've personally encountered is that I had to rewrite my DTS packages to SSIS packages (but I think SSIS is great... just more work)

A: From a purely practical perspective, the most compelling advantages for me are several powerfull TSQL commands that are not available in 2000, e.g. PIVOT/UNPIVOT, and the addition of the intelligent syntax expansion to the 2008 Management Studio that made working with this tool substantially more productive.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Successfully sending email but link is null I use Url.page() function but it always returning null value. I tried many times but it still return null value. My email is successfully sent but link is null.
var link = Url.Page("/Account/ConfirmEmailModel/",
                    pageHandler: null,
                    values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                    protocol: Request.Scheme, Request.Host.ToString());

await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"verify email.");


text:
Q: Django 4.0 getting many to many field objects in List View I have a book model and a genre model that have a many to many relationship. How would I go about getting all the books for a specific genre in a list view. I'm assuming its faster to get a Genre object and get all the books from it using a query such as "genre.objects.book_set.all" rather than going through all books and seeing if they have the specified genre. However I'm not sure how I would do that in a ListView? I wanna take the genre name from the url and then use that to get the genre object.
Here is what I have:
urls.py:
path('genre/<string:name>', GenreListView.as_view(), name='book-genre'),

Models.py:
class Genre(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
    return self.name

class Book(models.Model):
name = models.CharField(max_length=150, unique=True)
description = models.TextField()
user_count = models.IntegerField()
pages = models.IntegerField()
genres = models.ManyToManyField(Genre)
image = models.ImageField(default='book_imgs/default.jpg', upload_to='book_imgs')

def __str__(self):
    return self.name

Views.py
class GenreListView(ListView):

    model = Genre

    def get_queryset(self):
Not sure what to put here....

        return

A: You should pass id of Genre, then apply filter in get_queryset method to get all the books for specific genres in the following way:
urls.py
path('genre/<int:id>/', GenreListView.as_view(), name='book_genre'),

views.py
class GenreListView(ListView):
    model = Book
    template_name = 'any_folder_name/any_file_name.html'
    context_object_name = 'specific_books'

    def get_queryset(self):
        qs = super().get_queryset()
        return qs.filter(genres=self.kwargs['id'])

Then, you can show books related to specific genre in the template.
any_file_name.html

    {% for book in specific_books %}

{{book.name}}

{{book.description}}

{{book.pages}}

    {% endfor %}

Or, you can simply do it with function based views too.
urls.py
 path('genre/<int:id>/', views.specific_books, name='specific_books'),

views.py
def specific_books(request, id):
    specific_books = Book.objects.filter(genres=id)
    return render(request, 'any_folder_name/any_file_name.html', {'specific_books': specific_books})

Edit:
If you want to filter all books through name of Genre, so do this:
urls.py
 path('genre/<str:name>/', views.specific_books, name='specific_books'),

views.py
def specific_books(request, name):
    specific_books = Book.objects.filter(genres__name__icontains=name)
    return render(request, 'home/index.html', {'specific_books': specific_books})

A: You can do something like this:
class SciFiListView(View):
    scifi_books = Book.objects.filter(genres__name__icontains="scifi")
    return render(request, "books/list.html", {"scifi_books": scifi_books})

list.html
{% for book in scifi_books %}

{{ book.name }} | {{ book.description }}

{% endfor %}

A: I decided to switch my view to a Detail View instead of a List View and then from the html page, I could access the books associated with that genre.
html:
{% for book in genre.book_set.all %}

{{ book.name }}

    {% endfor %}

view:
class GenreDetailView(DetailView):
    model = Genre
    context_object_name = "genre"

model:
class Genre(models.Model):
    name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(null=True, unique=True)

def __str__(self):
    return self.name

def get_absolute_url(self):
    return reverse("book-genre", kwargs={"slug": self.slug})

def save(self, *args, **kwargs):
    if not self.slug:
        self.slug = slugify(self.name)
    return super().save(*args, **kwargs)

Url:
path('genre/<slug:slug>', GenreDetailView.as_view(), name='book-genre'),

I find this better than filtering through every single book and checking if it has the genre you are looking for.


text:
Q: XML Parsing Error here i am creating xml file dynamically at run time  but i m getting error
XML Parsing Error: junk after document element
Location: http://localhost/tam/imagedata.php?imageid=8
Line Number 9, Column 1:
^
   $id=$_GET['imageid'];
     $dom = new DomDocument('1.0');
     $query="select * from tbl_image_gallery where imageId='$id'";
    $select=mysql_query($query);
    while($res=mysql_fetch_array($select))
    {
        $content = $dom->appendChild($dom->createElement('content'));
        $image = $content->appendChild($dom->createElement('image'));
        $small_image_path = $image->appendChild($dom->createElement('small_image_path'));
        $small_image_path->appendChild($dom->createTextNode("load/images/small/".$res['image']));
        $big_image_path = $image->appendChild($dom->createElement('big_image_path'));
        $big_image_path->appendChild($dom->createTextNode("load/images/big/".$res['image']));
        $description = $image->appendChild($dom->createElement('description'));
        $description->appendChild($dom->createTextNode($res['description']));
        $dom->formatOutput = true;
     }
    echo $test1 = $dom->saveXML();

and xml format is
<?xml version="1.0"?>
<content>
  <image>
    <small_image_path>load/images/small/1.jpg</small_image_path>
    <big_image_path>load/images/big/1.jpg</big_image_path>
    <description>hgjghj</description>
  </image>
<image><small_image_path>load/images/small/2.jpg</small_image_path><big_image_path>load/images/big/2.jpg</big_image_path><description>fgsdfg</description></image><image><small_image_path>load/images/small/3.jpg</small_image_path><big_image_path>load/images/big/3.jpg</big_image_path><description>sdfgsdfg</description></image><image><small_image_path>load/images/small/4.jpg</small_image_path><big_image_path>load/images/big/4.jpg</big_image_path><description>gsbhsg</description></image><image><small_image_path>load/images/small/4.jpg</small_image_path><big_image_path>load/images/big/4.jpg</big_image_path><description>gsbhsg</description></image><image><small_image_path>load/images/small/avatar.jpg</small_image_path><big_image_path>load/images/big/avatar.jpg</big_image_path><description></description></image></content>

A: Can it be that you are posting html code into the description field?
Could be usefull to add a CDataSection instead of a TextNode
$cdata = $dom->createCDATASection($res['description']);
$image->appendChild($cdata);


text:
Q: IOS have a report builder generate in PDF I have data to generate report that have header footer and content.
In the content have many group when the data in each group over the page area it add new page and write header of group and continued content data
Where can I have lib. or something to do this Task ??
Thanks For Advance.
Add for request code
    NSArray *headObject = [uniqueStates allObjects];////Store head of each group
    NSArray *detail; //Store all of data to present in table

    int allData = [detail count]; // Tel amount of all data to show
    /*
    int headGroupline = 1; //Tel amount of head group line
    int footGroupline = 1; //Tel amount of foot group line
    */
    int detailIndex = 0; ///Tel what line we are now
    int detailHeadIndex = 0; ///Tel what group we are now
    int subdetail = 0; // Tel what line on group now

    int aviableLineInpage = 24; // Line avilable in page for data to show

    int allPage = 0; //Sum of all page

    for (; detailIndex < allData; ) {
        allPage++;
        for (int i=0; i < aviableLineInpage;) {

            if (allData - detailIndex == 0) {
                ///ShowgrandTotal
                ........

                detailIndex++;
                i+=25;
            }else{
                if (i == 0) {
                    //Show Head Group
                     ......
                }else{
                    if (subdetail == [[detail filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(buy_date == %@)", headObject[detailHeadIndex]]] count]+1) {
                        detailHeadIndex++;
                        //Show Head Group
                          ..........
                    }else{
                        if (subdetail == [[detail filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(buy_date == %@)", headObject[detailHeadIndex]]] count]) {
                            //Show sum of each group
                               ..........
                            i++;
                            detailIndex++;
                            subdetail++;
                            detailHeadIndex++;
                        }else{
                            //Show data of detail
                            ........................
                            detailIndex++;
                            subdetail++;
                        }
                    }
                }
                i++;
            }

        }//for all line in page
    }//for allData

It format is:
date 27/01/2014
  data1
  data2
  data3
sum date 27/01/2014

date 28/01/2014
  data1
  data2
<============if page brake add new page and

date 28/01/2014
  data3
sum date 28/01/2014

grand total........

But it goes
date 27/01/2014
  data1
  data2
  data3
sum date 27/01/2014

  data1
  data2
<============if page brake add new page and

date 28/01/2014
  data3
grand total........

Thanks very much

A: Use CGPDFDocumentRef and the associated functions to create the PDF document and each page it contains. When you create a page (UIGraphicsBeginPDFPageWithInfo) you can get the associated drawing context (UIGraphicsGetCurrentContext). Once you have that you can draw in a number of ways:

*

*You could create a view with your header and footer, add content and render it into the view (using its layer)

*You could draw images and text direct into the context (using CoreText (CTFrameDraw))

You need to create the logic to set how much content can fit on any one page and when you need to create a new page.
Also, depending on how you choose to draw content into the context you may need to scale and transform (CGContextScaleCTM + CGContextTranslateCTM) the context so that your content isn't upside down.
See this Apple guide.

A:     int allData = [detail count]; // Tel amount of all data to show
    /*
    int headGroupline = 1; //Tel amount of head group line
    int footGroupline = 1; //Tel amount of foot group line
    */
    int detailIndex = 0; ///Tel what line we are now
    int detailHeadIndex = 0; ///Tel what group we are now
    int subdetail = 0; // Tel what line on group now

    int aviableLineInpage = 24; // Line avilable in page for data to show

    int allPage = 0; //Sum of all page

    for (; detailIndex < allData; ) {
        allPage++;
        for (int i=0; i < aviableLineInpage;) {

            if (allData - detailIndex == 0) {

                detailIndex++;
                i+=25;
            }else{
                if (i == 0) {

                    if (subdetail == -1) {
                        subdetail = 0;
                    }
                }else{
                    if (subdetail == -1) {

                        subdetail = 0;
                    }else{
                        if (subdetail == [[detail filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(buy_date == %@)", headObject[detailHeadIndex]]] count]) {

                            i++;

                            subdetail = -1;
                            detailHeadIndex++;
                            if (detailHeadIndex == [headObject count] ) {
                                detailIndex++;
                            }
                        }else{

                            detailIndex++;
                            subdetail++;
                        }
                    }
                }
            i++;
            }

        }//for all line in page
    }//for allData


text:
Q: GLSL Geometry shader to replace glLineWidth I'm trying to write a geometry shader to replace glLineWidth behavior. I want to draw lines with a customizable width (doing this with a uniform suffices for now). The lines should always have the same thickness, regardless of the camera projection or distance to where the lines are.
Based on a lot of googling, I've come up with the following geometry shader:
#version 330

layout (lines) in;
layout (triangle_strip, max_vertices = 4) out;

uniform mat4    u_model_matrix;
uniform mat4    u_view_matrix;
uniform mat4    u_projection_matrix;
uniform float   u_thickness = 4; // just a test default

void main()
{
    float r = u_thickness / 2;

    mat4 mv = u_view_matrix * u_model_matrix;
    vec4 p1 = mv * gl_in[0].gl_Position;
    vec4 p2 = mv * gl_in[1].gl_Position;

    vec2 dir = normalize(p2.xy - p1.xy);
    vec2 normal = vec2(dir.y, -dir.x);

    vec4 offset1, offset2;
    offset1 = vec4(normal * r, 0, 0);
    offset2 = vec4(normal * r, 0, 0);

    vec4 coords[4];
    coords[0] = p1 + offset1;
    coords[1] = p1 - offset1;
    coords[2] = p2 + offset2;
    coords[3] = p2 - offset2;

    for (int i = 0; i < 4; ++i) {
        coords[i] = u_projection_matrix * coords[i];
        gl_Position = coords[i];
        EmitVertex();
    }
    EndPrimitive();
}

For completeness, here is the vertex shader:
#version 330

in vec4 a_position;

void main() {
    gl_Position = a_position;
}

... and my fragment shader:
#version 330

uniform vec4 u_color = vec4(1, 0, 1, 1);
out vec4 fragColor;

void main() {
    fragColor = u_color;
}

I can't get the math to work in all situations. With an orthogonal camera, the above works fine:

But with a perspective camera, the problem is that the line is not a fixed size. It gets bigger and smaller relative to how far away the object is.

I expected the line the be the same size using a perspective camera as well. What am I doing wrong?

A: I managed to fix it by taking into account the viewport size, and scaling my r using that. I do not know if this is the most efficient way to solve this problem (I am by no means a math head), but it does work.
In the code below, I now do all the work in screen space rather than camera/view space, and I use the u_viewportInvSize vec2 (which is 1/viewportSize) to scale my desired radius!
#version 330

layout (lines) in;                              // now we can access 2 vertices
layout (triangle_strip, max_vertices = 4) out;  // always (for now) producing 2 triangles (so 4 vertices)

uniform vec2    u_viewportInvSize;
uniform mat4    u_modelviewprojection_matrix;
uniform float   u_thickness = 4;

void main()
{
    float r = u_thickness;

    vec4 p1 = u_modelviewprojection_matrix * gl_in[0].gl_Position;
    vec4 p2 = u_modelviewprojection_matrix * gl_in[1].gl_Position;

    vec2 dir = normalize(p2.xy - p1.xy);
    vec2 normal = vec2(dir.y, -dir.x);

    vec4 offset1, offset2;
    offset1 = vec4(normal * u_viewportInvSize * (r * p1.w), 0, 0);
    offset2 = vec4(normal * u_viewportInvSize * (r * p2.w), 0, 0); // changing this to p2 fixes some of the issues

    vec4 coords[4];
    coords[0] = p1 + offset1;
    coords[1] = p1 - offset1;
    coords[2] = p2 + offset2;
    coords[3] = p2 - offset2;

    for (int i = 0; i < 4; ++i) {
        gl_Position = coords[i];
        EmitVertex();
    }
    EndPrimitive();
}

A: I'm not an expert, but having done this before, I'll offer my insight.
I'm assuming your gl_Positions are straight from the vertex shader which was calculated using a projection matrix. That means that their w component is the "clip-space position" of the point; this is what is used by the pipeline to give the projection its effect (further away things are smaller). So it needs to be taken into account.
Fortunately, the only thing you need to do is multiply your offset with it.
coords[0] = p1 + offset1 * p1.w;
coords[1] = p1 - offset1 * p1.w;
coords[2] = p2 + offset2 * p2.w;
coords[3] = p2 - offset2 * p2.w;

This should give you the effect you want.

A: Geometry shaders are not known for being fast. Using a geometry shader is a performance killer and should therefore only be suggested when all other options are off the table.
A possible solution without using a geometry shader is presented in the answer to OpenGL Line Width.

Anyway if you want to use a geometry shader, transform the vertex coordinate with the model view projection matrix in the vertex shader:
#version 330

in vec4 a_position;
uniform mat4  u_modelviewprojection_matrix;

void main()
{
    gl_Position = u_modelviewprojection_matrix * a_position;
}

Compute the normalized device coordinate in the geometry shader, by Perspective divide:
vec3 ndc_1 = gl_in[0].gl_Position.xyz / gl_in[0].gl_Position.w;
vec3 ndc_2 = gl_in[1].gl_Position.xyz / gl_in[1].gl_Position.w;

The normalized device space is a cube with the left, bottom, near of (-1, -1, -1) and right, top, back of (1, 1, 1).
Compute the vector between the points the of the lines. Scale by the viewport size to take into account the aspect ratio of the viewport.
Finally get the Unit vector to the line:
vec2 dir    = normalize((ndc_2.xy - ndc_1.xy) * u_viewportSize);
vec2 normal = vec2(-dir.y, dir.x);

Compute the hal thickness offset vector normal to the line and transform it to normalized device space. This is done by scaling by the inverse aspect ratio and multiplying by 2:
vec3 offset = vec3(normal * u_thickness * 0.5 / u_viewportSize * 2.0, 0.0);

Add the offset vector to the normalized device coordinates and "undo" the perspective divide:
gl_Position = vec4((ndc_1 + offset) * gl_in[0].gl_Position.w, gl_in[0].gl_Position.w);
EmitVertex();
gl_Position = vec4((ndc_1 - offset) * gl_in[0].gl_Position.w, gl_in[0].gl_Position.w);
EmitVertex();
gl_Position = vec4((ndc_2 + offset) * gl_in[1].gl_Position.w, gl_in[0].gl_Position.w);
EmitVertex();
gl_Position = vec4((ndc_2 - offset) * gl_in[1].gl_Position.w, gl_in[0].gl_Position.w);
EmitVertex();

That can be further optimized and leads to the following Geometry shader
#version 330

layout (lines) in;                              // now we can access 2 vertices
layout (triangle_strip, max_vertices = 4) out;  // always (for now) producing 2 triangles (so 4 vertices)

uniform vec2  u_viewportSize;
uniform float u_thickness = 4;

void main()
{
    vec4 p1 = gl_in[0].gl_Position;
    vec4 p2 = gl_in[1].gl_Position;

    vec2 dir    = normalize((p2.xy/p2.w - p1.xy/p1.w) * u_viewportSize);
    vec2 offset = vec2(-dir.y, dir.x) * u_thickness / u_viewportSize;

    gl_Position = p1 + vec4(offset.xy * p1.w, 0.0, 0.0);
    EmitVertex();
    gl_Position = p1 - vec4(offset.xy * p1.w, 0.0, 0.0);
    EmitVertex();
    gl_Position = p2 + vec4(offset.xy * p2.w, 0.0, 0.0);
    EmitVertex();
    gl_Position = p2 - vec4(offset.xy * p2.w, 0.0, 0.0);
    EmitVertex();

    EndPrimitive();
}

Fragment shader
#version 330

out vec4 fragColor;
uniform vec4 u_color = vec4(1, 0, 1, 1);

void main()
{
    fragColor = u_color;
}

Complete example: https://github.com/Rabbid76/graphics-snippets/blob/master/example/cpp/opengl/example_shader_geometry_1_line.cpp


text:
Q: How to figure out that given point is inside the rectangle or not i am working on app in which i want to draw an Rectangle.for draw a rectangle i have two CGRECT point.after draw a rectangle i have to pass a point and check whether the given point is lying inside the rectangle or not.can someone help me.Thanks
-(void)touchBeganAtPoint:(CGPoint)point{

    if (isDrawingCompleted) {
        match = NSNotFound;

        for (NSInteger i = 0; i < [pointArray count]; i++)
        {
            NSValue *touchPointValue = [pointArray objectAtIndex:i];
            CGPoint currentPoint = [touchPointValue CGPointValue];
            CGRect controlPointRect = [self controlPointRectForPoint:currentPoint];

            if (CGRectContainsPoint(controlPointRect, point))
            {
                match = i;
                break;
            }
        }
    }
}

point is the variable which i have to check lie inside the rectangle which will make with two point store in point array.point array have always two point.

A: Use CGRectContainsPoint.
bool CGRectContainsPoint (
   CGRect rect,
   CGPoint point
);

A: Use CGRectContainsPoint function


text:
Q: Ошибка при сборке проекта на webpack При запуске сборки в консоль вылетает вот такая ошибка:

throw new _ValidationError2.default(ajv.errors, name)

Сам так и не смог разобраться. Помогите, пожалуйста, понять что не так и как исправить.
Полный вид ошибки:

Вот конфиг:
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: {
        backup: './app/scripts/backupBase/backupDB',
        newOrder: './app/scripts/newOrder/newOrder',
        searchOrder: './app/scripts/searchOrder/searchOrder',
        redact: './app/scripts/redactOrder/redactOrder',
        mainPageCss: './app/css/mainPage.css'
    },
    output: {
        path: __dirname + '/build/js',
        filename: '[name].js',
        library: '[name]'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: [/node_modules/],
                use: [{
                    loader: 'babel-loader',
                    options: { presets: ['es2015'] }
                }]
            },
            {
                test:   /\.css$/,
                use: ExtractTextPlugin.extract({
                        fallback: 'style-loader',
                        use: 'css-loader'
                    })
            }, {
                test:   /\.(png|jpg|svg|ttf|eot|woff|woff2)$/,
                loader: 'file?name=[path][name].[ext]'
            }]
    },

    plugins: [
        new ExtractTextPlugin({
            filename: '[name].css',
            disabled: false,
            allChunks: true})
    ]
};

A: https://webpack.js.org/plugins/extract-text-webpack-plugin/
изменил строку на массив:
   use: ExtractTextPlugin.extract({ fallback: "style-loader", use: ['css-loader', 'sass-loader'] })


text:
Q: Entity Framework 5 namespaces I want to add Entity Framework 5 database first into a class library in Visual Studio 2012 targeting .net framework 4.5. I am confused with all the labels I need to key in:

*

*The EDMX file name when adding ADO.NET entity data model to the project. I put 'MyEF.edmx'.

*When saving the connection string into the config file. I put 'MyEntities'.

*After selecting some tables to include in my model, there's a textbox to input model namespace. I put 'MyModel'.

*Property 'custom tool namespace' of the MyEF.edmx file. I put 'TheEF'.

*Property 'custom tool namespace' of the MyEF.Context.tt file. I put 'TheContext'.

*Property 'custom tool namespace' of the MyEF.tt file. I put 'TheModel'.

Opening MyEF.edmx with ADO.NET entity data model designer, looking at the properties of MyModel, there are:

*

*entity container name, filled with 'MyEntities'. So the connection string name goes here.

*namespace, filled with 'MyModel'. This is coming from the table selection textbox.

Putting something into the edmx custom tool namespace doesn't seem to do anything. I got this conclusion because when I grep the entire source code folders, I found it only in a vbproj file.
Putting 'TheModel' into MyEF.tt custom tool namespace produces error from MyEF.Context.vb saying type 'MyTable' (this is the name of my database table) is not defined.
Can someone explain the purpose of each label?
If I want to put all the classes generated by this one edmx (DbContext, models, etc.) into one namespace, 'MyEF', what should I put in each of those places?

A: The various properties are used as follows:

*

*EDMX file name --> Used for the EDMX file name

*Connection string name --> Used for the connection string name in the config file, and also for the container name of the conceptual model (CSDL) part of the EDMX

*Model namespace --> Used for the namespace of the conceptual model (CSDL) part of the EDMX, and also for the store model (SSDL) part with .Store appended

*Custom tool namespace for the EDMX file --> I don't believe this is used for anything when using T4 generation of POCO entities. When using EF1-style built in code generation, setting this property will set the .NET namespace for all generated files.

*Custom tool namespace for .Context.tt file --> The .NET namespace used in the source file for the context

*Custom tool namespace for .tt file --> The .NET namespace used in the source files for the entities

Note that if you set the .Context.tt and .tt custom namespaces to different things, then the context will be generated in a different namespace to the entity types and this won't compile out-of-the-box. You can update the .tt files if you want to use different namespaces here, but more often people just use the same namespace for both.
Also note that you may need to choose "Run Custom Tool" from the context menu for each .tt file after changing the properties in order for the code to be re-generated.


text:
Q: Java XML String with attributes to NodeList (parsing) I have a string, whose contents is an XML document.
Here is an example of a string.
String xmlContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<Service oem=\"myOem\" agent=\"myAgent\" version=\"0.5.5.0\" build=\"30-01-2014-11-46\" />";

I want to convert this string to a NodeList. A Google search led to this article.
I tried the following code:
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlContent));
Document doc = db.parse(is);
NodeList oNodeService = doc.getElementsByTagName("Service");

The problem is that I get a rip on the "db.parse(is)" line. The problem seems to be that this method does not support XML attrihutes.
The error message is:
[Fatal Error] :1:70: Element type "Service" must be followed by either attribute specifications, ">" or "/>".
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 70; Element type "Service" must be followed by either attribute specifications, ">" or "/>".
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at PkgNetAccelerator32.MainEvents.ShowHtsInfo(MainEvents.java:1575)

How can I successfully convert this XML string to a NodeList?
UPDATE:
Hmm, the failure is specific to the XML string. I gave a shortened version above. I removed all attributes that cause no crashes.
String xmlContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Service hostname=\"sarah-linux.localdomain\"uname=\"Linux sarah-linux.localdomain 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux\" />";

If I were to hazard a guess, I would say it is the period or the dash. I wanted to get this update in first.

A:     String xmlContent = "<System><rpm-items><rtmap-items><Rule-list><name>RoutingPolicy3</name></Rule-list></rtmap-items></rpm-items></System>";
    InputStream isr = new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8));
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(isr);

    NodeList ruleList = doc.getElementsByTagName("System");


text:
Q: get value of checkbox laravel 4 I want to return an array that contains my list checked I do this :
View :
 {{ Form::checkbox('saison[]', $saison->id, false,array('class' =>'chk')) }}
 {{ HTML::link('ouvrircompte', 'Valider') }}

Controller :
 public function postOuvrircompte() {

    $saisons =Input::get('saison');
    foreach ($saisons as $saison)
       echo $saison ;
    // ....

Route:
Route::post('biens/{id}/details', 'UserController@postOuvrircompte');

But I have no result


text:
Q: Is there a list available for EventTrigger EventNames? I do not seem to find a list of available EventNames used in EventTriggers for different UI elements in WPF. I know some of the commonly used Event Names like

*

*Loaded

*Click

But it would be nice to get a list of all the event names available for example for a Grid Element.

A: The best resource for this would probably be Microsoft's documentation. For instance this is a list of all the events for a WPF grid.
http://msdn.microsoft.com/en-us/library/system.windows.controls.grid_events(v=vs.110).aspx

A: In Visual Studio you can also see the list of available events for a certain control.
They all should be usable as event triggers.
Just click on the respective control in the designer and take a look at the properties tab.
There should be a "flash" symbol at the top right corner of the properties tab. By clicking on it, you can change from "property view" to the "event view" of the control you selected.
You will then see all available events for the selected control.
You can then search for the documentation in the event your are interested in.


text:
Q: How to convert hexadecimal to decimal on DB2 I have a field in a db2 database which is on hexadecimal format i.e 0x0a
which is number 10 in decimal format. The hex field's datatype is char(1) for bit data.
hex(myfield) gives me the hexadecimal 0A

How can i convert 0x0a to 10 in a query on db2?
I have tried: cast(hex(myfield),integer)
and int(hex(myfield))
with no luck.
Is it possible?

A: AFAIK, there is no such single function built into DB2 that would perform that conversion, but there is a blog post showing how to define such a function. The following function is taken from that article:
--#SET TERMINATOR @
CREATE OR REPLACE FUNCTION HEX2INT(str VARCHAR(8))
RETURNS INTEGER
SPECIFIC HEX2INT
DETERMINISTIC NO EXTERNAL ACTION CONTAINS SQL
BEGIN ATOMIC
  DECLARE res INTEGER  DEFAULT 0;
  DECLARE pos INTEGER DEFAULT 1;
  DECLARE nibble CHAR(1);
  WHILE pos <= LENGTH(str) DO
    SET nibble = SUBSTR(str, pos, 1);
    SET res = BITOR(CASE WHEN BITAND(res, 134217728) != 0
                         THEN BITOR(16 * BITANDNOT(res, 134217728),
                                    -2147483648)
                         ELSE 16 * res END,
                    CASE nibble
                         WHEN '0' THEN 0
                         WHEN '1' THEN 1
                         WHEN '2' THEN 2
                         WHEN '3' THEN 3
                         WHEN '4' THEN 4
                         WHEN '5' THEN 5
                         WHEN '6' THEN 6
                         WHEN '7' THEN 7
                         WHEN '8' THEN 8
                         WHEN '9' THEN 9
                         WHEN 'A' THEN 10
                         WHEN 'a' THEN 10
                         WHEN 'B' THEN 11
                         WHEN 'b' THEN 11
                         WHEN 'C' THEN 12
                         WHEN 'c' THEN 12
                         WHEN 'D' THEN 13
                         WHEN 'd' THEN 13
                         WHEN 'E' THEN 14
                         WHEN 'e' THEN 14
                         WHEN 'F' THEN 15
                         WHEN 'f' THEN 15
                         ELSE RAISE_ERROR('78000', 'Not a hex string')
                         END),
        pos = pos + 1;
  END WHILE;
  RETURN res;
END
@
--#SET TERMINATOR ;

There are more functions for various conversion operations described.

A: I'm sure you could simplify the following
WITH fred (x) AS (VALUES 'f1'),

     nurk (a) as (SELECT UPPER(substr(x,1)) from fred
                  union all
                  select UPPER(substr(a,2)) from nurk
                   where substr(a,1,1) <> ' '),

     bare (b, c) as (select substr(a,1,1), (length(a) - 1)
                  from nurk),

     trap (d) as ((SELECT (ASCII(B) - ASCII('7')) *
                   power(16,c)
                   FROM BARE
                   WHERE (B BETWEEN 'A' AND 'F')
                   and
                   c <> -1)
                   union
                  (SELECT (ASCII(B) - ASCII('0')) *
                   power(16,c)
                   FROM BARE
                   WHERE (B not BETWEEN 'A' AND 'F')
                   and
                   c <> -1))
select sum(d) from trap

ran as
db2 -f "filename of above"
gave result of
241
try testing with values other than f1
John Hennesy

A: In Standard SQL (I hope so):
with inp (val) as
(values ('FF'), ('AB'), ('ABCDEF')),
     calc(val, urval, res, f) as
(select case when length(val) > 1
                  then substr(val, 1, length(val)-1)
             else '' end, val,
        locate(right(val, 1),'0123456789ABCDEF')-1, 16
 from   inp
 union  all
 select case when length(val) > 1
                  then substr(val, 1, length(val)-1)
             else '' end, urval,
        res + ((locate(right(val, 1),'0123456789ABCDEF')-1) * f),
        f * 16
 from   calc
 where  length(val) > 0)
select  urval, res
from    calc
where   val = ''

==>
URVAL             RES
FF                255
AB                171
ABCDEF     11.259.375

A: convert( datatype, column_Name)

Ex:  convert(decimal(18,2), column_Name)
--here column_Name has Hexadecimal value

A: The syntax is as follows
select CONVERT(int, 0xFFFFFF)

Check the documentation below should you need more details on converting to and from specific datatypes
Data types
https://technet.microsoft.com/en-us/library/ms187594(v=sql.105).aspx
Converting data types
https://technet.microsoft.com/en-us/library/ms191530(v=sql.105).aspx


text:
Q: How do I select a random value from an array in TestComplete? I'm using JScript to test the character limit of a textbox, and also to make sure that numbers, characters, and special characters are accepted.
If I have an array like ("a", "2", "$", "D"), how can I choose one random value at a time?
I know about Math.round(Math.random()*9), but I don't want to return just an integer.
Thank you.

A: Here is what I did:
str = new Array("a", "2", "$", "D");
var result = str[Math.floor(Math.random()*str.length)];
textBox.Keys(result);


text:
Q: How do I refresh a view? I'm refreshing my view model onRouteMatched...
    _onRouteMatched: function(oEvent) {
        this.getView().setModel(new JSONModel({siteInfo: {}, surveyInfo: {}, categories: []}), "view");
        var oViewModel = this.getView().getModel("view");
}

However, if I'm returning to the page without refreshing (by pressing the back arrow and then returning), I'm getting a duplicate ComponentId error when creating the view again.
        var oPanel = new sap.m.Panel({
           expandable: true,
           expanded: false,
           headerText: oData.results[0].CategoryDesc,
           id: "Panel" + index
        });

It's as though the view component "Panel" still exists, so that a new one can only be created on refresh, not onRouteMatched.
This works fine if I refresh the page, but how can I get the view to refresh on onRouteMatched?

A: Simply avoid programmatical controls creation (by coding) and try to define all the stuff right it the XML view and make use of bindings - it's a very powerfull feature that can solve 99% of your problems.
You define binding once and change the view only via data modifications in the model, but not via the DOM manipulation (bindings will do it for free based on the model state).
I'd recommed you to go throught the data binding tutorials in the official documentation.
As for your problem, if to imagine the solution without bindings, you should always destroy the stuff manually and recreate it again. Or perform some existence checks.


text:
Q: Trying to find the 2nd largest number in python using max function so i have return this code -
n = int(input())
arr = list(map(int, input().split()))
# arr.sort(reverse = True)
arr1 = max(arr)
arr2 = max(arr, key=lambda x: min(arr)-1 if (x == arr1) else x)
print(arr2)

Unable to understand how this min(arr)-1 is helping out here.

A: The logics behind the code you posted are to first find the largest number from the list with a normal call to max, and then find the second largest number by calling max again, but with a key function that by default returns the current number as the key, except that if it's the largest number, it returns a key that is guaranteed to be the smallest in the list so that it won't get returned by max again. In this case, the smallest number minus one is the key that is used by the code to make it the smallest of all.

A: In the expression:
arr2 = max(arr, key=lambda x: min(arr)-1 if (x == arr1) else x)

A lambda expression is being provided as the key argument to the max() function.  This means that this lambda will actually provide the values for the input arr list.  The lambda says that if the x value happens to be the maximum value, then replace it with the minimum value minus 1.  This effectively removes the maximum value from the list from being considered by the max() function.  This then leaves behind the second to highest value as the maximum value.
Another way to do this, which seems more intuitive to me, would be to use a list comprehension:
arr2 = max([x for x in arr if x != max(arr)])

Here we just explicitly remove the max value and then let max() find the second to highest value.


text:
Q: Extract numbers from decimal list I searched around not found suitable answers, maybe a simple question but really stop me forward:
aList = [Decimal('-1.23'), Decimal('4.56')]
how to extract only the numbers: ['-1.23', '4.56']?
any better methods than using split or re.findall()
Many thanks!

A: You can use str(…) [python-doc] to get a textual presentation of the decimal, for example:
>>> [str(a) for a in aList]
['-1.23', '4.56']

Now these are strings.
You can furthermore use float(…) [python-doc] to convert it to the nearest representable floating point number:
>>> [float(a) for a in aList]
[-1.23, 4.56]


text:
Q: java.lang.NullPointerException: FloatingActionButton.setVisibility(int)' on a null object reference I have created an Activity which contains four Floating Button and a fragment which calls Activity's Floating button to make them visible/invisible but when I access these Floating Buttons from fragment it throws null pointer exception.
Activity Code:
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    getInitialized();

    fabSettings = (FloatingActionButton) this.findViewById(R.id.fabSetting);
    fabStory = (FloatingActionButton) this.findViewById(R.id.fabStory);
    fabImage = (FloatingActionButton) this.findViewById(R.id.fabImage);
    fabVideo = (FloatingActionButton) this.findViewById(R.id.fabVideo);

}

Fragment Code:
 @SuppressLint("RestrictedApi")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_all_community, container, false);

    SessionManager sessionManager = new SessionManager(getActivity());
    if(sessionManager.isLoggedIn()){

        ActivityUser.fabSettings.setVisibility(View.VISIBLE);
        ActivityUser.laySearchCode.setVisibility(View.VISIBLE);
        ActivityUser.bottomLayout.setVisibility(View.VISIBLE);

        tvCreateCommunity.setVisibility(View.VISIBLE);
    }else{
        MainActivity.fabSettings.setVisibility(View.VISIBLE);
        MainActivity.bottomLayout.setVisibility(View.VISIBLE);
        MainActivity.laySearchCode.setVisibility(View.VISIBLE);
        ((MainActivity) getActivity()).getSupportActionBar().setTitle("");
        tvCreateCommunity.setVisibility(View.GONE);
    }
 }

Please help

A: Use this code
Fragment:
public class Fragment extends Fragment {

    public interface onHideEventListener {
        public void hideEvent(boolean isVisible);
    }

    onHideEventListener hideEventListener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            hideEventListener = (onHideEventListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement onHideEventListener");
        }
    }

    final String LOG_TAG = "myLogs";

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment2, null);

        SessionManager sessionManager = new SessionManager(getActivity());
        if(sessionManager.isLoggedIn()){
            hideEventListener.hideEvent(false);
        }else{
            hideEventListener.hideEvent(true);
        }
        return v;
    }
}

Activity:
public class MainActivity extends Activity implements onSomeEventListener{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public void hideEvent(boolean isVisible) {
        fabSettings.setVisibility(isVisible ? View.VISIBLE : View.INVISIBLE);
        laySearchCode.setVisibility(isVisible ? View.VISIBLE : View.INVISIBLE);
        bottomLayout.setVisibility(isVisible ? View.VISIBLE : View.INVISIBLE);
    }
}


text:
Q: Delete dial call number from recent call list in ios I have a some special requirement to delete dial call number from call list. I research a lot on SO but not able to get any answer for this. Is it possible in iPhone?

A: Apple doesn't allow developers to modify call list or history, since it will violate user's privacy policy. It is not possible to achieve in iOS with iOS public framework, used to submit apps to appstore. It is only possible by using private frameworks... or you can say jailbreaking the device. But you won't be able to submit app to store. It will be rejected.

A: Simple answer: No you cannot. Apple iOS doesn't allow you to access some of the applications such as Phone and Messages - So it is not possible for you directly access the call log, read messages or whatsoever. What you can do is, you can open the Messages/Phone app with a pre-defined number to call or a message to send for performing user verification actions.
Take the example of Uber app; you can call the driver by tapping on the Contact button, but there is no way that app can access your phone log and delete the recent numbers from the record - unlike Android devices.
It may be possible by jailbreaking, which on the other hand won't let you put your app on the App Store.


text:
Q: slicing tuples backwards - how to handle getting the first element? Let's say I want elements 1-3 of a tuple, backwards:
x = (0,1,2,3,4)
x[1:4]

Returns (1,2,3)
And
x[3:0:-1]

Returns (3,2,1)
But what if I want elements 0-2?
I can do x[2::-1] to get the correct answer of (2,1,0) but x[2:0:-1] returns (2,1) and x[2:-1:-1] returns ().
Is there a way to slice to the last item without using a if statement if I am slicing at unknown intervals?

A: One slightly inefficient way:
x[0:3][::-1]

Which is equivalent to:
tuple(reversed(x[0:3]))

I'm not sure offhand how well the unnecessary intermediate tuple gets optimized away.

A: You can use None in place of the empty element:
x[2:None:-1]

A: with x[-n:]  you can get the last n index and with [::-1] you can inverse it !
>>> x[-2:][::-1]
(4, 3)
>>>

A: Perhaps merge a "reverse-sentinel" tuple with your original tuple, and subscript that:
>>> x = (0, 1, 2, 3)
>>> y = (0,)

Then:
>>> (y + x)[3:0:-1]
(2, 1, 0)
>>> (y + x)[2:0:-1]
(1, 0)

Not as fast as Peter DeGlopper's solution, though:
#!/usr/bin/env python

import time

x = tuple(range(0,int(1e6)))
y = (0,)

start_time = time.time()
a = (y+x)[3:0:-1]
print("tuple add --- %s seconds ---" % (time.time() - start_time))

start_time = time.time()
b = x[0:3][::-1]
print("tuple rev --- %s seconds ---" % (time.time() - start_time))

Not even close, really:
$ ./test61.py
tuple add --- 0.0153260231018 seconds ---
tuple rev --- 6.19888305664e-06 seconds ---


text:
Q: How to set transparent background for richtextbox using the WPF RichTextBoxToolBar Control? I am using the WPF RichTextBoxToolBar control from this Code Project project, combined with the Exteneded WPF Toolkit's RichTextBox control.
When I enter text for the first time with no formatting it's all ok and the background is Transparent. But when I use the toolbar to set the background to Transparent it actually sets it to White. I've noticed the additional \highlight1 parameter in the RTF format of the text which does this thing.
Does anyone have experience with this toolbar? Is there a way to change this behavior? Can I disable the background color picker command?
Following is the code of a small test project I made to investigate this. The project only needs to install the Extended WPF Toolkit from NuGet and reference the dll from this zip.
XAML:
<Window x:Class="RtbTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:rtb="clr-namespace:RichTextBoxToolBar;assembly=RichTextBoxToolBar"
        xmlns:toolkit="http://schemas.xceed.com/wpf/xaml/toolkit" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <rtb:RichTextBoxToolBar Margin="0,0,0,5" DockPanel.Dock="Top" Name="EditTextToolbar" />

        <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal">
            <Button Content="Save RTF text" Click="ShowRtfText"/>
            <Button Content="Reload RTF text" Click="ReloadRtfText"/>
        </StackPanel>

        <toolkit:RichTextBox Name="EditTextRtb">
            <toolkit:RichTextBox.TextFormatter>
                <toolkit:RtfFormatter />
            </toolkit:RichTextBox.TextFormatter>
        </toolkit:RichTextBox>
    </DockPanel>
</Window>

Codebehind:
namespace RtbTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ShowRtfText(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(EditTextRtb.Text);
        }

        private void ReloadRtfText(object sender, RoutedEventArgs e)
        {
            string rtfText;

            rtfText = EditTextRtb.Text;
            EditTextRtb.Text = rtfText;
        }
    }
}


text:
Q: smartWizard and jQuery validate I am using smartWizard (can be found here http://techlaboratory.net/smartwizard) and now want to validate the form using jQuery validate plugin (can be found here http://bassistance.de/jquery-plugins/jquery-plugin-validation/ or here http://jqueryvalidation.org/)
I tried
$('#wizard').smartWizard({
    onFinish: function() {
        $("form").validate();
    }
});

but no working !
I am using .validate() only because i passed the rules in HTML attributes!

A: Well guys i found the answer; How we will use jQuery Validation with smartWizard? Simply submit the form on "onFinish" call back of smartWizard, put .validate(); in the page where ever you want. Validation plugin executes on the form submission, smartWizard does not submit the form. It actually tell you that user is at the last step of wizard and just clicked the Finish button.
$('#wizard').smartWizard({
    onFinish: function() {
       $("form").submit();
    }
});

$("form").validate({
    rules: {
        username: "required"
    }
});

There are many ways to apply a rule in jQuery Validation, above is one of them!

A: Latest version (SmartWizard 4.x) have an implementation with jQuery validator plugin. Check this demo Smart Wizard: Demo Input Validation
Also see jQuery Smart Wizard v6 Form Validation Demo


text:
Q: How to add explicit WHERE clause in Kafka Connect JDBC Source connector I am using kafka connect to source data from DB2 to kafka topic and i am configuring sql query to read the data from DB2 , below is query
SELECT SEQ_I AS error_id, TRIM(SEND_I) AS sca , to_char(CREATE_TS,'YYYY-MM-DD HH24:MI:SS.FF3') AS create_timestamp, CREATE_TS, TRIM(ERR_MSG) AS error_message , CASE substr(ERR_MSG,1,locate('-',ERR_MSG)-1) WHEN 'WARNING' THEN 'W' WHEN 'SUSPENDED' THEN 'F' END ERROR_TYPE FROM INTCHG_ERROR_DIR WHERE TRAN_I ='503' AND PRCS_N = 'GLOBAL'

am using setting "timestamp.column.name": "CREATE_TS" here problem is in the query their is already WHERE clause , and kafka connect tried to add another where clause with timestamp column and it is creating issue and one more issue is if i remove where clause from sql clause like below
SELECT SEQ_I AS error_id, TRIM(SEND_I) AS sca , to_char(CREATE_TS,'YYYY-MM-DD HH24:MI:SS.FF3') AS create_timestamp, CREATE_TS, TRIM(ERR_MSG) AS error_message , CASE substr(ERR_MSG,1,locate('-',ERR_MSG)-1) WHEN 'WARNING' THEN 'W' WHEN 'SUSPENDED' THEN 'F' END ERROR_TYPE FROM INTCHG_ERROR_DIR

then am getting error with substr , like below
SQL Error [22011]: THE SECOND OR THIRD ARGUMENT OF THE SUBSTR OR SUBSTRING FUNCTION IS OUT OF RANGE. SQLCODE=-138, SQLSTATE=22011, DRIVER=4.19.26

can anyone suggest on both is this issues , am stuck at this point .

A: This happens because you are trying to use both "mode": "timestamp" and query. TimestampIncrementingTableQuerier appends a WHERE clause to the query that conflicts with existing WHERE clauses in the query.
JDBC source connector docs is clear on this:

query
If specified, the query to perform to select new or updated rows. Use
this setting if you want to join tables, select subsets of columns in
a table, or filter data. If used, this connector will only copy data
using this query -- whole-table copying will be disabled. Different
query modes may still be used for incremental updates, but in order to
properly construct the incremental query, it must be possible to
append a WHERE clause to this query (i.e. no WHERE clauses may be
used). If you use a WHERE clause, it must handle incremental queries
itself.

As a workaround, you can modify your query to (depending on what SQL flavour are you using)
SELECT * FROM ( SELECT * FROM table WHERE ...)

or
WITH a AS
   SELECT * FROM b
    WHERE ...
SELECT * FROM a

For example, in your case the query should be
"query":"SELECT * FROM (SELECT SEQ_I AS error_id, TRIM(SEND_I) AS sca , to_char(CREATE_TS,'YYYY-MM-DD HH24:MI:SS.FF3') AS create_timestamp, CREATE_TS, TRIM(ERR_MSG) AS error_message , CASE substr(ERR_MSG,1,locate('-',ERR_MSG)-1) WHEN 'WARNING' THEN 'W' WHEN 'SUSPENDED' THEN 'F' END ERROR_TYPE FROM INTCHG_ERROR_DIR WHERE TRAN_I ='503' AND PRCS_N = 'GLOBAL') o"


text:
Q: Outputting tictactoe board I'm trying to print my tictactoe board so it looks like
 | |
-+-+-
 | |
-+-+-
 | |

This is my code:
def __str__(self):
    result = ""
    for i in range(self.nrows):
        for j in range(self.ncols):
            cell = str(self.gameboard[i][j])
            result += cell + "|"
        result += "\n"
        result += "-+"
        result += '\n'
    return result

The result looks like
 | | |
-+
 | | |
-+
 | | |
-+

How should I change the code so it looks like the first board? self.nrows is the number of rows, self.ncols is the number of columns, and self.gameboard is the 2d array.

A: That's not the most pythonic way, and you probably should diverge the code into some functions, but it's working:
def __str__(self):
    result = ""
    for i in range(self.nrows):
        for j in range(self.ncols-1):
            cell = str(self.gameboard[i][j])
            result += cell + "|"
        result += "\n"
        if i == self.nrows - 1:
            break  # added the last line, which is just |
        for j in range(self.ncols-1):
            result += "-+"
        result += '-'
        result += '\n'
    return result

Output for self.nrows = self.ncols = 3 and self.gameboard[i][j] = ' ' for each i,j:
 | |
-+-+-
 | |
-+-+-
 | |

A: You need to change the row result += "-+" to result += "-+" * self.ncols + "-". Reason is that you print "-+" symbol only once, but need to do that as many time as your number of columns. Also, in the end you need to add one more "-" symbol to make it look symmetric. In the end just remove the last row that have 2*ncols+2 symbols.
The complete code would be:
def __str__(self):
    result = ""
    for i in range(self.nrows):
        for j in range(self.ncols):
            cell = str(self.gameboard[i][j])
            result += cell + "|"
        result += "\n"
        result += "-+" * self.ncols + "-"
        result += '\n'

    # Remove the last row
    result = result[:-2*ncols-2]
    result += "\n"
    return result


text:
Q: If dontdisplaylastusername is turned on, loginui.exe keeps crashing with Microsoft credential provider V2 sample
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System]
  "dontdisplaylastusername"=dword:00000001

I was trying to build a custom V2 Credential Provider and basing it off of Microsoft's code sample. The custom credential provider works as expected in most scensrios. However, if I enable the following setting dontdisplaylastusername, either through policy or by setting this registry setting and try to go to the login screen, the cursor just spins and the screen just flashes and I am never able to get the login screen to come up. Without any custom v2 credential providers installed, I am able to get to the Other User screen correctly.
How can I fix this? I tried adding a username field to my custom version since Microsoft's version did not have one but that did not change anything and still crashed.
Any ideas?
This is the github repo I was using for the sample
Here is an example of the fault that is logged for the sample credential provider.
Fault bucket , type 0
Event Name: APPCRASH
Response: Not available
Cab Id: 0
Problem signature:
P1: LogonUI.exe
P2: 10.0.10586.0
P3: 5632d88c
P4: SampleV2CredentialProvider.dll
P5: 0.0.0.0
P6: 56cc64dd
P7: c0000005
P8: 0000000000003086
P9:
P10:
Attached files:
These files may be available here:
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\AppCrash_LogonUI.exe_5e45fd9b49f0ea6611374ae56677dfa1cb3a1fe_9798b224_0a4ffaf8
Analysis symbol:
Rechecking for solution: 0
Report Id: 5efbdb96-de9f-4254-b259-1beea7137fc7
Report Status: 96
Faulting application name: LogonUI.exe, version: 10.0.10586.0, time stamp: 0x5632d88c
Faulting module name: SampleV2CredentialProvider.dll, version: 0.0.0.0, time stamp: 0x56cc64dd
Exception code: 0xc0000005
Fault offset: 0x0000000000003086
Faulting process id: 0x3a8
Faulting application start time: 0x01d1910e42a0efb5
Faulting application path: C:\Windows\system32\LogonUI.exe
Faulting module path: C:\Windows\system32\SampleV2CredentialProvider.dll
Report Id: 038f9265-0f6f-45fa-bc3e-6c7de490ca34
Faulting package full name:
Faulting package-relative application ID:


text:
Q: Oracle - only allow items to be inserted if three column values are unique and a fourth column is not equal to a given char I am trying to enforce some uniqueness on data at the db level. For the sake of argument, my columns are:
ID
DocID (FK)
FileName
FileRevision
Province
ActiveState

So in this example I want the combo of DocID, FIleName, and FileRevision entered only once. This is no issue, I can just create a UNIQUE constraint.
However the problem is, if 'ActiveState' is set to 'X', I want to allow any combo of those items.
In other words, only force uniqueness if ActiveState <> 'X'.
My understanding is I can not have a UNIQUE constraint with conditions. I've read about indexes, wondering if that's the path I need to travel?
I'm no Oracle expert (obviously), just looking for a tip!

A: You can use virtual columns and then create a unique constraint on the virtual columns:
CREATE TABLE table_name (
  ID           NUMBER PRIMARY KEY,
  DocID        NUMBER,
  FileName     VARCHAR2(10),
  FileRevision NUMBER,
  Province     NUMBER,
  ActiveState  VARCHAR2(1),
  ActiveDocID  GENERATED ALWAYS AS (CASE ActiveState WHEN 'X' THEN NULL ELSE DocID END),
  ActiveFileName
               GENERATED ALWAYS AS (CASE ActiveState WHEN 'X' THEN NULL ELSE FileName END),
  ActiveFileRevision
               GENERATED ALWAYS AS (CASE ActiveState WHEN 'X' THEN NULL ELSE FileRevision END),
  CONSTRAINT table_name__uniq UNIQUE (
    ActiveDocID,
    ActiveFileName,
    ActiveFileRevision
  )
);

A: For the same, Oracle provides the Conditoinal Index concept. You can create an conditional index on your table like below -
CREATE UNIQUE INDEX idx_ActiveState
    ON YOUR_TABLE (CASE WHEN ActiveState = 'X' THEN NULL ELSE DocID END,
                   CASE WHEN ActiveState = 'X' THEN NULL ELSE FIleName END,
                   CASE WHEN ActiveState = 'X' THEN NULL ELSE FileRevision END);


text:
Q: How can I get new entered value on EditText with TextWatcher I can get the old value. But I do not have a solution to get a new entered
value.
In fact, I want to separate the old value from the new value.
For example: If oldText=hello and new entered EditText value equal to (hello w or w hello), I want newText=w.
public class MyTextWatcher implements TextWatcher {

    private String oldText = "";
    private String newText = "";

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        this.oldText = s.toString();
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

}

Thanks for help.

A: Try this code:
public class MyTextWatcher implements TextWatcher {

    private String oldText = "";
    private String newText = "";

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        this.oldText = s.toString();
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        newText = s.toString().replace(oldText, "").trim();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

}

Info about text watcher:
Differences between TextWatcher 's onTextChanged, beforeTextChanged and afterTextChanged

A: By start andcount parameters in the onTextChanged method, you can calculate and get the new typed value.
onTextChanged

This method is called to notify you that, within s, the count
  characters beginning at start have just replaced old text that had
  length before. It is an error to attempt to make changes to s from
  this callback.

So you can:
public class MyTextWatcher implements TextWatcher {

    private String newTypedString = "";

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        newTypedString = s.subSequence(start, start + count).toString().trim();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

}


text:
Q: Kyotocabinet and Scala(Java): Limit of DB files open? I write scala application that use a lot of Kyotocabinet Db files (i need to open 500-3k little kyotocabinet files at one time).
But after 512 opened (created) db files i have a error "Error:success: no error", and new db file does not created.
After googling i found similar problem with Tokyo Cabinet + Java here: https://groups.google.com/forum/#!msg/tokyocabinet-users/ve6OsRm_hyU/hXC7795iqPsJ but without solution.
So what's the deal ? How can i open more kyotocabinet files in one application ? May be there is a some bug in Kyotocabinet ?

A: Ok it seems that i found the answer for my question...
This is not a Java or Scala specific issue but a Kyotocabinet
First i try to reproduce this behaviour in another language. So i writed test program using Perl , and it fails too, but with more informative message:
terminate called after throwing an instance of 'std::runtime_error'
  what():  pthread_key_create
After that got sources of kyotocabinet and researched that for every kyoto File() object special TSDKey object created, and this object create pthread_key. By default one
process can create limited number of this keys, and this number defined in PTHREAD_KEYS_MAX.
So it seems that open more than 512 kyoto db files in one process is not possible :(

A: Yes, I did a try. Increasing the value of macro PTHREAD_KEYS_MAX will solve the problem.
I'm using Ubuntu 16.04, with libc version 2.23. libpthread is a add on of libc.

*

*Download source code from http://ftp.gnu.org/gnu/glibc/glibc-2.23.tar.bz2 .

*Modify macro PTHREAD_KEYS_MAX from 1024 to 2048. Don't be too large. I have tried 10240, but the test program crashed.

*Modify the maxcro value in system include file local_lim.h, and replace system libraries with your new version.

*Rebuild kyotocabinet.

*Copy libkyotocabinet.so and libpthread.so.0 to your test program path.

*export LD_LIBRARY_PATH=./

*Execute your test program. The number of max db files doubled.


text:
Q: is there a function "amongst" or equivalent in lodash or JS? I want the function "amongst" or "within" in lodash or JS. The opposite already exists, it is called "includes". Example :
_(['a', 42]).includes(42)

I would like to write
_(42).amongst(['a', 42])

Any clues ?

A: Your amongst / within function is a version of _.includes() with the search value 1st and the collection 2nd, so you can create one easily by flipping _.includes():

const amongst = _.flip(_.includes)

console.log(amongst(42, ['a', 42]))
console.log(amongst('b', ['a', 42]))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

And you can use _.mixin() to add it to lodash:

const amongst = _.flip(_.includes)

_.mixin({ amongst });

console.log(_(42).amongst(['a', 42]))
console.log(_('b').amongst(['a', 42]))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

In vanillaJS you can create a function that does the same thing:

const amongst = (value, collection) => collection.includes(value)

console.log(amongst(42, ['a', 42]))
console.log(amongst('b', ['a', 42]))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


text:
Q: Django : How to generate multiple times the same form on a page? I have to allow a user to register multiple participants to an event based on the number of participants that the user entered before.
To make it clear :
Event A :
X participants
--> X forms must be generated on the next page.
So my code on the next view looks like this :
    if request.method == 'POST':
        for i in range(0, quantity - 1):
            eventParticipant_form = EventForm(request.POST, request.FILES)

            if eventParticipant_form.is_valid():
                participant = eventParticipant_form.save(commit=False)
                participant.customer = customer
                participant.customerOrder = customerOrder
                participant.event = product
                participant.save()

The problem is that it only save the last form that i fill. It make sens i think as if even if I generate X eventParticipant_form the form is not saved after.
I don't really see how to do it the proper way. Any idea ?
Thanks


text:
Q: Pandas: Select a value from a choice of three columns and assign as a value in a different column - with pandas apply I'm embarrassed to ask this but after 3 days I'm banging my head off the wall.
I have a dataframe with an id and three separate fields eached populated with alternative urls.
I want to choose a url in order of preference (urlA,urlB,urlC) and assign the selected to a new field called chosenUrl.
I have a function that sees if a given url field is populated and if so it returns that url.
I wanted to run this as an apply function in pandas to make it run as fast as possible.
I have done similar applies successfully but every time i run it, it returns a blank. I can't share the actual data set but I've created an anonymised version for reference.
Any idea why it keeps returning blanks?
Code:
data = {'id': ['123','456','789'],
        'urlA': ['www.google.com','',''],
    'urlB': ['','www.amazon.com',''],
    'urlC': ['','','www.yahoo.com']
        }
df = pd.DataFrame(data, columns=['id','urlA','urlB','urlC'])

#function to select populated url - does the string contain a '.'?
def selectUrl(urlA,urlB,urlC):
    tmp = '.'
    if tmp in str(urlA):
        y= urlA
    elif tmp in str(urlB):
        y = urlB
    elif tmp in str(urlC):
        y= urlC
    else:
        y = ''
    return y

#Pandas apply statement
df['selectedURL']=df.apply(lambda x: selectUrl(x['urlA'],x['urlB'],x['urlB']), axis=1)

I would expect this to return

Any ideas? I was thinking that maybe its returning an object of the whole field which is ignored but haven't been able to figure it out. I have no doubt i'm going to facepalm after someone points something out but I will deserve it!
Any advice is appreciated

A: Because here is prioritize column urlA, then urlB and last urlC select this columns by priority in list (first are more prioritized), then replace empty strings to missing values, back filling missing values and fill first column by position:
df['url'] = df[['urlA','urlB','urlC']].replace('',np.nan).bfill(axis=1).iloc[:, 0]
print (df)
    id            urlA            urlB           urlC             url
0  123  www.google.com                                 www.google.com
1  456                  www.amazon.com                 www.amazon.com
2  789                                  www.yahoo.com   www.yahoo.com

Importance of order of values of list is possible see in changed data:
data = {'id': ['123','456','789'],
        'urlA': ['www.google.com','www.google.com',''],
    'urlB': ['','www.amazon.com','www.amazon.com'],
    'urlC': ['www.yahoo.com','','www.yahoo.com']
        }
df = pd.DataFrame(data, columns=['id','urlA','urlB','urlC'])

#A,B,C priority
df['url1'] = df[['urlA','urlB','urlC']].replace('',np.nan).bfill(axis=1).iloc[:, 0]
#C,B,A priority
df['url2'] = df[['urlC','urlB','urlA']].replace('',np.nan).bfill(axis=1).iloc[:, 0]
print (df)
    id            urlA            urlB           urlC            url1  \
0  123  www.google.com                  www.yahoo.com  www.google.com
1  456  www.google.com  www.amazon.com                 www.google.com
2  789                  www.amazon.com  www.yahoo.com  www.amazon.com

             url2
0   www.yahoo.com
1  www.amazon.com
2   www.yahoo.com


text:
Q: Arrange n Books When k Must Be Adjacent On A Shelf There will be n Books, and k of them $(k \leq n)$ must be adjacent
How many ways there are, to arrange them on a shelf?
What I thought is that as for the k books there are $k!$ ways to arrange them.
and as for the other there are $\dbinom{n}{n-k}$ ways to arrange them.
so the sum is $\dbinom{n!}{k!}*k!=n!$
or is it just $(n-k)!*k!$  ?

A: Consider the k books as a whole one big book then we have to arrange this $(n-k +1)$ books, and they can be arranged in $(n-k+1)!$ ways. Why$ (n-k+1)!?$ You just think and will get it. Then those k books can be arranged within themselves in $k!$ ways. So the answer is $(n-k+1)! \times k!$.

A: There are k! ways of arranging the k books.  Treat the k books as a single unit when arranging them against the other (n-k) books so we have (n-k+1)! arrangements for each arrangement of the k books.
So we have $$N=k!\times(n-k+1)!$$


text:
Q: Maintaining a ListView where each List item has a one to many relationship The way my app is set up is that I have a ListView, maintained by a CursorLoader, of posts made by the users. Each post has user comments that are associated with it. Each listitem has a custom textview at the bottom where the comments can be scrolled through(with a right or left swipe). Within each of the custom textviews is a list of the comments associated with its particular post. Its kind of like the comments on the Google+ app except the items are scrollable. The comments are stored in a separate database table than the posts.
The issue I'm having is that each time BindView is called I'm querying the database and retrieving a cursor with the associated comments and adding it to the custom textview list. This seems really inefficient to query the comments database table for each item. So I'm wondering if there would be an ideal way to handle this. My code looks something like:
public void bindView(View view, Context context, Cursor cursor)
    final String rowid = cursor.getString(cursor.getColumnIndexOrThrow(Database.ROWID));

    Cursor commentcursor = c.getContentResolver().query(DatabaseProvider.CONTENT_URI_COMMENTTABLE,   freeWriteCommentColumns, Database.PARENTPOSTROWID + " =?", new String[]{rowid}, null);

    commentcursor.moveToFirst();
    while (commentcursor.isAfterLast() == false){
            //get comment
            //add to comment text view list
            }

I've looked into CursorJoiners but that doesn't seem to useful. I've played around with JOINS but that makes the number of rows way larger than it needs to be. I'm currently playing around with a holder for the comments table cursor that is created when the adapter is created and set as a global variable. This seems like a decent avenue because I don't have to requery each time. I'm just not sure how to handle this situation.

A: I know that u tried it but this is the way to go. I had almost the same problem, even a larger one becuase mine was with JOIN and then a MergeCursor. But lets get back to your issue: bindView() is called on the UI and you doing DB calls on the UI thread, this is bad practice and on top of that you are running all over cursor.
I would have JOIN the query for the post and concat the comments at the SQL level of the loading and then i would just use one cursor for the posts and comments and everything would be much much better.
How to concat the string at the SQL level? all the comments together? well this i will have look and edit my answer.


text:
Q: Sharepoint RequestDigest is interpreted as parameter in cURL I use the following sequence of cURL commands to upload files to Sharepoint.
# Get Token
curl -X POST -d "" --ntlm -u usr:pw http://.../_api/contextinfo
# Checkout File
curl -X POST -d "" -H "X-RequestDigest: 0x...,11 Sep 2020 14:45:30 -0000" --ntlm -u usr:pw "http://.../_api/web/GetFileByServerRelativeUrl('...')/checkOut()"
# Upload File
curl --ntlm -u usr:pw --upload-file ... http://...
# Check In
curl -X POST -d "" -H "X-RequestDigest: 0x...,11 Sep 2020 14:45:30 -0000" --ntlm -u usr:pw "http://.../_api/web/GetFileByServerRelativeUrl('...')/checkIn(comment='Comment',checkInType=0)"

That works fine when running locally using libcurl. It does not when running on RHEL7. Then the ' -0000' within the header's token is interpreted as parameter resulting in the error message below.
curl: option -0000': is unkown

I cannot remove the space or minus because it is part of the token. I already tried to escape the header in several ways without success. Do you have an idea on how to resolve this?

A: I suspect you are invoking curl over SSH, like this:
ssh $host curl -X POST -d "" -H "X-RequestDigest: 0x...,11 Sep 2020 14:45:30 -0000" --ntlm -u usr:pw "http://.../_api/web/GetFileByServerRelativeUrl('...')/checkIn(comment='Comment',checkInType=0)"

This does not work because SSH does not transmit the argument vector as an array of strings. Instead, it transmits a single string, consisting of all the argument separated by spaces. Instead you have to write something like this:
ssh $host "curl -X POST -d \"\" -H \"X-RequestDigest: 0x...,11 Sep 2020 14:45:30 -0000\" --ntlm -u usr:pw \"http://.../_api/web/GetFileByServerRelativeUrl('...')/checkIn(comment='Comment',checkInType=0)\""

(Note that specifying passwords on the command line may be insecure because the arguments are visible using ps.)


text:
Q: How to add to salt state? (beginner doing Python project using virtualenv) First, some context: I'm following a web scraping tutorial and am running into (what I believe are) setup-related issues.  I keep running into errors with the last step of Part 0 (bottom of page).  After creating my virtualenv (using mkvirtualenv), I receive the following error when running the following command (from inside my virtualenv): pip install -r requirements.txt:
[Errono 2] No such file or directory: 'requirements.txt'
Storing debug log for failure in /home/dchaudh/.pip/pip.log

I did some quick googling and came across this solution which seems promising: it suggests that the problem is due to Salt (bc of something called chowning) and that adding no_chown: True to my salt state should fix the issue.
How do I add to the salt state, i.e., what file do I modify?  Any help would be appreciated
As you can tell from the tutorial, I'm a relative newbie (even moreso to virtual environments) and I feel like I quickly got in over my head in the process theof trying to find a solution.

A: Are you actually using Salt? I feel that you found that solution online and attributed your error to Salt. Nothing in the tutorial mentions Salt, so it seems unlikely that you would be using it.
Make sure you are actually in the new-coder/scrape directory before running pip install -r requirements.txt


text:
Q: localStorage.clear(); not working in Ember.js, at least not with an ajax call Please see follow-up question here here where it gets to the meat of the problem.
I am making an ajax call that reloads the data in the local storage of an Ember App. I am calling localStorage.clear(); right before the ajax call. However, after the ajax call, nothing is cleared!
The printout localStorage.getItem("model-emberjs") right after the clear() and is null as expected.
The printout localStorage.getItem("model-emberjs") right after the ajax call that follows has everything from before.
I'm using the LS adapter.
Do you have any idea why?

P.S. I don't know how to make ajax call work in jsbin so sorry no live example.

A: As @Benjamin already mentioned I also believe you have a caching problem. If you are using chrome try to disable the cache while developing by bringing up the extra settings dialog:

And then enable "Disable cache":

Now try again to call localStorage.clear() it should work this time.
Hope it helps.


text:
Q: Execution error, return code 1 when trying to create an external table in Hive I have searched and tried all solutions online and I seem to be getting the same error when trying to create an external table in hive:

FAILED: Execution Error, return code 1 from
org.apache.hadoop.hive.ql.exec.DDLTask.
org/apache/hadoop/hive/serde2/SerDe

I am trying to create an external table, populating it with data I extracted from Twitter using Flume. My extracted data is located in hdfs storage system : /user/hadoop/twitter_data.
I did the following:

*

*Downloaded hive-serdes-1.0-SNAPSHOT.jar from Cloudera.

*Add jar /home/hadoop/Desktop/Flume_cheat/twitter/hive-serdes-1.0-SNAPSHOT.jar.

*create external table Twitter_Flume3 (id BIGINT,created_at STRING,source STRING,favorited BOOLEAN,retweet_count INT,retweeted_status STRUCT<text:STRING,user1:STRUCT<screen_name:STRING,name:STRING>>,entities STRUCT<urls:ARRAY<STRUCT<expanded_url:STRING>>,user2_mentions:ARRAY<STRUCT<screen_name:STRING,name:STRING>>,hashtags:ARRAY<STRUCT<text:STRING>>>,text STRING,user3 STRUCT<screen_name:STRING,name:STRING,friends_count:INT,followers_count:INT,statuses_count:INT,verified:BOOLEAN,utc_offset:INT,time_zone:STRING>,in_reply_to_screen_name STRING) ROW FORMAT SERDE 'com.cloudera.hive.serde.JSONSerDe' LOCATION '/user/training/flume_result';

*FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. org/apache/hadoop/hive/serde2/SerDe
Version

*

*Hadoop version 3.2.1

*Hive version 3.1.2


text:
Q: Haskell manipulating file contents I'm a student from Portugal having some doubts about a project I have to handle.
My final objective is to create a pdf catalog with LaTeX that stores information about files using exiftool.
So far, i've managed to separate audio from video files and store their exiftool'ed information on a file, but it bulks them up.
for example:
======== Cartoon Battle.mp3
-ExifToolVersion=8.60
-FileName=Cartoon Battle.mp3
-Directory=.
-FileSize=4.0 MB
-FileModifyDate=2011:12:13 09:46:25+00:00
-FilePermissions=rw-rw-r--
-FileType=MP3
-MIMEType=audio/mpeg
-MPEGAudioVersion=1
-AudioLayer=3
-AudioBitrate=320 kbps
-SampleRate=48000
-ChannelMode=Stereo
-MSStereo=Off
-IntensityStereo=Off
-CopyrightFlag=False
-OriginalMedia=False
-Emphasis=None
-ID3Size=113441
-Title=Cartoon Battle
-Artist=Kevin MacLeod
-Year=2007
-BeatsPerMinute=130
-Genre=Unclassifiable
-Comment=(iTunPGAP) 0
-EncodedBy=iTunes v7.0.2.16
-Comment=(iTunNORM)  000001F7 0000014B 00001DBD 00000B18 000154C8 00000780 00008169                 00008180 00000780 00000780
-Comment=(iTunSMPB)  00000000 00000210 00000A84 00000000004A606C 00000000 003DE780 00000000 00000000 00000000 00000000 00000000 00000000
-Album=Far East
-Composer=Kevin MacLeod
-PictureFormat=JPG
-PictureType=Other
-PictureDescription=
-Picture=(Binary data 91855 bytes, use -b option to extract)
-DateTimeOriginal=2007
-Duration=0:01:41 (approx)
======== Comic Plodding.mp3
-ExifToolVersion=8.60
-FileName=Comic Plodding.mp3
-Directory=.
-FileSize=3.8 MB
-FileModifyDate=2011:12:13 09:46:24+00:00
-FilePermissions=rw-rw-r--
-FileType=MP3
-MIMEType=audio/mpeg
-MPEGAudioVersion=1
-AudioLayer=3
-AudioBitrate=320 kbps
-SampleRate=44100
-ChannelMode=Joint Stereo
-MSStereo=Off
-IntensityStereo=Off
-CopyrightFlag=False
-OriginalMedia=False
-Emphasis=None
-ID3Size=105099
-EncoderSettings=Logic Pro 8.0.1
-Comment=(iTunNORM)  000001AE 00000181 000026DF 0000365B 0001100A 00016CE5 00007D33     00007ECF 00010FF0 00016CE5
-Comment=(iTunSMPB)  00000000 00000210 000009D6 000000000040DA1A 00000000 003ABCBC     00000000 00000000 00000000 00000000 00000000 00000000
-Artist=Kevin MacLeod
-Composer=Kevin MacLeod
-Year=2008
-Genre=Silent Film Score
-PictureFormat=JPG
-PictureType=Other
-PictureDescription=
-Picture=(Binary data 84880 bytes, use -b option to extract)
-Album=Scoring - Silent Film: Dark
-DateTimeOriginal=2008
-Duration=0:01:36 (approx)

What i'd like to do is :
first, try to split the two songs on that file in some kind of list of some sort.
then, try and pick up some of the information inside a file, like the FileName, Size and all that.
So far, i've come up with this piece of code, but it isnt correct:
mymain = do{
  a <- readFile "audio.txt" ; -- file that has all the infos collected by exiftool
  ml <- splitRegex (mkRegex "========") a ; -- I expect this to separate each song and place their corresponding information on a single string

Can anyone give me a hint? I want to store some information on a File structure i've created, but first, i need to split it up by songs, then pick up what I want, right?
THanks for the help and excuse me for my bad french!
PS: I'm not that used to haskell (just starting)

A: A minimal fix is:
import Text.Regex

main = do {
  a <- readFile "audio.txt" ;
  print $ splitRegex (mkRegex "========") a ;
}

The arrow extracts a value from a monadic value - from a value of type m a where m is a monad and a is an arbitrary type. readFile returns a monadic value (of type IO String) but splitRegex accepts a plain value of type String. So arrow can be used to extract a String from IO String. But splitRegex returns a non-monadic value so <- cannot extract anything from it.
I suggest to split your code into IO code and non-IO code and use the syntax without ; and {}:
import Text.Regex

processData text = x where
  x = splitRegex (mkRegex "========") y
  y = text
  ...

main = do
  a <- readFile "audio.txt"
  print $ processData a

So IO code will use do and <- and non-IO code will use where and =.


text:
Q: Why does my ArrayList print the first object 3 times? I am relatively new to Java. I was practicing an exercise where we explore the polymorphic behavior of subclass and superclass instances. This exercise builds on the concepts of abstract classes and interfaces.
ArrayLists are introduced in this exercise.
One of the questions requires us to create an ArrayList of WrittenWork objects called products, and add the appropriate objects to the ArrayList.
My problem is that the ArrayList keeps printing the first item 3 times and then prints the rest of the items.
Could someone explain why this keeps happening?
EDIT: I realized the mistake I was making thanks to you guys!
I changed the for loop from
   for(WrittenWork w: products)
       System.out.println(w1.toString());
       System.out.println(w2.toString());
       System.out.println(w3.toString());

To
for(WrittenWork w: products)
    System.out.println(w.toString());

This Image shows how all the classes are connected
Here is the code:
import java.util.*;

public class BookStore
{
  public static void main(String[] args)
  {
   Author a1 = new Author("Malcom Gladwell");
   Author a2 = new Author("Steven Johnson");
   Author a3 = new Author("Mathias Johansson");
   Author a4 = new Author("Evan Ackerman");
   Author a5 = new Author("Erico Guizzo");
   Author a6 = new Author("Fan Shi");

   WrittenWork w1 = new Novel(a1, "What the Dog Saw and other adventures", 503);
   WrittenWork w2 = new Novel(a2, "How We Got to Now: Six Innovations That Made the Modern World", 320);
   WrittenWork w3 = new Novel(a2, "Everything Bad Is Good For you: How Today's Popular Culture is Actually Making us Smarter", 254);

   ArrayList<WrittenWork>products = new ArrayList<>();
   products.add(w1);
   products.add(w2);
   products.add(w3);

   for(WrittenWork w: products)
       System.out.println(w1.toString());
       System.out.println(w2.toString());
       System.out.println(w3.toString());

   }
 }

This is the output

A: Other than not having used brackets to correctly identify the for block, you have a logic flaw in your small piece of code.
You wrote

the ArrayList keeps printing the first item 3 times and then prints
  the rest of the items

This lead me to think your code doesn't really represents what you actually want to accomplish. This is totally normal in the beginning, don't worry.
It seems you'd like to print all the WrittenWork.
For that you used an (enhanced) for loop
for (WrittenWork w : products)

but you never taken into consideration the w local variable.
What happens in the background is that an Iterator<WrittenWork> (JavaDoc) is created for you, and each iteration the next element in the products list is given to you via w.
You just need to use that w variable to print all the elements of products. The Iterator will exhaust itself and the loop will stop.

For your knowledge, this for-loop style
for (WrittenWork w : products) { ... }

is equivalent to
for (Iterator<WrittenWork> iterator = products.iterator(); iterator.hasNext(); ) {
    final WrittenWork w = iterator.next();
    ...
}

You can see the checked condition is iterator.hasNext();.

A: for(WrittenWork w: products)
       System.out.println(w1.toString());
       System.out.println(w2.toString());
       System.out.println(w3.toString());

   }

In a program exection fashion it may make you feel right and it runs but the logical issue incurs that if you opt for printing all objects with segregate  System.out.println methods, then why did you use for(each)-loop?
Besides, you don't need to call toString() method called implicitly and automatically if an object reference is passed to System.out.println method

A: It should be:
  for(WrittenWork w: products)
       System.out.println(w.toString());

  }

You're already going over all the WrittenWork objects, using w1, w2, w3 nullifies the use of using for-loop in the first place.

A: You are iterating over the ArrayList but printing out w1, w2 and w3 on every iteration. As others pointed out print w in every iteration which points to the element corresponding to the iteration.
for (WrittenWork w: products){
   System.out.println(w.toString());
}

A: for (WrittenWork w: products){
   System.out.println(w.toString());
}

A: Try this:
for (WrittenWork w: products){
   System.out.println(w.toString());
}