text:
Q: Should we validate method arguments in JavaScript API's? I'm developing a JavaScript library that will be used by 3rd party developers.
The API includes methods with this signature:
function doSomething(arg1, arg2, options)

*

*arg1, arg2 are 'required' simple type arguments.

*options is a hash object containing optional arguments.

Would you recommend to validate that:
- argument types are valid?
- options attributes are correct? For example: that the developer didn't pass by mistake onSucces instead of onSuccess?

*

*why do popular libraries like prototype.js do not validate?

A: Validate as much as you can and print useful error messages which help people to track down problems quickly and easily.
Quote this validation code with some special comments (like //+++VALIDATE and //--VALIDATE) so you can easily remove it with a tool for a high-speed, compressed production version.

A: Thanks for the detailed answers.
Below is my solution - a utility object for validations that can easily be extended to validate basically anything...
The code is still short enough so that I dont need to parse it out in production.
WL.Validators = {

/*
 * Validates each argument in the array with the matching validator.
 * @Param array - a JavaScript array.
 * @Param validators - an array of validators - a validator can be a function or
 *                     a simple JavaScript type (string).
 */
validateArray : function (array, validators){
    if (! WL.Utils.isDevelopmentMode()){
        return;
    }
    for (var i = 0; i < array.length; ++i ){
        WL.Validators.validateArgument(array[i], validators[i]);
    }
},

/*
 * Validates a single argument.
 * @Param arg - an argument of any type.
 * @Param validator - a function or a simple JavaScript type (string).
 */
validateArgument : function (arg, validator){
    switch (typeof validator){
        // Case validation function.
        case 'function':
            validator.call(this, arg);
            break;
        // Case direct type.
        case 'string':
            if (typeof arg !== validator){
                throw new Error("Invalid argument '" + Object.toJSON(arg) + "' expected type " + validator);
            }
            break;
    }
},

/*
 * Validates that each option attribute in the given options has a valid name and type.
 * @Param options - the options to validate.
 * @Param validOptions - the valid options hash with their validators:
 * validOptions = {
 *     onSuccess : 'function',
 *     timeout : function(value){...}
 * }
 */
validateOptions : function (validOptions, options){
    if (! WL.Utils.isDevelopmentMode() || typeof options === 'undefined'){
        return;
    }
    for (var att in options){
        if (! validOptions[att]){
            throw new Error("Invalid options attribute '" + att + "', valid attributes: " + Object.toJSON(validOptions));
        }
        try {
            WL.Validators.validateArgument(options[att], validOptions[att]);
        }
        catch (e){
            throw new Error("Invalid options attribute '" + att + "'");
        }
    }
},

};
Heres a few examples of how I use it:
isUserAuthenticated : function(realm) {
WL.Validators.validateArgument(realm, 'string');

getLocation: function(options) {
    WL.Validators.validateOptions{
        onSuccess: 'function',
        onFailure: 'function'}, options);

makeRequest : function(url, options) {
    WL.Validators.validateArray(arguments, ['string',
        WL.Validators.validateOptions.carry({
        onSuccess : 'function',
        onFailure : 'function',
        timeout   : 'number'})]);

A: We have to discover and eliminate problems as soon as possible. If don't use TypeScript or Flow, you rather do it with a validation lib. It will help you avoiding spending hours hunting obscure errors caused by invalid types given as arguments. It looks like many take it serious - https://www.npmjs.com/package/aproba gets currently 9M(!) downloads per week.
To me it doesn't suite, explained here http://dsheiko.com/weblog/validating-arguments-in-javascript-like-a-boss
I go with https://www.npmjs.com/package/bycontract that based on JSDoc expressions:
import { validate } from "bycontract";

const PdfOptionsType = {
  scale: "?number"
}

function pdf( path, w, h, options, callback ) {
  validate( arguments, [
    "string",
    "!number",
    "!number",
    PdfOptionsType,
    "function=" ] );
  //...
  return validate( returnValue, "Promise" );
}

pdf( "/tmp/test.pdf", 1, 1, { scale: 1 } ); // ok
pdf( "/tmp/test.pdf", "1", 1, { scale: 1 } ); // ByContractError: Argument #1: expected non-nullable but got string

On methods you can just reuse existing JSDoc comment block:
import { validateJsdoc, typedef } from "bycontract";

typedef("#PdfOptionsType", {
  scale: "number"
});

class Page {
  @validateJsdoc(`
    @param {string}          path
    @param {!number}         w
    @param {!number}         h
    @param {#PdfOptionsType} options
    @param {function=}       callback
    @returns {Promise}
  `)
  pdf( path, w, h, options, callback ) {
    return Promise.resolve();
  }
}

However I keep this validation on dev/test environments, but skip it on live:
import { config } from "bycontract";
if ( process.env.NODE_ENV === "production" ) {
  config({ enable: false });
}

A: You have the right to decide whether to make a "defensive" vs. a "contractual" API.  In many cases, reading the manual of a library can make it clear to it's user that he should provide arguments of this or that type that obey these and those constraints.
If you intend to make a very intuitive, user friendly, API, it would be nice to validate your arguments, at least in debug mode.  However, validation costs time (and source code => space), so it may also be nice to leave it out.
It's up to you.

A: It depends. How big this library would be? It is said that typed languages are better for big projects with complex API. Since JS is to some extent hybrid, you can choose.
About validation - I don't like defensive programming, the user of the function shall be obliged to pass valid arguments. And in JS size of code matters.

A: When I've developed APIs like these in the past, I've validated anything that I feel is a "major" requirement - in your example, I'd verify the first two arguments.
As long as you specify sensible defaults, it should be pretty simple for your user to determine that "optional" arguments aren't specified correctly, since it won't make any change to the application, but everything will still work properly.
If the API is complex, I'd suggest following Aaron's advice - add comments that can be parsed by a compressor around your validation so the developers get the benefit of validation, but can extract the extra dead weight when pushing the code into production.
EDIT:
Here're some examples of what I like to do in the cases where validation is necessary. This particular case is pretty simple; I probably wouldn't bother with validation for it, since it really is trivial. Depending on your needs, sometimes attempting to force types would be better than validation, as demonstrated with the integer value.
Assume extend() is a function that merges objects, and the helper functions exist:
    var f = function(args){
      args = extend({
        foo: 1,
        bar: function(){},
        biz: 'hello'
      }, args || {});

      // ensure foo is an int.
      args.foo = parseInt(args.foo);

      //<validation>
      if(!isNumeric(args.foo) || args.foo > 10 || args.foo < 0){
        throw new Error('foo must be a number between 0 and 10');
      }

      if(!isFunction(args.bar)){
        throw new Error('bar must be a valid function');
      }

      if(!isString(args.biz) || args.biz.length == 0){
        throw new Error('biz must be a string, and cannot be empty');
      }
      //</validation>
    };

EDIT 2:
If you want to avoid common misspellings, you can either 1) accept and re-assign them or 2) validate the argument count. Option 1 is easy, option 2 could be done like this, although I'd definitely refactor it into its own method, something like Object.extendStrict() (example code works w/ prototype):
var args = {
  ar: ''
};
var base = {
  foo: 1,
  bar: function(){},
  biz: 'hello'
};
// save the original length
var length = Object.keys(base).length;
// extend
args = Object.extend(base, args || {});
// detect if there're any extras
if(Object.keys(args).length != length){
  throw new Error('Invalid argument specified. Please check the options.')
}

A: An intermediate way would be to return a reasonable default value (e.g. null) when required arguments are missing. In this way, the user's code will fail, not yours. And it will probably be easier for them to figure out what is the issue in their code rather than in yours.

A: Don't validate. More code is more code the user has to download, so it's a very real cost on the user and production systems. Argument errors are easy enough to catch by the developer; don't burden the user with such.


text:
Q: getPersistedString has protected access i just changed my code from

DialogPreference

to

PreferenceDialogFragmentCompat

but i got an error here
getPreference().getPersistedString("wwww");

the error said

getPersistedString(java.lang.String)' has protected access in
  'android.support.v7.preference.Preference

so what is the alternative for getPersistedString in v7 preference

A: I'm not an Android developer, but by looking at the source, you can use
public Set<String> getPersistedStringSet(Set<String> defaultReturnValue);

this way
final Set<String> values = getPreference().getPersistedStringSet(defaultValues);

Than you could loop the Set and find the appropriate value.

A: You can use
Preference preference = getPreference();
String persistedString = preference.getSharedPreferences().
                           getString(preference.getKey(), "defaultString");

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create mask by first positions only I have array:
a = np.array([[ 0,  1,  2,  0,  0,  0],
              [ 0,  4,  1, 35,  0, 10],
              [ 0,  0,  5,  4,  0,  4],
              [ 1,  2,  5,  4,  0,  4]])

I need select only from first consecutive 0 in each row:
[[  True   False  False  False  False  False]
 [  True   False  False  False  False  False]
 [  True   True   False  False  False  False]
 [  False  False  False  False  False  False]]

I try:
a[np.arange(len(a)), a.argmax(1): np.arange(len(a)), [0,0,0]] = True

But this is wrong.

A: You can use np.cumsum.
Assumption: you are looking for zeros only at the start of each row.
a = np.array([[ 0,  1,  2,  0,  0,  0],
              [ 0,  4,  1, 35,  0, 10],
              [ 0,  0,  5,  4,  0,  4]])

a.cumsum(axis=1) == 0
array([[ True, False, False, False, False, False],
       [ True, False, False, False, False, False],
       [ True,  True, False, False, False, False]], dtype=bool)

Basis: holds True for as long as the cumulative sum is 0 along each row.
Error-prone: an array with negative ints would cause this to fail.  I.e. for [-1, 1], this would evaluate to True at position 1.

A: You might use np.minimum.accumulate with the condition testing a == 0(over the rows); Since non zero gives False, so elements come after the first non zero will be set to False due to the accumulated minimum:
np.minimum.accumulate(a == 0, axis=1)
#array([[ True, False, False, False, False, False],
#       [ True, False, False, False, False, False],
#       [ True,  True, False, False, False, False],
#       [False, False, False, False, False, False]], dtype=bool)

A: Here's one with argmin + broadcasting -
(a==0).argmin(1)[:,None] > np.arange(a.shape[1])

Explanation with a sample step-by-step run
1) Input array :
In [207]: a
Out[207]:
array([[ 0,  1,  2,  0,  0,  0],
       [ 0,  4,  1, 35,  0, 10],
       [ 0,  0,  5,  4,  0,  4],
       [ 1,  2,  5,  4,  0,  4]])

2) Mask of zeros
In [208]: (a==0)
Out[208]:
array([[ True, False, False,  True,  True,  True],
       [ True, False, False, False,  True, False],
       [ True,  True, False, False,  True, False],
       [False, False, False, False,  True, False]], dtype=bool)

