text:
Q: Grails logging domain class not logging to stdout All my logging statements from Domain Classes never end up in the my 'stdout'.
I thought this line should do the trick:
stdout: 'grails.app.domain',

It works for all other stuff Servics, Cotrollers but not for Domain classes.
log4j = { root->
    appenders {
        console name:'stdout'
        rollingFile name:'file', maxFileSize: 5000000, maxBackupIndex:10, file:"${catalinaBase}" + File.separator + "logs" + File.separator + "tao.log"
        appender new EventLogAppender(source:'SC', name: 'eventLogAppender', layout:new EnhancedPatternLayout(conversionPattern: '%d{DATE} %5p %c{1}:%L - %m%n %throwable{500}'), threshold: org.apache.log4j.Level.ERROR)
    }

    error  'org.codehaus.groovy.grails.web.servlet',        // controllers
           'org.codehaus.groovy.grails.web.pages',          // GSP
           'org.codehaus.groovy.grails.web.sitemesh',       // layouts
           'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
           'org.codehaus.groovy.grails.web.mapping',        // URL mapping
           'org.codehaus.groovy.grails.commons',            // core / classloading
           'org.codehaus.groovy.grails.plugins',            // plugins
           'org.codehaus.groovy.grails.orm.hibernate',      // hibernate integration
           'org.springframework',
           'org.hibernate',
           'net.sf.ehcache.hibernate'

    all file: 'grails.app.controllers',
        stdout:'grails.app.controllers',
        eventLogAppender:'grails.app.controllers'

    all file: 'grails.app.services',
        stdout:'grails.app.services',
        eventLogAppender:'grails.app.services'

    all file: 'grails.app.domain',
        stdout: 'grails.app.domain',
        eventLogAppender:'grails.app.domain'

    all file: 'grails.app.jobs',
        stdout:'grails.app.jobs',
        eventLogAppender: 'grails.app.jobs'

    all file: 'grails.app.conf.Config',
        stdout:'grails.app.conf.Config',
        eventLogAppender:'grails.app.conf.Config'
}

A: For me the class/package "wildcard"-definition were always not clear, till I found a simple trick. In your class add:
println log.name

and the output is the desired class name to be included into the log4j config


text:
Q: Azure App Service Docker - Add file after deployment I'm trying to as much of my CI/CD process automated. Here is what I've got at this point:

*

*Azure App Service using a docker container.

*Azure DevOps code repository.

*Right now using Docker Hub as the repo for my docker container. Can move to Azure later.

I can push code to the repo, it builds the new image, pushes it to Docker Hub, once thats done it gets deployed to the Azure App Service just fine.
Where I'm running into issues is we have a Laravel app that is being deployed via this container. With Laravel there is an .env file that I don't want to push up to the code repository. How would one go about moving a file into the container once it's been deployed?
All I've been finding is how to do it via SSH or through the startup command, but all the examples assume the file is on the image.
Thanks for any tips/tricks/links/etc!! I've got a feeling this is one of those "ahh that was easy" things and what I'm searching just isnt the right verbiage.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to access database from server and my hosting is linux shared hosting I have an Linux shared hosting space. I am trying to connect through the IP of my hosting space to WORK LIGHT server.set the hosting IP in mysql.Xml file. but am Success fully create a app in localhost its working fine in simulator. when am trying to test the app in android device it didn't access the database. please some body help me how to access the database in device.either I need to purchase VIRTUAL PRIVATE DEDICATED SERVERS  to host my app database in those hosting space

A: Worklight does not work that way.
You need a host machine on top of which you should have either Tomcat, WebSphere or WebSphere Liberty profile installed. On top of this installation you deploy the Worklight Server (read the documentation).
The IP of the server is the IP of the host machine.
When you build your Worklight-based application, you build it with the IP address mentioned above (read the documentation). When launching the app and attempting to connect to the server/invoking an adapter procedure, the attempt will be done against that IP address.
That's called "on-prem", when you setup the server on your own infrastructure.
You do not try to connect your "remote host" to the "local server".
Frankly, I'm not sure what you're trying to do.
Please, stop developing.
Read the documentation, read it.
Knowledge Center: http://www-01.ibm.com/support/knowledgecenter/SSNJXP/welcome.html
Developer Center: https://developer.ibm.com/mobilefirstplatform


text:
Q: Symfony2\Doctrine - Retrieving User Roles I'm trying to set up my User entity to use roles, and following the documentation at http://symfony.com/doc/current/cookbook/security/entity_provider.html
Users work fine, and if I hardcode the $roles value everything works as expected, log in/out is good, etc. But, if I try and retrieve the roles through a many-to-many relationship as outlined in the documentation I get back null.
I should also mention that after creating the entities when I ran 'php app/console doctrine:schema:update --force' it created the role table, but not the 'user_role' table as it said it would. I went ahead and created it manually and entered a row for the user I was testing with, but that was my first clue something wasn't working. It's really frustrating because I followed the documentation and it looks like it should work.
The error I get back while trying to log-in is:
FatalErrorException: Error: Call to a member function toArray() on a non-object

Which points to return $this->roles->toArray() in the user entity.
My User Entity (the relevant bits):
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="ACME\MyBundle\Entity\UserRepository")
 *
*/

class User implements UserInterface, \Serializable
{

 ...
      /**
     * @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
     *
     */
    private $roles;
...
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->roles = new ArrayCollection();
    }

    public function getRoles()
    {
        return $this->roles->toArray();
    }
 ...
}

My Role Entity:
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="role")
 * @ORM\Entity()
 */
class Role implements RoleInterface
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(name="name", type="string", length=30)
     */
    private $name;

    /**
     * @ORM\Column(name="role", type="string", length=20, unique=true)
     */
    private $role;

    /**
     * @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
     */
    private $users;

    public function __construct()
    {
        $this->users = new ArrayCollection();
    }

    /**
     * @see RoleInterface
     */
    public function getRole()
    {
        return $this->role;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Role
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set role
     *
     * @param string $role
     * @return Role
     */
    public function setRole($role)
    {
        $this->role = $role;

        return $this;
    }
}

Does anybody see a problem in my code or have experience with this same issue? I'm stuck at the moment.

A: In your entity Role you have
 * @ORM\Table(name="role")

change it to
* @ORM\Table(name="user_role")

because your table name is user_role not role

A: I had the same probleme and i removed the toArray methode
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="ACME\MyBundle\Entity\UserRepository")
 *
*/

class User implements UserInterface, \Serializable
{

 ...
      /**
     * @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
     *
     */
    private $roles;
...
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->roles = new ArrayCollection();
    }

    public function getRoles()
    {
        return $this->roles;//return $this->roles->toArray();
    }
 ...
}


text:
Q: Error on DB connection when trying to build forms and bpm from deployment->docker when i tried to build formsflow-form,formflow-bpm ,keycloak etc from deployment docker i got error saying "could not connect to database". But i can build all these seperately.

A: It looks like from the error logs you are missing environment variables for database which is required to set up forms-flow-ai in Docker. You can checkout the Installation steps of formsflow.ai solution in docker and follow along it to resolve the issue.


text:
Q: Infinite Scroll does not scroll My code scrapes titles of youtube videos, but doesnt scroll down to scrape all titles.
When selenium opens the browser, it doesnt even scroll at all. How can i modify the code to scroll down infinitely and eventually scrape all titles.
import time
from selenium import webdriver
from bs4 import BeautifulSoup
import requests
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager

options = Options()
driver = webdriver.Chrome(ChromeDriverManager().install())
url='https://www.youtube.com/results?search_query=doctor'
driver.get(url)
content=driver.page_source.encode('utf-8').strip()
soup=BeautifulSoup(content,'lxml')
SCROLL_PAUSE_TIME = 0.5

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)
    titles = soup.findAll('a', id='video-title')
    for title in titles:
        print(title.text)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

A: You are using scrollHeight to get current height, but that value doesn't change when you scroll. Look here to see that you should use scrollTop instead. It also says that you should use this equation to detect if the scroll is at bottom:
element.scrollHeight - element.scrollTop === element.clientHeight

A: This works fine for me.
import time
from selenium import webdriver
from bs4 import BeautifulSoup
import requests
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager

options = Options()
driver = webdriver.Chrome(ChromeDriverManager().install())
url='https://www.youtube.com/results?search_query=doctor'
driver.get(url)
content=driver.page_source.encode('utf-8').strip()
soup=BeautifulSoup(content,'lxml')
SCROLL_PAUSE_TIME = 1

# Get scroll height
last_height = driver.execute_script("return document.documentElement.scrollHeight")

while True:
    # Scroll down to bottom
    print('In While True')
    driver.execute_script("window.scrollTo(0, arguments[0]);", last_height)
    print('executed')
    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)
    print('slept')
    titles = soup.findAll('a', id='video-title')
    for title in titles:
        print(title.text)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.documentElement.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height


text:
Q: Extending Kafka's Retention Policy There are two out of the box retention policies (message deletion strategy) for topics; delete and compact.
Former will delete messages based on log file size or date, latter will delete duplicate messages periodically by using message key. I'm wondering if there was a mechanism to extend Kafka's Log Compaction functionality? for example cleaning messages by an expiration date or other custom criteria?

A: you can use broker configs such as:
log.retention.bytes
The maximum size of the log before deleting it.
log.retention.hours
The number of hours to keep a log file before deleting it (in hours), tertiary to log.retention.ms property.
log.retention.minutes
The number of minutes to keep a log file before deleting it (in minutes), secondary to log.retention.ms property. If not set, the value in log.retention.hours is used.
log.retention.ms
The number of milliseconds to keep a log file before deleting it (in milliseconds), If not set, the value in log.retention.minutes is used.


text:
Q: Call refreshtoken WS only once with RX On a screen i have multiple WS called with a token, when token is expired, a function called refreshTokens is called :
  func postItemImpersonation(parameters: [String: Any]?) -> Observable<(HTTPURLResponse, T)> {
    let absolutePath = Constants.URL.Impersonation.url
    let impersonationHeader: [String: String] = [
    "Content-Type": "application/json",
    "X-Api-Key": "xxxxxxx"
    ]
    return self.manager.rx.request(.post, absolutePath, parameters: parameters, encoding: JSONEncoding.default, headers: impersonationHeader)
        .responseJSON()
        .timeout(RxTimeInterval.seconds(self.timeOutValue), scheduler: scheduler)
        .observeOn(self.scheduler)
        .map({ response -> (HTTPURLResponse, T) in
            if response.response?.statusCode == 500 {
                throw Error_Code_Network.REST_KO_TECHNIQUE_ERROR
            }
            else if response.response?.statusCode == 204 {
                throw Error_Code_Network.REST_NO_CONTENT
            }else if response.response?.statusCode == 401 {

                throw TokenError.unauthorized
            }

            let object = Mapper<T>().map(JSONObject: response.value)
            if let object = object, let response = response.response {
                return (response, object)
            }
            throw Error_Code_Network.REST_KO_TECHNIQUE_ERROR
        })
        .retryWhen({ errorObservable in
            errorObservable.enumerated().flatMap({ ( index , error ) -> Observable<Void> in
                if let e = error as? TokenError, e == TokenError.unauthorized, index < self.maxRequestRetry {
                    return self.refreshTokens().asObservable()
                        .map({ succeded -> Void in
                            if succeded {
                                return Void()
                            } else {
                                SessionManager.GetInstance().forceDeconnexion.accept(true)
                                throw TokenError.expired
                            }
                        })
                }
                throw error
            })
        })
}

}
but when two ws or more are called and token expired, refreshTokens is called several times, i want it to be called only once
how can i do that please ?

