text:
Q: Codeigniter Nesting Loop error in connecting to database I was going though the Codeigniter tutorial in the user guide but when I got to the section using the model I got an error saying that the execution timed out. I subsequently increased the php execution time to 1200 and the next error was the maximum nesting level has been been reached at 100, I have subsequently increased it to 200 with the same error.
It appears that its stuck in some kind of nesting loop just referencing the same 4 functions repeatedly.
I am running:
Codeigniter 3.0.0
Apache 2.4.9
PHP 5.5.12
SQL Server 2012 Express LocalDB - (Windows Authentication - if that makes a difference)
Part of the Error Message Below:
Fatal error: Maximum function nesting level of '200' reached, aborting! in C:\wamp\www\NewsApp\system\database\DB_driver.php on line 963

Call Stack
    Time    Memory  Function    Location
1   0.0010  151936  {main}( )   ..\index.php:0
2   0.0030  197064  require_once( 'C:\wamp\www\NewsApp\system\core\CodeIgniter.php' )   ..\index.php:292
3   0.0360  850512  News->__construct( )    ..\CodeIgniter.php:500
4   0.0390  985568  CI_Loader->model( ) ..\News.php:7
5   0.0410  992936  News_model->__construct( )  ..\Loader.php:305
6   0.0410  993224  CI_Loader->database( )  ..\News_model.php:6
7   0.0420  1016048 DB( )   ..\Loader.php:349
8   0.0520  1612760 CI_DB_driver->initialize( ) ..\DB.php:216
9   0.0520  1612904 CI_DB_sqlsrv_driver->db_connect( )  ..\DB_driver.php:401
10  15.0609 1616496 CI_DB_driver->query( )  ..\sqlsrv_driver.php:147
11  15.0609 1616728 CI_DB_driver->simple_query( )   ..\DB_driver.php:642
12  15.0609 1616728 CI_DB_driver->initialize( ) ..\DB_driver.php:768
13  15.0609 1616728 CI_DB_sqlsrv_driver->db_connect( )  ..\DB_driver.php:401
14  30.0707 1617416 CI_DB_driver->query( )  ..\sqlsrv_driver.php:147
15  30.0707 1617560 CI_DB_driver->simple_query( )   ..\DB_driver.php:642
16  30.0707 1617560 CI_DB_driver->initialize( ) ..\DB_driver.php:768
17  30.0707 1617560 CI_DB_sqlsrv_driver->db_connect( )  ..\DB_driver.php:401

What's going on here?
The model:
<?php
class News_model extends CI_Model {

    public function __construct()
    {
            $this->load->database();
    }

    public function get_news($slug = FALSE)
    {
            if ($slug === FALSE)
            {
                    $query = $this->db->get('news');
                    return $query->result_array();
            }

            $query = $this->db->get_where('news', array('slug' => $slug));
            return $query->row_array();
    }
}

Just $this->load->database(); is causing the loop.


text:
Q: "import pygame" is not working I'm just trying to build some Python game, but import pygame is not working.
I got this error massage:
/usr/bin/python3 /home/dinushi/g.py/snackgame.py
Traceback (most recent call last):
  File "/home/dinushi/g.py/snackgame.py", line 2, in <module>
    import pygame
ModuleNotFoundError: No module named 'pygame'

A: You need to install the pygame module (no need to use sudo):
pip3 install --user pygame

Another way to install is by sudo apt-get install python3-pygame

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I get analytics on a site without a frontend? For example, google Analytics would require me to insert a script in my layout. However, my app has no views and is only serving an API, without an interface. Are there any services to track traffic of a JSON API ? I intend to host on heroku.

