text:
Q: Selenium WebDriver.get(url) does not open the URL from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
import time

# Create a new instance of the Firefox driver
driver = webdriver.Firefox()

# go to the google home page
driver.get("http://www.google.com")

This opens a Firefox window but does not open a url.

*

*I have a proxy server(but the address bar does not show the passed url)

*I have two Firefox profiles.

Can 1 or 2 be an issue? if yes, then how can I resolve it?

A: I was facing exactly the same issue, after browsing for sometime,I came to know that it is basically version compatibility issue between FireFox and selenium. I have got the latest FireFox but my Selenium imported was older which is causing the issue. Issue got resolved after upgrading selenium
pip install -U selenium

OS: windows Python 2.7

A: I have resolved this issue.
If your jar files are older than the latest version and the browser has updated to latest version, then download:

*

*the latest jar files from the selenium website http://www.seleniumhq.org/download/, and

*the latest geckodriver.exe.

A: It is a defect of Selenium.
I have the same problem in Ubuntu 12.04 behind the proxy.
Problem is in incorrect processing proxy exclusions. Default Ubuntu exclusions are located in no_proxy environment variable:
no_proxy=localhost,127.0.0.0/8

But it seems that /8 mask doesn't work for selenium. To workaround the problem it is enough to change no_proxy to the following:
no_proxy=localhost,127.0.0.1

Removing proxy settings before running python script also helps:
http_proxy= python script.py

A: @Neeraj
I've resolved this problem, but i'm not sure if you are the same reason.
In general, my problem was caused by some permission issues.
I tried to move my whole project into ~/:
mv xxx/ ~/

and then i change give it the 777 permission:
chmod -R 777 xxx/

I'm not familiar with linux permission so i just do this to make sure i have permission to execute the program.
Even you don't have permission, the selenium program will not prompt you.
So, good luck.

A: import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.get("http://www.google.com");

OR

import org.openqa.selenium.support.ui.ExpectedConditions;

WebDriverWait wait = new WebDriverWait(driver,30);
driver.get("http://www.google.com");
//hplogo is the id of Google logo on google.com
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("hplogo")));

A: I had the similar problem. All I had to do was delete the existing geckodriver.exe and download the latest release of the same. You can find the latest release here https://github.com/mozilla/geckodriver/releases.

A: A spent a lot of time on this issue and finally found that selenium 2.44 not working with node version 0.12.
Use node version 0.10.38.

A: I got the same error when issuing a URL without the protocol (like localhost:4200) instead of a correct one also specifying the protocol (e.g. http://localhost:4200).
Google Chrome works fine without the protocol (it takes http as the default), but Firefox crashes with this error.

A: I was getting similar problem and Stating string for URL worked for me. :)
package Chrome_Example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Launch_Chrome {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "C:\\Users\\doyes\\Downloads\\chromedriver_win324\\chromedriver.exe");
        String URL = "http://www.google.com";
        WebDriver driver = new ChromeDriver();
        driver.get(URL);
    }

}

A: I had the same problem but with Chrome.
Solved it using the following steps

*

*Install Firefox/Chrome webdriver from Google

*Put the webdriver in Chrome's directory.

Here's the code and it worked fine
from selenium import webdriver

class InstaBot(object):
    def __init__(self):
        self.driver=webdriver.Chrome("C:\Program
        Files(x86)\Google\Chrome\Application\chromedriver.exe")# make sure
                                                      #it is chrome driver
        self.driver.get("https://www.wikipedia.com")

InstaBot()

A: Check your browser version and do the following.
1. Download the Firefox/Chrome webdriver from Google
2. Put the webdriver in Chrome's directory.

A: I was having the save issue when trying with Chrome.   I finally placed my chromedrivers.exe in the same location as my project.  This fixed it for me.

A: Update your driver based on your browser.
In my case for chrome,

*

*Download latest driver for your chrome from here : https://chromedriver.chromium.org/downloads
Check chrome version from your browser at : chrome://settings/help.

*While initialising your driver,
use driver = webdriver.Chrome(executable_path="path/to/downloaded/driver")

A: You need to first declare url as a sting as below:
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
import time

# Create a new instance of the Firefox driver

String URL = "http://www.google.com";

driver = webdriver.Firefox()

# go to the google home page
driver.get(URL);

A: Try the following code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

WebDriver DRIVER = new FirefoxDriver();
DRIVER.get("http://www.google.com");

A: Please have a look at this HowTo: http://www.qaautomation.net/?p=373
Have a close look at section "Instantiating WebDriver"
I think you are missing the following code line:
wait = new WebDriverWait(driver, 30);

Put it between
driver = webdriver.Firefox();

and
driver.getUrl("http://www.google.com");

Haven't tested it, because I'm not using Selenium at the moment. I'm familiar with Selenium 1.x.

A: I was having the save issue. I assume you made sure your java server was running before you started your python script? The java server can be downloaded from selenium's download list.
When I did a netstat to evaluate the open ports,  i noticed that the java server wasn't running on the specific "localhost" host:
When I started the server, I found that the port number was 4444 :
$ java -jar selenium-server-standalone-2.35.0.jar
Sep 24, 2013 10:18:57 PM org.openqa.grid.selenium.GridLauncher main
INFO: Launching a standalone server
22:19:03.393 INFO - Java: Apple Inc. 20.51-b01-456
22:19:03.394 INFO - OS: Mac OS X 10.8.5 x86_64
22:19:03.418 INFO - v2.35.0, with Core v2.35.0. Built from revision c916b9d
22:19:03.681 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub
22:19:03.683 INFO - Version Jetty/5.1.x
22:19:03.683 INFO - Started HttpContext[/selenium-server/driver,/selenium-server/driver]
22:19:03.685 INFO - Started HttpContext[/selenium-server,/selenium-server]
22:19:03.685 INFO - Started HttpContext[/,/]
22:19:03.755 INFO - Started org.openqa.jetty.jetty.servlet.ServletHandler@21b64e6a
22:19:03.755 INFO - Started HttpContext[/wd,/wd]
22:19:03.765 INFO - Started SocketListener on 0.0.0.0:4444

I was able to view my listening ports and their port numbers(the -n option) by running the following command in the terminal:
$netstat -an | egrep 'Proto|LISTEN'

This got me the following output
Proto Recv-Q Send-Q  Local Address          Foreign Address        (state)

tcp46      0      0  *.4444                 *.*                    LISTEN

I realized this may be a problem, because selenium's socket utils, found in: webdriver/common/utils.py are trying to connect via "localhost" or 127.0.0.1:
socket_.connect(("localhost", port))

once I changed the "localhost" to '' (empty single quotes to represent all local addresses), it started working. So now, the previous line from utils.py looks like this:
socket_.connect(('', port))

I am using MacOs and Firefox 22. The latest version of Firefox at the time of this post is 24, but I heard there are some security issues with the version that may block some of selenium's functionality (I have not verified this). Regardless, for this reason, I am using the older version of Firefox.

A: This worked for me (Tested on Ubuntu Desktop 11.04 with Python-2.7):
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.stackoverflow.com")

A: Since you mentioned you use a proxy, try setting up the firefox driver with a proxy by following the answer given here proxy selenium python firefox


text:
Q: What is wrong with my constraint in my create table query? I'm new to SQL programming and having a problem with a constraint I'm setting up on the table named SP. I am using MySQLWorkbench and getting this error:

Error Code: 1239. Incorrect foreign key definition for 'FK_SP_sNo': Key reference and table reference don't match

I don't see what's wrong with it. Can anybody please help and explain what's wrong?
Best regards
CREATE TABLE S
(
    sNo CHAR(5),
    sName CHAR(20),
    status NUMERIC(5),
    city CHAR(15),

    PRIMARY KEY (sNo)
);

CREATE TABLE P
(
    pNo CHAR(6),
    pName CHAR(20),
    color CHAR(20),
    weight NUMERIC(10),
    city CHAR(15),

    PRIMARY KEY (pNo)
);

CREATE TABLE SP
(
    sNo CHAR(5),
    pNo CHAR(6),
    qty SMALLINT,

    PRIMARY KEY (sNo, pNo),
    CONSTRAINT FK_SP_sNo FOREIGN KEY (sNo) REFERENCES S,
    CONSTRAINT FK_SP_pNo FOREIGN KEY (pNo) REFERENCES P
);

A: You need the column name for the referenced table.
CREATE TABLE SP
(
sNo CHAR(5),
pNo CHAR(6),
qty SMALLINT, PRIMARY KEY (sNo, pNo),
CONSTRAINT FK_SP_sNo FOREIGN KEY (sNo) REFERENCES S(sNo),
CONSTRAINT FK_SP_pNo FOREIGN KEY (pNo) REFERENCES P(sNo)
);

A: I don't know if this is the same in MySQL, but in Microsoft SQL Server I would define a FK_SP_sNo foreign key like this:
CONSTRAINT FK_SP_sNo FOREIGN KEY (sNo) REFERENCES S(sNo)

The difference here is that the REFERENCES clause is in the form:
CONSTRAINT ConstraintName FOREIGN KEY (LocalField) REFERENCES RemoteTable(RemoteField)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java Pubnub Subscribing to Channel I am new to Pubnub and i was just needing some help with my code:
package com.test;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.pubnub.api.*;
import org.json.*;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.i("Tag", "Start");
    final Pubnub pubnub = new Pubnub("demo", "demo");
    Log.i("Tag", "Creation of pubnub");

    try{
        pubnub.subscribe("DavidsChannel", new Callback() {

                    @Override
                    public void connectCallback(String channel, Object message) {
                        System.out.println("SUBSCRIBE : CONNECT on channel:" + channel
                                + " : " + message.getClass() + " : "
                                + message.toString());
                        Log.i("Tag", "CONNECT");
                    }

                    @Override
                    public void disconnectCallback(String channel, Object message) {
                        System.out.println("SUBSCRIBE : DISCONNECT on channel:" + channel
                                + " : " + message.getClass() + " : "
                                + message.toString());
                        Log.i("Tag", "DISCONNECT");
                    }

                    public void reconnectCallback(String channel, Object message) {
                        System.out.println("SUBSCRIBE : RECONNECT on channel:" + channel
                                + " : " + message.getClass() + " : "
                                + message.toString());
                        Log.i("Tag", "RECONNECT");
                    }

                    @Override
                    public void successCallback(String channel, Object message) {
                        System.out.println("SUBSCRIBE : " + channel + " : "
                                + message.getClass() + " : " + message.toString());
                        Log.i("Tag", channel);
                    }

                    @Override
                    public void errorCallback(String channel, PubnubError error) {
                        System.out.println("SUBSCRIBE : ERROR on channel " + channel
                                + " : " + error.toString());
                        Log.i("Tag", "ERROR");
                    }
                }
        );
    } catch (Exception e) {
        System.out.println("Error" + " : " + e.toString());
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
I doesn't subscribe to the channel and returns:
08-14 10:47:06.625  13752-13752/? I/Tag﹕ Start
08-14 10:47:06.641  13752-13752/? I/Tag﹕ Creation of pubnub
08-14 10:47:06.655  13752-13773/? I/Tag﹕ ERROR
I was also getting this error:
08-14 10:42:06.321    2828-2856/? W/NetworkManagementSocketTagger﹕untagSocket(52) failed with errno -22
Please help me, Thank you in advance.

A: https://github.com/pubnub/java
Just copy and remove extra stuff. Create new basic project then move their project files across accordingly.


text:
Q: PHP curl works on localhost but not on the web server? The below php code is making a REST API call that returns json object. This works fine when i use it on my localhost using WAMP Absolutely no problem.
However when i push this app on the server it would TimeOut and display 503 Service Unavailable.
I checked the logs it has an entry :

The TimeOut Specified has expired.

I contacted my admin he just said this app listens to PORT=64665 and HOST=0.0.0.0. What does that mean? What more changes do i need to make in my code to make it work on the server ? Help
<?php
$url = "http://xyz.net/v2/plan/";   // I have changed the REST URI API Link for security reasons

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, false);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);