A: I wrote an article detailing the solution to this problem: RxSwift and Handling Invalid Tokens
The key is to create a service that tracks the current token value and updates it when necessary.


text:
Q: How to load cudf in colab? I want to use cudf library in my projects and installed the rapids. It has been installed well, and here are some strings from outprint
Starting to prep Colab for install RAPIDS Version 0.14 stable
Checking for GPU type:
***********************************************************************
Woo! Your instance has the right kind of GPU, a 'Tesla T4'!
***********************************************************************

************************************************
Your Google Colab instance has RAPIDS installed!
************************************************

However when trying to import cudf, I get
ModuleNotFoundError: No module named 'cudf'

I have a suggestion that it could be connected to incompatible python versions, because when running an installation script
# Install RAPIDS
!git clone https://github.com/rapidsai/rapidsai-csp-utils.git
!bash rapidsai-csp-utils/colab/rapids-colab.sh stable

import sys, os

dist_package_index = sys.path.index('/usr/local/lib/python3.6/dist-packages')
sys.path = sys.path[:dist_package_index] + ['/usr/local/lib/python3.6/site-packages'] + sys.path[dist_package_index:]
sys.path
exec(open('rapidsai-csp-utils/colab/update_modules.py').read(), globals())

I got error
ValueError: '/usr/local/lib/python3.6/dist-packages' is not in list

so I changed the python3.6 to python3.7 everywhere. Anyway, how could I fix this?

A: We pushed an update last night that updates the RAPIDS install on Colab. You can run RAPIDS 0.18 and 0.19 now, as normal. It was more than just changing the paths (check out our github if you to see the changes made), but that was totally worth the try!  :)


text:
Q: Currency convertor I have an issue where the program wouldn't display the desired amount of amount  the user wanted to convert. Also how do you round the number to 3 decimal places, any ideas?
money = int(input("Enter the amount of money IN GDP you wish to convert :"))

USD = 1.25
EUR = 1.17
RUP = 83.87
PES = 25.68

currency = input("Which currency would you like to convert the money into?")

if currency == "USD":
    print(money) * USD
elif currency == "EUR":
    print(money) * EUR
elif currency == "RUP":
    print(money) * RUP
elif currency == "PES":
    print(money) * PES

A: Python includes the round() function which lets you specify the number of digits you want. So you can use round(x, 3) to do normal rounding up to 3 decimal places.
Example
print(round(5.368757575, 3)) # prints 5.369

Update
You can update your code in this way.
money = int(input("Enter the amount of money IN GDP you wish to convert: "))

USD = 1.25
EUR = 1.17
RUP = 83.87
PES = 25.68

currency = input("Which currency you like to convert the money into?: ")

if currency == "USD":
    print(round(money * USD, 3))
elif currency == "EUR":
    print(round(money * EUR, 3))
elif currency == "RUP":
    print(round(money * RUP, 3))
elif currency == "PES":
    print(round(money * PES, 3))

It outputs:
Enter the amount of money IN GDP you wish to convert: 100
Which currency you like to convert the money into?: USD
125.0

Enter the amount of money IN GDP you wish to convert: 70
Which currency you like to convert the money into?: RUP
5870.9


text:
Q: custom taxonomy in wordpress custom post type not showing I used wp-types types plugin to create custom post type and custom taxonomy. I got custom fields value in template file with types API successfully but taxonomy not showing and I didn't found any useful API for that.
Please guide me to how show custom taxonomy in custom post type.
thanks for your attentions.

A: I found the answer add this to template file:
<?php echo get_the_term_list( $post->ID, 'custom-taxonomy-name', '', '', '' ); ?>


text:
Q: ReactN setGlobal()/useGlobal() not working for me I'm trying to setGlobal() vars and objects in one page and retrieve them in the next page
StackOverflow.js
import React, {setGlobal, useGlobal, useEffect} from 'reactn'

setGlobal({
    myVar: '',
    myObj: {}
})

const StackOverflow = () => {
    const [myVar, setMyVar] = useGlobal('myVar')
    const [myObj, setMyObj] = useGlobal('myObj')

    useEffect(() => {
        setMyVar('Hello World')
        setMyObj({name: 'Mr Magoo'})
    }, [])

    useEffect(() => {
        console.log("MyVar: ", myVar, "\nMyObj: ", myObj)
    }, [myVar, myObj])

    return (

Click me

    )
}

export default StackOverflow

StackOverflow2.js
import React, {useGlobal} from 'reactn'

const StackOverflow2 = () => {
    const [myVar] = useGlobal('myVar')
    const [myObj] = useGlobal('myObj')

    return (

StackOverflow2

My Var: {myVar}

My Obj: {myObj.name}

    )
}

export default StackOverflow2

I expect to be able to setGlobal() vars/objects on one page, and useGlobal() vars/objects in second page. I'm getting nothing.


text:
Q: What can go wrong if cout.rdbuf() is used to switch buffer and never set it back? The author presented this code under the title A bus error on my platform
#include <fstream>
#include <iostream>

int main()
{
    std::ofstream log("oops.log");
    std::cout.rdbuf(log.rdbuf());
    std::cout << "Oops!\n";
    return 0;
}

The string "Oops!\n" is printed to the file "oops.log". The code doesn't restore cout's streambuf, but VS2010 didn't report a runtime error.

A: Since the other answers don't mention what to do about this I'll provide that here. You need to save and restore the buffer that cout is supposed to be managing. For example:
#include <fstream>
#include <iostream>

// RAII method of restoring a buffer
struct buffer_restorer {
    std::ios &m_s;
    std::streambuf *m_buf;

    buffer_restorer(std::ios &s, std::streambuf *buf) : m_s(s), m_buf(buf) {}
    ~buffer_restorer() { m_s.rdbuf(m_buf); }
};

int main()
{
    std::ofstream log("oops.log");
    buffer_restorer r(std::cout, std::cout.rdbuf(log.rdbuf()));
    std::cout << "Oops!\n";
    return 0;
}

Now when cout's buffer is replaced before cout is destroyed at the end of the program, so when cout destroys its buffer the correct thing happens.

For simply redirecting standard io generally the environment already has the ability to do that for you (e.g., io redirection in the shell). Rather than the above code I'd probably simply run the program as:
yourprogram > oops.log

Also one thing to remember is that std::cout is a global variable with all the same downsides as other global variables. Instead of modifying it or even using it you may prefer to use the usual techniques to avoid global variables all together. For example you might pass a std::ostream &log_output parameter around and use that instead of having code use cout directly.

A: Your program has Undefined Behavior.
The destructor of the global cout object will delete the stream buffer when going out of scope, and the same is true of log, which also owns that very same stream buffer. Thus, you are deleting the same object twice.
When a program has Undefined Behavior, anything could happen, from formatting your hard drive to terminating without any error.
On my platform, for instance, the program enters an infinite loop after returning from main().

A: Since log and std::cout share a buffer, that buffer will probably be freed twice (once when log goes out of scope, then once more when the program terminates).
This results in undefined behavior, so it's hard to tell the exact reason why it triggers a bus error on his machine but silently fails on yours.


text:
Q: Windows 10 and RDC Manager v2.7 missing cursor PowerShell ISE In Windows 7 no problems. Last week had to upgrade to Windows 10. Now I my mouse cursor disappears in the PowerShell ISE in Server 2012 R2. I tried [Console]::CursorSize = 25 from another post, but got an error. This is rather annoying. Please help. Thx

A: Adjust your Windows 10 DPI to recommended 100%:
Settings -> System ->Display, change scale and layout
And then also disable the high DPI scaling behavior for RDC:

*

*Right click RDC application.

*Under Compatibility tab, check "Override high DPI scaling behavior." box.

*Choose Scaling performed by "System".


text:
Q: Parallelism in RxJava I have some doubts about how to properly use parallel threads in RxJava with an Android app (Kotlin). I have this app that reads some RSS feeds. The user request to update all the feeds using this method:
override fun updateAllFeeds(): Completable {
    return menu()
            .map {
                val feeds = mutableListOf<String>()
                it.forEach { menuSection ->
                    menuSection.options.forEach { menuOption ->
                        menuOption.feed?.forEach { feed ->
                            if (!feeds.contains(feed)) feeds.add(feed)
                        }
                    }
                }
                feeds
            }
            .flatMapObservable {
                // Get each item from List
                Observable.fromIterable(it)
            }
            .flatMapCompletable { feedUrl ->
                // Update each feed
                rssDataStore.updateFeed(feedUrl)
            }
}

That Completable is used later here:
val task = rssRepository.updateAllFeeds().subscribeOn(Schedulers.from(threadExecutor))
                .observeOn(postExecutionThread.scheduler)

Where threadExecutor is a ThreadPoolExecutor with maximumPoolSize = 5.
I had the idea that the rssDataStore.updateFeed(feedUrl) part will be executed in parallel because of the ThreadPoolExecutor used in subscribeOn, but in Logcat I can see it is only running one at a time, sequentially, and the Observer's onComplete is fired when the last feed is updated. Is there a way to specify that rssDataStore.updateFeed(feedUrl) should be executed in parallel but get the onComplete only when the last thread has finished?


text:
Q: Given the same index, are iword() and pword() guaranteed to refer to separate underlying values? In the standard C++ ios library, is it guaranteed that &stream.iword(ind) != &stream.pword(ind) when called on the same stream with the same ind value?
Moreover, is it guaranteed that I can use the void* and long values individually given the same index (i.e. they're not implemented as a union, etc.)?
I suppose the X-Y problem here is how do I know if, given a random stream, my custom value ("allocated" using xalloc()) has been initialized? I ask because I've seen people use pword() to check a magic constant and then iword() to initialize that value if the previous condition fails.
I mainly care about C++11 and onward, though any relevant historical information is welcome.

A: The C++ standard says that iword() and pword() should behave as if they are manipulating two separate, independent blocks of storage - rather than, say, a single block whose contents are interpreted as long sometimes and void* other times.

[ios.base]
namespace std {
  class ios_base {
  // ...
  private:
    long* iarray; // exposition only
    void** parray; // exposition only
  };
}

[ios.base.storage]/3
  long& iword(int idx);

Effects: If iarray is a null pointer, allocates an array of long of unspecified size and stores a pointer to its first element in iarray. The function then extends the array pointed at by iarray as necessary to include the element iarray[idx]. Each newly allocated element of the array is initialized to zero. The reference returned is invalid after any other operations on the object. However, the value of the storage referred to is retained, so that until the next call to copyfmt, calling iword with the same index yields another reference to the same value...

[ios.base.storage]/5 repeats the exact same wording, substituting pword for iword, parray for iarray and void* for long.
The important part is "the value of the storage ... is retained" - a subsequent iword call with a given index should see the value that was written into the storage that the previous iword call with the same index provided a reference to, regardless of intervening method calls (other than copyfmt), even if that intervening method call is pword (and vice versa).


text:
Q: Multiple keys vs dictionary in memcache? What is a better approach? Having multiple keys or having a dictionary?
In my scenario I want to store songs in a country basis and cache that for further access later on. Below I write the rough pseudocode without disclosing too many details to keep it simple. The actual songs will most probably be IDs from songs in a database.
Many keys approach
cache.set("songs_from_city1", city1_songs)
cache.set("songs_from_city2", city2_songs)
..

Dictionary approach
cache.set("songs_by_city", {
  'city1': city1_songs
  'city2': city2_songs
  ..
})
..

A: As mentioned in the comment it mainly depends on the application requirement.
To Add another perspective,
You can think of it as the problem of 'storing and retrieve 1 object vs multiple granular objects'. There is a detailed discussion on this tradeoff in this post.
Hope it helps!


text:
Q: How to avoid refreshing of cells on when calling notifyDataSetChanged() for PinterestLikeAdapterView? Background
I'm using the PinterestLikeAdapterView library to show some images from the internet, which is like a gridView but with different height for each cell.
The problem
Since I use this library to show images from the internet, it's crucial that when calling notifyDatasetChanged won't cause a mess on the views.
For some reason, calling this function would call the getView() method with different positions for the views. for example, even though i didn't scroll at all, and call notifyDatasetChanged (or addAll in case it's an ArrayAdapter), for position 0 it will take what was the view of position 8, for position 1 it will take the view of position 7 , and so on...
This makes the whole grid to refresh its images, and so it ruins the UX.
Usually, in both gridView and listView, the way to overcome refreshing is to put the position that was used for the view inside the viewHolder, and if they are equal, it means that they still match.
for example:
... getView(...)
  {
  //<=inflate a new view if needed
  //avoid refreshing view in case it's still the same position:
  if(position==holder.position)
    return rootView;
  holder.position=position;
  //<=update the view according to its data
  ...
  }

