text:
Q: No GUI after upgrade to Ubuntu 9.10 (boots to command line) I have just upgraded to Ubuntu 9.10 (network upgrade using the update manager, from 9.04 which had different graphics related problems) and when I try to boot into it all I get a small Ubuntu logo, flickering text and then the tty1 command line with a logon prompt.
startx gives following error:
Fatal server error: no screens found
I traced down a tutorial that said I needed the latest graphics drivers (Gigabyte ATI Radeon 4650 HD installed with 9.10 catalyst drivers) so I did using the 'sh' command and a USB stick (I have a working Windows partition) and it installed fine but did not fix the problem.
Edit:
Thanks to UK and Arjan below I was able to understand the full error message of start x:
Parse error on lone 2 of /etc/X11/xorg.conf
'nameserver' is not a valid keyword in this section
Fatal server error: no screens found
This has nothing to do with a graphical error (sorry if I misled anyone) but the xorg.conf file has 3 lines in it and lines 2-3 have an entry 'nameserver'. Using the nano command I commented out (using a # before the entries) the nameservers and can now boot Ubuntu.
Thanks to everyone for their help.

A: From Ubuntu forums , You may need to reconfigure your xconf by using the following command,
sudo dpkg-reconfigure -phigh xserver-xorg

PS: Added additional Solutions
1) try to fix xserver in the recovery options.
2) check your xorg.conf for device section
Section "Device"
    Identifier "Configured Video Device"
    Driver "radeon" ## or make it "ati"
EndSection

A: Finally found the solution!
H/W: Dell Studio (1555) running Vista Home Premium 64bit; 4GB RAM; 250GB SATA (circa June 2009 B.FUTW7 [B.FUTW7 implies "Before Free Upgrade to Windows 7" LOL!] )
Booted USB version of Ubuntu 9.10 (x64) - worked perfectly.   From there I installed to the HDD (last step ADVANCED I made sure the boot info was placed on the partition and to not modify the main MBR).  After the installed it, I used EasyBCD 1.7 to get the boot to work - learning curve but worked fine.
But when I booted it went DIRECTLY to the console.  I finally found THIS site.
First, I tried to start "xstart" and it returned "Fatal server error: no screens found" - a big clue!
So then I followed UK's solution:

sudo dpkg-reconfigure -phigh xserver-xorg

and then vi to change the xconf.org:
Section "Device"
     Identifier "Configured Video Device"
     Driver "radeon" ## or make it "ati"
 EndSection

Driver listed was "fglrx".  https://help.ubuntu.com/community/BinaryDriverHowto/ATI
Funny, BEFORE the actual install, I downloaded the "ATI/AMD proprietary FGLRX graphic driver" - then I installed Ubuntu to the HDD.  So I guess it used THAT as the driver but it failed to work.
I chose to rename the driver to "radeon" per the above and now Ubuntu loaded FINE!
Now back into the GUI, it said for that driver "this driver is not activated".  Implies, perhaps, that my "attempt" to install during the "Test phase" remembered my CHOICE but didn't actually DOWNLOAD FOR THE INSTALL. So the new install used the "fglrx" driver in the xorg.conf but had not downloaded the drivers.
For a lark, I just downloaded the drivers using the "Restricted drivers" window ... once complete it changed the xorg.conf back to "fglrx" and I had to restart.  NOW it worked fine and booted in GUI mode.
At any rate, a few hours from start (of d/l Ubuntu and installing it) to finish and now Vista and Ubuntu are working perfectly together.
Cheers all!
jeff

A: Does it go straight to a text login prompt, or does it flicker, trying to go graphical, and then fail back to a prompt?  If there's no flicker, you probably don't have an X server installed.  Install xserver-xorg and gdm.

A: If you have problems to start X, try the following:
if the command startx doesn't work, you have to reconfigure xorg.conf.
You can do this by renaming the xorg.conf.failsafe file to xorg.conf.
It is recommended to backup your old xorg.conf file before replacing it.
Rename the original xorg.conf file by the following command:
$ mv -i xorg.conf xorg.conf.failsafe2
the -i option makes the mv command to promt when an exising file will be overwritten.
Next type the following command:
$ mv -i xorg.conf.failsafe xorg.conf
now you can try to start X by the following command:
$ startx
It works with me, I hope it also works for you.
Greets.

A: I have been having this exact same problems on my laptop since 9.10 was released and I tried to freshly install it.
I was aiming to keep XP x64 on a separate partion, and load Ubuntu onto another.
No command solutions worked, but this did work:
1) use a partition manager inside windows to create a NFTS partition (I used Partition Wizard - free and simple)
2) use Wubi from inside windows to install Ubuntu 9.10 onto the partition
3) boot and enjoy!*
*note: I had to reinstall the Windows boot loader from the CD because it had been over written by GRUB at previous Ubuntu install attempts, so if you're in the same boat, keep your Windows XP cd handy. I prefer to Windows boot loader to GRUB anyways.

A: Type the below command
X -configure
After the above process completes, run file system consistency check by typing below command
fsck
After the file system check is completed, Reboot you linux box by typing
init 6
You will get GUI login, it worked for me.


text:
Q: Restricted domain of $\sin (2x)$ The "restricted" domain of $\sin x$ is $[-\pi/2, \pi/2]$.
So what should be the domain of $\sin (2x)$; My say is that $2x$ belongs to $[-\pi/2, \pi/2]$ as I understand that the argument inside the function or the "input" values should remain the same irrespective of the input values being $2x$ or $3x$. All the input values should have the same domain as that of $\sin x$
$2x$ belongs to $[-\pi/2, \pi/2]$
$x$ belongs to $[-\pi/4,\pi/4]$
What I did in the last step is divide the domain by $2$ so that I get corresponding values of $x$ which satisfy the domain.
I can feel that somethings fundamentally wrong with my reasoning. Please correct me.
Edit 1- I know that I might be a bit annoying right now, but just to be super sure, I need to again know weather the argument in the pink box is right.

In the above question we are supposed to find the intervals in which the function $f(x) = \sin 2x$ in which the function is strictly increasing.
M1 stands for method 1 which you might as well ignore. I am concerned about method 2.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sorting files by "line content" frequency - print duplicates Imagine there is a file -
a
b
b
b
b
c
c
d
d
d

I want the output to be sorted based on frequency (I want the duplicate lines to be printed as well) as -
b
b
b
b
d
d
d
c
c
a

A: The following will do what you're after... though there are many other ways to achieve this... for example with gawk, as per Kamil's answer.

*

*The first sort will order the data by line data

*uniq -c will count the number of matching occurrences (they must be neighbours)

*sort -nr will sort by the number of occurrences, in reverse order

*The while loop iterates over each line

*

*read n l will ingest the count into n, and the line data into l

*The for loop will iterate n times

*echo "${l}" outputs the line data

(
    sort \
        | uniq -c \
        | sort -nr \
        | while read n l; do \
            for i in $(seq ${n}); do \
                echo "${l}"; \
            done; \
        done
) <<"EOF"
a
b
b
b
b
c
c
d
d
d
EOF

A: With GNU Awk:
gawk '
   { arr[$0]++ }
   END {
        PROCINFO["sorted_in"] = "@val_num_desc"
        for (ln in arr) for (i = 1; i <= arr[ln]; i++) print ln
       }
   '

The trick is to use an array and @val_num_desc. Every encountered line becomes an index, the associated value is increased each time the line appears. At the end we scan the entire array in a specific order:

"@val_num_desc"
  […] the element values, treated as numbers, are ordered from high to low.

source
So the outer (first) for is responsible for retrieving lines and their frequencies in the desired order; the inner (second) for is just to print the currently picked line the right number of times.
Note:

*

*Every character matters. A line and the same line with an extra trailing space are different.


text:
Q: Javascript playing sound results in "Error calling method on NPObject" I am trying to play a sound in my javascript file
document.getElementById("sound").innerHTML = "<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" id=\"beep\" loop=\"false\" />";
thissound=document.getElementById('beep');
thissound.Play();

but the thissound.Play() line gives me the error "Error calling method on NPObject"
Furthermore, if I add an alert("Played sound!") line right before the thissound.Play() line, there is no error and it works fine!
What is the problem with this? The sound does play, but then the program freezes.

A: This may be not pretty. If it is hard to detect when the sound is fully loaded, you can keep trying playing the sound until it works.
var error = true;

while(error) {
    try {
        error = false;
        thissound.play();
    }
    catch (e) {
        error = true;
    }
}


text:
Q: Telegram.Bot: Mesage.From - есть, а где Mesage.To? Уважаемые господа,
собственно, почти весь вопрос поместился в заголовок.
Не могу понять объектную модель сообщения в библиотеке Telegram.Bot.
В сообщениии есть поле From, но я не вижу поля To. В то же время, логически когда я пишу сообщение - я ведь его кому то адресую? Откуда можно получить эту инфу?
Вот как выглядит это в коде:


text:
Q: Sharing error: mount error(2): No such file or directory Refer to the mount.cifs(8) manual page (e.g. man mount.cifs) I need to share some folder via typical adsl home modem by this instruction:

so i tried this codes :

so@so-notebook:~$ sudo aptitude install cifs-utils -y
The following NEW packages will be installed:
  cifs-utils
0 packages upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 71.5 kB of archives. After unpacking 231 kB will be used.
Get: 1 http://archive.ubuntu.com/ubuntu bionic/main amd64 cifs-utils amd64 2:6.8-1 [71.5 kB]
Fetched 71.5 kB in 2s (44.0 kB/s)
Selecting previously unselected package cifs-utils.
(Reading database ... 333471 files and directories currently installed.)
Preparing to unpack .../cifs-utils_2%3a6.8-1_amd64.deb ...
Unpacking cifs-utils (2:6.8-1) ...
Setting up cifs-utils (2:6.8-1) ...
update-alternatives: using /usr/lib/x86_64-linux-gnu/cifs-utils/idmapwb.so to provide /etc/cifs-utils/idmap-plugin (idmap-plugin) in auto mode
Processing triggers for man-db (2.8.3-2ubuntu0.1) ...