A: Most analytics services offer some sort of server-to-server rather than client reporting of events. You should get some more consistency in data reported (e.g. you're not blocked by ad blockers or slow connections failing to load client side libraries) but also lose visibility into some events (user tracking depends on your authentication/cookie policy, time on page may be impossible to measure).
For a Rails app I'd look at https://segment.com/docs/sources/server/ruby/ which in my experience has done a good job of making it easy to report events and allows you to then forward them to whatever analytics service works best for your product.


text:
Q: Bot Framework send message to different user I have a bot that does a hand-off to a human operator.
When the operator joins I receive an event in the 'OnEventActivityAsync' event.
At that moment I want to send a message to the client that they're connected to the operator.
How do I change the turnContext/Activity to send the message to the client?
Not entirely sure which part of code to post. (can't post entire project due to company policies)
protected override async Task OnEventActivityAsync(ITurnContext<IEventActivity> turnContext, CancellationToken cancellationToken)
{
    if (turnContext.Activity.Name == "webchat/agentJoin")
    {
        _logger.LogInformation("webchat/agentJoin");
        //Database stuff here
        await turnContext.SendActivityAsync(MessageFactory.Text("Connected to customer"), cancellationToken);

        //How do I send a message to the client here? turnContext sends the message to the agent, not client

    }
}

A: Please See protocol definition in the below GitHub link experimentations:
https://github.com/microsoft/BotBuilder-Samples/tree/master/experimental/handoff-library
Factory Methods
SDK will include the following factory method to aid in creation of the events specified:
C#:
namespace Microsoft.Bot.Builder

{

    public static class EventFactory

    {

        public static IEventActivity CreateHandoffInitiation(

            ITurnContext turnContext,

            object handoffContext,

            Transcript transcript);

        public static IEventActivity CreateHandoffResponse(

            ConversationAccount Conversation,

            string code);

        public static IEventActivity CreateHandoffCompleted(

            ConversationAccount Conversation,

            string code,

            Transcript transcript);

    }

}

Protocol codes are defined as follows:
namespace Microsoft.Bot.Schema

{

    public static class HandoffCodes

    {

        public const string Accepted = "accepted";

        public const string Failed = "failed";

        public const string TimedOut = "timedOut";

        public const string EndOfConversation = "endOfConversation";

        public const string TransferBack = "transferBack";

    }

}

A: Thanks to the suggestion by Mick I took another look at proactive messages.
I had looked at it before, but never got it to work because of 'Unauthorized' errors.
Now I noticed there's a fix for that specific problem.
The code is based on the MS documentation for sending proactive notifications:
Send proactive Notifications
So what I do is:
turnContext.Adapter.ContinueConversationAsync(_appId, conversationReference, BotCallback, default(CancellationToken));

private async Task BotCallback(ITurnContext turnContext, CancellationToken cancellationToken)
{
    // If you encounter permission-related errors when sending this message, see
    // https://aka.ms/BotTrustServiceUrl
    await turnContext.SendActivityAsync("You're now connected to: Ted");
}


text:
Q: How to stop the UI navigating to the most recent result in the Services view? So I have maybe 10 different connections active at any one time, running a bunch of statements on different dbs. Every time a single statement/query is completed, my results view jumping to the latest completed statement in the console, on any one of the open running connections - which is annoying when its something like quickly dropping a temp table when i'm quickly reading results from another output.
Any idea if you can prevent this from happening?

A: Unfortunately, it is impossible now. Please file a feature request here: https://youtrack.jetbrains.com/issues/DBE
The workaround can be using 'In-editor results' mode, when you'll see the result just under your query and no one will ever grab it from you!


text:
Q: How do I read Spark processing log? I I have run a python script like this:
spark-submit \
 --master yarn \
 --deploy-mode client \
 --driver-memory 2G \
 --driver-cores 2 \
 --executor-memory 8G \
 --num-executors 3 \
 --executor-cores 3 \
 script.py

And I get logs like this:
spark.yarn.driver.memoryOverhead is set but does not apply in client mode.
[Stage 1:=================================================>       (13 + 2) / 15]18/04/13 13:49:18 ERROR YarnScheduler: Lost executor 3 on serverw19.domain: Container killed by YARN for exceeding memory limits. 12.0 GB of 12 GB physical memory used. Consider boosting spark.yarn.executor.memoryOverhead.
[Stage 1:=====================================================>   (14 + 1) / 15]18/04/13 14:01:43 ERROR YarnScheduler: Lost executor 1 on serverw51.domain: Container killed by YARN for exceeding memory limits. 12.0 GB of 12 GB physical memory used. Consider boosting spark.yarn.executor.memoryOverhead.
[Stage 1:====================================================>   (14 + -1) / 15]18/04/13 14:02:48 ERROR YarnScheduler: Lost executor 2 on serverw15.domain: Container killed by YARN for exceeding memory limits. 12.0 GB of 12 GB physical memory used. Consider boosting spark.yarn.executor.memoryOverhead.
[Stage 1:====================================================>   (14 + -8) / 15]18/04/13 14:02:49 ERROR YarnScheduler: Lost an executor 2 (already removed): Pending loss reason.
[Stage 1:=======================================================(26 + -11) / 15]18/04/13 14:29:53 ERROR YarnScheduler: Lost executor 5 on serverw38.domain: Container killed by YARN for exceeding memory limits. 12.0 GB of 12 GB physical memory used. Consider boosting spark.yarn.executor.memoryOverhead.
[Stage 1:=======================================================(28 + -13) / 15]^[18/04/13 14:43:35 ERROR YarnScheduler: Lost executor 6 on serverw10.domain: Slave lost
18/04/13 14:43:35 ERROR TransportChannelHandler: Connection to serverw22.domain/10.252.139.122:54308 has been quiet for 120000 ms while there are outstanding requests. Assuming connection is dead; please adjust spark.network.timeout if this is wrong.
[Stage 1:=======================================================(28 + -15) / 15]18/04/13 14:44:22 ERROR TransportClient: Failed to send RPC 9128980605450004417 to serverw22.domain/10.252.139.122:54308: java.nio.channels.ClosedChannelException
java.nio.channels.ClosedChannelException
18/04/13 14:44:22 ERROR YarnScheduler: Lost executor 4 on serverw36.domain: Slave lost
[Stage 1:=======================================================(31 + -25) / 15]18/04/13 15:05:11 ERROR TransportClient: Failed to send RPC 7766740408770504900 to serverw22.domain/10.252.139.122:54308: java.nio.channels.ClosedChannelException
java.nio.channels.ClosedChannelException
18/04/13 15:05:11 ERROR YarnScheduler: Lost executor 7 on serverw38.domain: Slave lost
[Stage 1:=======================================================(31 + -25) / 15]

*

*What does values in backets mean? (13 + 2)/15 later (28 + -13)/15 etc and finaly (31 + -25) / 15

*Why executors are lost?

*Is this application dead and I should kill it or it will finish succesfuly?

Regards
Pawel

A:
What does values in backets mean? (13 + 2)/15 later (28 + -13)/15 etc and finaly (31 + -25) / 15

The first number is the number of partitions that have finished for the current operation.
The second number is the number of partitions that are currently being processed. If the number is negative, that means that the partitions' results are invalid and must be recomputed.
Finally, the last number if the total number of partitions that the current operation has.

Why executors are lost?

As the log error messages say, the tasks are using more memory than what the executors have physically allocated.

Is this application dead and I should kill it or it will finish succesfuly?

Usually Spark should either be able to finish the application (whether it ends successfully or in error). However, in this case I would not have too much hope on it finishing successfully anyway - so if I were you I would just kill it and review the memory settings.


text:
Q: Unable to send emails in Django I've created an email account in the cPanel of my website and want to use it to send emails using the Django web framework.
There are the configurations in my Django settings:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
EMAIL_HOST = 'mail.mydomain.com'
EMAIL_PORT = 2525
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')

but when I run the function of ending the email I get this error:
for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -2] Name or service not known

So, what I've missed and occurred this problem.


text:
Q: Can't get the return new Chat to retrive the values Hi so I have a project for college where I need to build a chat in java that to work only in on computer where you execute the code and you give the name of the two users and a translation value but I am having a problem with the way they want me to do it since I cant use super, arrays , extends, or inherences I am having a problem how it currently is I my Main like this
import java.util.Scanner;
public class Main {

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    Chat ch = null;

    boot(in, ch);
    menu(in, ch);
}

public static Chat boot (Scanner in, Chat ch){

    String name1;
    String name2;
    int transvalue = 0;

    System.out.print("Username 1:");
    name1=in.nextLine();

    do{
    System.out.print("Username 2:");
    name2=in.nextLine();

    if (name1.equals(name2)){
        System.out.println("Names can't be equal");
        }

    }while(name1.equals(name2));

    do{

    System.out.print("Translation Value:");
    transvalue=in.nextInt();
    in.nextLine();
    if (transvalue<1 || transvalue>26){
        System.out.println("Value Can only be between 0 and 26");
    }

    }while(transvalue<1 || transvalue>26);

    return new Chat(name1,name2,transvalue);

    }

So this show be adding the info I put in to my class Chat
public class Chat {

private static final int id1 = 1;
private static final int id2 = 2;

private Users u1;
private Users u2;
private Conversation conv;

public Chat(String name1, String name2, int transvalue){
    u1 = new Users(id1,name1);
    u2 = new Users(id2,name2);
    conv = new Conversation(transvalue);

}

public static int getId1() {
    return id1;
}

public static int getId2() {
    return id2;
}

public Users getU1() {
    return u1;
}

public void setU1(Users u1) {
    this.u1 = u1;
}

public Users getU2() {
    return u2;
}

public void setU2(Users u2) {
    this.u2 = u2;
}

public Conversation getConv() {
    return conv;
}

public void setConv(Conversation conv) {
    this.conv = conv;
}

}

but when I add the info and try to return it like for example:
System.out.print(ch.getU1());

or
    System.out.print(ch.getU1().getName());
I am getting a null am I doing something wrong?
public class Users {

private int id ;
private String name;
private String mess;

public Users(int id,String name){
    this.id=id;
    this.name=name;

}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

Can anyone find or point out what I'm doing wrong
Thank you in Advance to all that take the time to Help


text:
Q: Adding value to Scala map Why does this work:
val x = Map[Int,Int]()
val y = (1, 0)
x + y

but not this?
val x = Map[Int,Int]()
x + (1, 0)

The error produced is:
<console>:11: error: type mismatch;
found   : Int(1)
required: (Int, ?)
          x + (1,0)
               ^

If I were to enter (1,0) into the REPL, it correctly types it as (Int,Int).
I should add that this works fine:
x + (1 -> 0)

A: This is an ambiguity caused by the similarity between the notation for tuples and the one for parameter lists :
x + (1,0) is notation for x.+(1,0) but sadly there is no method on x that takes two Int parameters. What you want is x.+((1,0)), i.e. x + ((1,0)).
There is something in Scala called auto-tupling, see this question and answers, which rewrites, for example, println (1,2) to println((1,2)). Except this will not work here because the + method takes a variable number of arguments and not a single  one like println.
You get that strange error message because it expect every value in your parameter list (1,0) to be a tuple, as in myMap + ((1,2), (1,3), (3,4)). It finds an Int instead of a (Int, Int), hence the error.

A: add another pair of parentheses to make it work:
val x = Map[Int,Int]()
x + ((1, 0))


text:
Q: Need help in installing blpapi and configuring Python Interpreter I am using Python 3.5 64 bit and Windows Machine. Normally i install packages using pip installer.
For blpapi library(bloomberg API), i used the steps mentioned in answer from following question Anaconda - Install blpapi in environment
Steps I followed:
conda create -n py35 python=3.5
activate py35
conda install -c macinv blpapi

This worked fine. But it has created a separate Python Environment and Interpreter
C:\Users\bl00mb3rg\Miniconda3\envs\py35
Already i have another python interpreter which was created while intalling python 3.5 64 bit.
Which Interpreter i have to use while configuring python IDE. If i select Conda python Env, i am not able to use libraries such as 'pdblp' which i installed using pip
How to make Conda install libraries in existing python instead of creating new Environment.

A: Install using Anaconda Prompt
conda install -c mbonix blpapi

A: https://anaconda.org/p-vg/blpapi/files

*

*This is the latest version of blpapi 3.9.2

*It has both packages for python 3.6 and 2.7

*Both windows and linux

conda install -c p-vg blpapi

A: This is tangential to the question, but you do not have to use conda; per Bloomberg's API Library page, you can run:
python -m pip install --index-url=https://bloomberg.bintray.com/pip/simple blpapi

from within your existing environment.


text:
Q: Wpf highlight image? Is there any effect in WPF I could Make an image shiny etc.?
(I want to use it for a hovered image)
A mask or something like this would be great.

A: Try applying a BitmapEffect to the image, just keep in mind that they can be expensive to use.
OuterGlowBitmapEffect might help you.

A: It depends on what do you mean by "shiny". A simple way is to have each image opacity set to 0.5 and change it to 1 when mouse is in.


text:
Q: docker network host on windows I am on windows 2019 server machine. I am running centos docker on it .
Is there anyway to  achieve results same as --network host on windows ;
On Linux --network host ensures

*

*All port mapped from host to container

*the container IP address is same as  host .

Unfortunately --network host is available only on Linux and I don't know when will windows give it but I need some workaround
For 1 I have resorted to doing -p 3000:3000 for all the ports which were required but I am unable to give same IP to the container and that is blocker for me .


text:
Q: Audio drivers, bluetooth drivers and wifi drivers don't work I know you may think that this question has been answered in other threads. But the point is that I tried almost all things are said in all of these kind of threads and didn't work for me. I installed Ubuntu 17.04 in my Asus-x205ta laptop (which has been horrible, many problems with grub errors and UEFI) and now neither WIFI drivers nor audio drivers nor Bluetooth drivers work. Another interesting thing I found is that in "Software and updates", in the additional drivers section, I can choose one privative driver for the CPU, but not for Wifi, Bluetooth or audio.
The most important problem for my needs is the WiFi problem.
As I said, I tried different things to solve the problem, that is to say, the most common ways to solve these problems.
Also I have read that this netbook has a lot of problems with Linux.
This is the output for iwconfig:
sergio@sergio-X205TA:~$ iwconfig
enx0050b61c7199  no wireless extensions.
lo        no wireless extensions.

And this is the output for lscip:
sergio@sergio-X205TA:~$ lsipc
RESOURCE DESCRIPTION                                              LIMIT USED  USE%
MSGMNI   Number of message queues                                 32000    0 0,00%
MSGMAX   Max size of message (bytes)                               8192    -     -
MSGMNB   Default max size of queue (bytes)                        16384    -     -
SHMMNI   Shared memory segments                                    4096    7 0,17%
SHMALL   Shared memory pages                       18446744073692774399 5248 0,00%
SHMMAX   Max size of shared memory segment (bytes) 18446744073692774399    -     -
SHMMIN   Min size of shared memory segment (bytes)                    1    -     -
SEMMNI   Number of semaphore identifiers                          32000    0 0,00%
SEMMNS   Total number of semaphores                          1024000000    0 0,00%
SEMMSL   Max semaphores per semaphore set.                        32000    -     -
SEMOPM   Max number of operations per semop(2)                      500    -     -
SEMVMX   Semaphore max value

And this is the output for lsusb:
sergio@sergio-X205TA:~$ lsusb
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 005: ID 6557:5500
Bus 001 Device 006: ID 0b95:772b ASIX Electronics Corp. AX88772B
Bus 001 Device 003: ID 05e3:0610 Genesys Logic, Inc. 4-port hub
Bus 001 Device 002: ID 04f2:b483 Chicony Electronics Co., Ltd
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

A: I have Xubuntu on my Asus X205TA (I used to use Debian then Lubuntu but they had a few oddities on the X205TA so I made the switch), here is what I did to get mine working with Xubuntu:
The prep work needed:

*

*Have 2 USB drives (We will call them B1 and B2), an Ubuntu 14.04 64bit ISO, and a Xubuntu 64bit ISO and another computer (not the X205TA)

*Use Rufus on the computer to make a Ubuntu 14.04 Live USB on the first USB drive (B1)

*Boot up the computer with the 14.04 Live USB (B1)

*Use the "startup disk creator" to make a Xubuntu Live USB with persistence on the second USB drive (B2)

*Add this file to /EFI/BOOT directory of the Xubuntu flash drive (B2)

*Shut down the computer

*Ensure that the laptop is plugged in and charging

*Plug the Xubuntu Live USB drive (B2) into the laptop

*Plug in your internet access device

*Boot the laptop & press ESC as it is booting (this will give you the boot order screen)

*Select "enter setup"

*Disable Secure Boot

*Save and exit the BIOS

*Press ESC as it is booting (this will give you the boot order screen)

*Select your Xubuntu Live USB drive (B2) drive from the list

*Select "Try Xubuntu" when prompted

*Open the "Terminal Emulator" program

Type in the following commands (or you could copy and paste them)

*

*sudo apt update

*sudo apt install gnome-disk-utility

Then do the following:

*

*Open the "Disks" program

*Find the laptops inbuilt storage and format it with a MBR/DOS partition system (top right, the gear)

*Once it is done use the "Install Xubuntu" program on the desktop to install it onto the laptops internal storage, make sure you have internet access on the laptop (USB cell phone tethering works well) and to select the option to install third party software.

*When the installation is complete you can shut-down the laptop & remove the USB Drive (but not your internet access device).

*Boot into your new install and log in

You now should have a semi working laptop, but as Billy Mays often said, "But wait there's more".
Open up the terminal and type in the following commands (or you could copy and paste them)

*

*sudo apt update

*sudo apt dist-upgrade

*Install any updates shown

*sudo reboot

If you are installing 18.04 then your Wifi and MicroSD card reader should be working fine but if you are experiencing system frezes then use the fix in postscript 1, or Wifi stability issues then use the fix in postscript 4. If you are installing version 17.10 or earlier. then follow postscripts 1, 2, 3, & 4 below.

^1 System freezes.
Open up the terminal and type in the following command

*

*sudo thunar

*Navigate to "/etc/default/"

*Open the "grub" file

*On the line "GRUB_CMDLINE_LINUX_DEFAULT" needs to be edited to read
GRUB_CMDLINE_LINUX_DEFAULT="quiet intel_idle.max_cstate=1"

*Save and close the file

*Close the file manager window

Type into the terminal

*

*sudo update-grub

*Let it run it's course

*sudo reboot

*All going well you should not experience any random system freezes

^2 Wifi driver install for version 17.10 or earlier.
Open up the terminal and type in the following commands (or you could copy and paste them)

*

*cd /tmp

*wget https://android.googlesource.com/platform/hardware/broadcom/wlan/+archive/master/bcmdhd/firmware/bcm43341.tar.gz

*tar xf bcm43341.tar.gz

*sudo mkdir -p /lib/firmware/brcm/

*sudo cp fw_bcm43341.bin /lib/firmware/brcm/brcmfmac43340-sdio.bin

*sudo mount -t efivarfs efivarfs /sys/firmware/efi/efivars

*sudo cp /sys/firmware/efi/efivars/nvram-74b00bd9-805a-4d61-b51f-43268123d113 /lib/firmware/brcm/brcmfmac43340-sdio.txt

*reboot

^3 Micro SD Card Reader fix for version 17.10 or earlier.

*

*Open the text editor and type the following text (as shown) into it
# Adjustment to make micro SD card reader work
  options sdhci debug_quirks=0x8000

*Save the file as "sdhci.conf" on the desktop
Open up the terminal and type in the following command

*

*sudo thunar

*Move the "sdhci.conf" file from the desktop to the directory "/etc/modprobe.d"

*Close the file manager window

Type into the terminal

*

*sudo update-initramfs -u -k all

*Let it run it's course

*sudo reboot

^4 Wifi stability fix for version 17.10 or earlier.

*

*Open the text editor and type the following text into it
blacklist btsdio

*Save the file as "fix-wifi.conf" on the desktop
Open up the terminal and type in the following command

*

*sudo thunar

*Move the "fix-wifi.conf" file from the desktop to the directory "/etc/modprobe.d"

*Close the file manager window

Type into the terminal

*

*sudo update-initramfs -u -k all

*Let it run it's course

*sudo reboot

*All going well your Micro SD card reader should now be working and the Wifi should not be working erratically

Note: As of the posting of this "how to" the laptops Bluetooth and sound are not supported and will not work, if you need either of them you will need a USB dongle.

A: The first thing you can try when you have driver issues is to use a more recent kernel. You can install a kernel easily with the Ukuu utility. See the official website.


text:
Q: Swiftmailer - Uncaught Error: Call to undefined method Swift_SmtpTransport::newInstance() I'm trying to send email using the Swiftmailer.
I'm getting an Uncaught Error:

Call to undefined method Swift_SmtpTransport::newInstance().

Here is the code:
require_once 'swift/lib/swift_required.php';

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
      ->setUsername ('email@gmail.com')
      ->setPassword ('password');

$mailer = Swift_Mailer::newInstance($transport);

$message = Swift_Message::newInstance('Weekly Hours')
       ->setFrom (array('email@gmail.com' => 'My Name'))
       ->setTo (array('email@hotmail.com' => 'Recipient'))
       ->setSubject ('Weekly Hours')
       ->setBody ('Test Message', 'text/html');

$result = $mailer->send($message);

Based on the above code, what would be causing that mistake?

A: I'm not quite familiar with SwiftMailer, but from the brief overview of the error you provided, and their documentation page, I can suggest you to try using new operator. From the error, it's clear that
Swift_SmtpTransport class doesn't have a newInstance method, so when you use it to create a new instance, it throws an error. Maybe try using this instead:
require_once 'swift/lib/swift_required.php';

$transport = new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl');
$transport->setUsername('email@gmail.com')->setPassword('password');

$mailer = new Swift_Mailer($transport);

$message = new Swift_Message('Weekly Hours');
$message
   ->setFrom(['email@gmail.com' => 'My Name'])
   ->setTo(['email@hotmail.com' => 'Recipient'])
   ->setSubject('Weekly Hours')
   ->setBody('Test Message', 'text/html');

$result = $mailer->send($message);

Edit: PHP Doesn't allow a direct method call after instantiating an object (without parenthesis). Thanks, Art Geigel.

A: Swift_Mailer::newInstance($transport);

The newInstance method is available in version 5.4, in newer version, it is removed.
Check version in composer.json.
"swiftmailer/swiftmailer": "^5.4"

A: add this lines in file : ./swift/classes/Swift/SmtpTransport.php
/**
 * Create a new SmtpTransport instance.
 *
 * @param string  $host
 * @param integer $port
 * @param string  $security
 *
 * @return Swift_SmtpTransport
 */
public static function newInstance($host = 'localhost', $port = 25, $security = null)
{
    return new self($host, $port, $security);
}

it was deleted in new version, but if you update from github, you need everytime add it


text:
Q: lower level assembly language? (how are processor instructions implemented?) So the lowest level we can "program" is individual instructions on a processor, but those instructions had to be programmed somehow in the first place. How does a processor know what to do when an instruction is run?

A: Useful articles:
http://www.gamezero.com/team-0/articles/math_magic/micro/ How to design a simple processor...
The lecture notes to this course: http://www.stanford.edu/class/ee382/ Processor Design

A: You want this book.

A: It's called "microcode" (or at least that's how it was called when I last looked at those 15+years ago).
The different hardware functional engines in the processor are coordinated with "microcode" software: fetch, decode a "machine code", execute etc.

A: Thinking in simplistic terms as the older processors would do it:
If you look at the instruction bits for most processors you will start to see patterns.  A few bits define one of the input registers, a few bits might define another input register, a few bits might define the result register, and a few bits define the operation.  So some parts of the hardware look at the bits that define operand a and they use that to connect operand a to the alu, other hardware uses the operand b bits to route operand b to the b input on the alu.  Other bits select the operation that the alu is supposed to do, add, and, or xor, etc.  Lastly the results bits route the output of the alu to the register that is to hold the result.   A bit simplistic but at the same time is not that far removed from how logic is written and how traditional processors and many of the smaller ones operate.  This is quite literally how the earliest computers operated, and "programming" them involved routing the answer from this alu into an input on that alu along with an input from the other thing until the result came out the end that you were looking for.
Some of the bigger modern processors are microcoded meaning there is actually another layer of instructions inside, your c = a + b operation may turn into a series of microcoded instructions that are kick started when your machine instruction comes in, and these would help perform the route the inputs to adder logic and the result back to the output types of things.
Logic these days is implemented using programming languages like verilog and vhdl, which are pretty close to existing software programming languages.  The difference being that many of the lines in the "code" execute at the same time, not necessarily in sequential order as you would with normal software.  Given some well written hdl it is not hard to pick up the language and understand what is going on.  You might want to check out opencores.org and grab the source for one of the many processor clones. The compiler tools for hdl is not far removed from that used for software, instead of instructions the code is boiled down into logic or gates, this bit anded with that bit, this bit ored with that bit.  Modules that can be implemented easily in logic and wired together.  And just like you can take a C program and run it on many processors and operating systems, you can take hdl and compile it for the types of gates in different fpgas or logic modules for different foundries.


text:
Q: Citrix won't launch java apps on JDK anymore, only JRE My company has been running java apps in JDK for years.  In production, the apps are accessed through citrix, and we always have installed the JDK in citrix to run the apps.
Lately, we are finding that citrix will not allow us to launch the java apps when the citrix server's JAVA_HOME is set to a JDK...but will launch them fine with the JRE.  Specifically, JDK 1.8.261_64 won't work, but JDK 1.8.251_64 works, as does JRE 1.8.261_64.   Since we need to be on 1.8.261, I guess we need to convert to JRE.
Outside of citrix, these same apps launch indifferent to JRE vs JDK.
Does anyone know of this change or any reason for the difference?  I've tried searching the internet and asking other programmers, but cannot find any information.
Thanks!


text:
Q: How do I make Selenium RC to not move the browser window? Is there a way to specify where Selenium RC spawns the browser window?
When I run my test script, Selenium RC opens 2 windows in the browser, the Selenium RC window and the AUT, and the Selenium RC window takes up most of my screen space. Ideally, I want to control where their location and size separately, but if not, it would be nice to at least make the AUT maximized so that I can eyeball some stuff. Is there a way to do this?
I have tried window_maximize(). Although it does make the AUT window bigger, it is located in the bottom of the screen - only the top 1/4 is visible. I am using Selenium RC with Python on a Mac if that matters.

A: This works from java:
selenium.getEval("this.browserbot.getCurrentWindow().moveTo((" + h + "),(" + v + "))");
selenium.getEval("this.browserbot.getCurrentWindow().resizeTo(" + w + "," + h + ")");


text:
Q: How do I do this math right? $(2 + 3x) * (4 + 5x) = 2(4 + 5x) + 3x(4 + 5x)$
I don't get it. What do I do?

A: The equation you have uses the law of distribution:
$$a(b+c)= ab + ac$$
If you set $a=4+5x$, $b=2$ and $c=3x$, you get the equation in your question.


text:
Q: Unable to setup Twitter auth for React Native app. Error: Unconfirmed callback I have a trouble with that callbacks with Twitter.
I have React Native crossplatform app. Now I'm setting Android's part. There is needed to make some operations to set Twitter Auth. One of is set callback url.
I have Twitter App inside their website called SunyaInnov . I'd been generated consumers keys (both, as expected). Set up callback url there to https://www.google.com.
Inside app I have this:
-AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.foodilog"
android:versionCode="1"
android:versionName="1.0">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="22" />

<application
  android:name=".MainApplication"
  android:allowBackup="true"
  android:label="@string/app_name"
  android:icon="@mipmap/ic_launcher"
  android:largeHeap="true"
  android:theme="@style/AppTheme">
  <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
    android:windowSoftInputMode="adjustResize">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
    </intent-filter>
      <intent-filter>
          <action android:name="android.intent.action.VIEW" />
          <category android:name="android.intent.category.DEFAULT" />
          <category android:name="android.intent.category.BROWSABLE" />
          <data android:scheme="foodilog" />
      </intent-filter>
  </activity>
  <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
  <meta-data
    android:name="com.facebook.sdk.ApplicationId"
    android:value="@string/facebook_app_id"/>
  <meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="**************************"/>
</application>

</manifest>

-login.js file where callback invokes:
import React, { Component } from 'react';
import {
    StyleSheet,
    View,
    Text,
    Image,
    Button,
    TouchableOpacity,
    Navigator,
    Dimensions,
    DeviceEventEmitter,
    NativeModules,
    requireNativeComponent,
    Platform,
    AsyncStorage,
    Linking,
    ActivityIndicator
} from 'react-native';
import CheckBox from 'react-native-icon-checkbox';
import { twitter } from 'react-native-simple-auth'
export default class LoginPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            agree: false,
            isLoading: true
        };
    }