However, here they re-use other views in a different order so this trick won't work here.
Because of this issue, not only i get refreshes of almost all of the visible views, but since i use DiskCacheLru library, it crashes since it tries to put 2 identical inputSteam data into the same key using 2 threads.
The question
What can I do?
Is this a known bug in the library?
Maybe I'm using a bad way to overcome refreshes?
for now, i use memory cache to at least get items that were cached before, but that's more like a "cure" than a "vaccine"...

A: Short answer:
Use an image loading library like Picasso that caches most recently used images in memory, so they don't need to be reloaded from the network.
Long answer:
AdapterView does something called View recycling, where Views which are no longer needed to display a position are re-used to display another. (For example, as you scroll down, Views that disappear off the top of the screen are reused for new positions at the bottom of the screen.) Because of this, it's normal for getView() to be passed the same View for more than one position.
This is done for performance reasons: Inflating new Views is hard and takes time, so AdapterView tries to do it as infrequently as possible.
When using a holder, you store references to ImageView and TextView children inside the item's View, so you don't have to look them up with findViewById() each time - you don't usually store anything specific to a particular position, because the View and its holder will often be used for different positions.
Now, when you call notifyDataSetChanged(), AdapterView assumes that the data set has completely changed. The image that was associated with position 8 may no longer be present, or it may be associated with position 12 now. Consequently, all the existing Views are scrapped - but because AdapterView would still like to avoid inflating new Views, they're re-used to display the new data, with no regard for what position they were displaying previously.
This explains why getView() is being passed the same View for different positions, and why visible positions are being refreshed when you call notifyDataSetChanged(). But how to avoid having your images refresh, ruining the user experience?
Use an image loading library like Picasso that caches most recently used images in memory, so they don't need to be reloaded from the network. The refresh will still happen, but it'll be instantaneous.

A: View getView(int position, View view, ViewGroup parent) will be always called ascendingly, after notifyDataSetChanged().
I guess that, the order of finishing download task will cause this problem.
As you mentioned in your question, keeping the position is a good way to avoid this problem.
Here is another way to solve it, also re-use the imageviews.
Keep a weak reference of each ImageView in download task.
Then wrap the download task in a dummy ColorDrawable.
When getView is called, set the dummy ColorDrawable to ImageView, and start the download. When download is complete, set the downloaded image back to the referenced ImageView in OnPostExecute().
Explanation
http://android-developers.blogspot.jp/2010/07/multithreading-for-performance.html
Source code
https://code.google.com/p/android-imagedownloader/source/checkout

A: There is a very good example on PinterestLikeListView in GitHub
Here is the library StaggeredGridView
A modified version of Android's experimental StaggeredGridView. Includes own OnItemClickListener and OnItemLongClickListener, selector, and fixed position restore.
You can get library project here library
and you can get Demo project Here
This is very good open source project, so you can use instead of PinterestLikeAdapterView

Hope this library is going to help you out.

A: seems that the authors of this library have fixed it, after some time i've reported about it:
https://github.com/huewu/PinterestLikeAdapterView/issues/8


text:
Q: How does Meteor connect to Mongo? Very new to Meteor.
I am trying to make a separate worker process that uses the ddp and ddp-login packages to log in to my main Meteor app's Mongo collections over DDP.
It is prompting for credentials.
My questions are:

*

*What are the default credentials Meteor sets up to connect to Mongo?

*Where are these located in the Meteor project? Where is the connection string?

*How do I change these credentials?

I have been hunting all over my project source and it's still "magical" to me.


text:
Q: Passing multiple system properties to google dataproc cluster job I am trying to submit a spark job on Dataproc cluster. The job needs multiple system properties. I am able to pass just one as follows:
gcloud dataproc jobs submit spark \
    --cluster <cluster_name> \
    --class <class_name> \
    --properties spark.driver.extraJavaOptions=-Dhost=127.0.0.1  \
    --jars spark_job.jar

How do I pass multiple properties?
I tried as follow, even this didn't work.
--properties ^#^spark.driver.extraJavaOptions=-Dhost=127.0.0.1,-Dlimit=10

A: I figured it out.
gcloud dataproc jobs submit spark \
    --cluster <cluster_name> \
    --class <class_name> \
    --properties spark.driver.extraJavaOptions='-Dhost=127.0.0.1 -Dlimit=10 -Dproperty_name=property_value' \
    --jars spark_job.jar


text:
Q: Booting the liveCD/USB in EFI mode fails on Samsung Tablet XE700T1A My tablet is Samsung Series 7 Slate (XE700T1A-A02FR (French Language)). It operates an Intel Sandy Bridge architecture. The main issue about this tablet is that it ships with an installed Windows 7 in (U)EFI mode (GPT partition table, etc.), so I'd like to get an EFI dual boot with Ubuntu.
But it seems I can't boot on the liveCD in EFI mode. It starts loading (up to initrd), but I then get a blank (black) screen. I've tried the nomodeset kernel option (as well as removing quiet and splash) with no luck.

[2012-09-27]
I have used the Ubuntu 12.04.1 Desktop ISO (I have read somewhere that it is the only one that can boot in EFI mode).
I'd say this has something to do with UEFI since the LiveCD boots in bios mode but not in efi mode.
Besides, I am not sure my boot info will help, since I can't boot the LiveCD in EFI mode. As a result I can't install ubuntu in EFI mode. So it would be the boot info from the liveCD boot in bios mode. This happens on a ubuntu-12.04.1-desktop-amd64 iso used on a LiveUSB. Live USB was created by dd'ing the iso onto the full disk device (i.e. /dev/sdx no number) of the Flash drive.
I have also tried copying the LiveCD files on a primary GPT partition, but with no luck, I just get the grub shell, no menu, no install option.

[2012-09-28]
I tried today a flash drive created with Ubuntu's Startup Disk Creator and the alternate 12.04.1 64 bit ISO. I get a grub menu in text mode (which meens it did start in efi mode) with install options / test options. But when I start any of these, I simply get a black screen (no cursor, neither mouse nor text-mode cursor). I tried removing the 'quiet' option and adding nomodeset and acpi=off, but it didn't do any good. So this is the same result as for the LiveCD.

[2012-10-01]
I have tried with a version of the secure remix version via usb-creator-gtk. The boot on the USB key has the same symptoms. Boot in EFI mode is impossible (I have menu but whatever entry I choose, I get the blank screen problem). The boot in BIOS mode works, I did the install. Then I used boot-repair to try installing grub-efi and get a system that would boot in efi mode. But I can't boot this system, because the EFI firmware doesn't seem to detect that sda contains a valid efi partition. Here is the resulting boot-info
Boot info 1253554

[2012-10-01]
Today, I have reinstalled the pre-shipped version of windows 7, and then installed ubuntu from a secure-remix iso dumped on USB flash drive vie usb-creator-gtk booted in BIOS mode. When install ended, I said "continue testing" then I used boot-repair to try get the bootloader installed.
Now, when I boot the tablet, I get the grub menu, it can chainload windows 7 flawlessly. But when I try to start one of the ubuntu options I get the same old blank screen.
Here is the new boot-info: Boot info 1253927

[2012-10-01]
I tried installing the 3.3 kernel by chrooting a live usb boot (secure remix again) into the installed system.
Same symptoms.
I feel the key to this is that the device's efi firmware (which is EFI v2.0) would expose the graphics hardware in a way that prevents the kernel to initialize it, and thus prevents it from booting (the kernel stops all drive access just after the screen turns kind of very dark purple).
Here is some info on the UEFI firmware as given by rEFInd:
EFI revision: 2.00
Platform: x86_64 (64 bit)
Firmware: American Megatrends 4.635
Screen Output: Graphics Output (UEFI), 800x600

[2012-10-08]
This week end I tried loading the kernel with elilo. Eventhough I didn't have more luck on booting the kernel, elilo gives more info when loading the kernel.
I think the next step is trying to load a kernel with EFI stub directly.

A: ** [2012-10-12] **
After some days of despair trying to compile a custom kernel to manage to boot Ubuntu in EFI mode, with no real belief and no success, I tried (again, with no real faith in it) with the new ubuntu 12.10 beta 2 version dumped on a flash drive with usb-creator-gtk.
Et voila !
The Ubuntu-12.10-beta2-amd64 LiveUSB manages to boot in EFI mode ! Install works, and I am left with ... A perfectly booting EFI install of ubuntu !!
I can now use efibootmgr and all. I installed rEFInd to get a nice graphical OS chooser.
I'm so happy !
took me a full month to get it work....
BTW: This answer is posted through my newly working samsung xe700t1a tablet runing Ubuntu 12.10 beta2.

A: just found my answer from https://help.ubuntu.com/community/UEFI#Converting_Ubuntu_into_EFI_mode
Secure boot is not fully supported yet, so i had to disable it


text:
Q: Get stdout and stderr of a nodejs application running in background as process there is an existing nodejs code on a ubuntu server running in the background. This existing code is having some issues and I want to see the console.logs of this code running.
I have found the process id of by:
 ps -aef | grep node

which gives
aman 20897     1  0 Sep26 ?        03:07:06 node Monitor/Broker.js

Can someone help with how do I find the logs/stdout/stderr for this process ?
Thanks

edit

output of lsof -p 20897


text:
Q: App Sharing is giving nil data I am creating an iPhone app and iWatch app. I want to share data from iPhone app to iWatch app.
I am using app group for both and saving data in User Defaults using suit name. But when I am retrieving values in iWatch then it is always nil.
I have created three provisioning profiles. One for app, second for watch kit and third for watch kit extension. All three having same group name. and from capabilities I have enabled App sharing and it is showing correct group name which I have enabled by clicking on it.
After that, In ViewController.swift (iPhone App)
 let userDefaults = UserDefaults.standard
    userDefaults.addSuite(named: "group.group.com.demo.appgroup")
        userDefaults.set("12345", forKey: "isDarkModeEnabled")
        userDefaults.synchr

