Q: Get source branch name in commit-msg hook of merge commit In the commit-msg hook for a merge commit, how can I get the branch name of the immediate source branch for the merge?  I can get the target branch with something like
git rev-parse --abbrev-ref HEAD

But HEAD and HEAD^ both refer to the target branch.  Is there a way to programmatically determine the source?  I'm using a bash script for the hook.
The default merge commit message contains this text:

Merge branch 'source-branch' into target-branch

So the commit-msg hook could grab the name right out of the message, but there's no guarantee that the user hasn't edited it.  If there's a more foolproof method, I would prefer it.
Edit: ah, unfortunately I also didn't realize that commit-msg doesn't actually even run on merge commits!  So I'll have to find a different way to do what I want anyway.

A: This will give you the commit being merged:
git rev-parse MERGE_HEAD

I do not think that there is a way to find the branch name other than guessing with a command like:
git for-each-ref | grep ^$(git rev-parse MERGE_HEAD)

(which finds all branches pointing to the commit you are merging)
Note that the commit being merged does not have to be a branch, one can also merge a commit directly like git merge deadbeef.
In the case of octopus merge, there is more than one commit being merged at the same time, and MERGE_HEAD is not present.
If you are to extract it from the merge message, then using .git/MERGE_MSG is safer than .git/COMMIT_EDITMSG, since it is less likely to be hand-edited.
The message is generated by git merge, hence has access to the branch name from git merge's arguments, but this does not seem to be stored on disk.

A:
but there's no guarantee that the user hasn't edited it

imvho you should use the merge commit summary line, after the user has had a chance to edit it.
I've edited subject lines for good reason.  All branch names are repo-local. Sometimes you're pulling from a coworker, sometimes you realize you typo'd during branch creation, or you're publishing from a wip that turned out well, there's lots more ways to get there.
If you're worried about inbound commits not meeting your standards for one of your own repositories, vet the inbound commits in its pre-receive.  No dvcs can be sure without doing that anyway.
#!/bin/sh
rc=0
existing=$(git for-each-ref --format='%(object)' refs/heads refs/tags);
validmergesubject='Merge (branch|tag) '\''[^ ]*'\'' (of|into) .*'
while read old new ref; do
    while read commit Subject; do
        if [[ ! $Subject =~ $validmergesubject ]]; then
            echo Merge $commit in $ref history has invalid summary line \"$Subject\"
            rc=1;
        fi;
    done  >&2 <<EOD
$(git log --merges --pretty='%H %s' $new --not $existing)
EOD
done
exit $rc


Q: How to get a range of elements from an array in Redisjson? I have a simple array as such :
[1,2,3,4,5]

and I wish to get a range for example from index 2 to index 4.
I can get the last element of the array by :
json.get key .[-1]

However I cannot find anyway to return a specific results without trimming the array.
Is there anyway I can get a range of elements from a Redis json array?

A: The answer is :
await Client.json.get("key" , {path : '$.[1:3]'})

which gets index 1 to 3.


Q: How to hide url in the popup window opened using window.open I am using below code to open a popup window in my page:
window.open("myPopupWindow.html", "_blank", "height=400, width=550, status=yes, toolbar=no, menubar=no, location=no, addressbar=no, top=200, left=300");

Although the url is disabled but even then it can be seen and copied. I have already set addressbar to no. How can I hide url in popup window?

A: Are you just trying to mask the address, to make it look nicer or hide the fact that you're linking to to another website, or is it that you don't want people to know they can access that page without using your popup?
If it's the former, then what you could do is make the page you open in window.open an iframe, and point the iframe to your actual page.  They user could still access the target page, but only via your nicer looking url.
The other option is to use something like a colorbox with an iframe instead of window.open, which will mask the address. Have a look at the Outside Webpage (iframe) example on this page.
Of course whichever option you choose, someone smart can still track down the target url via the source code and go there directly.

A: window.open('http://mysite/proxy.html')

and in proxy.html :
  <html>
       <body>
          <iframe src="/realPage.html"></iframe>
       </body>

  </html>

A: Simple solution open new tab after that add url to location.href.
window.open('','_blank').location.href = "url"


Q: QFileDialog::getOpenFileName doesn't set the initial directory on Mac OS 10.8 Mountain Lion I can not change the current directory with QFileDialog with Qt 4.8. The same code works fine on Windows and Mac OS 10.6 Snow Leopard. It also works fine if I don't use the native Mac OS X dialog.
This works:
fn=QFileDialog::getOpenFileName(this,"Select File","/Users/myuser/Desktop",QString(),0,QFileDialog::DontUseNativeDialog);

This doesn't work:
fn=QFileDialog::getOpenFileName(this,"Select File","/Users/myuser/Desktop");

It looks like if most of the time it opens the last path of the last call to getOpenFileName.

A: Got the same issue with Qt5.2.0 on Mavericks...
I found a work around: append a dummy file name to the directory you want to select.
However, be sure not to do this on Windows because the user will see it.
QString dir = "/Users/myuser/Desktop";
#if defined(__APPLE__)
dir += "/MyFile.txt";
#endif
fn = QFileDialog::getOpenFileName(this, "Select File", dir);

Also, for those like me that instantiate a file dialog because they need more options you can also do:
QFileDialog fileDialog(this, "Select File");
#if defined(__APPLE__)
fileDialog.selectFile(dir + "/MyFile.txt");
#else
fileDialog.setDirectory(dir);
#endif
...

A: This is a bug in Qt that is reportedly fixed in Qt 5.0.1 and Qt 4.8.4 (though it seems that it still reproducible in 4.8.4 by people (myself included)).
This bug has been reported in JIRA as QTBUG-20771, QTBUG-28161 and finally QTBUG-35779 (which appears to have finally fully resolved the issue in Qt 5.2.1). Here is a link to the patch in Gerrit.


Q: Navigator.getUserMedia and Navigator.webkitGetUserMedia undefined after updating to Chrome 74 After updating from Chrome 73 to 74 navigator.getUserMedia and navigator.webkitGetUserMedia return undefined.
Here https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getUserMedia I see that getUserMedia is actually deprecated in favor of navigator.mediaDevices.getUserMedia(), but in my case navigator.mediaDevices too is undefined so I cannot use it.
Anyone knows if it's a bug in the latest release of Chrome or if I need to use something else?

A: I tried a small setting on chrome and it turned out to work for me.
I enabled: chrome://flags/#unsafely-treat-insecure-origin-as-secure
and provided my HTTP server link along with the port.
It worked for me.
You could refer to the following:
1. https://stackoverflow.com/a/61472984/12906501
2. https://medium.com/@Carmichaelize/enabling-the-microphone-camera-in-chrome-for-local-unsecure-origins-9c90c3149339
Hope it helps!! Thanks.

A: Since version 74 of Chrome navigator.getUserMedia, navigator.webkitGetUserMedia and navigator.mediaDevices can be used only in secure context (https), otherwise they are undefined.
I've understood what the problem was while writing the question, as usual...

A: In my case HTTP was the cause of undefined for navigator.mediaDevices
with HTTPS works as expected


Q: ng-file-upload issue on IE9 - after uploading one file receiving error var prevFiles = ((ngModel && ngModel.$modelValue) || attr.$$ngfPrevFiles || []).slice(0);

I am getting an error that the result of this statement does not have a slice method.

A: Without knowing too much about the module I have a theory:
The first evaluation (ngModel && ngModel.$modelValue), when true, returns a Boolean which does not have a slice method.

A: There was an issue filed in Github about this https://github.com/danialfarid/ng-file-upload/issues/1139
Reportedly fixed in release 10.0.3.


Q: How can the code being allowed to continue from one question to another question even though the input answer had wrong for 3 attempts?

import time
import random
#declare variables and constant
guessingelement = ["Hydrogen", "Magnesium", "Cobalt", "Mercury", "Aluminium", "Uranium", "Antimony"]
nicephrases = ["Nice job", "Marvellous", "Wonderful", "Bingo", "Dynamite"]
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
guess_no = 0
score = 0

#set the maximum number of questions for looping and random pick an element from the list before deleting it
for i in range(7):
    randomelement = random.choice(guessingelement)
    guessingelement.remove(randomelement)
    time.sleep(2)

#tips of the element
if randomelement == "Hydrogen" and not out_of_guesses:
    print("Tip 1: It is the most flammable of all the known substances.")
    print("Tip 2: It reacts with oxides and chlorides of many metals, like copper, lead, mercury, to produce free metals.")
    print("Tip 3: It reacts with oxygen to form water.")

    #test the number of tries so that it doesn't exceed 3 times if answer is wrong
    while guess != randomelement and not(out_of_guesses):
        if guess_count < guess_limit:
            guess = input("Enter guess: ")
            guess_count += 1
        else:
            out_of_guesses = True

    #add score, praise when answer is correct and encourage when answer is wrong for 3 times
    if out_of_guesses:
        print("Out of Guesses, NICE EFFORT!")
    else:
        print(random.choice(nicephrases), ", YOU GET IT!")
        score = score + 1

#tips of the element
    if randomelement == "Magnesium" and not out_of_guesses:
        print("Tip 1: It has the atomic number of 12.")
        print("Tip 2: It's oxide can be extracted into free metal through electrolysis.")
        print("Tip 3: It is a type of metal.")

Same as first questions' code..
and so on....

