text:
Q: Understanding asymmetric in jmh I'm reading about benchmarking with JMH and now considering the example of asymmetric.
They only said this:

So far all the tests were symmetric: the same code was executed in all
  the threads. At times, you need the asymmetric test.

At which exactly "times" I need such symmetric benchmarking. I don't understand any practical use case of that facility. They provide the following one:
private AtomicInteger counter;

@Setup
public void up() {
    counter = new AtomicInteger();
}

@Benchmark
@Group("g")
@GroupThreads(3)
public int inc() {
    return counter.incrementAndGet();
}

@Benchmark
@Group("g")
@GroupThreads(1)
public int get() {
    return counter.get();
}

But can you give me some real world use-case of that? I mean, what sort of things may I want to measure asymmetrically?

A: Programmatic encryption is a specific use case:

Symmetric keys simply means that the key that encrypt the data is the same key that will be decypting the data. Asymmetric keys means that the algorthm uses a different key to encrypt and decyprt the data.
In cases where performance is a valid concern, you can help minimize the performance hit from WS-Security by intelligent use of your security options. Certain web services frameworks tend to generate "all of the above" security configurations, with messages fully signed and encrypted using WS-Security and sent over SSL connections. That's fine if you really want maximum protection and don't care about performance, but in most cases it makes more sense to use either SSL (if you're only concerned about protecting the information in transit between the client and a single server) or WS-Security encryption (if you need to ship data across multiple servers while preserving confidentiality when going through the intermediaries).
You can also use WS-SecureConversation for long-running exchanges of messages between clients and a server (even one accessed through intermediaries), for a relatively modest but significant performance gain as compared to WS-Security using certificates. WS-SecureConversation works especially well in exchanges of relatively small messages where the added overhead of certificates and asymmetric encryption can be large in comparison to the actual (symmetric) encryption of the message body.

Concurrency bug test automation is another use case:

Several different approaches have been proposed recently
to automatically fix concurrency bugs.  These
address concurrency problems resulting from inadequate synchronization, including atomicity violations, deadlocks, and data races. Roughly speaking,  in  all of these cases the fix amounts to inserting additional synchronization to inhibit bad interleaving scenarios.

And multi-core optimization:

In order to optimise performance, the JVM uses a "pseudo memory barrier" in code to act as a fencing instruction when synchronizing across multiple processors. It is possible to revert back to a "true" memory barrier instruction, but this can have a noticeable (and bad) effect upon performance.

References

*

*Java web services: The high cost of (WS-)Security

*WS-SecurityPolicy Examples Version 1.0

*Grail: Context-Aware Fixing of Concurrency Bugs (pdf)

*JNI performance - false sharing on the "-UseMembar" serialization page (David Dice's Weblog)

*SecureRF Offers Next Generation of Asymmetric Security for the Internet of Things | App Developer Magazine

*Symmetric vs. asymmetric (Security forum at Coderanch)

*What is Java's -XX:+UseMembar parameter


text:
Q: How to get information_schema in derby(JavaDB)? I am working on a program using JavaDB (which is include within the jdk in version 1.6+).
In my program, before it runs, it creates the DB and Table.  The problem is when I run this program and then shut it down and run again, an error occurs (because a table with same name already exists).
My code is like such (Java with SpringFramework) :
public class DBManager {
        private Connection conn = null;
        private PreparedStatement pstmt = null;
        private ResultSet rs = null;

    private Logger log = Logger.getLogger(DBManager.class);
    // JavaDB Embed Driver
    private String driver = "org.apache.derby.jdbc.EmbeddedDriver";
    // Database name
    private String dbName = "IIS_M_DB";
    // Table name
    private String tableName = "tbl_iis";
    // ConnectionURL
    private String connectionURL = "jdbc:derby:" + dbName + ";create=true";

    // Create Table Query
    private String createString = "CREATE TABLE " + tableName
            + "(con_id VARCHAR(40) constraint iismgr_pk primary key,"
            + "file_name VARCHAR(200),"
            + "result VARCHAR(30) default 'YET',"
            + "udt_date TIMESTAMP default CURRENT_TIMESTAMP,"
            + "reg_date TIMESTAMP default CURRENT_TIMESTAMP)";

    public void getConnection(){
        try{
            log.info("get Connection with : " + connectionURL);
            conn = DriverManager.getConnection(connectionURL);
        }catch(Exception e){
            log.error("failed to connect : " + connectionURL);
            e.printStackTrace();
        }
    }

    public boolean checkTable(){
        boolean result = false;
        String check = "select count(*) from information_schema.tables "
                + "where table_schema = '"
                + dbName + "' and table_name = '"
                + tableName + "'";
        try{
            pstmt = conn.prepareStatement(check);
            rs = pstmt.executeQuery();
            int resultInt = rs.getInt(0);
            if(resultInt < 1){
                result = true;
            }
        }catch(Exception e){e.printStackTrace();}
        return result;
    }

    public void createDB(){
        try{
            log.info("Get Driver.");
            Class.forName(driver);
            getConnection();
        }catch(Exception e){
            log.error("failed to get Driver.");
            e.printStackTrace();
        }
    }

    public void createTable(){
        try{
            log.info("creating Table.");
            pstmt = conn.prepareStatement(createString);
            pstmt.execute();
            pstmt.close();
        }catch(Exception e){
            log.error("failed to create table : " + tableName);
            e.printStackTrace();
        }
    }

    public void disconnect(){
        try{
            if(conn != null)
                conn.close();
        }catch(Exception e){
            log.error("failed to disconnect DB.");
            e.printStackTrace();}
    }

    //만약을 위한 셧다운 함수.
    public void shutDown(){
        if(driver.equals("org.apache.derby.jdbc.EmbeddedDriver")){
            boolean isSuccess = false;
            try{
                log.info("ShutDown DB.");
                DriverManager.getConnection("jdbc:derby:;shutdown=true");
            }catch(SQLException e){
                if(e.getSQLState().equals("XJ015"))
                    isSuccess = true;
                log.error("failed to shutDown DB.");
                e.printStackTrace();
            }
            if(!isSuccess)
                log.error("failed to shutDown DB.");
        }
    }
}

checkTable method is exactly what I am trying to do. And I saw that query on the Internet which they is working nicely in MySQL.
So I believe there is a similar command in Derby as well.

A: I solved XD.
But in different way, not using query.
I edited Exception area like below.
public void createTable(){
        try{
            log.info("creating Table.");
            pstmt = conn.prepareStatement(createString);
            pstmt.execute();
            pstmt.close();
        }catch(SQLException e){
            if(e.getSQLState().equals("X0Y32")){
                log.info("table " + tableName + " is already exist.");
            }
        }
    }

If other method with query, I will choice that as an answer of this question :D

redpajama_set_name: RedPajamaStackExchange


text:
Q: Securely encrypt integers (up to 2^48) into the shortest possible URL-safe string In my Django application I have hierarchical URL structure:
webpage.com/property/PK/sub-property/PK/ etc...
I do not want to expose primary keys and create a vulnerability. Therefore I am
encrypting all PKs into strings in all templates and URLs. This is done by the wonderful library django-encrypted-id written by this SO user.
However, the library supports up to 2^64 long integers and produces 24 characters output (22 + 2 padding). This results in huge URLs in my nested structure.
Therefore, I would like to patch the encrypting and decrypting functions and try to shorten the output. Here is the original code (+ padding handling which I added):
# Remove the padding after encode and add it on decode
PADDING = '=='

def encode(the_id):
    assert 0 <= the_id < 2 ** 64

    crc = binascii.crc32(bytes(the_id)) & 0xffffff

    message = struct.pack(b"<IQxxxx", crc, the_id)
    assert len(message) == 16

    cypher = AES.new(
        settings.SECRET_KEY[:24], AES.MODE_CBC,
        settings.SECRET_KEY[-16:]
    )

    return base64.urlsafe_b64encode(cypher.encrypt(message)).rstrip(PADDING)

def decode(e):
    if isinstance(e, basestring):
        e = bytes(e.encode("ascii"))

    try:
        e += str(PADDING)
        e = base64.urlsafe_b64decode(e)
    except (TypeError, AttributeError):
        raise ValueError("Failed to decrypt, invalid input.")

    for skey in getattr(settings, "SECRET_KEYS", [settings.SECRET_KEY]):
        cypher = AES.new(skey[:24], AES.MODE_CBC, skey[-16:])
        msg = cypher.decrypt(e)

        crc, the_id = struct.unpack("<IQxxxx", msg)

        if crc != binascii.crc32(bytes(the_id)) & 0xffffff:
            continue

        return the_id
    raise ValueError("Failed to decrypt, CRC never matched.")

# Lets test with big numbers
for x in range(100000000, 100000003):
    ekey = encode(x)
    pk =  decode(ekey)
    print "Pk: %s Ekey: %s" % (pk, ekey)

Output (I changed the strings a bit, so don't try to hack me :P):
Pk: 100000000 Ekey: GNtOHji8rA42qfq3p5gNMI
Pk: 100000001 Ekey: tK6RcAZ2MrWmR3nB5qkQDe
Pk: 100000002 Ekey: a7VXIf8pEB6R7XvqwGQo6W

I have tried to modify everything in the encode() function but without any success. The produced string has always the length of 22.
Here is what I want:

*

*Keep the encryption strength near to the original level or at least do not decrease it dramatically

*Support integers up to 2^48 (~281 trillions), or 2^40, because as it is now with 2^64 is too much, I do not think that we will ever have such huge PKs in the database.

*I will be happy with string length between 14-20. If its 20.. then yeah, its still 2 chars less..

A: Currently you are using CBC mode with a static IV, so the code you have isn't secure anyway and, like you say, produces rather large ciphertexts.
I would recommend swapping from CBC mode to CTR mode, which lets you have a variable length IV.  The normal recommended length for the IV (or nonce) in CTR mode, I think, is 12, but you can reduce this up or down as needed.  CTR is also a stream cipher which means what you put in is what you get out in terms of size.  With AES, CBC mode will always return you ciphertexts in blocks of 16 bytes so even if you are encrypting 6 bytes, you get 16 bytes out, so isn't ideal for you.
If you make your IV say... 48 bits long and aim to encrypt no larger than 48 bits, you'll be able to produce a raw output of 6 + 6 = 12 bytes, or with base64, (4*(12/3)) = 16 bytes.  You will be able to get a lower output than this by further reducing your IV and/or input size (2^40?).  You can lower possible values of your input as much as you want without damaging the security.
Keep in mind that CTR does have pitfalls.  Producing two ciphertexts that share the same IV and key means that they can be trivially broken, so always randomly generate your IV (and don't reduce it in size too much).


text:
Q: How to focus(), as in having a blinking caret on a div that has been given the attribute contentEditable? How to focus(), as in having a blinking caret on a div that has been given the attribute contentEditable?
What I have so far is:
$("#q_edit_field_wrap")
 .attr("contentEditable", true)
 .focus();

As is, I have to actually click on the div first.


text:
Q: Dictionary structure in firebase I want to write a program using a google Realtime DB firebase, The idea is similar to a dictionary, where one word is connected to many other words, and if you search for any of these words it will display all connected words.
I need to know how I can structure my data so I can implement my Idea, To be honest as starting I have no Idea where to start, Any idea, Links can help to start?
                  **------ UPDATE FIRST IDEA ---**

I am thinking to make a root for each word, and when searching for a word I can find all alternative/Synonyms words that connected to the root. Example:
Assume the root word is FIND with ID 1
and there is 3 alternative/Synonyms word SEEK,SPOT,SEARCH
The Data base will like
ID    word      rootID
1     FIND       0    -- 0 means its a root word
2     SEEK       1    -- root word is FIND
3     SEARCH     1
4     SPOT       1

Now if I am searching for SPOT, then I know that FIND is the root, now I can find all words that has root ID 1 and Synonyms to word FIND


text:
Q: how to print 2 alerts consecutives WinJS I want to print two alerts on my app, one to show an application and after pressing close button on first alert to show the second alert
Windows.UI.Popups.MessageDialog("Hello Welcome").showAsync();
Windows.UI.Popups.MessageDialog("Welcome to my app").showAsync();

if I just print an alert, everything works good but on the other scenary (two alerts) the code stops with an error, how to fix that??

A: You can't have multiple MessageDialogs open at the same time. Since the showAsync returns immediately (async reference), your code needs to wait until it's closed.
To do that you'd need to rely on the Promise returned by showAsync:
Windows.UI.Popups.MessageDialog("Hello Welcome")
    .showAsync().done(function() {
         Windows.UI.Popups.MessageDialog("Welcome to my app").showAsync()
    });

Above, the code waits for the done callback to be called on the Promise and then shows a second dialog.


text:
Q: Unable to send Email using Graph API (C# Console) by creating GraphServiceClient through AccessToken as well as ClientCredentialProvider I get the following error
Code: OrganizationFromTenantGuidNotFound
Message: The tenant for tenant guid 'tenantId' does not exist.
I created a .Net Core console app to send emails using the following 2 functions
I used the following namespaces
using Microsoft.Graph;
using Microsoft.Graph.Auth; //In .Net Core this is in preview only
using Microsoft.Identity.Client;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

Common Email Message to be sent in both the functions
            var message = new Message
            {
                Subject = "Meet for lunch?",
                Body = new ItemBody
                {
                    ContentType = BodyType.Html,
                    Content = "The new cafeteria is open."
                },
                ToRecipients = new List<Recipient>()
            {
                new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = "my email id"
                    }
                }
            },
                CcRecipients = new List<Recipient>()
             {
                 new Recipient
                 {
                     EmailAddress = new EmailAddress
                     {
                         Address = "2nd email id"
                     }
                 }
             }
            };

Scope required in the following functions
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
1st Method
var confidentialClient = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithClientSecret(clientSecret)
                .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}/v2.0"))
                .Build();

            // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
            var authResult = await confidentialClient
                    .AcquireTokenForClient(scopes)
                    .ExecuteAsync().ConfigureAwait(false);

            var token = authResult.AccessToken;
            // Build the Microsoft Graph client. As the authentication provider, set an async lambda
            // which uses the MSAL client to obtain an app-only access token to Microsoft Graph,
            // and inserts this access token in the Authorization header of each API request.
            GraphServiceClient graphServiceClient =
                new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
                {
                    // Add the access token in the Authorization header of the API request.
                    requestMessage.Headers.Authorization =
                            new AuthenticationHeaderValue("Bearer", token);
                })
                );