onize()
and in InterfaceController.swift (In Watch Extension)
let storageKey = "group.group.com.demo.appgroup"
        let userStorage = UserDefaults(suiteName: storageKey)

        // Get setting from storage or default
        if userStorage?.object(forKey: "isDarkModeEnabled") == nil
        {
            print("Data is nil")
        }
        else
        {
            lblTest.setText(userStorage?.object(forKey: "isDarkModeEnabled") as? String)
        }

But while I am fetching data fin watch extension, it is always giving me nil.
Please help to solve this issue.
Thanks

A: Have you created a shared app group?
The Apple documentation goes into quite specific detail about how to set this up. Also, it's a somewhat well-documented issue that people have trouble getting user defaults to work in the simulators, while they do work fine on real devices.
https://developer.apple.com/library/content/documentation/General/Conceptual/WatchKitProgrammingGuide/Settings.html
I know that talks about a settings bundle, but it works the same way for value exchange. It's important to note that Apple really would prefer you to use WCSession to transfer data between devices.

A: You can do like this
1.Enable AppGroups in Watch Extension and Main App in capabilities
2.Try Code:
let AppGroup = "group.com.demo.appgroup"
let AppUserDefaults = UserDefaults(suiteName: AppGroup)
AppUserDefaults.set("12345", forKey: "isDarkModeEnabled")
AppUserDefaults?.synchronize()


text:
Q: Sharing storage partition from linux device over usb I have an ARM device running linux using a micro sd card as it's storage. The sd card is split into 3 partitions, the boot partition, the linux partition and a 3rd partition for storage. The third partition is partitioned as FAT16 and formatted as such too.
On the device I swap between mounting the 3rd partition locally to access the storage and unmounting and using usb-gadget (modprobe g_file_storage file=/dev/mmcblk0p3) to share the partition over usb connection.
The problem I have is that the partition appears as unallocated when the device is attached via usb to a Windows machine (it appears fine in ubuntu/mac). I have tried both mkfs.vfat and mkdosfs from ubuntu.
I can use windows to format the "unallocated" partition but then when I try and mount the partition on the linux device (having done rmmod g_file_storage) it will not see the same filesystem that Windows created (presumably because the partition when shared is slightly different from the partition when mounted).
Has anyone found a way around this sort of issue?

A: Adding removable=y to the end of modprobe fixed this for me.


text:
Q: MSSQL 2008 SP pagination and count number of total records In my SP I have the following:
with Paging(RowNo, ID, Name, TotalOccurrences) as
(
    ROW_NUMBER() over (order by TotalOccurrences desc) as RowNo, V.ID, V.Name, R.TotalOccurrences FROM dbo.Videos V INNER JOIN ....
)
SELECT * FROM Paging WHERE RowNo BETWEEN 1 and 50
SELECT COUNT(*) FROM Paging

The result is that I get the error: invalid object name 'Paging'.
Can I query again the Paging table? I don't want to include the count for all results as a new column ... I would prefer to return as another data set. Is that possible?
Thanks, Radu

A: After more research I fond another way of doing this:
with Paging(RowNo, ID, Name, TotalOccurrences) AS
(
    ROW_NUMBER() over (order by TotalOccurrences desc) as RowNo, V.ID, V.Name,    R.TotalOccurrences FROM dbo.Videos V INNER JOIN ....
)
select  RowNo, ID, Name, TotalOccurrences, (select COUNT(*) from Paging) as TotalResults  from Paging where RowNo between (@PageNumber - 1 )* @PageSize + 1 and @PageNumber * @PageSize;

I think that this has better performance than calling two times the query.

A: You can't do that because the CTE you are defining will only be available to the FIRST query that appears after it's been defined. So when you run the COUNT(*) query, the CTE is no longer available to reference. That's just a limitation of CTEs.
So to do the COUNT as a separate step, you'd need to not use the CTE and instead use the full query to COUNT on.
Or, you could wrap the CTE up in an inline table valued function and use that instead, to save repeating the main query, something like this:
CREATE FUNCTION dbo.ufnExample()
    RETURNS TABLE
AS
RETURN
(
with Paging(RowNo, ID, Name, TotalOccurrences) as
(
    ROW_NUMBER() over (order by TotalOccurrences desc) as RowNo, V.ID, V.Name, R.TotalOccurrences FROM dbo.Videos V INNER JOIN ....
)
SELECT * FROM Paging
)

SELECT * FROM dbo.ufnExample() x WHERE RowNo BETWEEN 1 AND 50
SELECT COUNT(*) FROM dbo.ufnExample() x

A: Please be aware that Radu D's solution's query plan shows double hits to those tables. It is doing two executions under the covers. However, this still may be the best way as I haven't found a truly scalable 1-query design.
A less scalable 1-query design is to dump a completed ordered list into a @tablevariable , SELECT @@ROWCOUNT to get the full count, and select from @tablevariable where row number between X and Y. This works well for <10000 rows, but with results in the millions of rows, populating that @tablevariable gets expensive.
A hybrid approach is to populate this temp/variable up to 10000 rows. If not all 10000 rows are filled up, you're set. If 10000 rows are filled up, you'll need to rerun  the search to get the full count. This works well if most of your queries return well under 10000 rows. The 10000 limit is a rough approximation, you can play around with this threshold for your case.

A: Write "AS" after the CTE table name Paging as below:
with Paging AS (RowNo, ID, Name, TotalOccurrences) as
(
    ROW_NUMBER() over (order by TotalOccurrences desc) as RowNo, V.ID, V.Name, R.TotalOccurrences FROM dbo.Videos V INNER JOIN ....
)
SELECT * FROM Paging WHERE RowNo BETWEEN 1 and 50
SELECT COUNT(*) FROM Paging


text:
Q: java.nio.ByteBuffer - allocateDirect and garbage collection I read the following today:

Direct ByteBuffer objects clean up their native buffers automatically
  but can only do so as part of Java heap GC — so they do not
  automatically respond to pressure on the native heap. GC occurs only
  when the Java heap becomes so full it can't service a heap-allocation
  request or if the Java application explicitly requests it (not
  recommended because it causes performance problems).

I was under the impression that using Direct ByteBuffers meant you had to manually manage allocation/deallocation of native memory and that it wasn't subject to GC at all. However this article seems to say that if a GC does occur, then the direct ByteBuffer is subject to collection.
I thought that when doing off-heap storage, one of the main motivators is to avoid problems that might occur because of GC (e.g. long pauses).

A: The DirectByteBuffer objects are very small objects that essentially just hold a pointer into native memory. This allows allocation without expanding the managed heap and zero-copy IO.
So those objects generally don't increase GC pressure much.
What they do consume is native resources, virtual address space and possibly physical ram or swap space. If you're using memory-mapped files instead of buffers created by allocateDirect you may be able to vastly exceed the available physical ram because the memory will be backed by disk storage (similar to swap).
The only thing you cannot do, at least through official APIs, is unmapping the memory ranges that the direct buffers point to. Instead the underlying memory will be released once the buffers themselves are collected by the GC.
TL;DR: You don't get fully manual memory management, but you do escape from some of the limitations of the managed java heap.


text:
Q: Java Button for program Im in need of help with my java program code. Basically it is a program that allows users to request an item and the amount they want. If it is in stock they can click a "buy" button. Once clicked a confirm dialog will pop up asking if the user will like to buy 'x' units for 'y' amount. They can either choose yes, no or cancel. If they choose yes a pop up frame with the reciept will come up (havent done this part yet). The problem that i am having is that if they click no or cancel the reciept frame still shows - I dont want it to do this. Please can you tell me what is wrong with my code as it is not performing how i want it to perform. p.s. im a beginner in java as ive only been learning for a month
enter code here

public PurchaseItem() {

    this.setLayout(new BorderLayout());

    JPanel top = new JPanel();
    top.setLayout(new FlowLayout(FlowLayout.CENTER));
    JPanel bottom = new JPanel();
    bottom.setLayout(new FlowLayout(FlowLayout.CENTER));
    bottom.add(Buy);
    this.add(bottom, BorderLayout.SOUTH);

    setBounds(100, 100, 450, 250);
    setTitle("Purchase Item");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    top.add(new JLabel("Enter Item Key:"));
    top.add(ItemNo);
    top.add(new JLabel ("Enter Amount:"));
    top.add(AmountNo);
    top.add(check);

    Buy.setText("Buy"); Buy.setVisible(true);

    check.addActionListener(this);
    Buy.addActionListener(this);

    add("North", top);
    JPanel middle = new JPanel();
    middle.add(information);
    add("Center", middle);

    setResizable(true);
    setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
    String ItemKey = ItemNo.getText();
    String ItemAmount = AmountNo.getText();
    String Name = StockData.getName(ItemKey);

    int Yes = JOptionPane.YES_OPTION;
    int No = JOptionPane.NO_OPTION;

    int Amount = Integer.parseInt(ItemAmount);
    int Key = Integer.parseInt(ItemKey);

    int NewStock = StockData.getQuantity(ItemKey) - Amount;

    double Total = Integer.parseInt(ItemAmount) * StockData.getPrice(ItemKey);

    if (Name == null){
       information.setText("There is no such item");
    }
    else if (Amount > StockData.getQuantity(ItemKey)) {
    information.setText("Sorry there is not enough stock available");
}
    else {
        information.setText(Name + " selected: " + ItemAmount);
        information.append("\nIndividual Unit Price: " + pounds.format(StockData.getPrice(ItemKey)));
        information.append("\nCurrent Stock Available: " + StockData.getQuantity(ItemKey));
        information.append("\nNew Stock After Sale: " + NewStock);
        information.append("\n\nTotal: " + ItemAmount + " Units" + " at  " + pounds.format(StockData.getPrice(ItemKey)) + " each");
        information.append("\n= " + pounds.format(Total));
    }
    if (e.getSource() ==  Buy) {
        JOptionPane.showConfirmDialog(null, "Buy " + ItemAmount + " Units" + " for " + pounds.format(Total) + "?");
        if (Yes == JOptionPane.YES_OPTION) {
        JFrame frame2 = new JFrame();
        frame2.pack(); frame2.setBounds(250, 250, 500, 500); frame2.setTitle("Reciept"); frame2.setVisible(true);
        JPanel middle = new JPanel();
        middle.setLayout(new FlowLayout(FlowLayout.CENTER));
        middle.add(reciept);
        reciept.setBounds(260,260,400,400);
        reciept.setVisible(true);
        }

    }
}

}

A: if (Yes == JOptionPane.YES_OPTION) { is always true (Yes been equal to JOptionPane.YES_OPTION; int Yes = JOptionPane.YES_OPTION;).
You need to get the return value from JOptionPane.showConfirmDialog and compare that
int response = JOptionPane.showConfirmDialog(null, "Buy " + ItemAmount + " Units" + " for " + pounds.format(Total) + "?");
if (response == JOptionPane.YES_OPTION) {
    ...
}


text:
Q: Fixed header fadeIn on scroll I have an issue on my website in that there are two mysterious divs creeping into my HTML code, and I'm not really sure why.
I think it's the use of data-magellan-expedition="fixed" in the (poorly named sorry) #navigation block. Would really appriciate someone taking a look and giving me some pointers and how this could be fixed?
Website
All relevant code is pasted velow.
I'm using the below javascript:
$(window).load(function() {
  var offset = 200; // some offset value for which when the header becomes hidden
  $(window).scroll(function() {
    if($('#navigation').is(':visible') && $(window).scrollTop() < offset) {
      $('#navigation').fadeOut(100);
    } else if(!$('#navigation').is(':visible') && $(window).scrollTop() > offset) {
      $('#navigation').fadeIn(400);
    }
  });
});

This is the css:
#navigation {
  display: none;
  background-color:rgba(27, 28, 29, 1);
  height: 70px;
}