In the progress of changing:`
#tips of the element
    if randomelement == "Hydrogen":
        print("Tip 1: It is the most flammable of all the known substances.")
        print("Tip 2: It reacts with oxides and chlorides of many metals, like copper, lead, mercury, to produce free metals.")
        print("Tip 3: It reacts with oxygen to form water.")

    #test the number of tries so that it doesn't exceed 3 times if answer is wrong

        while guess != randomelement:
            if guess_count < guess_limit:
                guess = input("Enter guess: ")
                guess_count += 1
            else:
                print(random.choice(wronganswers))

        #add score, praise when answer is correct and encourage when answer is wrong for 3 times
        else:
            print(random.choice(nicephrases), ", YOU GET IT!")
            score = score + 1

However, after 3 times of attempts, it keeps printing the elements from the wronganswers list non-stop,
and can't proceed to the next question.
The output I expected is that it will show an element from the list when the input answer is wrong and
proceed to the next question.

A: I hope this helps. I wrote this code for myself in a new way. I have used recursion to keep the guess happening and simple used a while loop that will break when max attempts go beyond 3.
import random

elements = ["hydrogen", "magnesium", "cobalt", "mercury", "aluminium", "uranium", "antimony"]
nice_phrases = ["Nice job", "Marvellous", "Wonderful", "Bingo", "Dynamite"]

# I went ahead and created a dictionary of lists for storing the Hints
hints = {
    'hydrogen':
        [
            "Tip 1: It is the most flammable of all the known substances.",
            "Tip 2: It reacts with oxides and chlorides of many metals, "
            "like copper, lead, mercury, to produce free metals.",
            "Tip 3: It reacts with oxygen to form water."
        ],
    'magnesium':
        [
            "Tip 1: It has the atomic number of 12.",
            "Tip 2: It's oxide can be extracted into free metal through electrolysis.",
            "Tip 3: It is a type of metal."
        ],
}

score = 0

def guess_again():
    global score
    random_element = random.choice(elements)
    max_attempts = 3

    # this will remove the element from occurring again
    for x in elements:
        if x == random_element:
            elements.remove(x)

    while max_attempts > 0:
        user_guess = input("Take a Guess").lower()

        if user_guess == random_element:
            print(f"{random.choice(nice_phrases)}, you got it!")
            score += 1
            # If the answer is right calling the function again will continue the game
            guess_again()
        else:
            max_attempts -= 1
            print("That was a wrong guess. Here is a Hint")
            if random_element in hints:
                print(hints[random_element])
            else:
                print("Sorry no hints available at the moment")
        if max_attempts == 0:
            print("Sorry your out of guesses")
            print(f"{random.choice} was the element")

guess_again()

If the Answer is right it will select the next element and the game continues until all the elements in the list are finished. I have coded it to give 3 attempts for each elements. If you want the maximum 3 attempts for the entire duration of the game just declare max_attempts outside the function and give it global scope like done for score


Q: if_attribute on declarative authorization I have a many-to-many relationship like this:
A user has_many organizations through affiliations and vice-versa.
I'm using declarative organizations and I only want a user to edit a particular organization if he is affiliated and the affiliationtype attribute of affiliation is a particular value.
So affiliations has 3 columns , user_id, organization_id and affiliationtype_id
I can do:
o = Organization.find(:first)
o.affiliatons[0].user and get the user

now I wish to do this:
has_permission_on [:organizations], :to => :edit do
  if_attribute (...)
end

That if_attribute should see if the current user is the organization.affiliation[?].user and if the organization.affiliation[?].affiliationtype_id = "3"
I hope this is syntax issue ... I really need to get this working.

A: EDIT:
You can restrict the type of affiliation with intersects_with(&block) :
  has_permission_on [:organizations], :to => :edit do
    if_attribute :affiliations => intersects_with {
      user.affiliations.with_type_3
    }
  end

Why not create a named_scope to find affiliations whose affiliationtype_id = 3?

From declarative_authorization documentation:
To reduce redundancy in has_permission_on blocks, a rule may depend on permissions on associated objects:
authorization do
  role :branch_admin do
    has_permission_on :branches, :to => :manage do
      if_attribute :managers => contains {user}
    end

    has_permission_on :employees, :to => :manage do
      if_permitted_to :manage, :branch
      # instead of
      #if_attribute :branch => {:managers => contains {user}}
    end
  end
end


Q: Print "hello world" every X seconds Lately I've been using loops with large numbers to print out Hello World:
int counter = 0;

while(true) {
    //loop for ~5 seconds
    for(int i = 0; i < 2147483647 ; i++) {
        //another loop because it's 2012 and PCs have gotten considerably faster :)
        for(int j = 0; j < 2147483647 ; j++){ ... }
    }
    System.out.println(counter + ". Hello World!");
    counter++;
}

I understand that this is a very silly way to do it, but I've never used any timer libraries in Java yet. How would one modify the above to print every say 3 seconds?

A: You can use Thread.sleep(3000) inside for loop.
Note: This will require a try/catch block.

A: public class HelloWorld extends TimerTask{

    public void run() {

        System.out.println("Hello World");
    }
}

public class PrintHelloWorld {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new HelloWorld(), 0, 5000);

        while (true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                System.out.println("InterruptedException Exception" + e.getMessage());
            }
        }
    }
}

infinite loop is created ad scheduler task is configured.

A: The easiest way would be to set the main thread to sleep for 3000 milliseconds (3 seconds):
for(int i = 0; i< 10; i++) {
    try {
        //sending the actual Thread of execution to sleep X milliseconds
        Thread.sleep(3000);
    } catch(InterruptedException ie) {}
    System.out.println("Hello world!");
}

This will stop the thread at least X milliseconds. The thread could be sleeping more time, but that's up to the JVM. The only thing guaranteed is that the thread will sleep at least those milliseconds. Take a look at the Thread#sleep doc:

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

A: Try doing this:
Timer t = new Timer();
t.schedule(new TimerTask() {
    @Override
    public void run() {
       System.out.println("Hello World");
    }
}, 0, 5000);

This code will run print to console Hello World every 5000 milliseconds (5 seconds).
For more info, read https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html

A: Use java.util.Timer and Timer#schedule(TimerTask,delay,period) method will help you.
public class RemindTask extends TimerTask {
    public void run() {
      System.out.println(" Hello World!");
    }
    public static void main(String[] args){
       Timer timer = new Timer();
       timer.schedule(new RemindTask(), 3000,3000);
    }
  }

A: If you want to do a periodic task, use a ScheduledExecutorService. Specifically ScheduledExecutorService.scheduleAtFixedRate
The code:
Runnable helloRunnable = new Runnable() {
    public void run() {
        System.out.println("Hello world");
    }
};

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(helloRunnable, 0, 3, TimeUnit.SECONDS);

A: You can also take a look at Timer and TimerTask classes which you can use to schedule your task to run every n seconds.
You need a class that extends TimerTask and override the public void run() method, which will be executed everytime you pass an instance of that class to timer.schedule() method..
Here's an example, which prints Hello World every 5 seconds: -
class SayHello extends TimerTask {
    public void run() {
       System.out.println("Hello World!");
    }
}

// And From your main() method or any other method
Timer timer = new Timer();
timer.schedule(new SayHello(), 0, 5000);

A: This is the simple way to use thread in java:
for(int i = 0; i< 10; i++) {
    try {
        //sending the actual Thread of execution to sleep X milliseconds
        Thread.sleep(3000);
    } catch(Exception e) {
        System.out.println("Exception : "+e.getMessage());
    }
    System.out.println("Hello world!");
}

A: I figure it out with a timer, hope it helps. I have used a timer from java.util.Timer and TimerTask from the same package. See below:
TimerTask task = new TimerTask() {

    @Override
    public void run() {
        System.out.println("Hello World");
    }
};

Timer timer = new Timer();
timer.schedule(task, new Date(), 3000);

A: What he said. You can handle the exceptions however you like, but
    Thread.sleep(miliseconds);
is the best route to take.
public static void main(String[] args) throws InterruptedException {

A: Here's another simple way using Runnable interface in Thread Constructor
public class Demo {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                for(int i = 0; i < 5; i++){
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("Thread T1 : "+i);
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                for(int i = 0; i < 5; i++) {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("Thread T2 : "+i);
                }
            }
        });

        Thread t3 = new Thread(new Runnable() {

            @Override
            public void run() {
                for(int i = 0; i < 5; i++){
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("Thread T3 : "+i);
                }
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}

A: Add Thread.sleep
try {
        Thread.sleep(3000);
    } catch(InterruptedException ie) {}

A: For small applications it is fine to use Timer and TimerTask as Rohit mentioned but in web applications I would use Quartz Scheduler to schedule jobs and to perform such periodic jobs.
See tutorials for Quartz scheduling.

A: public class TimeDelay{
  public static void main(String args[]) {
    try {
      while (true) {
        System.out.println(new String("Hello world"));
        Thread.sleep(3 * 1000); // every 3 seconds
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}


Q: how to create a single webapplication as a sub domain for many companies i am working on a project that you can subscribe with your company name and you can use all features of site specificly to your company.
for example company abcd can get its own url from our website like
www.test.com/abcd/productlist.aspx
company efgh can also login with its own url and see its product list.
www.test.com/efgh/productlist.aspx
can any one help me how can i implement this with my site with best approaches
I am thinking on the approach that will use Global.ascx file to distinguish companies,
i will write code to extract company name from url in global.ascx for every valid request and in all the pages i will put this.form.action = request.rawurl.
is there any other approaches?
if anybody implemented this type of feature, please let me know your approaches.
Thanks

A: If you're working with ASP.NET 3.5 SP1 then you should investigate the new routing engine that has been introduced from the MVC project. It will make for a clean solution.

A: We are using the DLL from http://urlrewriting.net and rules similar to the following:
<urlrewritingnet xmlns="http://www.urlrewriting.net/schemas/config/2006/07">
  <rewrites>
    <add name="Customer" virtualUrl="^~/([^/]+)/([^/]+).aspx" destinationUrl="~/$2.aspx?customer=$1"/>
    <add name="CustomerStart" virtualUrl="^~/([^/]+)/$" destinationUrl="~/Default.aspx?customer=$1"/>
    <add name="CustomerStartAddSlash" virtualUrl="^http\://([^/]+)/([a-zA-Z0-9_-]+)$"
                                      destinationUrl="http://www.example.com/$2/"
                                      redirect="Domain" redirectMode="Permanent" />
  </rewrites>
</urlrewritingnet>

Those rules do the following mappings. These are rewrites, so the user always sees the left-hand URL in his browser:
Rule 1: http://www.example.com/customerA/something.aspx => http://www.example.com/something.aspx?customer=customerA
Rule 2: http://www.example.com/customerA/ => http://www.example.com/Default.aspx?customer=customerA

The third rule is a redirect rather than a rewrite, i.e., it ensures that the trailing slash is added in the user's browser (makes sure that relative paths work correctly):
Rule 3: http://www.example.com/customerA => http://www.example.com/customerA/

A: Take a look at these questions.
Your approach has a name. It's called Multitenancy.

A: I did not found any solution that fully suites my requirement , I have written my own logic for this , which uses Global.ascx's BeginRequest, Login page, Base page and common classes created for Response.Redirect. I am no longer directly using Asp.Net's Response.Redirect, Paths and Session variables, instead I have created wrappers over them to add companyName from url to the Paths.
Let me know if you need more information on my code
Other answers are welcome.
Thanks


Q: How to send a Whatsapp message to a specific user using third party apps in iPhone? Let my app be A and the app user is called A1
I have a completely different person with his mobile mobile number - N1
Now I want achieve the following in my app A - When the user A1 clicks on a button, Whatsapp is opened(if present) with a compose message to the number N1, whether or not he is in his contact list.
I am pretty sure that this is possible on Android as I my self have done it but in iOS, I am not able to find any solution. What ever solutions are out there don't achieve what I want as they open Whatsapp in general, and show me all the users out there. Please, do not redirect to the Whatsapp.com support URL as it is pretty useless.


Q: Ember : sortBy or Ember.computed.sort I saw an example of Ember sortBy somewhere which goes like:
model.sortBy("time").reverse().sortBy("place")

It was working, but am not sure if this is a good way to do that. Would the below a better fit for this. If yes, why.
sortOptions: ['time:desc','place']
Ember.computed.sort('model',sortOptions)

A: model.sortBy("time").reverse().sortBy("place")

Will sort the array model one time.
Ember.computed.sort('model',sortOptions)

Will recompute its value every time model or its properties change.
So what you should use depends on what you need. I don't think there's a significant difference in performance of the sort itself.


Q: PHP extension conflict with Ioncube extension The problem is with the IonCube obfuscation library being used to encode/obfuscate their PHP application.
This IonCube library which is a zend extension, is interfering with PHP extension.
When IonCube is enabled, for all encoded/obfuscated PHP pages monitored, PHP extensions’ “myextensionfunc” method is being skipped because of which I am having problem in my extension code and some transaction related values are missing.
“myextensionfunc i.e. (zend_execute)” function is used by my PHP extension to identify the some transaction related values and to monitor php app methods.
Problem here is that - Is there any workaround(apart from disabling ioncube) so that ioncube doesn't interfere with my php extension?
Please provide some thoughts on this, thanks.


Q: can't get href from beautifulsoup from 'a class' I'm trying to extract the href from this web site,
but I can't find the way to do that, I tried using this:
busqueda = requests.get('https://autos.mercadolibre.com.ar/vento/_DisplayType_LF')
auto_cont = BeautifulSoup(busqueda.content)
auto_cont.find_all('a',{'class':'item__info-title'}, href = True)

But there is a '< span>' content and I can't overcome that.

A: find_all has been explained. However, your selector is going to produce duplicates as it will pull the same urls from title and price. Instead, I would use a child combinator and a different class for parent and add a child a tag to get the unique list. I prefer select over find_all. select applies css selectors in order to match on elements. All these a tags have an href so no need to add a test.
from bs4 import BeautifulSoup as bs
import requests

r = requests.get('https://autos.mercadolibre.com.ar/volkswagen/vento/_DisplayType_LF')
soup = bs(r.content, 'lxml')
links = [item['href'] for item in soup.select('.list-view-item-title > a')]

Child combinator:

The child combinator (>) is placed between two CSS selectors. It
  matches only those elements matched by the second selector that are
  the children of elements matched by the first.

Ref:

*

*https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.html?highlight=select_one#css-selectors

A: Since you are using Beautiful Soup, it is important to understand that the find_all method will return a list of tags that match your requirements. Your issue is that you want the href attribute of those tags. To do that, you can use the notation tag['attr'] on each tag. To do that we will iterate through the returned tags.
from bs4 import BeautifulSoup
import requests

busqueda = requests.get('https://autos.mercadolibre.com.ar/vento/_DisplayType_LF')
auto_cont = BeautifulSoup(busqueda.content)
print([tag['href'] for tag in auto_cont.find_all('a',{'class':'item__info-title'}, href = True)])

A: Try this:
>>> import requests
>>> s = requests.Session()
>>> resp = s.get("https://autos.mercadolibre.com.ar/vento/_DisplayType_LF")
>>> from lxml import html
>>> doc = html.fromstring(resp.text)
>>> doc.xpath("//a[@class='item__info-title']")
[<Element a at 0x11c005688>, <Element a at 0x11c0059a8>, <Element a at 0x11c007e58>, <Element a at 0x11c007ea8>, <Element a at 0x11c007ef8>, <Element a at 0x11c007c78>, <Element a at 0x11c007db8>, <Element a at 0x11c007e08>, <Element a at 0x11c007d68>, <Element a at 0x11c007cc8>, <Element a at 0x11c007d18>, <Element a at 0x11c007bd8>, <Element a at 0x11c007c28>, <Element a at 0x11c007228>, <Element a at 0x11c003318>, <Element a at 0x11c003408>, <Element a at 0x11c0034f8>, <Element a at 0x11c003688>, <Element a at 0x11c0035e8>, <Element a at 0x11c003228>, <Element a at 0x11c003598>, <Element a at 0x11c003458>, <Element a at 0x11c003278>, <Element a at 0x11c003548>, <Element a at 0x11c0034a8>, <Element a at 0x11c003368>, <Element a at 0x11c0033b8>, <Element a at 0x11c0032c8>, <Element a at 0x11c0031d8>, <Element a at 0x11c003188>, <Element a at 0x11c003098>, <Element a at 0x11c003138>, <Element a at 0x11c0030e8>, <Element a at 0x11c003048>, <Element a at 0x11c0036d8>, <Element a at 0x11c003728>, <Element a at 0x11c003778>, <Element a at 0x11c0037c8>, <Element a at 0x11c003818>, <Element a at 0x11c003868>, <Element a at 0x11c0038b8>, <Element a at 0x11c003908>, <Element a at 0x11c003958>, <Element a at 0x11c0039a8>, <Element a at 0x11c0039f8>, <Element a at 0x11c003a48>, <Element a at 0x11c003a98>, <Element a at 0x11c003ae8>, <Element a at 0x11c003b38>, <Element a at 0x11c003b88>, <Element a at 0x11c003bd8>, <Element a at 0x11c003c28>, <Element a at 0x11c003c78>, <Element a at 0x11c003cc8>, <Element a at 0x11c003d18>, <Element a at 0x11c003d68>, <Element a at 0x11c003db8>, <Element a at 0x11c003e08>, <Element a at 0x11c003e58>, <Element a at 0x11c003ea8>, <Element a at 0x11c003ef8>, <Element a at 0x11c003f48>, <Element a at 0x11c003f98>, <Element a at 0x11c006048>, <Element a at 0x11c006098>, <Element a at 0x11c0060e8>, <Element a at 0x11c006138>, <Element a at 0x11c006188>, <Element a at 0x11c0061d8>, <Element a at 0x11c006228>, <Element a at 0x11c006278>, <Element a at 0x11c0062c8>, <Element a at 0x11c006318>, <Element a at 0x11c006368>, <Element a at 0x11c0063b8>, <Element a at 0x11c006408>, <Element a at 0x11c006458>, <Element a at 0x11c0064a8>, <Element a at 0x11c0064f8>, <Element a at 0x11c006548>, <Element a at 0x11c006598>, <Element a at 0x11c0065e8>, <Element a at 0x11c006638>, <Element a at 0x11c006688>, <Element a at 0x11c0066d8>, <Element a at 0x11c006728>, <Element a at 0x11c006778>, <Element a at 0x11c0067c8>, <Element a at 0x11c006818>, <Element a at 0x11c006868>, <Element a at 0x11c0068b8>, <Element a at 0x11c006908>, <Element a at 0x11c006958>, <Element a at 0x11c0069a8>, <Element a at 0x11c0069f8>, <Element a at 0x11c006a48>, <Element a at 0x11c006a98>, <Element a at 0x11c006ae8>, <Element a at 0x11c006b38>, <Element a at 0x11c006b88>]
>>> doc.xpath("//a[@class='item__info-title']/@href")
['https://auto.mercadolibre.com.ar/MLA-793135798-volkswagen-vento-20t-sportline-2007-4p-dh-aa-san-blas-auto-_JM', 'https://auto.mercadolibre.com.ar/MLA-793135798-volkswagen-vento-20t-sportline-2007-4p-dh-aa-san-blas-auto-_JM', 'https://auto.mercadolibre.com.ar/MLA-788603493-volkswagen-vento-25-advance-plus-manual-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-788603493-volkswagen-vento-25-advance-plus-manual-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-774423219-vento-comfortline-0km-2019-volkswagen-linea-nueva-vw-2018-_JM', 'https://auto.mercadolibre.com.ar/MLA-774423219-vento-comfortline-0km-2019-volkswagen-linea-nueva-vw-2018-_JM', 'https://auto.mercadolibre.com.ar/MLA-795714156-volksvagen-vento-advance-plus-25-anticipo-290000-y-ctas-_JM', 'https://auto.mercadolibre.com.ar/MLA-795714156-volksvagen-vento-advance-plus-25-anticipo-290000-y-ctas-_JM', 'https://auto.mercadolibre.com.ar/MLA-792330462-volkswagen-vento-25-luxury-wood-tiptronic-2009-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-792330462-volkswagen-vento-25-luxury-wood-tiptronic-2009-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-763941297-vento-highline-0km-automatico-auto-nuevos-volkswagen-vw-2019-_JM', 'https://auto.mercadolibre.com.ar/MLA-763941297-vento-highline-0km-automatico-auto-nuevos-volkswagen-vw-2019-_JM', 'https://auto.mercadolibre.com.ar/MLA-791000164-volkswagen-vento-20-advance-115cv-2015-_JM', 'https://auto.mercadolibre.com.ar/MLA-791000164-volkswagen-vento-20-advance-115cv-2015-_JM', 'https://auto.mercadolibre.com.ar/MLA-788125558-volkswagen-vento-14-tsi-highline-150cv-at-2017-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-788125558-volkswagen-vento-14-tsi-highline-150cv-at-2017-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-777140113-volkswagen-vento-gli-dsg-nav-my-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-777140113-volkswagen-vento-gli-dsg-nav-my-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-795016462-volkswagen-vento-25-luxury-tiptronic-2011-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-795016462-volkswagen-vento-25-luxury-tiptronic-2011-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-792487602-volkswagen-25-luxury-170cv-tiptronic-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-792487602-volkswagen-25-luxury-170cv-tiptronic-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-789645020-volkswagen-vento-20-advance-115cv-summer-package-371-_JM', 'https://auto.mercadolibre.com.ar/MLA-789645020-volkswagen-vento-20-advance-115cv-summer-package-371-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185003-vw-0km-volkswagen-vento-14-comfortline-highline-financiado-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185003-vw-0km-volkswagen-vento-14-comfortline-highline-financiado-_JM', 'https://auto.mercadolibre.com.ar/MLA-774502893-volkswagen-vento-14-comfortline-150cv-at-dsg-0km-2019-vw-_JM', 'https://auto.mercadolibre.com.ar/MLA-774502893-volkswagen-vento-14-comfortline-150cv-at-dsg-0km-2019-vw-_JM', 'https://auto.mercadolibre.com.ar/MLA-795734858-volkswagen-vento-25-luxury-tiptronic-2009-_JM', 'https://auto.mercadolibre.com.ar/MLA-795734858-volkswagen-vento-25-luxury-tiptronic-2009-_JM', 'https://auto.mercadolibre.com.ar/MLA-795501655-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-795501655-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-792476554-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792476554-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-790622152-volkswagen-vento-14-tsi-comfortline-dsg-como-nuevo-_JM', 'https://auto.mercadolibre.com.ar/MLA-790622152-volkswagen-vento-14-tsi-comfortline-dsg-como-nuevo-_JM', 'https://auto.mercadolibre.com.ar/MLA-741867064-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-741867064-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-770677950-volkswagen-vento-20-sportline-tsi-200cv-dgs-_JM', 'https://auto.mercadolibre.com.ar/MLA-770677950-volkswagen-vento-20-sportline-tsi-200cv-dgs-_JM', 'https://auto.mercadolibre.com.ar/MLA-756888148-volkswagen-vento-14-highline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-756888148-volkswagen-vento-14-highline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792470321-volkswagen-vento-highline-14-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792470321-volkswagen-vento-highline-14-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-780443475-volkswagen-vento-20-sportline-tsi-200cv-bi-xenon-_JM', 'https://auto.mercadolibre.com.ar/MLA-780443475-volkswagen-vento-20-sportline-tsi-200cv-bi-xenon-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185107-vw-0km-volkswagen-vento-14-comfortline-highline-financio-ya-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185107-vw-0km-volkswagen-vento-14-comfortline-highline-financio-ya-_JM', 'https://auto.mercadolibre.com.ar/MLA-763006237-volkswagen-nuevo-vento-comfortline-14-tsi-150cv-autotag-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-763006237-volkswagen-nuevo-vento-comfortline-14-tsi-150cv-autotag-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-792344363-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792344363-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-789195021-volkswagen-vento-comfortline-motor-14-at-tiptronic-_JM', 'https://auto.mercadolibre.com.ar/MLA-789195021-volkswagen-vento-comfortline-motor-14-at-tiptronic-_JM', 'https://auto.mercadolibre.com.ar/MLA-787103884-volkswagen-vento-comfortline-14-150-cv-dsg-_JM', 'https://auto.mercadolibre.com.ar/MLA-787103884-volkswagen-vento-comfortline-14-150-cv-dsg-_JM', 'https://auto.mercadolibre.com.ar/MLA-795438039-volkswagen-vento-14-highline-150cv-at-financio-leasing-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-795438039-volkswagen-vento-14-highline-150cv-at-financio-leasing-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-785080712-vento-25-advance-manual-permutofinancio-_JM', 'https://auto.mercadolibre.com.ar/MLA-785080712-vento-25-advance-manual-permutofinancio-_JM', 'https://auto.mercadolibre.com.ar/MLA-739533930-volkswagen-vento-20-tsi-i-2017-i-permuto-i-financio-_JM', 'https://auto.mercadolibre.com.ar/MLA-739533930-volkswagen-vento-20-tsi-i-2017-i-permuto-i-financio-_JM', 'https://auto.mercadolibre.com.ar/MLA-787212749-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-787212749-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-785738851-volkswagen-vento-advance-summer-package-20-unico-dueno--_JM', 'https://auto.mercadolibre.com.ar/MLA-785738851-volkswagen-vento-advance-summer-package-20-unico-dueno--_JM', 'https://auto.mercadolibre.com.ar/MLA-788508924-volkswagen-vento-25-advance-tiptronic-2007-_JM', 'https://auto.mercadolibre.com.ar/MLA-788508924-volkswagen-vento-25-advance-tiptronic-2007-_JM', 'https://auto.mercadolibre.com.ar/MLA-790696083-volkswagen-vento-14-highline-150cv-at-0km-tiptronic-nuevo-1-_JM', 'https://auto.mercadolibre.com.ar/MLA-790696083-volkswagen-vento-14-highline-150cv-at-0km-tiptronic-nuevo-1-_JM', 'https://auto.mercadolibre.com.ar/MLA-788446116-volkswagen-vento-20-sportline-tsi-200-2013-luxury-tdi-bora-_JM', 'https://auto.mercadolibre.com.ar/MLA-788446116-volkswagen-vento-20-sportline-tsi-200-2013-luxury-tdi-bora-_JM', 'https://auto.mercadolibre.com.ar/MLA-752087027-volkswagen-nuevo-vento-14-highline-0-km-2019-autotag-cb-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-752087027-volkswagen-nuevo-vento-14-highline-0-km-2019-autotag-cb-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-781505508-nuevo-vento-entrega-inmediata-tomo-usado-moto-auto-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-781505508-nuevo-vento-entrega-inmediata-tomo-usado-moto-auto-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-742485511-volkswagen-vento-14-highline-150cv-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-742485511-volkswagen-vento-14-highline-150cv-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-769182377-vw-volkswagen-vento-gli-230-cv-preventa-2019-0-km-_JM', 'https://auto.mercadolibre.com.ar/MLA-769182377-vw-volkswagen-vento-gli-230-cv-preventa-2019-0-km-_JM', 'https://auto.mercadolibre.com.ar/MLA-790609996-volkswagen-vento-20-luxury-i-140cv-dsg-automatico-diesel-_JM', 'https://auto.mercadolibre.com.ar/MLA-790609996-volkswagen-vento-20-luxury-i-140cv-dsg-automatico-diesel-_JM', 'https://auto.mercadolibre.com.ar/MLA-790664862-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-790664862-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-784454164-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-784454164-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-769868579-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-d-_JM', 'https://auto.mercadolibre.com.ar/MLA-769868579-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-d-_JM', 'https://auto.mercadolibre.com.ar/MLA-787564006-volkswagen-vento-20t-sportline-automatico-dsg-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-787564006-volkswagen-vento-20t-sportline-automatico-dsg-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-788080154-volkswagen-vento-20-sportline-tsi-200cv-dgs-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-788080154-volkswagen-vento-20-sportline-tsi-200cv-dgs-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-771885864-volkswagen-vento-14-comfortline-150cv-aut-sf-_JM', 'https://auto.mercadolibre.com.ar/MLA-771885864-volkswagen-vento-14-comfortline-150cv-aut-sf-_JM', 'https://auto.mercadolibre.com.ar/MLA-795273990-vento-25-manual-unico-dueno-80000-km-motor-cadenero-_JM', 'https://auto.mercadolibre.com.ar/MLA-795273990-vento-25-manual-unico-dueno-80000-km-motor-cadenero-_JM', 'https://auto.mercadolibre.com.ar/MLA-769870550-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-f-_JM', 'https://auto.mercadolibre.com.ar/MLA-769870550-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-f-_JM', 'https://auto.mercadolibre.com.ar/MLA-790653682-volkswagen-vento-25-triptronic-170-cv-cuero-carhaus-_JM', 'https://auto.mercadolibre.com.ar/MLA-790653682-volkswagen-vento-25-triptronic-170-cv-cuero-carhaus-_JM']


Q: Installing erlang 19.3 with ubuntu 18.04 gives the following error: crypto: No usable OpenSSL found, ssh : No usable OpenSSL found My OS is ubuntu 18.04, erlang version is 19.3, openssl version is 1.1.1, and when I use . /configure --prefix=/opt/erlang , the error report:
*********************************************************************
**********************  APPLICATIONS DISABLED  **********************
*********************************************************************

crypto         : No usable OpenSSL found
jinterface     : No Java compiler found
ssh            : No usable OpenSSL found
ssl            : No usable OpenSSL found

*********************************************************************
*********************************************************************
**********************  APPLICATIONS INFORMATION  *******************
*********************************************************************

wx             : wxWidgets not found, wx will NOT be usable

*********************************************************************
*********************************************************************
**********************  DOCUMENTATION INFORMATION  ******************
*********************************************************************

documentation  :
                 xmllint is missing.
                 Using fakefop to generate placeholder PDF files.

*********************************************************************

I check the version of libssl-dev
# dpkg -s libssl-dev
Package: libssl-dev
Status: install ok installed
Priority: optional
Section: libdevel
Installed-Size: 7669
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Architecture: amd64
Multi-Arch: same
Source: openssl
Version: 1.1.1-1ubuntu2.1~18.04.14
Depends: libssl1.1 (= 1.1.1-1ubuntu2.1~18.04.14)
Suggests: libssl-doc
Conflicts: libssl1.0-dev
Description: Secure Sockets Layer toolkit - development files
 This package is part of the OpenSSL project's implementation of the SSL
 and TLS cryptographic protocols for secure communication over the
 Internet.
 .
 It contains development libraries, header files, and manpages for libssl
 and libcrypto.
Homepage: https://www.openssl.org/
Original-Maintainer: Debian OpenSSL Team <pkg-openssl-devel@lists.alioth.debian.org>

I check the version of openssl:
# openssl version
OpenSSL 1.1.1  11 Sep 2018

What is the reason for the above error? How can I solve the above problem?


Q: How to automate data extraction from Elasticsearch Dev Tools? I have to do the following steps two or three times a day

*

*log in into Elasticsearch

*Go to Dev Tools

*Run a specific query by selecting it and pressing ctrl + enter
Query that I have to run

*Select the results that returns in the "buckets" and copy it.
The yellow markdown in the image is what I have to select and copy

*Then I go to https://www.convertcsv.com/json-to-csv.htm and paste the results so it converts to CSV.
Where I have to paste the results.

*I can then download the CSV and then import it into google sheets so I can view the results in a Looker Dashboard.
Button to download the converted CSV.
This take me some time everyday and I would like if there is any way that I could automate such routine.
Maybe some ETL tool that can perform at least part of the process or may some more specific way to do it with python.
Thanks in advance.
I don't have much experience with what I want to do and I tried to search online similar issues, but couldn't really find anything useful.

A: I don't know you tried, but there is a reporting tool on elasticsearch inside the "Stack Management > Reporting". On the other side, there are another tools which you can work from a server with crontab. Here are some of them :

*

*A little bit old but I think it can work for you. ES2CSV. YOu can check there are examples inside the docs folder. YOu can send queries via file and report to CSV.

*Another option which is my preference too. You can use pandas library of python. YOu can write a script according to this article, and you can get a csv export CSV. The article I mentioned is really explained in a great way.

*Another alternative a library written in Java. But the documentation is a little bit weak.

*Another alternative for python library can be elasticsearch-tocsv. This one is a little bit recently updated when I compare it to first alternative. But the query samples are a little bit weak. But there is a detailed article. You can check it.

*You can use elasticdump, which is written on NodeJS and a great tool to report data from elasticsearch. And there is a CSV export option. You can see examples on GitHub page.

I will try to find more and I will update this answer time by time. Thanks!


Q: Express JS not rendering jade template I'm going to keep this short, I'm just trying to render a jade template using express js.
I'm using express 3.0.0rc5 and jade 0.27.6.
Here's my jade templates, the layout:
// test-layout.jade
doctype 5
html
  head
    title My title
    block head
  body
    #content
      block content

And the index:
// test-index.jade
extends test-layout

block head
  script(src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js")

block content
  h1 My page

Here's some excerpts from app.js:
var app = express();
// Configuration
app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.get('/test-jade', function(req, res) {
    res.render('test-index', {}, function(err, html) {
    });
  });
app.get('/test', function(req, res) {
  res.send('this works');
});

Now whenever I try to go to http://myurl.com/test-jade the browser just hangs and timesout without showing any output in the console (even though I'm in dev mode).
However when I go to http://myurl.com/test I see 'this works'.
I feel like I'm missing something really simple here, I'm currently upgrading from 2.5 to 3.0.
Thanks in advance if anyone has advice.

A: Is it the blank call back?
 res.render('test-index', {}, function(err, html) {
 });

In my app I'm using
res.render('test-index', {});


Q: PHP number_format() and round() not producing valid upper-range results 3 CODE:
in_array($number, round(range(65,74)))

or
round(in_array($number,range(65,74)))

I'm doing a switch case whenever the user inputs 73.4 the result is null. But whenever I input 73 or 74 it executes.
How to do it I'm a newbie in php here.

A: You need to round the user input number and not the range. So, it will be ,
in_array(round($number), range(65,74));

DEMO.


Q: Autolayout is expecting a different height I'm struggling with autolayout in my iOS 7 project on Xcode 5. Let's say I want to show these buttons :
    Something
        -
        |                      10 pts fixed space from top
        -
     Button 1                  50 pts height on 4" display, reduce height if 3"5
        -
        |                      10 pts fixed space
        -
     Button 2                  50 pts height on 4" display, reduce height if 3"5

I layout my buttons in Interface Builder (with a storyboard).
Then I start adding constraints :

*

*The vertical spacing from "button 1" to "something"

*The leading space to container for "button 1"

*The fixed width for "button 1"

Problem is Autolayout is complaining about my button's, saying "Expected: height=30". Why ? I want a 50 pts button, why is this a problem ? Of course, I can fix this by adding a height constraint, but I want the height to be reduced if the height of the screen is reduced. And, if I run it, even on a 4" display, the button's height is set to 30, as autolayout said it "should be".. And I didn't even set the second button's constraints yet, which will make it even worse.
How can I achieve such a thing ? It seems really basic and I still don't understand what's going on.
Note that I could manually set all the heights in code, but I really want to avoid that.

A: What you can do for solving the vertical constraint issue is to give Equal constraints to your button1 and button2 and give a fixed vertical constraint to the something view and from your second button to the bottom of the superview.
So this way you won`t need to give a fixed height to any of them and the distance between them and other elements (something and bottom of superview) will be standard.
I hope this helps!