// Will dump json
var_dump(json_decode($result, true));

$response = "http://xyz.net/v2/plan/";
echo $response;
?>

A: Check your server's /etc/hosts file, there could be the problem, ie. domain mapped to another (wrong) IP address.


text:
Q: Query DbContext during OnModelCreating for tenantId filtering I am using .NET Core 5 with Entity Framework Core. I already have soft deletes by using SetQueryFilters with ActiveId to act as a delete.
I also want to apply a filter for certain tables that have a TenantId column to only show records that match the current user's organizations they are a part of (where TenantId falls within a list of OrganizationIds). I have the following code
public partial class AppContext : DbContext
{
    public AppContext (DbContextOptions<AppContext> options)
        : base(options)
    {
    }

    #region Generated Properties
    ...
    #endregion

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var entityType in modelBuilder.Model.GetEntityTypes())
        {
            var isActiveProperty = entityType.FindProperty("ActiveId");
            var isTenantProperty = entityType.FindProperty("TenantId");

            if (isTenantProperty != null && isTenantProperty.ClrType == typeof(Int32)
                && isActiveProperty != null && isActiveProperty.ClrType == typeof(Int32))
            {
                List<int> Ids = ///--Ids.NEEDTOGRABTHESE
                var parameter = Expression.Parameter(entityType.ClrType, "p");
                var filter = Expression.Lambda(
                    Expression.And(
                    Expression.OrElse(
                      Expression.Equal(Expression.Property(parameter, "ActiveId"), Expression.Constant((int)ActiveCodes.ACTIVE)),
                      Expression.Equal(Expression.Property(parameter, "ActiveId"), Expression.Constant((int)ActiveCodes.BLOCKED))
                    ),
                    Expression.Equal(Expression.Property(parameter, "TenantId"), ///--Ids.NEEDTOGRABTHESE)
                    ),
                parameter);

                entityType.SetQueryFilter(filter);//Update for ef 3.0
            }
        }
        #region Generated Configuration
        ...
        #endregion
    }
}

I'm struggling to find out how to query the database inside the OnModelCreating. I need to query the database in order to get the current users organizations. If I try to reference the context while inside OnModelCreating, I get the following error:

An attempt was made to use the model while it was being created. A DbContext instance cannot be used inside 'OnModelCreating' in any way that makes use of the model that is being created.

Since the only way I can access the current users organization is by accessing the database, and the dbContext is inaccessible at this point, what can I do to access the dbContext during the OnModelCreating?
Also if you suggest something is it efficient enough to be called every time OnModelCreating is built (would it cache the response)?

A: If I am understanding your requirement correctly, you need to use HasQueryFilter API.
ex:
modelBuilder.Entity<Organization>().HasQueryFilter(org => org.UserId == _userId);

here is the link, for a better explanation. Hope this will help

A: You need to create another context for Tenants. The solution you are looking for is here:
Solution


text:
Q: Change way of view data from DB I need a help with way of view data from database.
I have table with content from DB, like that:

  <% @scripts.each do |text| %>

      <%= text.book %>
      <%= text.chapter %>
      <%= text.line %>
      <%= text.body %>

  <% end %>

Output is like that:
book    chapter     line    body
  1         1        1       1 Lorem ipsum....
...
  1         1        10      10 Lorem ipsum....