try
            {
                await graphServiceClient.Users["my user guid"]
                      .SendMail(message, false)
                      .Request()
                      .PostAsync();

//I also tried with
               await graphServiceClient.Me
                      .SendMail(message, false)
                      .Request()
                      .PostAsync();
            }
            catch (Exception ex)
            {

            }

2nd Method
 IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
            .Create(clientId)
            .WithTenantId(tenantId)
            .WithClientSecret(clientSecret)
            .Build();

            var authResultDirect = await confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync().ConfigureAwait(false);

//Microsoft.Graph.Auth is required for the following to work
            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
            GraphServiceClient graphClient = new GraphServiceClient(authProvider);

            try
            {
                await graphClient.Users["my user id"]
                        .SendMail(message, false)
                        .Request()
                        .PostAsync();

//I also tried the following
                   await graphClient.Me
                        .SendMail(message, false)
                        .Request()
                        .PostAsync();
            }
            catch (Exception ex)
            {

            }

I have given all the required permissions. Some of the permissions are extra and may not be required. I gave the permissions to check if those permissions are the reason why I am getting the error but nothing changed.

I have also checked the token I am getting on jwt.io. I am getting the following roles
 "roles": [
     "Mail.ReadWrite",
     "User.ReadWrite.All",
     "Mail.ReadBasic.All",
     "User.Read.All",
     "Mail.Read",
     "Mail.Send",
     "Mail.ReadBasic"
  ],

I don't see any issue with the code or with the permissions that I have given but I am still missing something which I am unable to figure out. The reason why I say this is because when I tried to get user information by calling the api - https://graph.microsoft.com/v1.0/users, I get the users information as below.
value = [
{
    "businessPhones": [],
    "displayName": "user display name",
    "givenName": "user first name",
    "jobTitle": null,
    "mail": null,
    "mobilePhone": null,
    "officeLocation": null,
    "preferredLanguage": "en",
    "surname": "user last name",
    "userPrincipalName": "user information",
    "id": "user id"
    }
  ]

Any help is appreciated

A: This is because your Azure AD tenant does not have an Exchange online license under the O365 subscription.
As a result, your tenant does not have the ability to send Email messages.
If you have an o365 subscription, you'll see it here.
1.

2.

3.

A: @Chauncy Zhou was absolutely right with the solution.
But there are a couple of things you need to do if you are an individual because you will not get Office 365 license in your azure account as an individual.
I created a Developer.Microsoft.com account and then I used that account to create a new Azure account where I was able to add the license for Office for the Active Directory and that user. Rest of the code is already there and it works fine.


text:
Q: Tag synonyms for pgAdmin I am in the process of cleaning up the mess around the tags for pgadmin.
pgadminiii and pgadmin3 all refer to the same thing. Internally we (pgAdmin developers) just speak of "pgAdmin" nowadays.
I managed to propose pgadminiii as tag synonym, but could not do the same for pgadmin3. Got the error message:

Failed to propose synonym:
Version specific synonyms can only be created by moderators (click on
  this box to dismiss)

However, pgAdmin III is not a reference to a specific version of the program. And, strictly, there is no pgAdmin 3 at all. The precursors "pgAdmin I" and "pgAdmin II" are long forgotten. The switch to pgAdmin III marks the change to a different license and code base (from Visual Basic to C++) many years ago. The current version of pgAdmin is 1.14.2.
Could an admin kindly lend a hand? pgadmin should be the master tag.
I have now added a tag wiki and would appreciate assistance in cleaning up the aliases.
Disclosure: I am a (low activity nowadays) member of the dev team of pgAdmin.