A: Ok, I think I made it.
Here is what I did :

*

*I set all my constraints in the storyboard, with the Retina 4" form-factor.

*Constraints for the something view : fixed height & width, fixed top space and leading space. This view is absolutely fixed.

*Constraints for button 1 : fixed vertical space to something view, fixed leading space, fixed width. 2 height constraints : 30 <= height <= 50.

*Constraints for button 2 : fixed vertical space to button 1, fixed leading space, fixed width. Also 2 height constraints : 30 <= height <= 50. And fixed bottom space to bottom layout.
All constraints have a maximum priority of 1000, except the last one (fixed bottom space to bottom layout), which is set at 900 !
That way, the buttons keep a height >=30 and move up, but get shrinked vertically because the other constraints are more important.
Thanks a lot to @VasiliyDeych and @P.Sami for their advice. It helped a lot.

A: You're going to need to show us how your constraints are set up.
Constraints are a set of rules that the views must follow. If there is no rule saying the button must shrink with the parent view, it will not happen.
Based on your example, if I understood it correctly, you would want a set of constraints like this (defined in VFL for ease):
[yourParentView addVisualConstraints:@"V:|[something(100@75)]-(10@100)-[button1(<=50,>=30@100)]-(10@100)-[button2(button1@100)]-(>=300@50)-|"
                  forViews:NSDictionaryOfVariableBindings(something,button1,button2)];