_twitterSignIn() {
    if (this.state.agree) {`console.log("trying to auth with twitter")
        twitter({
          appId: API.TWITTER_CONSUMER_KEY,
          appSecret: API.TWITTER_CONSUMER_SECRET,
          callback: 'foodilog://authorize',
        }).then((info) => {
        console.log(info)
        const { authToken, authTokenSecret } = info;
          if (authToken && authTokenSecret) {
            AsyncStorage.setItem('CurrentSocialLogin', 'twitter');
            AsyncStorage.setItem('FoodilogTwitterToken', authToken);
            AsyncStorage.setItem('FoodilogTwitterTokenSecret', authTokenSecret);
            this.dispatchLogin(API.TWITTER_LOGIN_URL, authToken, authTokenSecret);
          }
          // info.user - user details from the provider
          // info.credentials - tokens from the provider
        }).catch((error) => {
            console.log(error)
          // error.code
          // error.description
        });
}

It's only part of JavaScript file that concerned to signin with twitter.
Problem showed for me is:

Error: Unconfirmed callback.

How can I figure out about how to setup that callback? What have to be on protocol place and host place inside callback.
Also notice: I use react-native-simple-auth package to auth with twitter (I think it's easiest way to auth and have anything necessary). If you have decisions about this let me know also.

A: Do you refer at twitter's settings?
//
Don't use localhost as a callback URL
Instead of using localhost, please use a custom host locally or http(s)://127.0.0.1.
Make sure to add these if you are using Twitter Kit
If you use Twitter Kit for iOS or Android, you will have to use the following callback URLs:
Android - twittersdk://
iOS - twitterkit-CONSUMERKEY://
I recommend you use react-native-twitter-signin


text:
Q: Change flutter-redux store from deep inside a widget tree In my app, the user can open a load a new file and replace the current data model.
Therefore, the app needs to update the outermost flutter-redux store by the just loaded new data model.
As I tried to replace the data just from the callback deep inside the widget tree, flutter reported an error. I suppose due to changed data during widget rendering.
Therefore, I changed the data model update of the store using WidgetsBinding.instance?.addPostFrameCallback:
if ( MainReducerHelper.getNewModelCallback is Function ) {
  WidgetsBinding.instance?.addPostFrameCallback((_) {
    MainReducerHelper.getNewModelCallback( action.newModel );
  });
}

Note, that MainReducerHelper.getNewModelCallback provides a callback, that allows to replace the flutter-redux store of the data model. The callback gets created alongside the first creation of the store.
While that works just fine, I'm not sure, if this is the canonical / right way to do this task.
If not, could you propose a better way? Or just confirm my approach?


text:
Q: Use public functions inside a public function Is it possible to use public functions inside a public function in php?
I got a few public functions which change the input and return it. I want to make a for statement inside a public function that loops through my functions, like:
$input

for= function1 -> output1 -> function2->output2->function3->output3.

I want to use the output of that for my next function. Also the 4 functions I have in my for loop has to loop 9 times.
in this case its about AES encrypt. i got 4 functions called: subBytes, shiftRows, mixColumns, addRoundkey.
This is my public function encrypt:
public function encrypt($input)
{
    $functions= ('subBytes', 'shiftRows', 'mixColumns', 'addRoundKey' );
    foreach($functions as $function)
    {
        $input = $$function($input);
    }

    return($input);
} //end function encrypt

and this is one of my functions:
public function subBytes($state)
{
    for ($row=0; $row<4; $row++){ // for all 16 bytes in the (4x4-byte) State
        for ($column=0; $column<4; $column++){ // for all 16 bytes in the (4x4-byte) State
            $_SESSION['debug'] .= "state[$row][$column]=" . $state[$row][$column] ."-->" . self::$sBox[$state[$row][$column]]."\n";
            $state[$row][$column] = self::$sBox[$state[$row][$column]];
        }
     }
     return $state;
}

A: Use code like this:
$output3 = function3(function2(function1($input)));

Or you can to add your function name into array and iterate over it:
$input = ''; // some value
$functioins = ('function1', 'function2', 'function3', 'function4');
foreach ($functions as $function) {
    $input = $$function($input);
}
$output = $input;

If we try to use public functions of object then:
public function encrypt($input)
{
    // array with methods names
    $methods= array('subBytes', 'shiftRows', 'mixColumns', 'addRoundKey' );
    foreach($methods as $method)
    {
        $input = $this->$method($input);
    }

    return($input);
}


text:
Q: Rickshaw.js gradient color on area chart? I am trying to create an area chart with gradient, like shown in the image.
I don't see where can I specify the gradient. I have created a CSS class and tried to add it to the chart series
var graph_lc2 = new Rickshaw.Graph({
  element: document.getElementById("linechart2"),
  height: 100,
  renderer: 'area',
  stroke: true,
  preserve: true,
  series: [{
    className: 'my-gradient',
    data: seriesData[1],
    name: 'Demo'
  }]
});

Any ideas?


text:
Q: In Chrome settings, which style is used to achieve the box shadow for boxes? In Chrome settings, which styles are used to achive the box shadow for boxes?
E.g.:

A: You can inspect the settings page in much the same way you can inspect any other web page, as they are implemented with HTML and CSS and rendered just like a web page.
Sections of settings are implemented with a component that looks like this:
<dom-module id="settings-section" assetpath="settings_page/" css-build="shadow">
  <template>

[[pageTitle]]

      <slot></slot>

  </template>
  </dom-module>

That scoped style element contains this CSS rule:
#card {
  box-shadow: var(--cr-card-elevation_-_box-shadow);
        background-color: white;
        border-radius: var(--cr-card-border-radius);
        flex: 1;
}

The --cr-card-elevation_-_box-shadow custom property is defined as follows:
--cr-card-elevation_-_box-shadow:  rgba(60, 64, 67, .3) 0 1px 2px 0,
              rgba(60, 64, 67, .15) 0 1px 3px 1px;


text:
Q: iPhone NSNumberFormatter for less than 1 value I have a floating point value
i.e. 0.0467

Want have a string
05
how can get it? Excluding the decimal point (.).
More precisely, if I have a floating point number, I want to divide it to integral and decimal, preferably into two string parts.

A: By following this, you will get desired result.
    float floatValue = 0.0467;
    NSString *str = [NSString stringWithFormat:@"%.2f", floatValue];
    str = [str stringByReplacingCharactersInRange:NSMakeRange(0, 2) withString:@""];
    NSLog(@"%@", str);    // Result will be: 05

A: fDecimal = 0.04567;
NSString * strDecimal = [NSString stringWithFormat:@"%0.2f", fDecimal];
NSString * strDecimalPart = [strDecimal substringWithRange:NSMakeRange(2, 2)];

A: The setting you are looking for is called fraction digits:
NSNumberFormatter* f = [[[NSNumberFormatter alloc] init] autorelease;
[f setMaximumFractionDigits:2];

Optionally you can use -[NSNumberFormatter setRoundingMode:] to specify how rounding should be done.


text:
Q: Photoshop canvas size inaccurate to mm input sizes Just recently when I go to create a new Photoshop (CC2014) document, I put in the document size (e.g. 220 x 158.5mm) but when I open up the canvas size panel the dimensions are different (i.e. 219.96 x 158.5mm). I'm thinking it might be a simple setting but can't seem to find anything. When I change the resolution to pixels/cm instead of pixels/inch it works fine, but I am wanting to use PPI.

A: The size of a document has to be in full pixel increments. That is you can not have half, quarter or 1/π sized pixels. This thus limits the actual sizes you can get.
For example if you want to use 300 dpi to make a 6cm wide document the  closest you can get is:
709 pixels wide  that is 6.002866... cm wide,
next possible increment is,
708 pixels that is 5.9944 cm wide.
Thus, you can not have a 6 cm wide document at 300 dpi. You can have something close, but not exact.


text:
Q: DropdownList com Modal boa tarde.
Tenho uma tela com uma grid feita em webforms, e ao clicar no botão existente na grid, é exibida uma modal com as informações do registro correspondente. Nesta modal tenho alguns dropdownlist ligados a tabelas.
Só que se coloco o evento OnSelectedIndexChanged não abre mais o modal. Alguém já passou por este problema?
Chamada do modal:
System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(@"<script type='text/javascript'>");
            sb.Append("$('#editModal').modal('show');");
            sb.Append(@"</script>");
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditModalScript", sb.ToString(), false);

Aqui o código de criação do dropdownlist:
<asp:DropDownList ID="DDLEditReq" runat="server" DataSourceID="SQLEditRec" style="width:340px"
                                            DataTextField="nome_usuario" DataValueField="id_usuario" ValidationGroup="DDL" AutoPostBack="True"
                                            OnSelectedIndexChanged="ddlb_req"></asp:DropDownList>

E aqui o código da criação da modal:
 <div id="editModal"  tabindex="-1" class="modal hide fade" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">


text:
Q: Error in osm data data import while nominatim installation I am doing nominatim installation on my server. I run the following command
./utils/setup.php --osm-file /usr/share/osm2pgsql/planetfile/planet-latest.osm.pbf --all

to import the pbf file and Few tables are imported successfully and finally at the end of the script I got the following error:
/usr/share/osm2pgsql/osm2pgsql -lSc -O gazetteer --hstore -C 24591 -d nominatim /usr/share/osm2pgsql/planetfile/planet-latest.osm.pbfUsing projection SRS 4326 (Latlong)
NOTICE:  table "place" does not exist, skipping
NOTICE:  type "keyvalue" does not exist, skipping
NOTICE:  type "wordscore" does not exist, skipping
NOTICE:  type "stringlanguagetype" does not exist, skipping
NOTICE:  type "keyvaluetype" does not exist, skipping
NOTICE:  function get_connected_ways(pg_catalog.int4[]) does not exist, skipping
Allocating memory for dense node cache
Allocating dense node cache in one big chunk
Allocating memory for sparse node cache
Sharing dense sparse
Node-cache: cache=24591MB, maxblocks=3147649*8192, allocation method=3
Mid: Ram, scale=10000000

Reading in file: /usr/share/osm2pgsql/planetfile/planet-latest.osm.pbf
Entity: line 1: parser error : Document is empty

^
/usr/share/osm2pgsql/planetfile/planet-latest.osm.pbf : failed to parse
Error occurred, cleaning up
osm2pgsql SVN version 0.80.0 (32bit id space)

DB Error: no such table

Please suggest what can I do to solve this issue. Give me any solution.
Thanks in advance.

A: You could try
apt-get isntall libprotobuf-c0-dev libprotobuf-dev protobuf-c-compiler protobuf-compiler


text:
Q: Bootstrap typeahead updater option I'm trying to use Twitter Bootstrap's typeahead javascript's updater option to retrieve multiple values for the same row then display one column on same selected row on the input box and the other column on another. Unfortunately I cannot seem to find out how below code is not working to update the input box which has an id of ProductName.
$('#ProductName').typeahead({
                source: function(query,process){
                    var query = {query:query};
                    return $.post('/products/ajax_search_product_by_name',query,function(data){
                        return process(data.options);
                    },"json");
                },
                minLength: 3,
                items: 50,
                updater: function(item){
                    lastIndex = item.lastIndexOf('-');
                    length = item.length;

                    var product_id;
                    var product_name;
                    product_id = item.substr(lastIndex + 1, length);
                    product_name = item.substr(0,lastIndex);
                    document.getElementById('ProductName').value = product_name;
                    console.log(product_name);
                }

I read in the documentation that the item has the scope of the typeahead instance:
The method used to return selected item. Accepts a single argument, the item and has the scope of the typeahead instance.

So I tried this instead of using DOM selector but it doesn't work either. I also tried jQuery way of $('#ProductName').val(product_name) but no luck.
Am I missing something here?

A: You are missing something here :)
The updater method isn't supposed to set the value into the input, just to return it.
The actual value setting is done after the updater method is called.
I believe that if you'll end your updater method with:
return product_name;

It should work fine.


text:
Q: Parse a string in c# after reading first and last alphabet I want to cut a string in c# after reading first and last alphabet.
string name = "20150910000549659ABCD000007348summary.pdf";
string result = "ABCD000007348"; // Something like this

string name = "1234 ABCD000007348 summary.pdf";

After reading 1234 "A" comes and at last "s" comes so I want "ABCD000007348"

A: Simply use Regex:
string CutString(string input)
{
     Match result = Regex.Match(input, @"[a-zA-Z]+[0-9]+");
     return result.Value;
}

A: Since you didn't say if it's always a timestamp at the beginning, I've instead opted to iterate over the string to find the first alphabetical character, rather than hardcoding s.Remove(0, n); where n is however many digits are in a timestamp.
string s = "20150910000549659ABCD000007348summary.pdf";
s = s.Replace("summary.pdf", String.Empty);

int firstLetter = 0;

foreach (char c in s)
{
    if (Char.IsLetter(c))
    {
        firstLetter = s.IndexOf(c);
        break;
    }
}

s = s.Remove(0, firstLetter);


text:
Q: Android Development SQLite vs. Hashtable So I'm following a tutorial on how to create a simple Android app that stores a bunch of random quotes. I've noticed that they used a SQLite database and many other Android tutorials uses SQLite to store things. I'm not  very used to SQLite. Can I achieve the same result just by storing the quotes in a hashtable?
What are the differences between a SQLite database and a hashtable in terms of performance?

A:
What are the differences between a SQLite database and a hashtable in terms of performance?

An (in-memory) hash table is (you probably should use HashMap) is going to be faster.  However, it does not address the problem of making your quotes "persist" when your app has shut down.
SQLite is a database, and the main point of a database is that the data persists.
(There are a whole bunch of other benefits in using a database of some kind.  One that is potentially relevant to you is that you can store more stuff in a typical database than you can hold in memory.  The database stores stuff on your device's hard drive / SSD / whatever which has far more capacity than main memory.)

A: http://www.brighthub.com/mobile/google-android/articles/25023.aspx
I suggest SQLite because u can access the database very easily and it is easy to understand and view the database tables also very easy through DDMS plugin for eclipse The above link helps you in DDMS

A: It's up to your intention. If you want to store data such as app preference, user score.. use SQLite. These data will be available for the next launch of application. Hashtable is in memory, of course it is faster than SQLite, all information stored in Hashtable will be lost when the app is deactived or terminated.


text:
Q: Django crontab is not running, even i setup everything I am using crontab in django and my OS is ubuntu
def my_scheduled_job():
    print("1")

This is code in settings.py
CRONJOBS = [
    ('*/1 * * * *', 'stocks.cron.my_scheduled_job')
]

If I run

python3 manage.py crontab run #with hash

it runs the function and print it, but it does not run when I run server. What should I do.
It was my code in crontab
    crontab -e
*/1 * * * * /usr/bin/python3 /home/stockstelegraph/manage.py crontab run 6b918d2422a9f4fce735a3383cee6485 # django-cronjobs

A: Your code actually works. You may be think that print("1") should appear in stdout? So it doesn't work that way, because cron doesn't use stdour and stderr for it's output. To see actual results you should point path to some log file in CRONJOBS list: just put '>> /path/to/log/file.log' as last argument, e.g:
('*/1 * * * *', 'stocks.cron.my_scheduled_job', '>> /path/to/log/file.log')


text:
Q: Batch Recursively Launch Specific .exe In windows I have a batch file, named the same as a folder in its current directory.
I am trying to recursively launch a specific .exe file that is a few folders deep in the above mentioned folder.
I am trying:
set "NAME=DRAGON QUEST XI S.exe"
for /R "%~n0\" %%I in ("%NAME%") do if exist "%%I" start "" /WAIT "%%I"

But that is trying to launch DRAGON.exe, then QUEST.exe, then XI.exe then S.exe and I don't understand why.
I think it will have something to do with quotes, but have tried adding/removing them from everywhere I could see and no luck.
Adding a wildcard to ("%NAME%*") works, but could be troublesome if there is more than one .exe that starts with DRAGON.

A: What you have encountered is caused by something that I consider a terrible design flaw of the for /R loop and expansion of its meta-variable together with the ~-modifiers.
Create the following batch file and execute it:
@for /R "%~dp0." %%I in (foo bar "foo bar" "foo bar?") do @(
    echo/
    echo Modifier '~nx': %%~nxI
    echo No modifiers  : %%I
    echo Modifier '~'  : %%~I
    echo Modifier '~f' : %%~fI
    echo '~' and quoted: "%%~I"
)

The output will be this, given that there are two files foo bar and foo barS available in the directory of the batch file:

Modifier '~nx': foo
No modifiers  : D:\test dir\foo
Modifier '~'  : D:\test dir\foo
Modifier '~f' : D:\test dir\foo
'~' and quoted: "D:\test dir\foo"

Modifier '~nx': bar
No modifiers  : D:\test dir\bar
Modifier '~'  : D:\test dir\bar
Modifier '~f' : D:\test dir\bar
'~' and quoted: "D:\test dir\bar"

Modifier '~nx': "foo bar"
No modifiers  : D:\test dir\"foo bar"
Modifier '~'  : D:\test dir\"foo bar"
Modifier '~f' : D:\test dir\"foo bar"
'~' and quoted: "D:\test dir\"foo bar""

Modifier '~nx': foo bar
No modifiers  : D:\test dir\foo bar
Modifier '~'  : D:\test dir\foo bar
Modifier '~f' : D:\test dir\foo bar
'~' and quoted: "D:\test dir\foo bar"

Modifier '~nx': foo barS
No modifiers  : D:\test dir\foo barS
Modifier '~'  : D:\test dir\foo barS
Modifier '~f' : D:\test dir\foo barS
'~' and quoted: "D:\test dir\foo barS"

It seems that the ~-modifiers (which remove potential surrounding quotation marks) are applied too late, namely after preceding an iterated item with the absolute root path. A standard for loop does not precede anything, so the problem cannot arise and the ~-modifiers may see a quoted string (remove /R "%~dp0." from the batch file, run it again from its parent directory and check quotation in the output).
The line that reflects our situation is the one '~' and quoted: "D:\test dir\"foo bar""; due to its wrong quotation, the command parser unintentionally recognises two different tokens "D:\test dir\"foo and bar"" in the expanded value of "%%~I".

To return to your code, there are the following options to work around the bad behaviour of for /R:

*

*Append a wildcard (best to use ? since it matches just a single character and therefore reduces the chance of matching unwanted items) and then recheck the name of the iterated item:
set "NAME=DRAGON QUEST XI S.exe"
for /R "%~n0" %%I in ("%NAME%?") do (
    if /I "%%~nxI"=="%NAME%" (
        if exist "%%I" (
            ECHO start "" /WAIT "%%I"
        )
    )
)

*Let dir /S return the matching file(s) and use for /F to process its output:
set "NAME=DRAGON QUEST XI S.exe"
for /F "delims=" %%I in ('dir /S /B /A:-D-H-S "%~n0\%NAME%"') do (
    if exist "%%I" (
        ECHO start "" /WAIT "%%I"
    )
)


text:
Q: How to implement ngFor callback in Angular4? I know that there are several questions about this point. I have a table and for each row I've a button to show row's details with a modal, so I need to call a function to initialize these buttons when ngFor has finished to render them.
This external function will add listeners "onClick" to every button to open modal, sadly I can't edit this external function anyway.

A: ngFor is synchounous, so as soon as the ngForOf array is updated during the ngDoCheck lifecycle it will render all items. So you can safely use ngAfterViewChecked in the parent component to perform your logic. When this lifecycle hook is triggered ngFor has added items to the DOM.


text:
Q: how to compare corresponding metrics in prometheus? lets say i have two corresponding tables, table1 and table2, in my database, one-to-one. for creation of each record in each table there is a metric. now, is it possible two use these two metrics(one from table1 and one from table2) to have na information how many records in table1 DOESNT have a corresponding record in table2 in a given moment? can i pass id of the record into metrics somehow?

A: If you're generating metrics for every record and each record has a unique identifier (i.e. label), then you can use the count and by aggregators. For example, count(table_metric{id="foo"}) by (table) would work if they each have a table label.
If the metric names are different, you'll probably want to use the or operator to create a union. For example, count(table_1_metric or table_2_metric) by (id).
In either case, if you want an entry in both tables, you'll want to check to make sure the count is 2.
Finally, just my two cents, but I wouldn't recommend making a habit of putting such high cardinality data into Prometheus. An alternative way of doing this would involve using something like this SQL exporter to generate metrics based off database queries (e.g. SELECT count(*) FROM T1 LEFT JOIN T2 ON T1.ID = T2.ID WHERE T2.ID IS NULL, which would show you how many don't match so you could investigate further).


text:
Q: jQuery - run script only after a specific div is loaded by ajax I want to run a script only when a specific div element is loaded. Since the website is using ajax, that specific div does load at default when the page loads. The div will load only later when a specific task is done.
I have tried the code below but can't make it work. How to do that?
jQuery( function($){

    $(".div_class_here").on("load", function() {

    // my code goes here

});

A: you can run after of load the div with ajax
Example:
jQuery( function($){
    $.ajax({
      method: "GET",
      url: "url",//url get data div
      data: { param: "param"}
    })
      .done(function( result ) {
         $(".div_class_here").html(result);
         // my code goes here
         //run you script here
      })
      .fail(function() {
        alert("error");
      });
})


text:
Q: A box has 100 different balls. No of Balls that can be selected = 1 to 100. How many ways can we select? A box have 100 balls. Each one is different. One boy can take atleast 1, atmost 100 balls. How many WAYS can he take balls ?
( clarification: Taking ball 1 then ball 2 = Taking ball 2 then ball 1 )

A: Each ball is either picked or not, so for each ball we have two possibilities, and so the total number of possible draws is $2^{100}$.
From that we need to subtract one way of picking where none of the balls got picked.
This leaves us with $2^{100}-1$ ways altogether.

A: Hint : The number of subsets of a $n$-elements set is $2^n$ (why and what is the link with the original question ?)


text:
Q: Loop through files in directory specified using argument I'm trying to loop through files in a directory, where the directory is passed through as an argument. I currently have the following script saved in test.sh:
#!/bin/bash
for filename in "$1"/*; do
    echo "File:"
    echo $filename
done

And I am running the above using:
sh test.sh path/to/loop/over

However, the above doesn't output the files at the directory path/to/loop/over, it instead outputs:
File:
path/to/loop/over/*

I'm guessing it's interpreting path/to/loop/over/* as a string and not a directory. My expected output is the following:
File:
foo.txt
File:
bar.txt

Where foo.txt and bar.txt are files in the path/to/loop/over/ directory. I found this answer which suggested to add a /* after the $1, however, this doesn't seem to help (neither do these suggestions)

A: Iterate over content of directory
Compatible answer (not only bash)
As this question is tagged shell, there is a POSIX compatible way:
#!/bin/sh

for file in "$1"/* ;do
    [ -f "$file" ] && echo "Process '$file'."
done

Will be enough (work with filenames containing spaces):
$ myscript.sh /path/to/dir
Process '/path/to/dir/foo'.
Process '/path/to/dir/bar'.
Process '/path/to/dir/foo bar'.

This work well by using any posix shell. Tested with bash, ksh, dash, zsh and busybox sh.
#!/bin/sh

cd "$1" || exit 1
for file in * ;do
    [ -f "$file" ] && echo "Process '$file'."
done

This version won't print path:
$ myscript.sh /path/to/dir
Process 'foo'.
Process 'bar'.
Process 'foo bar'.

Some bash ways
Introduction
I don't like to use shopt when not needed... (This change standard
bash behaviours and make script less readables).
There is an elegant way for doing this by using standard bash, without requirement of shopt.
Of course, previous answer work fine under bash, but. There are some
interresting way for making your script more powerfull, flexible, pretty, detailed...
Sample
#!/bin/bash

die() { echo >&2 "$0 ERROR: $@";exit 1;}            # Emergency exit function

[ "$1" ] || die "Argument missing."                 # Exit unless argument submitted

[ -d "$1" ] || die "Arg '$1' is not a directory."   # Exit if argument is not dir

cd "$1" || die "Can't access '$1'."                 # Exit unless access dir.

files=(*)                                           # All files names in array $files

[ -f "$files" ] || die "No files found."            # Exit if no files found

for file in "${files[@]}";do                        # foreach file:
    echo Process "$file"                            #   Process file
done

Explanation: considering globbing vs real files
When doing:
files=(/path/to/dir/*)

variable $files becomes an array containing all files contained under /path/to/dir/:
declare -p files
declare -a files=([0]="/path/to/dir/bar" [1]="/path/to/dir/baz" [2]="/path/to/dir/foo")

But if nothing match glob pattern, star won't be replaced and array become:
declare -p files
declare -a files=([0]="/path/to/dir/*")

From there. looking for $files is like looking for ${files[0]} ie: first field in array. So
[ -f "$files" ] || die "No files found."

will execute die function unless first field of array files is a file ([ -e "$files" ] to check for existing entry, [ -d "$files" ] to check for existing directory, ans so on... see man bash or help test).
But you could do replace this filesystem test by some string based test, like:
[ "$files" = "/path/to/dir/*" ] && die "No files found."

or, using array length:
((${#files[@]}==1)) && [ "${files##*/}" = "*" ] && die "No files found."

Dropping paths by using Parameter expansion:
For suppressing path from filenames, instead of cd $path you could do:
targetPath=/path/to/dir
files=($targetPath/*)
[ -f "$files" ] || die "No files found."

Then:
declare -p files
declare -a files=([0]="/path/to/dir/bar" [1]="/path/to/dir/baz" [2]="/path/to/dir/foo")

You could
printf 'File: %s\n' ${files[@]#$targetPath/}
File: bar
File: baz
File: foo

A: This would happen if the directory is empty, or misspelled. The shell (in its default configuration) simply doesn't expand a wildcard if it has no matches. (You can control this in Bash with shopt -s nullglob; with this option, wildcards which don't match anything are simply removed.)
You can verify this easily for yourself. In a directory with four files,
sh$ echo *
a       file    or      two

sh$ echo [ot]*
or      two

sh$ echo n*
n*

And in Bash,
bash$ echo n*
n*

bash$ shopt -s nullglob

bash$ echo n*

I'm guessing you are confused about how the current working directory affects the resolution of directory names; maybe read Difference between ./ and ~/


text:
Q: trim spaces on captured group regex after searching everywhere,  How can whitespace be trimmed from a Regex capture group?, seems to have the closest thing, and I can almost taste it,  but still no cigar....
So here goes, for my very first post to StackOverflow.....
I am trying to capture Exactly 27 characters of a string (for reasons that really don't matter).
So I used regex: .{27}
on this string "Joey Went to the Store and found some great steaks!"
the result was "Joey Went to the Store and "
Bingo exactly 27 characters.
But that result is causing errors in my program because of the trailing space. So now I need to also take that result and trim the space after "and " to return the result without the trailing space.   the final result needs to be "Joey Went to the Store and".
here's the kicker, I need it to all work from a single regex because the application can only apply 1 regex (really dumb program, but I'm stuck with it).

A: Take a look at this regex:
^.{26}[^\s]?

It will match 26 characters starting from beginning of line and will match the 27th only if it is not a white space character. See the demo below for more details.
Regex Demo


text:
Q: iOS NSDate() returns incorrect time I am trying to get current date in Swift using NSDate(). When I create breakpoint and stop application, I can see that there is 3 hours difference with devices' system time. Application is running on real iPhone. How to fix this?
I also wrote the following in App Delegate to be sure:
NSTimeZone.setDefaultTimeZone(NSTimeZone(name: "Europe/Kiev")!)

But it still does not work.

A: Here is the conversion for swift 3.0 :
func getCurrentLocalDate()-> Date {
    var now = Date()
    var nowComponents = DateComponents()
    let calendar = Calendar.current
    nowComponents.year = Calendar.current.component(.year, from: now)
    nowComponents.month = Calendar.current.component(.month, from: now)
    nowComponents.day = Calendar.current.component(.day, from: now)
    nowComponents.hour = Calendar.current.component(.hour, from: now)
    nowComponents.minute = Calendar.current.component(.minute, from: now)
    nowComponents.second = Calendar.current.component(.second, from: now)
    nowComponents.timeZone = TimeZone(abbreviation: "GMT")!
    now = calendar.date(from: nowComponents)!
    return now as Date
}

A: It doesn't return the wrong time. It returns exactly the right time. NSDate doesn't have any timezone information. Right now, my computer and your computer will report the exact same time when we call NSDate ().
NSLog displays NSDate in UTC. That's just what it displays. So if we both call NSLog right now, your computer will log the same date and time as mine. Because it is the same date and time.
If you want to process an NSDate (for example, to display the date and time to a user) you use an NSCalendar. The NSCalendar translates between NSDate, which is the same everywhere in the world, to the values that you want to display in your user interface, which will be different in London or in Kiev. If I look on my watch right now, I will see a different time than you see on your watch, and that is what NSCalendar is there for.

A: Also worth checking if your test device Date/Time is set to an older date.

A: For Swift 2.2 this function did the trick for me:
func getCurrentLocalDate()-> NSDate {
    var now = NSDate()
    let nowComponents = NSDateComponents()
    let calendar = NSCalendar.currentCalendar()
    nowComponents.year = NSCalendar.currentCalendar().component(NSCalendarUnit.Year, fromDate: now)
    nowComponents.month = NSCalendar.currentCalendar().component(NSCalendarUnit.Month, fromDate: now)
    nowComponents.day = NSCalendar.currentCalendar().component(NSCalendarUnit.Day, fromDate: now)
    nowComponents.hour = NSCalendar.currentCalendar().component(NSCalendarUnit.Hour, fromDate: now)
    nowComponents.minute = NSCalendar.currentCalendar().component(NSCalendarUnit.Minute, fromDate: now)
    nowComponents.second = NSCalendar.currentCalendar().component(NSCalendarUnit.Second, fromDate: now)
    nowComponents.timeZone = NSTimeZone(abbreviation: "GMT")
    now = calendar.dateFromComponents(nowComponents)!
    return now
}

If you want a different timezone you can change it directly, or even better, pass it as a function parameter.

A: You can also use Locale to get current time and date.
        let today = NSDate()
        let locale = NSLocale.current
        print("Time of today: \(today.description(with: locale))")

A: This func returns Now in a current time zone.
func convertDate(date:Date) -> Date {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    var comp = DateComponents()
    let calendar = Calendar.current
    comp.year = Calendar.current.component(.year, from: date)
    comp.month = Calendar.current.component(.month, from: date)
    comp.day = Calendar.current.component(.day, from: date)
    comp.hour = Calendar.current.component(.hour, from: date)
    comp.minute = Calendar.current.component(.minute, from: date)
    comp.second = Calendar.current.component(.second, from: date)
    comp.timeZone = TimeZone(abbreviation: "GMT")
    var dateFromCalendar = Date()
    if let calendarDate = calendar.date(from: comp) {
        dateFromCalendar = calendarDate
    }
    return dateFromCalendar
}

To use:
    let now = Date()
    let convertedDate = convertDate(date: now)


text:
Q: Current Iteration Query Script Devops Looping Through Projects I'm trying to put a script together that will let me loop through projects and create queries relevant to the current iteration.
I can loop through and create queries until it comes to looking at the iteration path and then it doesn't seem to like it.
When I run my script all of the other queries are created, and this one is as well, but it brings up an error when I go to look at it because it's posting that it's not in the right form.  How can I get this query to loop through like the others and bring back the appropriate team in the process?

I'm assuming that somehow I've got to put project and team as variables? I tried $project as well but that just presented a similar error.  Although I'm also confused about about the "" since the code doesn't like that either, and it won't even create the query when I've tried that.

    $JSON27 = @'
    {
      "name": "Current Sprint Query", "wiql": "SELECT [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State],[System.Tags],[Microsoft.VSTS.Scheduling.OriginalEstimate],[Microsoft.VSTS.Scheduling.CompletedWork],[System.IterationPath] FROM workitems WHERE [System.TeamProject] = @project AND [System.WorkItemType] <> '' AND [System.State] = 'Closed' AND [System.IterationPath] = @CurrentIteration('[Project]/Team')  ORDER BY [System.WorkItemType]"
      }
'@

 $response27 = Invoke-RestMethod -Uri $url1 -Headers @{Authorization = "Basic $token"} -Method Post -Body $JSON27 -ContentType application/json

A: Summarizing the discussion in comments as an answer below:
So, as the error message calls out, I think the issue is that you have @CurrentIteration('[Project]/Team') in your query instead of @CurrentIteration('[Project]\Team').
Your query should be this instead:
$JSON27 = @'
    {
        "name": "Current Sprint Query", "wiql": "SELECT [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State],[System.Tags],[Microsoft.VSTS.Scheduling.OriginalEstimate],[Microsoft.VSTS.Scheduling.CompletedWork],[System.IterationPath] FROM workitems WHERE [System.TeamProject] = @project AND [System.WorkItemType] <> '' AND [System.State] = 'Closed' AND [System.IterationPath] = @CurrentIteration('[Project]\Team')  ORDER BY [System.WorkItemType]"
    }
'@

EDIT:
By default, shared queries and new queries are scoped to the current project. For querying across multiple projects, you can add the TeamProject field to filter to a select number of projects as:
..
AND [System.TeamProject] IN ('Project 1', 'Project 2', 'Project 3')

However, using the @CurrentIteration macro would need you to select a Team and may not work across Projects and Teams. Check this idea on Developer Community for more details.

A: Please refer to the following script to get the project name first, and then create a query by looping through the obtained project name.
Please use @CurrentIteration('[Project]\\Team') instead of @CurrentIteration('[Project]/Team') or @CurrentIteration('[Project]\Team')
$token = "your PAT"

$url="https://dev.azure.com/org name/_apis/projects?api-version=6.0"

$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))

$response = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Basic $token"} -Method Get -ContentType application/json

echo $url

foreach ($project in $response.value.name){

  $url3="https://dev.azure.com/org name/$($project)/_apis/wit/queries/My Queries?api-version=6.1-preview.2"

  echo $url1

  $body = "{
    `"name`": `"query name`",
    `"wiql`": `"Select [System.Id], [System.State] From WorkItems where [System.IterationPath] = @CurrentIteration('[$project]\\$project Team') `"
        }"

echo $body

$response3 = Invoke-RestMethod -Uri $url3 -Headers @{Authorization = "Basic $token"} -Method Post -Body $body -ContentType application/json

echo $response3

 }


text:
Q: Rest-api call is not sent in Angular 6 and RxJS I have this method in the component:
saveItem() {
   return this.itemService.updateItem(this.item)
     .pipe(
       tap((data: any) => {
         this.toastr.success('Saved');
       }),
       catchError((error: any) => {
       return throwError(error.error);
      }
    )
  )
}

And this is the function inside the itemService:
updateItem(item: Item) {
    return this.http.post<any>(this.updateItemUrl, {
        item: item
    });
}

If I put a breakpoint inside the saveItem() on the line 'return this.itemService.updateItem(this.item)', and if I put a breakpoint inside the updateItem() on the line 'return this.http...', it correctly goes and stop into the breakpoints...
But I have the following issue: the rest-api calling is not triggered, and the http call is not sent.. in fact, if a I put a breakpoint inside the .pipe() operator, it doesn't go inside. Why?

A: Observables (like http-Requests) get only active when they have at least one subscriber.
=> No Subscriber => No Http-Request
You can subscribe explicitly by
myObservable.subscribe()

or implicitly by the async pipe in the html template
<span> {{ myObservable | async }} </span>

warm regards


text:
Q: Find all primes $p$ for which $19 p - 1$ is a perfect cube I set the equation to $19 p - 1 = n^3$, then got $19 p =(n+1)(n^2-n+1)$. I don't know what to do now.

A: Because $19$ is a prime, as long as $n+1,n^2-n+1 \gt 1,$ which is any time $n \gt 1,$ you need one of the factors on the right to be $19$ and one to be $p$.  That is not many possibilities.

A: $$ 19p = (n+1)(n^2 - n + 1)$$
Note that
$$ gcd(n+1, n^2 - n + 1) = gcd(n+1, (n+1)^2 - 3n)  = gcd(n+1, -3n) \in \{1, 3\}$$
Hence we have the following cases:

*

*If $gcd(n+1, n^2 - n + 1) = 3$, there are no solutions since we have $3^2$ on the RHS

*If $gcd(n+1, n^2 - n + 1) = 1$,
2a.$19 = n+1 \implies p = n^2-n+1 = 307$
2b. $19 = n^2 - n + 1 \implies n^2-n-18 = 0 \implies n=\frac{1\pm\sqrt{73}}{2}$
Hence $\boxed{p = 307}$ (case 2a) is the only solution. $19*307 - 1 = 18^3$

A: $n+1=m,n^2-n+1=(m-1)^2-(m-1)+1=m^2-3m+3$
$\implies(n+1,n^2-n+1)$ must divide $3$
If $3$ divides $n+1,3^2$ will divide $19p$ which is impossible $\implies p\ne19$
Now $n+1$ must divide $19p$ so, is one of $1,p,19,19p$
Check all four cases


text:
Q: CSS: Overflow hidden Consider the following HTML + CSS code:

  <form style='background-color: blue'>
    <input type='text' style='width:100%'>
    <textarea style='width: 100%'></textarea>
    <button type='submit' style='float: right'>send</button>
  </form>

Since the submit <button> is overflowing its parent <form> element, I would expect that overflow: hidden should (at best) clip the button and turn the rest invisible:

  <form style='background-color: blue; overflow: hidden'>
    <input type='text' style='width:100%'>
    <textarea style='width: 100%'></textarea>
    <button type='submit' style='float: right'>send</button>
  </form>

However, this is not the case. Instead of clipping the overflowing content, the parent element <form> was increased in order to contain all its content, including the overflowing <button>.
Over the web there are some hints about the reason for that. Example: "The overflow property only works for block elements with a specified height.", w3schools. Even so I'm still unsure of the reason why this happened.
Question
Why this happened?


text:
Q: Ionic - Unexpected token. A constructor, method, accessor, or property was expected I want to do news sharing function in my ionic2 apps, and I get this code from ionic document but still showing error.
This is qq sharing, sharing with news text, image, audio, and I also want to know is it ionic got shareSdk like MOB can derictly share with all platform, bcz I have to develop fb, weibo, wechat too. Too many coding
news.ts
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { NewsDataProvider } from '../../providers/news-data/news-data';

import { QQSDK, QQShareOptions } from '@ionic-native/qqsdk';

@Component({
  selector: 'page-news-detail',
  templateUrl: 'news-detail.html',
})
export class NewsDetailPage {
    new: any;
    constructor(public navCtrl: NavController,
        public navParams: NavParams,
        public newsData:NewsDataProvider,
        private qq: QQSDK) {
        this.new = navParams.get('new');
  }

  share(){
    this.qq.shareText(shareTextOptions)
       .then(() => {
          console.log('shareText success');
       })
       .catch(error => {
          console.log(error);
       });

    this.qq.shareImage(options)
       .then(() => {
          console.log('shareImage success');
       })
       .catch(error => {
          console.log(error);
       });
    }

    this.qq.shareNews(options)
       .then(() => {
          console.log('shareNews success');
       })
       .catch(error => {
          console.log(error);
       });
    }

    this.qq.shareAudio(options)
       .then(() => {
          console.log('shareAudio success');
       })
       .catch(error => {
          console.log(error);
       });
      }

}

Here is the error in my terminal


text:
Q: How to resolve "You are not running your eclipse instance with java 8" for JavaFX in Eclipse Mars 2.0 The error "You are not running your eclipse instance with java 8" appears after installing javaFX in Mars 2.0 on a Windows computer, and states the plugin is shut off because of this. How can this be fixed?

A: The way to resolve the "You are not running your eclipse instance with java 8" issue for Eclipse Mars 2.0, is to:

*

*1: Go here the place to download java 8. It has the number then u for update, and then number for whatever update after it. Eg. I downloaded "Java SE Development Kit 8u171".

*2: Find the newly downloaded application and run it. Eg. I found where I saved "jdk-8u171-windows-x64".

*3: During installation there dosen't need to be any changes made to the wizard or preferences set, just keep clicking next and agreeing to things.

*4: When the installation is done, open Eclipse, and you should see the error no longer appears. If you go to File > New > Other the folders presented will now include a folder called JavaFX, from which you can click on, and choose JavaFX project to make a new JavaFX project.


text:
Q: Java: Access button in another class from thread I have class1 and class2. Class1 is a UI, class2 makes changes to the UI. Class2 is shown below.
1) Is there a way to allow the entire class2 to use objects of class1 (JButton btnStartFullBuild, JButton btnShutdownServer, etc)
2) How do I allow the thread to change the background color of the button in Class1
(using: btnShutdownServer.setBackground(Color.blue); )
package examples;
import java.awt.Color;

import javax.swing.JButton;

public class Class2 {

    public static void shutdownServer(JButton btnStartFullBuild, JButton btnShutdownServer) {
// This works
        btnShutdownServer.setBackground(Color.blue);
// This works when passing text, but I cant modify other classes buttons
        new ThreadTest("Can I modify a button?").start();
    }

}
class ThreadTest extends Thread {
    public ThreadTest(String str) {
        super(str);
    }

    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Loop " + i + ": " + getName());
            try {
                sleep((int) (Math.random() * 2000));

            } catch (InterruptedException e) {
            }
        }
    }
}

A: Yes, but you probably don't want to, as Class2 could do all sorts of nasty things you don't want it to, like remove the buttons and other components
A better solution would be to use an Observer Pattern to allow Class2 to generate notifications that interested parties can respond to.
Also, Swing is not thread safe, so be careful when trying to modify the state of the UI from outside the context of the EDT.
Take a look at Concurrency in Swing for more details and other possible options, like SwingWorker (which has PropertyChange support)

A: I agree with the previous answer that this isn't the most elegant solution, but...it looks like it would be possible to do this with SwingUtilities.invokeLater:
// from inside your current run method
public void run() {
    for (int i = 0; i < 5; i++) {
        ...
    // access button here
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            btnShutdownServer.setBackground(Color.blue);
        }
    });

I'm no Swing expert, found this solution here: http://www.javamex.com/tutorials/threads/invokelater.shtml


text:
Q: Flask app deployment with dokku I`m trying to deploy helloworld Flask app with Dokku following the manual.
Requirements:
Flask==0.9
Jinja2==2.6
Werkzeug==0.8.3
gunicorn==0.17.2

Procfile:
web: gunicorn wsgi:app -b 127.0.0.1:$PORT

wsgi.py:
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

docker container listens to port 49153
wget 127.0.0.1:49153 gives me
Connecting to 127.0.0.1:49153... connected.
HTTP request sent, awaiting response... No data received.
Retrying.

docker logs gives no errors:
2014-02-01 08:35:03 [10] [INFO] Starting gunicorn 0.17.2
2014-02-01 08:35:03 [10] [INFO] Listening at: http://127.0.0.1:5000 (10)
2014-02-01 08:35:03 [10] [INFO] Using worker: sync
2014-02-01 08:35:03 [15] [INFO] Booting worker with pid: 15

How can I debug this error?

A: try update dokku to stable, or setup dokku on clean ubuntu

A: There is something wrong with your Procfile. You should not specify Flask to listen on 127.0.0.1 only. Try 0.0.0.0 instead.
Thus, I suggest you can modify your Procfile to be like this:
web: gunicorn wsgi:app -b 0.0.0.0:$PORT

A: don't specify host and port in your Procfile,
web: gunicorn wsgi:app is enough


text:
Q: ncmpcpp and mpd: jump to marked song after finishing current song I just started using ncmpcpp for the first time, moving from Clementine. In Clementine you can mark a song for playing next, ie. after current song is finished (with Ctrl + D). Is it any similar functionality in ncmpcpp? If not, is there a way I can add it?

A: select the song that you want to add, press a choose current playlist then choose after current song


text:
Q: CSV Files in Paraview I've been following Paraview's documentation for loading in csv files. I have one loaded in and ready to use, but i'm not entirely happy with the processes they've suggested. As both apply to dots and apply to grid points are both pretty ugly...
I'm using the dataset 'Sally', which as my lecturer suggested is apparently pretty well known (looks like a tornado or something). The dot layout of the data make it look like a tornado, but all the dots are set to one colour... How can i map different colours to different layers of the data?
Thank you

A: Here is how to Open your csv file in ParaView and load it as a Geometry.

*

*File -> Open -> Select your csv file -> Apply

*Filters -> Tables To Points -> Set X, Y and Z -> Apply

You know have a polydata with a lot of points. If you want to have coloring based on a parameters, you have to compute some data on the dataset, as your csv file does not seem to contain any.
For example :

*

*Filters -> Elevation -> Z axis -> Apply

Can be what your are looking for.


text:
Q: How can i run the report without specifying the parameter value in SSRS H, I have a parameter 'Client' as drop down in SSRS report. My requirement is to select all the records for all the clients if i don't select any parameter value and if i select particular value in the drop down,i need to display records for the that particular client.
I am getting the list of clients as a input from query.How can i add option select all by default.
Thanks in advance

A: You can do this a few ways...

*

*Check the "Allow Multiple values" on the general tab of the Parameter Properties, go into the Available values and select the dataset you are using to get the values, make sure the the column that contains the actual data to search on is what you select for the VALUE field...(with this one - make sure your query eliminates the NULLs for the Value field)  then you will have a drop down with all the values and it will add Select All...

*
Then in the Default Values tab, you can hook to the same query and select the VALUE field again... (as long as there aren't any NULLS) You may need to do tweaking depending on your query and values...

or

*

*You can check the "Allow Null Value" on the General tab in the Parameter Properties, then in the Default Values - select "Specify Values", then Add, and (null) pops in there automatically...

*Then call a stored procedure where the parameter defaults to NULL and if you pass NULL or don't pass in a string of values, your query will return all (not sure how you'd implement this if your query is embedded in the report... I try to do all of mine in Stored Procedures..)

A: Add "All" to the results of the query that returns a list of clients for the drop-down and make it the default selection.  Then handle it in your main stored procedure that if "All" was selected, you don't filter by clientId, and just get all clients.


text:
Q: Notation for nested factors that are random variables in R I need to compute the estimate the variance component for my data.
I have the following model, y = gene, cell line, gene*cell line, DNA extract[cell line]
How do I write this for the lme function?  I am confused on how to indicate that "DNA extract" is nested within "cell line" and also have it marked as a random variable.

A: Try:
lmer(y ~ gene + cell-line + gene*cell-line + (1|cell-line/DNA-extract))

Assuming that gene and cell-line are numeric, you'll need to make sure that your factors are identified as such in your data frame otherwise R will analyse them incorrectly. If they're character, you're fine.

A: If the nesting within the function does not work then it may be usefull to create an extra variable where DNA extract is already in the right order:
y = gene, cell line, gene*cell line, Ordered_DNA extract


text:
Q: Gaussian prime proof Prove or disprove that if $a+bi$ is a Gaussian prime, where a and b are nonzero, then $N(a+bi)$ is a rational prime.
I am pretty sure that there is a theorem that states this, but I'm not sure how to prove it.

A: How about trying some examples?  How about $3$?  How about $1+i$?  How about $2+i$?  How about $3+2i$?  How about $7$?  These are all Gaussian primes... which you should check, also.
Don't be allergic to numbers.  Numbers are your friends!


text:
Q: Jquery alternate way of calling :first I am using cheerio which is like jQuery for node.js, but :first is not available.
I want to use something like
var title = $(this).find('td:not([rowspan]):first').text();

So when I am grabbing data I can ignore all td elements that have [rowspan]. For most of the data it looks like

    Title
    somethingelse

    Title
    somethingelse

    Title
    somethingelse

    3
    Title
    somethingelse

Since there are no classes I need to grab the $('td:nth-child(1)') or  $('td:first') element, but in some cases its actually the second element.

A: Use .eq(0):
var title = $(this).find('td:not([rowspan])').eq(0).text();

A: You need to use the :first-child or :first-of-type and not :first:
var title = $(this).find('td:not([rowspan]):first-child').text();
var title = $(this).find('td:not([rowspan]):first-of-type').text();

If the above both doesn't work, you need to loop through to satisfy the stuff and once done, you can break.

A: maybe you can use .eq(0) to get the first element of the colection
$('td').eq(0)

A: If this is referring to the tr then you can use .first()
var title = $(this).find('td:not([rowspan])').first().text();

A: you can use nth-child(1)
var title = $(this).find('td:not([rowspan]):nth-child(1)').text();


text:
Q: variable variables in php with mysql_result this is my problem:
echo "SELECT * FROM fornitori_elatos WHERE NomeFornitore = '".${mysql_result($elenco_fornitori,$k,"NomeFornitore")}."';";

generate this error:

PHP Fatal error:Function name must be a string

can you help me?

A: Try this
echo "SELECT * FROM fornitori_elatos WHERE NomeFornitore = '".mysql_result($elenco_fornitori,$k,"NomeFornitore")."';";


text:
Q: Child views in a custom viewgroup not following boundaries I am creating a custom layout (viewgroup subclass) that divides the itself into cells, then positions child layouts based on their cell position and cell width/height.
Think of it like how widgets are organized.
I added a bunch of frame layouts with different background colors, and they seem to position correctly. However when I put in a textview, it expands well beyond that vertically and stays at a fixed width horizontally. The position works correctly though.
Code:
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

public class DynamicLayout extends ViewGroup {

int numCellsX = 6, numCellsY = 8;
int cellSize;

int blockMap[];

public DynamicLayout(Context context) {
    super(context);

    init();
}

public DynamicLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public DynamicLayout(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

private void init()
{
    blockMap = new int[numCellsX * numCellsY];
    clearBlockMap();
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    cellSize = getMeasuredWidth() / numCellsX;

    int specWidth = MeasureSpec.getSize(widthMeasureSpec);
    int specHeight = MeasureSpec.getSize(heightMeasureSpec);

    this.setMeasuredDimension(specWidth, specHeight);

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    if (getChildCount() > 0) {
        int wspec = MeasureSpec.makeMeasureSpec(getMeasuredWidth()
                / getChildCount(), MeasureSpec.EXACTLY);
        int hspec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(),
                MeasureSpec.EXACTLY);
        for (int i = 0; i < getChildCount(); i++) {
            View v = getChildAt(i);
            v.measure(wspec, hspec);
        }
    }
    Log.i("DYNA", "Measured");
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    Log.i("DYNA", "On Layout");

    clearBlockMap();

    for (int i = 0; i < getChildCount(); i++) {
        View v = getChildAt(i);

        if (v instanceof DynaServiceView) {
            DynaServiceView serviceView = (DynaServiceView) v;

            if (serviceView.getVisibility() == GONE)
                continue;

            int x = serviceView.getXPos();
            int y = serviceView.getYPos();
            int width = serviceView.getXCells();
            int height = serviceView.getYCells();

            //Is the thing too big?
            if (width > numCellsX)
            {
                Log.i("DYNA", "Warning, service too big, shrinking to size");
                width = numCellsX;
                serviceView.setWidth(width);
            }

            //Is there space?
            if (checkBlockMap(x, y, width, height))
            {
                Log.i("DYNA", "Found collision at child " + i +", resolving...");
                //Find somewhere to put this
                boolean foundSpot = false;
                for (int j = y; j <= numCellsY - height; j++)
                {
                    for (int k = x; k <= numCellsX - width; k++)
                    {
                        if (!checkBlockMap(k, j, width, height))
                        {
                            x = k;
                            y = j;
                            foundSpot = true;
                            break;
                        }
                    }

                    if (foundSpot)
                        break;
                }

                if (!foundSpot)
                    Log.i("DYNA", "No spot for child at: " + i + ", skipping!");
                else
                    Log.i("DYNA", "Resolved! New X/Y: " + x + ", " + y);
            }

            setBlockMap(x, y, width, height);

            //Has spot now, set layout
            serviceView.layout(l + (x * cellSize), t + (y * cellSize), (x * cellSize)
                    + (width * cellSize), (y * cellSize)
                    + (height * cellSize));
        }

    }
}

private boolean checkBlockMap(int x, int y, int width, int height)
{
    for (int  j= y; j < y + height; j++)
    {
        for (int k = x; k < x + width; k++)
            if (blockMap[(j * numCellsX) + k] == 1)
                return true;
    }
    return false;
}

private void setBlockMap(int x, int y, int width, int height)
{
    for (int  j= y; j < y + height; j++)
    {
        for (int k = x; k < x + width; k++)
            blockMap[(j * numCellsX) + k] = 1;
    }
}

private void clearBlockMap()
{
    for (int i = 0; i < blockMap.length;i++)
        blockMap[i] = 0;
}
}

Here is a picture explaining the problem. On the right you can see the layout's borders line up correctly, however on the left it's obvious that the child text view is not following it.

A: Found out the issue.... onMeasure wasn't setup correctly. Stupid mistake.