so inside my Vmware virtual machine installed win8 and tried to share one folder with New_folder name like this :
and get this error:
so@so-notebook:~/Desktop/trash$ sudo mount.cifs -o username=Guest //172.16.144.130//WIN-KBJV8JRF8FS/New_folder /home/so/Desktop/trash/ip_shar_test
Password for Guest@//172.16.144.130//WIN-KBJV8JRF8FS/New_folder:
mount error(2): No such file or directory
Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)
so@so-notebook:~/Desktop/trash$ sudo mount.cifs -o username=Guest //172.16.144.130/Guest /home/so/Desktop/trash/ip_shar_test
Password for Guest@//172.16.144.130/Guest:
mount error(2): No such file or directory
Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)
so@so-notebook:~/Desktop/trash$ sudo mount.cifs -o username=Guest //172.16.144.130/Guest /home/so/Desktop/trash/ip_shar_test
Password for Guest@//172.16.144.130/Guest:
mount error(2): No such file or directory
Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)
so@so-notebook:~/Desktop/trash$ sudo mount.cifs -o username=Guest //172.16.144.130/Guest /WIN-KBJV8JRF8FS/New_folder
Couldn't chdir to /WIN-KBJV8JRF8FS/New_folder: No such file or directory
so@so-notebook:~/Desktop/trash$ sudo mount.cifs -o username=Guest //172.16.144.130/Guest /home/so/Desktop/trash/ip_shar_test
Password for Guest@//172.16.144.130/Guest:
mount error(2): No such file or directory
Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)
so@so-notebook:~/Desktop/trash$ sudo mount.cifs -o username=Guest //172.16.144.130//WIN-KBJV8JRF8FS/New_folder /home/so/Desktop/trash/ip_shar_test
Password for Guest@//172.16.144.130//WIN-KBJV8JRF8FS/New_folder:
mount error(2): No such file or directory
Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)
so@so-notebook:~/Desktop/trash$ sudo mount.cifs -o username=Guest //172.16.144.130/Guest/New* /home/so/Desktop/trash/ip_shar_test
Password for Guest@//172.16.144.130/Guest/New*:
mount error(2): No such file or directory
Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)
so@so-notebook:~/Desktop/trash$ sudo mount.cifs -o username=Guest //172.16.144.130/Guest /home/so/Desktop/trash/ip_shar_test
Password for Guest@//172.16.144.130/Guest:
mount error(2): No such file or directory
Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)

SO what do you think?
Thanks for your attention.


text:
Q: In an AWS CloudFormation template, how can I tag an EC2 instance with it's own Id without getting circular reference errors? I've specified an EC2 instance in my CloudFormation template, and I want to tag it with it's own InstanceId, like so:
"Resources": {
    "myInstance": {
        ...
        "Tags": [
            { "Key": "instance.id", "Value": { "Ref": "myInstance" } },
            ...
        ]
    }
}

But trying to create a stack from this template generates a AmazonCloudFormationException: "Circular dependency between resources: [myInstance]"
Running instances and tagging them using the EC2 API is very straightforward:
//this is C#, but that's not significant

var instance = ec2Client.RunInstances(...) ...;
var id = instance.InstanceId;
ec2Client.CreateTags(new CreateTagRequest
{
    Resources = { id },
    Tags = { new Tag { Key = "instance.id", Value = id } }
});

This approach arises naturally from the fact that instance tags cannot be created as part of the RunInstances operation, so all tags, not just the self-identifier, must be applied in a subsequent API operation.
So... can I accomplish the same thing using CloudFormation? Thanks very much!
(cross-posted to the AWS Forums)

A: You can always create a startup script which will update the tag of the instance after the startup. You can use the following (AWS CLI):
aws ec2 create-tags --resources `wget -q -O - http://169.254.169.254/latest/meta-data/instance-id` --tags Key=id,Value=`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id`

However, if you only want to use the instance id inside your application, you can use wget -q -O - http://169.254.169.254/latest/meta-data/instance-id to fetch the instance id.

A: I don't think you can. CloudFormation only lets you tag a resource at creation time, and the value of the tag you want doesn't exist until the resource is created.
But I don't think this has to be a problem. The two use cases I can think of for tags are looking at an instance and seeing the tag values, or finding instances with certain tag values. You can see or find by instance-id without having a tag containing it.


text:
Q: Can a Windows CRITICAL_SECTION object be configured to deny recursive access? By default, a CRITICAL_SECTION object is recursive. Can this behaviour be configured like a pthread mutex to enable or disable recursive thread access?
To clarify in response to the comments: I am referring specifically to a Windows CRITICAL_SECTION object, not a Windows mutex.

A: No, it cannot. Documented APIs do not mention this in any way. Windows critical sections always accept recursive access.

A: A Critical Section always allows recursion within a thread.  So does a Mutex.  That is by design and cannot be changed.
A Semaphore, on the other hand, can prevent recursion within a thread.  See MSDN documentation for more details.


text:
Q: NSFileHandleReadCompletionNotification not posting I'm having an issue with NSFileHandleReadCompletionNotification not posting. I'm piping the results of one NSTask into another one. For whatever reason my getData method just will not be called. Any ideas? Both tasks are working properly because I'm getting the expected files written to my hard drive. Just no notification.
- (void) encodeVideo:(NSString*)path
{
    NSString* ffmpegPath = [[NSBundle mainBundle] pathForResource:@"ffmpeg" ofType:@""];
    NSString* presetFile = [[NSBundle mainBundle] pathForResource:@"128" ofType:@"ffpreset"];

    NSTask* encodeTask = [[NSTask alloc] init];

    NSMutableArray* arguments = [[NSMutableArray alloc] init];
    [arguments addObject:@"-y"];
    [arguments addObject:@"-i"];
    [arguments addObject:path];
    [arguments addObject:@"-f"];
    [arguments addObject:@"mpegts"];
    [arguments addObject:@"-ac"];
    [arguments addObject:@"2"];
    [arguments addObject:@"-fpre"];
    [arguments addObject:presetFile];
    [arguments addObject:@"-s"];
    [arguments addObject:@"320x240"];
    [arguments addObject:@"-aspect"];
    [arguments addObject:@"320:240"];
    [arguments addObject:@"-async"];
    [arguments addObject:@"2"];
    [arguments addObject:@"-"];

    [encodeTask setLaunchPath: ffmpegPath];
    [encodeTask setArguments: arguments];
    [encodeTask setStandardOutput:[NSPipe pipe]];

    NSMutableArray* segmentArguments = [[NSMutableArray alloc] init];
    [segmentArguments addObject:@"-t"];
    [segmentArguments addObject:@"10"];
    [segmentArguments addObject:@"-f"];
    [segmentArguments addObject:@"/Users/Morgan/Desktop/LiveStreamServer/video"];
    [segmentArguments addObject:@"-S"];
    [segmentArguments addObject:@"1"];

    NSString* segmenterPath = [[NSBundle mainBundle] pathForResource:@"mediastreamsegmenter" ofType:@""];
    NSLog(@"%@", segmenterPath);
    NSTask* segmentTask = [[NSTask alloc] init];

    [segmentTask setLaunchPath: segmenterPath];
    [segmentTask setArguments: segmentArguments];

    [segmentTask setStandardInput:[encodeTask standardOutput]];
    [segmentTask setStandardOutput:[NSPipe pipe]];
    [segmentTask setStandardError:[NSPipe pipe]];

    NSFileHandle *file = [[segmentTask standardOutput] fileHandleForReading];
    [file readInBackgroundAndNotify];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getData:) name:NSFileHandleReadCompletionNotification object:file];

    [segmentTask launch];
    [encodeTask launch];

    [arguments release];
    [segmentArguments release];
}

- (void) getData: (NSNotification *)aNotification
{
    NSData *data = [[aNotification userInfo] objectForKey:@"NSFileHandleNotificationDataItem"];
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"%@", string);
    [[aNotification object] readInBackgroundAndNotify];
}

A: Needed to read the stdError in the background as well. Had it outputting into a pipe, but wasn't reading it so the buffer got filled up.


text:
Q: Python PostgreSQL using copy_from to COPY list of objects to table I'm using Python 2.7 and psycopg2 to connect to my DB server ( PostgreSQL 9.3 ) and I a list of objects of ( Product Class ) holds the items which i want to insert
products_list = []
products_list.append(product1)
products_list.append(product2)

And I want to use copy_from to insert this products list to the product table. I tried some tutorials and i had a problem with converting the products list to CSV format because the values contain single quote, new lines, tabs and double quotes. For example ( Product Description ) :
<div class="product_desc">
    Details :
    Product's Name : name
</div>

The escaping corrupted the HTML code by adding single quote before any single quote and it, So i need to use a save way to convert the list into CSV to COPY it? OR using any other way to insert the list without converting it to CSV format??

A: I figured it out, First of all i created a function to convert my object to csv row
import csv

@staticmethod
def adding_product_to_csv(item, out):
writer = csv.writer(out, quoting=csv.QUOTE_MINIMAL,quotechar='"',delimiter=',',lineterminator="\r\n")
writer.writerow([item.name,item.description])

Then in my code i created a csv file using Python IO to store the data in it to COPY it and stored every object in the csv file using my previous function:
file_name = "/tmp/file.csv"
myfile = open(file_name, 'a')
for item in object_items:
    adding_product_to_csv(item, myfile)

Now I created the CSV file and it's ready to be copied using copy_from which exists in psycopg2 :
# For some reason it needs to be closed before copying it to the table
csv_file.close()
cursor.copy_expert("COPY products(name, description) from stdin with delimiter as ',' csv QUOTE '\"' ESCAPE '\"' NULL 'null' ",open(file_name))
conn.commit()
# Clearing the file
open(file_name, 'w').close()

And it's working now.


text:
Q: iPhoneX inputView wrong heigh I have a simple ViewController
The problem is the code
print("HEIGHT (keyboardSize.height)") prints Height = 69
Why ?
I have set input view frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 30)
So I expect the heigh would be 30 but it is not.
The problem appears only on iPhoneX.
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.inputView = SoftView()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        addCustomKeyboardNotification()
    }

    private func addCustomKeyboardNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(customKeyboardWillAppearNotification), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(customKeyboardWillHideNotification), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    private func removeCustomKeyboardNotification() {
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    @objc
    private func customKeyboardWillAppearNotification(notification: Notification) {
        guard let keyboardSize = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect,
              let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else {
            return
        }

        print("HEIGHT \(keyboardSize.height)")

        UIView.animate(withDuration: duration) {
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
        }
    }

    @objc
    private func customKeyboardWillHideNotification(notification: Notification) {
        guard let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else {
            return
        }

        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }

}

class SoftView: UIView {

    init() {
        super.init(frame: .zero)
        self.refresh()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func refresh() {
        self.backgroundColor = .green
        self.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 30)
        self.layoutIfNeeded()
    }

}


text:
Q: "document.createElement" Performance I wanted to create numerous rows in a popup to show my data using for loop, I was using text string to create and append the div , However I found document.createElement is performant and used that which increased the performance 20%, but since I populate 1000s of rows the time taken to create element by document.createElement is very high. Is there any way to improve performance by creating element once and resuse it with numerous instance, any advice on this would be appreciated

A: Once you have created an element, you can use Element.cloneNode() to copy it. It takes same time as document.createElement(), but has one advantage: if you have set several attributes or childNodes/innerHTML on the element, you can copy those too with one call: Element.cloneNode(true).
Most time takes the DOM-insertion of newly created Elements, and therefor insertion of every single new element is slow. A faster way is to create a documentFragment, append all new elements to that in the structure you need and then add the complete fragment to the DOM.


