text:
Q: for loop is run more times then specified. I have been trying to make a drop down menu in pygame. I have a method that that takes a list of strings and renders them to the screen using a for loop. The for loop is shown below.
        spacer = 0
        for text in range(5):
            spacer += 30
            rect = pygame.Rect(0, spacer, 100, 20)
            pygame.draw.rect(self.surface, (255, 0, 0), rect)
            self.rect_list.append(rect)

I appended each rectangle that was created in the for loop to a list rect_list.
i then printed the list to the screen to see it's contents. The Python IDLE window was spammed with the contents of the list.
The method that contained in the for loop is being called in a second method of another class Menu. The method in class Menu is called in a while loop:
while running:
        for event in pygame.event.get():
            if event.type == pg.QUIT:
                running = False
                pygame.quit()
                quit()

        #--------method being called in while loop----------#
        Menu_Class_Obj.render_menu()
        #--------method being called in while loop----------#
        pygame.display.update()

A: Every time your menu is rendered, you're appending to menu_items_rect_list. Whatever you put in that list will stay there indefinitely. If you want the list to be empty at the start of the frame, you need to clear it yourself.

A: The answer to my question is very obvious once I really thought  about what was happing. Since I'm calling the method that contains the for-loop in a while loop, the for-loop is being run multiple times. The two solutions I've used for this problem are:
1. setting a limit to how many items can be in the list:
if len(self.rect_list) > 5):
     self.rect_list = self.rect_list[:5]

and two; deleting any more elements then a specified number:
if len(self.text_rect_list) > len(self.sub_items):
                del self.text_rect_list[:len(self.sub_items)]