.logo {
  margin: -10px 0;
}
.nav {
  li {
    text-align: right;
    padding: 10px 0 0 0;
    font-family: 'Arvo', cursive;
    color: $primary-color;
    cursor: pointer;
  }
  li:hover {
    color: $secondary-color;
  }
}

.nav .active{
  color: $secondary-color;
}

and here is the HTML:

Link1

Link2

Link3

Link4

Now for some reason, somewhere along the line the below two divs are being rendered:

Which nudges the content when you begin to scroll and the js effect comes into effect at the offset point.
currently the below css has fixed it.
removeDivs div:nth-child(n+2) {
  display: none!important;
  height: 0!important;
}

Does anyone have any ideas as to what is causing this? I'm using Foundation 5.
Many thanks.


text:
Q: How to format different types of dates into one? I have a $birthday that i taken from the database and it shows sometimes 1.12 (DAY.MONTH - without zeros in numbers and without a year) and sometimes as 1.12.1999 (DAY.MONTH.YEAR - without zeros in numbers and with a year)
i need to get a final result for a $birthday as 1.12 (DAY.MONTH - without zeros) and compare it to the current date (CURRENT_DAY.CURRENT_MONTH - without zeros) $today = date("j.n");
if ($birthday == $today ) { echo 'Today is your birthday"; }else{ echo 'Today is not your birthday"; }
How can i do it, how can i format it correctly , because i have different $birthday outputs each time?

A: You can do it like this.
<?php
$pieces = explode(".", $birthday);
$day = ltrim($pieces[0], '0');
$month = ltrim($pieces[1], '0');
$birthday = $day . "." . $month;
?>

That should give you same format birthday each time without the year and without the leading zeros. Even if input is with or without zeros and with or without a year.

A: You need to figure out some patterns in the date strings. From the two data points that you've mentioned, I can see one common pattern in the 1.12 and 1.12.1999 date strings which is they both start with day.month. So, if this pattern is held true for all your cases, what simply can be done is to take the first two components of the date string,
$today = date("j.n");
$dateStr = '1.12.1999'; // or 1.12
preg_match('/\d+\.\d+/', $dateStr, $matches);
$isBirthdayToday = isset($matches[0]) && $matches[0] === $today;

I hope this helps.


text:
Q: k-means clustering mapping I am using K-Means clustering of sklearn and want to replace the computed K-Means cluster labels with the centroid values using trained K-Means model.
The code I am using is as follows:
# Initialize K-Means clustering model-
kmeans_conv1 = KMeans(n_clusters = 5)

# Train model on training data (compute k-means clustering)-
kmeans_conv1.fit(conv1_nonzero.reshape(-1, 1))

# number of clusters used-
kmeans_conv1.n_clusters
# 5

# Get centroids-
kmeans_conv1.cluster_centers_
'''
array([[-0.05669265],
       [ 0.06742188],
       [-0.08835593],
       [ 0.03749201],
       [ 0.0896403 ]], dtype=float32)
'''

# Clustered labels of each data point-
kmeans_conv1.labels_

set(kmeans_conv1.labels_)
Out[142]: {0, 1, 2, 3, 4}

# Get clustered label for each data point-
clustered_labels = kmeans_conv1.labels_

Currently, I am using if-else conditions to map the labels to the centroid values as:
new_clusters = []

for clabel in clustered_labels:
    if clabel == 0:
        new_clusters.append(kmeans_conv1.cluster_centers_[0][0])
    elif clabel == 1:
        new_clusters.append(kmeans_conv1.cluster_centers_[1][0])
    elif clabel == 2:
        new_clusters.append(kmeans_conv1.cluster_centers_[2][0])
    elif clabel == 3:
        new_clusters.append(kmeans_conv1.cluster_centers_[3][0])
    elif clabel == 4:
        new_clusters.append(kmeans_conv1.cluster_centers_[4][0])

At the end, I want 'new_clusters' list or np.array variable to contain the centroid values instead of the cluster labels.
However, is there a better way to achieve this without using if-else conditions?

A: This is sufficient:
for clabel in clustered_labels:
    new_clusters.append(
        kmeans_conv1.cluster_centers_[clabel][0]
    )

A: Found this method:
# First conv layer condition-
cond_conv1 = [clustered_labels == 0, clustered_labels == 1, clustered_labels == 2, clustered_labels == 3, clustered_labels == 4]

# values-
val_conv1 = kmeans_conv1.cluster_centers_[:, 0]

# Get new clustered value weights-
new_weights_conv1 = np.select(cond_conv1, val_conv1)


text:
Q: Using Jest.js to test Adobe ExtendScript I want to do unit testing with my Adobe JSX files using Jest.
However, all Jest tutorials have some package.json which I don't use, and they use modules and requires which aren't in ES3 javascript, etc.
Plus 'JSX' has been appropriated by React, so it's also probably going to think I'm doing React files and not Adobe ES3 files.
Is there some way to use Jest and not bother with any modules and packages? I just want to test some ancient-style ES3 code that's just javascript.
If JSX extension is going to muddle things up, is there a way to do this with a single JS file?

A: Eventually I got some help and it was stated to me that I should install the jest with its modules in the project's directory - my global installation won't do. And, sure enough once the installation went, it worked.


text:
Q: display binary pdf with form data I have a script in Perl that pic up some binary data from a databae and displays it in a new window. This works gracefully with images and regular Pdf files. But when the pdf contains form data(think its called Fdf *) it just wont work. Any ideas? For now im just checking if its an pdf(they are always saved as Pdf) and print it in the script like so. Do i need some special case for pdf´s with form data?

*

*Looks like this.Pdf with form
if($extension eq 'pdf'){
 print $binaryData;
}else{
 <img src="data:image/<%$extension%>;base64,<%$binaryData%>" />
}

Should add that there is no problem displaying the Pdf´s if they are hosted on the server.

A: After doing some testing, I found that the problem is with your PDF file, rather than the method you've employed to embed the PDF.
It could be that your PDF file is protected from being embedded?
I tried this quick and it works fine for me:
<object data="http://www.thewebjockeys.com/TheWebJockeys/Fillable_PDF_Sample_from_TheWebJockeys_vC5.pdf" type="application/pdf" width="100%" height="100%">

It appears you don't have a PDF plugin for this browser.
  No biggie... you can click here to
  download the PDF file.

</object>

Preview: http://i.imgur.com/1jJI8ud.png


text:
Q: MATLAB force num2str to format I'm searching for the reverse of this request
So when I type num2str(foo,3), I get this :
foo=0.00781
foo=0.0313
foo=0.125
foo=0.5
foo=2
foo=8

However I want to make them all of the same length, so something like this :
foo=0.0078
foo=0.0313
foo=0.1250
foo=0.5000
foo=2.0000
foo=8.0000

-How- can I do this with num2str? (And I would really appreciate if it also works if mat2str)
Thanks for any help!
Edit :
I noticed that there is another -yet unsolved- part to this problem, which is for numbers greater than 10, or 100, 1000, etc.
So what if I want this : ?
foo=000.5000
foo=002.0000
foo=008.0000
foo=032.0000
foo=128.0000

i.e. adding leading zeros to a specified length? I tried '%3.3f' but it doesn't work.

A: For a single number
You can include a C-like format specifier in num2str:
>> num2str(.125, '%0.4f')
ans =
0.1250

Or use sprintf:
>> sprintf('%0.4f', .125)
ans =
0.1250

For matrices
Use num2str with a matrix input. Include the desired separator column (such a space) in the format specifier:
>> num2str([.125 .5; 2 8], '%0.4f ')
ans =
0.1250 0.5000
2.0000 8.0000

If you then want mat2str-like format, you just need to procress the resulting string to include ; (or just ;) at the end of each line and enclose with [, ]:
x = [.125 .5; 2 8];
s = num2str(x, '%0.4f ');
s = [s repmat('; ', size(s,1), 1)].';
s = ['[' s(1:end-2) ']'];

In the example, this gives
>> s
s =
[0.1250 0.5000; 2.0000 8.0000]

Leading zeros
If you want leading zeros to achieve a fixed number of characters, use a format specifier of the form '%08.4f'. This means 4 decimal places, 8 characters in total, which gives up to 3 leading zeros. For example,
x = [.125 .5; 2 8];
s = num2str(x, '%08.4f ');
s = [s repmat('; ', size(s,1), 1)].';
s = ['[' s(1:end-2) ']'];

gives
>> s
s =
[000.1250 000.5000; 002.0000 008.0000]


text:
Q: mariaDB - error granting rights to users I have the following users in my database:
MariaDB [racktables]> select user from mysql.user;
+----------+
| user     |
+----------+
| admin    |
| rackuser |
| repluser |
| root     |
| root     |
| root     |
|          |
| admin    |
| rackuser |
| root     |
|          |
| root     |
+----------+
12 rows in set (0.00 sec)

I'm trying to set up permissions but I keep getting the following error message:
MariaDB [racktables]> grant all on racktables.* to rackuser;
ERROR 1133 (42000): Can't find any matching row in the user table
MariaDB [racktables]>

The user clearly exists... I'm not sure why I'm getting this message. Unless.. this is my first crack at using mariaDB.  I've imported a mysql database into mariaDB.  And I'm assuming that mariaDB's users should be in the mysql.users table.
But maybe I'm wrong?  I'm currently reading the mariaDB docs.. but I haven't found my answer yet.
Any tips would be appreciated.
Thanks.

A: I had to run the
FLUSH PRIVILEGES;
command first... and then the grants worked.


text:
Q: How to detect screen rotation through 180 degrees from landscape to landscape orientation? I've seen a few other questions similar to this but no answers.
Rotating from portrait to landscape (either direction) and back again, we get the helpful call to onConfigurationChanged().
However, when rotating from landscape to landscape (through 180 degrees) onConfigurationChanged() is not called.
I've seen mention of using OrientationEventListener but this seems flakey to me because you can rotate quickly around without triggering a display orientation change.
I've tried adding a layout change listener, but with no success.
So the question is, how to reliably detect such a change in landscape orientation?

A: May be you should add some logical code in your OrientationEventListener like this:
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

OrientationEventListener orientationEventListener = new OrientationEventListener(this,
        SensorManager.SENSOR_DELAY_NORMAL) {
    @Override
    public void onOrientationChanged(int orientation) {

        Display display = mWindowManager.getDefaultDisplay();
        int rotation = display.getRotation();
        if ((rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && rotation != mLastRotation) {
            Log.i(TAG, "changed >>> " + rotation);

            // do something

            mLastRotation = rotation;
        }
    }
};

if (orientationEventListener.canDetectOrientation()) {
    orientationEventListener.enable();
}

A: I use this code to have it work for my case.
  OrientationEventListener mOrientationEventListener = new OrientationEventListener(mActivity)
  {
     @Override
     public void onOrientationChanged(int orientation)
     {
        if (orientation == ORIENTATION_UNKNOWN) return;

        int rotation = mActivity.getWindowManager().getDefaultDisplay().getRotation();
        switch (rotation) {
          case Surface.ROTATION_0:
             android.util.Log.i(TAG, "changed ROTATION_0 - " + orientation);
             break;
          case Surface.ROTATION_90:
             android.util.Log.i(TAG, "changed ROTATION_90 - " + orientation);
             break;
          case Surface.ROTATION_180:
             android.util.Log.i(TAG, "changed ROTATION_180 - " + orientation);
             break;
          case Surface.ROTATION_270:
             android.util.Log.i(TAG, "changed ROTATION_270 - " + orientation);
             break;
        }
        if ((rotation != mLastRotation) && (rotation & 0x1) == (mLastRotation & 0x1))
        {
           android.util.Log.i(TAG, "unhandled orientation changed >>> " + rotation);
        }
        mLastRotation = rotation;
     }
  };

  if (mOrientationEventListener.canDetectOrientation()){
     mOrientationEventListener.enable();
  }

A: OrientationEventlistener won't work when the device isn't rotating/moving.
I find display listener is a better way to detect the change.
     DisplayManager.DisplayListener mDisplayListener = new DisplayManager.DisplayListener() {
        @Override
        public void onDisplayAdded(int displayId) {
           android.util.Log.i(TAG, "Display #" + displayId + " added.");
        }

        @Override
        public void onDisplayChanged(int displayId) {
           android.util.Log.i(TAG, "Display #" + displayId + " changed.");
        }

        @Override
        public void onDisplayRemoved(int displayId) {
           android.util.Log.i(TAG, "Display #" + displayId + " removed.");
        }
     };
     DisplayManager displayManager = (DisplayManager) mContext.getSystemService(Context.DISPLAY_SERVICE);
     displayManager.registerDisplayListener(mDisplayListener, UIThreadHandler);

A: You'd still want to use the display listener class: Google recommends it for handling 180-degree device rotations from an unlocked orientation. You cannot simply treat all callbacks to onDisplayChanged as 180 degree rotations. A more complete implementation from Google shows how to gather the Display rotation from the Display manager during the onDisplayChanged callback that superuser mentioned.
/** DisplayManager to listen to display changes */
private val displayManager: DisplayManager by lazy {
    applicationContext.getSystemService(DISPLAY_SERVICE) as DisplayManager
}

/** Keeps track of display rotations */
private var displayRotation = 0

...

override fun onAttachedToWindow() {
    super.onAttachedToWindow()
    displayManager.registerDisplayListener(displayListener, mainLooperHandler)
}

override fun onDetachedFromWindow() {
    super.onDetachedFromWindow()
    displayManager.unregisterDisplayListener(displayListener)
}

private val displayListener = object : DisplayManager.DisplayListener {
    override fun onDisplayAdded(displayId: Int) {}
    override fun onDisplayRemoved(displayId: Int) {}
    override fun onDisplayChanged(displayId: Int) {
        val difference = displayManager.getDisplay(displayId).rotation - displayRotation
        displayRotation = displayManager.getDisplay(displayId).rotation

        if (difference == 2 || difference == -2) {
            createCaptureSession()
        }
    }
}


text:
Q: HashMaps vs Reactive Programming I am starting to embrace reactive programming a bit more, and I'm trying to apply it to my typical business problems. One pattern I often design with is database-driven classes. I have some defined unit class like ActionProfile whose instances are managed by an ActionProfileManager, which creates the instances off a database table and stores them in a Map<Integer,ActionProfile> where Integer is the actionProfileId key. The ActionProfileManager may clear and re-import the data periodically, and notify all dependencies to re-pull from its map.
public final class ActionProfileManager {
    private volatile ImmutableMap<Integer,ActionProfile> actionProfiles;

    private ActionProfileManager() {
        this.actionProfiles = importFromDb();
    }

    public void refresh() {
        this.actionProfiles = importFromDb();
        notifyEventBus();
    }

    //called by clients on their construction or when notifyEventBus is called
    public ActionProfile forKey(int actionProfileId) {
        return actionProfiles.get(actionProfiles);
    }

    private ImmutableMap<Integer,ActionProfile> importFromDb() {
        return ImmutableMap.of(); //import data here
    }
    private void notifyEventBus() {
        //notify event through EventBus here
    }
}

However, if I want this to be more reactive creating the map would kind of break the monad. One approach I could do is make the Map itself an Observable, and return a monad that looks up a specific key for the client. However the intermediate imperative operations may not be ideal, especially if I start using the rxjava-jdbc down the road. But the hashmap may help lookup performance significantly in intensive cases.
public final class ActionProfileManager {
    private final BehaviorSubject<ImmutableMap<Integer,ActionProfile>> actionProfiles;

    private ActionProfileManager() {
        this.actionProfiles = BehaviorSubject.create(importFromDb());
    }

    public void refresh() {
        actionProfiles.onNext(importFromDb());
    }

    public Observable<ActionProfile> forKey(int actionProfileId) {
        return actionProfiles.map(m -> m.get(actionProfileId));
    }
    private ImmutableMap<Integer,ActionProfile> importFromDb() {
        return ImmutableMap.of(); //import data here
    }
}

Therefore, the most reactive approach to me seems to be just pushing everything from the database on each refresh through an Observable<ActionProfile> and filtering for the last matching ID for the client.
public final class ActionProfileManager {
    private final ReplaySubject<ActionProfile> actionProfiles;

    private ActionProfileManager() {
        this.actionProfiles = ReplaySubject.create();
        importFromDb();
    }

    public void refresh() {
        importFromDb();
    }

    public Observable<ActionProfile> forKey(int actionProfileId) {
        return actionProfiles.filter(m -> m.getActionProfileID() == actionProfileId).last();
    }
    private void importFromDb() {
        // call onNext() on actionProfiles and pass each new ActionProfile coming from database
    }
}

Is this the optimal approach? What about old data causing memory leaks and not being GC'd? Is it more practical to maintain the map and make it observable?
What is the most optimal reactive approach above to data driven classes? Or is there a better way I have not discovered?

A: Using BehaviorSubject is the right thing to do here if you don't care about earlier values.
Note most post discouraging Subjects were written in the early days of Rx.NET and is mostly quoted over and over again without much thought. I attribute this to the possibility that such authors didn't really understand how Subjects work or run into some problems with them and just declared they shouldn't be used.
I think Subjects are a great way to multicast events (coming from a single thread usually) where you control or you are the source of the events and the event dispatching is somewhat 'global' (such as listening to mouse move events).


text:
Q: Move Win2k3 to new hardware: STOP 0x0000007B (How can I get PERC drivers installed?) I have an ancient celeron-based Windows 2003 SBS server on an old Dell machine.  It has a very basic IDE non-RAID setup.  The server is so old, it takes about 30 minutes to boot up and log in.
A new Dell (ugh!) server was purchased with the intent of doing a ghost from one server to the other.  The new server has a PERC6/i RAID controller in in w/ SATA drives.
Copying the data works fine (using linux 'dd'), but the server refuses to boot with 'STOP 0x0000007B (0xF789EA98, 0xC0000034, 0x00000000 0x00000000)'
In my experience, this has been due to Windows not having the drivers for the RAID controller.
To fix this, I would boot the old server, download the drivers for the new server, extract them, right-click on the .inf file and hit 'Install'.  Then shutdown and start the copy process.
It's totally not working for me with this new Dell server.  I am certain I have the correct drivers--I used the driver from the CD that came with the server, and I also went online and downloaded the correct driver.  But the new server refuses to boot.
Does anyone with more experience with this have any pointers?

A: If you have the option, installing the drivers before ghosting is the preferred method for doing this. Windows SHOULD pick up the new drivers during the boot process on new hardware. This is a large part of how Physical-to-Virtual migrations work driver-wise.

A: I've had lots of similar problems with IDE RAID 1 and Windows being unable to boot.  It might be this specific error.
The discussion has been that IDE RAID isn't "real RAID", meaning that the OS is really still aware and doing some of the work.
If using RAID 1 on the original box, one idea that has come closest to working for me is to break the mirror and then go through the rest of your process.

A: Dell tech support confirmed it is a bug in their drivers when the source server is not up to SP2.  Their fix is to install SP2 and retry the transfer.

A: A big thumbs up to DriverInjection
I did a disaster recovery of backups from a physical machine restored into a VM. I had the exact same error as the OP. DriverInjection + devcon.exe let me get an unbootable VM running.


text:
Q: spaces causing placeholder to wrap incorrectly I am creating a typing trainer page where the user can practice their typing. Consider the following:
HTML:

  <input type="button" value="Start!">

   left!

https://jsfiddle.net/y7nwju6p/8/
As the user types, the character turns blue if it's correct and red if it's incorrect. Everything works correctly, as long as the text isn't more than one line. See the following:
https://jsfiddle.net/nce4zqeu/30/
The problem is that I am replacing characters in the placeholder with spaces as the user types so that it looks like they are disappearing. Once this amounts to an entire line of spaces, the text wraps incorrectly. Is there any way to make it so that it wraps correctly?
Thank you for your help.

A: The problem with your current implementation is that you need to insert nonbreaking space, in this post (javascript nonbreaking space) I found out that '\xa0' is the raw char for non breaking space.
After modifying your snippet in the following lines (144 and 147) from "\u2008" to "\xa0" it worked like a charm.

Edit
I discovered two issues in this code snippet, the first one is that "\u2008" doesn't work as expected on firefox (the spaces dissapeared from the placeholder), so "\xa0" is better to use in this case (worked in chrome and firefox).
The second one, is the issue that the author describes in this question, the answer was to use:
word-break: break-all; // this does the job in firefox
word-break: break-word; // this does the job in chrome

These properties must stay in that order so firefox can use only the first one and ignore the second one (because is not supported), and chrome will understand both of them but will ignore the first one and use the second one (because of the cascading nature of CSS).


text:
Q: non overlaping choice lists in symfony2 Using Symfony 2.2.4.
I have a form with two choice lists(multiple,non expanded) showing the same elements(entities of a class). I need to throw an error(onsubmit) when the user selects the same element from both choice lists. Is there a way to validate this selection that does not need to traverse both lists checking each element, you know, like an automatic/built in validation.
I need to catch the error and bind it to one of the choice lists in a way that allows me to show it as any other error, meaning through form_errors(form).
Any tips appreciated.

A: the easiest way is to add a listener in the buildForm of the AbstractType class, here an example
    $builder->addEventListener(
        FormEvents::POST_SUBMIT,
        function (FormEvent $event) {
            $form = $event->getForm();
            $coll1 = $form['field1']->getData();
            $coll2 = $form['field2']->getData();
            $ids1 = $coll1->map(function($entity) { return $entity->getId(); })->toArray();
            $ids2 = $coll1->map(function($entity) { return $entity->getId(); })->toArray();
            $intersect = array_intersect($ids1, $ids2);
            if (!empty($intersect)) {
                $form['field1']->addError(
                    new FormError('here the error')
                );
            }
        }
    );

Note that I have not tested the intersection of the collections but I hope the meaning is clear
Another (a bit hardest) way is to create a custom validation constraint
here the cookbook from symfony docs


text:
Q: Bootstrap 4: put inputs horizontal I am new in Bootstrap 4 and need some help. I want that my first two inputfiels are at the same line (horizontal) and not among themselves. Like this:
enter image description here
Here is my HTML code:

        <input class="form-control transparent-input" type="text" name="name" placeholder="Name" required>

        <input class="form-control transparent-input" type="text" name="surname" placeholder="Vorname" required>

        <textarea class="form-control transparent-input" cols="20" rows="10" placeholder="Enter your message"></textarea>

        <button type="button" class="btn btn-primary">Send</button>

Can somebody help me out?

A: Please try this way. I hope you will get your desired style.

                <input class="form-control transparent-input" type="text" name="name" placeholder="Name" required>

                <input class="form-control transparent-input" type="text" name="surname" placeholder="Vorname" required>

                <textarea class="form-control transparent-input" cols="20" rows="10" placeholder="Enter your message"></textarea>

                <button type="button" class="btn btn-primary">Send</button>


text:
Q: Finding the sum of fractions with increasing denominator and decrease numerator for n iterations? Considering something like this:

$ \frac{10}{10} + \frac{9}{11} + \frac{8}{12} + ...$

Where denominator increases each iteration while the numerator decreases. Is there a simple way to find the sum of n iterations of this without doing all the iterations?

A: $$\sum_{j=0}^{n} {\frac{10-j}{10+j}}$$
$$=-\sum_{j=0}^{n} {\frac{j+10-20}{10+j}}$$
$$=-\sum_{j=0}^{n} {\frac{j+10}{10+j}} + \sum_{j=0}^{n} {\frac{20}{10+j}}$$
$$= -(n+1) + 20 (\sum_{j=1}^{n+10} {\frac{1}{j}}-\sum_{j=1}^{10} {\frac{1}{j}}) $$
$$ = 20H_{n+10} -n -1-20\sum_{j=1}^{10} {\frac{1}{j}}$$
$$ = 20H_{n+10} -n -\frac{7255}{126}$$
Where $H_{k} = \sum_{j=1}^{k} {\frac{1}{j}}$ is the $k$th harmonic number. The harmonic numbers have formulas. Check:
http://mathworld.wolfram.com/HarmonicNumber.html

A: Using your example: Start by rewriting this as $1+\sum_{n=1}^{\infty}\frac{10-n}{10+n}$ (or you can re-index and start at $0$). I did it this way to show you the lower bound.
Comment: If this series is summable then:  $\lim_{\ n\to \infty} \frac{10-n}{10+n} \to 0$. Proof
Does this sequence go tend to $0$?
I say this to say that we need to be specific because as we see arbitrary sequences like this aren't summable.

A: $\sum\limits_{k=0}^{n-1} 1-\frac{2k}{n+k}=n-2\sum\limits_{k=1}^{n-1}\frac{k}{n+k}=n-2\sum\limits_{k=1}^{n-1}1-\frac{n}{n+k}= n-2(n-1)+2n\sum\limits_{k=1}^{n-1}\frac{1}{n+k}=\\
2-n+2n(H_{2n-1}-H_n)$


text:
Q: Adjusting the showing time of Shield UI I am new to Shield UI Chart and am trying to make my bars show gradually, but it won't work.
    Even the graph won't load when trying with this code:
<script type="text/javascript"> $(function () { $("#chart").shieldChart({
applyAnimation: true
  {
    duration: 1500
 },

            axisY: {
                title: {
                    text: "Axis y values"
   }
            },
            primaryHeader: {
                text: "Sample statistics"
},
dataSeries: [{ seriesType: 'bar',

                collectionAlias: 'Series A',
                data: [129,258,245,458,455]
            }, {
                seriesType: 'bar',
                collectionAlias: 'Series B',
                data: [325,254,145,478,588]
            }]
        });
    });
</script>

A: I think that it is merely a synthax error that you have made. You need to set the desired duration, instead of adding true.
Here is the code that works:
applyAnimation: {
    duration: 1500
}


text:
Q: How to deploy a website via git pull? I am planning to use GitHub to manage the code for my next website. Although I have used GitHub in the past, I have never used it to deploy a website. My rather unsophisticated plan is as follows:

However, I have several concerns about this model:

*

*If I am using git pull on my remote server, does that mean my website directory itself will become a git repository? If so, is there a way I can avoid this? For instance, could I create a /var/repo directory to contain the git repository and then "copy" the code over to the actual website directory (/var/www)? Is there an efficient way to set this up?

*Let's assume I run git pull for the first time and deploy the website on my server. Next, let's assume I edit an existing file and add a file directly on the server via FTP. When I run git pull for the second time, how will git handle these two files? Will my edited file be replaced and my new file be deleted? Will my edited file be replaced and my new file untouched? Will I not be able to run git pull at all?

*Let's assume I have a file named config.php on my computer that contains the usernames/passwords for the various users that can access my databases. Since config.php on my computer is configured for my localhost environment, when I use git pull on my server for the first time I will have to edit the variables. As such, when I run git pull for the second time, is that file on my server replaced with the localhost version again?

*As a followup to the last question: what would be the best way to handle configuration files that contain data such as usernames and passwords? Not only do I want to hide this sensitive data from the public GitHub repository, but I also want to ensure that when I run git pull, the already-modified configuration files on my server remain untouched.

A: *

*You can not run git pull without being in a git repo so first time you have to do a git clone repo_url to get the code to remote server. If you don't want to keep .git in var/www i.e. your git repo so you can pull the code to some other directory then move the code using rsync or mv.

*Editing files directly on remote server in considered a bad practice and it can bring conflicts to your repo. Anyway if you edit directly on remote server you won't be able to pull from github because git will throw an error saying your local changes will be overwritten with this merge. So you have to either stash the changes or drop them completely.

*For files containing passwords and other things i would suggest use environment variables for both local and remote server. Use environment variables in config.php to get sensitive information from the system. You just have to set those environment variables in the remote server once

*If you have any sensitive data then just put those files in .gitignore. When you pull your code from github, any file in gitignore will remain untouched as git will ignore those files.

A: *

*Yes, it will. But, if you specify in your .htaccess(or equivalent file) that the .git folder is to not be served, it shouldn't make much of a difference to end users.

*If you are going to have the server git pull then you don't want to directly modify the content on the server. If you do, you would have to commit your changes on the server and then merge them with your local changes. This will become messy. So, just always modify on your local machine, and push and pull accordingly.

*You should never store passwords in plain text, especially in a public GitHub repo. Have a completely separate part of the server (that is not under git) that stores the usernames/passwords hashed and salted. You can FTP to this location separately. You could also have 2 separate files, one for local development and one for the server.

*I kinda already answered this, just make sure to store the usernames / passwords somewhere else.


text:
Q: jquery input field focus out except a div I'm making ajax suggestion of search in which,
a suggestion box will be displayed

    <input type="text" name="search" class="searchinput"/>

 ......
 Item 1
 .....

and Javascript
$('#searchbox .searchinput').focus(
 function () {
    $('#searchbox #sugbox').show();
 });

 $('#searchbox .searchinput').focusout(
 function () {
    $('#searchbox #sugbox').hide();
 });

The suggestion box will open if the search textbox #searchbox .searchinput is focus and hide if focusout.
Problem : whenever i'm clicking the link on suggestion box, the suggestion box hides (because of input focusout event).
How can i check if the target div is the suggestion box so don't hide the box
ex ..
 $('#searchbox .searchinput').focusout(
 function () {
    if(target div is not sugbox)
        $('#searchbox #sugbox').hide();
 });

A: try to assign a class to sugbox at hover class
 $(".searchinput").focus(function(){
   $("#sugbox").show();
});
$(".searchinput").focusout(function(){
   if(!$("#sugbox").hasClass("hovered"))
   $("#sugbox").hide();
});
 $("#sugbox").hover(function(){
   $(this).addClass("hovered");
},function(){
   $(this).removeClass("hovered");
 });

here is example at jsfiddle : http://jsfiddle.net/kyawlay/9wg49L2b/5

A: add a mousedown handler (triggerd before focusout/blur I think) on the box also, set a flag to true when clicked, then check this flag before hidding
var boxClicked = false;
$('#mainsearch .searchinput').mousedown(// listen click handler
 function () {   boxClicked = true;});
$(document).mousedown(// reset boxclicked
 function () {   boxClicked = false;});

$('#searchbox .searchinput').focus(
 function () {
    $('#searchbox #sugbox').show();
 });

 $('#mainsearch .searchinput').focusout(
 function () {
    if(!boxClicked)   $('#mainsearch #sugbox').hide();// add condition
 });

A: You are using wrong selector. Check this demo. http://jsfiddle.net/m711LLwr/
$('#searchbox #sugbox').show();

Should be
$('#mainsearch #sugbox').show();

A: Try this, What it does is when searchinput loses focus then if sugbox has no class 'NoHide', then hide it.
On body on click event, the NoHide class is assigned to sugbox if click target is not searchinput and not sugbox and not sugbox anchor.
If event target is not in above 3 mentioned selectors then remove class NoHide. I have a fiddle but I want you to try in your page as fiddle will confuse you( as it has iframe and body area of fiddle is limited).
$('#searchbox .searchinput').focus(
 function () {

    $('#sugbox').show();
 });

 $('#searchbox .searchinput').focusout(
 function (event) {
        if(!$('#sugbox').hasClass('NoHide'))
        $('#sugbox').hide();
 });

$('body').on('click',
 function (event) {

    if(!$(event.target).is(".searchinput") && !$(event.target).is("#sugbox a") &&  !$(event.target).is("#sugbox")){
        $("#sugbox").hide().removeClass('NoHide');
    }else
    {
      $("#sugbox").show().addClass('NoHide');
    }
 });


text:
Q: Core dumped in running Mesos cluster on docker I have a docker image called ubuntu_mesos_spark. I installed zookeeper on it. I change "zoo.cfg" file like this:
This is "zoo.cfg" in node1(150.20.11.157)
tickTime=2000
initLimit=10
syncLimit=5
clientPort=2187
dataDir=/var/lib/zookeeper
server.1=0.0.0.0:2888:3888
server.2=150.20.11.157:2888:3888
server.3=150.20.11.137:2888:3888

This is "zoo.cfg" in node1(150.20.11.134)
tickTime=2000
initLimit=10
syncLimit=5
clientPort=2187
dataDir=/var/lib/zookeeper
server.1=150.20.11.157:2888:3888
server.2=0.0.0.0:2888:3888
server.3=150.20.11.137:2888:3888

This is "zoo.cfg" in node1(150.20.11.137)
 tickTime=2000
 initLimit=10
 syncLimit=5
 clientPort=2187
 dataDir=/var/lib/zookeeper
 server.1=150.20.11.157:2888:3888
 server.2=150.20.11.134:2888:3888
 server.3=0.0.0.0:2888:3888

Also I made a "myid" file in "/var/lib/zookeeper" of each node. For example for "150.20.11.157" its ID is "1" in myid file.
I installed Mesos and Spark on the docker too. I have a Mesos cluster of these three nodes too. I defined IP address of slaves nodes on this file: "spark/conf/slaves"
150.20.11.134
150.20.11.137

I added these lines in "spark/conf/spark-env.sh":
export MESOS_NATIVE_JAVA_LIBRARY=/usr/local/lib/libmesos.so
export SPARK_EXECUTOR_URI=/home/spark/program_file/spark-2.3.2-bin-
hadoop2.7.tgz

Moreover, I added these lines in my "~/.bashrc" file:
export SPARK_HOME="/home/spark"
PYTHONPATH=$SPARK_HOME/python:$SPARK_HOME/python/lib/py4j-0.10.7-
src.zip:$PYTHO$
export PYSPARK_HOME=/usr/bin/python3.6
export PYSPARK_DRIVER_PYTHON=python3.6
export ZOO_LOG_DIR=/var/log/zookeeper

I  want to run master code in "150.20.11.157".My docker-compose is :
 version: '3.7'
 services:
  zookeeper:
  image: ubuntu_mesos_spark
  command: /zookeeper-3.4.12/bin/zkServer.sh start
  environment:
   ZOOKEEPER_SERVER_ID: 1
   ZOOKEEPER_CLIENT_PORT: 2187
   ZOOKEEPER_TICK_TIME: 2000
   ZOOKEEPER_INIT_LIMIT: 10
   ZOOKEEPER_SYNC_LIMIT: 5
   ZOOKEEPER_SERVERS:
   0.0.0.0:2888:3888;150.20.11.134:2888:3888;150.20.11.137:2888:3888
 network_mode: host
 expose:
  - 2187
  - 2888
  - 3888
 ports:
  - 2187:2187
  - 2888:2888
  - 3888:3888

master:
image: ubuntu_mesos_spark
command: bash -c "sleep 20; /home/mesos-1.7.0/build/bin/mesos-
master.sh --ip=150.20.11.157 --work_dir=/var/run/mesos"
restart: always
depends_on:
 - zookeeper
environment:
 - MESOS_HOSTNAME="150.20.11.157,150.20.11.134,150.20.11.137"
 - MESOS_QUORUM=1
 - MESOS_LOG_DIR=/var/log/mesos
expose:
 - 5050
 - 4040
 - 7077
 - 8080
ports:
  - 5050:5050
  - 4040:4040
  - 7077:7077
  - 8080:8080

Also, I run this compose file on slaves nodes :"150.20.11.134,150.20.11.137":
 version: '3.7'
 services:
  zookeeper:
  image: ubuntu_mesos_spark
  command: /zookeeper-3.4.12/bin/zkServer.sh start
  environment:
   ZOOKEEPER_SERVER_ID: 2
   ZOOKEEPER_CLIENT_PORT: 2187
   ZOOKEEPER_TICK_TIME: 2000
   ZOOKEEPER_INIT_LIMIT: 10
   ZOOKEEPER_SYNC_LIMIT: 5
   ZOOKEEPER_SERVERS:
   0.0.0.0:2888:3888;150.20.11.134:2888:3888;150.20.11.137:2888:3888
 network_mode: host
 expose:
  - 2187
  - 2888
  - 3888
 ports:
  - 2187:2187
  - 2888:2888
  - 3888:3888

slave:
image: ubuntu_mesos_spark
command: bash -c "/home/mesos-1.7.0/build/bin/mesos-slave.sh --
master=150.20.11.157:5050 --work_dir=/var/run/mesos
--systemd_enable_support=false"
restart: always
privileged: true
network_mode: host
depends_on:
- zookeeper
environment:
 - MESOS_HOSTNAME="150.20.11.157,150.20.11.134,150.20.11.137"
 - MESOS_MASTER=150.20.11.157
 - MESOS_EXECUTOR_REGISTRATION_TIMEOUT=5mins #also in Dockerfile
 - MESOS_CONTAINERIZERS=docker,mesos
 - MESOS_LOG_DIR=/var/log/mesos
 - MESOS_LOGGING_LEVEL=INFO
expose:
  - 5051
ports:
  - 5051:5051

First I run "sudo docker-compose up" on Master node. Then I run it on slaves nodes. But I get this error:
On Master node, the error is:

Starting marzieh-compose_zookeeper_1 ... done
Recreating marzieh-compose_master_1  ... done
Attaching to marzieh-compose_zookeeper_1, marzieh-compose_master_1
zookeeper_1  | ZooKeeper JMX enabled by default
zookeeper_1  | Using config: /zookeeper-3.4.12/bin/../conf/zoo.cfg
zookeeper_1  | Starting zookeeper ... STARTED
marzieh-compose_zookeeper_1 exited with code 0
master_1     | I0123 11:46:59.585522     7 logging.cpp:201] INFO level logging started!
master_1     | I0123 11:46:59.586066     7 main.cpp:242] Build: 2019-01-21 05:16:39 by
  master_1     | I0123 11:46:59.586097     7 main.cpp:243] Version: 1.7.0