text:
Q: Урон в Unity2D мечом Я новичёк в Unity и в целом в c#, хотелсь бы узнать, как можно реализовать урон с помощью меча в 2д игре, смотрел гайд на ютубе, там показан меч перса как отдельный предмет, то есть, когда он касается врага, то урон отнимается, это я понял, только я скачал спрайты, где меч не отделен от персонажа, можно ли это как-то реализовать? Также, пытался для начал сделать через OnCollisionEnter2D, но когда проигрывается анимация, то не регестриурется прикосновения меча к врагу.

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


text:
Q: Multiprocessing IndexError out of range I'm having a issue with multiprocessing.pool on the following piece of code:
from multiprocessing import cpu_count
from multiprocessing.pool import Pool

if __name__ == '__main__':

    files = compile_paths()
    pool = Pool(processes=cpu_count())
    r = pool.map(compile_,files,chunksize=len(files))

That gives out:
 Traceback (most recent call last):

  File "<ipython-input-39-06f23d3cf8fa>", line 1, in <module>
    runfile('C:/Users/rafael/scripts/ETL/read.py', wdir='C:/Users/rafael/scripts/ETL')

  File "C:\Users\rafael\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\rafael\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/rafael/scripts/ETL/read.py", line 185, in <module>
    r = pool.map(compile_,files,chunksize=len(files))

  File "C:\Users\rafael\Anaconda3\lib\multiprocessing\pool.py", line 268, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()

  File "C:\Users\rafael\Anaconda3\lib\multiprocessing\pool.py", line 657, in get
    raise self._value
IndexError: list index out of range

This compile_ is a function that reads the paths from files and saves then in a folder. The problem is that I put a print("Howdy") at the start of the function and it's never printed. Moreover, I made smaller files just to test it out and it never leaves the pool.map() function.


text:
Q: Converting from framework to core I'm converting an existing web app from net framework to net core - but having a few troubles.

*

*How to replace usage of WebImage

*How to get CurrentCulture - used for Localization
Thanks in advance
/Søren

A: If I understand you correctly, you only need a good DI framework. Then you can just use an existing one that has an integration with MVC. (ASP.NET Core has a built in DI, so it's easier to start with, but this does not mean you can't use DI in previous versions).
I would suggest that you use SimpleInjector. This is a great DI-container that is updated and maintained a lot and has an MVC integration in a separate Nuget package. It's also easy to use and the creator answers questions here on SO. You just need to install SimpleInjector and SimpleInjector.MVC and you can begin injecting in the constructor of your controllers.
P.S. If you need to use existing 3d party libraries in ASP.NET Core you might have troubles with this. It's not possible out of the box unless authors updated them and uploaded to Nuget. See this question e.g.

A: Going to keep using MVC and combine it with framework Autofac


text:
Q: How to disable IBM Websphere Commerce Developer Feature Pack 4.0.0.0 While disabling IBM web commerce,I am always getting bellow error message.
"

C:\WCDE_ENT70\bin>disableFeature.bat -DfeatureName=foundation
  Disabling components
The system cannot find the path specified.
disableFeature.bat FAILED. The log file will contain more details
  about the failure. See C:\WCDE_E~3\logs\d isableFeature.log
  Troubleshooting help is available in the WebSphere Commerce
  Information Center
  http://publib.boulder.ibm.com/infocenter/wchelp/v7r0m0/topic/com.ibm.commerce.in
  stall.doc/refs/rigtrbshootmain.htm

"
Log file was not generated.
May I know how to disable the IBM Websphere Commerce Developer Feature Pack 4.0.0.0.?
I noticed that I could see same error message if I run versionInfo.bat as well.
Should I need to update any environmental variables?
Please suggest.

A: Opening a support ticket is the quickest way to get help on such errors.
But, if some one is seeing the mentioned error and are up for some investigation (aren't we all :-)) :
Key error that catches my eye is this one:

"The system cannot find the path specified"

Since you don't see the log file, I guess utility could not get far enough to even create the log file - likely because one or more of the paths it expects does not exist.
I would check C:\WCDE_ENT70\bin\setenv.bat file for the various paths set there. One or more of those paths may be the issue.
If paths exists, other thing I would check is : Windows uses the "8.3" short file names, so when looking for folders check for their short names and collisions on those names. Since we expect Windows to make OP's path as C:\IBM\WCDE_E~1, removing any other entries that has the same first six characters is worth a shot.
Else - PMR :-)

A: I would open a ticket with IBM Software Support.
-- Long Answer
Seems like a bigger issue if logs are not being generated correctly hence the ticket with IBM Software Support.


text:
Q: Use custom font upon language selection. I have a language switcher for a website I'm building and it seems to work as expected.
However, I'm trying to use a custom font when the user selects a specific language.
For example; when the user selects French – I want the font to switch to "Ubuntu title" font.
The other two languages (English and Spanish) I want them to use the default system font.
The font is stored locally(for now).
Here's the link to the font: http://www.cufonfonts.com/en/font/448/ubuntu-titling
Here's what I've got so far:

$('[lang="fr"]').hide();
    $('[lang="sp"]').hide();
    //retrieve value from localstorage
    let savedLang = localStorage.getItem('lang')
    //we check if the value is present
    if(savedLang){
      let element = document.querySelector(`option[value='${savedLang}']`);
     element.selected = true
      selectText(savedLang);
    }

    $('#lang-switch').change(function () {
      var lang = $(this).val();
      localStorage.setItem('lang', lang);
      selectText(lang);
    })

    function selectText(lang){
      switch (lang) {
      case 'en':
        $('[lang]').hide();
        $('[lang="en"]').show();
        break;
      case 'fr':
        $('[lang]').hide();
        $('[lang="fr"]').show();
        break;
      case 'sp':
        $('[lang]').hide();
        $('[lang="sp"]').show();
        break;
      default:
        $('[lang]').hide();
        $('[lang="en"]').show();
        }
    }
[lang="fr"],[lang="sp"]{display:none;}
@font-face {
font-family: 'UbuntuTitling-Bold';
font-style: normal;
font-weight: normal;
src: local('UbuntuTitling-Bold'), url('UbuntuTitling-Bold.woff') format('woff');
}

Change language

    <select id="lang-switch">
    <option value="en">English</option>
    <option value="fr">French</option>
    <option value="sp">Spanish</option>
    </select>

Hello!

Bojour!

Hola!

A: Wouldn't [lang="fr"] selector in css to overwrite the font property be sufficient?
[lang="fr"],[lang="sp"]{display:none;}
@font-face {
font-family: 'UbuntuTitling-Bold';
font-style: normal;
font-weight: normal;
src: local('UbuntuTitling-Bold'), url('UbuntuTitling-Bold.woff') format('woff');
}

[lang="fr"] {
    font-family:'UbuntuTitling-Bold';
}


text:
Q: basis for a subpace topology
Qurstion:
Show that if $\mathbf{B}$ is a basis for a topology on X then the collection
$\mathbf{B}_{Y}=\left \{ B\cap Y:B \in \mathbf{B} \right \}$ is a basis for the subspace topology on Y.

$\mathbf{B}$ is a basis for a topology on X means that X is non-empty an satisfies the definition for what it means to be a basis for a topology.
Any hints is appreciated.
Thanks in advance.