All constraints here are vertical (V:), the numbers in parentheses represent a number of points, followed by @ and the desired priority of maintaining that number of points. The | symbols represent the top and bottom edges of the superview. So ]-(>=300@50)-| is saying, I'd like to keep 300 or more pixels between button2 and the bottom of the superview, but I care about it with a priority of 50. button1(<=50,>=30@100) means I really care that this button is between 30 and 50 pixels in height, with a priority of 100. button2(button1) means I want button2 to be the same height as button1. I also really care about keeping that 10-point distance between my elements. And I somewhat care that something (which is flush to the superview's top edge, hence |[) is going to stay at 100 points tall.
Does this not work for what you are intending to do?


Q: Firebase login with GCP service account I am trying to login to the Firebase Tools CLI with a GCP service account. I have the path to the service account credentials saved as GOOGLE_APPLICATION_CREDENTIALS. I have logged out of firebase with firebase logout and have tried to sign in with the service account with firebase login --no-localhost and firebase login --no-localhost  --token $GOOGLE_APPLICATION_CREDENTIALS. However in bother cases a web browser opens asking me to log in with my user account. How can I log in to firebase with a service account?

A: Taken from Michael Bleighs comment:
"The Firebase CLI does support GOOGLE_APPLICATION_CREDENTIALS, but you don't need to "log in" with them. If the environment variable is pointing to a valid service account you should be able to just use CLI commands as if you are logged in. You do need to be logged out for GAC to work correctly. Run the command with --debug if you're getting errors while trying to do so."
I can confirm I have this working. Note you might need to run firebase use <project-id> for it to work correctly.