3) Get the indices where the False occurs signalling the end of first True island for each row. Thus, for any row where there is no zero or if the first element is  non-zero would result in argmin output as 0. Thus, our next task would be to use broadcasting to create a mask that starts as True from first row and stops being True at those argmin indices. This would be one with broadcasted-comparison against a range array extending covering all columns.
In [209]: (a==0).argmin(1)
Out[209]: array([1, 1, 2, 0])

In [210]: (a==0).argmin(1)[:,None] > np.arange(a.shape[1])
Out[210]:
array([[ True, False, False, False, False, False],
       [ True, False, False, False, False, False],
       [ True,  True, False, False, False, False],
       [False, False, False, False, False, False]], dtype=bool)

Timings
In [196]: a = np.random.randint(0,9,(5000,5000))

In [197]: %timeit a.cumsum(axis=1) == 0 #@Brad Solomon
     ...: %timeit np.minimum.accumulate(a == 0, axis=1) #@Psidom
     ...: %timeit (a==0).argmin(1)[:,None] > np.arange(a.shape[1])
     ...:
10 loops, best of 3: 69 ms per loop
10 loops, best of 3: 64.9 ms per loop
10 loops, best of 3: 32.8 ms per loop


text:
Q: Union of an uncountable number of $\sigma$-algebras Let $\mathcal{A}$ be an uncountable index set (such as $\mathbb{R}$).
Let $\{A_\alpha:\alpha \in \mathcal{A}\}$ be a collection of subsets of some space $S$. Define
$$\mathcal{F}=\bigcup \sigma(\mathcal{A}_{\alpha i}:i=1,2,3,...) $$
in which the union is taken over all countable sequences $\{\alpha_1,\alpha_2,...\}\subset \mathcal{A}$. (Note this union is an uncountable union)
Show that $\mathcal{F}$ is a $\sigma$-algebra.
I know this is a well known result. However I do not know how to prove it. I found this. I know how prove it for non-decreasing sequences, but that is not the case here.
I'd appreciate any help.
Thanks


text:
Q: Angular4 background image I am trying to make a background image to div. but image not showing. here is my code.
<div [ngStyle]="{'background-image' : imageresult.pictureUrl}"> some content here! </div>

A: try this and be sure that you have added your assets in angular-cli.json
[ngStyle]="{'background-image': 'url(' + imageresult.pictureUrl+ ')'}"


text:
Q: Mongoose remove _id and __v before sending to the front end When I get data from mongo via mongoose with...
      const allAssets = await assets
        .find({ company })
        .sort([['createdAt', -1]])
        .exec();
      res.status(200).json({ assets: allAssets });

I always get _id and __v  but I dont want to send these to the front end, is there a way I can easly say I dont want these values or remove them before sending them?
    {
      "indistructable": true,
      "_id": "5e345c2dc84be8995a5b4cf2",
      "baseUri": "https://api.website.com/nameco8/",
      "company": "jnameco8",
      "description": "asset",
      "image": "myimage.png",
      "name": "jim",
      "supply": 100,
      "createdAt": "2020-01-31T16:56:13.816Z",
      "updatedAt": "2020-01-31T16:56:13.816Z",
      "__v": 0
    },

I have tried adding
    __v: {type: Number, select: false},
    _id: { type: mongoose.Schema.Types.ObjectId, select: false },

to my schema but when saving to the schema I then get an error
"document must have an _id before saving"

A: As far as I believe schemas are for writes to restrict unknown fields from being written to documents which make your documents look similar across your collection, but if you need to remove few fields in read then try projection in .find() :
const allAssets = await assets
        .find({ company }, {_id :0, __v:0})
        .sort([['createdAt', -1]])
        .exec();
      res.status(200).json({ assets: allAssets });

A:  Schema.find()
      .select("-_id -__v")
      .exec()
      .then(result =>{
      console.log(result);
      })

In addition to @whoami - fakeFaceTrueSoul's answer, you can also add multiple <" -fieldName "> to your select statement in find()


text:
Q: Instalador com autoscoll Bom dia.
Estou criando um atualizador e preciso que fazer com que a cada $rs executado o scroll vá para baixo.
O que acontece atualmente?
Fica uma tela branca, mas executando, e quando acaba mostra tudo de uma vez.
O que gostaria:
Que foce executado cada $rs, mostrando seu echo e o scoll descendo automaticamente quando houver muitas linhas.
Meu código atual

 Aguarde, atualizando banco de dados, não feche