A: So we know that $B$ is a basis for the topology on $X$. To show that $B \cap Y$ is a basis for $Y$, we need to show that every open set $U \subset Y$ can be written as a union of sets of the form $B \cap Y$.
Let $U$ be an open set contained in $Y$. Then , because $Y$ is under the subspace topology of $X$ (I'm assuming this), $U$ is also an open set in $X$. Because $B$ is a basis for $X$, $U$ can be written as a union of sets from $B$, i.e.$$U = \bigcup_{\alpha \in A} B_\alpha$$ where $A$ is some indexing set and $B_\alpha \in B$ for every $\alpha$.
Now, just take the intersection with $Y$:
$$
U \cap Y  = U = \bigg(\bigcup_{\alpha \in A} B_\alpha\bigg) \cap Y = \bigg(\bigcup_{\alpha \in A} (B_\alpha \cap Y)\bigg)
$$
That is, $U$ has been written as a union of elements of the form $B_\alpha \cap Y$, where $B_\alpha \in B$. Hence, because $U$ was an arbitrary open set, $B \cap Y$ forms a basis for the subspace topology on $Y$.


text:
Q: How to avoid duplicating function call in the IF check and return statement if the condition evaluates to true? I have a function process. If attempts to retrieve one of name, address, phone from the input data (in that order) using their own functions which either return the appropriate value or return ''. If all return '' then return the data as it is.
Following is the code, is there a better way to avoid duplicating function invocations in both if check and return?
def process(data):
  if get_name(data):
    return get_name(data)
  elif get_address(data):
    return get_address(data)
  elif get_phone(data):
    return get_phone(data)
  return data

A: As per your code logic, you can write it like this. The or sequence will return the first positive data, in other words the data that is truthy.
def process(data):
    name = get_name(data)
    address = get_address(data)
    phone = get_phone(data):
    return name or address or phone or data

A: You can use walrus operator := if you use python 3.8+
def process(data):
  if name:=get_name(data):
    return name
  elif address := get_address(data):
    return address
  elif phone := get_phone(data):
    return phone
  return data


text:
Q: Angular jS Multiple Checkbox dropdown filter I have a Multiple Checkbox Dropdown. I want to make it as a Filter.
So, That if I check one or more boxes it should display data in Table accordingly.
How can I map this Multiple checkbox dropdown with a Table.
Kindly share an example.
Thanks In advance

A: You can use $watch in angularjs like
$scope.$watch('chkFilterData', function () {
        filterDataToTable();
    });

where chkFilterData is the data for Multiple Checkbox Dropdown


text:
Q: Instantiate 2D Array of objects using multiple classes I've hit a wall with my assignment.
I've created a 2D array of objects that I need to instantiate using various classes.
There's a whole bunch of other requirements, but my main concern (at the moment) is I can't figure out why I'm getting an array of ' c ' instead of ' . '
Here is a section of my code, with Driver class, Item class, Dot class, and Array class.
Any help would be much appreciated.
    public class Driver
    {

      public static void main(String[] args)
      {
      Driver a = new Array();
      ((Array) a).runArray();
      }
   }

    public abstract class Item extends Driver
    {

     private char component;

     public Item (char c)
     {
       component = 'c';
     }

    public char display()
   {
     return component;
   }

  //create a new array of objects.
  Item[][] array = new Item [10][10];

  }

 public class Dot extends Item
 {

   public Dot ()
   {
     super('.');
   }

 import java.util.*;

 public class Array extends Item
 {

   Array()
  {
    super(c);
  }

  Random randGen = new Random();
  private int CoordX = randGen.nextInt(3);
  private int CoordY = randGen.nextInt(3);

    public void runArray()
    {
        setArray();
        displayArray();
    }

    private void setArray()
    {
        for (int row = 0; row < array.length; row++)
            for (int col = 0; col < array[row].length; col++)
                    array[row][col] = new Dot();
    }

    private void displayArray()
    {
        for (int row = 0; row < array.length; row++){
            for (int col = 0; col < array[row].length; col++){
                System.out.print(array [row][col].display()+"\t");
            }
            System.out.println("\n");
        }
    }

A: Because no matter how you call the constructor of Item it will always be char c
public Item (char c)
     {
       component = 'c';
     }

change it to
public Item (char c)
     {
       component = c;
     }


text:
Q: Owlcarousel 2 less then 2 items resize I'm using Owlcarousel 2 (ngx-owl-carousel-o) and work good till i have 4/5 box image, but if i receive only one item or two the box with the image come too big, how i can fix this problem?
attach the image where up you can see the box image as single item, too big,
and below you can see with 5 items the size it's ok.
example http://betoffice.it
click in the button ALL under search
My Scss file
.content-carousel
{
        max-width: 85vw !important;
        margin: 0 auto;
        padding: 0 0 1.5rem;

        &.category-na {

            .owl-carousel .owl-item {
                width: 100% !important;
            }
        }

        .category-title {
            display: flex;
            justify-content: space-between;
            align-items: center;

            h2 {
                padding-left: 10px;
                text-transform: uppercase;
                font-size: 16px;
            }

            a{
                margin-right: 10px;
            }
        }

        .single-item {
            height: 100%;
            display: flex;
            flex-direction: column;
            border: 1px solid #e4e4e4;
            border-radius: 3px;

            .box-img {
                position: relative;

                &::after {
                    content:'';
                    position: absolute;
                    @include bg-icon('play', center, contain, 'png');
                    width: 47px;
                    height: 47px;
                    transition: opacity .8s ease-in-out;
                    opacity: 0;
                    z-index: 10;
                    left: 0;
                    right: 0;
                    top: 0;
                    bottom: 0;
                    margin: auto;
                }

                &::before {
                    content:'';
                    position: absolute;
                    background-color: rgba(1,20,48,.5);
                    z-index: 9;
                    opacity: 0;
                    transition: opacity .7s ease-in-out;
                    width: 100%;
                    height: 100%;
                    top: 0;
                    bottom: 0;
                    left: 0;
                    right: 0;
                }

                &:hover {

                    &::before {
                        opacity: 1;
                        border-top-right-radius: 3px;
                        border-top-left-radius: 3px;
                    }

                    &::after {
                        opacity: 1;
                    }

                    .date-start {
                        opacity: 0;
                    }
                }

                img {
                    border-top-right-radius: 3px;
                    border-top-left-radius: 3px;
                }
            }

            .box-meeting-info {
                display: flex;
                flex-direction: column;
                flex-grow: 1;

                p{
                    color: #1a1a1a;

                    &:hover, &:focus {
                        color: #1a1a1a;
                    }
                }
            }

        }

        .owl-carousel {

            .owl-item {
                padding: 0 10px;
            }
        }
    }

    @include media-breakpoint-up(xxl){

        .content-carousel {
            padding: 0 3rem 1.5rem;
        }
    }

owl-carousel-o {

    .single-item {
        background-color: #fff;
        border: 1px solid #ccc;

        .box-meeting-info {
            position: relative;
            padding: 1em;
        }

        &:hover {
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
    }

    .owl-carousel {

        .content-link-video {
            text-decoration: none;
        }

        .owl-stage {
            display: flex;
            padding-bottom: 15px;
        }
    }

    .owl-theme .owl-nav {
        position: absolute;
        top: 30%;
        width: 100%;
        display: none;

        .owl-prev, .owl-next {
            border: 1px solid #ccc;
            background-color: #f0f0f0;
            display: flex;
            justify-content: center;
            align-items: center;
            width: 40px;
            height: 40px;
            border-radius: 1px;

            &:hover {
                background-color: #e0dede;
            }

            &::before {
                content:'';
                height: 12px;
                width: 26px;
                opacity: 0.5;
            }
        }

        .owl-prev {
            left: -50px;
            position: absolute;

            &::before {
                @include bg-icon('arrow-left', center, contain, 'png');
            }
        }

        .owl-next {
            right: -50px;
            position: absolute;

            &::before{
                @include bg-icon('arrow-right', center, contain, 'png');
            }
        }
    }

    @include media-breakpoint-up(xl) {

        .owl-theme .owl-nav {
            display: block;
        }
    }
}

Component.html
    component.html

Meetings

        <owl-carousel-o [options]="customOptions">
            <ng-container *ngFor="let item of uniqueMeetings; let i = index">
                <ng-template carouselSlide [id]="i">

{{item._source.session_startDate | date:'dd MMM yyyy'}} - {{item._source.session_startDate | date:'H:mm:ss'}}

{{item._source.session_name}}

                </ng-template>
            </ng-container>
        </owl-carousel-o>


text:
Q: Laravel reuse form with variable that exists sometimes I have a form which contains separate date and time fields, when submitted my controller actually joins the two values to store into my datetime field in my database.
Form:

has('date')) has-error @endif">
    {!! Form::label('date', 'Date') !!}
    {!! Form::date('date', null, ['class' => 'form-control']) !!}
    {{ $errors->first('date') }}

has('time')) has-error @endif">
    {!! Form::label('time', 'Time') !!}
    {!! Form::time('time', null, ['class' => 'form-control']) !!}
    {{ $errors->first('time') }}

This works fine when creating a new record, but I want to reuse the form on my edit pages (using the same partial), I have to edit the values in the inputs like so:

has('date')) has-error @endif">
    {!! Form::label('date', 'Date') !!}
    {!! Form::date('date', $booking->reservation_datetime->format('Y-m-d'), ['class' => 'form-control']) !!}
    {{ $errors->first('date') }}

has('time')) has-error @endif">
    {!! Form::label('time', 'Time') !!}
    {!! Form::time('time', $booking->reservation_datetime->format('G:i'), ['class' => 'form-control']) !!}
    {{ $errors->first('time') }}

But this will consequently will cause issues on the create page.
How can I use the same form but only load values on edit pages?

A: You can use an intermediary variable:
<?php $date = isset($booking->reservation_datetime) ? $booking->reservation_datetime->format('Y-m-d') : null ?>

has('date')) has-error @endif">
    {!! Form::label('date', 'Date') !!}
    {!! Form::date('date', $date, ['class' => 'form-control']) !!}
    {{ $errors->first('date') }}

<?php $time = isset($booking->reservation_datetime) ? $booking->reservation_datetime->format('G:i') : null ?>

has('time')) has-error @endif">
    {!! Form::label('time', 'Time') !!}
    {!! Form::time('time', $time, ['class' => 'form-control']) !!}
    {{ $errors->first('time') }}


text:
Q: how to check: if array includes specific text properly? I am struggling with doing an array search that includes a piece of text that must include back slashes in it. I have tried includes(''); negating includes(''); and also trying similar using indexOf('').
I have a simple array, with at maximum four values; typically it has two, here is how it typically looks:
{tks: Array(2)}
tks: Array(2)
0: "https://mycoolwebsite.net/arcgis/rest/services"
1: "https://mycoolwebsite.com/arcgis/rest/services"
length: 2
__proto__: Array(0)
__proto__: Object

Here are the simple checks I'm trying to do: My second check with *includes* 'wdt' text seems to be working so I assume it's something with the backslashes. Anyway I can handle this? I'm perplexed why my if and else both get hit with the first check below using back slashes... I added the negating on the else to double check.. with and without that in the else, else is always hit.
    // right before doing the search I am building the array, just to add more context

    for (let i = 0; i < coolObj.length; i++) {
      if (coolObj[i].url){
          tr = coolObj[i].url;
          tks.push(tr);

          console.log({tks});
       }
     }

    console.log({tks}); // consoles as I have included above ^

    if (tks.includes('/arcgis/rest/services')) {

      console.log({tks});

    } else if (!tks.includes('/arcgis/rest/services')) {

      console.log({tks});

      console.log('does not include correct url');
      aT = '/arcgis/rest/services';
      lP = false;
      filterAt(aT);
    }
    if (tks.includes('wdt')) {
      console.log({tks});

    }else {
      console.log({tks});
      wT = 'wdt';
      filterWt(wT);
    }

A: From the MDN docs: The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
You have to test the strings using String.prototype.includes within the array elements thus:

const arr = ["https://mycoolwebsite.net/arcgis/rest/services", "https://mycoolwebsite.com/arcgis/rest/services"];

arr.forEach(el => {
  if (el.includes('/arcgis/rest/services')) {
    console.log(el, ': includes url');
  }
  else {
    console.log('does not include correct url');
  }
  if (el.includes('wdt')) {
    console.log(el, ': includes wdt');
  } else {
    console.log('does not include correct wdt');

  }

});


text:
Q: How to create c++ equivalent of Objective-C completion block as param Our iOS app depends on a c++ library. I'm new to c++, and I'm looking for the c++ equivalent of this:
Definition:
- (void)mySetter:(Thing)thing completion:(void (^)(BOOL))completion;

Use:
[self mySetter:thing completion:^(BOOL success) {
    // do something if successful
}]

I know this is a dumb question that's probably been answered, but all the answers I've come across are still pretty confusing for a c++ noob.
Happy to delete, but more happy to give out upvotes and check marks :)