A: You can't sign in to your Firebase project with a service account. You will need to use the proper user account of a collaborator on the project to sign in with Firebase tools.
Even when using the CI integration, the documentation says to:

*

*Start the signin process by running the following command:
 firebase login:ci

*Visit the URL provided, then sign in using a Google account.


Q: Insert Indirectly Into a Naming Table? Let's consider this diagram

With this JPA snippet of the Track class.
@Entity
@Table(name = "track")
public class Track {
    @Id
    @Type(type="pg-uuid")
    private UUID id;

    @Column(name = "genre")
    private String genre;

    /* Getters, setters, etc */
}

And the database schema
/** Liquibase */
<changeSet id="1" author="SoulBeaver">
    <createTable tableName="genre">
        <column name="name" type="VARCHAR(1024)">
            <constraints primaryKey="true" nullable="false" />
        </column>
    </createTable>

    <createTable tableName="track">
        <column name="id" type="UUID">
            <constraints primaryKey="true" nullable="false" />
        </column>
        <column name="genre" type="VARCHAR(1024)" />
    </createTable>
    <addForeignKeyConstraint baseTableName="track" baseColumnNames="genre" constraintName="genre_fk"
                             referencedTableName="genre"
                             referencedColumnNames="name" />
</changeSet>

Now, when I try to persist a track, which has been given a track.setGenre("Rock"); I get a RuntimeError stating that the key does not exist in Genre.
Is there any way I can avoid having to create the Genre class, persisting the Genre first, and finally persisting the Track?

A: Basically the FKey Constraint works in such a way that if you try to insert a value in child table with FKey value not present in your parent table, it will fail. This is not specific to JPA. It is how relational DB is designed.


Q: Why not wrap content within ``? It seems common to use the following HTML structure to accommodate
users who have enabled/disable javascript:
 <html>
     <style>
         div.body { display:none; }
         .body > ... { ... }
     </style>
     <script>
         document.onload( function() {
             javascript(CONTENT => div.body);
         });
     </script>
     <noscript>
         <style>
             body > :not(noscript) {
                 display:none;
             }
         </style>
     </noscript>
 <body>
     <div class="body">
     </div>
     <noscript class="body">
         CONTENT
     </noscript>
 </body>
 </html>

The mechanism uses a <div>; whose display attribute, initially set
to none, is subsequently set to block|grid|etc. and populated with
CONTENT once the page is loaded; alongside a <noscript>; which is
pre-populated with CONTENT.
No one seems to suggest simply popping the CONTENT within
<noscript> into the <body> when javascript is available as follows
:
 <html>
     <style>
         .body { ... }
         .body > ... { ... }
     </style>
     <script>
         document.onload( function() {
             let noscript = document.querySelector("noscript");
             noscript.outerHTML = noscript.innerHTML;
         });
     </script>
     <noscript>
         <style>
             body > noscript {
                 display:content;
             }
         </style>
     </noscript>
 <body>
     <noscript>
         CONTENT
     </noscript>
 </body>
 </html>

Here the CONTENT within noscript is displayed by default and if
there is javascript the tag is simply dropped; the specification
states the content of noscript should be parsable and that the parsed
result be readily assignable as noscript.outerHTML.
The first method requires one to repeat ones CONTENT in both the
noscript and wrapped into the javascript that populates the div;
this isn't especially DRY. I can't see that populating a page through
javascript calls is any faster then assigning ELEMENT.outerHTML; if
this is not true let me know.  The second method relies upona bit of
CSS trickery. Finally both methods seem subject to flicker.
The only reasons I can think of for not using the latter structure are
:

*

*SEO; I can't see how though e.g. you only have to scan CONTENT once, it sn't repeated, it isn't bundled between javascript, better
aria/a11y support.

*Frontend framework e.g. they all rely on the first structure