text:
Q: Easiest way to draw an NSImage dimmed out (like a disabled view) If I'm not really fussy about the exact tone etc of the dimmed image, is there a quick and dirty way to draw an NSImage slightly dimmed, like this?  I've searched online and can't really find what I'm looking for (but I'm not very good when it comes to understanding graphics and the correct technical terms).

I'm actually dimming icons for the same use-case as Xcode dimming icons like above (i.e. document has unsaved changes).

A: Swift 5 function to create a dimmed version of any input image:
func dimmedImage(_ image: NSImage, alpha: CGFloat) -> NSImage {
    let newImage = NSImage(size: image.size)
    newImage.lockFocus()

    let imageRect = NSRect(origin: .zero, size: image.size)
    image.draw(in: imageRect, from: imageRect, operation: .sourceOver, fraction: alpha)

    newImage.unlockFocus()
    return newImage
}

A: This works fine for me:
NSImage *iconImage = [NSImage imageNamed:@"Icon"];
NSSize iconSize = [iconImage size];
NSRect iconRect = NSMakeRect(0.0, 0.0, iconSize.width, iconSize.height);
[iconImage lockFocus];
[[NSColor colorWithCalibratedWhite:0.0 alpha:0.33] set];
NSRectFillUsingOperation(iconRect, NSCompositeSourceAtop);
[iconImage unlockFocus];
[iconImage drawInRect:iconRect
              fromRect:iconRect
             operation:NSCompositeSourceOver
              fraction:0.75];

Basically I'm adding a black layer with 33% opacity on top of the actual icon (masking it with NSCompositeSourceAtop). And then I'm just drawing the dimmed icon with an opacity of 75%.
[Edit: got rid of temporary black image by using NSRectFillUsingOperation(...), as advised by Nikolai Ruhe]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Capture SharePoint role group and group members? For our audit process I need to regularly capture all of our SharePoint role groups (for our main site collection) and the members in each group. Is there a reliable way to approach this problem?

A: I would use the powershell commands to write out each SPGroup (using SPWeb.SiteGroups) and then writing out each member of the group.

A: Solved using advice from Ryan Erickson, my proof (note: just a proof, hence sloppish standard code) is below (also not PowerShell as suggested since I'm more comfortable C# but it should be relatively easy to convert):
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace QIC.RE.SharePoint.Permissions.ConsoleApplication
{
    class Program
    {

        static void Main(string[] args)
        {
            string siteCollection = "http://dev/re";

            string version = Assembly.GetAssembly(typeof(Program)).GetName().Version.ToString();

            Console.WriteLine("[{0}] SharePoint Permissions started with version '{1}'.", DateTime.Now.ToShortTimeString(), version);

            try
            {
                using (var site = new SPSite(siteCollection))
                {
                    using (var web = site.OpenWeb())
                    {
                        foreach (SPGroup group in web.Groups)
                        {
                            Console.WriteLine("\n[{0}] Group: '{1}'.", DateTime.Now.ToShortTimeString(), group.Name);
                            Console.WriteLine("###########################");

                            if (group.Users.Count > 0)
                            {
                                foreach (SPUser user in group.Users)
                                {
                                    Console.WriteLine("\n[{0}] Username: '{1}'", DateTime.Now.ToShortTimeString(), user.Name);
                                    Console.WriteLine("\n[{0}] Login Name: '{1}'", DateTime.Now.ToShortTimeString(), user.LoginName);
                                    Console.WriteLine("\n[{0}] E-mail: '{1}'", DateTime.Now.ToShortTimeString(), user.Email);
                                    Console.WriteLine("\n[{0}] User ID: '{1}'", DateTime.Now.ToShortTimeString(), user.ID);
                                }
                            }
                            else
                            {
                                Console.WriteLine("[{0}] Group: '{1}' is empty.", DateTime.Now.ToShortTimeString(), group.Name);
                            }

                            Console.WriteLine("\n###########################");
                        }
                    }
                }
            }
            catch (Exception)
            {

                Console.WriteLine("[{0}] Error: Unable to open site '{1}'.", DateTime.Now.ToShortTimeString(), siteCollection);
                throw;
            }
        }
    }
}


text:
Q: Debugging segmentation faults (core dumped) for big projects I tried to run this code [the-git-link] (https://github.com/DropIn/SequentialTextReading), but I experience a "Segmentation fault (core dumped)". Do you have any idea about this error? I am running it on Ubuntu 14.4 and
the code is too big to use traditional debug methods on it like using gdb.
Any idea how to solve this problem or what tools should i use to solve it knowing that there are many files and main in the project?

A: You can also load your coredump to gdb and find the root cause, after your program crashed.
You may benefit from reading How to generate core dump file in Ubuntu, and How to analyze a program's core dump file with gdb?


text:
Q: How can I find executables installed by NuGet packages? My project needs to be packaged as a zip file for deployment. I want to create this zip file in a post build step.
To achieve this I have installed a 7-Zip command line package via NuGet. This package provides an executable which I want to call in my post build step. I know that I could call it by providing the path to the installed package but this path contains the version number of the package so a direct reference will break when the package is updated.
Is there some MSBuild variable that I could use to get the path to my installed packages' tools path?

A: I don't think there's a way to avoid the version number in the path for the package, but you can do something like what the SlowCheetah nuget package does to make it more portable between developer machines, etc.
<PropertyGroup Label="SlowCheetah">
 <SlowCheetahToolsPath>$([System.IO.Path]::GetFullPath( $(MSBuildProjectDirectory)\..\packages\SlowCheetah.2.5.12\tools\))</SlowCheetahToolsPath>
 <SlowCheetah_EnableImportFromNuGet Condition=" '$(SlowCheetah_EnableImportFromNuGet)'=='' ">true</SlowCheetah_EnableImportFromNuGet>
 <SlowCheetah_NuGetImportPath Condition=" '$(SlowCheetah_NuGetImportPath)'=='' ">$([System.IO.Path]::GetFullPath( $(MSBuildProjectDirectory)\Properties\SlowCheetah\SlowCheetah.Transforms.targets ))</SlowCheetah_NuGetImportPath>
 <SlowCheetahTargets Condition=" '$(SlowCheetah_EnableImportFromNuGet)'=='true' and Exists('$(SlowCheetah_NuGetImportPath)') ">$(SlowCheetah_NuGetImportPath)</SlowCheetahTargets>
</PropertyGroup>


text:
Q: Performance: Get and group productdetails from 5 tables in a single query instead of multiples? Currently I'm developing a background cms for an online shop.
I split the tables as follow in my database:
-products
-productdetails (descrition...)
-productimages
-product variants (colors..)
-product cross selling
Now on the product edit page i need to fetch all data for a single product.
So my question is how i can get those details more efficient then make 3-5 database calls.
Or would the processing with php be less efficient then make those 3-5 calls ?
At the moment the query looks like that:
SELECT
        pr.id, pr.categorieid, pr.itemnumber, pr.barcode, pr.price, pr.weight, pr.gender, pr.manufracture, pr.fsk18, pr.condition, pc.id AS pcid, pc.productcrossid, pc.sort, pd.productname,
        pd.productdesc, pd.additional, pd.linktitle, pd.metatitle, pd.metadesc, pd.urlkeywords, pi.id AS piid, pi.wichimage, pi.variantid, pi.image, pi.imagealt, pv.id AS pvid, pv.variant,
        pv.variantvalue, pv.sku, pv.price AS pvprice, pv.weight AS pvweight, pv.stock, pv.special
    FROM
        products pr
    LEFT JOIN
        productcross as pc
        ON pr.id = pc.productid
    LEFT JOIN
        productdetails as pd
        ON pr.id = pd.productid
    LEFT JOIN
        productimage as pi
        ON pr.id = pi.productid AND pd.lang = pi.lang
    LEFT JOIN
        productvariants as pv
        ON pr.id = pv.productid
    WHERE
        pr.id = :id
    ORDER BY pd.lang ASC

As result i recieve many rows, because of the left join each value get joined with the rows i joined before.
The problem is there are dynamic many rows for cross selling, variants, images, so it can be random if variants or images are more (else i could group them atleast because each variant can get an own image, but there can be also more images then variants)
Products 1 row, productdetails according to how many languages are used, most likely 3.
Edit: According to Explain and the indexes i set, the performance of this single query is very good.

Edit:
According Paul Spiegel i tryed using GROUP_CONCAT
   SELECT
        pr.id, pr.categorieid, pr.itemnumber, pr.barcode, pr.price, pr.weight, pr.gender, pr.manufracture, pr.fsk18, pr.condition, pc.id AS pcid, pc.productcrossid, pc.sort, pd.productname,
        pd.productdesc, pd.additional, pd.linktitle, pd.metatitle, pd.metadesc, pd.urlkeywords
    FROM
        products pr
    LEFT JOIN
        productsdetails as pd
        ON pr.id = pd.productid
    LEFT JOIN (
        SELECT
        GROUP_CONCAT(productcrossid) AS pcproductcrossid, GROUP_CONCAT(sort) AS pcsort, GROUP_CONCAT(id) AS pcid, productid
        FROM productscross
        WHERE productid = :id
        ) pc
        ON pr.id = pc.productid

    WHERE
        pr.id = :id
    ORDER BY pd.lang ASC

A:
As result i recieve many rows, because of the left join each value get joined with the rows i joined before.

That's not what LEFT means.
X JOIN Y ON ... delivers rows that show up on both X and Y.
X LEFT JOIN Y ON ... delivers all the rows of X even if there is no matching row (or rows) in Y.
You might get "many rows" because the relationship is "1:many".  Think of Classes JOIN Students  With JOIN you get multiple rows per Class (one per student), except for any classes without any students.  With LEFT JOIN, you additionally get a row for any Class with no students.
Your query with products will be a huge explosion of rows.  All products, expanded by multiple details by multiple images, etc.  It will be a mess.
In the EXPLAIN, multiply the numbers in the "Rows" column -- that will be a crude metric of how big the result set will be.
Use one query to get the images; another to get the colors; etc.  Use JOIN (or LEFT JOIN only when needed.
GROUP_CONCAT() is handy sometimes.  It might be useful to list the "colors".  But for "images", you would then have to split it up so you can build multiple <img..> tags.  That's rather easy to do, but it is extra work.
It is usually 'wrong' to have 1:1 mapping between tables.  In such cases, why not have a single table?
Do not fear 3-5 queries.  We are talking milliseconds.  The rendering of the page is likely to take several times as long as the SELECTs.  I often have several dozen queries to build a web page, yet I am satisfied with the performance.  And, yes, I ascribe to the notion of putting all the info about one 'product' on the page at once (when practical).  It's much better than having to click here to get the colors and click there to see the images, etc.

A: Rather than hitting so many query's you can refer to the concept which is known as flat tables in magento.
The logic behind using this concept is that what ever important data which is required to be show on the front end is stored in single table itself as well as the data is stored in there prescriptive tables.
So while querying you just need to pick the data from that flat table itself rather than querying to multiple tables and increasing the query execution time.
For reference Please check out the below link,Hope this helps.
Visit http://excellencemagentoblog.com/blog/2015/06/10/magento-flat-tables/
I do know the question is not regarding Magento but you can build your own logic to achieve this mechanism.


text:
Q: IIS7 Web.Config Caching - what are the differences here, and how does it all come together? In IIS7 I've got the ability to set caching options. These options are added to my web.config as such...
    <caching maxCacheSize="262144">
        <profiles>
            <add extension=".png" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" duration="00:00:30" />
            <add extension=".jpeg" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" duration="00:00:30" />
            <add extension=".jpg" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" duration="00:00:30" />
            <add extension=".css" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" duration="00:00:30" />
            <add extension=".js" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" duration="00:00:30" />
        </profiles>
    </caching>

However, I've also got the following for "caching"
    <staticContent>
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="90.00:00:00" />
        <remove fileExtension=".js" />
        <mimeMap fileExtension=".js" mimeType="text/javascript" />
    </staticContent>

What are the differences between these two configs?  They are both nested in the <system.webServer> tag, so they're both valid for IIS7.
Also, what is the right approach when using these? I currently only use this is my static assets folder. I don't use this caching on anything else.
Thanks in advance.

A: The main difference is that

*

*the first is for server-side caching of dynamic output such as aspx pages (basically keeps the page output in memory for subsequent requests). As @artem-vertiy's answer points out, using it for static content makes no sense.

*the second one is 'internet-side' : it is implemented by writing standard response headers, it tells both client browsers and public proxies how to manage cached files.

A: I've noticed that people often confuse the things above and write articles where recommend things as in the first block, i.e. output caching for static resources
Output caching:

Output caching is unnecessary for static files, such as HTML, JPG, or
  GIF files, and can cause more memory overhead for dynamic ASP.NET or
  PHP pages that read from a database that changes frequently

Thus
<add extension=".png" ../>
<add extension=".jpeg" ../>
etc.

is useless at least when you don't have ashx http handler for .png or .jpeg etc.


text:
Q: Abel means of function $f$ at a jump discontinuity Fourier Analysis An Introduction Chapter 2, Exercise 17 (a):
Abel means of $f$ converge to $f$ whenever $f$ is continuous at $\theta$:
$$\lim_{r\to1}A_{r}(f)(\theta)=\lim_{r\to1}(P_{r}*f)(\theta)=f(\theta),\mbox { with}\ 0 < r< 1.$$
An integrable function is said to have a jump discontinuity at $\theta$ if the two limits
$$\lim_{h\to0\\h>0}f(\theta+h)=f(\theta^{+})$$ and $$\lim_{h\to0\\h>0}f(\theta-h)=f(\theta^{-})$$
exist.
Prove that if $f$ has a jump discontinuity at $\theta$, then
$$\lim_{r\to1}A_{r}(f)(\theta)=\frac{f(\theta^{+})+f(\theta^{-})}{2},\mbox{ with } 0\le r< 1.$$
[Hint: $\frac{1}{2\pi}\int_{-\pi}^{0}P_{r}(\theta)d\theta = \frac{1}{2\pi}\int_{0}^{\pi}P_{r}(\theta)d\theta=\frac{1}{2}.$]
$$P_{r}(\theta)=\sum_{n=-\infty}^{\infty}r^{|n|}e^{in\theta}=\frac{1-r^{2}}{1-2r\cos\theta+r^{2}},\ with\ 0\le r<1.$$
$$A_{r}(f)(\theta)=\sum_{n=-\infty}^{\infty}r^{|n|}a_{n}e^{in\theta}$$
$$=\sum_{n=-\infty}^{\infty}r^{|n|}(\frac{1}{2\pi}\int_{-\pi}^{\pi}f(\varphi)e^{-in(\varphi-\theta)}d\varphi)e^{in\theta}$$
$$=\frac{1}{2\pi}\int_{-\pi}^{\pi}f(\varphi)(\sum_{n=-\infty}^{\infty}r^{|n|}e^{-in(\varphi-\theta)})d\varphi$$
I tried to prove when $f$ has a jump discontinuity at $\theta$, and I got this:
$$\lim_{r\to1}A_{r}(f)(\theta)=\lim_{r\to1}(\lim_{w\to\theta^{-}}(\frac{1}{2\pi}\int_{-\pi}^{w}f(\varphi)(\sum_{n=-\infty}^{\infty}r^{|n|}e^{-in(\varphi-\theta)})d\varphi)+\lim_{w\to\theta^{+}}(\frac{1}{2\pi}\int_{w}^{\pi}f(\varphi)(\sum_{n=-\infty}^{\infty}r^{|n|}e^{-in(\varphi-\theta)})d\varphi))$$
$$=\lim_{r\to1}(\lim_{w\to0^{-}}(\frac{1}{2\pi}\int_{-\pi}^{w}f(\varphi-\theta)(\sum_{n=-\infty}^{\infty}r^{|n|}e^{-in\varphi})d\varphi)+\lim_{w\to0^{+}}(\frac{1}{2\pi}\int_{w}^{\pi}f(\varphi-\theta)(\sum_{n=-\infty}^{\infty}r^{|n|}e^{-in\varphi})d\varphi))$$
But I still don't know how to prove the formula.

A: This question is from Stein–Shakarchi and they give the following hint:

Hint: Explain why $\frac{1}{2\pi} \int_{-\pi}^0 P_r(\theta)\,d\theta$
  = $\frac{1}{2\pi}\int_0^{\pi} P_r(\theta) = \frac{1}{2}$, then modify the
  proof given in the text.

The proof they're referring to is that of Theorem 4.1 in chapter 2:

Theorem 4.1. Let $\{K_n\}_{n=1}^{\infty}$ be a family of good kernels,
  and $f$ an integrable function on the circle.
  Then $$\lim_{n \to \infty} (f * K_n)(x) = f(x)$$ whenever
  $f$ is continuous at $x$. If $f$ is continuous everywhere,
  then the above limit is uniform.

In particular, since $P_r(\theta)$ is even and nonnegative with $\frac{1}{2\pi}\int_{-\pi}^{\pi} P_r(\theta) = 1$, we have the identity given in the hint. Then
\begin{align}
A_r(f)(\theta) - \frac{f(\theta^+) + f(\theta^-)}{2}
&= \frac{1}{2\pi}\int_{-\pi}^{\pi} f(\theta-t)P_r(t)\,dt
- \frac{f(\theta^+) + f(\theta^-)}{2} \\
&= \frac{1}{2\pi}\int_{-\pi}^0 f(\theta - t)P_r(t)\,dt
+ \frac{1}{2\pi}\int_0^{\pi} f(\theta - t)P_r(t)\,dt
- \frac{f(\theta^+) + f(\theta^-)}{2} \\
&= \frac{1}{2\pi}\int_0^{\pi} f(\theta + t)P_r(t)\,dt
+ \frac{1}{2\pi}\int_0^{\pi} f(\theta - t)P_r(t)\,dt
- \frac{f(\theta^+) + f(\theta^-)}{2} \\
&= \frac{1}{2\pi}\int_0^{\pi}[f(\theta + t) - f(\theta^+)]P_r(t)\,dt
+ \frac{1}{2\pi}\int_0^{\pi}[f(\theta-t)-f(\theta^-)]P_r(t)\,dt.
\end{align}
From here you can continue similarly to the proof in the text,
using the left- and right-continuity of $f$ at $\theta$ to
bound the integrals near $0$ and using the properties of
good kernels to bound them away from $0$.


text:
Q: Sound output starts delayed Via SPDIF hearable sound starts late, e. g. in the Test Sound dialog I maximally can hear "Left" when the voice should say "Front Left".
When I have pavucontrol open (in the background) whilst clicking on the Test Sound it starts immediately.
Generally, starting any audio/media file, the beginning is not output/hearable. Connecting either optical or coaxial. This only seems to affect Ubuntu 12.10, wasn't the case in 12.04, doesn't seem to be the case in 13.04!
From ubuntuusers.de a bit of help -- playing a non hearable sinus to keep spdif alive:
apt-get install sox
play -n -c2 synth sin gain -100   # -c2 for two channels

Hardware on an ASRock 970 Extreme3 (and GeForce 210):
$ cat /proc/asound/cards
 0 [SB             ]: HDA-Intel - HDA ATI SB
                      HDA ATI SB at 0xfe200000 irq 16
 1 [NVidia         ]: HDA-Intel - HDA NVidia
                      HDA NVidia at 0xfe080000 irq 25

$ cat /proc/asound/card0/codec* | grep Codec
Codec: Realtek ALC892

Some pulseaudio -v output pasted to http://paste.ubuntu.com/5629082/
Can I upgrade from pulseaudio 2.1 somehow?
Live Ubuntu 13.04 output pasted to http://paste.ubuntu.com/5630475/ -- actually here only the very first invocation of sound (or after some long user pause?) starts delayed, ie after "... Left", "Front Right" is heard whereas in 12.10 it's always "... Left", " ... Right".

A: I know I'm about to revive an old thread, but I have found a easy working solution that fixes the problem.
From : https://wiki.archlinux.org/index.php/PulseAudio
To disable loading of the module-suspend-on-idle module, comment out the following line in the configuration file in use (~/.config/pulse/default.pa or /etc/pulse/default.pa):
### Automatically suspend sinks/sources that become idle for too long
# load-module module-suspend-on-idle

Finally restart PulseAudio to apply the changes.

A: It sounds like power management is preventing the soundcard from outputting the first snippet of audio. From http://wiki.gentoo.org/wiki/Power_management/Soundcard, the important bits are as follows:

Runtime tuning
You can tune the driver in the sysfs filesystem under
  /sys/module/snd_hda_intel/parameters
The power_save_controller knob controls, if power-saving mode is
  enabled. It's preset by the kernel option ... power-saving ....
The power_save knob sets the time-out in seconds. It's preset by the
  kernel option Default time-out ...
pm-utils
pm-utils contains a script to enable the power-saving mode when on
  battery and disable when on AC. It overrides the default values of the
  kernel.
If you use pm-utils, but don't want this kind of regulation, disable
  the script: root # touch /etc/pm/power.d/intel-audio-powersave

From the above text, the things to try are:

*

*in the terminal, run the following and try playing audio again:
echo N | sudo tee /sys/module/snd_hda_intel/parameters/power_save_controller

If audio is fine, then you need to make it permanent by adding a new file in /etc/modprobe.d/ with the following content:
options snd_hda_intel power-saving=N

*run sudo touch /etc/pm/power.d/intel-audio-powersave and reboot
if the fix worked then audio should play normally, if not then remove the file again:
sudo rm /etc/pm/power.d/intel-audio-powersave

If neither of these work, then I'm out of ideas :-).

A: *

*Find PulseAudio config files which contains load-module module-suspend-on-idle lines:
neatsoft@desktop:~$ grep module-suspend-on-idle /etc/pulse/*
/etc/pulse/default.pa:load-module module-suspend-on-idle
/etc/pulse/system.pa:load-module module-suspend-on-idle

*Comment out that lines.

*Restart PulseAudio to apply the changes:
pulseaudio -k
Just tested on Ubuntu 17.04 and it works fine.

A: The accepted answer about not loading module-suspend-on-idle doesn't fix the issue for me. To "fix" this I had to leave a continuous silence command running in the background, see UPDATE 2 of the following question:

*

*Short audio playback is muted, requires warming up or secondary audio in background
And I've reproduced this problem both in laptop's internal speakers and PCs through HDMI and headphones, no need for SPDIF, on latest ArchLinux and Ubuntu.

A: This is a general issue with SPDIF/digital out and the receiver processing the signal, etc.   If there is no signal, the receiver go into an idle mode. It takes from a few to a few hundred milliseconds to begin to play the signal. The ONLY way to fix it is to cause your SPDIF output to constantly send SOME signal, thus keeping the receiver processing alive at all times. At the moment, I just solved this problem in Windows using a tiny utility some guy wrote in .NET that outputs a null signal at all times. He calls it SPDIF Keep-Alive.  This keeps the signal flowing and my receiver constantly listening. I have not yet seen a way to do this for Linux, but I would imagine the support to create such a thing is EVERYWHERE. Hopefully, this has given someone an idea on what to search for or where to look next! -K9SPY
Digital audio keep-alive keep alive
SPDIF Keep-Alive keep alive
TOSLINK keep-alive keep alive
times out
goes to sleep
powers down
SPDIF sound delay

A: I need to run a special "inaudible" sound file (silence does not work for me) on Ubuntu 18.04 and Xubuntu 20.04 - but same back to Debian 6!
What worked for me: How to Fix First Play of Sound Delayed, Missed or Muffled

A: For me this worked:

*

*In /etc/pulse/daemon.conf:

*

*set default-sample-rate to 48000

*set alternate-sample-rate to 48000
Source: This Gitlab issue:

A: I have run into this problem with audio over HDMI, while audio over USB was working perfectly fine at the same time. In fact, even audio over HDMI is only buggy for me with one specific monitor, so I assume that it is this monitor that turns off its sound system in the absence of a sound signal and requires some time for starting it.
The removal of module-suspend-on-idle did not fix HDMI audio for me and instead of the other suggestion of playing a silent audio file in a loop, I came up with a slighly nicer way of keeping the connection alive by connecting a null source to the sound output. The way I did it is by first loading the null source and loopback modules using the following commands:
pactl load-module module-null-source
pactl load-module module-loopback

This should usually suffice as by default the loopback will connect the null source to the default sound output. However, if you have used these modules earlier and connected them in some other way, then those connections will be remembered and reapplied. In this case one can wire them up correctly in an interactive manner in pavucontrol:

*

*On the Recording tab, connect the input of the loopback device to the null input.

*On the Playback tab, connect the output of the loopback device to the HDMI output.

(If the loopback device is missing from the device list, "Show: All streams" must be selected on the bottom first.)
It must be possible to do the second part with command line parameters as well, but since pulseaudio remembers the module connections anyway, I never needed to connect the devices again since my intial experiment. Once the devices are correctly connected once, in the future it is sufficient to load the two modules either using the commands from above or by adding
load-module module-null-source
load-module module-loopback

to the config file (~/.config/pulse/default.pa or /etc/pulse/default.pa).


text:
Q: How to set Python default locale on Windows? I know I change change the locale for an application using
import locale
locale.setlocale(locale.LC_ALL, '')

Documentation says default value for locale usually comes from LANG environment variable. However, on Windows platform, it seems to be different. Where does Python takes the default value for locale? Is there a way to change this default value for all my Python scripts?

A: The default system locale for a windows system can be set via the control panel. Python uses this default locale when you call setlocale with '' as the second argument.
See here on how to change the default locale.

A: It is the value you've set in Control Panel.


text:
Q: Set a CSS class on an ASP.NET RadioButtonList ListItem Is there any way to set a CSS class on an input item in a radio button list? I'd like to reference these form values by class in jQuery.
Given an ASP.NET RadioButtonList with classes set on the ListItems:
 <asp:RadioButtonList ID="RadioButtonList" runat="server">
      <asp:ListItem class="myClass" Text="Yes" Value="1" />
      <asp:ListItem class="myClass" Text="No" Value="0" />
 </asp:RadioButtonList>

Will render as:

          <input id="RadioButtonList_0" type="radio" value="1"
               name="RadioButtonList"/>
          Yes

          <input id="RadioButtonList_1" type="radio" value="0"
               name="RadioButtonList"/>
          No

Unfortunately, the "myClass" class is added to the  that contains the radio button item, not the <input> itself. How could I get it to look like this instead:

          <input id="RadioButtonList_0" class="myClass" type="radio" value="1"
               name="RadioButtonList"/>
          Yes

          <input id="RadioButtonList_1" class="myClass" type="radio" value="0"
               name="RadioButtonList"/>
          No

(This does not even get into the issue of adding the classes to dynamically bound RadioButtonLists.)

A: An alternative you may want to try to do is change your CSS class to accomindate the Server Control Rendering.
So in your CSS instead of the following:
.myClass { ... }

You Use this:
.myClass input { ... }

I don't know if you can set the class attribute (via class or CSSClass) in a declarative manner; however, the above should give you a work around.

A: untested
$('.myclass input:radio').each(function() {
        this.css({'style-name':'style-value'})
)};

once the list is rendered, you can possibly manipulate the css client side using the above statement.

A: Using .NET you could create an event handler to the RowBinding event.  This would allow you to access the individual controls within each item in the list.  Once you pull the RadioButton control, you could programaticaly set it's CssClass to apply your class on the RadioButton level.
You could also use jquery to find the radio button controls that have myClass applied, and then apply another class to that.
Third, you could just change the definition of MyClass to also specify that it's only applied to input elements under elements that have MyClass applied.

A: Yes, RadioButtonList renders horrible HTML.
Anyway, it's still easy to get them from jQuery.
Try
$('span.myclass input:radio')

Above will get all the radio buttons inside the span with class 'myclass'.

A: the desigeek response is pretty good..
To get this to work for radiobuttons I had to do this on document.ready()
$('#<%=radRisksMarginTrading.ClientID  %>_0').addClass("validate[required]");
$('#<%=radRisksMarginTrading.ClientID  %>_1').addClass("validate[required]");

I'm sure there is a much better way to do it by looping but I need a quick fix for 5 radiobutton lists..


text:
Q: Clear key listeners from JPanel I have created java swing application. In that application, there is a textfield.I have attached key listner for that text field also. Using that, enter key is identified and popup another JPanel. There is a JTable which is loaded data from DB and there is a JButton. The selected row from that table is loaded to that previous textfield.
There is a very rare issue with that implementation. when we have that JPanel, mistakenly the user pressed the enter button twice in very very short period at once. Then after we load that panel ther is a unusal behavior. by default the JButton is pressed without any key pressed.
According to my investigation, the problem can be solved, if we have a method to cler keylistner actions once it finished.
Are ther any methods?


text:
Q: How to prevent Jquery script loading twice in ajax call or submit JQuery Function to Ajax Called Page Hi guys i got a problem with my Code. I load new Page Content on click of Button and got a JQuery Function with onclick which changes a love or like count on Page. If i dont include the JQuery Function into the Ajax loaded page it doesn`t work but if i do he acts twice the function any idea how to fix this or solutions?
This is the JQuery Script from page:
$(".toggle").on("click", function(e) {

            $('.alert-box').hide();
        $( '.alert-box' ).remove();
  var $this = $(this);
  var $lovecount = $this.closest("div").find(".lovecount");
  if ($(e.target).hasClass('love')) {
    //alert('Liebe genommen');
  var val = +$lovecount.text() + (this.checked ? -1 : -1);
  $(e.target).prop( "checked", false );

  } else {
    //alert('Liebe gegeben');
  var val = +$lovecount.text() + (this.checked ? 1 : 1);
  $(e.target).prop( "checked", true );

  };
  //var val = +$lovecount.text() + (this.checked ? 1 : -1);
  $lovecount.text(val)
  $('.alert-box').toggle(!this.checked);
  $(this).toggleClass("love");

  var postid = $this.attr("data-post");
  var userid = $this.attr("data-userid");
  dataString = 'userid=' + userid + '&postid=' + postid;

  // Are you not supposed to send the new value to the server?

  $.ajax({
    type: 'POST',
    url: 'inc/give-love.php',
    data: dataString,
    success: function(response) {
      $('
'+response+'
').prependTo('body').delay(3000).fadeOut(1000, function() {

        $('.alert-box').hide();
        $( '.alert-box' ).remove();

      });
    }
  })
})

with this i change and toggle input from this HTML Code Structure.

              <img src="uploads/<?php echo $row['picture']; ?>">

<?php echo $row['title']; ?>

                <a class="favorite-button" href="#" data-post="<?php echo $row['id']; ?>" data-userid="<?php echo $_SESSION['user_id'];?>">

               <?php $timeago=get_timeago(strtotime($row['created'])); echo $timeago;?>
               1,3k Reaktionen

                OnePost von<?php echo $row['poster']; ?>

<?php echo $row['loves']; ?>

                <?php
                                if($row['is_liked'] != 1){ ?>

                                <input data-post="<?php echo $row['id']; ?>" data-userid="<?php echo $_SESSION['user_id'];?>" type="checkbox" id="toggle" class="toggle">

                                <?}else{?>

                                <input data-post="<?php echo $row['id']; ?>" data-userid="<?php echo $_SESSION['user_id'];?>" type="checkbox" id="toggle" class="toggle love" checked="true">

                <?php }?>

</input>

                    <a href="#" class="share-facebook social-links-a" data-network="Facebook" data-post="<?php echo $row['id'] ?>" data-url="https://onepost.eu/neu/post.php">
                    <a href="#" class="share-twitter social-links-a" data-network="Twitter" data-post="<?php echo $row['id']; ?>" data-url="https://onepost.eu/neu/post.php">
                    <a href="#" class="share-google-plus social-links-a" data-network="Pinterest" data-post="<?php echo $row['id']; ?>" data-url="https://onepost.eu/neu/post.php">
                    <a href="#" class="share-whatsapp social-links-a" data-network="WhatsApp" data-post="<?php echo $row['id']; ?>" data-url="https://onepost.eu/neu/post.php">

When i include the JQuery script in Ajax page it fires twice the function if not onclick is not working. How to prevent this or make it working the right way?

A: If you append any element after DOM has loaded, you need to use delegate(); selector.
$(document).ready(function(){
$("#div1").append('<button id="btn">Click</button>');
//You can use delegate() selector and when you click #btn its works.

$("body").delegate("#btn", "click", function(){
alert("Button has working!");
});
});


text:
Q: How to whitelist a domain while blocking forgeries using that domain? How do you deal with the case of:

*

*wanting to whitelist a domain so that emails from it won't get eaten, but

*not having emails forged to appear to be from that domain get bogusly whitelisted

whitelist_from_recvd looks promising, but then you have to know at
least the TLD of every host that could send you mail from that domain.  Often RandomBigCompany.com will outsource email to one or more sending companies (like Constant Contact and the like) in addition to using servers that reverse-resolve to something in its own domain. But it looks like whitelist_from_recvd can only map to one sending server pattern so that would be problematic.
Is there a way to say something like "if email is from domain X, subtract N points from the spam score"?
The idea would be that if the mail is legit, that -N will all but guarantee it isn't considered spam.  But if it is spam, hopefully all the other failed tests will render it spam even with the -N being included.

A: This is the problem that Sender Policy Framework solves (if it's implemented correctly). The catch is, the sender has to set it up.


text:
Q: How can I extract text information from an owner-drawn window, given a HWND? I'm writing a simple automated test application for Win32. It runs as a separate process and accesses the target application via the Windows API. I can read window hierarchies, find labels and textboxes, and click buttons by sending/posting messages etc. All fine.
Unfortunately many controls in the target application are composed of nothing more than an owner-drawn control/window. (For example, we use the BCG menus and controlbars). Finding the correct part of the control to send a 'click' to is problematic.
Is there any way, given a HWND, to extract GDI drawing commands? I'd like to know each piece of text drawn to that control, and its coordinates.
Failing that, is there any way to capture a single control/window (again by HWND) into a bitmap? Worse-case scenario, I could OCR it.

A: You can use TextGRAB SDK to do this. Unfortunately it is shareware and costs $30.

A: To capture a window as a bitmap:
RECT rc;
GetClientRect(hWnd, &rc);
int cx = rc.right-rc.left;
int cy = rc.bottom-rc.top;

HDC winDC = ::GetDC(hWnd);
HDC tempDC = ::CreateCompatibleDC(winDC);
HBITMAP newBMP = ::CreateCompatibleBitmap(winDC, cx, cy);

HBITMAP oldBmp = (HBITMAP)::SelectObject(tempDC, newBMP);
BitBlt(tempDC,0,0,cx,cy, winDC,0,0,SRCCOPY|CAPTUREBLT);
// now you have the window content in the newBMP bitmap, do with it as you please here

::SelectObject(tempDC, oldBmp);
::DeleteObject(newBMP);
::DeleteDC(tempDC);
::ReleaseDC(hWnd, winDC);


text:
Q: Passing class instance as a pointer and using the overloaded subscript operator on this pointer I have a class that holds an array of integers and to get a reference of this array the subscript operator [] is overloaded (this is a stripped down example with logic checks etc removed):
class Foo {
public:

Foo() {};

// and overload the [] operator
int& operator[](const int index);

private:
const int LEN = 7;
int arr[LEN];
};

int& Foo::operator[](const int index) {
    return arr[index];
}

A pointer of an instance of such class (named boo) is passed to a function. Now what I want to do is:
int val = boo[0];

but it fails "error: invalid cast from type 'Foo' to type 'int'".
My first idea was that Im passing a pointer to a class and I should bring a copy of the instance into scope and use that copy instead. This works. But Im curious if it would be possible to use the user defined type as a true built in type? Should I use a wrapper?

A: You need to either use :
boo->operator[] ( 0 );

or
(*boo)[0];

I.E. dereference the pointer to the object boo.

A: Because the overloaded operator is defined for objects, not pointers to objects. There's two options:
int val = boo->operator[](0);

or
int val = (*boo)[0];

Or you can pass the object (by value or reference) instead of a pointer to it.
Your case is equivalent to:
Boo* b = ....;
b[0];           //this returns a Boo object

as opposed to:
Boo b;
b[0];           //calls operator[]


text:
Q: Magento Module Development I need to modify Menu.php located at app/code/core/Mage/Adminhtml/Block/Page/Menu.php. My question is can I change the directory path to local (app/code/local/Mage/Adminhtml/Block/Page/Menu.php) without having any issues in the future?

A: The best practice for overriding a Magento core class is explained in the following article
You need to create your own basic module, and rewrite the core class to point to your module's class. That class may then extend the existing Magento core class, overriding or extending any methods.
However, you could simply copy the file and its path to the local directory, since Magento's autoloader defaults there first when looking for classes. The problem with this is that, when you decide to upgrade Magento, you must fully copy the new file to your path (if it were modified by the upgrade) and reapply your modifications.
The rewrite/extend is a much more maintainable solution, but the latter is quick and easy. The choice is yours!


text:
Q: Google maps usage limits My application has a store-locator functionality and we have implemented it in the following manner,
On the first page user gets a input text box where we have used google js places api, autocompleteservice. So we have included the following script tag
<script src='https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&[OUR_KEY]'></script>

There is no map displayed on this page, however when the user clicks on search, the next page displays the map with user selected location and our stores around it. This page has the following script added
<script src='https://maps.googleapis.com/maps/api/js?&[OUR_KEY]}'></script>

Question:
1. Do we need to add the '[OUR_KEY]' value on both pages ?
2. If we have added it to both the pages, how will google charge ? Since the first page does not contain any map loads, will it count the hits for first page as well which has the autocompleteservice ?

A: 1. Do we need to add the '[OUR_KEY]' value on both pages ?
According to the Google Maps API FAQ

The Google Maps JavaScript API v3 and the Maps Image APIs previously did not require an API console key. This is still supported for legacy applications to ensure backwards compatibility, but is no longer recommended for new applications.

Plus, some features arn't available whitout api key.
You can find more inforamtion about avaialble feature and commercial usage on the FAQ : https://developers.google.com/maps/faq#keysystem
2. If we have added it to both the pages, how will google charge ? Since the first page does not contain any map loads, will it count the hits for first page as well which has the autocompleteservice ?

your site or application generates 25 000 map loads or more each day, for more than 90 consecutive days, we'll get in touch with you to talk about payment.

https://developers.google.com/maps/documentation/javascript/usage
For the JavaScript API, only map loads are counted
About The Places Library :
The Places Library in the Google Maps JavaScript API, is covered by the Google Maps JavaScript API limits.
So, the search for autocompletion will count for a request and the page load on the second page will also count in your quota.


text:
Q: Legends Lost quest stuck (already have Sunder and Wraithguard) I have this quest opened saying I need to find the detoured caravans.
I wasn't finding anything, than I looked it up on the internet. I've already found those long ago, already completed the quest, and have the items rewarded.

 I remember defeating the ebony centurion and the items are in my house in Solitude: the mannequins have the gauntlets.

I don't know if it reopened or never closed. Is there a way to force complete it with no consequences? I just want to remove it from my journal.
I'm playing an unmodded Anniversary Edition.


text:
Q: standard conversions:Qualification conversions This is the point from ISO :Standard Conversions:Array-to-pointer conversion: $4.4: Qualification conversions /5th point
    A multi-level pointer to member type, or a multi-level mixed pointer and
     pointer to member type has the form:
           cv 0 P 0 to cv 1 P 1 to . . . cv n − 1 P n − 1 to cv n T
    where P i is either a pointer or pointer to member and where T is not a
    pointer type or pointer to member type.

Can any one Explain this.If possible give the example ..
What actually meant for that form.Can any one eloborate it ?
Similarly ..There are different form in that section(Qualification conversions)

A: A multilevel pointer is a pointer to a pointer.
Variables can be const or volatile normally (these are called cv-qualifiers).  When you have a pointer, both the pointed-to data and the pointer itself can have cv-qualifiers.  When you have a multilevel pointer, there can be cv-qualifiers at any level.
For example:
int i1 = 1;
const int i2 = 2;
int * p1 = &i1; // p1 is a non-constant pointer to a non-constant int
int * const p2 = &i1; // p2 is a constant pointer to a non-constant int
int const * p3 = &i2; // p3 is a non-constant pointer to a constant int
const int * p4 = &i2; // same as p3
int const * const p5 = &i2; // p5 is a constant pointer to a constant int
int * * pp1 = &p1; // non-const pointer to non-const pointer to non-const int
int * * const pp2 = &p1; // const pointer to non-const pointer to non-const int
int * const * pp3 = &p2; // non-const pointer to const pointer to non-const int
int const * * pp4 = &p3; // non-const pointer to non-const pointer to const int
// etc.

A: They're simply saying that you can have a pointer to a pointer to a pointer to a pointer to ...to something other than a pointer. At each of those steps along the way, you can have const, volatile, or both. So, for example, you could have:
int const * volatile *const volatile x;

which means x is a const, volatile pointer to a volatile pointer to a const int.


text:
Q: ImageView in relativelayout overlapping with other widgets I am trying to build a custom view in Android that shows an image, and some text fields (non-editable).
I started by extending the RelativeLayout class for my custom view.
In the constructor of my custom view I created an ImageView and a TextView, and added them to the layout.
The TextView is loaded immediately, but the ImageView is loaded on a different thread and the bitmap is populated through a handler.
Once the bitmap is loaded, the ImageView is overlapping the TextView. The TextView is supposed to be on the "right-of" the ImageView, but this adjustment is not happening automatically.
I tried using customView.invalidate(), but that did not help.
This problem is not there when the same components are declared via XML.
Any help in resolving would be appreciated. Thanks
public class MyView extends RelativeLayout {
    private TextView productName;
    private ImageView productImage;

public MyView(Context context) {
    super(context);
    initHandler();
}

public MyView(Context context, AttributeSet attrs, int defStyleAttr,
        int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    initHandler();
}

public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initHandler();
}

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
    initHandler();
}

private void initHandler() {
    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            // implement logic to show content here
            productName.setText(currentProduct.getTitle());
            productImage.setImageBitmap(currentProduct.getImageBitmap());

            MyView.this.invalidate();
        }
    };

    productImage = new ImageView(getContext());
    RelativeLayout.LayoutParams layout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    layout.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    layout.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
    productImage.setLayoutParams(layout);

    //keep the textview to right of imageview
    productName = new TextView(getContext());
    layout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    layout.addRule(RelativeLayout.RIGHT_OF, productImage.getId());
    layout.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    productName.setLayoutParams(layout);
    productName.setTextColor(Color.parseColor("#ffffff"));

    this.addView(productImage);
    this.addView(productName);

    //logic to load content on a new thread goes here
}

}
XML in which I included the custom view:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.mycompany.MyView
    android:background="@android:color/black"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
</RelativeLayout>

A: you need add an id to your View in xml
<com.mycompany.MyView

android:id="@+id/myView"

android:background="@android:color/black"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

and in your java initilize it like
ImageView im = (ImageView)findViewById(R.id.myView);

try that


text:
Q: How to stop scroll event function when the user move to another page I am adding the scroll event in javascript for one of my pages. The code is like this:

    document.getElementById("myProject").addEventListener("scroll", myFunction);

     function myFunction() {
     document.getElementById("scrollEvent").innerHTML = "These are all my projects so far";

     }

So, when users start scrolling, they will see a text "These are all my projects so far".
My problem is how to stop showing this text when users move to another page.
Please help ( I am a verrrry fresh developer)
Thanks so much

A: A few thoughts.

*

*Without knowing your dev environment (e.g. are you using MVC with a framework?), I will assume you are simply talking about separate/individual HTML pages.

*Each HTML page can have its own javascript. Just like HTML and CSS, there is no need to have the same javascript functions on every page. (You don't have the same HTML content on every page, right?) Usually, we divide up the javascript into multiple files - some files are added to every page, some are specific to a certain page. It is easiest to have one (external) javascript file that you reference on every page, and then specific javascript code for each page - either in a second external file that is referenced, or on the HTML page inside <script>//js here</script> tags.

*If the DIV with ID myProject is not on the other page, then the javascript won't do anything. However, it is not good to have broken javascript on a page, so make sure it is not included on other pages.
If you are using a framework, like CodeIgniter or ReactJS or Angular, please tell us so we can adjust our answers accordingly.

A: If the case is a switching between browser tabs, you can use two different events like below.
$(window).blur(function(e) {
  // stop scroll event, when switching to another tab
  document.getElementById("myProject").removeEventListener("scroll");
});
$(window).focus(function(e) {
  // start scroll event
  document.getElementById("myProject").addEventListener("scroll", myFunction);
});

I am not sure what you are actually looking for, because when user switch between tabs, he can not see the text anymore no matter there is a scroll event or not. If you are concern about performance, then the above solution would help.


text:
Q: Functions of Random Variables - I am not sure if I am understanding this problem correctly. Let T be an exponential random variable with parameter $\lambda$. Let X be a discrete random variable defined as X = k if $k \leq T < k+1$ and k = 0, 1, 2, ...
Find the PMF of X.
I am not sure if I am doing this problem correctly. Here is my approach.
$F_x(k \leq T < k+1) = F_t(k+1) - F_t(k)$
= $(1 - e^{-\lambda (k+1)} - (1 - e^{-\lambda k})$
= $-e^{-\lambda(k+1)} + e^{-\lambda k}$
From there, I differentiate:
$f_x(k) = \lambda e^{-\lambda(k+1)} - \lambda e^{-\lambda k}$
I am unsure if I did this correctly - perhaps because I am misunderstanding something. Perhaps, what is the purpose of defining X = k in the given question?

A: Note that $X$ is discrete, so differentiating doesn't really make sense.
You need to compute $p[X=k]$ .
You have $p[X=k] = p[T < k+1] - p[T \le k]  = (1-e^{-\lambda (k+1)}) - (1-e^{-\lambda k}) = e^{-\lambda k} (1-e^{-\lambda})$.
As a quick check, note that $\sum_{k \ge 0} p[X=k] = 1$.


text:
Q: Powershell - how to set multiple action on get-aduser "dataset" I'm trying to run a script that modify password for multiple AD user accounts, enable the accounts and force a password change at next logon.
I use this code but that's not work :
Get-ADUSER -Filter * -SearchScope Subtree -SearchBase "OU=myou,OU=otherou,DC=mydc,DC=local" |
Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "NewPassord" -Force) |
Enable-ADAccount |
Set-ADUSER -ChangePasswordAtLogon $true

If I run the Get-ADuser line with ONLY one of the other line that's run fine ex :
Get-ADUSER -Filter * -SearchScope Subtree -SearchBase "OU=myou,OU=otherou,DC=mydc,DC=local" |
    Enable-ADAccount
Where I'm wrong ? I'm new to PowerShell probably I'm misunderstanding something.

A: Your pipeline doesn't work the way you expect it does.
$UserList=Get-ADUSER -Filter * -SearchScope Subtree -SearchBase "OU=myou,OU=otherou,DC=mydc,DC=local"
foreach ($User in $UserList) {
    Set-ADAccountPassword $User -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "NewPassord" -Force
    Enable-ADAccount $User
    Set-ADUSER $user -ChangePasswordAtLogon $true
}

Pipelines aren't good for multiple actions on the same object. They only work if each command in the pipeline forwards the same object as the initial object. For that, iterating through a loop makes a lot more sense.

A: Get-ADUSER -Filter * -SearchScope Subtree -SearchBase "OU=myou,OU=otherou,DC=mydc,DC=local" | %{
Set-ADAccountPassword $.Name -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "NewPassord" -Force)
Enable-ADAccount $.Name
Set-ADUSER $_.Name-ChangePasswordAtLogon $true
}


text:
Q: Apart from Union , Union all and Pivot in MS- Sql server can I combine two columns into one column I am having a result set like
Col1:    Col2

a         b

c         d

I want result set like
a

b

c

d

Without using Union, Union all and Pivot.

A: SELECT T.x
FROM table
     CROSS APPLY (
         VALUES (Col1), (Col2)
     ) AS T(x)

A: You can use unpivot.
select value from yourtable
    unpivot (value for field in (col1,col2)) u


text:
Q: Could not cast value of type 'UIViewController' to UITableViewController I'm trying to segue from one view controller to another, and pass data to the next controller, but I keep getting this error:

Could not cast value of type ViewController to [VC2]

Setup looks like this:

*

*NavigationController is initial entry point to VC1

*ViewController1 is a collectionViewController with show segue to VC2

*ViewController2 is a viewController with only a container to embed VC3

*ViewController3 is a tableViewController with static table and
collectionView.

VC3 is my destinationViewController and embedded in VC2.  When I select a collectionViewCell from VC1 I get Signal SIGABRT.
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

        selectedImage = UIImage(named: wholeArray[indexPath.row]["image"] as! String)!
        selectedLabel = wholeArray[indexPath.row]["name"] as? String

        self.performSegueWithIdentifier("show", sender: nil)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

    if (segue.identifier == "show") {
      let secondVC: ViewController02 = (segue.destinationViewController as? ViewController02)!

            secondVC.image = selectedImage
            secondVC.label = selectedLabel
        }
    }

Since UITableViewController is a subclass of UIViewController, this code should work just fine.  What am I doing wrong?
** Updated question with type inheritance and exact error message: **
class ViewController01: UICollectionViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

class ViewController02: UIViewController {

class ViewController03: UITableViewController, UICollectionViewDataSource, UICollectionViewDelegate,UIScrollViewDelegate {

class HeaderView: UIView {

2015-10-07 11:26:27.384 UITableViewHeader[45474:3576139] Unknown class _TtC17UITableViewHeader14ViewController in Interface Builder file.
Could not cast value of type 'UITableViewHeader.ViewController02' (0x107a38360) to 'UITableViewHeader.ViewController03' (0x107a38a50).

A: Change this line in your code
let secondVC: ViewController02 = (segue.destinationViewController as? ViewController02)!

To
let secondVC:ViewController02 = segue.destinationViewController as! ViewController02

or simple to:
    let secondVC = segue.destinationViewController as! ViewController02


text:
Q: jQuery Mobile - Remove back button only when pointing to a particular page I have a mobile web app with a login screen. After logging in, the user goes to the homescreen of the app. Since I have back buttons enabled for the entire application, the back button appears on the homescreen; however, pressing "Back" now will take the user back to the login page (which I don't want). At the same time, the homescreen should have a "Back" button, since  user might get to the homescreen from some other screen in the app and might want to go back.
So basically is there any easy way to disable the back button if it's going to go to the login screen, but not if it's going someplace else?

A: Another strategy you could consider is having the login page add a parameter to the query string of the home page indicating that back should be disabled.
http://myapp.com/page.html?backDisable=true

Inside your page a simple javascript call could determine if the parameter was passed and if so disable the back button.  Here's a sample using the URL parser plugin.
if ($.url().param('backDisable') === 'true') {
  $('#backButton')[0].disabled = true;
}

A: How about setting up an array of pages visited and checking it to see if the last page was the login page:
//setup array of page views
var page_views = [];
//add event handler for `pageshow` event
$('[data-role="page"]').live('pageshow', function () {
    //add current page to page_views array
    page_views.push(this.id);
    var page_views_length = page_views.length;
    //check if the current page is the homescreen and if the last page was the login page
    if (this.id == 'homescreen_id' && page_views_length > 1 && page_views[(page_views_length - 2)] == 'login_id') {//this assumes your login page has the id of `login_id` and your homescreen page has the id of `homescreen_id`
        //run code to hide the back button
    }
});

A: Add data-ajax="false" to your login-in form.
I assume your login form and home screen exist on the same domain.
So when you go to example.com you see login form (if not logged in)
... when you go to example.com you see a welcome screen...
PHP example of my index layout... (dirty):
<div data-role="page">
<?php if ($notloggedin) { ?>
    <form method="post" action="<?= $this->baseUrl('/'); ?>" id="login-form" data-ajax="false">...form...</form>
<?php } else { ?>
    YOUR PAGE
<?php } ?>
</div>

jquery mobile page links


text:
Q: R How to have dataframe with inputs in different chracter sets I have a problem with R on my windows XP and rstudio
I have inputs in hebrew, chinese and other languages with accentuated letters. All characters are displayed on my console and editor but not in the dataframe...

d <- data.frame(beta=c("לחשיקר","'וקויכחגקכ"), gamma=c("gö", "áóò"), delta= c("可可","是"))
head(d)

this is the output
> d <- data.frame(beta=c("לחשיקר","'וקויכחגקכ"), gamma=c("Hö", "áóò"), delta= c("可可","是"))
> head(d)
                                                                       beta gamma            delta
1                          <U+05DC><U+05D7><U+05E9><U+05D9><U+05E7><U+05E8>    Hö <U+53EF><U+53EF>
2 '<U+05D5><U+05E7><U+05D5><U+05D9><U+05DB><U+05D7><U+05D2><U+05E7><U+05DB>   áóò         <U+662F>

I have read that I can set my locale to chinese or hebrew and so on, but is there a locale to have all characters simultaneously ?
Is it possible to have this on linux if it is impossible on windows ?
I use my data to print graphs with ggplots, via

color=

to go throughout all my colums containing these foreign terms, and of course, the unicodes  appear in my legend. Is it possible to at least change these, by hand, in the legend to the true characters in the original languages ?
This is my system on windows 32 bits (I do not have linux presently)
> sessionInfo()
R version 3.1.2 (2014-10-31)
Platform: i386-w64-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252 LC_NUMERIC=C                           LC_TIME=English_United States.1252


text:
Q: Clarification on Threads and Run Loops In Cocoa I'm trying to learn about threading and I'm thoroughly confused. I'm sure all the answers are there in the apple docs but I just found it really hard to breakdown and digest. Maybe somebody could clear a thing or 2 up for me.
1)performSelectorOnMainThread
Does the above simply register an event in the main run loop or is it somehow a new thread even though the method says "mainThread"? If the purpose of threads is to relieve processing on the main thread how does this help?
2) RunLoops
Is it true that if I want to create a completely seperate thread I use
 "detachNewThreadSelector"? Does calling start on this initiate a default run loop for the thread that has been created? If so where do run loops come into it?
3) And Finally , I've seen examples using NSOperationQueue. Is it true to say that If you use performSelectorOnMainThread the threads are in a queue anyway so NSOperation is not needed?
4) Should I forget about all of this and just use the Grand Central Dispatch instead?

A:
1)performSelectorOnMainThread
Does the above simply register an event in the main run loop …

You're asking about implementation details. Don't worry about how it works.
What it does is perform that selector on the main thread.

… or is it somehow a new thread even though the method says "mainThread"?

No.

If the purpose of threads is to relieve processing on the main thread how does this help?

It helps you when you need to do something on the main thread. A common example is updating your UI, which you should always do on the main thread.
There are other methods for doing things on new secondary threads, although NSOperationQueue and GCD are generally easier ways to do it.

2) RunLoops
Is it true that if I want to create a completely seperate thread I use "detachNewThreadSelector"?

That has nothing to do with run loops.
Yes, that is one way to start a new thread.

Does calling start on this initiate a default run loop for the thread that has been created?

No.
I don't know what you're "calling start on" here, anyway. detachNewThreadSelector: doesn't return anything, and it starts the thread immediately. I think you mixed this up with NSOperations (which you also don't start yourself—that's the queue's job).

If so where do run loops come into it?

Run loops just exist, one per thread. On the implementation side, they're probably lazily created upon demand.

3) And Finally , I've seen examples using NSOperationQueue. Is it true to say that If you use performSelectorOnMainThread the threads are in a queue anyway so NSOperation is not needed?

These two things are unrelated.
performSelectorOnMainThread: does exactly that: Performs the selector on the main thread.
NSOperations run on secondary threads, one per operation.
An operation queue determines the order in which the operations (and their threads) are started.
Threads themselves are not queued (except maybe by the scheduler, but that's part of the kernel, not your application). The operations are queued, and they are started in that order. Once started, their threads run in parallel.

4) Should I forget about all of this and just use the Grand Central Dispatch instead?

GCD is more or less the same set of concepts as operation queues. You won't understand one as long as you don't understand the other.

So what are all these things good for?
Run loops
Within a thread, a way to schedule things to happen. Some may be scheduled at a specific date (timers), others simply "whenever you get around to it" (sources). Most of these are zero-cost when idle, only consuming any CPU time when the thing happens (timer fires or source is signaled), which makes run loops a very efficient way to have several things going on at once without any threads.
You generally don't handle a run loop yourself when you create a scheduled timer; the timer adds itself to the run loop for you.
Threads
Threads enable multiple things to happen at the exact same time on different processors. Thing 1 can happen on thread A (on processor 1) while thing 2 happens on thread B (on processor 0).
This can be a problem. Multithreaded programming is a dance, and when two threads try to step in the same place, pain ensues. This is called contention, and most discussion of threaded programming is on the topic of how to avoid it.
NSOperationQueue and GCD
You have a thing you need done. That's an operation. You can't have it done on the main thread, or you'd simply send a message like normal; you need to run it in the background, on a secondary thread.
To achieve this, express it as either an NSOperation object (you create a subclass of NSOperation and instantiate it) or a block (or both), then add it to either an NSOperationQueue (NSOperations, including NSBlockOperation) or a dispatch queue (bare block).
GCD can be used to make things happen on the main thread, as well; you can create serial queues and add blocks to them. A serial queue, as its name suggests, will run exactly one block at a time, rather than running a bunch of them in parallel.
So what should I do?
I would not recommend creating threads directly. Use NSOperationQueue or GCD instead; they force you into better thinking habits that will reduce the risk of your threaded code inducing headaches.
For things that run periodically, not fitting into the "thing I need done" model of NSOperations and GCD blocks, consider just using the run loop on the main thread. Chances are, you don't need to put it on a thread after all. A rendering loop in a 3D game, for example, can be a simple timer.

A: Run Loops
You can think of a Run Loop to be an event processing for-loop associated to a thread. This is provided by the system for every thread, but it's only run automatically for the main thread.
Note that running run loops and executing a thread are two distinct concepts. You can execute a thread without running a run loop, when you're just performing long calculations and you don't have to respond to various events.
If you want to respond to various events from a secondary thread, you retrieve the run loop associated to the thread by
[NSRunLoop currentRunLoop]

and run it. The events run loops can handle is called input sources. You can add input sources to a run-loop.
PerformSelector
performSelectorOnMainThread: adds the target and the selector to a special input source called performSelector input source. The run loop of the main thread dequeues that input source and handles the method call one by one, as part of its event processing loop.
NSOperation/NSOperationQueue
I think of NSOperation as a way to explicitly declare various tasks inside an app which takes some time but can be run mostly independently. It's easier to use than to detach the new thread yourself and maintain various things yourself, too. The main NSOperationQueue automatically maintains a set of background threads which it reuses, and run NSOperations in parallel.
So yes, if you just need to queue up operations in the main thread, you can do away with NSOperationQueue and just use performSelectorOnMainThread:, but that's not the main point of NSOperation.
GCD
GCD is a new infrastructure introduced in Snow Leopard. NSOperationQueue is now implemented on top of it.
It works at the level of functions / blocks. Feeding blocks to dispatch_async is extremely handy, but for a larger chunk of operations I prefer to use NSOperation, especially when that chunk is used from various places in an app.
Summary
You need to read Official Apple Doc! There are many informative blog posts on this point, too.


text:
Q: Do non-additive subgroup ideals of rings exist? Let $(R,+,\cdot)$ be a ring. A subset $I$ of $R$ is called an ideal if it satisfies

*

*$(I,+)$ is a subgroup of $(R,+)$

*$I$ "absorbs" products in $R$, that is, for every $x\in I$ and every $a\in R$, both $ax$ and $xa$ are in $I$

My question is: what would we call a subset $I$ that does not satisfy the "additive subgroup" condition?
I can´t find an answer anywhere. I think these type of subsets should also have some interesting properties? Does there exist any theorem about them?

A: I think you are describing a (monoid) ideal.


text:
Q: Can't connect Android to desktop server I'm developing a game using libGdx and Kryonet and I'm currently working on the server <-> android connection.
First I run the server on a computer, and if I run two instances of the program on the same computer (so the IP will be the local IP: "127.0.0.1"), I don't get any problems, and the connection works fine.
But if instead of running the game on desktop, I run it on the android device, the connection doesn't happen. Both the devices are connected to the same Wi-fi network, so to discover the IP, what I do is type "ipconfig" on the console, and check the line that says: "IPv4 Adress" under "Wireles LAN adapter Wi-Fi" (I think it's this one).
I've added this 3 lines to the android manifest file (are they really needed?):
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Here's the important error log:

Do I need to do anything on the device some extra code for the android connection to establish? More permissions perhaps?
Here's the relevant code:
MPServer:
public class MPServer {
Server server;
Array<PlayerInfo> playersInfo;
int numNewPlayers;

public MPServer() throws IOException {
    numNewPlayers = 0;
    playersInfo = new Array<PlayerInfo>();
    server = new Server();

    Network.registerPackets(server);
    addListeners();
    server.bind(Network.PORT);
    server.start();
}

private void addListeners() {
    server.addListener(new Listener() {
        @Override
        public void connected(Connection connection) {

        }

        @Override
        public void disconnected(Connection connection) {

        }

        @Override
        public void received(Connection c, Object object) {

        }
    });
}

public static void main(String[] args) {
    try {
        new MPServer();
        Log.set(Log.LEVEL_DEBUG);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

MPClient:
public class MPClient {
static final int TIME_OUT = 5000;
Client client;
MultiPlayMatch match;

public MPClient(String name, int team, MultiPlayMatch match) {
    this.match = match;
    client = new Client();
    client.start();

    Network.registerPackets(client);
    addListeners();

    try {
        client.connect(15000, Network.WIFI_IP, Network.PORT);
    } catch (IOException e) {
        e.printStackTrace();
        client.stop();
    }

    while(true) {

    }

}

private void addListeners() {
    client.addListener(new Listener.ThreadedListener(new Listener() {
        @Override
        public void connected(Connection connection) {

        }

        @Override
        public void disconnected(Connection connection) {

        }

        @Override
        public void received(Connection connection, Object object) {

        }
    }));
}
}

A: If you are using Windows OS , the reason might be windows firewall, try disabling it if you want to connect your mobile to the local server.


text:
Q: Best ways to split a string with matching curly braces I'm working in C# right now and I'm using JSON.Net to parse json strings to well, C# objects.  Part of my problem is that I'm getting some strings like this:
{"name": "John"}{"name": "Joe"}

When I try to deserialize with JsonConvert.DeserializeObject<>, it throws an exception.
I'm wondering what would be the best way to split of this bigger string into smaller json strings.
I was thinking about going through the string and matching curly braces of "level 0".  Does this seem like a good idea?  Or is there some better method to do this?

A: You can use a JsonTextReader with the SupportMultipleContent flag set to true to read this non-standard JSON.  Assuming you have a class Person that looks like this:
class Person
{
    public string Name { get; set; }
}

You can deserialize the JSON objects like this:
string json = @"{""name"": ""John""}{""name"": ""Joe""}";

using (StringReader sr = new StringReader(json))
using (JsonTextReader reader = new JsonTextReader(sr))
{
    reader.SupportMultipleContent = true;

    var serializer = new JsonSerializer();
    while (reader.Read())
    {
        if (reader.TokenType == JsonToken.StartObject)
        {
            Person p = serializer.Deserialize<Person>(reader);
            Console.WriteLine(p.Name);
        }
    }
}

Fiddle: https://dotnetfiddle.net/1lTU2v

A: I found the best way is to convert your string to an array structure:
string json = "{\"name\": \"John\"}{\"name\": \"Joe\"}";

json = json.Insert(json.Length, "]").Insert(0, "[").Replace("}{", "},{");

// json now is     [{"name": "John"},{"name": "Joe"}]
List<Person> result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Person>>(json);

Assuming your class name is Person :
public class Person
{
    public string Name { set; get; }
}


text:
Q: How to automatically authorize clients for Postgresql? Every time I connect to postgresql database I authorize my IP in Google Cloud. As I am going to use AWS(it gives a new IP on every connection), I want to automatically authorize those IPs.
So how can I do it? Is there any certificate or json files that I can use for this?

A: The most secure way to do it would be to use the Cloud SQL proxy, which allows you to connect without Authorized IPs.
Another, less secure way would be to use the Cloud SQL Admin API to authorize your IP address as needed - you can use gcloud or a REST call to programmatically do this as needed. Please note that:

*

*The IP will be authorized until removed, even if you stop using it

*Configuring new authorized networks replaces any existing authorized networks. You'll either need to GET the current list and append (but be wary of race conditions!) OR use a shared value store to make sure the list of IPs is currently up to date.


text:
Q: How to load customer by attribute in magento2? What is the best way to load Customer by custom attribute?
I create custom module. What should I overwrite?

*

*Model/Customer

*Model/ResourceModel/Customer

*Model/ResourceModel/CustomerRepository

What is the best way?

A: We should try with Service Contracts Layer.
Take a look: vendor/magento/module-backend/Model/Search/Customer::load()
    $searchFields = ['firstname', 'lastname', 'company'];
    $filters = [];
    foreach ($searchFields as $field) {
        $filters[] = $this->filterBuilder
            ->setField($field)
            ->setConditionType('like')
            ->setValue($this->getQuery() . '%')
            ->create();
    }
    $this->searchCriteriaBuilder->addFilters($filters);
    $searchCriteria = $this->searchCriteriaBuilder->create();
    $searchResults = $this->customerRepository->getList($searchCriteria);

We can use Magento\Customer\Api\CustomerRepositoryInterface::getList() to retrieve customers which match a specified criteria.


text:
Q: Questions on linear regression I had a few true / false questions on a practice test that I would like to discuss if possible.

*

*A value $R^2$ close to 1 indicates the linear regression is a good fit to data

Yes, but I am not sure how to reason it other than intuitively. More precisely, why do we decide to define $R^2$ as 1-(sum of residuals/total sum of squares)?

*

*The estimate of the error variance $s^2$ is a random variable

I believe it is because how the error varies is normally distributed if I remember correctly. If anyone could elaborate it would be much appreciated.

*

*$∑(Y_{1,i}−Y_{2,i})^2 = 0$, where $Y_1$ is the predicted value and $Y_2$ is the actual value.

Since the sum of residuals is zero and since this is equivalent to the sum of residuals it must be zero.

A: c) Is definitely wrong, because it is the sum of SQUARED residuals. It would be the variance of prediction errors, if you divided it by the degrees of freedom, assuming that the mean of prediction errors is 0.
a) $R^2$ is the proportion of explained variation on the whole variation. The formula is just a different representation of $R^2$.
b) I would say, everything calculated from random variables is a random variable itself.


text:
Q: Prove that three vectors are coplanar Three vectors are given: $u,v,w$. It is given that:
$|u|=|v|=|w|= \sqrt{2}$; $u\cdot v=u\cdot w=v\cdot w=-1$.
Prove that vectors $u,v,w$ are coplanar (on the same plane).
I have a few ideas, but I don't know if they are helpful in this case:
I know that three vectors are co-planar if $u\cdot(v x w)=0$.
In addition, I assume that you can prove it with linear dependence, but I don't know how to use it here.
In addition, I thought that maybe the angle between the vectors can be of help- $120$ degrees between every $2$ vectors- but does that necessarily mean that they are on the same plain-  co-planar?

A: The sum of three angles formed by three non-coplanar vectors is always less than 360 degrees. However instead of proving this general statement one can arrive at the required result immediately, observing that the vectors in the problem form an equilateral triangle. An easy check shows:
$$(u+v+w)\cdot(u+v+w)=|u|^2+|v|^2+|w|^2+2u\cdot v+2v\cdot w+2w\cdot u=0\\
\implies u+v+w=0.$$
As the three vectors are linearly dependent, they are coplanar.


text:
Q: max+1 without interference When a row is added to my table, I need a certain column's value to be max+1. This is not an auto increment situation because it's only within a set of rows within the table. In other words, when selecting certain rows, the max of THOSE rows is what needs to determine the next row I add, not the max of the entire table. So there can be more than 1 row with the same values, just not more than 1 row within my x rows I select.
This is when they are added. The values can also be changed later on, manually, via a form, and would still need to remain unique within that set (which is easy, of course).
The problem, here, is since there is a tiny delay between checking for the max value and updating it, technically, even though this has not happened in years of me using this, a second user "could" come along and get that same max value, in between the original user's select and update.
I'd rather not have to do locking the table, and the framework I am working within doesn't have transactions built in. Just curious if anyone has other ideas.
One idea I had was locking the method itself... when someone is using it, add a temporary row to the db, then check for it and if one is there, have the second user basically redirect to the same page until that row is removed. But a lot of extra db work involved there, so I don't know...
This same issue comes into play when there is a limit. Say only 50 people can add a row, 49 have added them, 2 members could both get that same 49 in between a select and update, and be allowed in.


text:
Q: Identities For Generalized Harmonic Number I have been searching for identities involving generalized harmonic numbers
\begin{equation*}H_n^{(p)}=\sum_{k=1}^{n}\frac{1}{k^p}\end{equation*}
I found several identities in terms of $H_n^{(1)}$, but I am looking for some interesting identities for $H_n^{(2)}$. Does anyone know of any identities know of any nontrivial identities for $H_n^{(2)}$?  I found some listed on Wikipedia, but this list is not comprehensive. Thanks for your help.

*

*integral identities

*summation identities

*recursive identities

*in terms of another function

A: There is a nice list and a set of references at mathworld.  Additionally, I discovered this one while writing a thesis on the Riemann Zeta function.
$$\sum_{n=1}^\infty \frac{H_n^{(s)}}
 {n^s}=\frac{\zeta(s)^2+\zeta(2s)}{2}.$$

A: I discovered a Generalized Harmonic Summation Identity some time ago.

$$ \sum_{r=1}^{n} \dfrac{H_{r} ^{(m)}}{r^m} = \dfrac{1}{2} \left( [H_{n}^{(m)}]^2 + H_{n}^{(2m)} \right) \quad ; \quad m \geq 1 $$

I have posted a proof here.


text:
Q: Remove duplicates only if both columns are the same - excel I would like to remove rows with duplicates only if two columns are the same:
A   B   C.
—————————.
AA  11  L.
AA  12  l.
BB  12  L.
AA  11  C.
Basically, I want to check if both, A and B are the same, if they are, remove duplicates.
So output is:
A   B   C.
—————————.
AA  11  L.
AA  12  L.
BB  12  L.

A: It is standard behavior of Remove duplicates function. Just uncheck cols what you not need to compare.

A: Let's say the data is like this:

My formula at D2 is =COUNTIFS($A$2:A2;A2;$B$2:B2;B2) and drag down.
Later on, you can filter in that column for any value higher than 1 (a 2 means a second coincidence, a 3 a third coincidence, and so on) and delete all those rows)
Hope this helps
IMPORTANT: Please, note the sorting here is important, because the formula starts counting from first row of data, so if you change the order, what was the first coincidence could be now the second one, and then be deleted. Be aware of that.


text:
Q: Remove accidental .dll file association On Windows 10 I have accidentally set the association for .dll files to Notepad++ - how can I remove the association so that dll files go back to having no assocation?
I found this question, which concerns .exe files rather than .dll
I have poked aorund the registry, but I can't seem to find any Notepad++ entries for associations

A: Use this REG file to reset the association settings for .DLL file type.
Windows Registry Editor Version 5.00

[-HKEY_CLASSES_ROOT\.dll]

[HKEY_CLASSES_ROOT\.dll]
@="dllfile"
"Content Type"="application/x-msdownload"

[HKEY_CLASSES_ROOT\.dll\PersistentHandler]
@="{098f2470-bae0-11cd-b579-08002b30bfeb}"

[-HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.dll\UserChoice]

Copy the above lines to Notepad and save the file with .REG extension. Double-click the file to apply the settings to the registry.


text:
Q: How to transpose multiple cells at once in Excel I have an Excel document such as this, with many listings:
Name
Address
City, State
ZIP

Name
Address
City, State
ZIP

In between each, there is a blank line. How can I convert it to something like:
Name, Address, City, Sate, ZIP
Name, Address, City, Sate, ZIP

I have done some research and the macros seem to give errors. The special paste also only allows me to do 1 by one.

A: You don't need macros for this!
Just enter this in Sheet2 and adapt the sheetname in the formulas:

*

*A1: =OFFSET(Sheet1!$A$1,(ROW()-1)*6,0)

*A2: =OFFSET(Sheet1!$A$1,(ROW()-1)*6+1,0)

*A3: =OFFSET(Sheet1!$A$1,(ROW()-1)*6+2,0)

*A4: =OFFSET(Sheet1!$A$1,(ROW()-1)*6+3,0)

*A5: =OFFSET(Sheet1!$A$1,(ROW()-1)*6+4,0)

Then mark the entries you just made and drag them down as long as needed.. Done!

A: I answered this a couple of days ago but my answer seems to have been lost.  Perhaps I did not post it correctly since I am new to this site.
I have not lived in the States since the late 1970s but our two addresses in Detroit had different numbers of lines.  The formula solution relies on every address having the same number of lines so I do not see it as an adequate solution.
I placed the following English addresses in Sheet1.  The first is a typical UK address.  The other two are real (except for the name and postcode) but less usual.  The second is a village-style address with houses named instead of numbered and the local town included in addition to the village name.  The third address is most unusual since it has no street name.  As the address implies, the house was built into the ruins of what was once the west front of the abbey of Bury St Edmunds.
John Smith
5 Acacia Avenue
York
Yorkshire
YO3 2RG

Sarah Jones
Lilac Cottage
Chapel Lane
Houghton
Huntingdon
Cambridgeshire
CB12 4TG

Alice Green
1 The West Front
Abbey Ruins
Bury St Edmunds
IP33 1RS

The following macro will copy these addresses to Sheet2 in the style you seek.
Sub Test2()

  Dim Col1Crnt As Integer
  Dim Col1Max As Integer
  Dim Col2Crnt As Integer
  Dim Sheet1() As Variant
  Dim Row1Crnt As Integer
  Dim Row1Max As Integer
  Dim Row2Crnt As Integer

  With Sheets("Sheet1")
    ' Find the last used row in Sheet1
    Row1Max = .Cells.Find("*", .Range("A1"), xlFormulas, _
                                            , xlByRows, xlPrevious).Row
    ' Load column 1 to Sheet1.
    Sheet1 = .Range(.Cells(1, 1), .Cells(Row1Max, 1)).Value
    ' Although I am only loading one column, Sheet 1 will be a 2D array
    ' with the row as the first dimension and the column as the second.
    ' I have loaded Sheet1 to an array because switching between
    '  worksheets is very slow.
  End With

  With Sheets("Sheet2")
    Row2Crnt = 1
    Col2Crnt = 1
    For Row1Crnt = 1 To Row1Max
      If Sheet1(Row1Crnt, 1) = "" Then
        ' blank line
        If Col2Crnt <> 1 Then
          ' Only advance row for first blank row
          Row2Crnt = Row2Crnt + 1
          Col2Crnt = 1
        End If
      Else
        .Cells(Row2Crnt, Col2Crnt).Value = Sheet1(Row1Crnt, 1)
        Col2Crnt = Col2Crnt + 1
      End If
    Next
  End With

End Sub

Hope this helps


text:
Q: How to generate all days between two dates in SQLAlchemy? I need a sequence of all days between two dates =, in raw PostgreSQL, I would use generate_series function. How to do this with SQLAlchemy?

A: I managed to do it:
result = func.generate_series(min_date, max_date, '1 day')


text:
Q: MySQL bitwise comparison I have mysql with a user table with answers from a poll saved as a bitwise. How do I find the user with most or least common answers with the reference bitwise?
+------+---------+--+
| User | Answers |  |
+------+---------+--+
| A    |       1 |  |
| B    |       5 |  |
| C    |      10 |  |
+------+---------+--+

A: Assuming by 'reference bitwise' you mean that you have another value that is a bitmask that you are trying to match against the Answers column, something like this should do it for you.  In this case, I'm using '4' as the reference bitmask and myTable as the name of your table..
SELECT User, BIT_COUNT(Answers & 4) AS MatchedBits FROM myTable ORDER BY MatchedBits DESC

This returns:

+------+-------------+
| User | MatchedBits |
+------+-------------+
| B    |           1 |
| A    |           0 |
| C    |           0 |
+------+-------------+

You can also add a LIMIT 1 clause to get just the top result, but of course that won't tell you if there is more than one top result with the same number of bits matched.


text:
Q: WPF Ribbon ToolTip flickers I have a very strange behavior on my Tooltips that are associated with dropdown items.
I've posted a video because it's easier to see
https://imgur.com/a/RxFvAPP
My XAML looks something like this
 <RibbonGroup x:Name="PageRibbonGroup" Header="{x:Static p:Resources.Page_Ribbon_Group}" LargeImageSource="{svgc:SvgImage Source='pack://application:,,,/Resources/HomeTab/Page/page_group.svg'}">
                        <RibbonComboBox>
                            <RibbonGallery x:Name="PagesListComboboxGallery" SelectedItem="{Binding XPath=.}" MaxColumnCount="1">
                                <RibbonGalleryCategory  x:Name="PagesListComboboxGalleryCategory" ItemsSource="{Binding}"/>
                                <RibbonGallery.ToolTip>
                                    <ToolTip Placement="Bottom" Content="ASDF" ToolTipService.ShowDuration="5000"/>
                                </RibbonGallery.ToolTip>
                            </RibbonGallery>
                        </RibbonComboBox>
 </RibbonGroup>

This happens from what I see on every tooltip that is on an Element that is in a dropdown.
I can't find a reason on why this is happening.
I've also created a repo
https://github.com/SebiCiuca/RibbonToolTipFlicker
For combobox and dropdown button you can reproduce this behavior, but for Button3 the Tooltip works fine.

A: If you're looking for a workaround that bypasses the bug, as I am, you may be able to retarget your project to .NET 5.0. An alternative that keeps using .NET 6.0 is to publish your start-up project as self-contained deployment and configure the project with the RuntimeFrameworkVersion set to 6.0.2.
This is how you can do it from within Visual Studio 2022:

*

*In the menu click Build → Publish Selection.

*Click + New, select Folder in the wizard, click Next and Folder then Next again.

*Choose a folder for the output of the publish process and click Finish.

*At the bottom of the Settings panel for the publish profile, click Show all settings.

*In the dialog select set Deployment mode to Self-contained and click Save button. The Publish profile should look similar the image below.

*Next, you'll need to manually edit the .csproj for. It's easiest to do this with a text editor such as VSCode or Notepad++ but even built-in Windows Notepad should do it.

*Once you have the '.csproj' file open, at the following XML tag beneath the <TargetFramework>net6.0-windows</TargetFramework> tag and save the project:

    <RuntimeFrameworkVersion>6.0.2</RuntimeFrameworkVersion>

*Return to Visual Studio, click Publish and once complete, click the Open folder link.

You can now find and run the .exe file within the publish folder and it should run your application using .NET 6.0.2 instead of the current latest 6.0.3 and the tooltip bug should no longer be present. If you still see the bug and you're not sure if you've retargeted your project correctly, you can arrange to present the value of the System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription which should return the value ".NET 6.0.2" if done correctly.
Note that if you run your project from the usual bin\Release or bin\Debug directory (as would running the project from Visual Studio) it will use whatever the current release is. Only the published application will use the previous version. You'll also need to remember to republish your project whenever you make a code change if you want to test it with the .NET 6.0.2 runtime.
Once .NET 6.0.5 is released and you want to publish your application using the new version, simply reverse step 6 above by remove the RuntimeFrameworkVersion element from the .csproj file.

A: https://github.com/dotnet/wpf/pull/6063/files
Looks like a WPF Bug introduced in version 6.0.3, that should be fixed in .NET 6.0.5
This behavior does not reproduce in .NET 5 or .NET 6.0.2.


text:
Q: OpenGl: which is the best solution? So, my question that what function shoud I use, what is the fastest, or which is the most prevalent solution.
The solution alternatives:
-the vertex array
-polygon by polygon
-or another alternative
An object has triangles, quads and polygons which has more indices. But the vertex array I know can store only triangles, quads, or something like that. But how can I render the polygons? Is it right that I only render polygon by polygon the polygons wich has more indices? (I've heard the glMultiDrawElements, but it has similar data structure if I render poly by poly, isn't it?)
Or there's a good alternative I don't know?

A: You should convert the polygons to triangles and use a vertex buffer object.


text:
Q: Installing new API client library into deployed App Engine app I'm working on an App Engine app that has both a front end (Dart/Polymer) and back end (Endpoints for Python). After developing locally, I'm expecting to do something along the following lines:
Upload the app to App Engine.
Generate a new discovery document for the API by running
$> wget -O discovery.json <project>.appspot.com/_ah/api/discovery/apis/...

Generate the new API client library by running
$> generate.dart files -i . -o .

Install the new client library in the front end lib/ or whatnot.
Upload the app. Modify integration tests to point to the deployed app. Verify tests pass.
Undo changes to integration tests. Reinstall local version of API client library. Continue development.
As you can see, this will become tedious. Anyone have some tips to streamline this process? Am I going about it the wrong way? Maybe I should look at doing more on the deployed server?

A: I worked on this some more and came up with the following general sequence of actions that require fewer steps (download discovery doc only once and deploy only once):

*

*Change the API (working on localhost)

*Use endpointscfg.py with the --hostname parameter to generate a discovery document for dev_appserver ('localhost:8080')

*Generate the client library using discoveryapis_generator

*Rename the client library (myapi_remote.dart)

*Use endpointscfg.py with the --hostname parameter to generate a discovery document for the App Engine runtime (yourproject.appspot.com')

*Generate the client library using discoveryapis_generator

*Rename the client library (myapi_remote.dart)

*Install the both client libraries in the Dart project's lib/ directory

*Symlink myapi.dart to myapi_remote.dart

*Build and Deploy

*Symlink myapi.dart to myapi_local.dart

*Continue development

Now you have both local and remote client libraries at hand and can just change the symlink as desired to access your local or deployed data. Note that the discovery document produced by endpointscfg.py for dev_appserver specifies "https" rather than the correct "http". This can be fixed in the Dart file generated by discoveryapis_generator.
Indeed, this entire workflow can be shortened considerably by simply altering the rootUrl parameter given in the client library's MyApi constructor.
Of course this is all automated in a Python script. I haven't looked for one on Github, etc, but it's pretty basic stuff. I'll post it here if someone asks.


text:
Q: Electron Mocha and Spectron I am using Electron to write a desktop application. I want to use Spectron and Mocha because they seem to be the biggest and most supported things out there for testing electron. I am in Windows 10.
using the boiler plate project here :
https://github.com/florin05/electron-spectron-example
The testbed works using 'npm install' then 'npm test'.
then I cleared out the node_modules folder and did it again, after I only changed electron and spectron to their newest versions. Spectron to 12.0.0 and electron to 10.0.0(per spectron's minor version matching requirement).
Now the test bed gives me the following error
 1) Sample Test
       "before each" hook for "opens a window":
     javascript error: javascript error: Cannot convert undefined or null to object
  (Session info: chrome=85.0.4183.84)
      at Object.getErrorFromResponseBody (node_modules\webdriver\build\utils.js:94:12)
      at WebDriverRequest._request (node_modules\webdriver\build\request.js:133:31)
      at processTicksAndRejections (internal/process/task_queues.js:93:5)
      at async Browser.wrapCommandFn (node_modules\@wdio\utils\build\shim.js:58:29)
      at async Browser.wrapCommandFn (node_modules\@wdio\utils\build\shim.js:58:29)
      at async Object.startApp (test\hooks.js:13:17)
      at async Context.<anonymous> (test\search.js:9:11)

This seems like the simplest possible test of electron and I cannot figure out what I am doing incorrectly. Are there any Electron testing experts out there that would like to tell me why this does not work? I am fairly new to Node and web dev, perhaps I've overlooked something implicit.


text:
Q: How to insert array elements into db only if they do not already exist Here is my db schema:
CREATE TABLE technologies (
    technologyName VARCHAR(50) NOT NULL PRIMARY KEY
);

CREATE TABLE videos (
    videoId             INT          NOT NULL AUTO_INCREMENT PRIMARY KEY,
    title               VARCHAR(300) NOT NULL,
    url                 VARCHAR(300) NOT NULL,
    description         VARCHAR(300) NOT NULL,
    channelName         VARCHAR(300) NOT NULL
);

CREATE TABLE technology_video_map (
    videoId        INT,
    technologyName VARCHAR(50),

    PRIMARY KEY (videoId, technologyName),
    FOREIGN KEY (videoId) REFERENCES videos(videoId),
    FOREIGN KEY (technologyName) REFERENCES technologies(technologyName)
);

I want the user to submit a video:
var input = {
  title: 'Grunt makes your web development better!',
  url: 'https://www.youtube.com/watch?v=TMKj0BxzVgw',
  description: 'If you\'re not using a task runner/build system like Grunt or Gulp...',
  channelName: 'LearnCode.academy',
  technologies: ['Grunt', 'JavaScript']
};

And I want to insert it into the db. Inserting only the video is easy enough for me:
var technologies = input.technologies; // save for later
delete input.technologies;
connection.query('INSERT INTO videos SET ?', input, function (err, result) {
    var videoId = result.insertId;
});

(connection comes from the brilliant node-mysql)
What I am having trouble with, is inserting the technologies into the db. I have identified that the first step is:

*

*Insert elements in input.technologies into the technologies table if they do not already exist.

I can only imagine doing this using a for loop or something which is yucky.
The second step, I think, is:

*Insert a new record into the junction table, technology_video_map from the connection.query callback, as we need the videoId.

Again, I cannot imagine an idiomatic way to do this using SQL. Can someone please guide me?

A: You can use INSERT IGNORE and join your input.technologies array. This will insert records that do not exist and will ignore records that already exist
var query = "INSERT IGNORE INTO technologies (technologyName) VALUES ('" + input.technologies.join("'),('") + "')";

A: You have to check for its existence
if not exists(select technologyName from technoligies
              where technologyName='$technologies')
insert (..)

If you are not using a stored procedure, then fire a query to fetch it. If it fails, then insert it.