<?php
include("../conexao/conexao.php");

    $rs1 = $mysqli->query("UPDATE ...;");
    if (!$rs1) {echo " - Versão do site
";}else {echo " - Versão do site. Sucesso!
";}
    sleep(2);

    $rs2 = $mysqli->query("INSERT .... ;");
    if (!$rs2) {echo " - Insert erro
";}else {echo " - Insert sucesso!
";}
    sleep(2);

    .
    .
    .

    unlink("updateSQL_v423.php");
?>

 Pronto! Banco de dados atualizado. APERTE F5, para recarregar a tela.

A: Você pode fazer um backend em php ter esse retorno,  já que o PHP retorna só quando está tudo pronto..
Segue a sugestão:

var retorno = $('.retorno')
$('[botao]').on('click', function(){
     const aguarde = $('
Aguarde enquanto processamos seu pedido ...
')
     retorno.append( aguarde )
     setTimeout(()=>{
        update()
     },500)

})

function update(){
     const update = $('
- Versão do site
')
     retorno.append( update )
     setTimeout(()=>{
       insert()
     }, 1500)

}

function insert(){
     const update = $('
- Insert erro
')
     retorno.append( update )
     setTimeout(()=>{
       done()
     }, 1500)

}

function done(){
     const update = $('
 Pronto! Banco de dados atualizado. APERTE F5, para recarregar a tela
')
     retorno.append( update )
}

  <button botao>Clique</button>

Funções javascript:
No caso função update seria assim:
function update(){
   $.ajax({
      url: 'seuArquivo.php',
      type: 'post',
      dataType: 'json',
      data: {
        id: 1,
        nome: 'Sei la',
        opcao: 'update'
      }
   }).done( result => {
       const update = $('
'+ result.msg +'
')
       retorno.append( update )
       inserir()
   })
}

function inserir(){
   $.ajax({
      url: 'seuArquivo.php',
      type: 'post',
      dataType: 'json',
      data: {
        nome: 'Dado a inserir',
        opcao: 'inserir'
      }
   }).done( result => {
       const insert = $('
'+ result.version +'
')
       retorno.append( insert )

       const done = $('
 Pronto! Banco de dados atualizado. APERTE F5, para recarregar a tela
')
        retorno.append( done )
   })
}

No php seuArqui.php
$_opcao = $_POST['opcao']

switch($_opcao){
  case 'update':
      //Faça suas operações e retorne com echo json_encode
      $version = array('version' => '- Versão do site')
      echo json_encode( $version )
  break;
  case 'inserir':
     //Faça suas operações e retorne com echo json_encode
      $version = array('version' => 'Inserir result')
      echo json_encode( $version );
   break;
}

Então, essa é a sugestão.


text:
Q: Laravel testing database migration fails due to Passport I installed Laravel Passport and migrated the new tables just fine in my database. But when I try to run migrations for the testing database, ie. artisan migrate --database=testing I get:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'oauth_auth_codes' already exists

The only table that exists in the testing database is the migrations table. It looks as if it's checking the regular database and seeing this Passport table instead of checking the testing database. Did I miss something simple here?

A: php artisan ... commands will use your .env variables for configuration, so yes, unless you specified which database connection to use, it will use your default .env's DB_ variables.
You can define something like a .env.testing, then re-run as php artisan migrate --env=testing to use that file instead of your default one.
.env:
DB_CONNECTION=mysql
DB_DATABASE=database
...
# Host, Port, Username, Password,

.env.testing:
DB_CONNECTION=mysql
DB_DATABASE=testing
...
# Host, Port, Username, Password,


text:
Q: Correlation between multiple azure app insight telemetries We know that we can correlate the operations within an Azure App Insight resource using the operation Id and parent operation Id.
We have multiple app services, function apps running in Azure and we would like to track an operation that is triggered from one app service and ended in another app service. I don't think would be possible by default in Azure as the Azure backend wouldn't know about this.
I hope we can add custom props to the telemetry and track this across all app insights.
Is there a way to do this or has anyone somehow achieved this?
For example, I want to track a login from my angular app to an API then to a Token validation system(another API), and then back to the angular app. My expected output,
| timestamp | operationId | parent operationId | name | itemType | app insight name |


text:
Q: How can I do this in Jade? I'm trying to translate this in my jade template but can't. Any help?

   ricicla

      .me

   &nbsp&nbsp è un'idea di OttoQuattro Web & Video Agency

Thanks!!

A: Something like this...
span.riciclame_piccolo ricicla
    span.rosa .me
span.footer_p &nbsp&nbsp è un'idea di
    a(href="http://www.ottoquattro.com", target="_blank") OttoQuattro Web & Video Agency


text:
Q: In my code javascript is not working properly with asp.net? I have used a asp datalist with feedback form for news website but javascript is not working correctly and the mouse hover and onclick functions are not working so this is the code--
<%@ Page Title="" Language="C#" MasterPageFile="~/admin.master" enableEventValidation="false" AutoEventWireup="true" CodeFile="Dtalist.aspx.cs" Inherits="Dtalist" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

      <asp:HiddenField ID="hdnfldVariable" runat="server" />
        <asp:DataList ID="DataList1" runat="server" BackColor="White" BorderColor="#666666" BorderWidth="4px" Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" GridLines="Vertical" RepeatColumns="3" RepeatDirection="Horizontal" OnItemCommand="DataList1_ItemCommand" OnItemDataBound="DataList1_ItemDataBound" >
            <FooterStyle BackColor="#8C4510" Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" ForeColor="#F7DFB5" />
            <HeaderStyle BackColor="#333333" Font-Bold="True" Font-Italic="False" Font-Overline="False" Font-Size="XX-Large" Font-Strikeout="False" Font-Underline="False" ForeColor="White" HorizontalAlign="Center" VerticalAlign="Middle" />
            <HeaderTemplate>
                Latest News
            </HeaderTemplate>
            <ItemTemplate>

                            <asp:Label ID="Label1" runat="server" BackColor="Silver" BorderColor="#FF9900" Font-Bold="True" Font-Size="Large" Font-Underline="True" Text='<%# Eval("news") %>'></asp:Label>
                            <asp:Label ID="Label3" runat="server" Text='<%# Eval("nid") %>' Visible="False"></asp:Label>

                            <asp:Image ID="Image1" runat="server"  ImageUrl='<%# Eval("photo","~/img/{0}") %>' Width="200px" Height="500px"/>

                            <asp:Label ID="Label2" runat="server" BackColor="#CCCCCC" Font-Size="Medium" Text='<%# Eval("description") %>'></asp:Label>

                            <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" >Please login first!</asp:TextBox>

                            <asp:Button ID="Button1" runat="server" BackColor="#7AC1FF" Enabled="False" ForeColor="#333333" Text="COMMENT" CommandName="Comment" />

    <asp:Button BorderStyle="None" ID="Rating1" onmouseover="return Decide(1);" OnClientClick="return Decide(1);"
        Height="20px" Width="20px" CssClass="Empty" runat="server" />
    <asp:Button BorderStyle="None" ID="Rating2" onmouseover="return Decide(2);" OnClientClick="return Decide(2);"
        Height="20px" Width="20px" CssClass="Empty" runat="server" />
    <asp:Button BorderStyle="None" ID="Rating3" onmouseover="return Decide(3);" OnClientClick="return Decide(3);"
        Height="20px" Width="20px" CssClass="Empty" runat="server" />
    <asp:Button BorderStyle="None" ID="Rating4" onmouseover="return Decide(4);" OnClientClick="return Decide(4);"
        Height="20px" Width="20px" CssClass="Empty" runat="server" />
    <asp:Button BorderStyle="None" ID="Rating5" onmouseover="return Decide(5);" OnClientClick="return Decide(5);"
        Height="20px" Width="20px" CssClass="Empty" runat="server" />

    <asp:Label ID="lblRate" runat="server" Text=""></asp:Label>

                            <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button" />

            </ItemTemplate>
        </asp:DataList>

</asp:Content>

With backend as--
 protected void Button2_Click(object sender, EventArgs e)
    {
        string variable = hdnfldVariable.Value;
        Response.Write("");
}

I think there is a problem with referencing the datalist items...

A: Your javascript is trying to reference the controls by the ids such as "lblRate" and "Rating1" etc.
The problem is that these controls are Runat="Server" and even more, it is within a Asp DataList. Once rendered onto the client's screen, the controls will be given unique ID's, something on the lines of DataList1_ctl00_lblRate. To see what it render's out as, just view the html page source from your browser after the page is rendered.
getElementById needs to specify the correct ID from the result html, and not what you put on the ID field in the control. It is why asp controls have a property called ClientID to help you get the id that will actually be rendered on the html.
Assuming that you would like your javascript to work with how ever many elements in the DataList, you should change it to be relative to the button clicked and have other forms of identifying the control you want to target.
An example would be to include the use of jQuery, and use css classes to navigate the rendered list relative to the button clicked
first add a class to the row so that you can find it

Then add a class to the elements you want to identify and remember that the triggering element should pass in itself so that the javascript can have a reference point to start
<asp:Button  ID="Rating1" OnClientClick="return Decide(this, 1);" CssClass="Empty jq-rating-1-button" runat="server" />

then the js can be modified to something similar to the below (I've only included enough code to demonstrate the idea):
function Decide(button, option) {
    var temp = "";
    // get the closest parent with the css class of '.jq-data-list-row'
    var $row = $(button).closest('.jq-data-list-row');
    // find a child of the row with the css class of '.jq-rating-1-button'
    var $Rating1 = $row.find('.jq-rating-1-button');

    if (option == 1) {
        $Rating1.addClass("Filled");
        .
        .
        .
    }

    return false;
}


text:
Q: Way to horizontally align text in different footnotes Is there any way to align text in footnotes without adding \hspace{} and guessing the spacing?
What I have:

What I would like to have:

MWE
\documentclass{scrreprt}
\usepackage{siunitx} %for SI units
\usepackage{wasysym} %for diameter symbol

\begin{document}
    Some text\footnote{PTFE tube: $\diameter_{\text{inner}}=\SI{0.5}{\milli\meter}$, $\diameter_{\text{outer}}=1/16^{\prime\prime}$} and some other text\footnote{Silicone tube: $\diameter_{\text{inner}}=\SI{1}{\milli\meter}$, $\diameter_{\text{outer}}=\SI{3}{\milli\meter}$}.
\end{document}

A: You could use the eqparbox package:
\documentclass{scrreprt}
\usepackage{siunitx} %for SI units
\usepackage{wasysym} %for diameter symbol
\usepackage{eqparbox}
\begin{document}
    Some text\footnote{%
    \eqmakebox [A][l]{PTFE tube:}
    \eqmakebox [B][l]{$\diameter_{\text{inner}}=\SI{0.5}{\milli\meter}$,} $\diameter_{\text{outer}}=1/16^{\prime\prime}$}
    and some other text\footnote{%
    \eqmakebox [A][l]{Silicone tube:}
    \eqmakebox [B][l]{$\diameter_{\text{inner}}=\SI{1}{\milli\meter}$,} $\diameter_{\text{outer}}=\SI{3}{\milli\meter}$}.
\end{document}


text:
Q: Angular - bootstrap modal inside ng-repeat - how to update data on the main scope? I am using ng repeat to display a table, the table contains an 'edit' button that opens a modal. Once the data is updated in the modal I dont know how to get the modal scope data back to the main scope data used to generate the table.
Basically I want to be able to use the data from the modal to update the main ng-repeat table.
Example Fiddle
here is the function executed when closing the modal:
$scope.customer = customer;

   $scope.ok = function (customer) {

      $modalInstance.close($scope.customer);
                    };

});

In my example, you can see that the "customer.details" are not updated when updated in the modal.
Thanks in advance for your help.

A: If you use ng-model instead of ng-modal it works.
i edited your fiddle


text:
Q: How to set a Greenplum datasource in IBM Liberty Server I have an IBM WebSphere Liberty server and a Greenplum Database. I want liberty server to connect Greenplum with SSL.
Here is my setting in server.xml:
<dataSource id="GreenplumDataSource" jndiName="jdbc/greenplum" type="javax.sql.DataSource">
    <jdbcDriver libraryRef="GreenplumLib" javax.sql.DataSource="com.pivotal.jdbcx.GreenplumDataSource"/>
    <properties databaseName="postgres" serverName="10.x.x.1" portNumber="5432" user="x" password="x" URL="jdbc:pivotal:greenplum://10.x.x.1:5432;DatabaseName=postgres;EncryptionMethod=SSL;CryptoProtocolVersion=TLSv1.2;ValidateServerCertificate=false"/>
</dataSource>
<library id="GreenplumLib">
    <file name="/data/IBM/WebSphere/Liberty/usr/lib/PROGRESS_DATADIRECT_JDBC_DRIVER_PIVOTAL_GREENPLUM_5.1.4.000275.jar"/>
</library>

A simple application uses this JNDI to connect Greenplum. And I get an error from the application:
Try to get connection : = jdbc/greenplum !!! Did not get the connection = java.sql.SQLInvalidAuthorizationSpecException: [Pivotal][Greenplum JDBC Driver][Greenplum]no pg_hba.conf entry for host "10.161.113.15", user "gpadmin", database "postgres", SSL off. DSRA0010E: SQL State = 28000, Error Code = 0
It seems the data source does not use SSL to connect Greenplum. Is there something wrong with my settings?

A: The documentation for the properties supported by this driver does not indicate that its DataSource has a URL property, so I suspect that everything you put under the URL attribute is being ignored.
Try specifying each of the properties individually, as follows,
<dataSource id="GreenplumDataSource" jndiName="jdbc/greenplum" type="javax.sql.DataSource">
    <jdbcDriver libraryRef="GreenplumLib" javax.sql.DataSource="com.pivotal.jdbcx.GreenplumDataSource"/>
    <properties databaseName="postgres" serverName="10.x.x.1" portNumber="5432" user="x" password="x" encryptionMethod="SSL" cryptoProtocolVersion="TLSv1.2" validateServerCertificate="false"/>
</dataSource>

Hopefully this will work. The JDBC driver's documentation isn't very clear on whether the listed properties all pertain to their DataSource, or DriverManager, or both.  If you end up needing to have Liberty connect via the DriverManager instead, you can configure it to do that in recent versions, but let's try the DataSource approach first and see if it works.

A: It sounds like the issue is that the pg_hba.conf file for Greenplum has not been edited to allow this host to connect (though there may be issues with the connection string as listed above). You should add a line to pg_hba.con in Greenplum's $MASTER_DATA_DIRECTORY something like:
host all gpadmin 10.161.113.0/24 md5
That would set up connectivity on all databases for gpadmin connecting on the 10.161.113 subnet.  After editing the file, run gpstop -u to update the configuration across the cluster.
As a practical note, this is trying to connect to the postgres database.  That is not a good idea as that manages (I believe) the system catalog database.  You should create a separate database and try to connect to that instead.
Jim

A: Thanks for your reply. I have fixed the issue. I set the wrong data source type and driver class before. Here is the correct setting:
<dataSource id="GreenplumDataSource" jndiName="jdbc/greenplum" type="java.sql.Driver">
    <jdbcDriver libraryRef="GreenplumLib" javax.sql.DataSource="com.pivotal.jdbc.GreenplumDriver"/>
    <properties databaseName="postgres" serverName="10.x.x.1" portNumber="5432" user="x" password="x" URL="jdbc:pivotal:greenplum://10.x.x.1:5432;DatabaseName=postgres;EncryptionMethod=SSL;CryptoProtocolVersion=TLSv1.2;ValidateServerCertificate=false"/>
</dataSource>


text:
Q: Error reading - .dbf strzero.prg I have an application (C#) which accesses data from .dbf files and populates a SQL database.  This works by reading the contents of a SQL file for the query and executes this against the .dbf and populates a datatable, the contents are then inserted into the SQL database.
I have this working for various queries, apart from one:
SELECT
b.id as LegacyAppointsID,
b.perfdate as "Date",
starttime as "time",
b2.duration as duration,
b.staffid as LegacyEmployeeId,
b.clientid as LegacyClientId,
'' as Employee,''as Client,
b.serviceid as LegacyServiceId,
'' as "Service",
0 as IsTask,
b.note as "Notes"
from Book b
inner join Blocks b2 on b.id = b2.bookid

When this one runs i get the following error displayed when executing the query against the .dbf file:
System.Data.OleDb.OleDbException: File 'strzero.prg' does not exist.
Now, if I remove the join part of the query (and the referenced columns) then the query is executed and the datatable is populated correctly, without error.  This is the only query that i have, which features a join to a second .dbf
The query is quite basic, so i am unsure as to what could be wrong with the join.
Is there a certain way that the join needs to be formatted?


text:
Q: Search large harddrive efficiently for filetype with indexing My question is somewhat related to "How to improve searching with os.walk and fnmatch" but I want to expand a little.
Let's assume we have a file collection on a harddrive, which is about 10-50 TB big. I want to find all files with a specific ending on a regular basis. The collection changes daily as new files are added. In a first run, I want to store the attained information, so that in the following runs only the changed files have to be searched which I understand as some kind of indexing of the file system and hope to greatly speed up every consecutive search.
I prefer working in python, but a hint to a readymade software-solutions as well as open-source projects in other languages is greatly appreciated.


text:
Q: UDF's in Excel add-in I have an add-in which defines a User Defined Formula (checks regular expression matching) in Excel in which it will be used to in cells custom validation.
Assume user A has the add-in installed and user B doesn't have the add-in. Thus, if user A created a worksheet and validated a specific cell using the UDF then when user B tries to open this worksheet and edit the same cell, he will keep getting an error because the UDF is not defined and no matching data is allowed (I would call it an undefined behavior because user B doesn't have the UDF defined).
Is there a way to resolve this issue that doesn't user B to install the add-in? Or to clear the data validation for any problematic cell?
I should mention that using a UDF in custom validation is done by defining a named range that wraps the UDF with the pattern needed to match because UDFs can't be used directly as a formula in data validation.
Thanks in advance.

A: You can check if the result of the UDF is an error (i.e. the user doesn't have access to it, resulting in a #NAME? error):
=IF(ISERROR(UDF()),<alternative validation>,UDF())

This way, if the add-on containing the UDF is installed, that will be used for validation. If not, you can provide an alternative validation (probably simpler) or just allow/disallow everything.


text: Q: Changing colorschemes I am using telescope to change my colorscheme according to my mood. But I found out that when I change the colorscheme, it does not change the default theme in my init.lua. How can I achieve that?


text:
Q: Android Activity only works if it's declared as main and launcher activity I'm building a music player in android. What I'm trying is to show playlist
when the app launches and user click on the list item and intent is passed to the android_player activity which plays the song.
But it's not working and when i click on list item app crashes and closes.
But when I declare music_player activity as launcher it works. But I want to show the playlist first and not the music_player.
I have following manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
   <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".AndroidMusicPlayerActivity"
        android:label="@string/app_name"
        android:configChanges="keyboardHidden|orientation"
        android:screenOrientation="portrait">
        <-- <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter> -->
   </activity>
</application>

What changes I should make to my manifest file to make it work.
AndroidMusicPlayerActivity has following code to receive intent

@Override
protected void onActivityResult(int requestCode,
                                 int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == 100){
         currentSongIndex = data.getExtras().getInt("songIndex");

         // play selected song
         playSong(currentSongIndex);
    }

}

MainActivity which shows playlist passes following intent
 lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting listItem index
                int songIndex = position;

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        AndroidMusicPlayerActivity.class);
                // Sending songIndex to PlayerActivity
                in.putExtra("songIndex", songIndex);
                setResult(100, in);
                // Closing PlayListView
                finish();
            }
        });

Log Cat data, when I click on listitem.
04-30 16:17:16.946: D/OpenGLRenderer(3858): Enabling debug mode 0 04-30
16:17:29.958: W/IInputConnectionWrapper(3858): showStatusIcon on inactive InputConnection
04-30 16:17:30.018: D/OpenGLRenderer(3858): Flushing caches (mode 0)

What changes I should make to make this code work.
I'm new to android. Please help.
Thanks!!

A: why you are making both activity as launcher in manifest? remove it then check.

A: I may be missing something but in your itemClickListener you seem to be calling finish() on your first activity without starting the second.
Surely you need to add a startActivity(in); call.


text:
Q: Wiki: Current state of the art of Delphi 3rd party TCP/IP components libraries I've not been doing bare metal TCP/IP for about 18 months, so I wonder what the current state of the art is.
I'm looking for both positive and negative aspects, with development of both server and client software.
I will be doing a project that needs a rock-solid TCP/IP layer, so for me that is an important aspect :)
For this to become a community wiki, I'm looking for broader answers than just 'rock solid'. So for instance information about the feature-width is also appreciated.
I'll be updating the question with relevant aspects found in the answers in order to get a wiki entry that has a balanced overview of those libraries.
For example, see my answer below with my past experience with Indy
I'm ambivalent on the exception handling and anti-freeze in Indy, though I got used to it, it still felt somewhat unnatural.
Right now I develop in both Delphi 2007 (non Unicode) and XE (Unicode), so the libraries I'm considering should support at least those two Delphi versions.

A: Edit: Summary of my past experience with Indy, and the comments (thanks Eugene, Marjan)
(please update with the current Indy state of the art):
Pro:

*

*ships with Delphi

*mature

*development community

*open source so lots of eyes scrutinizing those sources

*a truckload of valuable comment documentation in the source code

*OpenSSL support

*supports a broad set of Delphi versions (including 2007 and XE)

*wide choice of protocols

Con:

*

*the version shipping with Delphi was not always the most stable one; download from the sources was usually required to get a stable build

*(in the mean time) lots of duplication of code that now is in Delphi (but Indy requires for compatibility with older Delphi versions)

*not all TCP/IP components were up-to-date (for instance, back then the POP3 client component did not support some basic POP3 commands)

*version interoperability was a pain: upgrading from one Indy version to another could be very time consuming

*I'm ambivalent on the exception handling and anti-freeze in Indy, though I got used to it, it still felt somewhat unnatural.

*breaking changes are made between build updates; ifdefs required to accommodate those

*Unclear release status if any at all, no RCs for a long while, getting trunk can make your local copy unstable

A: ICS - The Internet Component Suite
ICS - see www.overbyte.be. Open source by François Piette. To me this has always been the number 1 alternative to Indy. It's most interesting selling point: it makes using asynchronous stuff easy, and being async seems to be closer to "bare metal" sockets programming.
I've used it to build a fairly complex VNC proxy where the proxy itself (server) is built with ICS and the clients are a mixture of Indy and ICS. In periods of high demand the proxy handles about 100 simultaneous connections and about 10 simultaneous VNC screen sessions. It eats up an average of 5 mbit/s, handles connections over two distinct Internet connections. I don't think the 100 + 10 is the limit, because the server handles that without any problems and CPU usage is too low to mention.
Pros:

*

*Works asynchronously

*Somewhat easier on beginners because it doesn't need threads

*Supports a good number of protocols

Cons:

*

*Relies on Windows messaging. I'm simply not comfortable with that.

*The async behavior makes implementing most protocols slightly difficult (because most protocols are in the form of send command / receive response). This shouldn't matter for most people since ICS offers ready-made implementation for the most-used protocols.

All that being said, I haven't used ICS in a very long time, I'm not up-to-date with all the bells and whistles. This is CW, so please edit and expand!

A: I have used Indy since 2003 for my own TCP communications framework. It is rock-solid, I have a version used with Delphi 2007 and another with Delphi 2010, if you handle the threadng correctly there is no need to use the anti-freeze stuff, and I have consistent exception handling on the client and the server by implementing my own wrapper around this.
You can dowload it here (http://www.csinnovations.com/framework_delphi.htm) - look for the Tcp units, mainly AppTcpServerUnt and AppTcpClientUnt.

A: I would strongly recommend  Clever Internet Suite, it's by far the best designed and written set of communication components. It's not free and so not that well known, but it's well worth investigating.
Pro:

*

*well designed and written

*contains many components and implements various protocols.

*supports a broad set of Delphi versions (including 2007 and XE)

*SSL support

*mature product as the release history indicates

Con:

*

*not open source

A: The answer really depends on many factors and your requirements, such as

*

*what layers are needed (TCP, SSL/TLS, application-level protocols)

*whether you need a client or a server as well (server is much more complicated task)

*whether you count paid options.

In general, not much (positive) happened in 18 months or even in 3 years as most developers look at .NET as primary development platform.
Clever Internet Suite mentioned in other answer and DevArt's SecureBridge gained some new functionality.
Our SecureBlackbox offers support for the most advanced features (besides native SSL/TLS): IPv6, HTTPS Proxy with basic, digest and NTLM authentication (starting with SecureBlackbox 9), International Domain Names (starting with SecureBlackbox 9), DNSSEC, bandwidth control and more.
Application-level protocols supported by SecureBlackbox are HTTP (client and server), WebDAV (client and server), FTP (client and server), SSH and SFTP (client and server), SMTP and POP3 clients, DNS client, AS2 and AS3. All of the protocols (besides SSH and SFTP, of course) have complete support for SSL/TLS.
The list of supported protocols can be found on Packages page. Supported protocol features are listed on Technical Specification page for each package.

A: You could consider using a higher protocol level like HTTP, because:

*

*It's more firewall and VPN friendly;

*It's well documented and known as a good protocol;

*It already has secured HTTPS version;

*It has a very low overhead over row TCP/IP;

*It's ready to use in an AJAX environment (if you need it in the future);

*Microsoft already did the low-level tuning for you in modern version of Windows.

In this case, you could take a look at two Open Source classes working from Delphi 6 up to XE:
THttpApiServer which implements a HTTP server using fast http.sys kernel-mode server:

*

*The HTTP Server API enables applications to communicate over HTTP without
using Microsoft Internet Information Server (IIS). Applications can register
to receive HTTP requests for particular URLs, receive HTTP requests, and send
HTTP responses. The HTTP Server API includes SSL support so that applications
can exchange data over secure HTTP connections without IIS. It is also
designed to work with I/O completion ports.

*The HTTP Server API is supported on Windows Server 2003 operating systems
and on Windows XP with Service Pack 2 (SP2). Be aware that Microsoft IIS 5
running on Windows XP with SP2 is not able to share port 80 with other HTTP
applications running simultaneously.

TWinHTTP which handles client-side HTTP/1.1 request using the WinHTTP API:

*

*Microsoft Windows HTTP Services (WinHTTP) is targeted at middle-tier and
 back-end server applications that require access to an HTTP client stack;

*Is much faster than older WinINet API.

Resulting speed is very good (especially the server), and you will rely on Microsoft implementation. The first is the core of IIS, and the second is used in the latest versions of Internet Explorer.

A: Worked with NetMaster components way (way!) back in the old Delphi versions (2! 3! 4!)
Did some work with Indy, but had the unnatural feeling also (actually I'd describe it more as bulky)
Stumbled upon Synapse when I was searching for just a light wrapper around the Windows network API,
And then rediscovered plain old TTcpClient/TTcpServer. They are Delphi's own wrapper around winsock! I use them blocking, with a dedicated TThread inheritant for each TTcpClient, and let TTcpServer do the threads and do all the work in DoAccept, see here for an example.
This, fow now, gave me the rock-solid feel we're looking for. If you want to support heavy load, I would try and build a thread manager that handles several sockets/connections per thread, or have two sets of threads: a few that listen a larger number of 'dormant' connections, and the others that handle lesser 'active' connections, switching connections between the threads depending on wether a request or response is being handled. (e.g. HTTP's Connection: keep-alive)


text:
Q: Download file using fread in while loop - restrictions I'm downloading a large file like that:
$fd = fopen($url, "r");

while(!feof($fd))
{
    set_time_limit(0);

    echo fread($fd, 4096);
    ob_flush();
    flush();
}

But in this script I have one problem - my web server has a three restrictions:

*

*max_execution_time - max 450 seconds,

*max_input_time - max 450 seconds,

*memory_limit - max 256M.

Finally I can download only a part of a file...
I'm downloading this file for watch a movie on my web site using flowplayer.
How I can change this script - it should "refresh"/reload every downloaded (for example) 2MB. Is it possible?
Thanks.


text:
Q: How to pass the touches to view from scrollview
I have 3 tableviews placed upon scrollview at x = 0.0, x = 320.0 and x = 640.0.
When the user horizontally swipes the tableviews (as they are on top), I want to pass the swipe event to its superview and when the user vertically swipes tableviews the tableview must scroll vertically.
How can I achieve this?

A: To pass the touch from UIScrollView, use this code as a category:
@implementation UIScrollView (FixedApi)

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];

    NSLog(@"touch view = %@", [[touch view].class description]);
    if ([[[touch view].class description] isEqualToString:@"UITableViewCellContentView"]) {
        //To pass the touch to UITableViewCell
    } else if ([[[touch view].class description] isEqualToString:@"UITableView"] && isHorizntalSCroll == true && pageNumber == 2) {
        //To pass the touch to UITableView

    } else if ([[[touch view].class description] isEqualToString:@"UIView"]) {
        //To pass the touch to UIView
    } else {
    [self.superview touchesBegan:touches withEvent:event]; // or 1 nextResponder, depends
    [super touchesBegan:touches withEvent:event];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if ( !self.dragging ) [self.nextResponder.nextResponder touchesEnded:touches withEvent:event];
    [super touchesEnded:touches withEvent:event];
}

@end

To determine the vertical/Horizontal scrolling, you can use this code:
.h file <UIScrollViewDelegate>
BOOL pageControlIsChangingPage;
CGPoint startPos;
int     scrollDirection;
int CX; //The width of the pages.
BOOL isHorizntalSCroll;
int pageNumber;

.m file
#pragma mark -
#pragma mark UIScrollViewDelegate stuff
- (void)scrollViewDidScroll:(UIScrollView *)_scrollView {
    if (scrollDirection==0){//we need to determine direction
        //use the difference between positions to determine the direction.
        if (abs(startPos.x-scrollView.contentOffset.x)<abs(startPos.y-scrollView.contentOffset.y)){
            NSLog(@"Vertical Scrolling");
            scrollDirection=1;
            isHorizntalSCroll = false;
            [scrollView setPagingEnabled:NO];
        } else {
            NSLog(@"Horitonzal Scrolling");
            scrollDirection=2;
            isHorizntalSCroll = ture;
            [scrollView setPagingEnabled:YES];
        }
    }

    if (scrollDirection==1) {
        [scrollView setContentOffset:CGPointMake(startPos.x,scrollView.contentOffset.y) animated:NO];
    } else if (scrollDirection==2){
        [scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x,startPos.y) animated:NO];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)_scrollView {
    if (pageControlIsChangingPage) {
        return;
    }

    CGFloat pageWidth = _scrollView.frame.size.width;
    int page = floor((_scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    pageControl.currentPage = page;
    pageNumber = page;
    NSLog(@"page number = %d",page);
    if (page == 3 || page == 0) {
        [scrollView setContentSize:CGSizeMake(CX, personalInfo.frame.size.height + 100)];
    } else {
        [scrollView setContentSize:CGSizeMake(CX, [scrollView bounds].size.height)];
    }

    pageControlIsChangingPage = NO;
}

#pragma mark -
#pragma mark PageControl stuff
- (IBAction)changePage:(id)sender {
    /*
     *  Change the scroll view
     */
    CGRect frame = scrollView.frame;
    frame.origin.x = frame.size.width * pageControl.currentPage;
    frame.origin.y = 0;

    [scrollView scrollRectToVisible:frame animated:YES];

    /*
     *  When the animated scrolling finishings, scrollViewDidEndDecelerating will turn this off
     */
    pageControlIsChangingPage = YES;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollViews{
    startPos = scrollView.contentOffset;
    scrollDirection=0;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollViews willDecelerate:(BOOL)decelerate {
    if (decelerate) {
        scrollDirection=3;
    }
}

That's it,

A: disable horizontal scroling for each tableview via IB or code and set the contentsize of the base scroll view to be 960,heightOfTableview and you should be just fine... this should get you going.


text:
Q: Public ECR image for aws-cli instead of docker hub amazon https://hub.docker.com/r/amazon/aws-cli I am searching for the ECR version for the aws-cli, instead of the one found on docker hub (https://hub.docker.com/r/amazon/aws-cli) to not stress the rate limit imposed upon by docker.
I have searched https://gallery.ecr.aws and cannot find aws-cli by Amazon/AWS, only the one by bitnami.
Does anyone know where to find it, or should I redirect my question elsewhere and if yes, where?


text:
Q: Tomcat JSF 1 Erro com f:convertNumber Olá, uso minha aplicação no tomcat 6, preciso mudar para o tomcat 7 mas em todas os lugares que uso o f:convertNumber recebo o seguinte erro:

/pages/pvt/ipd/cliente/consultar.xhtml @37,105 value="#{clientePocketController.cliente.codcliente}": Can't set property 'codcliente' on class 'br.com.mili.entities.geral.cliente.Cliente' to value '1.793'

Editado
<h:inputText id="txtCodCliente" value="#{clientePocketController.cliente.codcliente}"
         converterMessage="Permitido apenas números.">
     <f:convertNumber integerOnly="true" minIntegerDigits="0"  pattern="######" locale="pt_BR"/>
     <f:validateLength maximum="6" />
</h:inputText>

Estou usando JSF 1.2. Alguém pode me ajudar? Obrigado.

A: Talvez o problema seja que você esteja setando o valor = '1.793' em um campo do tipo inteiro, mas o jsf já tem um conversor padrão para o tipo Integer que nesse caso não precisaria especificar.


text:
Q: Using regex function to manipulate string in c# I would like to remove jsessionid=99171C97AE28712E048E321DB6B192F3 from the string below using regex in c#
www.ploscompbiol.org/article/fetchObjectAttachment.action;jsessionid=99171C97AE28712E048E321DB6B192F3?uri=info%3Adoi%2F10.1371%2Fjournal.pone.0066655&representation=XML

I have tried
string id = id.Replace(";jsessionid=.*?(?=\\?|$)", "");

but it is not working, please help!

A: Regex.Replace(text, "jsessionid=[^\\?]+","")

A: You can use the following to remove the jsession.
Regex rgx = new Regex("jsessionid=[^\\?]*)");
string id = rgx.Replace(line,"");

A: In case you change your mind and you don't want to use RegEx but manage with string.replace function,
        string sample = "ansjsessionid=99171C97AE28712E048E321DB6B192F3wer";
        sample = sample.Replace( sample.Substring(sample.IndexOf("jsessionid="),43),"");

Note that I've assumed that ID is always 32 character long.

A: Solution not using Regex:
var url = @"www.ploscompbiol.org/article/fetchObjectAttachment.action;jsessionid=99171C97AE28712E048E321DB6B192F3?uri=info%3Adoi%2F10.1371%2Fjournal.pone.0066655&representation=XML";

var startIndex = url.IndexOf("jsessionid=");
var endIndex = url.IndexOf('?', startIndex);
url.Remove(startIndex, endIndex - startIndex);

Note if a '?' is not found then it will throw an exception.


text:
Q: Как сделать имитацию «сидения» на странице? Всем привет, я точно не знаю, как вам правильно объяснить, но я постараюсь
В общем, возьмём страницу, к примеру: google.com, нужно отправить на неё запрос и оставаться при этом сидеть на странице
И желательно, чтобы не нагружало ОЗУ, ибо запросов будет более 10тыс с прокси
Как это реализовать?
Язык NODE JS, читал про websocket, я в правильном направлении?


text:
Q: How do create a custom database driver for CodeIgniter How do you create a custom database driver to extend CodeIgniter's functionalities to other types of database systems? I'm using iRODS (www.irods.org). I have a version of the site created using MySQL, but I want to be able to change the database backend with minimal changes. Is there an easy way to add this function, like how you can add a custom library in CI? I haven't been able to find any so far.

A: I'm assuming you mean how do you create a custom Active Record driver for codeigniter? Otherwise I'm probably far off the mark here but:
There is no way I know of to simply extend or override the DB classes it is not a common thing. You can implement your own and patch up your CI config to use the new DB though.
Under system/database/drivers you find all the AR driver source. You would need to reimplement each function in each of the four files (may be able to skip on forge if you don't use it.)
I'd use the MySQL driver as a starting template as you mention you already use that, in which case you'll want to make sure all the features you use are re-implemented.
It sounds like a daunting task if you're not too experienced but I assure you the code is pretty simple.


text:
Q: How can I change Trash icon in unity I've changed so many icons individually by using Main Menu.
Now I want to change icons of Trash (empty and full trash) with some PNG but I don't know what to do.
I'm using Ubuntu 12.04

A: Locate your trash.desktop file, and change the icon that way.  If you don't have a trash.desktop file, you can create one.  Open gedit, and include the following:
[Desktop Entry]
Type=Application
Icon=user-trash
Name=Trash
GenericName=Trash
Comment=open trash in PCManFM
Categories=FileManager;Utility;Core;GTK;
Exec=pcmanfm trash:///
StartupNotify=true
Terminal=false
MimeType=x-directory/normal;inode/directory;

Change the line Icon=user-trash with the location of your image.  Save as trash.desktop and exit.
Also you can look into ~/.icons and /usr/share/icons,and change the icon that way.


text:
Q: Sticky Footer Not at Bottom of 4K Screen I'm creating a website and I'm having some issues.  I'm using my boss' 4k monitor to test if the my sticky footer is all the way at the bottom.  And it's not.  The weird thing is that the footer never changes how far down it is even if I change min-height: 100vh; to something higher.
Here's my HTML:

        Brockville - (613) 865-7733 &nbsp &nbsp
        Cornwall - (343) 885-7733 &nbsp &nbsp
        Kingston - (613) 817-7733 &nbsp &nbsp
        Ottawa - (613) 454-7733

        <form action="http://www.truespeed.ca/contact">
            <input type="submit" value="Contact" class="contact" />
        </form>
        <form action="#">
            <input type="submit" value="My Account" class="myaccount" />
        </form>
        <form action="http://webmail.truespeed.ca/">
            <input type="submit" value="Webmail" class="webmail" />
        </form>

            <button class="navbar-toggle" data-toggle="collapse" data-target=".navHeaderCollapse">

            </button>

Home

Internet

Cable

DSl

Wireless

Business Cable

Business DSL

Phone

Residential Phone

Business Phone

Transfers and Rates

Android TV

Shaw Direct

Careers

Promotions!

News and Alerts!

Shaw Direct!

                    Previous

                    Next

Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.Test.

Privacy Policy

Terms of Service

Acceptable Use Policy

Warranty & Returns Policy

Third Party Copyright Notices

Terms of Service for Phone

Truespeed Internet Services Inc. 2014-2016, all rights reserved.

And my CSS:
.page {
    display: flex;
    flex-wrap: wrap;
    flex-direction: column;
    min-height: 100vh;
}
.page-content {
    flex: 1;
    width: auto;
}
html, body {
  height: 100%;
  width: auto;
}
footer {
    background-color: #00AEFE;
    height: auto;
}
footer p {
    color: white;
}

A: Make sure that your  has no padding or margin values:
footer {
  background-color: #00AEFE;
  height: auto;
  margin: 0;
  padding: 0;
}


text:
Q: set text to textbox based on selected value from dropdownlist in gridview asp net I have one Dropdown and one textBox in my gridview.
gridview contains some subject name and in database there is fees for particular
subject. I want to show that Fees into textbox on every value selected for dropdown.
i have done the same functionality which gives exact output what i want but not immediately after selection of subject, it gives value on button click.
may be i have done something wrong but not found exact solution please help.
ASPX code :
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowDataBound="Gridview1_RowDataBound" CssClass="EU_DataTable">
    <Columns>
        <asp:TemplateField HeaderText="Program Name">
            <ItemTemplate>
                <asp:DropDownList ID="ddl_ProgList" runat="server" AppendDataBoundItems="true" OnSelectedIndexChanged="ddl_ProgList_SelectedIndexChanged" ControlStyle-Width="160px">
                    <asp:ListItem Value="-1">Select</asp:ListItem>
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>

       <asp:TemplateField HeaderText="Fees">
            <ItemTemplate>
                <asp:TextBox ID="txt_fees" runat="server" ControlStyle-Width="75px"></asp:TextBox>
            </ItemTemplate>
            <FooterStyle HorizontalAlign="Right" />
            <FooterTemplate>
                <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
            </FooterTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Code Behind :
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Control ctrl = e.Row.FindControl("ddl_ProgList");
        if (ctrl != null)
        {
            DropDownList dd = ctrl as DropDownList;

            //SqlConnection conn = new SqlConnection(connStr);

            clsProg_TB objprg = new clsProg_TB();
            objprg.Center_Code = ddl_centerCode.SelectedItem.ToString();
            DataSet ds = clsUserLogicLayer.LoadPrograms(objprg);
            dd.DataTextField = "prg_Name";
            dd.DataValueField = "prg_Name";
            dd.DataSource = ds.Tables[0];
            dd.DataBind();
        }
    }
}
protected void ddl_ProgList_SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList ddl = sender as DropDownList;

    foreach (GridViewRow row in Gridview1.Rows)
    {

        Control ctrl = row.FindControl("ddl_ProgList") as DropDownList;
        if (ctrl != null)
        {
            DropDownList ddl1 = (DropDownList)ctrl;

            if (ddl.ClientID == ddl1.ClientID)
            {
                TextBox txt2 = row.FindControl("txt_fees") as TextBox;
                clsProg_TB objprg = new clsProg_TB();
                objprg.Center_Code = ddl_centerCode.SelectedItem.ToString();
                objprg.Prg_Name = ddl1.SelectedItem.ToString();
                DataSet ds = clsUserLogicLayer.getProgFees(objprg);
                if (ds.Tables[0].Rows.Count != 0)
                {
                    txt2.Text = ds.Tables[0].Rows[0][0].ToString();
                }
            }
        }
    }
}

A: You can try to update Row and the bind the gridview again. You also need to set GridView.SetEditRow() before starting editing. Another way is to update your dataTable and bind it again.
   protected void ddl_ProgList_SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList ddl = sender as DropDownList;

    foreach (GridViewRow row in Gridview1.Rows)
    {
GridView.SetEditRow(row.RowIndex);

        Control ctrl = row.FindControl("ddl_ProgList") as DropDownList;
        if (ctrl != null)
        {
            DropDownList ddl1 = (DropDownList)ctrl;

            if (ddl.ClientID == ddl1.ClientID)
            {
                TextBox txt2 = row.FindControl("txt_fees") as TextBox;
                clsProg_TB objprg = new clsProg_TB();
                objprg.Center_Code = ddl_centerCode.SelectedItem.ToString();
                objprg.Prg_Name = ddl1.SelectedItem.ToString();
                DataSet ds = clsUserLogicLayer.getProgFees(objprg);
                if (ds.Tables[0].Rows.Count != 0)
                {
                    txt2.Text = ds.Tables[0].Rows[0][0].ToString();
                }
            }
        }
         Gridview1.UpdateRow(row.RowIndex, false);
    }
Gridview1.DataBind();
}


text:
Q: How to send a correct status header with Wordpress? I read about Wordpress' own status_header() function and I read on PHPs own functions to output a status header. I want to output a 410 gone header on a particular page. But if I try and check the header I only get '200' OK.
I tried for example:
<?php if( is_page( 97324 )) { http_response_code( 410 ); } ?>

As a solution for PHP newer as version 5.4.
And I tried Wordpress' own status_header as follows:
<?php if( is_page( 97324 )) { status_header( 410 ); } ?>

I put that line in the header template at the very top, as I read this ist where it should be put.

Solution
I added a working solution according to the answer I was given by @jimmy obonyo. I used the action hook pre_get_posts and now my page sends the correct status code. My solution looks like this and this code is put to the theme's functions.php
function handle_410() {
    if( is_page( 97324 )) {
        status_header( 410 );
        nocache_headers();
    }
}
add_action( 'pre_get_posts', 'handle_410' );

A: Use status_header() before $wp_query->set  in the function file :
function handle_404() {

    // Guess it's time to 404.
    $wp_query->set_404();
    status_header( 404 );
    nocache_headers();

}


text:
Q: Responsively resizing image and background image in tandem I have two images, a JPG and an SVG, that must be overlaid, the JPG on top of the SVG. They both must resize exactly proportionally as the viewport dimensions change, and not just at specific breakpoints, but continually. The JPG is an image in a figure (

) tag set and the SVG is a CSS background: url(/url/to/image.svg). The background image looks like a picture frame around the
 image, so to keep them looking like they're one unit, it's critical that they each maintain the same aspect ratio as the viewport resizes to any dimension.
I am at a loss as to how to make this happen without either or both getting out of sync and the
 image is overlapping the background, or the background is getting too large for the
. Here's what I've tried.

    <img
        width="1024" height="682"
        src="//localhost:8181/wp-content/uploads/2021/08/istockphoto-1034140728-1024x1024-1.jpeg"
        class="attachment-large size-large"
        alt=""
        loading="lazy"
        data-src="//localhost:8181/wp-content/uploads/2021/08/istockphoto-1034140728-1024x1024-1.jpeg"
        data-srcset="//localhost:8181/wp-content/uploads/2021/08/istockphoto-1034140728-1024x1024-1.jpeg 1024w, //localhost:8181/wp-content/uploads/2021/08/istockphoto-1034140728-1024x1024-1-300x200.jpeg 300w, //localhost:8181/wp-content/uploads/2021/08/istockphoto-1034140728-1024x1024-1-768x512.jpeg 768w"
        data-sizes="(min-width: 960px) 75vw, 100vw"
        srcset="//localhost:8181/wp-content/uploads/2021/08/istockphoto-1034140728-1024x1024-1.jpeg 1024w, //localhost:8181/wp-content/uploads/2021/08/istockphoto-1034140728-1024x1024-1-300x200.jpeg 300w, //localhost:8181/wp-content/uploads/2021/08/istockphoto-1034140728-1024x1024-1-768x512.jpeg 768w"
        sizes="(min-width: 960px) 75vw, 100vw">

This is the CSS for the background as it's currently constituted:
.outline-img {
    padding: 9.4%;
    width: 118%!important;
    background: url(/wp-content/uploads/2021/09/frame.svg);
    background-repeat: space;
    background-position: 50%;
}

The weird padding and width values are how I'm currently attempting to "hold" the image within the SVG image's dimensions. Any padding less than that clips the outer edges of the SVG image. Any width less than that makes the image not fit in the SVG's inner edges. And when I resize the browser, the framed image doesn't "stick" to the inner dimensions of the SVG.
I'd love to know if there's an easier way to do this. I tried suggesting making both of these into one JPG image, but the designer is interested in this solution primarily.

A: I assume the dimension of the image remains same. You can try the following approach.

figure {
  background: url(https://cdn.pixabay.com/photo/2017/11/10/16/59/frame-2936877_960_720.png) no-repeat;
  background-size: 100% 100%;
  padding: 5%; /*adjust for your need*/
  width: 30%; /*adjust for your need*/
}

img {
  display: block;
  width: 100%;
  height: auto;
}

A: You could try in 2 different ways:

*

*Merge the 2 images together in a unique image, asking the designer again, that would save you time. svg and jpg behave differently

*if 1. is not an option, convert the .jpg image in .png and choosing the same size of the svg, the image itself will be the same but the transparency will give you the same size. (the important here is actually the aspect ratio)
In both case, add the property object-fit:contain to keep the aspect ratio during scaling and leave width and height set to auto
Going in the direction of using the same images the designer provided will lead to not necessary extra code, plus, even keeping the same aspect ratio, you should take care of the positioning during scale, another hassle which is going to create you problem with particular devices like iPadPro not being exactly targeted from more than one CSS framework around.

A: Let's look at the question a little differently.
We have a picture and we need to make it a responsive frame.
But this frame does not have to be one picture.
Instead of one frame, we make a set of images from which, using css, we will assemble a responsive frame around the image.
What you need to do:
Cut the frame into 4 corner pieces.
We also make 4 elements for the top / bottom and left / right edges.
Next, we make a table like this
https://jsfiddle.net/n5zfue27/1/
This solution supports any browser including IE6.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


text:
Q: When is "an established connection" supposed to be true in CodeIgniter? Can't figure this one out:
In the DB_driver.php (core system/database)
this is beginning of init function...
    /**
     * Initialize Database Settings
     *
     * @return  bool
     */
    public function initialize()
    {
        /* If an established connection is available, then there's
         * no need to connect and select the database.
         *
         * Depending on the database driver, conn_id can be either
         * boolean TRUE, a resource or an object.
         */
        if ($this->conn_id)
        {
            return TRUE;
        }

        // ----------------------------------------------------------------

        // Connect to the database and set the connection ID
        $this->conn_id = $this->db_connect($this->pconnect);

The initialize() is called wihtin CI_Controller so when creating new objects for example like this:
$x = new PartyPooper();
$y = new PartyPooper();

initialize() in the DB_driver is called twice. Nothing strange with that, but I would expect $this->conn_id to be set when creating PartyPooper() object second time ($y)?
When is "an established connection" supposed to be true? (In the example two database connections are made when there would should only be one?)
I'm using the latest database drivers in the development branch: https://github.com/EllisLab/CodeIgniter/tree/develop/system/database
I am using the mysqli-driver with persistant connections of.
UPDATE:
I'm not a huge fan messing with core-files, but I couldn't figure out another solution here. Please tell me if there's a better way of achieving of what I want to do.
I came up with this code (using sessions to handle storing and checking for existing db-connections (of the "subdriver"-object. (mysqli object in my case)):
public function initialize()
{
        /* If an established connection is available, then there's
         * no need to connect and select the database.
         *
         * Depending on the database driver, conn_id can be either
         * boolean TRUE, a resource or an object.
         */
        if ($this->conn_id) {
                return TRUE;
        }

        $conn_session_id_name = 'dbsession_conn';
        if (isset($_SESSION[$conn_session_id_name])) {
                $sess = $_SESSION[$conn_session_id_name];

                // Set connection id object or resourse and return true
                // because no more connecting has to be done
                if (is_object($sess) || is_resource($sess)) {
                        $this->conn_id = $sess;
                        return TRUE;
                }
        }
            // Connect to the database and set the connection ID
        $this->conn_id = $this->db_connect($this->pconnect);

        // Store conn object or resource etc into session
        if (is_object($this->conn_id) || is_resource($this->conn_id)) {
                $_SESSION[$conn_session_id_name] = $this->conn_id;
        }

        // No connection resource? Check if there is a failover else throw an error
            if ( ! $this->conn_id)
            {
            //rest of code as before...

My application got extremly much faster because it used one connection instead of around 60.
But my original question remains:
When is this supposed to be true in the initialize() function?
if ($this->conn_id) {
    return TRUE;
}

(I didn't remove it when changing the code because I suppose it has some purpose-but even if I can't figure out which)
UPDAtE2 - clarification:
In a model I have a db select statement that is supposed to return PartyPooper objects:
eg. $res = $q->result('PartyPooper');
This PartyPooper is a controller that stores information about people, like names, years , birthdays etc, but it also handles stuff like calculation of info within the same object.
class PartyPooper extends CI_Controller { .... }

But as I understand from the comments below I should do like this instead?
class PartyPooper extends CI_Controller { .... }
class PartyPooperObject { .... } //Store information about people in this object

eg. $res = $q->result('PartyPooperObject');

A: This piece of code
    if ($this->conn_id) {
            return TRUE;
    }

just assures that the initialize method is only called once per object.
If it has been called on the current object already, it must not be executed another time.


text:
Q: Can`t get json object to with knockout I can`t get json object.
My object is:
public class Person
{
   public string firstName { get; set; }
   public string lastName { get; set; }
}

PersonsControll:
    public ActionResult Index()
    {
        return View();
    }

    // GET: /Persons/GetPerson
    //[AcceptVerbs(HttpVerbs.Get)]
    //[OutputCache(Duration = 0, VaryByParam = "*")]
    public JsonResult GetPerson()
    {
        Person p = new Person { firstName = "Jonas", lastName = "Antanaitis" };
        return Json(p, JsonRequestBehavior.AllowGet);
    }

My  index view:
@Scripts.Render("~/bundles/knockout")

First name:

Last name:

When I go to ".../GetPerson" in browser, I get this displayed:
{"firstName":"Jonas","lastName":"Antanaitis"}
,but when try to get data witch javascript in view - I dont`t get this data.
What I am doing wrong, why I cant get data?
Where commented code - I tried this approaches.. but nothing helped.
I tried:
*$.ajax({
    type: "GET",
    cache: false,
    url: ".../GetPerson",
}).done(function (msg) {
    alert("Data Saved: " + msg.readyState + "  " + msg.firstName + "  " + msg.lastName);
});*

Then alert box displays: "Data Saved: undefined  Jonas  Antanaitis"

A: You are mixing async code with sync code... You have this line here
var data = $.getJSON(".../GetPerson", function (result) {

data will actually be the a promise (this is what the ajax returns). You do not actually have the data until the callback executes - ie result is the thing that has the ACTUAL data.
You need to move the binding to INSIDE the callback OR use an observable that you set after the fact:
1) Inside the callback example

2) Use an observable

And the corresponding html (The with binding makes it a bit cleaner than if):

First name:

Last name:

The advantage of the second method is that you are binding everything quickly... and can then show your data as it comes in.


text:
Q: How to convert files with extensions wmf, bmp, dwg, dxf to use in OpenLayer? currently, I am working on POC and trying to build some kind of map engine. I have implemented already and incorporated OpenLayer with Angular 6 and Material Design. It looks nice, but I got a new requirement that user should be able to import files in the formats like wmf, bmp, dwg, dxf, originally from AutoCad.

Use case: User/Client drew floor and want to add it to map engine than add some custom features like camera, polygon etc.
it's not a problem to do it with the static image, but I am looking for a way to implement based on specified file formats.

Current observation:

*

*OpenLayers doesn't support those formats;

*I can try to convert dwg, dxf in vector format like GeoJson, but with loss of original quality of the drawing (dwg, dxf - do not fully support open vector format - KML, GeoJson) - for me its a crutch;

*simply convert it to image png/jpg and load as static source - the easiest way  to do so, but I am not satisfied with quality when zoom image;

*implement own ol.source to work with one of this format;

A: Create a rest service and transform the files to the shapefile using python converters.Host the shapefile as a wfs service and serve to the client and finally if the client wants to download the data and use the wfs as the source and push a geojson back to the client.

A: Have a look at libraries that can convert those format in json you can parse to create your layers.
gdsestimating/dxf-parser could do it for dxf.


text:
Q: how to block connection to a domain in firefox i need to utterly block a domain from even being connected to. obviously, addons wont work, since those only check the URL of the site the browser is navigating to, not domains the browser is connecting to.
i need firefox, but preferably every browser to refuse to even make connection with the domain wherever and whenever they are being connected to, for example in an iframe, or loading an image from them on a site with a different URL.
changing the hosts file at C:\windows\system32\drivers\etc
did NOTHING at all. writing this as a test:
127.0.0.1 google.com
127.0.0.1 www.google.com

anywhere in the file did nothing, and i could still connect to google.
as a reference, i would need something like when a website has an invalid certificate. when that happens, firefox refuses to even connect to the domains. would it be possible to assign an invalid certificate to specific domains, so that they get blocked?
also, every hosts file changing addon i tried for firefox changes the windows hosts file, and it obviously doesnt work. is it possible to change the actual settings firefox uses instead?
also, i am using windows xp, but that shouldnt mean its impossible.

A: For the matter of C:\windows\system32\drivers\etc\hosts:
- I agree with @DavidPostill 's comment which explains the need of refreshing local name cache with ipconfig /flushdns
But sadly, as long as I remember, you can't block entire domains this way: only specific hosts, not whole domains (sorry, no regular expression interpretation).
In other words, I think you can block (after refreshing the name cache, with the above command or automatically after a reboot) www.google.com but not google.com because the destination is considered literally, as a whole; so the latter rule applies only to a connect request directed exclusively to google.com.

Your goal of blocking entire domains may be attained theoretically in diverse ways (maybe apart proprietary network security suites), even if you don't own a separate server; two of these:

*

*Running a local DNS server (even on the very same Windows XP machine, or on another machine you can link to the local network, running either Linux or Windows) and instructing it to redirect to another host any request directed to forbidden domains, and forward anything else to external (ISP?) DNS.
See BIND, a very popular and open source DNS server.
You local DNS service will become the default DNS server in Windows network configuration, which is immutable by non-privileged users.
If "bad requests" are redirected to localhost, this solution has the effect of leading to "error loading page" status.

*Running a local proxy server configured to redirect to an error page each request originally directed to the forbidden domains.
Each different browser requires not too much work to be configured, in a tamper-free fashion, to not connect directly to the web but instead to connect to the local proxy server.
Better is if you can run the proxy server in a local network environment where you can forbid (via firewall/routing rules) direct access to the web, except for the proxy server itself.
A good open source proxy, which works well even on Windows XP, is squid.
If "bad requests" are managed by a proxy, this solution has the effect of leading to a friendly (customizable) error page.
Both BIND and squid are very well documented on the net.

If you can tell us more on your setup (single machine? Or local network, made by which machines? Any server around? Configurable router?) maybe we can help you better...


text:
Q: How do I create a Rewind Functionality for YouTube video Hi Friends I want to develop a rewind functionality that when i clicked on rewind button the YouTube Video which is shown in I-frame rewind for 10 sec But I could not get How can I Create this If you have any solution Please share with me soon.

Here is my code.

    [![<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Youtube videos proxy server</title>

        <?php
        $val="";
        $vid="0TvTyj5FAaQ";
        $str = file_get_contents('video.json');
        $json = json_decode($str, true);
        foreach ($json as  $value) {
           if($value\["id"\]==$vid){
               $val="TRUE";
               break;
           }else{
               continue;
           }
           }
             if($val=="TRUE"){ ?>

                This video has restricted content.

             <?php }else{
        ?>

        <iframe id="player" width="700" height="345" src="https://www.youtube.com/embed/<?php echo $vid?>?enablejsapi=1&showinfo=0&rel=0">

        <button id='rwnd' onclick="rewind()" >Rewind</button>

             <?php } ?>

][1]][1]

Here is video.json file.

[
{
"id": "0dV1Bwe2v6c"
},
{
"id":"0dmhKtQ74wo"
},
{
"id":"0dV1Bwe2v6c"
}
]

A: Friends I got the answer now hope it will help you too. json file is same as in the question i added in code.

Here is the solution....

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Youtube videos proxy server</title>

        <?php
        $val="";
        $vid="0TvTyj5FAaQ";
        $str = file_get_contents('video.json');
        $json = json_decode($str, true);
        foreach ($json as  $value) {
           if($value["id"]==$vid){
               $val="TRUE";
               break;
           }else{
               continue;
           }
           }
             if($val=="TRUE"){ ?>

                This video has restricted content.

             <?php }else{
        ?>

        <iframe id="player" width="700" height="345" src="https://www.youtube.com/embed/<?php echo $vid?>?enablejsapi=1&showinfo=0&rel=0">

        <button id='rwnd' disabled>Rewind</button>

             <?php } ?>


text:
Q: I got a General Protection Fault while transferring files SO I was transferring files from one portable hard disk to another (I had two of them connected to the laptop and suddenly the whole thing crashed. Any idea why this could happen? Should I be worried?
I'm using Ubuntu 12.04.

A: With laptops, soometimes it's a lack of power.
Try using external power with both drives. You can get cables which split so you can plug the free end into a USB 5v supply.


text:
Q: A question from the Lyapounov's Central Limit Theorem Suppose that $|X_{nk}| \leq M_n$ with probability $1$ and $M_n/s_n \rightarrow 0$. Verify Lyapounov's condition and then Lindeberg's condition.
I am little confused with the meaning of $|X_{nk}| \leq M_n$ with probability $1$? Is it mean $P(|X_{nk}| \leq M_n)=1$ or it related with the convergence with probability $1$?

A: What is meant is $P(|X_{nk}| \leq M_n)=1$, that is, for each row, the random variables are bounded by a bound $M_n$ which may depend on the number of the row.


text:
Q: Show the result in Camunda I want to validate a given date in Camunda and want Camunda to show me the result but I don't know how to receive the result.
please help me.
The Pics:
[1]: https://i.stack.imgur.com/ZYjR1.png
[2]: https://i.stack.imgur.com/jWeD2.png
[3]: https://i.stack.imgur.com/7U1Ui.png
[4]: https://i.stack.imgur.com/Iw8cM.png

A: The id used when setting the variable is "date".
The id used in the form (process variable name) is "dateResult".
The id in the form need to match the id of the process data you want to show.


text:
Q: Error when calculating final polygon after subtracting all intersecting polygons using shapely This question is a follow-on question from Calculating final polygon after subtracting all intersecting polygons using shapely which was answered.
I have a list of centroids that I buffer to 5000 meters radius. I need to take each resulting circle and run it against the remaining centroids(also buffered to 5000 m) and find the final shape after subtracting all intersections.
In other words, I need the circle shape A to iterate over the dataset, find all circle shape(s) that intersect with it (B and C) and then create a column with a geocoordinates of the polygon, that is resulting after all intersecting circle areas are subtracted (see image below) and if it does not intersect with any other circle(s), just add a geocoordinate for the entire circle:

Here is the code I have:
df.head()

# Output:
#                cell_centroid  pop     id
#0  POINT(21.25602 55.903539)   9004.0  0
#1  POINT(21.119156 55.538406)  517.0   1
#2  POINT(21.249535 55.890204)  10369.0 2
#3  POINT(21.359934 55.904164)  800.0   3
#4  POINT(24.433042 56.104589)  800.0   4

df['cell_centroid'] = df['cell_centroid'].apply(wkt.loads)

gdf = gpd.GeoDataFrame(df, geometry="cell_centroid", crs = 4326).to_crs(crs=3857)

gdf["buffer"] = gdf.buffer(5000)
gdf["difference"] = None

gdf = gdf.set_geometry("buffer")

for i, row in gdf.iterrows():
    others = gdf[gdf["id"] != row["id"]]
    diff = row["buffer"].difference(others.cascaded_union)
    gdf.loc[i, "difference"] = diff

gdf = gdf.set_geometry("difference")

The error I am getting now is:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-122-ad757ced6ebf> in <module>
      3     diff = row["buffer"].difference(others.cascaded_union)
      4 #    gdf.loc[i, "difference"] = gpd.GeoSeries(diff)
----> 5     gdf.loc[i, "difference"] = diff
...

ValueError: Must have equal len keys and value when setting with an iterable

What's the right way to assign the resulting polygon (diff) to the GeoDataFrame?
I have found GeoPandas setting geometry for a row with .loc and Multipolygons for a similar issue, but its solution does not work in my case.

A: Deniz is right, the problem is  "difference" for field name because difference is:
a) a method object of Shapely used by GeoPandas (object.difference(other)
b) an index object of Pandas used by GeoPandas (pandas.Index.difference)
import geopandas as gpd
import matplotlib.pyplot as plt
import descartes
gdf = gpd.read_file("circles.shp")
# plot circles
fig, ax = plt.subplots(figsize=(6,6))
for i in gdf.index:
    ax.plot(*gdf.geometry[i].exterior.xy)
    ax.add_patch(descartes.PolygonPatch(gdf.geometry[i], fc='blue', alpha=0.2))
    ax.axis('equal');

With a field name different from "difference" and using unary_union instead of cascaded_union  (see  shapely.ops.cascaded_union(geoms)¶)
gdf["differ"] = None
for i, row in tt.iterrows():
    others = gdf[gdf["id"] != row["id"]]
    diff = row["geometry"].difference(others.unary_union)
    gdf.loc[i, "differ"] = diff
fig, ax = plt.subplots(figsize=(6,6))
for i in tt.index:
    ax.plot(*gdf.differ[i].exterior.xy)
    ax.add_patch(descartes.PolygonPatch(gdf.differ[i], fc='blue', alpha=0.2))
ax.axis('equal');

You can also use itertuples()
for row in gdf.itertuples(index=True):
    others = gdf[gdf["id"] != getattr(row, "id")]
    diff = getattr(row,"buffer").difference(others.unary_union)
    gdf.loc[row.Index, 'differ'] = diff


text:
Q: Receiving a HTTP 500 Error while testing with jersey test framework I implemented a REST web service and want to test my implementation with jUnit test.
As I am using the REST reference framework Jersey, I want to use the provided test framework JerseyTest, but I get some strange behaviour:
If my resource creates a response containing a String, every thing works fine (see test case responseCodeIs404IfGetForNotExistingGuiTag()).
The problem occures as soon as my response contains a pojo (see test case responseCodeIs200IfGetForExistingGuiTag()). I don't receive the expected 200 response code, but a 500 'Internal Server Error'. If I test the whole interface "by hand" every thing works fine. So I assume I need to configure the test framework in some way, but I couldn't figure out how.
I took this implementation as template.
I use Jersey 2.0 (as it is currently running on my glassfish 4.0 (no opportunity to update this)), Mockito as mocking framework and Jackson as JSON framwork.
I hope you guys can help me. If you need some more information please let me know it.
GuiTagResource.java
@Path("/char")
public class GuiTagResource {

    private GuiTagRepository guiTagRepo;

    @Inject
    public void setGuiTagRepo(GuiTagRepository guiTagRepo) {
        this.guiTagRepo = guiTagRepo;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{id}")
    public Response getGuiTagById(@PathParam("id") int guiTagNo) {

        Optional<GuiTag> guiTag = guiTagRepo.getCharGuiTagById(guiTagNo);

        Response response;

        if (!guiTag.isPresent()) {
            //This case works fine
            response = Response.status(404).entity("GuiTag with id " + Integer.toString(guiTagNo) + " was not found.")
                    .type(MediaType.APPLICATION_JSON).build();
        } else {
            //This case produces a 404 Error
            CharacteristicGuiTag guiTagTo = fromEntity((CharacteristicGuiTagEntity) guiTag.get());
            response = Response.status(200).entity(guiTagTo).build();
        }

        return response;
    }
}

GuiTagResourceTest.java
public class GuiTagResourceTest extends JerseyTest {
    @Mock
    private GuiTagRepository repoMock;

    @Override
    protected Application configure() {

        MockitoAnnotations.initMocks(this);

        enable(TestProperties.LOG_TRAFFIC);
        enable(TestProperties.DUMP_ENTITY);

        ResourceConfig config = new ResourceConfig(GuiTagResource.class);
        config.register(new InjectableProvider());

        return config;
    }

    @Test
    public void responseCodeIs404IfGetForNotExistingGuiTag() {

        when(repoMock.getCharGuiTagById(Mockito.anyInt())).thenReturn(absent());

        Response response = target("char/5").request().get();

        //Passes -> response code is 404
        assertThat(response.getStatus(), is(404));
    }

    @Test
    public void responseCodeIs200IfGetForExistingGuiTag() {

        Optional<GuiTag> compareTag = getGuiTagMock();
        CharacteristicGuiTag pojo = fromEntity((CharacteristicGuiTagEntity)     compareTag.get());

        when(repoMock.getCharGuiTagById(Mockito.anyInt())).thenReturn(compareTag);

        Response response = target("char/5").request().get();

        CharacteristicGuiTag responsePojo = response.readEntity(CharacteristicGuiTag.class);

        //Doesn't pass as response is 500?
        assertThat(response.getStatus(), is(200));
    }

    private Optional<GuiTag> getAbsentMock() {
        //returns a Optional.absent() to fake a failed db get.
    }

    private Optional<CharacteristicGuiTagEntity> getCharGuiTagMock() {
        //returns a guiTag
    }

    class InjectableProvider extends AbstractBinder implements Factory<GuiTagRepository> {

        @Override
        protected void configure() {
            bindFactory(this).to(GuiTagRepository.class).in(Singleton.class);
        }

        public GuiTagRepository provide() {
            return repoMock;
        }

        public void dispose(GuiTagRepository service) {
            repoMock = null;
        }
    }

}

The console Logs
Nov 21, 2014 12:53:26 PM org.glassfish.jersey.server.ApplicationHandler initialize
INFO: Initiating Jersey application, version Jersey: 2.0 2013-05-03 14:50:15...
Nov 21, 2014 12:53:27 PM     org.glassfish.jersey.test.grizzly.GrizzlyTestContainerFactory$GrizzlyTestContainer start
INFO: Starting GrizzlyTestContainer...
Nov 21, 2014 12:53:27 PM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [localhost:9998]
Nov 21, 2014 12:53:27 PM org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.

Nov 21, 2014 12:53:28 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 1 * LoggingFilter - Request received on thread main
1 > GET http://localhost:9998/char/5

Nov 21, 2014 12:53:28 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 5.0.0.Final
Nov 21, 2014 12:53:28 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 2 * LoggingFilter - Response received on thread main
2 < 500
2 < Date: Fri, 21 Nov 2014 11:53:28 GMT
2 < Content-Length: 0
2 < Connection: close


text:
Q: TestFlightapp.com will shutdown on 2/26/2015 As noticed that TestFlight going to be shutdown. So anymore it will be available or only on iTunesConnect, i tried to login with connect Itunes by Enterprise account  , but we  got warning "Your Apple ID isn't enabled for iTunes Connect" but when i tried to login with connect Itunes by developer account then it will connect,
so my problem is why it is connecting with Itunes when we are login with enterprises account

A: Enterprise accounts cannot submit apps to the AppStore and as such cannot access that part of the developer portal. You don't need test flight to distribute apps if you have an enterprise account anyway. You can create ad hoc builds that will work on any device installed upon. Obviously you need to familiarise yourself with the Terms & Conditions i.e. it's a violation to distribute apps using an Enterprise License to any device that is outside of that Enterprise/Company.


text:
Q: Fixing orientation problems with views ios 6 I'm trying to create a simple ios 6 app. I've added a View and a Button inside my initial view controller, which was created by story board.
I'm trying to understand how orientation works with views/buttons/images/etc.

*

*When I launch the simulator, the first problem I see is that it defaults to landscape for some reason. I would have expected the default to be portrait. How do I adjust this?
In my view controller I have the following:
-(NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
-(BOOL) shouldAutorotate {
    return YES;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationMaskPortrait; /* I get an implicit cast. I warning here too. */
}
I've also tried modifying the Supported Interface Orientations in the Summary tab to support but no luck there either.

*When I change the orientation through the simulator or my phone, the View disappears or becomes really thin. How do I keep the width at 100% no matter what orientation I'm in? I've attached a few screen shots.

This is how it's suppose to look:

But when I change the orientation, this happens:

A: The simulator will always launch in the first orientation listed under supported orientations in the plist. If you put landscape first it will launch in landscape mode.
For the resizing issue you will need to set a height constrain on the button. Go to storyboard , select the button, and then use the constrain menus at the botton of the storyboard view.


text:
Q: silverStripe using composer and this what's showing [Composer\Downloader\TransportException] I setup my AMP stack separately. Installed composer using the windows installer and  set the php.exe for composer as "c:/php/php.exe" which is where the php.exe is.
Doing  composer create-project silverstripe/installer ./silverApp returns this
 [Composer\Downloader\TransportException]
  Content-Length mismatch, received 515115 bytes out of the expected 1069991
How do I fix this..?

A: This is a problem with one of the Packagist mirrors. It should be resolved in the meantime, but if you still encounter this issue https://github.com/composer/composer/issues/7782#issuecomment-438585301 contains some background information and provides this command to switch the mirror to use:
composer config repositories.packagist.org composer https://repo-eu-uk-1.packagist.org

You can later unset the mirror with this command:
composer config repositories.packagist.org --unset