master_1     | F0123 11:46:59.587368     7 process.cpp:1115] Failed to initialize: Failed to bind on 150.20.11.157:5050: Cannot assign requested address
master_1     | * Check failure stack trace: *
master_1     |     @     0x7f505ce54b9c  google::LogMessage::Fail()
master_1     |     @     0x7f505ce54ae0  google::LogMessage::SendToLog()
master_1     |     @     0x7f505ce544b2  google::LogMessage::Flush()
master_1     |     @     0x7f505ce57770
  google::LogMessageFatal::~LogMessageFatal()
master_1     |     @     0x7f505cd19ed1  process::initialize()
master_1     |     @     0x55fb7b12981a  main
master_1     |     @     0x7f504f0d0830  (unknown)
master_1     |     @     0x55fb7b1288b9  _start
master_1     | bash: line 1:     7 Aborted                 (core dumped) /home/mesos-1.7.0/build/bin/mesos-master.sh --ip=150.20.11.157 --work_dir=/var/run/mesos

Moreover when I run "sudo docker-compose up" on slave nodes. I got this error:

slave_1      | F0123 11:40:06.878793     1 process.cpp:1115] Failed to initialize: Failed to bind on 0.0.0.0:5051: Address already in use
slave_1      | * Check failure stack trace: *
slave_1      |     @     0x7fee9d319b9c  google::LogMessage::Fail()
slave_1      |     @     0x7fee9d319ae0  google::LogMessage::SendToLog()
slave_1      |     @     0x7fee9d3194b2  google::LogMessage::Flush()
slave_1      |     @     0x7fee9d31c770
  google::LogMessageFatal::~LogMessageFatal()