A: In C++ you would usually use std::function for this, which is a class template that can hold any kind of callable function/object including a lambda (caveat: as long as it's copyable):
void mySetter(Thing thing, std::function<void(bool)> completion) {
  // ...
  completion(true);
}

mySetter(thing, [](bool success) {
  // ...
});

Note that in Objective-C++ (.mm files) you can generally mix C++ and Obj-C types freely, so you could for example pass a block as a parameter to a C++ function — you just need to be aware of the proper block pointer syntax.
void mySetter(Thing thing, void (^completion)(BOOL)) {
  // ...
  completion(YES);
}

mySetter(thing, ^(BOOL success) {
  // ...
});


text:
Q: WPF window position I have asked a question before about creating a child window here ... Now when I open child window, it doesn`t open centered to the parent window. How can I set it to open centered to the parent window?

A: Try this.
aboutWindow.WindowStartupLocation= WindowStartupLocation.CenterOwner ;

aboutWindow.ShowDialog(this);

A: This solution worked fine for me.
Here's a method I've found for centering a window to either its parent or the main window for the application, in WPF. It's not too different from how you do it in WinForms.
For the child window, set its WindowStartupLocation to "CenterOwner". This will cause it to show in the center of the owning Window.
Collapse
<Window x:Class="WpfApplication1.TestChild"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="TestChild" Height="300" Width="300"
    WindowStartupLocation="CenterOwner">

Now, all that's left to do is set its owner before displaying it. If the code you're using to display the window is running inside of a Window class, then you can just use this.
Collapse
TestChild testWindow = new TestChild();
testWindow.Owner = this;
testWindow.Show();

This isn't always the case, however; sometimes, you need to display the child window from the code running on a page or a user control. In this case, you want the child window to be centered to the main window of the application.
Collapse
TestChild testWindow = new TestChild();
testWindow.Owner = Application.Current.MainWindow;
testWindow.Show();

A: You can try this:
 AboutWindow window = new AboutWindow();
 window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
 window.Owner = this;

 window.ShowDialog();


text:
Q: Ruby on Rails: Create multiple records with multiple files uploaded at once I've created a Rails app using ActiveStorage that can upload multiple small video files into one record. My model is 'clip' and I'm currently uploading multiple videos files to one clip record.
I have this in the clip model:
has_many_attached :videos

This in the controller's private params.
def clip_params
  params.require(:clip).permit(:name, :duration, videos: [])
end

And this in the form to upload the videos.
<div class="field">
  <%= form.label :videos %>
  <%= form.file_field :videos, multiple: true %>
</div>

It works fine and the videos are uploading to the one record. However, what I need to do is -- upon upload of multiple files -- create a separate record for each of the video files uploaded. Of course I can do this one at a time by uploading one file each time, but I'd like to be able to upload multiple files at once (e.g. 15 small video files), and have my app create a separate record for each video uploaded -- so multiple clips each with an attached video. I'm assuming I can use a Clip.create in a loop somewhere (maybe the model) but not sure where to begin. Any ideas?


text:
Q: How to construct vector or list in testWithParam Parameter I am new to google test.
To test a class method, i have created a struct with the necessary variables
This is the sample model which i am working on.
    struct A {
    int a;
    int b;

    A(int _a, int _b) : a(_a), b(_b){}

    };

    struct B : public A {
     bool btest;

    B( A _aStruct, bool _b) : A(_Struct), btest(_b) {}

    };

    struct C : public B {

    std::vector<int> xVec;

    C(B _bStruct, std::vector<int>_xVec) : B(_bStruct) , xVec(_xVec){}
    };

    class Test : public classToTest , public testing::TestWithParam<C>
    {
     void SetUp()
    {
     //.....
    }

    };

    //Instantiate the test case with Parameters
    INSTANTIATE_TEST_CASE_P(Sampletest , Test, Values (B(1, 2, true), std::vector<int>(10,12,11)));

TEST_P(Test, TestSample )
{
 ...

}

I am getting Error in the Vector Construction.
How to get the vector or list Constrcuted in TestWithParam ???
INSTANTIATE_TEST_CASE_P is work without Vector for the Struct B.

A: The vector initialization was Wrong. it has to be installed with std::vector{10,12,11}.
thanks @YSC


text:
Q: How is typecasting Connection to OracleConnection different from connection.unwrap(OracleConnection.class) How is typecasting a java.sql.Connection to OracleConnecction different from getting OracleConnection from java.sql.Connection unwrap method .
Also, If I am creating OracleConnection through connection.unwrap(OracleConnection.class) then should I close the OracleConnection in finally or java.sql.Connection in finally.

A: The difference is somewhat subtle but meaningful.
Typecasting will fail with ClassCastException if the actual implementation object is incompatible with the declared class.  I.e. if the implementation is not an OracleConnection and you try to typecast it you'll get the exception.
Using unwrap(Class clazz) will attempt to find an object of the specified type and return that, failing with a SQLException instead if that's not possible.  The benefit of using the Wrapper interface methods is that you can check in advance if the unwrap will succeed, with the isWrapperFor method.


text:
Q: How to remove extra space inside of jQuery UI dialog box here is my dialog box

I want to delete or remove the extra spaces inside of dialog box. How can I achieve it?
for extra details here my HTML

  <?php
    $sql1 = "SELECT * FROM beneficiary WHERE id = '$id'";
    $result1 = mysql_query($sql1);
  ?>

      Name
      Action

  <?php
    while($row1 = mysql_fetch_array($result1)){
      echo "
";
      echo "".$row1['name']."	";
      echo "";
      echo "<button class='edit_beneficiaries'>EDIT</button>";
      echo "<button class='del_beneficiaries'>X</button>";
      echo "
";
      echo "
";
    }
  ?>

  <button class="beneficiaries" name="beneficiaries">Beneficiaries</button>

and jQuery script
jQuery("#beneficiaries_window").dialog({
  modal: true,
  resizable: false,
  draggable: false,
  autoOpen: false,
  buttons:[{
    text: "Close",
    click: function(){
      jQuery(this).dialog("close");
    }
  }]
});

//beneficiaries open dialog
jQuery(".beneficiaries").click(function(event){
  jQuery("#beneficiaries_window").dialog("open");
    event.preventDefault();
  });

but in my firebug i see this
's but their is no
 inside of the

how can i remove this im clueless about this extra spacing?

A: $('#div_id').dialog({
        title   : 'Add User',
        position: { my: "center", at: "center", of: window },
        width   : 1000,
        height  : 500,
        modal   : true,
        closeOnEscape: false
    });

you can define width, height in it, define its width accordingly.

A: The reason it has extra spacing because of this

<?php
while($row1 = mysql_fetch_array($result1)){
  echo "
";
  echo "".$row1['name']."	";
  echo "";
  echo "<button class='edit_beneficiaries'>EDIT</button>";
  echo "<button class='del_beneficiaries'>X</button>";

  echo "
";          <----THIS
 make the extra spacing

  echo "
";
}

?>


text:
Q: Scalatest ExecutionContext I would like to know which ExecutionContext I should use (and why) on scalatest % 2.2.6 to run my futures and mock's futures.
class Foo {
   def foo: Future[String] = Future.sucessful("B")
}

class Bar(foo: Foo) {
   def bar: Future[String] = foo.foo()
}

class MyTest extends WordSpec {

  implicit val ec: ExecutionContext = ??? // ...global? Why global? Why not?

  val myMock = mock[Foo]
  val myBar = new Bar(myMock)

  "..." in {
    (myMock.foo _).expects(*).returning(Future.succesful("A"))
    whenReady(myBar.bar())(_ shouldBe "A")
  }
}

A: Just import scala.concurrent.ExecutionContext.Implicits.global and this will load the default ExecutionContext for the Future objects in your tests to work properly.
NOTE: For using Futures on tests is OK the global implicits. For real projects consider to use ExecutionContext per case.


text:
Q: Chrome extension infinite loop I have an infinite loop that I do not understand
function bot(cartInfo, tab) {
    function injector(file, message) {
        chrome.tabs.executeScript(tab.id, {file: file, runAt: 'document_end'}, function(r) {
            chrome.tabs.sendMessage(tab.id, message, function(result) {
            });
        });
    }

    //this section gets repeated over and over
    chrome.tabs.onUpdated.addListener(
        function myListener(tabId, changeInfo, updateTab) {
            injector('addToCart.js', cartInfo.sizeInfo);
            chrome.tabs.onUpdated.removeListener(myListener);
        }
    );

}

I want it to enter the addListner section call the injector( which runs another file addToCart) once and return and exit.  If I remove the line chrome.tabs.onUpdated.removeListener(myListener);  It will work but calls the injector function infinitely.  If I keep the line it exits the loop, but does not execute the injector.   Is there a way to get around this? or  a way to remove the listener while inside the addToCart file so I know it has been executed at least once?

A: I don't recommend having the removeListener within the callback it's removing. I think if you refactor the code a little you should be able to get it to work. This makes the listener method more explicit and moves the removeListerner to trigger at the end of injector method.
function bot(cartInfo, tab) {

    var myListener = function(tabId, changeInfo, updateTab) {
        injector('addToCart.js', cartInfo.sizeInfo);
    }

    function injector(file, message) {
        chrome.tabs.executeScript(tab.id, {file: file, runAt: 'document_end'}, function(r) {
            chrome.tabs.sendMessage(tab.id, message, function(result) { });
        });
        chrome.tabs.onUpdated.removeListener(myListener);
    }

    chrome.tabs.onUpdated.addListener(myListener);
}


text:
Q: Scale coordinates got on a device I'm developing an Android app which lets the user draws and then checks if it has drawn inside a shape or not. The coordinates of the shape are retrieved by a .txt created before. Now, I created it on a Google Pixel C, so when the user draws the algorithm I made do not have any problem. I tried the app on a Galaxy Tab, which has a screen resolution of 1920 x 1200 and the shape its obviously in a different position. I made this method which converts the coordinates but it doesn't work:
public void loadShapePoints () {
    BufferedReader reader = null;
    Display display = getWindowManager(). getDefaultDisplay();
    Point size = new Point();
    display. getSize(size);
    int width = size. x;
    int height = size. y;
    float tmp = 0;
    try {
        reader = new BufferedReader(new InputStreamReader(getAssets().open(protocol+cornice)));
        String mLine;
        for (int elem=0; (mLine = reader.readLine()) != null; elem++) {
            mLine = mLine.replaceAll("\\s+","");
            if (elem%2==0) {
                tmp = Float.parseFloat(mLine);
            } else {
                float x = Float.valueOf(tmp)*(width/(float)2560);
                float y = Float.valueOf(Float.parseFloat(mLine))*(height/(float)1704);
                Pair p1 = new Pair(x, y);
                points.add(p1);
            }
        }
    } catch (IOException e) { } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) { }
        }
    }
    drawView.setShape(points);
}

I'm reading the file on this way because it is structured as well:
line 1: x1
line 2: y1
line 3: x2...
I used 2560x1740 in the conversion because it is the resolution of the Google Pixel C which I used on the emulator to develop the app.
I noticed that the only way to make it works on the Galaxy Tab A is to put 2600x2200 as coordinates (I don't know why), but obviously if I put this value it will not works as soon as I get back on the Pixel C. How can I convert them? Can the problem is that the drawing area is divided into 3 part which gets resized on different screen resolutions? This is the xml of the area:
<LinearLayout 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"
android:background="#FCFCFC"
android:orientation="vertical"
android:layout_marginTop="8dp"
tools:context=".PaintingActivity" >

<!-- Top Buttons -->

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="50dp"
    android:layout_gravity="center"
    android:orientation="horizontal" >

    <ImageButton
        android:id="@+id/draw_btn"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="50dp"
        android:contentDescription="@string/brush"
        android:background="@drawable/rounded_corners"
        android:padding="13dp"
        android:layout_marginTop="5dp"
        android:src="@drawable/brush" />

    <ImageButton
        android:id="@+id/erase_btn"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="50dp"
        android:contentDescription="@string/erase"
        android:background="@drawable/rounded_corners"
        android:padding="13dp"
        android:layout_marginTop="5dp"
        android:src="@drawable/eraser" />

    <ImageButton
        android:id="@+id/undo_btn"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:contentDescription="Undo"
        android:background="@drawable/rounded_corners"
        android:padding="16dp"
        android:layout_marginTop="5dp"
        android:src="@drawable/undo" />

</LinearLayout>

<!-- Custom View -->

<com.example.sample.DrawingView
    android:id="@+id/drawing"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_marginBottom="3dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="3dp"
    android:layout_weight="1"
    android:background="#FFFFFFFF" />

<!-- Menu in basso -->

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical" >

    <!-- Top Row -->

    <LinearLayout
        android:id="@+id/toprow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/form_intro"
            android:layout_marginTop="15dip"
            android:layout_marginBottom="25dip" />

        <EditText
            android:id="@+id/edittitle"
            android:layout_width="400dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dip"
            android:layout_marginBottom="25dip"
            android:singleLine="true" />
    </LinearLayout>

    <!-- Bottom Row -->

    <LinearLayout
        android:id="@+id/bottomrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/button_1"
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:layout_marginLeft="160dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/button_bg"
            android:text="Avanti"
            android:textColor="#FFFFFF" />
    </LinearLayout>
</LinearLayout>

This is how it looks like and its structure:

EDIT: the problem is that if I draw this segment on the Pixel C I get these coordinates:

1540.9375,
  513.01074

If I do it on the Galaxy Tab A I get these:

1158.0,
  279.0

A: I solved modifying the method as well:
public void loadShapePoints () {
    BufferedReader reader = null;
    float height = drawView.getCanvasHeight();
    float width = drawView.getCanvasWidth();
    float tmp = 0;
    try {
        reader = new BufferedReader(new InputStreamReader(getAssets().open(protocol+cornice)));
        String mLine;
        for (int elem=0; (mLine = reader.readLine()) != null; elem++) {
            mLine = mLine.replaceAll("\\s+","");
            if (elem%2==0) {
                tmp = Float.parseFloat(mLine);
            } else {
                float x = (width/2540)*(Float.valueOf(tmp));
                float y = (height/1109)*(Float.valueOf(Float.parseFloat(mLine)));
                Pair p1 = new Pair(x, y);
                points.add(p1);
            }
        }
    } catch (IOException e) { } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) { }
        }
    }
    drawView.setShape(points);
}

The problem was that the drawing area was getting reduced on each device, so, since it has a different size than the screen, I had to manually calculate it and divide per the Google Pixel C drawing area size (2540x1109).


text:
Q: stop redirecting page if it is redirecting by clicking on anchor I want to prevent page redirecting I know it can be achieve by this
window.onbeforeunload = function() {
        return "Dude, are you sure you want to leave? Think of the kittens!";
}

which was answered here Prevent any form of page refresh using jQuery/Javascript
But in my case I only want to prevent page when it is redirecting by clicking on any of the anchor tag.
Also event.preventDefault() will not work in my case while clicking on anchor tag because all anchors are not redirecting page so it should work fine.
I only want to stop redirecting page if it is redirecting by clicking on anchor. Any solution?

A: You can keep a flag which tells you whether or not the user clicked an a tag, then read that on your onbeforeunload script:
window.onbeforeunload = function () {
    if (_clickedAnchor) {
        _clickedAnchor = false;
        return "Dude, are you sure you want to leave? Think of the kittens!";
    }
}

_clickedAnchor = false;

jQuery(document).ready(function () {
    jQuery("a").click(function () {
        _clickedAnchor = true;
    });
});

A: You can use onhashchange.
With jQuery:
$(window).on('hashchange', function() {
    alert('bye byee?');
});

Plain DOM JavaScript:
window.onhashchange = function() {
    alert('bye byee?');
};

Note: You will need to create a custom "hash-change" handler for older browser which don't support this event.
You can easly do this with setInterval and detect any changes in document.location.hash.

Failsafe onhashchange for older browsers:
var currentHash = document.location.hash;

window.prototype.onhashchange = function( callback ) {
    if(typeof(callback) == 'function') {
        setInterval(function() {
            if(document.location.hash !== currentHash) {
                callback();
            }
        }, 650); // more than a half-a-second delay
    }
}

And you can use it as an event in regular DOM convention.

A: So since you tagged jQuery I'll put my solution in terms of that. You can grab all the a tags and then check to make sure the anchor is a redirect, then use the e.preventDefault();
$('a').on('click',function(e){
    if ($(this).attr('href') != window.location.href)
    {
       e.preventDefault();
       //do stuff
    }
});

A: The caller will be null if a link is clicked:
window.onbeforeunload = function() {
    alert(window.onbeforeunload.caller)
}


text:
Q: using lambda that captures a promise as a callback I want to use boost fibers to accomplish async communication with an external service. I use a set of promise and future for each individual fiber to be called on a separate reader fiber in order to wake up the originator fiber that waits for a future.
The problem is I can not figure out the type of the lambda function. I tried to use std::function and std::bind. But I did not manage to figure out the right type.
The callback is in the following structure:
struct AsyncClientCall {
    std::string response;
    bool status;    // Storage for the status of the RPC upon completion.
    // what is the proper type for this
    std::function<void()> callback;
};

It works for PODs, such as:
    asyncCall->callback = [i = msg] () mutable {
        std::cout << "release the lock: " << i << std::endl;
    };

But it does not with boost::fibers::promise, since there is no copy constructor:
    asyncCall->callback = [p = std::move(promiseRsp)] () mutable {
        p.set_value();
    };

However there is no problem with the lambda itself, since this works fine
auto  callback = [p = std::move(promiseRsp)] () mutable {
    p.set_value();
};

So my question is how to get around this properly if I want to use promise for synchronisation between fibers


text:
Q: How to generate a colorbar for manually colored plots in matplotlib? Suppose I need to control line colors myself for some reason, for example:
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
for i in np.linspace(0, 1, 100):
    plt.plot([i,i+1,i+2], color=mpl.cm.viridis(i))

How to generate a colorbar for such a plot?

A: You would need to create a colorbar without any reference axes. This can be done with the matplotlib.colorbar.ColorbarBase class. See also this example from the gallery.
To use this, you need to create a new axis in the plot, where the colorbar should sit in; one way of doing this is to use make_axes_locatable.
Here is a complete example.
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

for i in np.linspace(0, 1, 9):
    plt.plot([i,i+1,i+2], color=mpl.cm.viridis(i))

divider = make_axes_locatable(plt.gca())
ax_cb = divider.new_horizontal(size="5%", pad=0.05)
cb1 = mpl.colorbar.ColorbarBase(ax_cb, cmap=mpl.cm.viridis, orientation='vertical')
plt.gcf().add_axes(ax_cb)

plt.show()


text:
Q: Highcharter drilldown with multiple yAxis With the following chart:
highchart() %>%
  hc_chart(type = "waterfall") %>%
  hc_yAxis_multiples(create_yaxis(naxis = 2, heights = c(2, 2))) %>%
  hc_add_series(data = c(1,3,2), yAxis = 0) %>%
  hc_add_series(data = c(20, 40, 10), yAxis = 1)

How add a drilldown for yAxis = 0 and other drilldown for yAxis = 1 ?


text:
Q: Can I inherit from data odoo? I have this from the OCA:
<odoo noupdate="1">
    <record id="medical_specialty_adult_mental" model="medical.specialty">
        <field name="code">408467006</field>
        <field name="name">Adult mental illness</field>
    </record>

    <record id="medical_specialty_anesthetics" model="medical.specialty">
        <field name="code">394577000</field>
        <field name="name">Anesthetics</field>
    </record>

    others speciality .....
</odoo>

My question is: how can I inherit one of the speciality?

A:
To inherit it you must write it in the same way that it was defiined in the original module with the difference that in the id put first the name of the original module and followed by a dot and the id.

You only need to put the fields that you are going to modify.
<odoo noupdate="1">
    <record id="original_module_name.medical_specialty_adult_mental" model="medical.specialty">
        <field name="name">new_name</field>
    </record>

    <record id="original_module_name.medical_specialty_anesthetics" model="medical.specialty">
        <field name="code">new_code</field>
    </record>
</odoo>

Remember to add the file to the manifest


text:
Q: Woocommerce redirect checkout-form after validation I am using Woocommerce and after purchase validation through form-checkout.php, I can't forward some variables (eg: price, order num, etc...) to another URL through the form by using POST method.
I replace this line:
<form name="checkout" method="post" class="checkout woocommerce-checkout" action="<?php echo esc_url( wc_get_checkout_url() ); ?>" enctype="multipart/form-data"

by this line:
 <form name="checkout" method="post" class="checkout woocommerce-checkout" action="https://www.smt-sps.com.tn/paiement/" enctype="multipart/form-data">

But doesn't work… I hope that someone can help.


text:
Q: gsutil cp command copies entire directory path (on Windows) - bug? I am having a problem where gsutil does not seem to follow the behavior described in the documentation (at least in Windows). The documentation states:

When performing recursive directory copies, object names are constructed that mirror the source directory structure starting at the point of recursive processing. For example, the command:
gsutil cp -R dir1/dir2 gs://my_bucket

will create objects named like gs://my_bucket/dir2/a/b/c, assuming dir1/dir2 contains the file a/b/c.

However, in practice I have found that it will create objects named:
gs://my_bucket/dir1/dir2/a/b/c

ie, it copies the entire directory path stated in the gsutil command, rather than "starting at the point of recursive processing" (dir2) as stated in the documentation.
Am I missing/misunderstanding something here?

A: I noticed the same behavior when using the gsutil cp -R command with a similar directory structure.  In order to copy the desired directory from within the 'dir2' level I used the command: gsutil rsync -r dir1/dir2 gs://mybucket


text:
Q: Check if window.closed but also with a redirect to another URL/Host I have code to check if a window is closed. It works IF I stay on the same page.
With Internet Explorer, if I click on a link that then redirects to another site, that window.closed returns true even though the WINDOW never actually is closed.
I am doing this:
w = window.open("mypage.html");

var t = setInterval(function() {
  if (!w) {  alert('a'); }
  if (w.closed) { alert('b'); }
   if (!w || w.closed) {
     clearInterval(t); hide('mainShadow');
   }
}, 800);

Within "mypage.html", there is a link to another site.  When going to that other side, the w.closed returns true.
Is there a good way in IE to really check if the window is closed or not.
The contract isn't really satisfied because the window never actually closed.
This code works in Chrome, not in IE9

A:
The contract isn't really satisfied because the window never actually closed.

This seems to be the origin of the confusion. The window object in JavaScript-in-a-browser refers to window displaying a document as embodied in some browser window, but it does not refer to that window as the browser sees it itself. Nor is it the case that a single browser window is associated with a single window instance. So a window instance can be closed because it's not longer displayed. That's accurate because the window element is not, strictly speaking, about the browser entity window that is an external view of the window, as opposed the JavaScript object window that is an internal view of the window that a document containing code sees.
The short version is that I don't believe there's a way to do this from within a web page, since the outer scope of visibility, the window object, doesn't refer to the actual object you want to manipulate.

A: There is no way you can prevent this functionality due to the same-origin policy.  However, you might be able to use window.opener.someFunction() to call a function in the parent window every 100 ms.  If the parent window doesn't receive a message after say 500 ms, then it can assume that the window it opened was closed.  You could try similar with window.postMessage, but it won't work in IE.


text:
Q: Funny issue with external USB device interface Just out of curiosity:
A friend had a WD external case + SATA 2.5 disk, which fell on the floor and broke. The disk ended in trash (uprepairable). Out of the broken case, i took the PCB, a model of control board named "4061-705030-101 Rev.AA" with 2(3) connectors -- the SATA current+data and the miniUSB plug on the other side. I plugged it with a disk on the one side, the cable on the other, and, yes, it worked!
So it worked for quite some time with SATA 2.5 HDDs and on 3 computers at least (2 laptops, one with win7 and one with winXP, and a desktop in office with winXP) and worked fine. But i needed it on another 2 winXP desktops, and it refuses to work. Windows pops the "found new hardware" asking for a driver... but this driver is never found anywhere, and nobody seems to know anything. The drive is only marked as an unknown "USB device" in Device Manager.
It is funny that on some computers with WinXP it works, on others not. I tried to see what those computers have in common, and as far as i can get (i am not going to search the whole globe for this!) is that they have an Intel CPU (in both properly drivers installed and working flawlessly).
So, any idea?

NEW INFORMATION

I had some time yesterday to experiment. I connected the same interface with a few SATA HDDs (2.5, 3.5) and i noticed that with some disks it works with others not, differently on different computers. So down at the disk level looking for differences, i checked the needed milliAmperes on the disks, and voila! (I think) it is a matter of power. It depends on the current given by the USBs. Strangely though, winXP thinks a driver is missing. :-)

A: What you describe is salvaging an USB to SATA convertor from a broken drive. Those things are generally quite universal and you can indeed use them with other drives.
One often encountered problem with USB2 and older is that the USB bus supplies a maximum of 500 mA at +5 volt.  That is not enough for all drives.
To use your board you need to:

*

*Either use a drive which draws less power than 500mA (minus whatever the board uses).

*Or supply power via another source such as a external PSU (aka wallwart)

*Or try to kludge multiple USB ports into providing power.

*or have a badly designed motherboard which does not check if it exceeds max power.

Strangely though, winXP thinks a driver is missing. :-)

Yup. Seen that before when I use my "Xcraft External hard drive enclosure" [sic] with a 7200 RPM/650mA drive and XP. No idea why windows returns this particular error message. Maybe it is 'brown out/unrecognised/hence unknown.


text:
Q: Does the LLVM OCaml binding include intrinsic support? I can't seem to find reference to intrinsics in the official LLVM OCaml binding, beyond the is_intrinsic function.
I am building a backend which needs to perform some target-specific code-generation (for SSE, AVX, and NEON), and intrinsics are the standard path in the C++ API.

A: The OCaml binding supports intrinsics in exactly the same way as the C language binding:
There is no special support for them in the interface (as there is in the full C++ interface), but they can be declared extern and called just like any other functions.
e.g.:
open Llvm

let () =
  let c = create_context () in

  let f32_t = float_type c in
  let f32x4_t = vector_type f32_t 4 in

  let m = create_module c "test" in

  (* declare void @printv(<4 x float>)
   * nonce extern which forces preservation of vector results *)
  let printv =
   declare_function "printv"
     (function_type (void_type c) [|f32x4_t|]) m in

  (* declare <4 x float> @llvm.x86.sse.sqrt.ps(<4 x float>) nounwind readnone *)
  let sqrtps =
   declare_function "llvm.x86.sse.sqrt.ps"
     (function_type f32x4_t [|f32x4_t|]) m in

  (* define i32 @main() { entry: *)
  let main = define_function "main" (function_type i32_t [| |]) m in
  let at_entry = builder_at_end c (entry_block main) in

  (*%sqrtps = call <4 x float> @llvm.x86.sse.sqrt.ps(<4 x float> <float 1.000000e+00, float 2.000000e+00, float 3.000000e+00, float 4.000000e+00>)*)
  let cv1234 = const_vector [| const_float f32_t 1.0; const_float f32_t 2.0;
  const_float f32_t 3.0; const_float f32_t 4.0 |] in
  let sqrt = build_call sqrtps [| cv1234 |] "sqrtps" at_entry in

  (* call void printv(sqrtps) *)
  ignore (build_call printv [| sqrt |] "" at_entry);

  (* ret void *)
  ignore (build_ret (const_null i32_t) at_entry);

  (* Print .ll to stderr *)
  dump_module m

produces:
; ModuleID = 'test'

declare void @printv(<4 x float>)

declare <4 x float> @llvm.x86.sse.sqrt.ps(<4 x float>) nounwind readnone

define i32 @main() {
entry:
  %sqrtps = call <4 x float> @llvm.x86.sse.sqrt.ps(<4 x float> <float 1.000000e+00, float 2.000000e+00, float 3.000000e+00, float 4.000000e+00>)
  call void @printv(<4 x float> %sqrtps)
  ret i32 0
}

which compiles into x86 correctly invoking sqrtps on the xmm registers.

A: Disclaimer: I never used LLVM. After a quick look at the binding documentation, it looks like the answer is "no". There is a support for inline assembly however, which may or may not suit your needs.
Finally, it seems it is accepted by the LLVM developers that the OCaml binding is not complete: if you want to, you can add some more functionality (if you're not familiar with OCaml, C bindings are really not the easiest part, but the LLVM bindings are full of example code that you could probably successfully adapt to other LLVM functions), then provide a patch for it on the LLVMdev list.


text:
Q: slow mysql query to get product id and its category id I need help with this simple sql query that runs out of memory my server:
SELECT p.product_id, c.category_id
FROM product p, product_to_category ptc, category c
WHERE p.status = "1" AND
p.product_id = ptc.product_id AND
c.category_id = ptc.category_id
GROUP BY p.product_id;

What is wrong with it? I just want to get product id and what category is the product.

A: You don't need category table.
SELECT p.product_id, ptc.category_id
FROM product p, product_to_category ptc
WHERE p.status="1"
    AND p.product_id=ptc.product_id

And with join
SELECT p.product_id, ptc.category_id
FROM product p
JOIN product_to_category ptc
    ON p.product_id=ptc.product_id
WHERE p.status="1"

A: It seems very unlikely that your query would have such poor performance.  But, you can start by using explicit join syntax to make the query easier to understand:
SELECT p.product_id, c.category_id
FROM product p join
     product_to_category ptc
     on p.product_id = ptc.product_id join
     category c
     on c.category_id = ptc.category_id
WHERE p.status="1"
GROUP BY p.product_id;

Some possibilities:

*

*If you missed one of the conditions in the where clause, you could be generating lots of rows.

*Your tables are inordinately large for the system you are working on.

*Your are actually running out of temporary storage space for the aggregation, and your temporary space is full


text:
Q: Insert into a table MYSQL it doesn't make the register:
$reg = mysql_query("INSERT INTO privado (usuario_nombre, titulo, partitura, video, instrumentos, valoracion, votos, descripcion, etiquetas) VALUES ('".$nick."', '".$titulo."', '".$partitura."', '".$video."', '".$instrumentos."', 0, 0, '".$descripcion."', '".$etiquetas."'");
                if($reg) {
                    echo "Datos ingresados correctamente.";
                }else {
                    echo "ha ocurrido un error y no se registraron los datos.";
                }

It says "ha ocurrido un error..." so $reg is false.
What's wrong?
Thank for your help.

A: try this and you can see what the error is and then you can debug it
$reg = mysql_query("INSERT INTO privado (usuario_nombre, titulo, partitura, video, instrumentos, valoracion, votos, descripcion, etiquetas)
                       VALUES ('".$nick."', '".$titulo."', '".$partitura."', '".$video."', '".$instrumentos."', 0, 0, '".$descripcion."', '".$etiquetas."') ") or die(mysql_error());

A: Ok, there was a syntax error.
mysql_query("INSERT INTO privado (usuario_nombre, titulo, partitura, video, instrumentos, valoracion, votos, descripcion, etiquetas) VALUES ('".$nick."', '".$titulo."', '".$partitura."', '".$video."', '".$instrumentos."', 0, 0, '".$descripcion."', '".$etiquetas."')");
There was a braket missing.
Thanks for your help.


text:
Q: Log Archiving Solution What is the best solution for log archiving ? I have two application server (tomcat6) and I need to keep application log files for 7 years. Shipping, zipping and writing them on Bluray or DVD is time consuming, some the process is already automated but still takes so long, what do you suggest ?

A: The simpliest solution to me is to use syslog or one of its derivatives (rsyslog, syslog-ng) to send all logs to central servers. (Plural because you may want to have some kind of failover for security, or load-balancing if the log volume is very high)
Primary components you need are:

*

*Compress logs with the most efficient algorithm you can afford depending on the log volume and computing power on the central server(s). gzip with the default aggressivity setting should do the job.

*Use the most resilient storage solution you can affrod (RAID5 seems a minimum)

Log files are very repetitive, so a day worth of application logs should have a very high compression ratio, allowing you to store your 7 years in a decent amount of hard-drive.


text:
Q: Changing the default python on RedHat 6 We have a cluster consists of 5 machine for running Apache spark.
One of the machine the default python is 2.7 and the command which python output the following path /usr/local/bin/python
The other 4 machine, the default python is 2.6 and the command which python output the following path /usr/bin/python.
How can I change the python on the first machine to be like the others?

A: I presume that the machines have different version of the same OS or even different OS.
You could  manage different version of Python using for example virtualenv or virtualenvwrapper.
After that you install the packages you want in your /env installation/
more info about virtualenv


text:
Q: Is it right to create am html5 game with Canvas or custom html structure I am trying to find out the best way of convering flash games into html5.
I built one game with custom html, css, js and had some issues with having the game fullscreen always on any desktop/mobile screen, audio issues on apple devices etc.
As far as i checked all html5 games are created with canvas. I am trying to understand if that is possible to create any type of flash game with canvas and avoid issues i had like to have the game fullscreen without any issues or custom coding, avoid audio issues.
Will it be possible to create any type of structure from flash game with the canvas?
I am new to Canvas so i need to know all pros and cons and see if the canvas performance will be better than the custom html one.
Also the game will have an API for the game logic so how easy it will be to integrate the game API with the canvas?
Mostly games are Slot machine games so i will need winning combinations logic, lots of animations.
Any help is apprecited.
Thanks.

A: Notice that this snippet wont work on stackoverflow because it's nested in an iframe
Fullscreen is a standard feature with a rather wide support: https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullScreen#Browser_compatibility

var c = document.body.appendChild(document.createElement("canvas"));
var ctx = c.getContext("2d");
c.width = window.outerWidth;
c.height = window.outerHeight;
ctx.textAlign = "center";
ctx.font = "120px Arial";
setInterval(function () {
    c.width = window.outerWidth;
    c.height = window.outerHeight;
    ctx.fillStyle = "rgba(" +
        (Math.floor(Math.random() * 255)) + "," +
        (Math.floor(Math.random() * 255)) + "," +
        (Math.floor(Math.random() * 255)) +
        ",0.5)";
    ctx.fillRect(Math.floor(Math.random() * c.width), Math.floor(Math.random() * c.height), Math.floor(Math.random() * c.width), Math.floor(Math.random() * c.height));
    ctx.fillStyle = "white";
    ctx.fillText("Click for fullscreen", Math.floor(c.width / 2), Math.floor(c.height / 2));
    ctx.strokeText("Click for fullscreen", Math.floor(c.width / 2), Math.floor(c.height / 2));
}, 1000 / 60);
c.onclick = function goFullScreen(evt) {
    if (c.requestFullscreen) {
        c.requestFullscreen();
    }
    else if (c.webkitRequestFullScreen) {
        c.webkitRequestFullScreen();
    }
    else if (c.mozRequestFullScreen) {
        c.mozRequestFullScreen();
    }
};


text:
Q: Regex for entire words I need some help creating a regex. The String value is:
{"meta":[{"this_id":"111111"},{"this_id":"222222"},{"this_id":"333333"}],"type":"Account"}

I want to create a list with all the ids, so element[0] would be 111111, element[1] would be 222222, for example. I would also like to at least be able to isolate the type and set that to a String.
Can I receive some help on this? I tried to do
String[] tokens = stringToBreakUp.split(":");

Then I was just focused on all the tokens after the 2nd element in that list. I am not sure how to search list based on a key. I think I need some sort of key. But I am new at doing these things.

A: Just use \\d+ to get all the numbers. Check demo
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(yourString);
while (m.find()) {
    // print m.group() to get all ids
}

A: Use any JSON parsing library such as GSON or Jackson and convert it into Java Object.
Sample code using GSON library:
Type type = new TypeToken<Map<String, Object>>() {}.getType();
Map<String, Object> data = new Gson().fromJson(jsonString, type);

// just iterate the map and get the desired value

Sample code using Jackson library:
JSONObject obj = new JSONObject(s);
JSONArray jsonArray = obj.getJSONArray("meta");
for (int i = 0; i < jsonArray.length(); i++) {
    System.out.println(jsonArray.getJSONObject(i).get("this_id"));
}

output:
111111
222222
333333

A: I absolutely agree that the RegEx is not an appropriate tool to parse JSON, but this simple test will help you to do it.
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.testng.Assert.assertEquals;

public class SimpleTest {

    @Test
    public void test() throws Exception {
        String str = "{\"meta\":[{\"this_id\":\"111111\"},{\"this_id\":\"222222\"},{\"this_id\":\"333333\"}],\"type\":\"Account\"}";

        Pattern idPattern = Pattern.compile("\\{\"this_id\"\\s*\\:\\s*\"(\\d+)\"\\}");
        Matcher idMatcher = idPattern.matcher(str);
        Collection<String> ids = new ArrayList<>();
        while (idMatcher.find()) {
            ids.add(idMatcher.group(1));
        }
        assertEquals(Arrays.asList("111111", "222222", "333333"), ids);

        Pattern typePattern = Pattern.compile("\"type\"\\s*\\:\\s*\"([^\"]+)\"");
        Matcher typeMatcher = typePattern.matcher(str);
        String type = typeMatcher.find() ? typeMatcher.group(1) : null;
        assertEquals("Account", type);
    }

}


text:
Q: Imacro using eval to remove two certain words this is my code:

TAG POS=82 TYPE=P ATTR=* EXTRACT=TXT
TAG POS=85 TYPE=P ATTR=* EXTRACT=TXT
TAG POS=86 TYPE=P ATTR=* EXTRACT=TXT
'clean the extracted data:
SET replies EVAL("'{{!EXTRACT}}'.replace(/[\\$|'[EXTRACT]'|#EANF#]/g, '');")
'below code is suppose to put the extracted replies into the summerizer box
TAB OPEN
TAB T=2
SET !ERRORIGNORE YES
URL GOTO=http://www.summarizing.biz/best-summarizing-strategies/article-summarizer-online/
TAG POS=1 TYPE=TEXTAREA FORM=ID:summarizingform ATTR=ID:draft CONTENT={{replies}}
EVENT TYPE=MOUSEUP POINT="(1140,899)"
PROMPT "Please enter the captcha:" !VAR1
TAG POS=1 TYPE=INPUT:TEXT FORM=ID:summarizingform ATTR=ID:sum_secure CONTENT={{!var1}}
SET !ERRORIGNORE NO
TAG POS=1 TYPE=A ATTR=ID:summar_btn
'Prompt and ask for the rephrased summery
PROMPT "type the rephhrased summery" !VAR2
TAB T=1

I'm trying to remove "[EXTRACT]" and "#EANF#" from the extracted data but when I use this code:
SET replies EVAL("'{{!EXTRACT}}'.replace(/[\\$|'[EXTRACT]'|#EANF#]/g, '');")

it removes all capital "E X T R A C T" from the text. for example if I have the word "Report" in my extracted data it becomes "eport" after going through the Eval.
please help me.
thanks in advance

A: here's the right eval command in case someone is interested:
SET replies EVAL("'{{!EXTRACT}}'.replace(/(EXTRACT|#EANF#)/g, '');")

oh my god this Eval thing is so powerful...opens a whole alot of possibilities for you...

A: Maybe not the best, but a solution,
 1. Try to set the complete text as a var, f.ex:
SET !VAR1 and here goes your EXTRACTED TEXTS ETC.

2. Paste the text somewhere into an online notepad in a second tab, ghostbin, piratepad, ...

*Record with experimental mode how you edit the text WITH the keyboard.

*Set the edited text again as your new !VAR1 and use !VAR1 as your whole text
As said, not best solution etc. but could be one.
One question i still have, why dont you simply delete the words "[EXTRACT]" and "#EANF#" ?


text:
Q: Why does the Wordpress database schema not use foreign keys? Today i check the tables of the wordpress database but i can't find foreign keys to relate tables , can anybody tell me why wordpress don't have foreign keys ?

A: WordPress uses MyISAM, because of more functionality and better performance, but MyISAM did not support foreign keys. It was a trade off.

A: Foreign keys are just constraints - they make it easier to preserve integrity of the data, but are not required to correlate the tables. Wordpress uses MySQL and MySQL can use many "engines" for storing the tables, but AFAIK only one of them (InnoDB) supports foreign keys. Wordpress probably decided not to use it for performance reasons.


text:
Q: limit of difference of harmonic series $$\lim_{n\to\infty}\frac{1}{n+2}-\frac{1}{2(n+1)}$$
Having difficulty with the limit. Would this be solveable, by writing all terms individually, cancelling out; then attempting to find a convinient form?
I am particularly interested in whether this converges...

A: You could observe that
$$
\frac{1}{n+1}-\frac{1}{2(n+1)}=\frac{n}{2(n+2)(n+1)}
$$
and take it from there.

A: In addition to the answers received, another approach is to write the series expansion at n = Infinity.
You would have something like:
http://www.wolframalpha.com/input/?i=Limt%5B1%2F(n%2B2)%20-%201%2F(2(n%2B1))%2C%20n%20-%3E%20Infinity%5D&t=crmtb01
HTH ~A


text:
Q: Custom drawing order for AR overlay effects in OpenGL ES (10) I am working on a augmented reality application and need to sort the rendering of three different kinds of geometry.
Level 1
Background geometry. This is a set of triangles that represent basic architecture. Walls etc.
Level 2
Photograph plane. A photograph of the architecture placed as a texture on a plane in space. That plane is geometrically in front of Level 1 (as seen from the virtual camera)
Level 3
Dynamic geometry. These are primitives like boxes etc, to augment the scene. They are geometrically behind Level 2, because they are correctly placed inside the coordinate system of Level 1
Desired effect:
a) I want Level_2 to always be drawn in front of Level_1
This is automatically achieved by placing the image plane closer to the camera.
b) I want Level_3 to be occluded correctly against Level_1, thereby hiding parts of a dynamic box, if it is placed partly behind a wall of Level_1.
This automatically happens with normal pipeline too. Depth testing etc.
c) I want all Fragments/Pixels of Level_3 to be drawn ABOVE Level_2, even if they are actually behind it. The effect should make the objects appear, as if they are occluded by parts of the photograph.
I know that this is possible, because i have an application in X3Dom (which renders to webgl) that can achieve this effect via the "sortkey" attribute.
But i could not recreate the same effect in pure OpenGL.
I thought it should be a simple use of Stencilbuffer or Z-Buffer tricks, but i don't get it to work.
How do i give an "always pass" to the Level_3 geometry, so that it is drawn above everything else, but also correctly occluded against Level_1?
Or how do i make Level_2 hide only Level_1 and not Level_3 even if it is in front of both?
Basically:
1) Level_2 hides Level_1
2) Level_1 and Level_3 occlude each other
3) Visible parts of Level_3 (against Level_1) are not occluded by Level_2
Any help?
Thanks!

A: You need to render scene in three stages accordingly to levels you've described. The level_1 should be rendered first with depth test enabled. Then, you should render level_2 with disabled depth test. And at third stage you should render level_3 with depth test enabled. Thus the geometry of level_2 would be rendered totally overlapping level_2 meanwhile it would not effect z-buffer, so the geometry of level_3 would be rendered as if level_2 wasn't be rendered at all.
To enable and disable depth test you should call glEnable and glDisable functions.
Calling glDisable(GL_DEPTH_TEST) would disable depth test and update of depth buffer. To enable depth test and writing to depth buffer you should call glEnable(GL_DEPTH_TEST)
General steps you need to do:
    /*
    Render level_1
    */

    glDisable(GL_DEPTH_TEST); //disable depth test and update of the depth buffer

    /*
    Render level_2
    */

    glEnable(GL_DEPTH_TEST);  //enable depth test and update of the depth buffer

    /*
    Render level_3
    */

A: Found out after a while, but forgot to update here.
The solution was as simple as expected.
DepthTesting stays active all the time. Rendering is called in order 1, 2, 3.
Rendering of level 2 is enclosed in
gl.glDepthMask(false);
gl.glDepthMask(true);
Allows for correct depth rendering and occlusion of every level but will not change the depth buffer from rendering level 2 elements. Therefore level 3 elements ignore the depth of level 2 and clip against level 1.


text:
Q: How to have multi-level dependencies in eclipse In my java project I have a library I am working on and a second project that has the first project as a dependency. The first project has a library as a dependency in the form of a jar file. When I run the second project, I get a java.lang.NoClassDefFoundError for one of the classes of the jar file. When I move the src for the second project into the first project, it runs without errors. I've added the jar library to the export tab on the first project but the problem persists. What can I do to fix this?

A: Add the first project to the Java build path of the second project:
Select the second project and in Project > Properties: Java Build Path, in the Projects tab click Add... and select the first project.


text:
Q: Creating webhooks or listening events from shopify POS I am developing a loyalty app or Shopify POS system. I want to listen to the events such as cart creation or Updation or customer creation etc on the POS system and work accordingly. I have created some webhooks which are working only through the online shop but not from POS.
I have searched a lot but didn't find a way to make them work through POS.
I am creating my app using nodeJs and expressJs.
This is my current code of accepting the hooks which are working only from the online shop.
app.post('/getproduct', (req,res) => {
    // alert("skfjfjn");
    res.status(200).send('OK');
    console.log("nagesh test ")
    console.log(req)

  });

This image is my webhook on admin.