*historic reasons e.g. setting noscript.outerHTML breaks events or something ut they are broken under the spec anyhow, jQuery.unwrap
being a "recent" development, browser woes.


Q: Django form isn't rendering at all I'm trying to make a non model form that just gets input text for a chat like interface.
views.py
def get_input(request):
    if request.method == 'POST':
        form = inputForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')

    else:
        form = inputForm()

    return render(request, 'index.html', {'form': form})

def shelley_test(request):
    form = inputForm()
    return render(request, 'shelley_test.html')

form.py
from django import forms

class inputForm(forms.Form):
    input = forms.CharField(label='input field')

shelley_test.html
<form action="/get_input/" method="get">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>

please please help. I'm new at django and stumped :(

A: You're not sending the form to the context in your shelley_test method - see the difference in the render line compared with get_input.
Note though you don't need shelley_test at all: just go straight to /get_input/ to see the empty form.


Q: Hash created from CSV row not behaving like a normal hash I'm getting some weird issues. I'm trying to allow importing of a CSV into my model. I'm getting an unknown attribute 'hashtag' for Job. error, but that's not the issue. My model definitely has a hashtag column.
When I get the error, if I try doing job.to_hash I get {"hashtag"=>"apples", "number"=>"10", "job_type"=>"0"} and if I do job.to_hash.symbolize_keys (with or without a !) I get {:hashtag=>"apples", :number=>"10", :job_type=>"0"}
However, here comes the issue. Both of these seem to be of the Hash class when I call .class on them. But if I try assigning it to a variable and calling ["hashtag"] or [:hashtag] on it, it returns nil.
Example of what I mean:
>> foo = job.to_hash.symbolize_keys
=> {:hashtag=>"apples", :number=>"10", :job_type=>"0"}
>> bar = {hashtag: "apples", number: "10", job_type: "0"}
=> {:hashtag=>"apples", :number=>"10", :job_type=>"0"}
>> foo == bar
=> false

>> foo.class
=> Hash
>> foo.class == bar.class
=> true

Model:
class Job < ApplicationRecord
  require 'csv'

  def self.import(file)
    file = CSV.read(file.path, headers:true)
    file.each { |job| Job.create(job.to_hash)}
  end
end

CSV:
hashtag,number,job_type
apples,10,0
bees,10,0
carrots,10,0

I really don't see what's going wrong... I'm literally copying and pasting the foo variable above into a new variable and it works, yet the original doesn't, despite, despite apparently being a hash as well.

A: Apparently the :hashtag has two different encodings for me, seems like one is stored as US-ASCII, and one (the parsed) in UTF-8. Funny that I was able to reproduce this only by pasting this into my irb.
To solve this, make sure they have the same encoding


Q: Compiling cross-referenced classes in Codelite I'm sure this topic has come up before, but I am not sure what even to google for:
I am new to C++ and while learning I wrote first a Vector class, then a Matrix class (which uses the Vector class). While working on the Vector class the program compiled fine, but when adding the Matrix class (which includes and uses the Vector class) I'm starting to get compile errors. Specifically "undefined reference to functionname" - eventhough the function for sure exists and was working fine before when only the Vector class existed (it's a getter function for a component).
Showing this code to someone who knows C++ but not Codelite they said my code is fine, but the compiling/build order seems weird and that it seems like the software tries to compile my classes like a main.cpp.
Is that enough for anybody to give me any pointers to what to research/look up to get this working?


Q: Why are rails development credentials gitignored by default? I'm generating credentials using the following command:
rails credentials:edit --environment development
I notice that rails puts this in the gitignore:
+/config/credentials/development.key
I dont understand why, based on the following reasons:

*

*The development credential file is encrypted by default, hence harmless to check in as long as the master key isnt checked in.

*It's essential for a fresh environment setup (eg. on a new dev environment)

*If the original file is lost, all the data in the dev environment will have to be reseeded.

I'm inclined to check it in but figured, given Chesterton's fence and all, I'm likely missing something.

A: I figured it out. I was confused between the development.key and the  config/credentials/development.yml.enc. The latter is the encrypted credential file.


Q: Python/Bash - Tab completion not including files when arguments are provided I'm not sure whether this is a Python issue or a bash issue, but I'm having trouble with tab completion not working on files (only directories) when I'm providing arguments to my python script. Example of how I want it to work:
python myscript.py -e data_dir/da[TAB]
python myscript.py -e data_dir/data.tsv

However, it works when I'm not providing an argument, or if I'm using an equals sign between the argument and the file path. Examples of scenarios where it works:
python myscript.py data_dir/da[TAB]
python myscript.py data_dir/data.tsv

python myscript.py -e=data_dir/da[TAB]
python myscript.py data_dir/data.tsv

Is what I'm expecting unreasonable, considering the normal behavior of python and bash? I.e. is my tab completion working like it's supposed to? Alternatively, am I using python arguments incorrectly when I'm not including the equals sign with my arguments?
I'm using bash version 4.3.11(1)-release and python version 2.7.6.
Thanks!


Q: Issue with stock Browser picking photos from Gallery I am working on a web page for uploading photos from a mobile device, using the <input type="file" accept="image/*"/> tag. This works beautifully on iphone and on chrome on the android, but where we are running into issues is with the stock android browser.
The issue arises when you select a file from your gallery (it works fine when you use the camera to take a photo). And we have narrowed it down even further to seeing that the data MIME type isn't available when taken from the gallery on the stock browser (the photos below show the first 100 characters of the data URL being loaded.  The goal was to force JPEG, but without the MIME type we cannot know for sure how to fix this.  See code below for how the images are being rendered.
How can an image be rendered without the type? Better yet, does anybody know why the type is not available on the stock android browser?
EDIT
Firstly, these are not the same image, they were taken near the same time, and that's not the issue, that's why the data is different (The MIME type doesn't appear on any images on the stock browser, so that's not the problem.
Update
I confirmed that the MIME type is the issue by inserting image/jpeg into the stock browser where it is on chrome. Unfortunately, we have no way of guaranteeing that it's going to be jpeg, so we again really can't do it that way
 _readInputFile: function (file, index) {
            var w = this, o = this.options;
            try {

                var fileReader = new FileReader();

                fileReader.onerror = function (event) {
                    alert(w._translate("There was a problem opening the selected file. For mobile devices, some files created by third-party applications (those that did not ship with the device) may not be standard and cannot be used."))
                    $('#loadingDots').remove();
                    return false;
                }
               fileReader.onload = function (event) {

                var data = event.target.result;
                //alert(data.substring(0,100));
                //var mimeType = data.split(":")[1].split(";")[0];

                alert("Load Image"); //I get to this point
                $('#' + w.disp.idPrefix + 'hiddenImages').append($('<img />', {
                    src: data,
                    id: "dummyImg" + index,
                    load: function(){
                    var width = dummy.width();
                    var height = dummy.height();
                    $('#dummyImg' + index).remove();
                    alert("Render"); // I don't get here
                        var resized = w._resizeAndRenderImage(data, null, null, biOSBugFixRequired, skewRatio, width, height);
                        alert("Image Rendered"); // I don't get here

                    }
                }));
            }
            fileReader.readAsDataURL(file);
        }
        catch (e) {
        }
 }

Chrome

Stock Browser

A: Since the issue is probably browser-related, and you can't really fix the browser(you could report a bug to Google though), I'd suggest taking a different path.
Have a look Here:
In Node.js, given a URL, how do I check whether its a jpg/png/gif?
See the comments of the accepted answer, which suggests a method to check the file type using the file stream. I'm pretty sure this would work on browser-implemented Javascript and not only in Node.js.


Q: Passing params in Knockout component as a AMD Module My tagname component is like below and while the component is registered as a single AMD module, I want to get the all params.
ko.components.register('tagname', {
  synchronous: true,
  require: params.url
});

<tagname params="url: 'some/relative/url'"></tagname>

How can I do that?

A: The function that you provide for your view model (or as the createViewModel factory) will receive all of the params. For example:
define(['knockout', 'text!./my-tagname.html'], function(ko, templateString) {
    function MyTagNameComponent(params) {
        // do something with params here
    }

    return { viewModel: MyTagNameComponent, template: templateString };
});

So, your component will receive its params as the first argument to MyTagNameComponent in this case.
Here is a sample: http://jsfiddle.net/rniemeyer/g7zhjfz1/


Q: How can this element button be clicked using protractor? I'm trying to select this button using protractor:
<button tabindex="-1" type="button" class="btn btn-default pull-left" ng-click="$arrowAction(-1, 0)">

 <i class="glyphicon glyphicon-chevron-up">
 </i>

</button>

the only unique element in this is ng-click="$arrowAction(-1, 0)"
Nothing I have tried works:
element(by.css("//button[@ng-click='$arrowAction(-1, 0)']")).click();

A: //button[@ng-click='$arrowAction(-1, 0)'] is not a valid CSS selector. It actually looks like this is an XPath expression and you meant to use by.xpath() locator.
You can though use the partial attribute check instead:
$("button[ng-click*=arrowAction]").click();

$ here is a shortcut to element(by.css(...)), *= means "contains".
Or, do an exact match:
$("button[ng-click='$arrowAction(-1, 0)']").click();

I still don't like the location technique used in this case, but, given what we have, it is probably the best we can do. Ideally, if you have control over the application code and templates, add a meaningful id, class or a custom data attribute to uniquely identify the element.


Q: HTML - Send email without open new windows in Outlook I send an email to a client that contains a button that must be pressed to send a user's cofee.
Pressing the button opens a new Outlook window and then the user must click on SEND
I would like the new window not to be opened but automatically the email must be sent without any confirmation.
is it possible to do this?
Thanks


Q: Success on emulator, Force stop on real device I deployed an application for Android which is successfully running on emulator.
But, when I try to run on real device (My device is Acer A200, tablet), my application always forced stop. The requirement of the operating system is no problem.
The error in logcat when I tried to run on real device is :
07-16 15:09:20.870: I/SqliteDatabaseCpp(780): sqlite returned: error code = 1, msg = no such table: kategori, db=/data/data/com.mroring.belajarperancis/databases/MY_DATABASE

I think the application didn't install the database correctly. What should I do ?
Thanks in advance :)

A: table name "kategori" does not exist on your database, you should check the code if you created the table or not. if created, change the version number of the database, It will call the onUpgrade method and the database will create again.