A: This has been cleaned up as part of The great Stack Overflow tag/question cleanup of 2012.
Basically, pgadminiii and pgadmin3 have been retagged pgadmin.
I didn't add the synonyms, as it was indicated that the version numbers were outdated.  If you want specific version numbers (1.14.2) then we can add the tag for you, just give us a question and we'll put it on.
Note that we wouldn't make a synonym for it, because version numbers being a synonym generally doesn't work (sometimes there's no need for one, other times, you need just that version, etc.).


text:
Q: JS: Nested promises I do not understand how to chain promises:
getUser is a promise function and also search is a promise function. getUser will return a language value.
With this data is not an array value, which should be returned by the search function
getUser(userId)
  .then(({ language }) => {
    const data = search('content', language)
    res.send(200, {
      content: data,
      user: { language }
    })
  })
  .catch((error) => next(error))

A: To avoid nesting, you can use Promise.all: this will allow you to pass the language value through the chain as well:
getUser(userId)
    .then(({ language }) =>
        Promise.all([language, search('content', language)])
    ).then(([language, data]) =>
        res.send(200, {
            content: data,
            user: { language }
        })
    ).catch((error) => next(error))

A: If search returns a promise, then you need to use .then() to get access to the data in that promise. And you should return promises in order to enable chaining at higher levels:
getUser(userId)
  .then(({ language }) => {
    return search('content', language)
      .then((data) => {
        res.send(200, {
        content: data,
        user: { language }
      });
  })
  .catch((error) => next(error))

Note that normally you could avoid nesting by returning the promise returned by search(), and chaining another .then() call afterward, but because you're trying to capture the language parameter from the original method call, you need the value to be in scope. Trincot's answer shows how you can capture the value of language for better chaining.


text:
Q: linear combination of infinitely divisible random variables II I have a question that repeats the question I found here:
If X and Y are real valued random variables with infinitely divisible distributions, does aX+bY also have an infinitely distribution (a,b∈R). I've seen this stated in several places as obvious, but I have only seen the proof in the case that X and Y are independent. Does anyone know where I can find the proof if we don't assume independence?
The answer was:
I doubt that is true in general. Counter example: Let W1
be a standard normal random variable, and
W2=W1, if |W1|≤1
W2=−W1, otherwise
Then W2
is also a standard normal r.v., but W1+W2
has a finite support, and is not constant, therefore not infinitely divisible, according to
https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&ved=0ahUKEwiowYfs3srKAhXEMyYKHaM1DskQFggzMAM&url=http%3A%2F%2Fweb.abo.fi%2Ffak%2Fmnf%2Fmate%2Fgradschool%2Fsummer_school%2Ftammerfors2011%2Fslides_rosinski.pdf&usg=AFQjCNE_2G83w4nq7gqDM5xvP3pt8c281A&cad=rja
However,
According to
https://books.google.com/books?id=zBZqDQAAQBAJ&pg=PA66&lpg=PA66&dq=%22linear+combination%22+%22infinitely+divisible%22&source=bl&ots=bWYkYPGvw5&sig=ACfU3U3IYtQG1VPv3lMFqP3UqR5xzYQZ6g&hl=en&sa=X&ved=2ahUKEwiru8zt0vvhAhUMn-AKHRTRCsEQ6AEwBnoECAkQAQ#v=onepage&q=%22linear%20combination%22%20%22infinitely%20divisible%22&f=false
The book "Random and Vector Measures (Series on Multivariate Analysis)" p.66
aX+bY does be ID
Can you pls help me regarding this issue?

A: If $X$ has standard normal distribution and $Y=X$ when $|X| \leq 1$ and $-X$ when $|X|>1$ then $Y$ also has standard normal distribution and $X+Y$ does not have an ID distribution. This is because it is  a bounded random variable and it is not a constant.


text:
Q: Buscar una cadena en una consulta a la base de datos Estoy tratando de realizar un buscador para una web, pero necesito buscar palabras concretas en ese buscador, como por ejemplo "portatil i5".
He probado con LIKE pero no lo hace bien. Tengo que decir que a lo mejor esa cadena que busco no está al principio ni al final, si no que está contenida.
He probado esta función de MySQL:
SELECT * FROM comparador WHERE MATCH (titulo) AGAINST ('+"portatil i5"' IN BOOLEAN MODE)

No me devuelve nada, pero si pongo un 14, sí lo hace bien.
Y también esta otra:
SELECT * FROM comparador WHERE MATCH (titulo) AGAINST ('+portatil +i5' IN BOOLEAN MODE)

La que devuelve unos resultados similares es la primera, pero al poner i5 se fastidia la consulta.
Luego, a parte, esto viaja desde un post con ajax.
EDICIÓN
Registros en la bd de Ejemplo
(34528, 0, '', '', 0, '', '', 0, 0, '', '', 0, '', 'PORTATIL ASUS X509JA-BR491T i3-1005G1 15.6HD 8GB 512SSD W10 COLOR PLATA', '', '', '', '', '90NB0QE1-M10120', 'DESYMAN', '', 369, 0, '0', '', 0, 'https://desyman.com/articulos/artporta asus x509ja-br491t_1.jpg\r', 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '0000-00-00 00:00:00', 0, 0, '2020-10-08 07:10:40'),
    (34529, 0, '', '', 0, '', '', 0, 0, '', '', 0, '', 'PORTATIL ASUS X509JA-BR252T i3-1005G1 15.6HD 8GB 256SSD W10 COLOR PLATA', '', '', '', '', '90NB0QE1-M09760', 'DESYMAN', '', 339, 0, '0', '', 0, 'https://desyman.com/articulos/artporta asus x509ja-br252t_1.jpg\r', 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '0000-00-00 00:00:00', 0, 0, '2020-10-08 07:10:40'),

Tabla en la BD
CREATE TABLE `comparador` (

`id` int(11) NOT NULL,
  `id_categoria` int(11) NOT NULL,
  `categoria` text COLLATE utf8_spanish2_ci NOT NULL,
  `ruta_categoria` text COLLATE utf8_spanish2_ci NOT NULL,
  `id_subcategoria` int(11) NOT NULL,
  `subcategoria` text COLLATE utf8_spanish2_ci NOT NULL,
  `marca` text COLLATE utf8_spanish2_ci NOT NULL,
  `id_marca` int(11) NOT NULL,
  `id_proveedor` int(11) NOT NULL,
  `tipo` text CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL,
  `ruta` text CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL,
  `estado` int(11) NOT NULL,
  `url_producto` text COLLATE utf8_spanish2_ci NOT NULL,
  `titulo` text COLLATE utf8_spanish2_ci NOT NULL,
  `titular` text CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL,
  `descripcion` text COLLATE utf8_spanish2_ci NOT NULL,
  `youtube` text COLLATE utf8_spanish2_ci NOT NULL,
  `multimedia` text CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL,
  `codigo` text COLLATE utf8_spanish2_ci NOT NULL,
  `proveedor` text COLLATE utf8_spanish2_ci NOT NULL,
  `ean` text COLLATE utf8_spanish2_ci NOT NULL,
  `costo` float NOT NULL,
  `canon` int(11) NOT NULL,
  `stock` text COLLATE utf8_spanish2_ci NOT NULL,
  `detalles` text CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL,
  `precio` float NOT NULL,
  `portada` text CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL,
  `vistas` int(11) NOT NULL,
  `ventas` int(11) NOT NULL,
  `vistasGratis` int(11) NOT NULL,
  `ventasGratis` int(11) NOT NULL,
  `ofertadoPorCategoria` int(11) NOT NULL,
  `ofertadoPorSubCategoria` int(11) NOT NULL,
  `oferta` int(11) NOT NULL,
  `precioOferta` float NOT NULL,
  `descuentoOferta` int(11) NOT NULL,
  `imgOferta` text CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL,
  `finOferta` datetime NOT NULL,
  `peso` float NOT NULL,
  `entrega` float NOT NULL,
  `fecha` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;

Código php de la aplicación
// Incluimos nuestro archivo CONEXION
require_once "../app/conexion.php";

$articuloAbuscar = $_POST["articulo"];

$articulo = DB::queryExecute("SELECT *
                                FROM comparador
                                WHERE MATCH (titulo)
                                AGAINST ('".$articuloAbuscar."' IN NATURAL LANGUAGE MODE)
                                LIMIT 50;
                            ");

echo "
";
    for($i=0; $i<count($articulo); $i++){

        echo "
";

            if($articulo[$i]["portada"] != null){
                echo "" . "
";
            }else{
                echo "No tiene imagen" ."
" ;
            }

            $id = $articulo[$i]['id'];

            echo "
";
            echo " Titulo: ".$articulo[$i]["titulo"] ."". "
";
            echo " Proveedor: ".$articulo[$i]["proveedor"] ."". "
";
            echo " PN: " . $articulo[$i]["codigo"] . "" . "

";
            echo " Costo: " . $articulo[$i]["costo"] . "" . "

";
            echo " Stock: " . $articulo[$i]["stock"] . "" . "

";
            echo "
                    <button class='btn btn-success mb-5'>Crear Oferta EMSEEL</button>
                  ";
            echo "
                    <button class='btn btn-success mb-5'>Crear Oferta Informatica</button>
                  ";

        echo "
";
    }
echo "
";

json_encode($articulo);

Class conexion
class DB {

public static function connect() {
    try{
        $connection = new PDO("mysql:host=10.48.0.19;dbname=bbdd-tienda-integra","root","pass");
        $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }catch(PDOException $e){
        echo "Error: ". $e->getMessage();
    }

return $connection;
}

// EXECUTE QUERY MYSQL TYPE SELECT
public static function queryExecute($sql){
    $arrayData = array();

    try{

        $connection = DB::connect();

        $stmt = $connection->query($sql);
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $stmt->execute();

        // SAVE THE DATA IN ARRAY
        $arrayData = $stmt->fetchAll();

    }catch(PDOException $e){
        echo 'Error: '. $e->getMessage();
    }
return $arrayData;
}

consulta INDEX
//generamos la consulta
$resultado = DB::queryExecute("SELECT DISTINCT id, titulo, codigo, proveedor, costo, stock, portada FROM comparador ORDER BY id ASC LIMIT 10");

Tengo que decir, que es una aplicación realizada con php puro, nada de MVC, y solo la estoy modificando, no la he realizado yo y me estoy volviendo loco con muchas cosas....
Gracias de antemano

A: Con la información nueva que proporcionas puedo ayudarte mejor.
Para empezar, deberías proteger tu código de los graves problemas de seguridad asociados a la inyección SQL que debe solucionarse con consultas preparadas o bien usando PDO::quote().
Como estableces una conexión por cada consulta SQL (algo que no te recomiendo y que es malísimo en cuestión a rendimiento), lo más sencillo es preparar tu función para recibir los valores de los marcadores para hacer uso de una consulta preparada:
$articulo = DB::queryExecute("
    SELECT *
    FROM comparador
    WHERE
      MATCH (titulo) AGAINST (:articulo IN NATURAL LANGUAGE MODE)
    LIMIT 50;
", [
    ':articulo' => $_POST["articulo"]
]);

La implementación del método de tu clase cambiaría a:
class DB {
    /* ... */

    public static function queryExecute($sql, $marcadores = []) {
        try {
            $connection = DB::connect();
            /* No hacemos la consulta, solo la preparamos */
            $stmt = $connection->prepare($sql);
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            /* Ejecutamos la consulta usando los marcadores proporcionados */
            $stmt->execute($marcadores);
            /* Devolvemos el resultado, no es necesario almacenarlo */
            return $stmt->fetchAll();
        } catch(PDOException $e) {
            /* Finalizamos la ejecución del script */
            die(htmlspecialchars('Error: '. $e->getMessage()));
        }
    }
}

Por otro lado estoy viendo que tu PHP genera HTML y luego parece intentar devolver un JSON con json_encode($articulo);, pero obviamente eso último no funcionará sin una función de salida al navegador (como echo).

Problemas que sufres con tus dos búsquedas:

*

*+"portatil i5": Las comillas se usan para buscar exactitud en la secuencia de términos. Estás buscando el término portátil seguido inmediatamente después por el término i5. Si no existe ningún registro que tenga ambas palabras inmediatamente una después de la otra entonces no te aparecerá ningún resultado.

*+portatil +i5: El símbolo + indica que debe encontrarse esa palabra y el - que no debería estar. Ten en cuenta que el término i5 no llega a la longitud mínima por defecto (3 caracteres) para que pueda ser indexado, por lo que la consulta lo ignorará por completo.
Para solucionar esto último necesitarás cambiar la configuración del servidor MySQL de manera permanente y reconstruir el índice de búsqueda de texto completo de la manera que expongo a continuación.
Configuración del servidor MySQL
Para modificar el tamaño mínimo de los términos que se agregarán al índice de texto completo hay que agregar las siguientes líneas al apartado [mysqld] del archivo de configuración del servidor MySQL (suele ser /etc/mysql/my.cnf):
[mysqld]
innodb_ft_min_token_size=1
ft_min_word_len=1

Reiniciar el servidor MySQL para que surtan efecto los cambios.
Reconstrucción del índice de búsqueda de texto completo
Ahora deberemos reconstruir el índice de búsqueda de texto completo para que incluya los nuevos términos mediante la siguiente consulta SQL:
OPTIMIZE TABLE comparador

A partir de ahora podrás usar el término i5 en una búsqueda pare delimitar los resultados obtenidos.
Puedes ver la respuesta original en este enlace.


text:
Q: grads is showing none after loss.backward() in fgsm attack import torch
from torch import nn
from transformers import BertTokenizer, BertForSequenceClassification

# Load pre-trained model and tokenizer
model = BertForSequenceClassification.from_pretrained('bert-base-uncased')
model.cuda()

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')

# Set up device (CPU or GPU)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Define PGD/FGSM attack functions
def fgsm_attack(model, loss_fn, input_ids, attention_mask, labels, epsilon=0.1):
    input_ids = input_ids.float()
    attention_mask = attention_mask.float()
    input_ids.requires_grad = True
    attention_mask.requires_grad = True
    logits = model(input_ids=input_ids.long(), attention_mask=attention_mask.long())[0]
    loss = loss_fn(logits, labels)
    loss.backward()

    # Create perturbation tensor based on sign of gradients
    perturbation = epsilon * input_ids.grad.sign()

    # Add perturbation to input tensor and clamp values
    perturbed_input = input_ids + perturbation
    perturbed_input = torch.clamp(perturbed_input, 0, 1)

    # Detach input from computation graph and return perturbed input
    return perturbed_input.detach()

from tqdm import tqdm
for batch in tqdm(validation_dataloader):
    input_ids = batch[0].to(device)
    token_type_ids = batch[1].to(device)
    attention_mask = batch[2].to(device)
    labels = batch[3].to(device)
    peterbed_inputs = fgsm_attack(model, nn.CrossEntropyLoss(), input_ids, attention_mask, labels, epsilon=0.1)

    #outputs = model(input_ids, attention_mask=attention_mask, token_type_ids = token_type_ids)

I imported the BERT model and tried to perform fgsm attack on it. But it throws the error while getting sign of input_ids.grad.sign() showing that the value is None
Can some please help me why the input_ids.grad showing None
I expected input_ids.grads not to be None


text:
Q: Minimal Elements with respect to big Oh Let $\mathcal{F}$ be a finite set of functions from the natural numbers to the natural numbers. Consider the set $S_{\mathcal{F}}=\{g:\mathbb{N}\to\mathbb{N}\mid f\in O(g)\text{ for every } f\in\mathcal{F}\} $. I want to decide whether $S$ has a minimal element with respect to big Oh, i.e. can I show (or disprove) that there exists a $g\in S$ such that for every other $h\in S$, we have $g\in O(h)$? I think if I just choose $g$ to be the sum of all the functions in $\mathcal{F}$ then this does the trick.
Now, does the result also hold if $\mathcal{F}$ is replaced with any countable set of functions? I feel like this result should be true and that I should be able to apply some sort of well ordering principle or Zorn's lemma type argument to solve this, but I'm not really sure how to proceed. Any help is appreciated!

A: Consider $\mathcal{F} = \{n \mapsto n^\alpha \,\mid\, 0<\alpha < 1\}$.
Assume that your conclusion holds, i.e. there is $g \in S = S_{\mathcal{F}}$ such that for every $h \in S$, we have $g \in O(h)$.
Consider $h_n := g_n / \ln n$ (here, I ignore the requirement $h_n \in \Bbb{N}$, this can be fixed by rounding, I omit the details).
Let $\alpha \in (0,1)$ be arbitrary. Choose $\beta \in (\alpha,1)$. Then $n^\beta \in O(g)$, i.e. $n^\beta / g_n \leq C$ for all $n$. But this implies
$$
n^\alpha / h_n = n^\alpha \cdot \ln (n) / g_n \leq C' \cdot n^\beta / g_n \leq C \cdot C',
$$
since the logarithm grows slower than any positive power of $n$.
By what we just showed, $h \in S$. By choice of $g$, this implies $h \cdot \ln n = g \in O(h)$, which is obviously false.
Hence, the claim fails in general for infinite sets $\mathcal{F}$. Note that we can even choose $\mathcal{F}$ to be countable by considering only $\alpha \in (0,1) \cap \Bbb{Q}$.


text:
Q: Run function when pthread exits I have a C++ app in which I create pthreads to run user provided functions. I want to be able to be alerted in some way when a thread exits so that I can remove it from an array of pthread that I am using to keep the threads. Is there a way to do this, or should the function just set some "magic value". Because my main code that spawns the pthreads is in a sort of runloop, I can easily check for an exit condition.

Also, is using a std::vector<pthread_t> overdoing to keep track of my threads an overload? The number of threads is not necessarily any sort of constant, many threads or very few could be running. Or is there another STL container that would be good for these additions and deletions (additions always at one end, deletions almost anywhere). Is there some other structure for keeping track of pthreads? Would a stack or a list be right here? Or a standard C array with a generous maximum good? Due to the nature of the problem, I could also maintain a fixed size array of worker threads to whom I pass the user functions that must be executed. Is this a good solution?
Sorry for the long confused question, but I have only worked with threading in dynamic languages where this would never be an issue.

EDIT (3/08/12):
After reading @jojojapan's answer, I have decided to use a threadpool of sorts. In my structure, I have one producer (a thread in a runloop) and many consumers (the worker threads in the pool). Is there a data structure that is made for multithreaded one-producer many-consumer use? Or whould I just use a std::queue with a pthread_mutex_t on it?

A: *

*One option you might want to consider is to not actually end and delete threads once they finished a task, but instead keep them alive and have them wait for a new task to be assigned to them. You can accomplish this by doing two things:

*

*Use an (almost) infinite loop in the thread

*Use a concurrent queue or some other technique that makes them wait for a signal to be given by another thread. Design patterns and strategies are discussed in several SO questions, e.g. this one

*If you really want to send a signal once a thread ends, you can use a pthread_cond_t and call pthread_cond_signal on it just before a thread reaches its return statement. Of course that assumes that there is some other thread running that waits for these signals and acts upon them by removing the corresponding thread from the vector. Details on the usage are described on the corresponding man page, but also in this SO post.
Edit related to the comment and the edited part of the question:

*

*Regarding the number of worker threads: That depends on the resources used the most by the threads. If what those threads do is mostly computation and a bit of memory access, in other words, if they are CPU-bound, it makes sense to use as many threads as your CPU can maintain (specifically, there is a certain number of cores, and number of (hardware) threads per core that your CPU can run before they start slowing each other down. The threads you are creating (software threads) should be about as many, or perhaps a few more (up to two times as many as hardware threads is reasonable according to what @Tudor says here)). However, if your threads make heavy use of memory (memory-bound) or harddisk (IO-bound) or other resources such as the network, NFS, or some other server, you might want to reduce the number of threads in order (a) not to cause them to block each other, and (b) not to put unreasonably much load on certain resources. Determining the right number of threads may be a matter of experimenting, and keeping the number configurable is generally a good idea.

*Regarding the best data structure to store work tasks: The concurrent bounded queue mentioned in the comments of the post I cited further above is probably very good. I haven't tried it myself, though. But if you'd like to keep things simple, a standard std::queue, or even simply a std::vector would not be a bad choice, if you protect them properly using the signal/mutex technique.

A: Consider changing strategy entirely and use an existing threadpool library. They'll do the job for you, you will save a lot of not so funny debugging.
Boost.thread pool is one of many, link.

A: A simple way to do this is to just use a pipe.
Open the pipe before spawning the threads.  Pass the pipe fd as part of your thread data.  Before the thread exits have it write its pthread_self() to the pipe.  Have main or separate thread on the read end of pipe.  It reads the dead thread's tid and immediately does a pthread_join.  (If it is a separate reaper thread it can just block on the pipe read; if it is in main just make it part of your select/poll or whatever.)
This gives you the flexibility of not using an data structure to save the TIDs at all if don't want.  If you do want to save them then a list or a map is a better choice than a vector.
If you have main starting the threads and a separate 'reaper' thread collecting them and you want to save them in some structure then you will need to synchronizing access to the structure between the two.


text:
Q: Return value from service once $resource promise is resolved I have such working code:
Service (factory?):
myApp.factory('MyService', ['$q','$resource', 'MyResource',
    function ($q, $resource, MyResource) {

        return {
            getRoles: function () {
                return MyResource.getRoles(); //MyResource makes API calls using $resource
            } } });

Controller:
$scope.Roles = MyService.getRoles();
$scope.Roles.$promise.then(function () { $scope.RolesCount = $scope.Roles.length; });

What I'd like to do is to create such function in MyService that will return number of roles once getRoles is resolved so I can use it in controller like this:
$scope.RolesCount = MyService.getRolesCount();

and then in html
{{RolesCount}}

Unfortunately, I have no idea how to do this since my getRolesCount() method needs to return something so I can't use $promise.then() inside MyService. I'll try to update my question's title once I come up with something more accurate.

A: If server response needs to be transformed in a service, then then should be moved there. However, it's not practical or possible if then is supposed to unwrap a promise and assign a value to scope, like in the code above.
$resource returns an object that is filled on promise resolution. The way a resource is supposed to be used in view is:
{{Roles.length}}

When an object is updated, it will be updated in view, too. Assigning the value to another variable is inefficient.
It's impossible to do something like
$scope.RolesCount = MyService.getRolesCount();

because getRolesCount is asynchronous, and the value it resolves with is scalar. It is possible to flatten it with `async..await, (TypeScript or ES2017), but will require additional measures to synchronize control flow with AngularJS digests, as explained in this answer.


text:
Q: Best way to prevent unauthorized user on Angular site from seeing site for a split second before being redirected to login? I am currently building an Angular front end on a site that pulls much of its data from an API that requires authorization via login.
I have built the following authInterceptor that works well and redirects users to the login page if a 401 error is sent from the server:
angular
  .module('myApp.services')
  .factory('authInterceptor', ['$rootScope', '$q', '$window', '$location', function($rootScope, $q, $window, $location) {

    return {
        'request': function(config) {
          config.headers = config.headers || {};
          if ($window.sessionStorage.token) {
            config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
          }

          return config;
        },
        'response': function(response) {
          return response || $q.when(response);
        },
        responseError: function(rejection){
          if (rejection.status == 401){
            $location.path('#/login');
          }
          return $q.reject(rejection);
        }

      };
  }])

The problem with this is that the API calls and therefore, the 401 errors don't occur until the end of the page load process -  so, users can see a split second of all of the elements (e.g., HTML, CSS, images and all other elements that don't hit the API) loading up on my page before the application hits the API and gets the 401.
I've worked around this by putting a random API call right at the beginning of my MainController that doesn't really do anything but this seems like the wrong way to do it since I'm making an unnecessary ping to the server. Any suggestions and best practices around this?
Also, when I do hit those unauthorized routes, I get the ugly 401 error messages in my console - is there a way to do this redirect without displaying those to the user or is this normal?

A: I think ng-cloak may help you here as you can add this to elements that should be hidden until your application is bootstrapped, I have done something similar, will try and get you an example

A: If you use a ui-router for your application routing, you could use nested states and a resolve clause in a parent of your 'authenticated' states to make sure that you only get to that controller/template if your 'login' request has successfully resolved and to redirect to a 'sign-in' state if the request fails.
Here is some guidance on how to protect your 'authenticated' routes using ui-router:
http://blog.john.mayonvolcanosoftware.com/protecting-routes-in-angularjs/


text:
Q: The values of operands in TEA algorithm will not get decrypted correctly in Assembly I'm writing an assembly project to perform Tiny Encryption algorithm. I followed the C-Code on Wikipedia and transformed it into x86 assembly.
However when I run the algorithm the inputs v0 and v1, they get transformed into gibberish as they should, however, when I try to decrypt the ciphertext, I don't get the original back.
Here is the encryption procedure
encrypt PROC
xor eax, eax
xor ebx, ebx
xor ecx, ecx
xor edx, edx
xor esi, esi
xor edi, edi
mov ecx, 32
LOOP1:
;sum+= delta
mov eax, sum
ADD eax, delta
mov sum, eax
; (v1 << 4) + k0
mov eax, v1
SAL eax, 4
ADD eax, key0
mov v1l4, eax
; (v1 + sum)
mov eax, v1
ADD eax, sum
mov v1ps, eax
; (v1 >> 5) + k1
mov eax, v1
SHR eax, 5
add eax, key1
mov v1r5, eax
;((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1)
mov eax, v1l4
xor eax, v1ps
xor eax, v1r5
; v0 += ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1)
ADD v0, eax
; (v0 << 4) + k2
mov eax, v0
SAL eax, 4
ADD eax, key2
mov v0l4, eax
; (v0 + sum)
mov eax, v0
ADD eax, sum
mov v0ps, eax
; (v0 >> 5) + k3
mov eax, v0
SHR eax, 5
add eax, key3
mov v0r5, eax
; ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3)
mov eax, v0l4
xor eax, v0ps
xor eax, v1r5
; v1 += ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3)
ADD v1, eax

dec ecx
cmp ecx, 0
JG LOOP1
ret
encrypt ENDP

Here is the decryption procedure
decrypt PROC
xor eax, eax
xor ebx, ebx
xor ecx, ecx
xor edx, edx
xor esi, esi
xor edi, edi
mov ecx, 32
LOOP2:
; (v0 << 4) + k2
mov eax, v0
SAL eax, 4
ADD eax, key2
mov v0l4, eax
; (v0 + sum)
mov eax, v0
ADD eax, sum
mov v0ps, eax
; (v0 >> 5) + k3
mov eax, v0
SHR eax, 5
ADD eax, key3
mov v0r5, eax
; ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3)
mov eax, v0l4
xor eax, v0ps
xor eax, v1r5
; v1 -= ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3)
SUB v1, eax

; (v1 << 4) + k0
mov eax, v1
SAL eax, 4
ADD eax, key0
mov v1l4, eax
; (v1 + sum)
mov eax, v1
ADD eax, sum
mov v1ps, eax
; (v1 >> 5) + k1
mov eax, v1
SHR eax, 5
ADD eax, key1
mov v1r5, eax
; ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1)
mov eax, v1l4
xor eax, v1ps
xor eax, v1r5
; v0 -= ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1)
SUB v0, eax
; sum -= delta
mov eax, sum
SUB eax, delta
mov sum, eax

dec ecx
cmp ecx, 0
JG LOOP2
ret
decrypt ENDP

Many thanks!


text:
Q: AppWidgets on AppWidgetHost disappearing after reboot Now this is an unconventional method for using AppWidgets. I'm working in the system level in AOSP. Basically the AppWidgets have a custom widget category that I poll to get the Providiers and everything I need. Now the issue is twofold: 1.) The AppWidgets do not update like they should and 2.) They disappear after reboot and don't show up in the widget list anymore. This also happens when I set the category to be a launcher widget as well(when the service isn't running, launcher widgets work as expected). I can provide logs and stack traces where possible and do anything to help figure this out. I'm tearing my hair out with this. The code for the AppWidgetHost is below.
Notes:
- I can't use the Settings intents to select AppWidgets, because I need a custom picker.
public class SecondScreenService extends Service {

private ArrayList<View> ssas = new ArrayList<>();
private ArrayList<Integer> appWidgetIds = new ArrayList<>();
private ArrayList<AppWidgetProviderInfo> secondScreenWidgets = new ArrayList<>();
private FrameLayout fakeRootView;
private SecondScreenView rootView;
private ViewsPagerAdapter viewsPagerAdapter;
private ViewPager viewPager;
private WindowManager wm;
private DisplayManager dm;
private LayoutInflater inflater;
private AppWidgetManager mAppWidgetManager;
private AppWidgetHost mAppWidgetHost;
private BroadcastReceiver mReceiver = new PackageReceiver();
private ArrayList<Integer> pos = new ArrayList<>();
private int scrollState;
public static final int APPWIDGET_HOST_ID = 3254;
public static final String TAG = "BLUG";

private final IBinder mBinder = (IBinder) new LocalBinder();

public class LocalBinder extends Binder {
    public SecondScreenService getService() {
        return SecondScreenService.this;
    }
}

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

@Override
public void onCreate() {
    inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);

    fakeRootView = (FrameLayout) inflater.inflate(R.layout.second_screen_root, null);

    rootView = (SecondScreenView) fakeRootView.findViewById(R.id.secondscreenview);

    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
            WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
            PixelFormat.OPAQUE);

    params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SECOND_SCREEN;
    params.gravity = Gravity.LEFT | Gravity.TOP;
    params.x = 400;
    params.y = 0;
    params.width = 1040;
    params.height = 160;

    wm.addView(fakeRootView, params);

    viewPager = (ViewPager) fakeRootView.findViewById(R.id.second_screen_viewpager);
    viewsPagerAdapter = new ViewsPagerAdapter(this);
    viewPager.setAdapter(viewsPagerAdapter);

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
    intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
    intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
    intentFilter.addDataScheme("package");

    registerReceiver(mReceiver, intentFilter);
    mAppWidgetManager = AppWidgetManager.getInstance(this);
    mAppWidgetHost = new AppWidgetHost(this, SecondScreenService.APPWIDGET_HOST_ID);
    mAppWidgetHost.startListening();
    pollWidgets();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mAppWidgetHost.stopListening();
    if (fakeRootView != null) {
        wm.removeView(fakeRootView);
        fakeRootView = null;
    }
}

private void pollWidgets() {
    for(View view : ssas) {
        mAppWidgetHost.deleteAppWidgetId(((AppWidgetHostView) view).getAppWidgetId());
    }
    ssas.clear();
    int appWidgetId = this.mAppWidgetHost.allocateAppWidgetId();
    List<AppWidgetProviderInfo> widgets = new ArrayList<>();
    mAppWidgetManager.getInstalledProviders(AppWidgetProviderInfo.WIDGET_CATEGORY_SECOND_SCREEN);
    widgets.addAll(mAppWidgetManager.getInstalledProviders(36864));
    for(AppWidgetProviderInfo awpi : widgets) {
        System.out.println("BLUG: SysUI: got widget " + awpi.provider.toString());
        mAppWidgetManager.bindAppWidgetId(appWidgetId, awpi.provider);
        AppWidgetHostView hostView = mAppWidgetHost.createView(this, appWidgetId, awpi);
        hostView.setAppWidget(appWidgetId, awpi);
        ssas.add((View) hostView);
    }
    if(this.viewPager != null && this.viewsPagerAdapter != null) {
        viewsPagerAdapter = new ViewsPagerAdapter(this);
        viewPager.setAdapter(viewsPagerAdapter);
    }
}

private class PackageReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                SecondScreenService.this.pollWidgets();
            }
        }, 1000);
    }
}

private class ViewsPagerAdapter extends PagerAdapter {
    private Context mContext;

    public ViewsPagerAdapter(Context context) {
        mContext = context;
    }

    @Override
    public Object instantiateItem(ViewGroup collection, int position) {
        View view = (View) SecondScreenService.this.ssas.get(position);
        collection.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup collection, int position, Object view) {
        collection.removeView((View) view);
    }

    @Override
    public int getCount() {
        return SecondScreenService.this.ssas.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "";
    }
}
}


text:
Q: Como fazer setTimeout rodar "infinitamente" Preciso que uma função seja executada a cada 2 minutos.
Encontrei neste link uma solução para a minha necessidade:
Link
O Código abaixo, chama um alert após 5 segundos ao deixar o mouse parado.
Observação
Coloquei 5 segundos para poupar tempo no teste.
<script type="text/javascript">
$(function() {
    timeout = setTimeout(function() {
       alert('executa função');
    }, 5000);
});

$(document).on('mouseover', function() {
    if (timeout !== null) {
        clearTimeout(timeout);
    }

    timeout = setTimeout(function() {
        alert('executa função');
    }, 5000);
});
</script>

O que eu preciso:
Eu preciso que este script funcione da mesma forma só que em um loop infinito, onde a cada 5 segundos será chamado o alert.
Eu tentei abraçar o código com:
while(0 = 0){

}

Mas não funcionou...
Como faço então para que minha função seja executada infinitamente a cada 5 segundos automaticamente?

A: Use setInterval, que faz basicamente mas mesma coisa, mas repetindo a cada período
<script type="text/javascript">
var timeInterval = null;
$(document).on('mouseover', function() {
    if (timeInterval !== null) {
        clearInterval(timeInterval);
    }

    timeInterval = setInterval(function() {
        alert('executa função');
    }, 5000);
});
</script>

A: Para que o evento ocorra infinitamente sem o mouseover, basta remove-lo. Veja:
function Temporizador(initiate) {
    if (initiate !== true) {
        alert("Olá mundo");
    }
    setTimeout(Temporizador, 5000);
}

$(function() {
    Temporizador(true);
});

Se chamar o Temporizador(true); com true, ele não executa o primeiro alert, mas somente a cada 5 segundos.


text:
Q: Is a metal chain inside a pc case a bad idea? I have a pc case, sitting on wood, connected to a surge protector. I've put a metal chain into the case, one side connected to a random empty space in the case and the other side connected to the AIOs pipe, not pinching it or damaging it in anyway, fits perfectly. It's touching the guard thingy on top of the power and HDD Storage section. And its also touching  the graphics  card. Could this damage the pc? i use surge protector so i think it should be fine. Any ideas? thanks in advance.

A: It can possibly create a short circuit. Magic smoke will escape and you're gonna have a bad time.
A proper surge protector protects the PC from electrical surges from the outside. It has no effect on stuff that's happening entirely on the "internal" side of the protector.

A: What could happen is, that the metal (conductive) chain touches some of the bare metal parts of your PC, when it is shaken/moved around. The surge protection only protects your system from power surges over your powerbar/plug, not from the inside. Everything on the inside is technically vulnerable. From how it looks right now though, I have no concerns. What should not happen is, that the chain comes on top of the graphics card, because then you would risk it sliding towards your mainboard and touching some exposed electronic components and short them, which would effectivly damage/kill your system. Just make sure, that when you want to move the chain, you turn off the power (actually unplug it), so if you accidentally touch any important parts on your boards, they aren't powered.
If your system is standing like so and is not moved much, then you should be good to go :)
I am adding to this: Usually, nothing unnecessary should be inside your casing. This is the safest way to go. But I understand why you're doing this and I think the risk is acceptable in that case.
I would judge that differently if this wasn't a mini ITX board, becuase it would have too much overhang under the GPU for that metal chain to touch easily. But since this is mini ITX, it's fine.


text:
Q: Python Flask: urls to different websites as variables Hi I'm currently learning Flask and was wondering how I can put a link to another website as a variable? I have included the code below, basically I would like to link things like facebook, li etc as a variable.
@app.route('/social')
def social():
    return render_template('index.html',
        **mainbody = ("Links to social things are here, facebook, linkedin etc email https://www.facebook.com/")**,
        number = number,
        bettotal = bettotal,
        winnings = "%0.2f" % winnings,
        result = ("Place a bet!"))

Thanks for your help.


text:
Q: FreeRTOS Mutex Unexpected behaviour #include "main.h"
#include "FreeRTOS.h"
#include "semphr.h"
#include "task.h"

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
void Task1(void *argument);
void Task2(void *argument);
void PrintMsg(char *data);
/* USER CODE BEGIN PFP */

SemaphoreHandle_t hMutex = NULL;
TaskHandle_t hTask1 = NULL;
TaskHandle_t hTask2 = NULL;
UART_HandleTypeDef huart2;

int main(void) {
    /* MCU Configuration--------------------------------------------------------*/
    /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
    HAL_Init();
    /* Configure the system clock */
    SystemClock_Config();
    /* Initialize all configured peripherals */
    MX_GPIO_Init();
    MX_USART2_UART_Init();

    /* USER CODE BEGIN 2 */
    xTaskCreate(Task1, "Task 1", configMINIMAL_STACK_SIZE, NULL, 2, &hTask1);
    xTaskCreate(Task2, "Task 2", configMINIMAL_STACK_SIZE, NULL, 2, &hTask2);
    /* USER CODE END 2 */

    hMutex = xSemaphoreCreateMutex();
    if (hMutex == NULL) {
        PrintMsg("Mutex not created\r\n");
    } else {
        PrintMsg("Mutex created\r\n");
    }

    vTaskStartScheduler();

    /* USER CODE BEGIN WHILE */
    while (1) {
        /* USER CODE END WHILE */
        /* USER CODE BEGIN 3 */
    }
    /* USER CODE END 3 */
}

void Task1(void *argument) {
    /* USER CODE BEGIN 5 */
    /* Infinite loop */
    for (;;) {
        if (xSemaphoreTake(hMutex,2000) == pdTRUE) {
            PrintMsg("Shared Resource Start and Executing Task 1\r\n");
            xSemaphoreGive(hMutex);
            PrintMsg("Shared Resource End and Executing Task 1\r\n");
            vTaskDelay(100);
        } else {
            PrintMsg("Task 1 Didn't get access to shared resource\r\n");
        }
    }
    /* USER CODE END 5 */
}

void Task2(void *argument) {
    /* USER CODE BEGIN 5 */
    /* Infinite loop */
    for (;;) {
        if (xSemaphoreTake(hMutex,2000) == pdTRUE) {
            PrintMsg("Shared Resource Start and Executing Task 2\r\n");
            //xSemaphoreGive(hMutex);
            PrintMsg("Shared Resource End and Executing Task 2\r\n");
            vTaskDelay(100);
        } else {
            PrintMsg("Task 2 Didn't get access to shared resource\r\n");
        }
    }
    /* USER CODE END 5 */
}

void PrintMsg(char *data) {
    int i = 0;
    while (*(data + i) != '\0') {
        HAL_UART_Transmit(&huart2, (uint8_t*) &data[i], 1, 0xFF);
        i++;
    }
}

HW USED:STM32F446RE
When i run this code,I get output as follows
//Output Start
Mutex created
Shared Resource Start and Executing Task 1
Shared Resource End and Executing Task 1
Task 2 Didn't get access to shared resource
Task 1 DiTask 2 Didn't get access to shared resource
Task 1 Didn't get access to shared resource
Task 2 Didn't get access to shared resource
.
.
//Output End
Question1)
Considering Task1 was scheduled first as the priority of Task1 and 2 are same.
Task1 is executed correctly.
After this,Task2 is scheduled but was not able to take the mutex because of which i got output as "Task 2 Didn't get access to shared resource".Why is this so?
Question2 )
"Task 1 DiTask 2 Didn't get access to shared resource" in this line,it seems that Task1 was exceuting but it got preempted by Task2 which should have not happened as both the Tasks have same priority??

A: Q1: The likely explanation here is that you're being fooled by competing tasks overwriting each others' buffered UART output. UART is slow, task switching is fast :)
After Task1 prints "Shared Resource Start and Executing Task 1" and releases the mutex for the first time, scheduler immediately switches to Task2 (maybe because Task1 has used up its time slot?). Task2 grabs the mutex, quickly spits both of its messages into UART buffer and enters sleep for 100 ticks. The scheduler immediately switches back to Task1, but unfortunately the buffered messages from Task2 haven't hit the UART output yet. UART buffer gets overwritten by the message "Shared Resource End and Executing Task 1" before a single byte of Task2-s messages is printed.
After that the entire process stalls because you haven't released the mutex in Task2.
Q2: tasks with equal priorities get preempted by each other when the scheduler decides so (usually when they enter sleep or have exhausted their time slot)
I would recommend this tutorial/book, chapter 3 for a great explanation of how tasks work.

A: USART is a resource, so it can't be shared by two tasks without a sync mechanism, like a mutex. Your usage of PrintMsg() violates this rule.
The scheduler is run at configTICK_RATE_HZ frequency. If configUSE_TIME_SLICING is 1 (or undefined), the scheduler switches between equal priority tasks. If you don't want this default behavior, set configUSE_TIME_SLICING to 0.
Keep it in mind that your configTICK_RATE_HZ setting of 1000 gives at most ~1 ms runtime to each task, unless there are no other tasks ready to run. Higher priority tasks can also preempt it before that 1 ms passes. With 115200 baud rate, you can send ~10 bytes or so in this ~1 ms time period.


text:
Q: How to Customize Humanized Moment js Date Result I want to customize the humanize date result with moment js. Let's say I have a date and I want to take the remaining time that return back a result "in 3 months"
moment("20141001", "YYYYMMDD").fromNow(); // in 3 months

How can I customize the resultant string like 3 months left ? Is moment provide any external parameter to customize the resultant or any other way I can achieve this?

A: "Like moment#fromNow, passing true as the second parameter returns value without the suffix. This is useful wherever you need to have a human readable length of time."
Moment documentation
So,
var start = moment([2007, 0, 5]);
var end = moment([2007, 0, 10]);
start.from(end);                   // "in 5 days"
start.from(end, true);             // "5 days"
start.from(end, true) + " left";   // "5 days left"


text:
Q: Multiple accidental POST requests in Python I have this program that sends a GET request using requests library and then sends a POST request to another server.
import requests

# inside the loop :
headers = {'charset':'utf-8','Content-Type':'application/json'}
url = "http://someurl/_get_v2.php"
data = jenal

try :
    resp = requests.post(url,json=data,headers=headers, timeout=(connect_timeout,read_timeout))

    print "Post request sent"
# If a connection error occurs, start from the beginning of the loop
except requests.exceptions.ConnectionError as e:
    continue
# If a read_timeout error occurs, start from the beginning of the loop
except requests.exceptions.ReadTimeout as e:
    continue
time.sleep(10)

This is the POST part from the main loop. I used try and except in case if the program runs into a delay, I don't want it to stop for any error, but refreshes and continues from the beginning of the loop and so on for ever. Logically, the program should be fine, but when there is a multiple number of delays suddenly the program sends multiple POST requests at the same time.
E.g: the log should be like this:
10 sent.
20 sent.
30 sent.
45 sent (5 seconds delay).
55 sent
but what happens is this :
10 sent
20 sent
30 sent
delay..
45 sent
45 sent
45 sent (a few copies of the data are sent at the same time which corrupts my database)
55 sent
How am I supposed to prevent the extra copies?
This is the first part of the program. In case there's anything in the post part, this part repeats and I can see the print each time:
connect_timeout = 3.05
read_timeout = 2

while True:
loop_time_start = time.time()
# GET

url_source = 'http://something/api_json.asp?cmd=list_metering&auth=YWRtaW46YWRtaW4='
try:
    url = requests.get(url_source)
    print "GET request sent"
except requests.exceptions.ConnectionError as e: continue

A: What if you add a timer to the code.
import requests
from datetime import datetime, time

posting = False

# inside the loop :

if not posting:
    posting = True

    headers = {'charset':'utf-8','Content-Type':'application/json'}
    url = "http://someurl/_get_v2.php"
    data = jenal

    start = datetime.now()
    try :
        resp = requests.post(url,json=data,headers=headers,timeout=(connect_timeout,read_timeout))

        print "Post request sent"

        posting = False

    except requests.exceptions.ConnectionError as e:
        # If you continue here, then there will be no sleep.
        # If your POST fails straight away, it tries again straight away.

        # You should print/log here so you know which exception is being caught.

        # Add Timer
        end = datetime.combine(start.date(), time(0))

        ShouldISleep(start, end)

        posting = False

        continue

    except requests.exceptions.ReadTimeout as e:
        # If you continue here, then there will be no sleep.
        # If your POST fails straight away, it tries again straight away.

        # You should print/log here so you know which exception is being caught.

        # Add Timer
        end = datetime.combine(start.date(), time(0))

        ShouldISleep(start, end)

        posting = False

        continue

    time.sleep(10)

Create a function
def ShouldISleep(t1, t2):
    passed = (t1 - t2).seconds
    if passed < 10:
        time.sleep(10 - passed)

A: I would recommend looking at the approved answer on this question.


text:
Q: Как исправить ошибку Array 'f' cannot have a deferred shape? Я пытаюсь решить СДУ с комплексной переменной методом Рунге-кутты 4 порядка, используя GNU Fortran Compiler. Как устранить ошибку "Array 'f'  cannot have a deferred shape"?
program main
      integer, parameter :: n = 3, nsteps = 100
      real, parameter :: a = 0.0, b =1.0
      real ::  x(0:n)

      real :: d, hbar,W,omega0,omega,gamma1, E, delta
      d=3.335641E-30
      hbar=1.0546e-34
      omega = 2.482/(6.24e18*hbar)
      W = 1.25e10
      omega0= 2.4743/(6.24e18*hbar)
      delta=0.0
      gamma1= 1E15
      E=(1/hbar)*W;
      x = (/1.0, 0.0, 0.0,0.0/)
      h = (b - a)/nsteps
      call rk4sys(n,h,x,nsteps)
end program main

subroutine xpsys(n,x,f)
      complex, dimension (0:n) ::  x, f
      integer n

      f(0)= (-(0., 1.))*d*x(1)*E - x(2)*E+gamma1*x(4) ! 00+
      f(1)= ((0., -1.)*(x(2)*(delta)+ d*E*(x(0)- x(3)))-gamma1*x(2)/2)!11
      f(2)= (0., 1.)*(x(2)*(delta)+ d*E*(x(0)- x(3)))-gamma1*x(2)/2!10
      f(3)= (0., 1.)*d*(x(1)*E- x(2)*E)-gamma1*x(3)!01

end subroutine xpsys

subroutine rk4sys(n,h,x,nsteps)
      complex ::  x(0:n), f(:,:)
      real, allocatable :: y(:)
      integer :: i, k, n
      real :: h
      print *,0,x
      allocate (y(0:n), f(0:n,4))
    out:  do k = 1,nsteps
            call xpsys(n,x,f(0,1))
    in1:    do i = 0,n
              y(i) = x(i) + 0.5*h*f(i,1)
            end do in1
            call xpsys(n,y,f(0,2))
    in2:    do i = 0,n
              y(i) = x(i) + 0.5*h*f(i,2)
            end do in2
            call xpsys(n,y,f(0,3))
    in3:    do i = 0,n
              y(i) = x(i) + h*f(i,3)
            end do in3
            call xpsys(n,y,f(0,4))
    in4:    do i = 0,n
              x(i) = x(i) + (h/6.0)* (f(i,1) + 2.0*(f(i,2) + f(i,3)) + f(i,4))
            end do in4
            print *, k, x
          end do out
end subroutine rk4sys

A: В процедуре rk4sys динамически-распределяемый массив f должен быть описан как allocatable:
subroutine rk4sys(n,h,x,nsteps)
  complex ::  x(0:n)
  complex, allocatable :: f(:,:)
  real, allocatable :: y(:)
  ...


text:
Q: Does Subversion merge diff or just update revision on unmodified files We have some feature branches that can get put on ice for a few weeks at a time.  After making many changes in the trunk, is it best to merge the changes from trunk into the branches or drop the branch and create a new branch directly from the trunk and copy the changes from the starting branch into it.
The reason I ask is that for a merge SVN simply takes a diff of the trunk from last merge to head and applies that to the branch.
In many cases the changes in the trunk far outweigh the changes in the branch, so from the size of the diff it would make sense to drop the feature branch and create a new one with the feature branches changes patched in.
This is particularly an issue when a lot of PDF's are updated.
It seems like another way would be for SVN to realize that a file in the branch was never touched and therefore update the revision number it points to rather than blindly applying the diff.
From the output of Subversion it seems as if it is applying the diffs though.

A:
It seems like another way would be for
  SVN to realize that a file in the
  branch was not touched and therefore
  update the revision number it points
  to. This would avoid the extra space
  for the diff.

AFAIK, applying diff don't take any significant extra space in subversion.
If the diff is small, it should take merely the similar amount of space as just updating revision.
BTW, merging from trunk to branch ?  It'd only make sense only if you plan to merge branch back to the trunk later.
http://svnbook.red-bean.com/en/1.5/svn.branchmerge.basicmerging.html

A: I think the way you're using Subversion is probably incorrect (I've done this before to). What you need to do is merge a range of revisions into your trunk.
Example:
Rev: 100
/trunk

(Make a branch)
Rev:101
/trunk (r100)
/branch (r101)

(Lots of changes)
Rev: 200
/trunk (r100)
/branch (r200)

Now what you need to do is to generate all the diffs between r100 and r200 and apply them to the trunk. Merge is a little misleading (like the documentation states). Your use case is a fairly common scenario which is covered in the documentation.
I don't think there's any best practise on whether to merge trunk->branch or branch->trunk. It's very dependant on how you want to work and your scenario. From the sounds of it, the feature branch would be more unstable the trunk. It would make sense to merge into trunk once you have the feature completed. In order to limit conflicts when you merge back into trunk, you can continuously merge from the trunk->branch.

A: From the Subversion 1.6 CHANGES file:
identical files share storage space in repository (issue #2286)
So, it appears that even though the diff is applied, upon commit, the code should discover identical files and just use pointers to the first version of the files.


text:
Q: One KStream to multiple topics using duplicate messages; broadcast In a Kafka streaming topology, I would like to route a stream from an incoming topic using a KStream, enhance the message, and output to a destination topic. In the middle of the stream however, I'd also like to send all the messages to another topic.
KStream<Integer, GenericRecord> ksDevice = builder.stream("source_topic", Consumed.with(Serdes.Integer(), genericRecordSerde));

KStream<Integer, GenericRecord> ksEnhance = builder.stream("enhance_topic", Consumed.with(Serdes.Integer(), genericRecordSerde));

ksDevice.join(ksEnhance, (k, v) -> /* enhance message */))
.to("orthogonal_topic")
.to("destination_topic")

This obviously isn't possible because .to() terminates the stream.
I also can't use kstream.branch() because this will send the message to either one topic or the other; I need to send all messages to both topics.
I saw a post where the author suggested that you can do this by using kstream.filter().to("topic")
kstream.filter().to("topic")
Streaming messages to multiple topics
But I can't see how this is done without terminating the stream.

A: The linked post is correct. In your case, you don't need a filter. Create an intermediate variable
KStream k = ksDevice.join(...)
k.to()
k.to()

Alternatively, use .through().to().
But as commented, you're needlessly duplicating the exact same data on the broker. Two distinct consumer groups can be used instead to read from one topic.


text:
Q: Setting toolbar as transparent when not at the top? I currently have a fragment with a toolbar that "disappears" when scrolling down and "reappears" on scroll up but I want to change it so that the background of the toolbar is transparent if it's showing and not all the way at the top (or even just ALWAYS transparent). This is what I currently have:
activity_fragment.xml:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:background="@color/colorPrimaryDark">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            app:layout_scrollFlags="scroll|enterAlways"
            app:theme="@style/CustomActionBar" />

    </android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout >

I've tried android:background="@null" on both the Toolbar and the AppBarLayout but that didn't work.
I suspect the issue is with the how/where I inflate the recylerview that gets displayed beneath the the fragment_container:
FragmentAlbumGallery.java:
   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_recycler_gallery, container, false);
        mAlbumRecyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
        mAlbumRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
return v;
}

fragment_recycler_gallery.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ActivityGallery"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
</android.support.v7.widget.RecyclerView>

Screenshot of what my fragment looks like now:

A: You need to customize the style CustomActionBar:
<style name="CustomActionBar">
    <item name="android:background">@android:color/transparent</item>
</style>

That's all, folks


text:
Q: View.onMeasure() not called I have a very simple custom View with onMeasure() overriden. My onMeasure() decides the size according to the background Drawable. When the View is first created from xml everything works normally. But then I set a different background programatically, so the View should resize. The View has now a different background, but it doesn't resize and onMeasure() is not called.
I tried everything - requestLayout(), forceLayout(), invalidate(), setLayoutParams() - without any effect. What am I doing wrong? I just want my View to resize.

A: The problem was that I was calling setBackground() inside my View's onSizeChanged(). I refactored the code and it works now.

A: Have you tried the obvious thing, i.e. how is your method declared?
If you did not add the @override annotation, add it, and see if your compiler tells you that it is not overriding anything. If so, check the name and method signature of onMeasure.
Otherwise, make sure you understand when the measure() method is supposed to be called: How Android draws Views.


text:
Q: Tablas de multiplicar con php utilizando funciones Hola amigos tengo este codigo php lo que mi profesor me pide es que lo adapte a funciones y las utilize, por ejemplo ingresar este codigo a una funcion y pasarle el valor 'num' por parametros pero usando funciones espero que alguien me ayude porfavor gracias!
$n=$_POST['num'];
if ($n<1 or $n>10) {
    echo "no has escrito un nůmero entre el 1 y el 10.";
    }
else {
     echo "
Tabla del $n:
";
     $i=1;
     while ($i<=10) {
           echo "$n x $i = ".$n*$i."
";
           $i++;
           }
     }
?>```

A: Por lo que entiendo en tu pregunta buscas es crear una funcion donde le puedas pasar a la funcion el valor y este ejecute el resultado.
Si visitas el manual de PHP en la seccion de FUNCIONES PHP podras ver la estructura que debe tener una funcion creada por el usuario.
Se me ocurre lo siguiente:
    <?php

    function bucle($n){

       if ($n<1 or $n>10) {
        echo "no has escrito un nůmero entre el 1 y el 10.";
        }
    else {
         echo "
Tabla del $n:
";
         $i=1;
         while ($i<=10) {
               echo "$n x $i = ".$n*$i."
";
               $i++;
               }
         }
         }

bucle(6);

     ?>

cuando quieras ejecutar dicha funcion puedes llamarla en cualquier parte del codigo, tambien puedes hacerlo declarando una variable y pasandole esa variable a la funcion, ejemplo de ello:
<?php
$a = 4;
$b = 6;
$c = 8;
$d = 10;

bucle($a);
bucle($b);
bucle($c);
bucle($d);


text:
Q: Collision detection not detecting I have an array of objects that are all 'rectangles'. I also have a circle that is the object. The equation I use for gravity is:
newYPos = oldYPos + prevFallingSpeed + gravity
Basically, I am adding the rate of gravity to the number of pixels the circle 'fell' in the previous frame and then adding that to the position of the circle in the last frame.
I am detecting if any part of the ball is inside of any of the objects using this code:
for(var i = 0; i < objects.length; i++){
    if(ball.x > objects[i].x - ball.r && ball.y > objects[i].y - ball.r && ball.x < ball.r + objects[i].x + objects[i].w && ball.y < ball.r + objects[i].y + objects[i].h){
        alert('test');
        gSy = (-1 * gSy);
    }
}

The code checks if the circle's coordinates plus or minus the radius is greater than the top/left positions of the walls of the box and less than the right/bottom positions of the walls of the box.
The ball is inside the object at one point, but I never get an alert. I've tried everything I can think of. Hopefully I'm just making some dumb mistake I can't see...
Here is a jsfiddle if you are up for messing with my code or don't understand the variables:
http://jsfiddle.net/JGKx5/

A: The small problem:
You have four objects.

*

*Two of them (numbers 1 and 3) are tall and thin, and off to the left or right. The ball never goes near them.

*One of them (number 2) is short and wide, and at y-coordinates smaller than the ball ever attains.

*The other one (number 0) is short and wide, and its y-coordinates are ones that a real physical ball would pass through -- but because your ball moves in discrete steps your script never actually sees it do so. (It goes from y=580.4 to y=601.2.)

The big problem:
In the jsfiddle, all your comparisons in the collision test appear to be exactly the wrong way around :-). (Which is odd since the ones in the code here are the right way around.)
With both of these changed (I made the ball move by 0.1*gSy instead of by gSy, and flipped all the comparison operators), collisions are detected.


text:
Q: Random large download across the office of Windows 10 desktops Couple months ago, I've just completed the office-wide upgrade to Windows 10. We have about 40 Dell' desktops running Win 10 and MS Office, and no other business applications installed besides Malwarebytes, CCleaner, Chrome, Belarc.
Yesterday (Sept 20), users started complaining about their browsers failing to load websites. I've checked my LinkBalancer and noticed that random workstations downloading heavy amount of data while maxing out our two ISP: 100Mbps and 20Mbps. As they block the entire bandwidth, other users get times-out and not being able to get anything.
Unfortunately, we don't have proper network edge equipment where I can limit per session bandwidth.
This morning there are still couple of instances of massive downloads.
Any clue/idea I should check.
Thank you

A: There are a few place you could check:
If you have some workstations having this massive download constantly:

*

*Just to be sure, check for any irregular user activity: Torrent,
movie files (avi,mkv) or steam.

*Install wireshark on them. Wait for the massive download and sniff
the packets and check for the IPs where the number of packets is the
highest. Using the command nslookup with the IP may give you the
name of the source, or just googling the IP.

If this is very random, there's 2 things you could check:

*

*Go to a workstation where the massive download occurred and check if there weren't any recent update from windows (go to Windows Update > Advanced Options > Update history). If this is an update issue, check WSUS (https://technet.microsoft.com/en-us/windowsserver/bb332157.aspx).

*[more difficult and time demanding] Find a way to monitor network activity: A feature on yours appliance or set up a server and put it between your workstations and your router.


text:
Q: In MVC, how do I pass in form data as query strings? I want to make it so that when people search for something, what they searched gets added to the url of the next page. So they can favorite the page, and then access the page again without filling in the  form again. All the posts I can fine assume I want to pass in hard coded query string parameters.

A: When you send an HTTP POST request, the data that the client send to the server are stored in the request's body.
While, when you send an HTTP GET request, you can send data to the client that are in the query string (after the question mark, ?, in form of key/value pairs, ?name=test&age=21) of your url.
That being said, you have to add a filter to your ActionResult method in your controller that allows only HTTP GET request to reach it. For instance, you need something like this:
public class HomeController : Controller
{
    [HttpGet]
    public ActionResult ActionName(string name, int age)
    {
    }
}

Then the client can make a GET request using the following url:
www.domain/Home/ActionName?name=test&age=21


text:
Q: Extending S/4HANA OData service to SCP I want to extend a custom OData service created in a S/4HANA system. I added a Cloud Connector to my machine, but I don't know how to go from there. The idea is that I want people to access the service from SCP and that I don't need multiple accounts accessing the service on the S/4 system, but just the one coming from SCP. Any ideas?

A: Ok I feel silly doing this but it seems to work. My test is actually inconclusive because I don't have a cloud connector handy, but it works proxy-ing google.
I'm still thinking about how to make it publicly accessible. There might be people with better answers than this.

*

*create the cloud connector destination.

*make a new folder in webide

*create file neo-app.json.

content:
{
    "routes": [{
        "path": "/google",
        "target": {
            "type": "destination",
            "name": "google"
        },
        "description": "google"
    }],
    "sendWelcomeFileRedirect": false
}

path is the proxy in your app, so myapp.scp-account/google here. the target name is your destination. I called it just google, you'll put your cloud connector destination.

*Deploy.

My test app with destination google going to https://www.google.com came out looking like this. Paths are relative so it doesn't work but google seems proxied.
You'll still have to authenticate etc.


text:
Q: PHP CURL returning different result from CURL for Linux I'm trying to work out why a call to a web service isn't returning the results I need.
Using CURL for Linux with
curl -i -H "Accept: application/json" "https://www.thisapi.com/stuff/?status=something" > myfile.txt

I get the correct results, an object starting: {"object_count": 4, ...
Using PHP with libcurl and
$curl = curl_init();
$hdr[] = 'Content-type: application/json';
$hdr[] = 'Accept: application/json';

curl_setopt($curl, CURLOPT_HTTPHEADER, $hdr);

$url = 'https://www.thisapi.com/stuff/?status=something';
curl_setopt($curl, CURLOPT_URL, $url);

//return the data
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$results = curl_exec($curl);

Ignores the URL variable "status" and I get {"object_count": 8 ...
Can anyone help me to work out in which ways these two requests are not equivalent and therefore why they are not returning the same results?

A: In the second case you have an additional header you are sending - Content-type: application/json. Perhaps this is causing the API endpoint to respond differently, ignoring the parameter in the URL, as it is expecting something in JSON format.


text:
Q: Implicit termination of start conditions in flex without using `unput()` Let's say I'm parsing hexadecimal numbers in flex. I have something like this:
%x hexnumber
%%
"0x"                { BEGIN hexnumber }
<hexnumber>[0-9A-F] { process_digit(); }

This works fine; the 0x prefix starts hex-parsing mode, and then each digit is processed in turn.
The problem is that a hex constant doesn't have an explicit terminator token. So, how do I switch back to the INITIAL state? By the time I know that the next character isn't part of the numeric constant, it's been consumed.
I can always push it back onto the input stream with unput():
<hexnumber>.        { unput(*yytext); BEGIN INITIAL; }

...but I'd very much prefer not do this (because of implementation details beyond the scope of this question using unput() is very expensive for me).
I know that the generated state machine is capable of automatically switching back to the INITIAL state without consuming the next character, because otherwise rules like [0-9A-F]+ wouldn't work. Is there a way to achieve this using explicit start conditions?

A: Use yyless(0) instead of unput(*yytext); yyless is essentially free since it only adjusts a couple of pointers. It makesno attempt to reallocate or move the input buffer. (You also need BEGIN(INITIAL), of course.)
A much messier solution would be to use trailing context to distinguish between hex characters followed by other hex characters:
 [[:xdigit:]]/[[:xdigit:]]    process_digit();
 [[:xdigit:]]                 process_digit(); BEGIN(INITIAL);

But that is a lot less flexible.


text:
Q: Where to find a direct link or torrent for Ubuntu Gnome ALTERNATE ISO? I can't find any place to download Ubuntu Gnome 14.04 LTS in alternate ISO version.
Doesn't it exist ?

A: As of at least 14.04, alternate ISOs are only built for Lubuntu.

A: It is clearly linked on the Get Ubuntu GNOME page. There are no "alternate" ISO images for derivatives, generally.


text:
Q: How to initialize Flowplayer HTML5 in Javascript I am building an html page with a player. I get the video url and cover url by a remote service. I would know if it is possible (and how to do) to initialize the flowplayer in javascript without change with jquery the url and the cover about the video
 <div class="flowplayer" id="modern" data-key="" style="display:none;  background: #000 url(cover.jpg) 0 0 no-repeat; background-size: cover;"
 data-swf="lib/flowplayer5.5.2/flowplayer.swf"
 data-advance="false">
     **<video id="video" controls>
           <source id="videoSource" type="video/mp4"src="video.mp4">
     </video> </div>**

I did this:
$("#player").flowplayer({

                        swf:'lib/flowplayer5.5.2/flowplayer.swf',
                         splash: true,
                         ratio: 9/16,
                         clip: {
                           sources: [
                              { type: "video/mp4",
                                src:  url }
                            ]
                          }
                        });

I obtain this error: Cannot read property 'initialSources' of null


text:
Q: Should I store access and refresh token independently for multiple clients in google oauth2? I am building google oauth2 for my application. For now I am starting with web client and planing for mobile client in future.
While storing refresh and access token in backend I am storing tokens as refresh_token_web and access_token_web so that it will be clear that these tokens are for web client. Basically tokens are stored independently for each type of client.
As I understand tokens are given for application and not for specific client. If user does oauth2 using mobile client will refresh_token_web still work or it will be out of scope?
Am I doing right thing by storing tokens independently? Anyone has faced any issue with this approach?

A: As I understand tokens are given for application and not for specific client
First you need to differentiate roles involved in an OAuth scenario. According to the specification, client is an application which require tokens to access protected resources.
And then there's an resource owner who own the true resource. In most of the scenarios this will be a human user like you and me. But sometimes there are OAuth grants which allow token issuing for a client. For example Client Credentials Grant issue token to client.
So to answer your question, first you need to differentiate the grant that you are using. If your application simply use tokens issued to it, then you can simply use set of tokens of that application in the backend. But if it involved end users, then you need to differentiate token per user.
Usually, your users should have a unique identifier (ex:- email is one such). So you may create two entries to store refresh tokens of both applications (web and mobile) separately against the unique foreign key (which is the user ID). Also read through a related answer which discuss a similar subject from here.


text:
Q: Why is this matrix diagonalizable? $$
A=
\begin{bmatrix}
0 & 0 & 0 \\
0 & 0 & 0 \\
0 & 0 & 0
\end{bmatrix}
$$
I know that is symmetric, but to diagonalize it we want to invert the matrix for $$P^{-1}AP=D$$ But we can't find the determinant of matrix A because $$\frac{1}{det(A)}$$ the denominator is zero.
Why is matrix A diagonalizable?

A: It is already a diagonal matrix. So P is the identity matrix.

A: We have $P^{-1}AP=D$ with $D=A$ and $P=I_3$
$A$ is a diagonal matrix, hence diagonalizable.

A: Let $v$ a vector in $\mathbb{R}^3$, then
$$
A v = 0 v
$$
So $0$ is an eigenvalue of $A$. The eigenvalues of $A$ are all zeros, while the eigenvectors are arbitrary, you can use the vectors of the base so that $P = I_3$


text:
Q: Using the same connection on AMPPS and MySQL Workbench I am using AMPPS 3.2 and MySQL Workbench 5.2.31 on Windows 7.
I have installed MySQL as a service, running "C:\Program Files (x86)\Ampps\mysql\bin\mysqld.exe" install in Administrator mode, and I have started it manually. It was successfully done because I can use PHPMyAdmin, and AMPPS shows MySQL working.
The problem is with MySQL Workbench. There is the same connection configured in it, but when I try to connect, the following error appears:
Your connection attempt failed for user 'root' from your host to server at localhost:3306: Access denied for user 'root@localhost' (using password: NO)
What can be wrong?

A: I was able to fix this issue by selecting MySQL Fabric Management Node in Connection Method dropdown.
Click "Test Connection" button.


text:
Q: Is there a way to find out if an iPhone / iPad app is installed already? I'm writing a freeware version of an app and would like to check if a user already has the unfree version installed, and print a message whose contents are conditional on the results of the installation check... anybody know if this is possible?
the closest I've come to a solution is to make use of the CFPreferencesSetValue API with a kCFPreferencesAnyUser / kCFPreferencesCurrentHost pairing... I haven't tried it, but based on the documentation it sounds possible.
however in my current specific situation this API will not be able to solve my problem, because I want to check for the presence of an app I wrote 4 months ago that didn't write any data to the CFPrefs registry... because back then I didn't know of it nor did I foresee this situation arising...  the only way CFPrefs can assist me is in future apps now that I know it exists :)
so I'm wondering if there are other ways to do it?   any help will be appreciated :)

A: You can register a custom URL scheme for your existing application and then call canOpenURL in your new application to detect if the application is installed.

A: According to this answer, if you have the same top level app id you can access your other app's data area.  I believe wild-card app id's can also share data, see the provisioning portal docs.

A: You can share data between applications via the keychain. Write data in the full app and check from the free one or vice versa.

A: Hi i have been researching on this topic for a few months i found out this.
There is no authentic way to detect all apps installed in your device that is not jail broken.
For doing it what i did was, I used this statement.
if( [[UIApplication SharedApplication] canOpenURL:(the apps scheme)] )
{
NSLog(@"App found");
}

You can find a list of schemes in the below sites.
This one has a json api too.
http://schemes.zwapp.com/
http://schemes.zwapp.com/.json?page=1  to http://schemes.zwapp.com/.json?page=470  incrementally.
This one has very famous app schemes and example of usage too
http://handleopenurl.com/
The better way to look into it
https://github.com/danielamitay/iHasApp

A: Sorry, no, there is no way for an app to find out information about any other app installed in an iPhone (without jailbreaking).  Apple intentionally sandboxes the apps so they are completely isolated.
The best possible thing you could do (in the future) is register a URL handler that would launch your other app, and in turn would re-launch your current app with a parameter.
-dan