I want to switch way of show book number as book title. I was thinking about Constant board, like:
in Script model:
BOOKS = {"1" => "Book1", "2" => "Book2" .... "66" => "Book66"

def book_name
  BOOKS[book_number]
end

in Script controller:
def book_number
  params[:script][:book]
end

in view file:

  <% @scripts.each do |text| %>

      <%= text.book_name %>
      <%= text.chapter %>
      <%= text.line %>
      <%= text.body %>

  <% end %>

When I done this i receive:
undefined local variable or method `book_number' for #


text:
Q: Problema com função que gera url amigável Boas
Tenho uma função que me gera o nome para as urls amigáveis mas estou a ter um problema que quando a função gera o nome se esse nome conter acentos ela não coloca a mesma palavra mas sem acento coloca outro caracter
Função
function url_amigavel($string) {
        $palavra = strtr($string, "ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ", "SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy");
        $palavranova = str_replace("_", " ", $palavra);
        $pattern = '|[^a-zA-Z0-9\-]|';    $palavranova = preg_replace($pattern, ' ', $palavranova);
        $string = str_replace(' ', '-', $palavranova);
        $string = str_replace('---', '-', $string);
        $string = str_replace('--', '-', $string);
        return strtolower($string);
    }

Por exemplo
César Sousa
Deveria de converter em cesar-sousa
Mas esta a converter assim
c-sar-sousa

A: Para limpar qualquer coisa que você queira botar em uma URL você pode usar a seguinte função (que usa iconv):
function sanitize_title($title) {
    // substitui espaços por "-"
    $title = preg_replace('#\s+#', '-', $title);

    // faz a transliteração pra ASCII
    $title = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $title);

    // remove qualquer outra coisa inválida da url
    $title = preg_replace('#[^a-zA-Z0-9_-]+#', '', $title);

    return $title;
}

Antes de chamar esta função é bom que você use setlocale para que a transliteração funcione corretamente:
setlocale(LC_ALL, 'pt_BR.UTF-8');

Exemplo:
    echo sanitize_title('César Sousa');
    echo sanitize_title('áéíóú@#_888999-teste outras  palavras');
Gera:
cesar-sousa
aeiou_888999-teste-outras-palavras

Veja um teste no ideone

A: Uma função simples que funciona comigo:
function url_amigavel($string){
    return preg_replace("/&([a-z])[a-z]+;/i", "$1", htmlentities($string));
}

Algo mais completo seria:
function url_amigavel($string){
    $url = str_replace(' ', '_', $string);
    $url = preg_replace("/&([a-z])[a-z]+;/i", "$1", htmlentities($url));

    return strtolower($url);
}

Veja aqui o teste:

Espero que funcione
Abs


text:
Q: Accelerometer in a QHO This is an extension of a previous idea where the authors proposed to put a microorganism on a mechanical oscillator. However, I can't ask the bacterium how it "feels" to be standing on a superposition state or how it "feels" when its floor gets measured.

*

*Trap a recording accelerometer in a harmonic potential

*Initialise the motional state in the ground state $|0\rangle$

*Displace the accelerometer motional state. This is to mark our reference in time in the reading of the accelerometer.

*Initialise the motional state in the ground state $|0\rangle$

*Prepare the motion in a superposition of Fock states, such as
$|0\rangle+|N\rangle$, where $N>0$

*Measure the motional state

*Download the accelerometer reading

What would had the accelerometer read?
My wild guess is that

*

*If motion projected to $|0\rangle$ then this would answer the question How does it "feel" to stand on a superposition?. The total acceleration integrated over time would be $0$, i.e., any effect on the acceleration from the superposition of step 5 would be undone at the measurement event.

*If motion projected to $|N\rangle$, then this would answer how does it "feel" when its floor gets measured?. The accelerometer would measure a narrow peak in the acceleration, and the width of that peak is the time it took for the motion to collapse, i.e., the measurement event was not instantaneous.


text:
Q: Simple components and the irreducible characters of the group ring $K[G]$ Let $K$ be an algebraically closed field of characteristic $0$ and $G$ a finite group. I know that the group ring $K[G]$ is a semisimple and so decomposes as a direct sum of $m$ simple components where $m$ is equal to the number of irreducible characters of $G$.
What is the exact relationship between these Wedderburn components and the (complete) set of irreducible characters? In particular how does this relate to the contragredient character of an irreducible character?
Many thanks for your help.


text:
Q: ESX(i) Interface Bonding ala Linux? I'm planning to virtualize some Linux hosts that I've got, and I'm going to be putting ESXi on the physical machines. Currently, I've got two switches set up for redundancy, and I've got bonding setup in mode 1 (active/backup).
Here's the simple logical layout:

Essentially, any switch, NIC, or firewall can die and everything still maintains connectivity.
I would very much like to continue this when I move to ESXi, but I haven't seen any evidence that it's possible (in fact, Duncan Epping from Yellowbricks indicates that it might not be possible, if I'm understanding the question and answers correctly).
Since I am relatively new to this whole "bare-metal virtualization" thing, I figured I'd ask people who knew more than me.
Can you set up your NICs in ESXi to be highly available? And if so, how?

A: It's SO easy it's not true, you simply define your vswitches and attach two or more physical NICs to them using the GUI, each NIC is then capable of carrying the traffic from your VMs (which don't need to know that their underlying networks are protected) or the service console. There are a number of load-balancing policies to choose, from a simple failover option to ones that truly balance your traffic across as many NICs as you've assigned.
I'm sure you'll find it very easy but if you have any queries just ask ok.
EDIT - here's how it appears on one of my boxes, showing two vswitches (one for management, one for VM traffic), it really is that simple.
alt text http://www.buckley-mellor.com/phil/sf/esx4ivswitchnics.jpg


text:
Q: Microsoft.Office.Interop.Word.FormFields.Item does not exist in VS 2010 I am upgrading a Windows application that was designed in Visual Studio 2005 and .Net 2 to Visual Studio 2010. One function of the application allows the end-user to open an existing MS Word document which is pre-populated with data from the active Window (i.e. customer account #, name, etc). The existing code that sets the field value is as follows:
public void SetField(string fieldName, string value)
{
    object fName = fieldName;
    try
    {
        document.FormFields.Item(ref fName).Result = value;
    }
    catch (COMException ex)
    {
        if (ex.Message != "The requested member of the collection does not exist.")
        throw;
    }
}

The "Item" method no longer exists. Is there a replacement?

A: Guessing from the documentation, it looks like it's just become an index - so maybe
document.FormFields[fName].Result = value;

(originally I had FormFields[ref fName] - as commented below the ref was wrong.)


text:
Q: write unicode character to a file in php - not duplicate I have a unicode string received over HTTP Post or fetched from a DB (does not matter)
In PHP I checked the encoding of the string using "mb_detect_encoding" and got UTF-8 as the result.
SO therefore the string is in Unicode.
But how do I write the string from php to a output file with the proper encoding
    $fd = fopen('myfile.php', "wb");
    fwrite($fd, $msg."\n");

What I see is "टेसà¥à¤Ÿ" instead of the actual string which is
टेस्ट्
Pasting the 'junk' into Notepad++ and then from menu option doing 'encoding UTF-8' will show the proper text.
EDIT
*SOLUTION*
Sorry for posting the question and figuring out the answer myself.
I found the solution at the following site
http://www.codingforums.com/showthread.php?t=129270
function writeUTF8File($filename,$content) {
        $f=fopen($filename,"w");
        # Now UTF-8 - Add byte order mark
        fwrite($f, pack("CCC",0xef,0xbb,0xbf));
        fwrite($f,$content);
        fclose($f);
}

A: PHP does not change the encoding of the string or does anything with it when you write to a file. It simply dumps the bytes of the string (PHP strings are really byte arrays) into the file, period. If you actually receive the string as UTF-8 and do not do anything with it except write it to a file, the content of the file will be UTF-8 encoded. Your problem is most likely that whatever application you're using to view the file does not properly read it as UTF-8 encoded.

That BOM solution is not necessarily the best. A BOM is not necessary for UTF-8 and many applications have problems with it. It only helps applications that are otherwise unable (too stupid) to detect that a file is UTF-8 encoded. The better solution may be to simply explicitly tell the application in question that it needs to treat the file as UTF-8 encoded when opening the file. Or use a better application.

A: You have to specify the strict parameter of mb_detect_encoding, or you'll get many false positives.
Also, while the output may be UTF-8, you will have to specify the right headers (content-encoding) and/or the charset meta tag (if it's HTML).

A: Sorry for posting the question and figuring out the answer myself.
I found the solution at the following site here
function writeUTF8File($filename,$content) {
        $f=fopen($filename,"w");
        # Now UTF-8 - Add byte order mark
        fwrite($f, pack("CCC",0xef,0xbb,0xbf));
        fwrite($f,$content);
        fclose($f);
}


text:
Q: How can i create this type of user interface? I am working on a tv remote application in that i have to create  this type of user interface(ignore the red dashed line) i tried using a circle background that is
    <?xml version="1.0" encoding="utf-8"?>

 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape
            android:shape="oval">
            <solid
                android:color="@color/colorGreyShade2"/>
            <padding
                android:bottom="@dimen/_40sdp"
                android:left="@dimen/_40sdp"
                android:right="@dimen/_40sdp"
                android:top="@dimen/_40sdp"/>
            <stroke
                android:width="1dp"
                android:color="@color/colorGreyShade2"/>
        </shape>
    </item>
    <item>
        <shape
            android:shape="oval">
            <solid
                android:color="@color/colorGreyShade2"/>

            <size
                android:width="@dimen/_100sdp"
                android:height="@dimen/_100sdp"/>
            <stroke
                android:width="1dp"
                android:color="@color/colorGreyShade1"/>
        </shape>

    </item>
</layer-list>

and using this as background of a layout and trying to adjust the navigation buttons in that but not able to achieve.
Can i use this image in an ImageView and detect user clicks from five button areas?

A: You can achieve this from this. no need create drawable layer list. You can use imageview, textview and constraint layout.And this will also easy to implement all five button clicks.
bg_circle_fill_white.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/divider" />

    <stroke
        android:width="1dp"
        android:color="@color/black" />

    <padding
        android:bottom="1dp"
        android:left="1dp"
        android:right="1dp"
        android:top="1dp" />

    <corners android:radius="@dimen/_100sdp" />
</shape>

layout.xml
<?xml version="1.0" encoding="utf-8"?>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="@dimen/_200sdp"
        android:layout_height="@dimen/_200sdp">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="@dimen/_150sdp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:background="@drawable/bg_circle_fill_white"
            android:layout_height="@dimen/_150sdp">

            <androidx.appcompat.widget.AppCompatImageView
                android:layout_width="wrap_content"
                android:src="@drawable/ic_previous_arrow"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                android:padding="@dimen/_5sdp"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_height="wrap_content" />

            <androidx.appcompat.widget.AppCompatImageView
                android:layout_width="wrap_content"
                android:src="@drawable/ic_next_arrow"
                app:layout_constraintEnd_toEndOf="parent"
                android:padding="@dimen/_5sdp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_height="wrap_content" />

            <androidx.appcompat.widget.AppCompatImageView
                android:layout_width="wrap_content"
                android:src="@drawable/ic_arrow_up"
                app:layout_constraintEnd_toEndOf="parent"
                android:padding="@dimen/_5sdp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                android:layout_height="wrap_content" />

            <androidx.appcompat.widget.AppCompatImageView
                android:layout_width="wrap_content"
                android:src="@drawable/ic_arrow_down"
                app:layout_constraintEnd_toEndOf="parent"
                android:padding="@dimen/_5sdp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                android:layout_height="wrap_content" />

            <androidx.appcompat.widget.AppCompatTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="@dimen/_20sdp"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:text="OK"
                android:background="@drawable/bg_circle_fill_white" />

        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>


text:
Q: Find out whether a URL is broken? I have a URL that should contain a video:
http://img.epictv.compodcasts/Surf_Report_Tahiti_Take_2_podcast.mp4
But, it seems to be broken (the resource is not available). Is it possible to know that it is broken programatically?

A: If you want to check URL just do a HEAD request using a NSURLConnection.

A: First thing I think of is to ping the URL, thought NSURLConnection can do that too (And actually any ping process should be based on NSURLConnection).
You can use this open-source for that.
Hope this answer satisfies you.


text:
Q: Bind external script events to html in components I'm trying to call an external script
In public/index.html
<script src="https://embed.selly.gg"></script>

An event is suppose to be called when I click on a button with a specific data tag.
In components/shop/ShopItem.js
<button className={classes.button} data-selly-product={product.id}>
    Buy
</button>

But nothing happens.
How do I bind the events from embed.selly.gg to the component html?

A: You can do something like this:
componentDidMount () {
    const script = document.createElement("script");

    script.src = "https://embed.selly.gg";
    script.async = true;

    document.body.appendChild(script);
}

A: What if you simple ping the parent on mount with a function and put
@piyush-zalani 's script registration method there with a condition. If the script has been loaded, do not load again.
Shopitem.js
componentDidMount(){
  const { onMount } = this.props;
  onMount('https://embed.selly.gg');
}

Shop.js
...
state = {}

handleCreateScriptTag = src => {
  const { loadedScripts } = this.state;
  if (loadedScripts && loadedScripts.indexOf(src) > -1) return;

  const script = document.createElement("script");

  script.src = src;
  script.async = true;

  document.body.appendChild(script);

  this.setState(prevState => ({
    loadedScripts: [...prevState.loadedScript, src]
  }))
}

render() {
  return (
    <ShopItem onMount={this.handleCreateScriptTag} />
  )
}


text:
Q: Adding a feature for unseen words I am using sklearn countvectorizer to build my term-document matrix
However,
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(min_df=1)
corpus = ['this is jummy speaking now']
X = vectorizer.fit_transform(corpus)
c = vectorizer.transform(['lol 123']).toarray()

What happens is that X would be a term document matrix of 5 words. However,  i would like the matrix to have an unknown column aka term document matrix of 6 words. In the case when a new unseen word is found, i would like it to be part of the unknown column. like for example (lol and 123) is not in the corpus. It should be part of the unknown column.


text:
Q: Autocomplete in golang in emacs I'm aware a lot is involved in getting autocomplete to work in emacs, including:

*

*auto-complete

*company

*flymake

I am not sure which components are responsible for which aspects.  What is the package that when I start typing...
fmt.P

Would finish with
fmt.Println

?
I believe I have company as my auto-complete, and at present, if I start:
fm

It finishes fmt, but
fmt.

Produces nothing, and
fmt.P

Produces
fmt.package

Which is entirely wrong.  What package should I investigate to understand what is going on?

A: Autocomplete, company-mode, flymake, oh my.  I recommend you uninstall all of the above and use Emacs' native completion instead:

*

*install gocode and make sure the binary is in Emacs' PATH;

*install the go-complete package in Emacs (I got it from melpa, but you may prefer to install it manually);

*add the following to your .emacs:
(add-hook 'completion-at-point-functions 'go-complete-at-point)

*press M-TAB in a go-mode buffer.

A: Since the original answer was written, the original gocode has ceased being maintained.  While there exist forks of gocode that work well with recent versions of Go, the recommended replacement is golsp

*

*Install the eglot pakage from ELPA (not necessary if you are running Emacs 29 or later, which includes eglot out of the box).

*Install golsp and make sure it is in your path.

*Add the following to your .emacs:

(add-hook 'go-mode-hook #'eglot-ensure)

*Press M-TAB in a go-mode buffer.


text:
Q: How to obtain certain lines from a text file in c#? I'm working in C# and i got a large text file (75MB)
I want to save lines that match a regular expression
I tried reading the file with a streamreader and ReadToEnd, but it takes 400MB of ram
and when used again creates an out of memory exception.
I then tried using File.ReadAllLines():
string[] lines = File.ReadAllLines("file");

StringBuilder specialLines = new StringBuilder();

foreach (string line in lines)

 if (match reg exp)

  specialLines.append(line);

this is all great but when my function ends the memory taken doesnt clear and I'm
left with 300MB of used memory, only when recalling the function and executing the line:
string[] lines = File.ReadAllLines("file");
I see the memory clearing down to 50MB give or take and then reallocating back to 200MB
How can I clear this memory or get the lines I need in a different way ?

A:         var file = File.OpenRead("myfile.txt");
        var reader = new StreamReader(file);
        while (!reader.EndOfStream)
        {
            string line = reader.ReadLine();
            //evaluate the line here.
        }
        reader.Dispose();
        file.Dispose();

A: You need to stream the text instead of loading the whole file in memory. Here's a way to do it, using an extension method and Linq:
static class ExtensionMethods
{
    public static IEnumerable<string> EnumerateLines(this TextReader reader)
    {
        string line;
        while((line = reader.ReadLine()) != null)
        {
            yield return line;
        }
    }
}

...

var regex = new Regex(..., RegexOptions.Compiled);
using (var reader = new StreamReader(fileName))
{
    var specialLines =
        reader.EnumerateLines()
              .Where(line => regex.IsMatch(line))
              .Aggregate(new StringBuilder(),
                         (sb, line) => sb.AppendLine(line));
}

A: You can use StreamReader#ReadLine to read file line-by-line and to save those lines that you need.

A: You should use the Enumerator pattern to keep your memory footprint low in case your file can be huge.


text:
Q: Script slow on ipad and safari I have a script to animate elements with a data attribuut. This is the script.
// fade in the elements one by one.
function showContent() {
    var toAnimate = $('.animate-content');
    // put in the correct order.
    toAnimate.sort(function(a, b) {
        return a.getAttribute('data-sequence') > b.getAttribute('data-sequence');
    });

    toAnimate.each(function(i) {
        $(this).delay(500 * i).fadeTo(1000, 1);
    });
}

// start fading in the elements after a delay.
setTimeout(showContent, 250);

But this script making the website super slow on an iPad and Safari. Does anyone know what I'm doing wrong? Why this script making my website verry slow

A: Try this:
var toAnimate = $('.animate-content');
toAnimate.sort(function(a, b) {
    return a.getAttribute('data-sequence') > b.getAttribute('data-sequence');
});

function showContent() {
    toAnimate.each(function(i) {
        $(this).delay(500 * i).fadeTo(1000, 1);
    });
}

setTimeout(showContent, 250);


text:
Q: Error in sending mail via STMP in aws elasticbeanstalk I am unable to resolve this error. I am running django. It works properly on my local, but I have deployed the code to aws elasticbeanstalk where it throws the below error.
Also my smtp configuration is something like this.
I have also tried to ALLOW low secure apps in Google settings.
But nothing seems to work.
# SMTP configuration
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'email@gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_USE_TLS = True

Environment:
Request Method: POST
Request URL: http://odm-masala-app-env.eba-ijhfppue.us-west-2.elasticbeanstalk.com/accounts/register/

Django Version: 3.1
Python Version: 3.7.10

Installed Applications:

['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'category',
 'accounts',
 'store',
 'carts',
 'orders',
 'admin_honeypot',
 'storages']

Installed Middleware:

['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django_session_timeout.middleware.SessionTimeoutMiddleware']

Traceback (most recent call last):
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/var/app/current/accounts/views.py", line 53, in register
    send_email.send()
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/mail/message.py", line 284, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages
    new_conn_created = self.open()
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 69, in open
    self.connection.login(self.username, self.password)
  File "/usr/lib64/python3.7/smtplib.py", line 730, in login
    raise last_exception
  File "/usr/lib64/python3.7/smtplib.py", line 721, in login
    initial_response_ok=initial_response_ok)
  File "/usr/lib64/python3.7/smtplib.py", line 642, in auth
    raise SMTPAuthenticationError(code, resp)

Exception Type: SMTPAuthenticationError at /accounts/register/
Exception Value: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbt\n5.7.14 JzmJlDR_KXwRjsGoeGbUwfJiFaseGdN7r4Tr5kVIBAWkZ_KxJtmoZ21tvxssaWR96lYr1\n5.7.14 1McFMOBeAoLgjKAhaZSf7Z0H7mCYUPyXbKlQ-CmDohYCNFK3GmWZG47EBOB2uOnH>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14  Learn more at\n5.7.14  https://support.google.com/mail/answer/78754 63sm12202837pfz.119 - gsmtp')

A: This is because gmail uses captcha verification, please try disabling it from below link.
https://accounts.google.com/DisplayUnlockCaptcha


text:
Q: What is the difference between PublicKeyToken and public key? Each signed .NET has both a public key token (8 byte) and a public key (128 bytes).
What is the difference between the 2, and why do we need two public "keys"?

A: Public Key token is just the hash of the public key. Here for info.

UPDATE

Why we need public key?

Since assembly can be signed and signed assemblies will contain the public key. When loading DLL .NET will use the public key to validate the assembly against the signature. Signature can be only generated using the private key while public key itself can be used for validating the signature.
This process makes sure assembly is not tampered with.
From CLR via C#:

Signing an assembly with a private key
  ensures that the holder of the
  corresponding public key produced the
  assembly. When the assembly is
  installed into the GAC, the system
  hashes the contents of the file
  containing the manifest and compares
  the hash value with the RSA digital
  signature value embedded within the PE
  file (after unsigning it with the
  public key). If the values are
  identical, the file's contents haven't
  been tampered with, and you know that
  you have the public key that
  corresponds to the publisher's private
  key. In addition, the system hashes
  the contents of the assembly's other
  files and compares the hash values
  with the hash values stored in the
  manifest file's FileDef table. If any
  of the hash values don't match, at
  least one of the assembly's files has
  been tampered with, and the assembly
  will fail to install into the GAC.

UPDATE 2
Why public key token needed? Since public key is too big to work with so (Again from CLR visa C#):

The size of public keys makes them
  difficult to work with. To make things
  easier for the developer (and for end
  users too), public key tokens were
  created. A public key token is a
  64-bit hash of the public key.
  SN.exe's -tp switch shows the public
  key token that corresponds to the
  complete public key at the end of its
  output.
  Because public keys are such large
  numbers, and a single assembly might
  reference many assemblies, a large
  percentage of the resulting file's
  total size would be occupied with
  public key information. To conserve
  storage space, Microsoft hashes the
  public key and takes the last 8 bytes
  of the hashed value. These reduced
  public key values—known as public key
  tokens—are what are actually stored in
  an AssemblyRef table. In general,
  developers and end users will see
  public key token values much more
  frequently than full public key
  values. Note, however, that the CLR
  never uses public key tokens when
  making security or trust decisions
  because it is possible that several
  public keys could hash to a single
  public key token.


text:
Q: Find matching rows in a numpy matrix of 3 Given a cube of mxmxm, I need to know the rows, in the 6 faces that the smallest value in their row is greater than a given n.

A: To obtain the various faces:
faces = np.array([
    x[ 0,  :,  :],
    x[-1,  :,  :],
    x[ :,  0,  :],
    x[ :, -1,  :],
    x[ :,  :,  0],
    x[ :,  :, -1],
])

Now collapse the last dimension axis:
# No information on orientation provided by OP so always pick axis=-1
row_mins = np.min(faces, axis=-1)

And then keep only the rows that satisfy the condition:
valid_rows = faces[row_mins > n]
print(valid_rows)

A: You can filter the values with the help of iteration. For numpy iteration

codes
import numpy as np
data=np.arange(54).reshape(6,3,3)
print(data,data.ndim)

#n : given value to filter
n=10

#to get all the elements that are greater than n
print(data[data>n])

for i in data:
  for row in i:
    if  row[row>n].size :
        print(row)

Let me know if you have any doubts.


text:
Q: Cannot resolve method OnStartCommand() I am trying to create a service in android API 22.
I getting error while trying to override the method OnStartCommand();
'cannot resolve method'.
When I don't override the method I am getting error 'method does not override method from super class'. I am using Android Studio 1.5.1
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class BlockService extends Service {

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void OnStartCommand(Intent intent,int flags, int startId){
    Toast.makeText(this,"service Started",Toast.LENGTH_LONG).show();
  }

}

screenshot

A: Java is case-sensitive. The method name is onStartCommand(), not OnStartCommand().


text:
Q: How to hide label attribute of select's option? please tell me how to hide label attribute of select's option
<select>
  <option label='.65' value='10'>10 gram</option>
  <option label='.23' value='20'>20 gram</option>
  <option label='.85' value='30'>30 gram</option>
</select>

in firefox its ok but in google chrome it displays the label in front end instead of the text
i.e
in firfox front end it will displays
10 gram
20 gram
30 gram

and in google chrome
.65
.23
.85

A: if you change label to lab or something else, it will show same as in Firefox.


text:
Q: Accessing Rails images by direct path I am integrating a Angular app with Rails and I have a problem with accessing the images. Angular app has a lots of path to images with structure: (for example)
   src="assets/img/layout/ico-przystawki.png"

But that doesn't work in a Rails application, because I shouldn't be using the 'img' part. It should be like this:
   src="assets/layout/ico-przystawki.png"

Is there a way to tell Rails application to use direct paths to images, so that I don't have to change every time these paths?

A: I found myself using the non-stupid-digest-assets gem for this very purpose. See https://github.com/alexspeller/non-stupid-digest-assets

A: Stop assets precompile and then you can access all img (and assets file) with src="assets/ut/ico-przystawki.png"

A: Try to use the provided rails helper method image_tag instead when you call an image:
<div>
   <%= image_tag("ico-przystawki.png") %>
</div>

Read more about that here:
http://apidock.com/rails/ActionView/Helpers/AssetTagHelper/image_tag


text:
Q: Python Flask Cors error - set according to documentation I have created API using Flask in Python. Now I am trying to create front end, where I want to call API. I set CORS according Flask-Cors documentation, unfortunately it doesn't work.
from flask_cors import CORS
CORS(app)

I got this error
CORS error - Safari
CORS error - Chrome
I have found some similar topics, where was some solution. I have tried, but neither of them work for me. E.g.
CORS(app, origins=['http://localhost:4200'])
app.config['CORS_HEADERS'] = 'Content-Type'

I have also tried cross_origin decorator, but it doesn't work as well.
@app.route("/login", methods = ["POST"])
@cross_origin(origin='*')
def login():
    credentials = request.get_json()
    ....

Could someone help me, how to solve this problem?

A: Make sure the URL you are trying to access begins with 'http://' or 'https://' according to your web server's configuration


text:
Q: Can Ubuntu 12.04LTS fit on a normal CD, 700MB, or i do need a DVD? i just want to know if the new ubuntu (12.04LTS) can fit perfectly on a normal cd :)

A: I stopped burning a CD (or DVD) for ISO files about 2 years ago.
A cheap 2GB Flash USB drive is 3-4 times faster for installs, and can be repeatedly reused (for later releases).

A: You can install from a normal CD:
http://www.ubuntu.com/download/desktop/install-ubuntu-desktop


text:
Q: Python: Screen Scraping table values I am currently using Python 2.7 with Selenium and beautiful soup 4 installed.
I'm creating a script that is navigating through pages of tables. In the table, each row has a link that takes me to another page, which I can scrape as a form. Is there a way I can pull the values of one column (there is only one column in the table) and store them as an array?
This way, I can cycle through the array to navigate each of the links.
Thanks!

A: try using driver.find_elements_by_css_selector() so you'd do something like:
tds = driver.find_elements_by_css_selector("#your-table-id td")

tds will now be a list of element objects. Note this will give you all tds in the table.


text:
Q: Weaving a binary file from an object file using LD and objcopy I am trying to build a custom binary file which data mostly comes from a .o file, compiled from a big C file which looks like the following:
int a[] = { ... };
int b[] = { ... };
int c[] = { ... };

This C file basically contains a big set of data arrays, all declared within the same section. An important note here is that I cannot modify the content of this C file.
Is it possible, using LD scripts, objcopy, or any other tool, to weave a set of output binary files containg just one or a few of these variables, in a specific order (not necessarily the same order as they appear in the C file)?
I tried to use a LD script for this, but the finest granularity of inclusion seems to be the section of an object file. To achieve what I want I would need to be able to reference symbols directly.
The output will ultimately be a simple binary file (generated using objcopy -Obinary), containing only the concatenation of the desired arrays. So for this question we can assume that I only need to output all data in a single section (i.e. there is no code, nor is there any other input than this big C file).


text:
Q: How to get Servlet class from URI I'm in a Filter implementation and have a response which will call a redirect.
Now I try to determine which Servlet class the redirect URL will call. (without call Servlet itself - I only want to know which class)
like:
public void doFilter( ServletRequest request, ServletResponse response, FilterChain filterChain ) throws IOException, ServletException
{
    ...
    filterChain.doFilter( request, response );
    //now the response is a redirect
    if (redirect) {
         Class servletClass = request.getRequestDispatcher( response.getString() ).[getServletClass()]; //or something like
    ...
    }
}

I need to know if it's a redirect AND if a specific servlet is called, cause i must manipulate the response BEFORE the redirect.
Exactly:

*

*an request reach the filter. (It's an XmlHttpRequest, but i think it doesn't matter)

*the response will cause an redirect.

*the response comes to browser and there I see in JavaScript "hey it's a redirect - but which servlet will accessed?" - I need this information at this time in JavaScript. So I try to put some extra information to the response.

A:
Now I try to determine which Servlet class the redirect URL will call

Since your ultimate goal is just to redirect, I think using response#sendRedirect in the servlet you're redirecting from is an easier way to do this all together.  Redirecting this way will allow you to avoid this:
if (redirect) {
         Class servletClass = request.getRequestDispatcher( response.getString() ).[getServletClass()]; //or something like
    ...
    }

Filters aren't really meant for directing requests to the proper servlets.  I admit though that this often ends up being done because the servlet-mapping xml element in web.xml isn't very robust.  Despite this, its best to stick to having your web xmls map which urls go to which servlets - when possible - because it is declarative and easier to maintain.


text:
Q: Xamarin Forms iOS - Carrier Bar background color changes on Detail, not Master I have a MasterDetail page, Detail is a Naviagtion page, Master contains a Listview.  I'm changing the color of the header bar background color and text using
((NavigationPage)Detail).BarBackgroundColor = Color.Navy;
((NavigationPage)Detail).BarTextColor = Color.White;

This changes the carrier bar text to white for both the Master and Detail sections, but only changes the carrier bar background on the Detail section, the Master is still white/transparent so the text is no longer visible.  Is this a bug?  I would expect the bar variables to work the same, to only work on the Navigation page since that is the page they are being applied to.
note- I am NOT setting the StatusBarStyle to LightContent, the status bar on a content page shows as black text on a white background.

*Edit - I would expect it to look like this - the CarrierBarText color is changes only on the Navigation Page:

A: I think this is expected behavior instead of a bug. The iOS status bar is translucent, but the navigation bar on the Detail page extends to the top of the window so the status bar looks like it has a color.
The Master page also extends to the top of the window so when it's pushed into view, the top 20px get displayed under the status bar, which in this case is just the background of the page. You can change the page's background to Navy to match the navigation bar so it appears more consistent.

A: The only way to change the iOS Status Bar Color in Xamarin.Forms is to set the BarTextColor of a NavigationPage. Detail pages must be a NavigationPage, so they're able to set the BarTextColor property.
Because the Master page isn't a NavigationPage, it doesn't have a BarTextColor property, and it can't change the iOS Status Bar Color.
My recommendation is to change the background color of the Master page to a darker color (like Navy Blue) so that the white text in the iOS Status Bar is still visible.
James Montemago did a great blog post that talks about setting the iOS Status Bar Color:
http://motzcod.es/post/110755300272/ios-tip-change-status-bar-icon-text-colors

If you are using Xamarin.forms you must also set the BarTextColor = Color.White on your NavigationPage! Additionally, you should go into your info.plist and set "View controller-based status bar appearance" to No


text:
Q: Are these expressions to call of a particular kind of deviation right? I am translating a material on visual sensors and having a hard time figuring out what to call this.
The situation is that when the sensor senses a circle mark, sometimes it does not detect a fine circle. Instead, the circle becomes a little wavy, having some parts of outline sticking out of the real line, and some parts going inside.
I need to express the length of the difference between the real line and the off-points of the detected line. I came up with the following two expressions. Does either of them indicate what I am trying to say?

Positive/negative difference" OR "Positive/negative deviation length".

A: I think simply "deviation" is fine. Deviation is already defined as "a measure of difference between the observed value of a variable and some other value".
So I'm pretty certain you don't even need the "length"-part. The term "deviation in length" is only used when referring to an actual difference in length.
I'd go for "The deviation between the two lines in [unit] is X".


text:
Q: How to Make a Slider Witty like javascript? I have started a project that Web pages serving from C++ application.
there is a lot of javascript tutorial from beginners to to novice.
and how can i embed this javascript slider to web page made by Witty C++?
i Have one server made by Qt run on Windows, one windows client made by Qt and one android client made by Qt, now i am started to web client with Witty and Qt.
But i need to only witty and Javascript Tutorial make slider.
Javascript Tutorial
But this link only show pop up message.
there is no basic or any example for slider. Can any anybody show how it is made?
thanks

A: ok my error is setTimeout function in javascript. there is no fail with witty, this slider is great me , now going on styling wow:)
WImage* img = new WImage(root());

img->setId("imgslider");
std::string command = std::string(      "var i = 1;"
                                          "var path = new Array();"
                                          "path[0] = \"1.jpg\";"
                                          "path[1] = \"2.jpg\";"
                                          "path[2] = \"3.jpg\";"
"var ifr = document.getElementById('imgslider');"
"function start(counter){"
                                          "if(counter < 10){"
                                            "setTimeout(function(){"
                                              "counter++;"
                                              "counter = counter % 3;"
                                              "ifr.src = path[counter];"
                                              "console.log(counter);"
                                              "console.log(path[counter]);"
                                              "console.log(ifr.src);"
                                              "start(counter);"
                                            "}, 1000);"
                                          "}"
                                        "}"
                                        "start(1);"
                                        );
img->doJavaScript(command);


text:
Q: MVC Razor Get Month Name I have the following code in my MVC 4 razor view, which is supposed to take the DateTime property called modifiedDate, and print out the month name, ie, Jan, Feb etc, instead of 1, 2.
@foreach (var post in Model.NewsList)
{

@post.modifiedDate.Value.Month.ToString("mmm")

}

Any ideas how to do this?
Thanks.

A: See The "MMMM" Custom Format Specifier
Usage:
DateTime? date = DateTime.Now;

date.Value.ToString("MMMM"); // Prints the Month name (e.g. May)

Corrected:
@foreach (var post in Model.NewsList)
{

@post.modifiedDate.Value.ToString("MMMM")

}


text:
Q: Ubuntu isn't booting My Ubuntu 21.04 isn't booting after setup proprietary drivers and reboot.
Driver: NVIDIA driver metapackage from nvidia-driver-450
Video card: GeForce GTX 1050 Mobile
I've installed this driver in Software & Updates > Additional Drivers
And after i've booted my system, i saw an error.
Error:
/etc/profile/ line 27, Syntax error: unexpected end of file
profile code:
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).

if [ "${PS1-}" ]; then
  if [ "${BASH-}" ] && [ "$BASH" != "/bin/sh" ]; then
    # The file bash.bashrc already sets the default PS1.
    # PS1='\h:\w\$ '
    if [ -f /etc/bash.bashrc ]; then
      . /etc/bash.bashrc
    fi
  else
    if [ "`id -u`" -eq 0 ]; then
      PS1='# '
    else
      PS1='$ '
    fi
  fi
fi

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i

By the way, I don't see the line 27 in gedit in the file profile


text:
Q: Can I delete the default application_controller installed with Rails? When I create a new app there is a default controller added called application_controller.
Is this holding important information or can I delete it?

A: Well, every other controller you generate will inherit from the ApplicationController, so you kinda need it. Is your interest purely academic, or are you having problems with it?


text:
Q: Intersecting a result set with a table I have two tables.
The first one is people, it has three columns (id, name, age).
The second one is for people group, it has three columns (group_id, person_id).
First I have a query to get people whose age is greater equal than 18:
SELECT *
FROM people
WHERE age >= 18;

Now I want to get a group which contains ALL this people. How can I do it?

A: You want all the above 18 years olds in one group?  Well, let's count them and see if the numbers match:
select pg.group_id
from people_group pg join
     people p
     on pg.person_id = p.id and p.age >= 18
group by pg.group_id
having count(distinct pg.person_id) = (select count(*) from people where age >= 18);

A: You can try the following:
select pg.group_id
from people_group pg
left join people p on p.id = pg.person_id and p.age >= 18
group by pg.group_id
having sum(case when p.id is null then 1 end) is null

SQLFiddle


text:
Q: Why is it that my thumbnail PIL function won't work the 2nd time?
def create_thumbnail(f, width=200, height=100):
    im = Image.open(f)
    im.thumbnail((width, height), Image.ANTIALIAS)
    thumbnail_file = StringIO()
    im.save(thumbnail_file, 'JPEG')
    thumbnail_file.seek(0)
    return thumbnail_file

It seems that my error is "IOError: cannot identify image file"...based on my traceback log.

A: The only thing I can think of is that you are running on Windows, in which case Image.open() will open a file handler but does not close it.  (That behaviour does not occur on Linux/Unix - the file is closed by the end of your code, and it doesn't matter if it isn't anyway).


text:
Q: Equivalent of `curl --connect-to` in Python Requests library curl has an option connect-to
   --connect-to <HOST1:PORT1:HOST2:PORT2>

          For  a  request  to  the  given  HOST:PORT pair, connect to CONNECT-TO-HOST:CONNECT-TO-PORT instead.  This option is suitable to direct requests at a specific
          server, e.g. at a specific cluster node in a cluster of servers.  This option is only used to establish the network connection. It does NOT affect  the  host-
          name/port  that is used for TLS/SSL (e.g. SNI, certificate verification) or for the application protocols.  "host" and "port" may be the empty string, meaning
          "any host/port".  "connect-to-host" and "connect-to-port" may also be the empty string, meaning "use the request's original host/port".

          This option can be used many times to add many connect rules.

What is the equivalent in Python Requests library?

A: There is no such equivalent but you can patch lower levels to rewrite the remote address before creating the connection.
This works in Python 3:
from unittest.mock import patch

# contextmanager for forcing a connection to a given host, port
def connect_to(host, port):
    from urllib3.util.connection import create_connection as orig_create_connection

    def _forced_address_connection(address, *args, **kwargs):
        forced_address = (host, port)
        return orig_create_connection(forced_address, *args, **kwargs)

    return patch('urllib3.util.connection.create_connection', _forced_address_connection)

# force connections to 127.0.0.1:8080
with connect_to('127.0.0.1', 8080):
    res = requests.get('http://service.example.com/')

Solutions like patching PoolManager or using a custom adapter are not enough because the URL is rewritten as well (and thus the Host:  header). When you use curl --connect-to, nothing is altered at HTTP level.
I also needed to optionally force http connections despite the URL scheme. This is the working augmented version for that:
import contextlib
from unittest.mock import patch

@contextlib.contextmanager
def connect_to(host, port, force_http=False):
    from urllib3.connection import HTTPConnection
    from urllib3.util.connection import create_connection as orig_create_connection

    def _forced_address_connection(address, *args, **kwargs):
        forced_address = (host, port)
        return orig_create_connection(forced_address, *args, **kwargs)

    class ForcedHTTPConnection(HTTPConnection):
        def __init__(self, **kwargs):
            httpconn_kw = ('host', 'port', 'timeout', 'source_address', 'blocksize')
            httpconn_kwargs = dict([(k, kwargs[k]) for k in httpconn_kw if k in kwargs])
            super().__init__(**httpconn_kwargs)

    patchers = [patch('urllib3.util.connection.create_connection', _forced_address_connection)]
    if force_http:
        patchers.append(patch('urllib3.connectionpool.HTTPSConnectionPool.ConnectionCls', ForcedHTTPConnection))

    for p in patchers:
        p.start()

    yield

    for p in patchers:
        p.stop()

# force connections to 127.0.0.1:8080 using http
with connect_to('127.0.0.1', 8080, force_http=True):
    res = requests.get('https://service.example.com/')

see also Python 'requests' library - define specific DNS?.


text:
Q: Recursive Merge Sort, wrong data type for argument? I feel like ive properly solved the problem, but the program my school is using wants me to add to existing code. The types conflict, and i get this error:
main.cpp: In function 'void mergeSort(std::vector<int>&, int, int)':
main.cpp:21:25: error: cannot convert 'std::vector<int>' to 'int*' for argument '1' to 'void merge(int*, int, int, int)'
   merge(array, p, mid, r);

#include <vector>
using namespace std;

// Takes in an array that has two sorted subarrays,
//  from [p..q] and [q+1..r], and merges the array
void merge(int array[], int p, int q, int r) {
  // This code has been purposefully obfuscated,
  //  as you'll write it yourself in next challenge.
  int i, j, k; int n1 = q - p + 1; int n2 =  r - q; int L[n1], R[n2]; for (i = 0; i < n1; i++) L[i] = array[p + i]; for (j = 0; j < n2; j++) R[j] = array[q + 1+ j]; i = 0;j = 0;k = p; while (i < n1 && j < n2){ if (L[i] <= R[j]) { array[k] = L[i]; i++;} else { array[k] = R[j]; j++; } k++; } while (i < n1) { array[k] = L[i]; i++; k++; } while (j < n2) { array[k] = R[j]; j++; k++; }
}

// Takes in an array and recursively merge sorts it
void mergeSort(vector<int>& array, int p, int r) {
  if(p >= r)
  {
    return;
  }
  int mid = (p + r) / 2;
  mergeSort(array, p, mid);
  mergeSort(array, mid + 1, r);
  merge(array, p, mid, r);
};

This is what is provided. I'm told to add the definition to mergeSort
I have not tested the code, so it could be wrong. This is not about how to solve Merge Sort, it is about the different types and get merge to accept it. Forgive me if this question is not formatted right, first time here.
Thanks in advance!

A: To get the underlying int* in array, use the .data() method:
void mergeSort(vector<int>& array, int p, int r) {
  //stuff
  merge(array.data(), p, mid, r);
};

The .data() method returns an int* representing the underlying buffer in which the elements of the vector are stored. This should remove the error.


text:
Q: No video sound on Ubuntu from laptop computer speaker I am using Ubuntu 10.04 along Windows7 on my laptop.
I can listen to spotify and no problem.
But any kind of video on Firefox or Chrome does not play sound.
It plays video but without sound.
When I play avi, there is no sound coming from my laptop computer speaker either.
Could anyone tell me how to fix this problem?
I am using Dell Latitude D830.
Thanks in advance.

A: Have you checked that the default sound output used by the system is the same as for Spotify?
It might be the origin of your problem.
If not, does changing the volume has any effect in Spotify? (when you move the volume slider in the system taskbar)?
By the way, it should be useful if you told us which desktop environment your are using. :)


text:
Q: How to update LiveData of a ViewModel from background service and Update UI Recently I am exploring Android Architecture, that has been introduced recently by google. From the Documentation I have found this:
public class MyViewModel extends ViewModel {
    private MutableLiveData<List<User>> users;
    public LiveData<List<User>> getUsers() {
        if (users == null) {
            users = new MutableLiveData<List<Users>>();
            loadUsers();
        }
        return users;
    }

    private void loadUsers() {
        // do async operation to fetch users
    }
}

the activity can access this list as follows:
public class MyActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
        model.getUsers().observe(this, users -> {
            // update UI
        });
    }
}

My Question is, I am going to do this:

*

*in the loadUsers() function I am fetching the data asynchronously where I will first check the database(Room) for that data

*If I do not get the data there I will make an API call to fetch the data from the web server.

*I will insert the fetched data into the database(Room) and update the UI according the data.
What is the recommended approach to do this?
If I start a Service to call the API from the loadUsers() method, how can I update the MutableLiveData<List<User>> users variable from that Service?

A: You can use MutableLiveData<T>.postValue(T value) method from background thread.
private void loadUsers() {
    // do async operation to fetch users and use postValue() method
   users.postValue(listOfData)
}

A: Take a look at the Android architecture guide that accompanies the new architecture modules like LiveData and ViewModel. They discuss this exact issue in depth.
In their examples they don't put it in a service. Take a look at how they solve it using a "repository" module and Retrofit. The addendums at the bottom include more complete examples including communicating network state, reporting errors, etc.

A: If you are calling your api in Repository then,
In Repository:
public MutableLiveData<LoginResponseModel> checkLogin(LoginRequestModel loginRequestModel) {
    final MutableLiveData<LoginResponseModel> data = new MutableLiveData<>();
    apiService.checkLogin(loginRequestModel)
            .enqueue(new Callback<LoginResponseModel>() {
                @Override
                public void onResponse(@NonNull Call<LoginResponseModel> call, @Nullable Response<LoginResponseModel> response) {
                    if (response != null && response.isSuccessful()) {
                        data.postValue(response.body());
                        Log.i("Response ", response.body().getMessage());
                    }
                }

                @Override
                public void onFailure(@NonNull Call<LoginResponseModel> call, Throwable t) {
                    data.postValue(null);
                }
            });
    return data;
}

In ViewModel
public LiveData<LoginResponseModel> getUser() {
    loginResponseModelMutableLiveData = repository.checkLogin(loginRequestModel);
    return loginResponseModelMutableLiveData;
}

In Activity/Fragment
loginViewModel.getUser().observe(LoginActivity.this, loginResponseModel -> {
        if (loginResponseModel != null) {
            Toast.makeText(LoginActivity.this, loginResponseModel.getUser().getType(), Toast.LENGTH_SHORT).show();
        }
    });

Note : Using JAVA_1.8 lambda here, you can use without it

A:
... in the loadUsers() function I am fetching the data asynchronously ...
  If I start a Service to call the API from the loadUsers() method, how
  can I update the MutableLiveData> users variable from that
  Service?

If the app is fetching user data on a background thread, postValue (rather than setValue) will be useful.
In the loadData method there is a reference to the MutableLiveData "users" object. The loadData method also fetches some fresh user data from somewhere (for example, a repository).
Now, if execution is on a background thread, MutableLiveData.postValue() updates outside observers of the MutableLiveData object.
Maybe something like this:
private MutableLiveData<List<User>> users;

.
.
.

private void loadUsers() {
    // do async operation to fetch users
    ExecutorService service =  Executors.newSingleThreadExecutor();
    service.submit(new Runnable() {
        @Override
        public void run() {
            // on background thread, obtain a fresh list of users
            List<String> freshUserList = aRepositorySomewhere.getUsers();

            // now that you have the fresh user data in freshUserList,
            // make it available to outside observers of the "users"
            // MutableLiveData object
            users.postValue(freshUserList);
        }
    });

}

A: I am assuming that you are using android architecture components. Actually it doesn't matter wherever you are calling service, asynctask or handler to update the data. You can insert the data from the service or from the asynctask using postValue(..) method. Your class would look like this:
private void loadUsers() {
    // do async operation to fetch users and use postValue() method
    users.postValue(listOfData)
}

As the users is LiveData, Room database is responsible for providing users data wherever it is inserted.
Note: In MVVM like architecture, the repository is mostly responsible for checking and pulling local data and remote data.


text:
Q: Mongo error : Could not lock auth data update lock. on root user i have a mongodb on 2.6.9.
my connected user is root:
mongo --username myadmin --password thepassword --port  27018 --host 127.0.0.1 admin
MongoDB shell version: 2.6.9
connecting to: 127.0.0.1:27018/admin
mongos> db.getUsers()
[
{
    "_id" : "admin.myadmin",
    "user" : "myadmin",
    "db" : "admin",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        },
        {
            "role" : "dbAdminAnyDatabase",
            "db" : "admin"
        },
        {
            "role" : "readAnyDatabase",
            "db" : "admin"
        },
        {
            "role" : "clusterAdmin",
            "db" : "admin"
        }
    ]
},

So i am root, but when i want update a user:
mongos> db = db.getSiblingDB('myuser')
myuser
mongos> db.updateUser(  'myuser' ,{ pwd: 'hg76vZa091', roles: ['dbOwner','dbAdmin','readWrite'] } )
2015-10-06T09:00:00.100+0000 Error: Updating user failed: Could not lock auth data update lock. at src/mongo/shell/db.js:1155

So i try to grant userAdmin to myadmin, and it's not working.
mongos> use admin
mongos> db.grantRolesToUser(     "myadmin",     [       { role: "userAdminAnyDatabase", db: "admin" }     ] )
2015-10-06T08:46:40.987+0000 Error: Could not lock auth data update lock. at src/mongo/shell/db.js:1287

Root user cannot grand user ? cannot update user ? How i can do it ?
Maybe i miss some query in my script. I try
use admin

or
    use root
before grant or update user, but it's not working. Any idea?

A: You are actually using root and admin database by your query
'use root' or 'use admin'
use root will not change your user it will just change your database.
So to add user or role .you need to login by root.As you have mentioned in very first line actually you are login as "myadmin " on database "admin"


text:
Q: OpenCV cvFindContours questions I'm following this guide: http://www.aishack.in/2010/08/sudoku-grabber-with-opencv/2/
and modifying to iOS 5.0.
I managed to find the largest contour (the sudoku "board"), however, it only locates the surrounding square, without the lines inside, as in the tutorial. can this be easily solved?
I'll try and find a way around it, but still would like to know. thanks!

A: I assume that you are using the camera right now. Try to load the image what is used in the tutorial and check if your implementation works on that image. Then you can continue with nice sudoku images from the web. You may also change the camera angle and distance from the sudoku when taking pictures to get a better, clearer view.


text:
Q: Unity não atualiza frames ao girar o personagem com o movimento do mouse O meu Unity não esta dando erro, nem nada. Está tudo OK, mas o personagem não se mexe.
Já olhei o código e nada de erro , eu mexo o mouse e não acontece nada com o personagem. A versão do Unity é 4.6 e o código é esse:
public class PlayerMovement : MonoBehaviour
{
   public float speed = 6f;
   Vector3 movement;
   Animator anim;
   Rigidbody playerRigidbody;
   int floorMask;
   float camRayLenght = 100f;

   void Awake(){
      floorMask = LayerMask.GetMask ("Floor");
      anim = GetComponent<Animator> ();
      playerRigidbody = GetComponent<Rigidbody>();
   }

   void FixUpdate(){
      float h = Input.GetAxisRaw ("Horizontal");
      float v = Input.GetAxisRaw ("Vertical");
      Move (h, v);
      Turning ();
      Animating (h, v);
   }

   void Move(float h,float v){
      //tertemina o movimento
      movement.Set(h,0f,v);
      //normaliza o movimento
      movement = movement.normalized * speed * Time.deltaTime;
      // efetua o movimento
      playerRigidbody.MovePosition (transform.position + movement);
   }

   //girar o jogador
   void Turning(){
      Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);
      RaycastHit floorHit;

      if (Physics.Raycast (camRay, out floorHit, camRayLenght, floorMask)) {

          Vector3 playerToMouse=floorHit.point-transform.position;
          playerToMouse.y=0f;
          // rotaçao do personagem
          Quaternion newRotation= Quaternion.LookRotation(playerToMouse);
          playerRigidbody.MoveRotation(newRotation);
      }
   }

   void Animating(float h,float v){
      bool walking = h != 0f || v!=0f;
      anim.SetBool ("IsWalking", walking);
   }
}

A: O erro está em:
void FixUpdate(){
  float h = Input.GetAxisRaw ("Horizontal");
  float v = Input.GetAxisRaw ("Vertical");
  Move (h, v);
  Turning ();
  Animating (h, v);
}

O Unity usa uma função interna chamada FixedUpdate
Tudo que estiver dentro dela será chamado a cada atualização de frame.
Se você usar outro nome, ele vai pensar que é outra função ou método.
Basta trocar o
FixUpdate()

por
 FixedUpdate ()

O código ficará assim:
void FixedUpdate(){
  float h = Input.GetAxisRaw ("Horizontal");
  float v = Input.GetAxisRaw ("Vertical");
  Move (h, v);
  Turning ();
  Animating (h, v);
}

*Não se esqueça de dizer mais detalhes do tutorial que está fazendo para facilitar o pessoal que for tentar tirar tuas dúvidas
Unity training day 2014: Survival Shooter


text:
Q: Is there a way to save RFB (vnc) streams to file? [GStreamer] I am finding a way to connect to VNC and record the video using GStreamer. So far, I can connect to the VNC server but can only view the video using autovideosink. I wanted to save the video to a file.
This is what I tried and is working:
gst-launch-1.0 -e -vvv rfbsrc host=127.0.0.1 width=1024 height=768 shared=true view-only=true ! videoscale ! video/x-raw,width=1024,height=576 ! videorate ! videoconvert ! autovideosink

This is for saving the video file using filesink:
gst-launch-1.0 -e -vvv rfbsrc host=127.0.0.1 width=1024 height=768 shared=true view-only=true ! videoscale ! video/x-raw,width=1024,height=576 ! videorate ! videoconvert ! filesink location=video.flv

Results:
A file is saved with large size and is not playable.
Any inputs will be a big help. Thank you in advance.

A: Finally made it. Made some changes with mov output file:
gst-launch-1.0 -e -vvvv rfbsrc host=127.0.0.1 port=5900 ! videoconvert ! x264enc ! video/x-h264, profile=baseline ! qtmux ! filesink location=output.mov

Posted the answer for future references. Thanks.


text:
Q: How can one connect from Heroku to a firewalled host to get data from MongoDb? I am currently developing a service application that pulls data from Mongo and returns it to consumers.  There is a layer of authentication involved and I am using Heroku to host the service.  Mongo was being hosted on MongoLabs, but there were some significant performance concerns and so we have moved to hosting Mongo on one of our cloud servers.  We want to be able to secure access to Mongo using a firewall, white-listing the ip address of the service app on Heroku.
There are a couple of issues with this.
Issues
Well, at least these are main ones...

*

*Heroku, while providing some nice features like easily managing cluster settings, s/w upgrades, etc., draws ip addresses from a pool.  While the dns value of an application's url may not change, the underlying ip address can and will change.

*to be better secured, mongo-server01 is placed behind a firewall that requires rules to be added using static ip addresses to allow access.

Since Heroku can't provide static ip addresses, we need to consider options for how Heroku can access mongo-server01 while still protecting the data it hosts.
Static IP addresses for outbound requests
There seem to be a couple of options, specifically for Heroku.  Fixie and QuotaGuard Static both seem to serve that function, but these seem to be geared toward HTTP and HTTPS communication only (perhaps not even HTTPS).

Mongo doesn't use HTTP, it uses its own network protocol over port 27017, by default
  https://groups.google.com/forum/embed/#!topic/mongodb-user/eX_RIv2cZVw

Does this mean these proxies won't work for calls to Mongo?  In theory, there doesn't seem to be any reason that a proxy is only for HTTP or HTTPS requests.  That being said, there doesn't seem to be any way to get in to these Heroku plugins and configure the proxy to use a different port or to handle Mongo's particular protocol.
If we could get into the proxy, perhaps we could put an additional set of ssh keys in place so the ssl tunnel chain could continue on to mongo-server01.  But there doesn't see to be any way to ssh to these proxies or access configuration through the plugin dashboards.
The question (finally!)
How can one connect from Heroku to a firewalled host to get data from MongoDb?  Are there proxies that can be used to achieve this?
The simple approach.  Won't work because Heroku applications don't use static ip addresses.

Using a proxy.  The Heroku proxy plugins don't know how to proxy mongodb protocol.  Can't install ssh keys on proxy for ssh tunneling.

What can be done to get a connection without opening up the Mongo server to the world?

A: I spoke with the folks at QuotaGuard and they do have something that does the trick.

we offer a SOCKS proxy which should do the trick as it proxies at the TCP layer

https://devcenter.heroku.com/articles/quotaguardstatic#socks-proxy-setup
I did need to make a simple change to bin/qgsocksify
#SOCKS_DIR="$(dirname $(dirname $(readlink -f ${BASH_SOURCE[0]})))/vendor/dante
SOCKS_DIR="${HOME}/vendor/dante"

After that, the proxy worked like a charm.


text:
Q: How to exclude core-js using useBuiltIns: "usage" Using babel 7.5.5, core-js 3.1.4 and webpack 4.38.0, how can I exclude core-js from transpiling?
I do not want to exclude node_modules altogether since I have libs that need transpiling
If I use exclude: /node_modules\/(core-js)/, a core-js module throws

TypeError: $ is not a function

This leaves me with two other options.

*

*Use includes instead, include my src directory and every dependency that needs transpiling one by one

*Use useBuiltIns: entry instead of usage, since in this case exclude: /node_modules/\(core-js)/ works, and import core.js at the top of main.js

Both of these options don't really seem like good solutions to me since usage is "no longer experimental" since 7.4.
Is there any way to make it work using usage? Is it a bug in either babel-loader or babel? Or is my configuration at fault?
This is my Webpack config:
const path = require('path');
const webpack = require('webpack');

module.exports = {
    mode: 'production',
    entry: {
        main: ['./src/main'],
    },
    output: {
        path: path.resolve(__dirname, './build/'),
        publicPath: '/build/'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules\/(core-js)/,

                use: {
                    loader: 'babel-loader'
                },
            },
            {
                test: require.resolve('jquery'),
                use: [
                    {
                        loader: 'expose-loader',
                        options: 'jQuery'
                    },
                    {
                        loader: 'expose-loader',
                        options: '$'
                    }
                ]
            }
        ]
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        })
    ],
};

This is my babel config:
module.exports = function (api) {
    api.cache(true);

    return {
        presets: [
            [
                '@babel/preset-env',
                {
                    corejs: {
                        version: 3,
                    },
                    useBuiltIns: 'usage',
                }
            ]
        ],
    };
};

You can reproduce the error with the following repository: https://github.com/tomm1996/usebuiltins-exclude-test

A: You need to exclude both core-js and webpack/buildin from the Babel transpilation.
You can use the folling exclude Regexes:
exclude : [
  /\bcore-js\b/,
  /\bwebpack\/buildin\b/
]

Here is also a complete babel-loader configuration with some useful comments:
{
  module : {
    rules : [{
      test : /\.js$/,
      // Some module should not be transpiled by Babel
      // See https://github.com/zloirock/core-js/issues/743#issuecomment-572074215
      exclude : [
        /\bcore-js\b/,
        /\bwebpack\/buildin\b/
      ],
      loader : "babel-loader",
      options : {
        babelrc : false,
        // Fixes "TypeError: __webpack_require__(...) is not a function"
        // https://github.com/webpack/webpack/issues/9379#issuecomment-509628205
        // https://babeljs.io/docs/en/options#sourcetype
        sourceType : "unambiguous",
        presets : [
          ["@babel/preset-env", {
            // Webpack supports ES Modules out of the box and therefore doesn't require
            // import/export to be transpiled resulting in smaller builds, and better tree
            // shaking. See https://webpack.js.org/guides/tree-shaking/#conclusion
            modules : false,
            // Adds specific imports for polyfills when they are used in each file.
            // Take advantage of the fact that a bundler will load the polyfill only once.
            useBuiltIns : "usage",
            corejs : {
              version : "3",
              proposals : true
            }
          }]
        ]
      }
    }
  }
}

See https://github.com/zloirock/core-js/issues/743#issuecomment-572074215

Edit: Also if you try to use @babel/plugin-transform-runtime:
plugins : [
  // Require the Babel runtime as a separate module to avoid the duplication
  // https://webpack.js.org/loaders/babel-loader/#babel-is-injecting-helpers-into-each-file-and-bloating-my-code
  ["@babel/plugin-transform-runtime", {
    // Requires @babel/runtime-corejs3
    // https://babeljs.io/blog/2019/03/19/7.4.0#migration-from-core-js-2
    corejs : { version: 3, proposals: true }
  }],
}

You may run into a similar error:
Uncaught TypeError: _typeof2 is not a function
    at _typeof (typeof.js:8)
    at eval (sockjs.js:123)
    at Object.eval (sockjs.js:131)
    at eval (sockjs.js:6565)
    at Object../node_modules/sockjs-client/dist/sockjs.js (main.js:13790)
    at __webpack_require__ (main.js:70)
    at eval (webpack://PUBLIC_ENGINE/(:8000/webpack)-dev-server/client/clients/SockJSClient.js?:110:14)
    at Object../node_modules/webpack-dev-server/client/clients/SockJSClient.js (main.js:13874)
    at __webpack_require__ (main.js:70)
    at eval (webpack://PUBLIC_ENGINE/(:8000/webpack)-dev-server/client/socket.js?:56:41)

This can be solved by excluding @babel/runtime-corejs3 from the transpilation:
exclude : [
  /\bcore-js\b/,
  /\bwebpack\/buildin\b/,
  /@babel\/runtime-corejs3/
]


text:
Q: PHP + JS validation not working I have written a talent contact form where I have used both jQuery validation as well as custom PHP validation for form fields.
Both were tested working ok on all browsers [ not below ie 8] during development phase.
It is now live.
From the usages log we find in very few cases  the validation is not working properly and probably on the following particular field. Some users were able to submit the form without choosing that particular field.
Can you point out/ suggest where is the problem? I'm trying to contact users who somehow bypassed the validation and know what's happening on their device and also their browser version. Also they seem nontechnical and genuine users. So attempt of hacking through form inputs is not likely the case.
Thanks to all for your time and effort
The bypassed input field
<div class="BNF_input_row">
    <label for="BNF_select_talent" class="BNF_input_label">
        Select Your Talent (required)
    </label>
    <select multiple="true" tabindex="106" class="input" id="BNF_select_talent" value="" name="BNF_select_talent[]" onclick="addTalentScdriptOption()" onblur="addTalentScdriptOption()" >
        <?php  echo BNF_Booking::getTalentList(); ?>
    </select>
</div>

js validation code
var vlidation_option ={
   rules: {
     BNF_your_name: {
       required: true,
       minlength: 2
     },
     BNF_your_comp: {
       required: true,
       minlength: 3
     },
     BNF_your_email: {
       required: true,
       email: true
     },
     BNF_your_phone: {
       required: true,
     },
     'BNF_select_talent[]': {
       required: true,
     },
     BNF_choose_format: {
       required: true,
     },
     BNF_master_script: {
       extension: "doc|docx"
     },

   },
   messages: {
     BNF_your_name: {
       required: "Required",
       minlength: jQuery.format("At least {0} characters required!")
     },
     BNF_your_comp: {
       required: "Required",
       minlength: jQuery.format("At least {0} characters required!")
     },
     BNF_your_email: {
       required: "Required",
       email: jQuery.format("that email is not valid!")
     },
     BNF_your_phone: {
       required: "Required",
               phoneUS: "Not valid phone number"
     },
     'BNF_select_talent[]': {
       required: "Required",
     },
     BNF_choose_format: {
       required: "Required",
     },
     BNF_master_script: {
               extension: "only .doc and .docx files are accepted"
     },
   },

};
jQuery("#BNF_booking_form").validate(vlidation_option);

PHP validation
public static function verifyData($data){
    $response = array();
    $response['status'] = "";
    $iserror = false;
    if(!isset($data['name']) || trim($data['name']) == ''){
        $response['status'] .= "Enter your name\n";
        $iserror = TRUE;
    }
    if(!isset($data['comp']) || trim($data['comp']) == ''){
        $response['status'] .= "Enter your company\n";
        $iserror = TRUE;
    }
    if(!isset($data['email']) || trim($data['comp']) == ''){
        $response['status'] .= "Enter your email\n";
        $iserror = TRUE;
    }
    if(!isset($data['phone']) || trim($data['comp']) == ''){
        $response['status'] .= "Enter your phone\n";
        $iserror = TRUE;
    }
    if(!isset($data['talent']) || trim($data['comp']) == ''){
        $response['status'] .= "Select talent(s) for the job\n";
        $iserror = TRUE;
    }
    if(!isset($data['script']) || trim($data['comp']) == ''){
        $response['status'] .= "Attach scripts for talents\n";
        $iserror = TRUE;
    }
    if(!$iserror){
        $response['status'] = "YES";
    }
    return $response;
}

A: Just debug it.
Use Firefox console + Firebug. In Javascript write out your variables with
console.log("Testing var1: " + var1);

And you will see it in the console log.
PS: Also, I am not sure, but check the validation options. Are you really really sure you need the squared brackets after BNF_select_talent in there?
'BNF_select_talent[]': { <===
   required: true,
 },
'BNF_select_talent[]': { <===
   required: "Required",
 },

A: For PHP, looks like you need to trim and validate talent instead of comp, try this:
Replace this,
if(!isset($data['email']) || trim($data['comp']) == ''){
    $response['status'] .= "Enter your email\n";
    $iserror = TRUE;
}
if(!isset($data['phone']) || trim($data['comp']) == ''){
    $response['status'] .= "Enter your phone\n";
    $iserror = TRUE;
}
if(!isset($data['talent']) || trim($data['comp']) == ''){
    $response['status'] .= "Select talent(s) for the job\n";
    $iserror = TRUE;
}
if(!isset($data['script']) || trim($data['comp']) == ''){
    $response['status'] .= "Attach scripts for talents\n";
    $iserror = TRUE;
}

With,
if(!isset($data['email']) || trim($data['email']) == ''){
    $response['status'] .= "Enter your email\n";
    $iserror = TRUE;
}
if(!isset($data['phone']) || trim($data['phone']) == ''){
    $response['status'] .= "Enter your phone\n";
    $iserror = TRUE;
}
if(!isset($data['talent']) || trim($data['talent']) == ''){
    $response['status'] .= "Select talent(s) for the job\n";
    $iserror = TRUE;
}
if(!isset($data['script']) || trim($data['script']) == ''){
    $response['status'] .= "Attach scripts for talents\n";
    $iserror = TRUE;
}

For JS, try this:
$.validator.addMethod("talentRequired", function (value, element) {
    var count = $(element).find('option:selected').length;
    return count > 0;
});

And replace,
'BNF_select_talent[]': {
    required: true,
},

With,
'BNF_select_talent[]': "required talentRequired",


text:
Q: Building a list from user input throughout different functions I started the how to learn python the hard way recently. I'm on exercise 36, where we design our own text adventure game. I was hoping to have the user go through different rooms collecting items to later be used on the boss in the last room. But I can't figure our how to keep adding to the same list when I change rooms. This is what i have so far for that part (I cut out description text)...
def add_item():
    backpack = []
    i = 0
    while 1:
        i += 1
        item = raw_input(" > ")
        if item == '':
            break
        backpack.append(item)

        print "\nAh, the %s, let us hope this serves you well." % item
        print "This is the inventory you have acquired so far..."
        print backpack

def dizzygas_hallway():
    print "If so which item do you choose? (cloak or pendant)"
    add_item()

def dark_laboratory():
    print "Which item do you take? (book, potion or sword)\n"
    add_item()
    print "You exit the only door in sight..."
dizzygas_hallway()

A: I think you're close, just swap some lines around. Otherwise every time you wanted to add an item, you create an new, empty list.
backpack = []  # Define outside of function

def add_item():
    global backpack  # Use global variable (this line isn't 'necessary', though)


text:
Q: React-Native doesn't extract strings from associative array in map I cannot put strings from the associative array to another associative array. This is very weird phenomenon. This is the code and result
[Code]
    p.phone_score_list.map(par => {
      console.log(`par`, par);
      console.log(typeof par.ipa);

      phoneScoreList.push({
        ipa: par.ipa,
        // ipa: par.phone,
        phone: par.phone,
        pronuncedIpa: par.pronuncedIpa,
        qualityScore: par.quality_score,
        soundMostLike: par.sound_most_like,
      });
    });
    console.log(`phoneScoreList`, phoneScoreList)

The result is below.
"ipa" and "pronuncedIpa" are "n" in the par parameter but after inputting the ipa into another associative array like the above code, it's gonna be undefined. Do you know the reason and how to handle it?

This is phone_score_list.

A: It's possible that you're assigning references to an object that has since been dropped from memory. I would try to create a new object like so
const newObject = { ...par };
phoneScoreList.push(newObject);