Q: Filter a list of data using a select box in Blazor I have a table called SchoolsTable and there is a view that will show all the records that have been entered. Here is the my model:
 public partial class SchoolsTable
    {
        public int Id{ get; set; }
        public int Name{ get; set; }
        public int State{ get; set; }
    }

What I want to do is have a dropdown in that view that will let me select a State and the data shown on the view will only be those that have the corresponding state.
The razor component:

           Schools
          @foreach (var item in school)
          {
        @item.Name
        @item.State
          }

@code{
    private List<SchoolTable> schools=new List <SchoolTable>();
    private SchoolTable school= new SchoolTable();
    protected override async Task OnInitializedAsync()
    {
        GetSchoolTable();

    }
    private List<SchoolTable> GetSchoolTable()
    {
        schools= SchoolService.GetSchoolTable();
        return schools;
    }
}

the select gets all the states as duplicates:
Choose a State:
<select name="State">
    @foreach (var item in schools)
    {
        <option value="@item.State">@item.State</option>
    }
</select>

additionally, I have created a state table which has 2 records in them:
 public partial class StatesTable
        {
            public int Id{ get; set; }
            public int Description{ get; set; }
        }

using this select, gets the states as singles and no duplicate states
Choose a State:
<select name="State">
    @foreach (var item in branch)
    {
        <option value="@item.Id">@item.Description</option>
    }
</select>

A: You need to do a couple of things.
First you need to bind the selected value of your <select> element to a field. For that you need to use the @bind attribute:
Choose a State:
<select id="State" @bind="selectedState">
    <option value="">Choose a state</option>
    @foreach (var item in branch)
    {
        <option value="@item.Id">@item.Description</option>
    }
</select>

@code {
    private int? selectedState;
}

Also add an option with empty value in your select so that by default no state is selected:
<option value="">Choose a state</option>

Now you can create a property that returns the filtered schools based on the selected state:
private List<SchoolTable> FilteredSchools => selectedState.HasValue ?
    schools.Where(s => s.State == selectedState.Value).ToList() :
    schools;

Use this property to generate the
 element content:
Choose a State:
<select id="State" @bind="selectedState">
    <option value="">Choose a state</option>
    @foreach (var item in branch)
    {
        <option value="@item.Id">@item.Description</option>
    }
</select>

        Schools
        @foreach (var item in FilteredSchools)
        {
            @item.Name
            @item.State
        }

@code{
    private List<SchoolTable> schools = new List<SchoolTable>();
    private int? selectedState;

    private List<SchoolTable> FilteredSchools => selectedState.HasValue ?
        schools.Where(s => s.State == selectedState.Value).ToList() :
        schools;

    protected override void OnInitialized()
    {
        schools = SchoolService.GetSchoolTable();
    }
}