slave_1      |     @     0x7fee9d1deed1  process::initialize()
slave_1      |     @     0x55e99f661784  main
slave_1      |     @     0x7fee8f595830  (unknown)
slave_1      |     @     0x55e99f65f139  _start
slave_1      | * Aborted at 1548243606 (unix time) try "date -d @1548243606" if you are using GNU date *
slave_1      | PC: @     0x7fee8f5ac196 (unknown)
slave_1      | * SIGSEGV (@0x0) received by PID 1 (TID 0x7fee9f9f38c0) from PID 0; stack trace: *
slave_1      |     @     0x7fee8fee8390 (unknown)
slave_1      |     @     0x7fee8f5ac196 (unknown)
slave_1      |     @     0x7fee9d32055b google::DumpStackTraceAndExit()
slave_1      |     @     0x7fee9d319b9c google::LogMessage::Fail()
slave_1      |     @     0x7fee9d319ae0 google::LogMessage::SendToLog()
slave_1      |     @     0x7fee9d3194b2 google::LogMessage::Flush()
slave_1      |     @     0x7fee9d31c770 google::LogMessageFatal::~LogMessageFatal()
slave_1      |     @     0x7fee9d1deed1 process::initialize()
slave_1      |     @     0x55e99f661784 main
slave_1      |     @     0x7fee8f595830 (unknown)
slave_1      |     @     0x55e99f65f139 _start
slave_1      | I0123 11:41:07.818897     1 logging.cpp:201] INFO level logging started!
slave_1      | I0123 11:41:07.819437     1 main.cpp:349] Build: 2019-01-21 05:16:39 by
slave_1      | I0123 11:41:07.819470     1 main.cpp:350] Version: 1.7.0
slave_1      | I0123 11:41:07.823354     1 resolver.cpp:69] Creating default secret resolver
slave_1      | E0123 11:41:07.927773     1 main.cpp:483] EXIT with status 1: Failed to create a containerizer: Could not create
  DockerContainerizer: Failed to create docker: Failed to get docker version: Failed to execute 'docker -H unix:///var/run/docker.sock --
  version': exited with status 127