Q: FileNotFoundException when restarting the app I don't know why but I get an FileNotFoundException from my Init() function.
What's happening is, when I launch the app for the first time, it's normal to get one (the file does not exist). Then I press a button which calls Save and so creates the file (if I add a Log just after outputStream.close(), I'm able to see it). I actually tried to open the created file with a FileInputStream and I didn't get the exception.
But. When I close the app and open it again. I get the FileNotFoundException. Any idea why ?
public class MyClass {
    public static Context mContext ;
    public static void Save(){
        String test = "test" ;
        FileOutputStream outputStream;
        try {
            outputStream = mContext.openFileOutput(FILENAME, Context.MODE_PRIVATE);
            outputStream.write(test.getBytes());
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void Init(Context c){
        mContext = c ;
        FileInputStream inputStream;
        try {
            inputStream = c.openFileInput(FILENAME);
            String test = "";
            char ch ;
            while((ch=(char) inputStream.read())!=-1)
                test+= ch ;
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Edit :
So, those calls are not in an activity but in a static class. Init is called from onCreate of my main activity. Save is called from onPause of another activity. Hope that helps.


Q: AngularJS ng-cloak: empty page is displaying in IE9 when browser cache is cleared I just encountered a weird issue on angular's ng-cloak. When I cleared my IE9 browser's cache and close and open my browser again, when i accessed the page, it display empty page :( but when i tried to refresh the page it the page is now displaying.


Q: Jquery compare data/object differences on checked I'm trying to make a checkbox to hihglight the differences between data inside a div rather than table.
So if row has differences "Single, Single, Married" this should be highlighted.
http://jsfiddle.net/Ly61u493/1/
Logic:
$('.check-diff').click(function() {
if($(this).prop('checked')){
    //highlight status except header
    alert("Bang highlight it...");
} else{
    //unchecked should remove the highlight areas
    alert("Not highlighted");
}
});

    Click to see differences
<input type="checkbox" class="check-diff">

Name

John

Henry

Kim

Status

Single

Married

Single

Car

Yes

Yes

Yes

A: how about the following jquery code?
$('.check-diff').click(function() {
if($(this).prop('checked')){
    checkDiff();
} else{
    $(".row").each(function(){
        $(this).css("background-color","#fff");
    });
}
});

function checkDiff(){
$(".row").each(function(){
    var diff = false;
    var source = $(this).find(".diff").first().text();
    $(this).find(".diff").each(function(){
        var compare = $(this).text();
        if(source != compare){
           diff = true;
        }
    });
    if(diff == true){
        $(this).css("background-color","red");
    }
 });
}

hope i got you right and you get an idea, how to move on! :)

A: You can use 2 each loops and a class name for the rows you want to check. Only row that has a class name checkDiff will be validated and cells that has a class name diff.
JSnippet DEMO - validate difference in rows base on the cell text
JS:
$(function(){

    $('.check-diff').click(function() {
        if($(this).prop('checked')){
            $('.row.checkDiff').each(function(i,ele){
                var values = $(ele).find('.diff');
                var first = values.eq(0).text();
                var diff = false;
                values.each(function(j,e){
                    if ($(e).text() !== first) diff = true;
                });
                if (diff) $(ele).addClass('highlight');
            });
        } else{
            $('.row.checkDiff').removeClass('highlight');
        }
    });

});

HTML:
Click to see differences
<input type="checkbox" class="check-diff">

Name

John

Henry

Kim

Status

Single

Married

Single

Car

Yes

Yes

Yes

Kids

Yes

Yes

No

Home

Yes

Yes

Yes


Q: Detecting unused props passed in components in React I currently refactoring some old code and I'm curious if there's any way to detect parameters which are passed into the component but never actually used inside it? Without looking at all the places where the component is called and checking manually.
Eg. detecting that name and age are not used inside the Greet component so can be deleted.
export default function Greet ({ greeting }) {
  return (
    <h1>{greeting}</h1>
  )
}

<Greet greeting="Hello Word" name="David" age="100"/>

A: TypeScript will warn you if you try to pass unknown props.
Eslint will warn you if you have unused variables, imports ...
with rules like:

*

*no-unused-expressions

*no-unused-vars

*react/no-unused-prop-types

*unused-imports


Q: How to access Windows.Services.Store from Java application We have a Java application that we publish in the Windows Store.  We would like to implement in-app purchases, for which we need to use the Windows.Services.Store API.
How can we access the Windows.Services.Store API from Java?


Q: HTML5 swipe.js css3 transitions; offscreen rendering and caching of page elements I am building a HTML5 magazine for tablets and desktops with use of swipe.js (http://swipejs.com).
Everything seems to work fine, In one HTML page I have set next to each other fullscreen list elements. The whole magazine is build up in one static html file. I can slide through the pages by swiping on tablets, and by using buttons for the desktop version (consider the example on the swipe.js homepage, but then with fullscreen slides).
The pages are placed next to each other, and have the dimensions of the screen.
[ |0||1||2| .. |i-1||i||i+1| .. |n| ]

The swipe.js transitions are done with help of css3, using the translate3d() css function. In this case, hardware rendering is used.
On desktop (Chrome, Safari, FF), iPad1 and (even better on) iPad2 this has the desired effect I was looking for; smooth transitions. Perfect!
However, on the iPad3, the pages seem to render 'slow' when entered (by transition) for the first time. Even without setting background images (just the color), the 'rendering' of the transitioned page is considered a little 'slow'; the page is build up by 'flickering' blocks.
Assumption:
My assumption is (after reading into the subject), that this is because the browser only renders the elements that are in-screen, and will cache the swiped pages only for a while, cleaning the cache afterwards to control memory management.
My question: Is there a way to control the offscreen rendering and caching, so that I can force (pre) render page elements i-1, i+1 (and flush the cache for all other page elements), to speed up my transition rendering?
Note: In several topics on StackOverflow, 'flickering' of css3 transitions is mentioned. I have implemented the suggested CSS tricks but will not solve my case.
-webkit-backface-visibility: hidden;
-webkit-transform:translate3d(0,0,0);

A: In the end the solution was a hack of Swipejs in which I added a method 'hideOthers()', setting the style visibility to 'hidden', which unloads the pages from hardware memory:
hideOthers: function(index) {
  var i = 0;
  var el;

  for( i in this.slides ) {
      el = this.slides[i];
      if ( el.tagName == 'LI' ) {
          // Show pages i-1, i and i+1
          if ( parseInt(i) == index
             || (parseInt(i) + 1) == index
             || (parseInt(i) - 1) == index
          ) {
              el.style.visibility = 'visible';
          }
          else {
              el.style.visibility = 'hidden';
          }
      }
   }
}

..and added the trigger below as last line in the 'slide()' method
// unload list elements from memory
var self = this;
setTimeout( function() { self.hideOthers(index); }, 100 );

Only the translate3d was needed to toggle the hardware acceleration on (as mentioned in my question above):
-webkit-transform:translate3d(0,0,0);

You can find the result (including iScroll for vertical scrolling) here.

A: in regards to the webkit backface/translate3d props used to trigger hardware acceleration, I've read that in iOS 6+ these don't work quite the same as in previous versions, and (more importantly) that hardware acceleration needs to be applied not only on the element that is being animated, but also on any element that it is overlapping/overlaps it.
reference (not much): http://indiegamr.com/ios6-html-hardware-acceleration-changes-and-how-to-fix-them/
To be fair this is fairly anecdotal, I was myself unable to fix my own flickering issue - due to tight deadlines - but this might be a point in the right direction.


Q: AngularJS Form data is not defined In AngularJS, I have a form, that when submitted, passes data off to a controller and sends it to an API.
Form:
 <form ng-submit="newCompany()">

                ID<input type="text" name="id" id="id" ng-model="newCompany.id" tabindex="1" class="form-control">
                Name<input type="text" name="name" id="name" tabindex="2" ng-model="newCompany.name" class="form-control">
                Primary Contact<input type="text" name="primary_contact" id="primary_contact" tabindex="2" ng-model="newCompany.primary_contact" class="form-control">
                Address<input type="text" name="address" id="address" tabindex="2" ng-model="newCompany.address" class="form-control">
                Function<input type="text" name="function" id="function" tabindex="2" ng-model="newCompany.function" class="form-control">
                Telephone<input type="text" name="telephone" id="telephone" tabindex="2" ng-model="newCompany.phone" class="form-control">
                Fax<input type="text" name="fax" id="fax" tabindex="2" ng-model="newCompany.fax" class="form-control">
                URL<input type="text" name="url" id="url" tabindex="2" ng-model="newCompany.url" class="form-control">

                        <input type="submit" name="add-submit" id="add-submit" tabindex="10" class="form-control btn btn-primary" value="Add Company">

{{ addCompany }}

        </form>

And the controller...
app.controller("CompaniesController", ['$scope', 'Companies', function($scope, Companies) {
    $scope.title = 'Companies';
    $scope.title_sub = 'Add Company';

   $scope.companyData = {
       id: $scope.newCompany.id,
       name: $scope.newCompany.name,
       primary_contact: $scope.newCompany.primary_contact,
       address: $scope.newCompany.address,
       function: $scope.newCompany.function,
       telephone: $scope.newCompany.phone,
       fax: $scope.newCompany.fax,
       url: $scope.newCompany.url
   };

    $scope.newCompany = function() {
        var company = new Companies($scope.companyData);
        company.$save();
    };

    $scope.companies = Companies.query();
}]);

However - I get an error that says "cannot read property 'id' of undefined"
Does anybody know what is wrong here? I thought $scope.[NG-MODEL] gets the form data...

A: *

*You have a $scope.newCompany variable which is a function, not an object.

*When you initialize $scope.companyData, you call  id: $scope.newCompany.id, where $scope.newCompany is undefined. Try define it first with all its properties ($scope.newCompany = {
id : "",
...
})

*Call your submit function something else.

*Do not create a function whose name itself a 'function'. (function: $scope.newCompany.function). This is reserved as a keyword.
These steps may be close to the result you want to see, if not reply back.


Q: How to switch to another branch while recursively initing submodules I have a git repository with several submodules (see an example). Its structure looks like this:
I--A--B <- main
       \
        C <- branch-c

*

*Commit A adds a submodule-a

*Commit B adds a submodule-b

*Commit C adds a submodule-c on branch branch-c
When I clone the above repo using
git clone --recurse-submodules <URL> only the submodule-a and submodule-b submodules get initialised and cloned.
When I then want to check out branch branch-c using git checkout branch-c, the directory for submodule-c gets created, but the submodule itself is not initialised. There is no indication in the command output that some additional steps are needed. Neither git status nor git diff give any hint.
When instead I want to check out branch-c using git checkout --recurse-submodules branch-c I get an error:
fatal: not a git repository: ../../.git/modules/subrepos/subrepo-c
fatal: could not reset submodule index

How do I check out (or switch to) branch branch-c while automatically initialising all submodules?

A: Your example repository is lacking a branch-c, so it's not a complete MCVE, but it's a good start :)

When I clone the above repo using git clone --recurse-submodules <URL> only the submodule-a and submodule-b submodules get initialised and cloned.

Yes, this is the current behaviour of git clone --recurse-submodules. The submodules are cloned and initialized using an invocation of git submodule update --init --recursive during the checkout phase of git clone, and as such, only submodules recorded in the default branch (or the branch specified using git clone -b <branch>) are cloned and initialized.

When I then want to check out branch branch-c using git checkout branch-c, the directory for submodule-c gets created, but the submodule itself is not initialised. There is no indication in the command output that some additional steps are needed. Neither git status nor git diff give any hint.

Yes, this is unfortunately still the default behaviour of Git. Submodules working trees are not checked out by default by git checkout <branch>. git submodule status (or just git submodule) will show uninitialized submodules with a - prefixed.

When instead I want to check out branch-c using git checkout --recurse-submodules branch-c I get an error:
fatal: not a git repository: ../../.git/modules/subrepos/subrepo-c
fatal: could not reset submodule index

This is a good reflex but unfortunately it does not work in that specific case and leads to this bad UX. git checkout --recurse-submodules <branch> assumes that every submodule recorded in branch-c are already initialized. Since that's not the case here, it errors out because it can't find the .git directory of the submodule. The message could be clearer. What you have to do (the first time you switch to branch-c after cloning your repository) is to check out branch-c non-recursively, and then initialize the submodule:
git checkout branch-c
git submodule update --init --recursive

Then, you will be able to correctly switch between your branches with --recurse-submodules:
git checkout --recurse-submodules main
git checkout --recurse-submodules branch-c
# etc

Note that you can set submodule.recurse in your config to avoid having to use --recurse-submodules all the time.


Q: Phone emulator in Visual Studio 2015 RC on Windows 10 preview build 10074 does not work I had some problem in running some Phone of the emulators in VS2015 RC so I tried to install also the "Pre-release Microsoft Emulator for Windows 10 Mobile" and then also the external SDK ...
Now, even thought I uninstalled the external Windows 10 SDK and made a "repair" of VS2015 RC, no one of the phone emulators stars (it goes till the "OS is starting" phase and then remain in that state till, after many minutes, the emulator crashes and some time a popup says "The emulator is unable to get the sensor states from the device: Operation failed because connection is shut down", ... most of the times no error is reported).
I also tried to delete in the Hyper-V manager both the created emulators virtual machines and the related  Virtual Switches related to Windows Phone Emulator Internal: these are recreated at the next run of the emulator from VS, but nothing changed ...
Any suggestion? How can I make at least some of the phone emulators work properly?
Regards
Enzo


Q: Check File Extension in android i made a small method to check whether defined folder has files with a specific extension or not. I m getting null point exception on run.pls help to find mistake.method is checking .mp4 files and returning true if found and message is displayed.
Here is Code:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView filecheck;

        filecheck = (TextView) findViewById(R.id.filecheck);

        filecheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (accept()) {
                    Toast.makeText(MainActivity.this, "Files Found", Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(MainActivity.this, "Files Not Found", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public boolean accept() {
        final File pathname = new File("/sdcard/test/");
        String files[] = pathname.list();
        System.out.println(files.length);
        for (String s : files) {
            if (s.contains(".mp4")) {
                System.out.println(s);
                return true;
            }
            return false;
        }
        return false;
    }
}

Here is exception:
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: jss.testmethods, PID: 23659
                  java.lang.NullPointerException
                      at jss.testmethods.MainActivity.accept(MainActivity.java:38)
                      at jss.testmethods.MainActivity$1.onClick(MainActivity.java:24)
                      at android.view.View.performClick(View.java:4478)
                      at android.view.View$PerformClick.run(View.java:18698)
                      at android.os.Handler.handleCallback(Handler.java:733)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:149)
                      at android.app.ActivityThread.main(ActivityThread.java:5257)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
                      at dalvik.system.NativeStart.main(Native Method)

A: i was expecting simple error, i missed to add permission for read storage. it is working now.


Q: How do I define custom comparison (0 < mytype) in python? So I'm currently (ab)using python notation to create a domain specific language. As part of this I'm overriding comparison functions to return non-boolean values.
So, for (mytype1 < mytype2) and (mytype < 0) I can easily do this by defining the __lt__() magic method.
However, I cannot figure out how to do so for (0 < mytype) as presumably the magic method would need to be defined on the built-in int type. There doesn't seem to be a __rlt__() function as exists for numeric operations.
How do I add support for this comparison where the lhs is of type int (in python3)?

A: As per the documentation the reflected form of __lt__() is __gt__().

There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other’s reflection, __le__() and __ge__() are each other’s reflection, and __eq__() and __ne__() are their own reflection. If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority. Virtual subclassing is not considered.


Q: iOS SDK - using @2x, and icons.. where do they go? I have been developing my app for about a week and have loaded some images into it.
I noticed that you can put an image into the app and it scales correctly.  I have some larger images that have scaled down and look great.
I guess this is discouraged because it takes some processing power or memory correct?  Okay, so I want to scale my images to their actual size.
Let's say I have a button that is 40x50
Should that be the @2x size, or should I double that, and set that to the @2x size?
Second question is:  I read apple guidelines about submissions to the app store, and it looks like you need to submit a plethora of icons.  I know you can apply a retina icon, and a regular icon when setting up your project.  What about the rest.  do you just use their naming guidelines and dump them into your project somewhere?

A:
should that be the @2x size, or should I double that, and set that to the @2x size?

Listen to your intuition. It's not called image@0.5x but image@2x...

do you just use their naming guidelines and dump them into your project somewhere?

After your graphics designer has sent you the necessary files, yes. But not just "somewhere". Rather into the root of your app bundle.


Q: Swift iOS 13 : Click on push notification how to open textfield? User want to interact on click of push notification and send comment/reply/message.
I have following code in AppDelegate:
     func configureNotification() {
        let center = UNUserNotificationCenter.current()

        center.requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }

        center.delegate = notificationDelegate

        let replyAction = UNTextInputNotificationAction(identifier: replyID, title: "Add reply", options: [], textInputButtonTitle: "Send", textInputPlaceholder: "Reply here")

        let deafultCategory = UNNotificationCategory(identifier: "CustomSamplePush", actions: [replyAction], intentIdentifiers: [], options: [])
        center.setNotificationCategories(Set([deafultCategory]))

        UIApplication.shared.registerForRemoteNotifications()
    }

And Handle action like following:
 func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {

        let identifier = response.actionIdentifier
               let request = response.notification.request

        if identifier == replyID{
            let textResponse = response as! UNTextInputNotificationResponse
            let newContent = request.content.mutableCopy() as! UNMutableNotificationContent
            newContent.body = textResponse.userText
            addNotification(content: newContent, trigger: request.trigger, indentifier: request.identifier)
        }

        completionHandler()
    }

    func addNotification(content:UNNotificationContent,trigger:UNNotificationTrigger?, indentifier:String){
        let request = UNNotificationRequest(identifier: indentifier, content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request, withCompletionHandler: {
            (errorObject) in
            if let error = errorObject{
                print("Error \(error.localizedDescription) in notification \(indentifier)")
            }
        })
    }

FYI : This code perfectly run for iOS 11 device but not working in iOS 13