I searched a lot about that and I could not figure this out. Would you please guide me what the right way is to write docker compose for running Mesos and Spark cluster on docker?
Any help would be appreciated.
Thanks in advance.

A: Problem solved. I changed docker compose like this and Master and Slaves run without problem:
"docker-compose.yaml" in Master node is in the following:
version: '3.7'
services:
zookeeper:
 image: ubuntu_mesos_spark_python3.6_client
 command: /home/zookeeper-3.4.12/bin/zkServer.sh start
 environment:
  ZOOKEEPER_SERVER_ID: 1
  ZOOKEEPER_CLIENT_PORT: 2188
  ZOOKEEPER_TICK_TIME: 2000
  ZOOKEEPER_INIT_LIMIT: 10
  ZOOKEEPER_SYNC_LIMIT: 5
  ZOOKEEPER_SERVERS: 0.0.0.0:2888:3888;150.20.11.157:2888:3888
 network_mode: host
 expose:
  - 2188
  - 2888
  - 3888
 ports:
  - 2188:2188
  - 2888:2888
  - 3888:3888

master:
image: ubuntu_mesos_spark_python3.6_client
command: bash -c "sleep 30; /home/mesos-1.7.0/build/bin/mesos-master.sh
--ip=150.20.10.136 --work_dir=/var/run/mesos --hostname=x.x.x.x"  ##hostname :
IP of the master node
restart: always
network_mode: host
depends_on:
 - zookeeper
environment:
- MESOS_HOSTNAME="150.20.11.136"
- MESOS_QUORUM=1
- MESOS_LOG_DIR=/var/log/mesos
expose:
 - 5050
 - 4040
 - 7077
 - 8080
ports:
 - 5050:5050
 - 4040:4040
 - 7077:7077
 - 8080:8080

Also,"docker-compose.yaml" file in slave node is like this:
 version: '3.7'
 services:
  zookeeper:
   image: ubuntu_mesos_spark_python3.6_client
   command: /home/zookeeper-3.4.12/bin/zkServer.sh start
   environment:
     ZOOKEEPER_SERVER_ID: 2
     ZOOKEEPER_CLIENT_PORT: 2188
     ZOOKEEPER_TICK_TIME: 2000
     ZOOKEEPER_INIT_LIMIT: 10
     ZOOKEEPER_SYNC_LIMIT: 5
     ZOOKEEPER_SERVERS: 150.20.11.136:2888:3888;0.0.0.0:2888:3888
   network_mode: host
   expose:
   - 2188
   - 2888
   - 3888
   ports:
   - 2188:2188
   - 2888:2888
   - 3888:3888

 slave:
 image: ubuntu_mesos_spark_python3.6_client
 command: bash -c "sleep 30; /home/mesos-1.7.0/build/bin/mesos-slave.sh
 --master=150.20.11.136:5050 --work_dir=/var/run/mesos
 --systemd_enable_support=false"
 restart: always
 privileged: true
 network_mode: host
 depends_on:
 - zookeeper
 environment:
 - MESOS_HOSTNAME="150.20.11.157"
 #- MESOS_MASTER=172.28.10.136
 #- MESOS_EXECUTOR_REGISTRATION_TIMEOUT=5mins #also in Dockerfile
 #- MESOS_CONTAINERIZERS=docker,mesos
 - MESOS_LOG_DIR=/var/log/mesos
 - MESOS_LOGGING_LEVEL=INFO
expose:
 - 5051
ports:
 - 5051:5051

Then I run "docker-compose up" in each node and they run without any problems.