text:
Q: Why Twitter Typeahead doesn't work with React js? I'm currently using Twitter Typeahead in my React Project and i would like to display suggestions based on Typeahead but i can't manage to make it work.
Below my code :
var Search = React.createClass({
    getInitialState: function () {
        return {query: ''};
    },
    handleChange: function (e) {
        this.setState({query: e.target.value});
    },
    componentDidMount(){
        var suggestions = {
            query: "d",
            results: [
                {name: "first"},
                {name: "second"},
                {name: "third"},
                {name: "fourth"}
            ]
        };

        var suggests = new Bloodhound({
            datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            limit: 10,
            local: suggestions
        });

        var template = _.template('<%= name %>');

        $(React.findDOMNode(this.refs.suggestion)).typeahead({
                hint: true,
                highlight: true,
            },
            {
                name: 'suggests',
                displayKey: 'name',
                source: suggests.ttAdapter(),
                templates: {
                    suggestion: function (data) {
                        return template(data);
                    }
                }
            });
    },
    render() {
        <form action="myAction" method="GET">
            <input name="q" id="query" ref="suggestion" className="form-control suggestions" type="text"
                   value={this.state.query}
                   onChange={this.handleChange} onBlur={this.handleChange}/>
        </form>
    }

});

Based on my code, what do i need to add or change to be able to get autocompletion & suggestions working on my project. Thanks a lot for your valuable advice & help.

A: The following are missing

*

*Initialize bloodhound

*Render method is missing a return

*bloodhound local option should take suggestions.results and not just suggestions

var Search = React.createClass({
  getInitialState: function() {
    return {
      query: ''
    };
  },
  handleChange: function(e) {
    this.setState({
      query: e.target.value
    });
  },
  componentDidMount: function() {
    var suggestions = {
      query: "d",
      results: [{
        name: "first"
      }, {
        name: "second"
      }, {
        name: "third"
      }, {
        name: "fourth"
      }]
    };

    var suggests = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      limit: 10,
      local: suggestions.results
    });

    suggests.initialize(); // <----- THIS ONE

    var template = _.template('<%= name %>');

    $(React.findDOMNode(this.refs.suggestion)).typeahead({
      hint: true,
      highlight: true,
    }, {
      name: 'suggests',
      displayKey: 'name',
      source: suggests.ttAdapter(),
      templates: {
        suggestion: function(data) {
          return template(data);
        }
      }
    });
  },
  render: function() { // <---- MISSING A RETURN HERE
    return (<form action="myAction" method="GET">
                <input name="q" id="query" ref="suggestion" className="form-control suggestions" type="text"
                       value={this.state.query}
                       onChange={this.handleChange} onBlur={this.handleChange}/>
            </form>);
  }

});

Here is a demo http://jsbin.com/vubehe/edit?html,output


text:
Q: How do you consume WCF services from a console app using Autofac? So I have a console application in which I am using Autofac.
I have set up my console application as follows:
I have a class I call ContainerConfig - In this I have all my builder registrations:
public static class ContainerConfig
{
    public static IContainer Configure()
    {
        var builder = new ContainerBuilder();

        builder.Register(c => new MatchRun()).As<MatchRun>).SingleInstance();

        builder.RegisterType<AuditLogic>().As<IAuditLogic>();
        builder.RegisterType<AuditRepository>().As<IAuditRepository>();

        builder.RegisterType<ValidationLogic>().As<IValidationLogic>();

        return builder.Build();
    }
}

I call my main applcation as follows:
    private static void Main(string[] args)
    {
        var container = ContainerConfig.Configure();
        using (var scope = container.BeginLifetimeScope())
        {
            var app = scope.Resolve<IApplication>();

            app.Run(args);

        }
    }

The issue is that I have a connected WCF service.  This is my AuditRepository. (FYI - I have not touched WCF for years so I have forgotten most of what I knew).
Its currently constructed to create and dispose of the the proxy each time I make a call to that client.   This functions - mostly.
Looks like this:
    public string GetStuff(string itemA, string itemB)
    {
        try
        {
            GetProxy();
            return _expNsProxy.GetStuff(itemA, itemb);
        }
        catch (Exception ex)
        {
            IMLogger.Error(ex, ex.Message);
            throw ex;
        }
        finally
        {
           // CloseProxyConn();
        }
    }

What i am wondering is can I do this better with Autofac - creating a single instance vs the constant open close - or am I just totally crazy? I know I am not fully asking this the right way - not 100% sure how to actually word the question.
Thanks

A: The approach to always create a new proxy and close it after each call is good for WCF.
Otherwise you can run into issues. For example if one service call fails the channel created by the proxy goes into a faulted state and you can not do more calls on it just abort it. Then you need to create a new proxy. Also you can have threading issues if you call the same proxy from multiple threads simultaneously.
Check also this documentation with a sample of how to handle errors correctly when calling WCF services.
There is an Autofac.Wcf package that can help you with the creation and freeing of channels. Check the documentation here. It uses the dynamic client generation approach where you just give the interface of your WCF service and it generates the channel based on the interface. This is a bit more low level approach so you will have to understand more what is going on. The generated client class does this for you in the background.
You need two registrations one for the channel factory that is a singleton:
builder
  .Register(c => new ChannelFactory<IYourWcfService>(
    new BasicHttpBinding(), // here you will have to configure the binding correctly
    new EndpointAddress("http://localhost/YourWcfService.svc")))
  .SingleInstance();

And a factory registration that will create the channel from the factory every time you request the service:
builder
  .Register(c => c.Resolve<ChannelFactory<IYourWcfService>>().CreateChannel())
  .As<IIYourWcfService>()
  .UseWcfSafeRelease();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Should I locally store CSS generated by the Google Web Fonts API? I am using some Google Web Fonts. I hear that Google deal with all the issues between different browsers and serve different media depending on the browser in the request header.
My question is, at what point does it do this?
Reason being is that for the API you can simply include a CSS file which contains the @font-face request. Can I simply include that CSS in my own CSS file, thereby saving a HTTP request, or does that CSS change depending on the browser that requests it?
I really hope that makes sense.
E.g., Google suggest you include the following in your CSS file:
@import url(http://fonts.googleapis.com/css?family=Exo);
the contents of which are:
@font-face {
  font-family: 'Exo';
  font-style: normal;
  font-weight: 400;
  src: local('Exo Regular'), local('Exo-Regular'), url('http://themes.googleusercontent.com/static/fonts/exo/v1/ZcGd2dvMSgl3mHN3lKAjNw.woff') format('woff');
}

A: Not an answer to your exact question, but even if it were possible at the moment, I would never locally cache any CSS that Google serves "live" because:

*

*even if it works now, it may break later if they change something

*you do not add any reliability, because the font itself still has to be fetched from Google

*you do not really improve performance much: if everything is configured correctly, the HTTP request will happen only once and be cached thereafter. Also, the user may have the font CSS cached from another site that uses Google Fonts.

A: The CSS served up by Google Webfonts changes depending on the user agent in the HTTP request header, so you'd be better off using @import. The reason is the different implementations of web fonts in different browsers.

A: If you want to store local CSS then you MUST store font locally too because otherwise it will again have an extra HTTP request.
And Google allows downloading font for local usage but you can check for web too.
https://developers.google.com/webfonts/faq


text:
Q: Float: right not working properly in Firefox addon Code I am working with a Firefox add-on in which i need a button in the right of a panel for which i am using the float:right style attribute but when i use this attribute the button aligns right and the text area located under it disappears however when i run the code without the float right attribute the code works fine.
Here is the code where i have used the float right attribute.

<head>
    <style type="text/css" media="all">
      textarea {
        margin: 2% 5%;
        width:90%
      }
    </style>
  </head>

<body>
    Email Arrieved
    <input type="button" id ="clearall" value="Respond" style="float: right;>
    <textarea rows="4" id="edit-box" ></textarea>
  </body>

</html>

Desired output is that i should be that the text with the button should be left align and the button should be right aligned with the text-area located under them.
Am coding for an addon in Firefox so is there some specific function to do this or there is something wrong with the css.

A: You forgot to close the style attribute value. Is that it ? Looks fine here.

      textarea {
        margin: 2% 5%;
        width:90%
      }
    Email Arrieved
    <input type="button" id ="clearall" value="Respond" style="float: right";>
    <textarea rows="4" id="edit-box" ></textarea>


text:
Q: How to exclude character " in a token JavaCC Hello i´m working with JavaCC and I am writing a token that put one String between " ". Context:
void literalString(): {} { """ (characteresString())? """ }
void characteresString(): {} { <characterString> | characteresString() <characterString> }

So i made this token to put one String:
TOKEN : {<characterString : ~["\", "] >}

The problem is I don´t know how to exclude the " symbol in the token, if I put """ it gives me error, if i put one " error again.
Thank you in advance

A: Instead of
void literalString(): {} { """ (characteresString())? """ }

use a token definition
TOKEN : { <STRING : "\"" (<CHAR>)* "\"" >
        | <#CHAR : ~["\""] > // Any character that is not "
}

Now this defines a string to be a ", followed by zero or more characters that are not "s, followed by another ".
However some languages have further restrictions, such as only allowing characters in a certain range. For example if only printable ascii characters excluding "s where allowed, then you would use
TOKEN : { <STRING : "\"" (<CHAR>)* "\"" >
        | <#CHAR: [" ","!","#"-"~"]> // Printable ASCII characters excluding "
}

But, say you want to allow " characters if the are preceded a by \ and you want to ban \ characters unless they are followed by a " or another \ or an n. Then you could use
TOKEN : { <STRING : "\"" (<CHAR> | <ESCAPESEQ>)* "\"" >
        | <#CHAR: [" ","!","#"-"[","]"-"~"] > // Printable ASCII characters excluding \ and "
        | <#ESCAPESEQ: "\\" ["\"","\\","n"] > // 2-character sequences \\, \", and \n
}


text:
Q: Convert Column Timestamp to Date Time I have  a dataframe that has a column with a TimeStamp. The data in this column is float64
timestamp
1582574539
1582574454
1582573814
1582573499
1582573234

I want to convert this column to DateTime or add a new column with the readable DateTime
DateTime
2/24/20 14:52
2/24/20 14:50
2/24/20 14:46

I tried the following code -
df1['DateTime'] = datetime.fromtimestamp(df1.timestamp)

And got the following errors -
TypeError("cannot convert the series to " "{0}".format(str(converter)))
TypeError: cannot convert the series to <class 'int'>


text:
Q: Regarding recursive file run and replace the main content of input file sed "s/eth0/$change/" <  ifcfg-eth0

Our file contains:
DEVICE=eth0

I want to replace the eth0 with any input I enter, every time I run the program.
To be specific, the above mentioned command does the following:
Every time I run my program, it asks to enter the value which we want in order to replace eth0. It does replace it once but the next time I run the script, it does not work because it no longer has eth0 as a pattern in the file which it can change.
sed -i will only make the changes once but i need it recursively..

A: You don't mean "recursively" you mean more than once. And your problem is that you are matching the wrong thing.
Don't match the value you want to change match the line you want to change.
Match /^DEVICE=/ that is and replace the part of the line you care about or the whole thing.

A: file.txt:
DEVICE=eth0

Try this:
$ change=wlan0
$ sed -r "s/(.*=).*/\1$change/" file.txt
DEVICE=wlan0
$ change=eth0
$ sed -r "s/(.*=).*/\1$change/" file.txt
DEVICE=eth0

A: Use sed -i "s/^DEVICE=\(.*\)/DEVICE=$change/" ifcfg-eth0. This should replace the any pattern after DEVICE= with $change.


text:
Q: Is it possible to save multiple data to a database column Hi all i have my database structure as follows
 Field        Type
FileHeader    longblob
BatchHeader   longblob
Entry         longblob
BtchEntry     longblob
FileControl   longblob

I will have the data to be inserted is as follows
101 111111111 1111111111104021031A094101
52201               1                   1         PPD1         110402110402   1111000020000001
6221110000251                00000000011              1                     1 0111000020000001
822000000100111000020000000000000000000000011                                  111000020000001
52251               1                   1         CCD1         110402110402   1111000020000002
6281110000251                00000000011              1                     1 0111000020000002
822500000100111000020000000000010000000000001                                  111000020000002
9000006000001000000060066600012000000000003000000000003

as you can observe there are multiple lines that starts with 5,6 and 8. I would like to save those individually to the corresponding columns of my table. Is it possible to do if so can any mention the best method to do it. If unclear please specify
The code i written is
 using (StreamReader srRead = new StreamReader(filePath))
    {
        while (srRead.Peek() >= 0)
        {
            strLine = srRead.ReadLine();
            if (strLine.StartsWith("1"))
            {
                strFileHeader = strLine;
            }
            if (strLine.StartsWith("5"))
            {
                strBatchHeader = strLine;
            }
            if (strLine.StartsWith("6"))
            {
                strEntry = strLine;
            }
            if (strLine.StartsWith("8"))
            {
                strBtchcntrl = strLine;
            }
            if (strLine.StartsWith("9"))
            {
                strFileCntrl = strLine;
            }
        }

  string strQuery = "insert into tblfiles(FName, FData,FileHeader,BatchHeader,Entry,BtchEntry,FileControl) values (@_FName,@_FData,@_FileHeader,@_BtchHeader,@_EntryDets,@_BtchCntrl,@_FileCntrl)";
        MySqlCommand cmd = new MySqlCommand(strQuery);
        cmd.Parameters.Add("@_FName", MySqlDbType.VarChar).Value = filename;
        cmd.Parameters.Add("@_FData", MySqlDbType.LongBlob).Value = bytes;
        cmd.Parameters.Add("@_FileHeader", MySqlDbType.LongBlob).Value = strFileHeader;
        cmd.Parameters.Add("@_BtchHeader", MySqlDbType.LongBlob).Value = strBatchHeader;
        cmd.Parameters.Add("@_EntryDets", MySqlDbType.LongBlob).Value = strEntry;
        cmd.Parameters.Add("@_BtchCntrl", MySqlDbType.LongBlob).Value = strBtchcntrl;
        cmd.Parameters.Add("@_FileCntrl", MySqlDbType.LongBlob).Value = strFileCntrl;
        InsertUpdateData(cmd);

But this will insert the latest to the DB but i would like to save each and every line as per i stated

A: No - a column can only store one value per row. You could combine all your batch headers into one blob and store that as a single value, but you would have to be able to split them apart again when your read the data.
Instead - it looks as though:

*

*each file starts with a '1' record and ends with a '9' record

*each file contains zero or more batches

*each batch starts with a '5' record and ends with an '8' record

*each batch contains zero or more entries ('6' records)

If that is all correct, then you need 3 tables that would look something like:
File table:
Field         Type
-----------   --------
FileID        integer   # unique file ID - see AUTO_INCREMENT in the MySQL reference
FName         varchar
FData         longblob
FileHeader    longblob  # '1' record
FileControl   longblob  # '9' record

Batch table:
Field         Type
-----------   --------
FileID        integer   # references a row in the File table
BatchID       integer   # unique batch ID
BatchHeader   longblob  # '5' record
BatchControl  longblob  # '8' record

BatchEntry table:
Field         Type
-----------   --------
BatchID       integer   # references a row in the Batch table
EntryId       integer   # unique file ID
Entry         longblob  # '6' record

That should get you started. Good luck.

A: Why don't you use Stringbuilder and append the required lines to that string builder and write them to the DB instead of using strings. Seperating each column will be a tough one to retrieve the data if you need. So declare a string builder and append the lines to each and every one you required and after all write to the DB
string strFileHeader = string.Empty;
StringBuilder strBatchHeader=new StringBuilder();
StringBuilder strEntry=new StringBuilder();
StringBuilder strBtchcntrl=new StringBuilder();
string strFileCntrl = string.Empty;

using (StreamReader srRead = new StreamReader(filePath))
    {
        while (srRead.Peek() >= 0)
        {
            strLine = srRead.ReadLine();
            if (strLine.StartsWith("1"))
            {
                strFileHeader = strLine;
            }
            if (strLine.StartsWith("5"))
            {

                strBatchHeader.AppendLine(strLine);
            }
            if (strLine.StartsWith("6"))
            {
                strEntry.AppendLine(strLine);
            }
            if (strLine.StartsWith("8"))
            {
                strBtchcntrl.AppendLine(strLine);
            }
            if (strLine.StartsWith("9"))
            {
                strFileCntrl = strLine;
            }
        }

 string strQuery = "insert into tblfiles(FName, FData,FileHeader,BatchHeader,Entry,BtchEntry,FileControl) values (@_FName,@_FData,@_FileHeader,@_BtchHeader,@_EntryDets,@_BtchCntrl,@_FileCntrl)";
        MySqlCommand cmd = new MySqlCommand(strQuery);
        cmd.Parameters.Add("@_FName", MySqlDbType.VarChar).Value = filename;
        cmd.Parameters.Add("@_FData", MySqlDbType.LongBlob).Value = bytes;
        cmd.Parameters.Add("@_FileHeader", MySqlDbType.LongBlob).Value = strFileHeader;
        cmd.Parameters.Add("@_BtchHeader", MySqlDbType.LongBlob).Value = strBatchHeader.ToString();
        cmd.Parameters.Add("@_EntryDets", MySqlDbType.LongBlob).Value = strEntry.ToString();
        cmd.Parameters.Add("@_BtchCntrl", MySqlDbType.LongBlob).Value = strBtchcntrl.ToString();
        cmd.Parameters.Add("@_FileCntrl", MySqlDbType.LongBlob).Value = strFileCntrl;
        InsertUpdateData(cmd);


text:
Q: How to forward headers using FastAPI - Tracing use cases Below is simple server written with FastAPI and running with Uvicorn.
In order to send the value to the next hop, the '/destination' url, I need to pass the value to the forward_request method.
In this implementation, passing the value is easy, because the calls' depth is just 1 function more.
But if I have a function that calls a function that calls a function...., I need to pass the value again and again and...
Is there a simpler way to share the value downstream without passing it?
Is there a way, without using inspect or some dark magic, to understand what is the scope that the function forward_request lives in?

Why am I asking this question?
I am using Jaeger for tracing and I need to forward the header x-request-id that I receive in the 1st server (/source in this example) to the 2nd server (/destination in this example).
If FastAPI\Uvicorn processed just 1 request at a time, I could have shared the value as a singleton class and access it from anywhere, but since requests are handled in parallel, the function forward_request doesn't have the context of who called it.

Some black magic
Function forward_request can inspect the call stack and figure from it, what is the value that was received, but that is one ugly way to do things.

Server Code
import asyncio

import aiohttp as aiohttp
from fastapi import FastAPI, Request
import uvicorn

from datetime import datetime

app = FastAPI()

@app.get("/source")
async def route1(value: int, request: Request):
    print(f'source {value}')
    start = datetime.now().strftime("%H:%M:%S")
    await asyncio.sleep(5)
    resp: dict = await forward_request(value)
    end = datetime.now().strftime("%H:%M:%S")
    return {
        "start": start,
        "end": end,
        "value": value,
        "resp": resp
    }

@app.get("/destination")
async def route2(value, request: Request):
    print(f'destination {value}')
    start = datetime.now().strftime("%H:%M:%S")
    await asyncio.sleep(5)
    end = datetime.now().strftime("%H:%M:%S")
    return {
        "start": start,
        "end": end,
        "value": value
    }

async def forward_request(value: int) -> dict:
    async with aiohttp.ClientSession() as session:
        async with session.get('http://127.0.0.1:5000/destination', params={'value': value}) as resp:
            resp = await resp.json()

    return resp

if __name__ == "__main__":
    uvicorn.run("main2:app", host="127.0.0.1", port=5000, log_level="info", workers=1)


text:
Q: C++ Warning Array Subscript Has Type 'char' I require some help with code that throws a 'Warning array subscript has type 'char' [-Wchar-subscripts]' message.
The code in question is:-
static
const long hextable[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-19
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 30-39
    -1, -1, -1, -1, -1, -1, -1, -1, 0, 1,
    2, 3, 4, 5, 6, 7, 8, 9, -1, -1, // 50-59
    -1, -1, -1, -1, -1, 10, 11, 12, 13, 14,
    15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 70-79
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, // 90-99
    13, 14, 15, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 110-109
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 130-139
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 150-159
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 170-179
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 190-199
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 210-219
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 230-239
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1
};

long hex2long(const char* hexString)
{
    long ret = 0;
    while (*hexString && ret >= 0)
    {
        ret = (ret << 4) | hextable[*hexString++];
    }
    return ret;
}

Now it appears that the line ret = (ret << 4) | hextable[*hexString++]; has issues.
I am hoping someone can assist me re-structuring this code to prevent the error.

A: Change const char* to const unsigned char*.
From GCC Warnings:

-Wchar-subscripts Warn if an array subscript has type char. This is a common cause of error, as programmers often forget that this type is signed on some machines. This warning is enabled by -Wall.

The compiler doesn't want you to use negative indices for the array, so it throws a warning to let you know of this potential problem.


text:
Q: Will the netinstall (minimal) work with a USB cellular modem? Installing Ubuntu minimal is extremely easy when the system has a LAN card and connected to internet via Cable & Router...
I Recently came across a situation where I needed to install Ubuntu Minimal on a system which wash not having a LAN card and cable internet anywhere around...
The only access to the internet was through a USB Plug n Play Data-Card Modem.
May anyone suggest something so that I may install Ubuntu Minimal using USB Modem as the only source of Internet, if it's possible at all?? (This relates to Ubuntu 12.04 in specific)

A: Sorry, the minimal image includes only wired drivers and limited wireless (WiFi) support. What you want is not possible with the default mini.iso, although you can of course remaster it to include the necessary modules. Use the expert install, so you can drop to a shell (busybox) before the network detection part and load the modules, set the IP, etc.


text:
Q: Is there a D plugin currently available for Xcode 4.3? Is there a D plugin currently available for Xcode 4.3? I tried to follow the link provided on the wiki, but the link (http://michelf.com/projects/d-for-xcode/) appears to be broken*. I did a search on Github and the project in question hasn't been updated since early last year (March 28, 2011).
Update:
[*] It seems it was just me, I've check again and it loads fine.

A:
To Xcode 4 users: D for Xcode is only partially working with Xcode 4 currently; version 3 of Xcode is fully supported.

It seems not - I'll edit this answer if full support comes back. Till then I've been using SublimeText (it only has highlighting - autocomplete or precompile checking).


text:
Q: Broken BIOS, refreshing SATA drives list after hot plug Just messing around with my new system and finding myself stuck.
What I have :

*

*Windows 10 UEFI installed on my first SATA drive, let's call it drive1 (i.e. : drive1 has an ESP partition)

*xUbuntu x64 on a flash drive

*3 spare SATA drives with 1TB of unallocated memory (let's call them drive2, 3, and 4)

*a broken BIOS which keeps me from modifying boot order.

What I want :

*

*xUbuntu UEFI installed on drive1

*drive2, drive3, and drive4 formatted and mounted within xUbuntu

*the system to UEFI boot into drive1 xUbuntu

*no Win10 at all!

In order to boot into live xUbuntu I have to boot with drive1 unplugged (if not, sys fall into Win10 ; broken BIOS, remember).
When re-plugging drive1 afterward and running gParted in live xUbuntu the software just won't see the hot plugged SATA drive.
How do I force "rescan" for the whole four SATA drives once hot plugged ? Is this even possible after boot?
If not, how do I get rid of Win10 and its ESP partition / replace Win10 with xUbuntu?
Am I running in circles here ? Is there a simpler solution ?
I thought about uefi-installing xUbuntu onto drive2 (with drive1 unplugged) and then reboot with the four drives plugged, but then sys will have two conflicting ESP partition...

A: If I understand correctly, you don't want to preserve any data on any of your disks. If so, the easiest solution is to use Windows to delete all of the partitions on all of the disks. The computer will then be unable to boot from any of those disks and should boot to your USB Ubuntu installation medium.
Also, there's a good chance that the firmware isn't really defective, but has damaged NVRAM entries. If so, then booting into it (via a boot-time keystroke or by typing systemctl reboot --firmware-setup in Ubuntu -- but the latter doesn't always work) and picking an option to reset all settings to their default may fix the problem. You should do this before installing Ubuntu, since this action often removes all the existing NVRAM boot entries. (That's the point, really; if entries are corrupted, removing them will fix the problem.)
For further background reading, I recommend:

*

*Adam Williamson's blog entry on how EFI works -- This page describes the theory behind EFI-mode booting.

*My page on installing Linux on EFI systems -- This page is a more practical introduction to EFI-mode booting than Adam Williamson's blog.

*My page on the CSM -- This page covers the CSM, including when it's useful and when it's not.

*The Ubuntu community wiki entry on UEFI -- This page is a bit disjointed, but is the most Ubuntu-specific introduction to EFI and its issues.


text:
Q: Specification Pattern Example After reading a series of blogs (here and here) by Chris Missal from LosTechies.com on the Specification Pattern I am am really interested in finding more complete examples. Does anyone know where I could find a more fleshed out example or perhaps an open source project that uses this pattern?

A: I actually think the Wikipedia page (at the time of this post) is a more concise and easier to absorb example of using the Specification pattern...lostechies.com actually references it.
Here is the link: Wikipedia: The Specification Pattern

A: Also take a look at the Dimecasts 'Learning the Specification pattern' for a walkthrough of an example.
Having learned the Specification pattern through the same blogs as you listed, I'm not yet convinced.  It could just be that the examples are too simplistic so it seems more work that it's worth.  A good, extensive example that shows come genuine benefit would be nice.

A: Take a look at the "Specifications" paper authored by Eric Evans and Martin Fowler.
The following blog article - "The Specification Pattern" - might also be of use to you.

A: For me one of the best examples is the Route Specification that Eric Evans uses on his book.
The source code is here, it is written in Java but is very easy to understand and translate to C#.

A: You can find many sample projects about design patterns (Specification Pattern as well) here from "Professional ASP.NET Design Patterns" book.


text:
Q: How does the setter of a Core Date attribute manage memory? Does a setter of a CoreData-attribute retains? or copies the value or what does the setter? I want to know if I have to (auto-)release the value that I am putting into the setter.
I've done some quick tests on that. Assuming the following model:
+----------+
| Class A  |
+----------+
| v :int32 |
+----------+

The generated ManagedObject then looks like this:
//A.h
@interface A :  NSManagedObject
{
}
@property (nonatomic, retain) NSNumber * v;
//...

//A.m
@implementation A
@dynamic v;
...

Ok, the property is marked with retain, so if I set a NSNumber to v the NSNumber should be retained. but it is not (I think). I did the following:
A *a = ... ;
NSNumber *retainCheck = [[NSNumber alloc] initWithInt:23];
NSLog(@"retainCheck1: %i",[retainCheck retainCount]);
a.v = retainCheck;
NSLog(@"retainCheck2: %i",[retainCheck retainCount]);
NSLog(@"retainCheck3: %i",[a.v retainCount]);
NSLog(@"pointer1: %#x",retainCheck);
NSLog(@"pointer2: %#x",a.v);

this produces the following output:
retainCheck1: 1
retainCheck2: 1
retainCheck3: 1
pointer1: 0x62f068
pointer2: 0x62f068

Both NSNumbers are the same NSNumber-instance (same pointer-value -> so it does no copy or sth like that) and the NSNumber doesn't seem to be retained by the setter.
Am I doing sth. wrong in my test? or is the behaviour of NSManagedObject-setters not the same as described in the header?
edit: I am calling retainCount because I wanted to observer a retain not release or autorelease. The observed behaviour can be explained by the flyweight-pattern linked by Abizern

A: You shouldn't care how a Core Data object manages it's memory, just have faith that it will do so properly.  Looking at the retain count of an object is rarely useful, as it can change depending on many things in the Cocoa SDK.
All you need to do is make sure that for every time you call alloc, retain, new or copy in your code, it is balanced somewhere with an autorelease or release.

A: Firstly - Don't worry about how Core Data manages it's properties - As long as you release the objects that you own, that's what matters.
Secondly - you're testing using NSNumber. NSNumber is a strange class that adopts the flyweight design pattern, so getting the retainCount of an NSNumber isn't going to tell you anything about how Core Data manages its objects.

A: From the Core Data Programming Guide:

In addition to always being nonatomic, dynamic properties only honor retain or copy attributes—assign is treated as retain. You should use copy sparingly as it increases overhead. You cannot use copy for relationships because NSManagedObject does not adopt the NSCopying protocol, and it's irrelevant to the behavior of to-many relationships.

The Core Data @dynamic accessors always retain properties on assignment.
As for the retainCount, don't look at it like that (as @Abizern and @Simon Goldeen already mentioned). The iOS frameworks deal with it in their own way to ensure that the memory management rules hold.


text:
Q: Twitter Bootstrap Popovers not working Here is my HTML:

After 30 Days you'll have the option to keep your account for $15 per month -no contract required-or revert to a single page free account.*

JavaScript:
$('#disclaimer').popover({
  trigger: 'hover',
  html: true,
  placement: 'right',
  content: 'hello world'
});

When I hover over the element, nothing happens.. no JavaScript errors or anything, not sure whats wrong

A: Using your exact code, all I had to do to get it to work was wrap it in a function call and put the script below the div tag.  If you placed your jQuery in an onload function it would work just as well.  Good luck.
Use this:

After 30 Days you'll have the option to keep your account for $15 per month -no contract required-or revert to a single page free account.*

OR
$(document).ready(function()
{
  $('#disclaimer').popover(
  {
     trigger: 'hover',
     html: true,
     placement: 'right',
     content: 'hello world'
  });
});

A: i had been looking for over a day as to why my popover wasn't working after getting autodisabled due to events happening on my page (a complicated app, something that gets enabled/disabled depending on the state of what is going on) and the key was to NOT have it the document ready but to have it out in a function because it gets enabled after document initialization on a button click.


text:
Q: Reading from, and then replacing all the text in a .txt file I'm very new to Python (and coding in general, if I'm honest) and decided to learn by dipping into the Twitter API to make a weird Twitterbot that scrambles the words in a tweet and reposts them, _ebooks style.
Anyway, the way I have it currently set up, it pulls the latest tweet and then compares it to a .txt file with the previous tweet. If the tweet and the .txt file match (i.e., not a new tweet), it does nothing. If they don't, it replaces the .txt file with the current tweet, then scrambles and posts it. I feel like there's got to be a better way to do this than what I'm doing. Here's the relevant code:
words = hank[0]['text']
target = open("hank.txt", "r")
if words == "STOP":
    print "Sam says stop :'("
    return
else:
    if words == target.read():
        print "Nothing New."
    else:
        target.close()
        target = open("hank.txt", "w")
        target.write(words)
        target.close()

Obviously, opening as 'r' just to check it against the tweet, closing, and re-opening as 'w' is not very efficient. However, if I open as 'w+' it deletes all the contents of the file when I read it, and if I open it as 'r+', it adds the new tweet either to the beginning or the end of the file (dependent on where I set the pointer, obviously). I am 100% sure I am missing something TOTALLY obvious, but after hours of googling and dredging through Python documentation, I haven't found anything simpler. Any help would be more than welcome haha. :)

A: I suggest you use yield to compare hank.txt and words line by line so that more memory space could be saved, if you are so focused on efficiency.
As for file operation, I don't think there is a better way in overwriting a file. If you are using Linux, maybe 'cat > hank.txt' could be faster. Just a guess.

A: with open(filename, "r+") as f:
    data = f.read()// Redaing the data
    //any comparison of tweets etc..
    f.truncate()//here basically it clears the file.
    f.seek(0)// setting the pointer
    f.write("most recent tweet")// writing to the file

No need to close the file instance, it automatically closes.
Just read python docs on these methods used for a more clear picture.


text:
Q: Simplifying algorithm testing for researchers. I work in a group that does a large mix of research development and full shipping code.
Half the time I develop processes that run on our real time system ( somewhere between soft real-time & hard real-time, medium real-time? )
The other half I write or optimize processes for our researchers who don't necessarily care about the code at all.
Currently I'm working on a process which I have to fork into two different branches.
There is a research version for one group, and a production version that will need to occasionally be merged with the research code to get the latest and greatest into production.
To test these processes you need to setup a semi complicated testing environment that will send the data we analyze to the process at the correct time (real time system).
I was thinking about how I could make the:

*

*Idea

*Implement

*Test

*GOTO #1

Cycle as easy, fast and pain free as possible for my colleagues.
One Idea I had was to embed a scripting language inside these long running processes.
So as the process run's they could tweak the actual algorithm & it's parameters.
Off the bat I looked at embedding:

*

*Lua (useful guide)

*Python (useful guide)

These both seem doable and might actually fully solve the given problem.
Any other bright idea's out there?
Recompiling after a 1-2 line change, redeploying to the test environment and restarting just sucks.
The system is fairly complicated and hopefully I explained it half decently.

A: If you can change enough of the program through a script to be useful, without a full recompile, maybe you should think about breaking the system up into smaller parts. You could have a "server" that handles data loading etc and then the client code that does the actual processing. Each time the system loads new data, it could check and see if the client code has been re-compiled and then use it if that's the case.
I think there would be a couple of advantages here, the largest of which would be that the whole system would be much less complex. Now you're working in one language instead of two. There is less of a chance that people can mess things up when moving from python or lua mode to c++ mode in their heads. By embedding some other language in the system you also run the risk of becoming dependent on it. If you use python or lua to tweek the program, those languages either become a dependency when it becomes time to deploy, or you need to back things out to C++. If you choose to port things to C++ theres another chance for bugs to crop up during the switch.

A: Embedding Lua is much easier than embedding Python.

*

*Lua was designed from the start to be embedded; Python's embeddability was grafted on after the fact.

*Lua is about 20x smaller and simpler than Python.
You don't say much about your build process, but building and testing can be simplified significantly by using a really powerful version of make.  I use Andrew Hume's mk, but you would probably be even better off investing the time to master Glenn Fowler's nmake, which can add dependencies on the fly and eliminate the need for a separate configuration step.  I don't ordinarily recommend nmake because it is somewhat complicated, but it is very clear that Fowler and his group have built into nmake solutions for lots of scaling and portability problems.  For your particular situation, it may be worth the effort to master it.

A: Not sure I understand your system, but if the build and deployment is too complicated, maybe you could automate it? If deployment is completely automatic, would that solve the problem?
I don't understand how a scripting language would solve the problem? If you change your algorithm, you still need to restart calculation from the beginning, don't you?

A: It kind of sounds like what you need is CruiseControl or something similar; every time hyou touch the baseline code, it rebuilds and reruns tests.


text:
Q: IPhone/Android SMS intercept and redirection to an application Is it possible to intercept an SMS coming from a certain number and direct it to a certain application on the iPhone/Android where it will be processed?
Thanks.

A: In Android, what you can do is register a BroadcastReceiver to be notified that an SMS has been received, mark the message as read in the SMS Content Provider and then delete that specific message from the content provider.  This will prevent any other applications from being able to read the message once you have deleted it and no notifications will be shown in the notification space.  That said, I have no idea what will happen to the applications that receive the Intent indicating that a message has been received but then cannot access it in the database.  This could result in unpredictable behavior as a result of a number of race conditions.

A: Yes. It is possible in Android. I'm doing it in an app I'm developing.
What you need to do is:
public class SMSService extends BroadcastReceiver {
public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private String phoneNumber;
private String sms;
private Context context;

@Override
public void onReceive(Context context, Intent intent) {
    this.context = context;
    if (intent.getAction().equals(SMS_RECEIVED)) {
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;

        if (bundle != null) {
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];

            for (int i = 0; i < msgs.length; i++) {

                msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);

                // get sms message
                sms = msgs[i].getMessageBody();

                // get phone number
                phoneNumber = msgs[i].getOriginatingAddress();

                if (phoneNumber.equals("Some other phone number")){
                    // the sms will not reach normal sms app
                    abortBroadcast();

                Thread thread = new Thread(null,
                        doBackgroundThreadProcessing, "Background");
                thread.start();
                }

            }
        }
    }
}

private Runnable doBackgroundThreadProcessing = new Runnable() {
    // do whatever you want
};

IMPORTANT:
In manifest file you have to define SMS priority with an high number. I believe the max is 100.
<!-- SMS Service -->
    <service android:name=".SMSService" />
    <receiver android:name=".SMSService">
        <intent-filter android:priority="100">
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

A: For Android the answer is no. You can implement a BroadcastReceiver that is called whenever the device receives an SMS text message but cannot keep other applications (e.g. the built-in Messaging app) from receiving them too.

A: For Android the answer is Yes.
android.provider.Telephony.SMS_RECEIVED event is an ordered broadcast and you can tune the priority. This means your application will receive the event before everyone else. And you can cancel Broadcast for the rest of Broadcast Receivers.
You can find more information here: stackoverflow.com/can-we-delete-an-sms-in-android-before-it-reaches-the-inbox/

A: In Android, once you received an SMS message in your application, you can use an Intent object to pass the details of the message to another activity/application for further processing. If you need to pass the message to your own application, use the sendBroadcast() method to broadcast the Intent object. In your activity, you would just need to use the registerReceiver() method to listen for the broadcast.
Hope it helps!
Wei-Meng Lee


text:
Q: CoreData sort by upcoming birthdays I'm building my first app in xcode and trying to fetch a list of people ordered by upcoming birthdays using coreData and NSFetchedResultController. My entity is setup as follows
uBirthdays
--------------
NSString uName
NSDate uBday

Here is my current code:
- (NSFetchedResultsController *)fetchedResultsController {

if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
}

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"uBirthdays" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"uBday" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

[fetchRequest setFetchBatchSize:20];

NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"sectionNameGen" cacheName:@"Root"];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;

[sort release];
[fetchRequest release];
[theFetchedResultsController release];

return _fetchedResultsController;

}

Is it possibly to sort that by upcoming birthdays? or would I have to de-normalize my birthdays so I can sort by month and day only? Any input is greatly appreciated.
Thank you

A: Here's what you can do.
1) Set NSSortDescriptors for your uBDay and uName so your records will be sorted first by birthday, then by name.
2) Create a NSPredicate that pulls all birthdays between [NSDate now] (i.e. today) up to a certain time in the future (i.e. 30 days into the future = [NSDate dateWithTimeIntervalSinceNow:kOneDayTimeInterval*30])
Example code below:
#define kOneDayTimeInterval 86400 // this is in seconds: 86400 = 1 day

    - (NSFetchedResultsController *)fetchedResultsController {
        ...
        NSSortDescriptor *sortByBDay = [[NSSortDescriptor alloc] initWithKey:@"uBday" ascending:YES];
        NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"uName" ascending:YES];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortByBDay,sortByName, nil];
        [fetchRequest setSortDescriptors:sortDescriptors];
        [sortDescriptors release];
        [sortByName release];
        [sortByReleaseDate release];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(uBDay > %@) AND (uBDay <= %@)", [NSDate date], [NSDate dateWithTimeIntervalSinceNow:kOneDayTimeInterval*30]];
        [fetchRequest setPredicate:predicate];
        ...


text:
Q: Does anyone know how we can unit test IBM MQ Message Flows in an isolated way using stubs? I am new to IBM-MQ and trying to understand how we can perform unit testing on message flows.
I am aware of the tools like CA Lisa to do Service Virtualization and testing at system testing level.
But in my case I am looking for the unit testing framework like Java Junit tests where developer can create tests and required stubs to test the IBM MQ Message flows independently.
Thank You in advance.

A: We write integration tests against deployed flows. We use the Spring Testframework and Junit as a base.
Here are some thoughts about our testing:

*

*For synchronous dependencies we either write mock flows that we deploy in a separate IIB application, or we use JUnit helpers for things like SMTP and LDAP.

*For asynchronous dependencies like IBM MQ we use in our tests the JmsTemplate or directly the IBM MQ classes for JMS to send and receive messages. Before each test we clean the queues with PCF messages.

*For file nodes we use the environment variable MQSI_FILENODES_ROOT_DIRECTORY in the real flow and in Junit to easily find the files. We also clean the File input and output directories before each test to start clean.

*To speed up the unit tests and to test things like assert that no message arrived we subscribe in our Junit tests to Monitoring Events. When we receive the Transaction End event we are sure the flow is finished and can assert that a file is there, that no message is on a certain queue, etc.

A: Start using the MQ Messaging REST API Using the messaging REST API available in MQ V9.1.0.0 well actually V9.0.0.4 I believe.
I used to use all sort of workarounds in the past but if you want to just PUT messages on to queues and GET them off them and have MQ 9.1 installed or can install it then you can use the MQ Messaging REST API
An HTTP POST to .../ibmmq/rest/v1/messaging/qmgr/QMGR1/queue/Q1/message will PUT your message on to Q1
An HTTP DELETE to .../ibmmq/rest/v1/messaging/qmgr/QMGR1/queue/Q1/message will GET your message from Q1
I'm using Postman to do this but there is no reason you can't use SoapUI or any of your other favourite test tools.
One caveat at the moment is that you are limited to Text messages but given a very high percentage of messages are XML or JSON or CSV there's a fair chance this may fit the bill for you.

A: Before going to the stage of choosing testing framework, I would suggest choosing a good testing strategy first. With IIB message flow, my suggestion is to do integration unit testing. Here

*

*'Unit testing' means using stubs instead of the Test/QA/Prod APIs for the message flow's dependencies like queues, databases, HTTP APIs, FTP APIs, etc. This is to treat an entire message flow (instead of one piece of it) as a unit. Also this is to isolate the message flow under test, because stubs are 100% controllable during testing.

*'Integration' means multi-process, i.e. the message flow under test is in a process, and the stubs that the message flow interacts with are in other processes. This is unlike the traditional Java JUnit tests where 'mock objects' are typically in the same process (JVM) as the Java method under test.

A critical justification for doing integration unit testing is to deprecate traditional unit testing (for message flows). This is because

*

*It is difficult, if even possible, to create traditional unit test that makes the message flow under test, or parts of the message flow under test, to be in the same process (like JVM) as the stubs.

*There could be requirement from delivery process perspective to do integration unit testing. Many teams have integration design documents for message flows. These documents describe how the message flows interact with their external dependencies (queues, databases, etc.), and the data/message transformations inside the message flows. Developers and project managers are often inclined to test against the design documents, that is, test the message flows interacting with external dependencies, as well as the data/message transformations. Traditional unit testing might be good at testing the data/message transformations, but seems not good at testing the external dependencies interactions.

*To avoid duplicate testing logic and effort, integration unit testing seems a better choice than traditional unit testing.

To carry out integration unit testing strategy, there could be a variety of flavors of testing frameworks/tools that can be used. The factors for choosing one framework/tool could be open source vs commercial, high code vs medium code vs no code, etc.
Here is an example of open source + no code tool for doing integration unit testing: https://apitestbase.io/docs/en/iib-integration-unit-testing. Disclaimer: I am the tool developer.


text:
Q: show user control when button_click event I want to display user control when button_click event.
The user contol declartion is

        <LUC:LoginLoader ID="loginUserControl" runat="server" />

I have tried with
protected void Page_Load(object sender, EventArgs e)
    {

        loginUserControl.Visible = false;
    }

 protected void Button1_Click(object sender, EventArgs e)
    {
        loginUserControl.Visible = true;

        System.Threading.Thread.Sleep(5000);
        ScriptManager1.RegisterPostBackControl(Button1);
        string result = asset.UserLogin(txtloginid.Text, txtpassword.Text);
        if (Convert.ToInt32(result) == 1)
        {
            Session["uname"] = txtloginid.Text;
            Server.Transfer("CreatedInventory.aspx");
        }
        else
        {
            pwdinfo.Text = "Please enter correct password";
            txtpassword.Focus();
        }
    }

but it is not working, please give some suggetions

A: oh got it try this
protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostback)
    {
        loginUserControl.Visible = false;
    }
}

Update : you are using multithreading right, i guess that its getting visible false in some other thread, check that


text:
Q: Page Layout Image-Field Snippet not working I have a problem using an Image Field in a Page Layout. What I did was the following:

*

*Created Image Field

*Created Content Type (inherited from Article Page)

*Added the Field to the Content Type and deployed the solution

*Created Page Layout with the Content Type

*Generated a snippet for the Image Field

Field:
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Field
       ID="{4ea31e74-f59d-4ddf-863c-607a01735f65}"
       Name="pls_H2_2_Image"
       DisplayName="Titel 2 Bild"
       Type="Image"
       Required="FALSE"
       Group="Custom">
  </Field>
</Elements>

Generated Snippet (why did the snippet convert > and < ? If I generate the snippet for Page Image (standard article page field) > and < are shown properly):

Titel 2 Bild

Titel 2 Bild

<img alt="" src="/_layouts/images/home.gif" style="BORDER: px solid; ">

Snippet Preview (note that in fact no picture is displayed, only the code):
Titel 2 Bild

Generates the following (Picture selected in edit-mode then saved the page):

I also generated the snippet for the Page Image Field (inherited from Article Page) which works without a problem. I don't understand why my custom Image Field doesn't get displayed while the Page Image does (even the preview of the snippet for the Page Image field already shows a picture and no html img code)
Edit:
I added two screenshots to clarify my problem, with the hope that someone will understand and help me.
What "Titel 2 Bild" looks like in the preview:

What "Page Image" looks like (and how "Titel 2 Bild" should look like):

A: Finally found the mistake. One property was missing in the field definition: RichText="True"
Full field definition:
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Field
       ID="{4ea31e74-f59d-4ddf-863c-607a01735f65}"
       Name="pls_H2_2_Image"
       DisplayName="Titel 2 Bild"
       Type="Image"
       Required="FALSE"
       RichText="TRUE"
       Group="Custom">
  </Field>
</Elements>

A: Adding to Razze's reply, it isn't work for me until I added and extra property for the field which is RichTextMode="FullHtml" to be finally like:
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
 <Field
   ID="{4ea31e74-f59d-4ddf-863c-607a01735f65}"
   Name="pls_H2_2_Image"
   DisplayName="Titel 2 Bild"
   Type="Image"
   Required="FALSE"
   RichText="TRUE"
   RichTextMode="FullHtml"
   Group="Custom">
 </Field>
</Elements>


text:
Q: What is the use of function void QQuickWindow::setDefaultAlphaBuffer(bool useAlpha)? In Qt 5.1.0 documentation it says

void QQuickWindow::setDefaultAlphaBuffer(bool useAlpha)
useAlpha specifies whether to use alpha transparency on newly created windows.
In any application which expects to create translucent windows, it's necessary to set this to
true before creating the first QQuickWindow, because all windows will share the same
QOpenGLContext. The default value is false.

I have used this function to create a transparent background with a QQuickView, However it didn't change anything (on Windows 7) as far as I can see, here is my code:
QQuickWindow::setDefaultAlphaBuffer(true);
QQuickView view;

view.setColor(Qt::transparent);
view.setSource(QUrl::fromLocalFile("test.qml");
view.setResizeMode(QQuickView::SizeRootObjectToView);

bool b = view.hasDefaultAlphaBuffer();

QWidget* p = QWidget::createWindowContainer(&view, NULL, Qt::FramelessWindowHint);
p->setAttribute(Qt::WA_TranslucentBackground);
p->show();

and here is my test.qml:
import QtQuick 2.0

Rectangle
{
 width: 300;
 height: 300;
 color: "transparent"

 Rectangle
 {
  x: 50;
  y: 50;
  width: 100;
  height: 100;
  color: "blue";
 }
}

So what is the use of this function?

A: Maybe you need to use the function on your QQuickView object:
view.setDefaultAlphaBuffer(true);


text:
Q: Initializing an array member of a struct by name I have a struct that looks something like this:
typedef struct
{
    uint32_t a;
    uint32_t b;
    uint32_t c[5];
    uint32_t d;
} MY_STRUCT_T;

I want to initialize c, by name, to a non-zero value. I want everything else to be 0.
If c were not an array, I could do:
static MY_STRUCT_T my_struct = {.b = 1};

And I know I can do this:
static MY_STRUCT_T my_struct = {.c[0]=5,
    .c[1]=5,
    .c[2]=5,
    .c[3]=5,
    .c[4]=5};

but I was wondering if there was a more elegant syntax of which I am unaware:
Something like:
static MY_STRUCT_T my_struct = {.c[] = {5,5,5,5,5}};

I have read the following, but they don't answer this question:
Initializing a struct to 0

Initialize/reset struct to zero/null
A better way to initialize a static array member of a class in C++ ( const would be preferred though )

How to initialize all members of an array to the same value?

A: So I wrote this question and then experimented for a while and found that the following would work:
static MY_STRUCT_T my_struct = {.c={5,5,5,5,5}};

A: OP has 3 goals: 1) field array size is fixed width, 2) initialization like {7,7,7,7,7} is fixed width, 3) c  to a non-zero value.  As #1 and #2 have their sizes independent coded, 2 of the 3 goals can be met, but not all 3 - that is tricky.
What is to prevent/warn about MY_STRUCT_T my_struct = {.c = {5,5,5,5,5}}; not meeting goals should uint32_t c[5]; later become uint32_t c[6];?  Nothing really.
Lacking a maintainable coding paradigm, consider this - copy one by one


text:
Q: Python Flask unicode string encoding conversion I'm new to Flask and encoding. Using Python3
I have an app:
from flask import Flask
from flask import request
from flask import jsonify
import requests

app = Flask(__name__)

QUERY_PARAM = 'q'

@app.route('/response', methods=['GET'])
def get_query():
    query = request.args.get(QUERY_PARAM)
    user_input = dict()
    user_input['text'] = query
    return jsonify(user_input), requests.codes.ok

I put in /response?q=what is ab\u0026c
It is now returning: {"text":"what is ab\u0026c"}
I want it to return: {"text":"what is ab&c"}
Tried a couple of encoding in the code but none of them worked for me.
Can someone tell me how I can achieve this and help me understand it?

A: You implementation seems to be working correctly, but you are passing the query param in a wrong way.
You want to send the text: "what is ab&c".
This text needs to be encoded to encoded for urls.
For example you could use python for this, by running the following lines in the shell:
>>> from urllib.parse import urlencode
>>> payload = dict(q="what is ab&c")
>>> urlencode(payload)
'q=what+is+ab%26c'

With that result we know that the request would be:
http://localhost:5000/response?q=what+is+ab%26c

Which results in:
{
  "text": "what is ab&c"
}


text:
Q: Time scale for surface reconstruction I've been reading about surface reconstruction in condensed matter physics, and it got me wondering. Is there any way to assign a time scale to this phenomenon?
For example, suppose we were to take a slab of pure silicon and cleave it, as described in the Wikipedia article, along the (100) surface. The atoms on the new surface are going to relax to a new optimal configuration and form dimers. Is there a way to estimate how long it's going to take them to relax? Since the difference in energy between the two structures is large, does it happen basically as we're cleaving them, as the edge of the cutting surface is moving along them?


text:
Q: Possible types of elements for generic collections List<? super MyClass> parentsOfMyclass
List<? extends MyClass> childsOfMyclassFirst
List<T extends MyClass> childsOfMyclassSecond

Please explain me what types valid to add in these collections ? I can add instance of MyClass to all of these collections?

A: List<? super MyClass> - contains something that is superclass of MyClass, which means that you can put only MyClass and it superclasses here.
List<? extends MyClass> - contains something that extends MyClass, which means that you can't add anything here (because you don't know which subclass is used exactly). Although you can say for sure, that items are MyClass (or subclasses).
List<T extends MyClass> - contains T, that is subclass of MyClass. Can only add T and subclasses of it.

A: You can't actually use the last option like that. It can be used in class declaration, but not in variable declaration.
static class MyClass {}

static class My2ndClass extends MyClass {}

static class ListExt<T extends MyClass> {}

public static void main(String[] args) {
    List<? super MyClass> parentsOfMyclass;
    List<? extends MyClass> childsOfMyclassFirst;
    List<T extends MyClass> childsOfMyclassSecond; //error

    ListExt<? extends MyClass> extList;

    childsOfMyclassFirst.add(new MyClass()); //error
    parentsOfMyclass.add(new MyClass());
    extList.add(new MyClass()); // error
}

A: You can add instance of MyClass only in the first case (with super). ? super MyClass makes the list a consumer, it can namely receive objects of type MyClass. In the second case the list cannot receive anything, it is a producer, a read-only list. In the third case you can add a subtype of MyClass if you make downcasting before: .add((T)object); and it of couse it does not throw an exception.
The correct syntax of the third case would be List<T> list and T extends MyClass should be in the class declaration.


text:
Q: SOQL and SQL joins Good Morning
From what I can see joins are not available in the traditional sense with SOQL.  I think I need to use "relationship".  I have not had any success so far and want to confirm I'm going in the right direction as this query is critical for a time sensitive project.
The issue is that I need to retrieve all postal codes on a Case that correspond to a series of values provided for a specific field(social media handle) of the Social Persona. I need to be able to pass a series of social media handle as a parameter and return the corresponding postal code for each.  Sounds simple enough but like I said everything I tried has been unfruitful and I'm not convinced I'm using the correct approach.
Any direction someone can provide would be very appreciated and an example would be ideal of course.
Thanks in advance for any insight.


text:
Q: How to implement AES-GCM encryption using kernel Crypto API? Hi I am working on a stackable filesystem WrapFS and trying to implement AES-GCM cipher on it to encrypt the data stored in the underlying file system. I am having major troubles in handling the GCM mode for AES at kernel level. However I was successful in implementing AES in CTR mode and the code for the same is attached below. Can someone point me in the right direction as to how to modify it to AES-GCM ?
I looked at this link, but that didn't help much.
I am looking for two things: 1.) How to store authentication tags alongside encrypted data in files written and 2.) How to handle IV of AES-GCM by sending to and receiving from lower filesystem.
Thanks
int decrypt_encrypt_page(struct page *src_page,
                     struct page *dst_page,
                     char *key,
                     int key_len,
                     int encrypt)
{
    int ret = 0;
    struct scatterlist src_sg, dst_sg;
    struct crypto_blkcipher *tfm;
    struct blkcipher_desc desc;

    sg_init_table(&src_sg, 1);
    sg_init_table(&dst_sg, 1);

    sg_set_page(&src_sg, src_page, PAGE_SIZE, 0);
    sg_set_page(&dst_sg, dst_page, PAGE_SIZE, 0);

    tfm = crypto_alloc_blkcipher(default_algo, 0, 0);

    if (IS_ERR(tfm)) {
        printk(KERN_ERR "failed to load transform for %s: %ld\n",
               default_algo,
               PTR_ERR(tfm));
        ret = IS_ERR(tfm);
        goto out;
    }
    desc.tfm = tfm;
    desc.flags = 0;

    ret = crypto_blkcipher_setkey(tfm, key, key_len);
    if (ret) {
        printk(KERN_ERR "setkey() failed flags=%x\n",
               crypto_blkcipher_get_flags(tfm));
        goto out;
    }
    if (encrypt)
        ret = crypto_blkcipher_encrypt(&desc, &dst_sg, &src_sg, PAGE_SIZE);
    else
        ret = crypto_blkcipher_decrypt(&desc, &dst_sg, &src_sg, PAGE_SIZE);
    if (ret)
        printk(KERN_INFO "Some error occured while encrypting.\n");

out:
    crypto_free_blkcipher(tfm);
    return ret;
}


text:
Q: checking if login it and cart is empty I am trying to combine two IF statements.
the FIRST statement checks if the cart if empty.
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1)

The SECOND statement change if the user is login in or not...
 if ($_SESSION['User']['AccessLvl'] == null)

I need to check if the cart is empty and if it is I have echo a message saying. cart if empty at the same thing i need to change if the user is login and if they is i dont want to show a form which I have and if they are not, they form should show.
I tried this but didn't work
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
    echo 'cart if emepy';
    if ($_SESSION['User']['AccessLvl'] == null) {
    }
}
else{
   echo ' <form name="login" action="login.php"></form>';
}

summary
The first statement checks if they is anything in cart and if they is nothing, the form should not show. IF the user is logged in the form should not show if they is anything in the cart because the form is a login in form and they is no point for the person to log in twice... The second if statement is statement that i used to check if someone is logged in or not

A: I think it needs to be something like this:
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
echo 'cart if emepy';
} else {

if (is_null($_SESSION['User']['AccessLvl']) || !isset($_SESSION['User']['AccessLvl'])) {
echo ' <form name="login" action="login.php">

</form>';

} else {

}
}

The problem was that your check for the user was in the check if the cart wat empty or not.

A: Why you don't try to do something like this:
if (!isset($_SESSION["cart_array"]) && count($_SESSION["cart_array"]) < 1 && $_SESSION['User']['AccessLvl'] != null)
{
    echo "logged in but cart empty";
}
else if($_SESSION['User']['AccessLvl'] == null)
{
   echo "not logged in";
}
else
    echo "all right, logged in and cart not empty!";

A: How about this:
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1)
{
    echo "cart is empty";
}
else
{
    //show cart here
    if ($_SESSION['User']['AccessLvl'] == null) //user is not logged in
    {
        //show login form
        echo ' <form name="login" action="login.php"></form>';
    }

}


text:
Q: I tried to install NodeJS v14 and broke everything, how to install new version without breaking dependencies? So I found out that for some reason, unlike on Windows you don't just get to chose your NodeJS version. When I install it normally, I get version 10, via command:
sudo apt-get install nodejs

Tried on two Ubuntu based machines, one Ubuntu 14 (old I know) and one Linux Mint 20.3 Una. Both give me version 10 of nodejs, which is years old. On the nodejs website, I found this helpful guide that helped me break my system by running this:
curl -fsSL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs

So that did install nodejs 14 as promised, but now nothing that depends on NodeJS can be installed. I get error like this for npm, which is pretty much necessary for working with nodejs:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 npm : Depends: nodejs but it is not going to be installed
       Depends: node-abbrev (>= 1.0.4) but it is not going to be installed
       ...
       ...
       Depends: node-slide but it is not going to be installed
       Depends: node-tar (>= 0.1.18) but it is not going to be installed
       Depends: node-which but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I tried to remove nodejs, but when I install it again I now always get the v14 and the system remains broken.
Can you please help me fix this? Could you also please explain what the command I ran did?

A: Remove NodeJS completely(package, config)
sudo apt purge nodejs
sudo apt autoremove
sudo apt purge npm

Update Package List
sudo apt update

Note: Check for any .npm or .node folder in your home directory and delete those.
Reinstall NodeJS
sudo apt install nodejs


text:
Q: how to access mac files from ubuntu flash drive So I'm running ubuntu from a thumb drive that's plugged into my Mac. I want to access some files from the Mac harddrive while I'm booted into ubuntu, but when I click on the MacOSX harddrive to locate the files, I get this error:
"Unable to access location. Error mounting /dev/sda2 at /media/ubuntu/MacOSX: wrong fs type, bad option, bad superblock on /dev/sda2, missing codepage or helper program, or other error"
I don't want to mess anything up with the Mac laptop in and of itself, I just want to get some files from the harddrive. Is there a way to do this that won't pose any possible future issues with the Mac?


text:
Q: YII compress your application output using gzip what is the benefit of below  code that is two events.
what its actually doing ??
require_once($yii);
$app = Yii::createWebApplication($config);
Yii::app()->onBeginRequest = function($event)
{
  return ob_start("ob_gzhandler");
};

Yii::app()->onEndRequest = function($event)
{

return ob_end_flush();
};

$app->run();

please explain the function of this code in my application.what it does ?? and how can it help me ??

A: The above code buffers the content and gzips it according to browser, rather than sending it straight away.
Yii::app()->onBeginRequest = function($event)
{
return ob_start("ob_gzhandler");
};

The above means that when the requests starts, it will buffer the content, and using the callback will set the content as gzip,deflate or none, depending on browser.
Yii::app()->onEndRequest = function($event)
{
return ob_end_flush();
};

The above code simply means that at the end of the request, it will output the buffer contents.

A: It buffers the content, and just before sending it the browser, asks if the browser can accept zipped content. If it can, it will zip the HTML before supplying. Otherwise, it will supply it unzipped.
Zipped content reduces the size of the HTML the browser needs to download, which can increase performance. How much performance gain your users will see depends on the size of the HTML - bigger pages will see more benefit, while tiny pages may actually take longer to render, because the browser has to unzip the content first. Use Firebug or Chrome Developer Toolbars to see whether it's worth it.
Also, check the impact on the server side. Again, the downside of increased server load can outweigh the increased client-side page render speed. Hence, it works best with lots of caching.
This is normally something you do when you are optimising the site, looking for performance gains.

A: if you want add gzhanlder straight to main config file you Can Set Following lines in main.php
'onBeginRequest'=>create_function('$event', 'return ob_start("ob_gzhandler");'),
'onEndRequest'=>create_function('$event', 'return ob_end_flush();'),

this Two lines Add GzipHandler


text:
Q: Better way for new users to contact moderators Well, the previous question on a better way to contact moderators, An @Moderators ping got a big vote of no confidence.  But we've been trying to address the perception among new users that our site (and other SEs) are unwelcoming – "rude" is a word often used.
A relevant quote many of our users agree on: "The process by which one can contact a moderator has significant amounts of mystery."
Sure, new users should have perfect mastery of the help center and go root through meta and somehow know about the various chat rooms – but we're not talking about a problem with experienced users; it's with new users who don't have much chance of knowing about most of that. We value the "improving" nature of SE – putting bad questions on hold, workshopping them, etc. – but it is obviously hard on new users and many of them find themselves at a loss as to what to do/where to go. Chat is, frankly, often even worse; the lack of good moderation tools there generally makes it just a place to "take the argument to" and argue some more, escalating rather than de-escalating the situation.
I understand that a custom flag is "supposed to be" the path to that. But that's very unclear to a new user. (Actually, they tend to assume that anyone hassling them over their question quality must be one of the mods.)
We get pulled into it sooner or later; I'd rather it be by some kind of "need help" button than when there's a bunch of angry folks, and someone's already deleted all their content from the site, and a big mess is already well in progress.
It could use the flagging system, but just be more obvious visually. A button, a dropdown option under help... "Get Help" or "Contact a Moderator" or something similar.
(It actually wouldn't hurt to have some more contextual help too; if someone's looking for help on their closed question, surfacing relevant help center/meta stuff to them based on that context would be good – we don't have edit access to most of the help center, and newbies don't always find it intuitive where to get info.)

A: Ultimately, I don't think this is a good idea.
I'm not an SO guy, I moderate Christianity and Gardening, I'm pretty active on the site you moderate too.
The problem you're trying to solve doesn't get fixed with an easy line to the moderators. The problem you're trying to fix is solved with better community education, better enforcement of existing rules and simply more patience on the part of the community.
Here are the problems I see:

*

*This idea simply doesn't scale. This has been pointed out already, but it's not only true on the big 3. Plenty of other sites have sufficient volume to make this a problem.

*This already exists. If a user wants to contact the mods they have the option to flag, I know you've discounted this, but flagging is probably the right answer.

*It puts the burden on the moderators instead of the community. SE doesn't work unless the community is helping new users along. It would be impossible to add sufficient moderators to help every new user, and adding more to the moderator load seems impractical. Especially when, generally, the community is plenty good at handling this kind of thing themselves.
That said, there are some things you can do to facilitate being nice, and easier contact of the moderators on your site if you want to do that.

*

*Set the tone. The moderators can and should set the tone for interactions not just with new users, but with all users. If the moderators are being jerks, their users will be. Be nice. Even in your regular site interactions, and your users will be nice.

*Be more active in chat. If users don't want to flag, then chat is the best way to get in touch with a moderator. If the mods aren't in chat, they don't have many options. Chat is a great place to do quick support work. While the moderator tools aren't great, it is a good place to have a chat with a new user if you're having issues. The lack of moderation tools is a straw man, there's no need for moderation tools when you're simply having a discussion. If you have to you can even take it private.

*Launch a meta campaign. SE had the Summer of Love campaign a couple of years ago and it seemed to nicen things up a lot around here. It might not hurt (if you're seeing too many folks being driven away by rudeness), to launch one of your own.
To me, the only bit about this request that's worth pursuing is the parenthetical. Giving some contextual clues about what they are doing might help to get them where they need to go in the help center. One of the complaints I've seen on RPG.SE's meta a few times has been that important info is hard to find. It would be best to give the community some idea of which help center pages to link to struggling users. I've seen relatively few of those links around in comments on the site.


text:
Q: Returning adjacent keys from a TreeMap Given the following TreeMap:
Map<Double, Integer> treeMap = new TreeMap<Double, Integer>() {{.
        put("52.1", 1);
        put("53.4", 2);
        put("57.1", 3);
        put("59.4", 7);
        put("60.2", 11);
        put("71.6", 16)}};

What would be the best way to return the closest n matches (in both directions) for a given double? For instance, n=2 and "58.0" would return 53.4, 57.1, 59.4, 60.2

A: tl;dr
new TreeMap <>(
        Map.of(
                52.1d , 1 ,
                53.4d , 2 ,
                57.1d , 3 ,
                59.4d , 7 ,
                60.2d , 11 ,
                71.6d , 16
        )
)
.floorKey( 58.0d )     // Or call `.ceilingKey( 58.0d )`

See this code run live at IdeOne.com.

57.1

NavigableMap::lowerKey/higherKey
TreeMap is a NavigableMap.
The NavigableMap interface provides methods for retrieving adjacent keys (and entries).

*

*lowerKey

*higherKey
Repeat the commands to fetch as many adjacent keys as you desire, until receiving a null.
Comparing keys
On second reading, it seems you do not have a key. You have a value you want to compare to keys in a map.
In this case, fetch a Set of all the keys in the map. NavigableMap extends SortedMap. So we can call SortedMap::keySet. The returned set iterates in sorted order.
Set< Double > set = map.keySet() ;

Make a List of that, to access individual elements by index.
List< Double > doublesListSorted = List.of( set.toArray() ) ;  // Get un-modifiable list.

Now you can loop the sorted list to compare values.
NavigableMap::floorKey/ceilingKey
Or, as dnault commented, we can ask the NavigableMap to compare key values for a nearest-match.

*

*floorKeyReturns the greatest key less than or equal to the given key, or null if there is no such key.

*ceilingKeyReturns the least key greater than or equal to the given key, or null if there is no such key.

Example code
Make an input map. We use Map.of initially for its convenient literal syntax. Then we feed that un-modifiable map to the constructor of TreeMap. Our literal input seen here happens to be sorted, but that is irrelevant, as the TreeMap constructor will sort the entries by key.
NavigableMap < Double, Integer > map =
        new TreeMap <>(
                Map.of(
                        52.1d , 1 ,
                        53.4d , 2 ,
                        57.1d , 3 ,
                        59.4d , 7 ,
                        60.2d , 11 ,
                        71.6d , 16
                )
        );

map.toString(): {52.1=1, 53.4=2, 57.1=3, 59.4=7, 60.2=11, 71.6=16}

Set our target to which we want the closest matches.
Double target = 58.0d;

Get the adjacent keys, next lower, and next higher.
Double nextLower = map.floorKey( target );
Double nextHigher = map.ceilingKey( target );

nextLower = 57.1
nextHigher = 59.4

See this code run live at IdeOne.com.

Notes:

*

*As commented by erickson your double-brace initialization is something of a hack. Now unnecessary given the new List.of literal syntax shown in this Answer.

*If you care about accuracy, use BigDecimal rather than Double.


text:
Q: styles.css file is not working. how to solve the problem? I made a website and got to the point where you need to connect styles.css, but after all the manipulations, my site has not changed and no design has been connected. I tried to rewrite css and html, tried different tips, but nothing helped me. any ideas?
I would be grateful for any advice!

*

*1part base.html

<!DOCTYPE html>

    <title>{{title}}</title>
    <link type="text/css" href="{% static 'women/css/styles.css' %}" rel="stylesheet" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="shortcut icon" href="{% static 'women/images/main.ico' %}" type="image/x-icon"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

{% block mainmenu %}

{% for m in menu %}
    {% if not forloop.last %}

{{m.title}}

    {% else %}

{{m.title}}

    {% endif %}
{% endfor %}

{% endblock mainmenu %}```

I've added screenshots below if anyone needs them.

[1][1]
[2][2]
[3][3]
[4][4]

- PS I have already tried these options, gives an error

```<link type="text/css" href="{% static 'women/css/styles.css' %}" rel="stylesheet" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="shortcut icon" href="{% static 'women/images/main.ico' %}" type="image/x-icon"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">```

  [1]: https://i.stack.imgur.com/3exw2.png
  [2]: https://i.stack.imgur.com/ye5k7.png
  [3]: https://i.stack.imgur.com/ZKSs6.png
  [4]: https://i.stack.imgur.com/eQRvd.png

A: Don't know if its the same issue but I find clearing the cache can fix styling issues (ctrl+f5)

A: Check static dirs in settings.py and correct static dirs, because it may cause issues in connecting with dirs.
[for reference I am giving you settings of static dirs below]
settings.py
 STATIC_URL = "/static/"
 STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
 MEDIA_URL = "/media/"
 MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")

If the settings are okay then remember whenever you change something in CSS browser doesn't Change CSS directly you need to make a hard reset your browser's tab by pressing
Ctrl + shift + R

A: If it's on server, make sure to collectstatic after you make changes in files of your static folder. To make your static folder updated.
python manage.py collectstatic

Then restart gunicorn and nginx
sudo systemctl daemon-reload
sudo systemctl restart gunicorn
sudo systemctl restart nginx

However if it's in your local computer, you might just need to hard-reload your browser (ctrl+shift+R).
If it still doesn't work, make sure the path of your css file is correct.


text:
Q: Problem instantiating a class in a scriptlet When I want to instantiate a class or use a static class method, I get an error on the web page. Here I show you what happens:
I have created this super simple class to show the problem:
package CalculosMatematicos;

public class calculos {

    public static int resultado;

    public static int metodoSuma(int num1, int num2){

        resultado = num1 + num2;
        return resultado;
    }

    public static int metodoResta(int num1, int num2){

        resultado = num1 - num2;
        return resultado;
    }

    public static int metodoMultiplicar(int num1, int num2){

        resultado = num1 * num2;
        return resultado;
    }

    public static int metodoDividirf(int num1, int num2){

        resultado = num1 / num2;
        return resultado;
    }

}

In the JSP I wrote:

<%@page import="CalculosMatematicos.*"%>
<!DOCTYPE html>

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

Hello World!

        La suma de 7 + 5 es: <%= calculos.metodoSuma(7,5)%>

The error is this:

A: The class itself should be static otherwise you have to create a new object of type calculos
to give a little more clarification from https://www.geeksforgeeks.org/static-class-in-java/
 // Static nested class
    public static class NestedStaticClass {

    // Only static members of Outer class
    // is directly accessible in nested
    // static class
    public void printMessage()
    {

        // Try making 'message' a non-static
        // variable, there will be compiler error
        System.out.println(
            "Message from nested static class: "
            + msg);
    }
}

So your class should be static because you have not instantiated it.
So either make the main class a static or instantiate the non-static class prior to use.
package CalculosMatematicos;

public static class calculos {

    public static int resultado;

    public static int metodoSuma(int num1, int num2){

        resultado = num1 + num2;
        return resultado;
    }

    public static int metodoResta(int num1, int num2){

        resultado = num1 - num2;
        return resultado;
    }

    public static int metodoMultiplicar(int num1, int num2){

        resultado = num1 * num2;
        return resultado;
    }

    public static int metodoDividirf(int num1, int num2){

        resultado = num1 / num2;
        return resultado;
    }

}


text:
Q: Node JS + Express won't run, DEBUG=appname ./bin/www I'm trying to get a node/express server running on a mac, and this command isn't running
DEBUG=ExpressApp ./bin/www

This is the error that gets thrown out:
module.js:340
    throw err;
      ^
Error: Cannot find module 'express'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/Users/jaysen/Desktop/ExpressApp/app.js:1:77)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)

UPDATE
After re-running npm install, I just get a blank line.


text:
Q: C# gravity simulation code acting weird I have been working on a (kind of) gravity simulation using C# and Winforms, and I am getting some very weird behavior. It pretty much makes an object when you click, and is attracted to the other objects. The problem is that, unless they are within some weird distances, they will not be attracted in the positive directions (right, down.), but they are attracted upwards and to the left.
This is the update code:
    public Vector GetGravEffect(GravObject other)
    {
        if ((Math.Abs(X - other.X) <= Mass * Form.DrawScale + other.Mass * Form.DrawScale) &&
            (Math.Abs(Y - other.Y) <= Mass * Form.DrawScale + other.Mass * Form.DrawScale))
        {
            return new Vector(0, 0);
        }

        double tAngle = Math.Atan2((other.Y - Y), (other.X - X));

        double tMagnitude = (GravModifier * Mass * other.Mass / ((Math.Pow((other.X - X), 2)) + (Math.Pow((other.Y - Y), 2))) * 1000);

        Complex c = Complex.FromPolarCoordinates(tMagnitude, tAngle);

        Vector r = new Vector(c.Real, c.Imaginary);

        return r;
    }

Full code is here: https://docs.google.com/open?id=0B79vmyWxBr-kTnUtQURPUlVidzQ
Thanks for any help!

A: Problem is not in GetGravEffect method (it gives correct results), but in Update method. It completely ignores physical laws. You cannot sum values returned by GetGravEffect and consider it to be velocity. GetGravEffect returns force that one object attracts the other. You must sum these forces and then do additional computations that includes inertia, acceleration and time to calculate resulting velocity. Also casting X and Y to int is not good idea, because you looses much of accuracy, especially for slow velocities. With following corrected method it works great:
    public void Update() {
        Vector Force = new Vector(0, 0);
        foreach (GravObject g in Form.Objects) {
            if (this != g)
                Force += GetGravEffect(g);
        }

        double TimeElapsedSinceLastUpdate = Form.Timer.Interval * 0.001;
        Vector acceleration = Force / Mass;
        Velocity += acceleration*TimeElapsedSinceLastUpdate;

        X = (X + Velocity.X * Form.VelocityScale);
        Y = (Y + Velocity.Y * Form.VelocityScale);

        if (X + Mass * Form.DrawScale >= Form.Panels.Panel2.Width || X - Mass * Form.DrawScale <= 0)
            Velocity.X *= -1;
        if (Y + Mass * Form.DrawScale >= Form.Panels.Panel2.Height || Y - Mass * Form.DrawScale <= 0)
            Velocity.Y *= -1;
    }


text:
Q: In S3E12 of Buffy The Vampire Slayer, why is Buffy so weak? Okay, so it might seem like a daft question on the face of it but in the episode "Helpless", Buffy is

 given a drug which zaps her slayer powers, and she has to deal with her life as a normal girl.

However, we see Xander, Giles, even Willow managing to at least deal with vampires, so it's not unreasonable to assume that a fit, well trained person couldn't manage. That's where I actually get to the point. Buffy spends her life training, and we know that she can grow, which means that her muscles probably develop.
So she's a well-trained (if a bit shell shocked), fit person. What gives?

A: The key is that it turned out to be a drug that was causing her weakness, rather than (as Buffy originally assumed) a magical attack or incident that removed the Slayer magic but otherwise left her unaffected.  The drug may or may not have needed a magical component in order to overcome the Slayer's resistance to poisons, but its primary function was undoubtedly medical, not magical.  (Edit: as the OP points out, it was described in the episode as a muscle relaxant.)
Given that, the dosage would have had to be carefully calibrated in any case, in order to avoid leaving her either with too much of her magically enhanced strength on the one hand or leaving her unable to walk on the other.  You will note that multiples doses were used, allowing Giles to judge the impact and adjust the dose as necessary.
For the purposes of the Cruciamentum, the dosage chosen was clearly intended to leave her with the strength of the average teenage girl - not the strength of a well-trained athlete and warrior.
As to why the Council didn't use magic to temporarily remove her Slayer powers, leaving her otherwise unaffected, presumably that either isn't possible or the Council lack the necessary knowledge and/or power.  (After all, if it was easy to remove a Slayer's power then no Slayer would ever survive long enough to do much good.)


text:
Q: Array overwrites instead of adding Good afternoon,
I'm still a beginner in programming, currently learning Android.
I am making a screen that captures some information from a website and moves to a list view. The code below works when I use only the main page of the site, when I try to move to page 2 instead of adding to the end of the Array, it overwrites the entire Array.
I have reached the limit of my knowledge, I can kick it a silly mistake in how they are built, but I could not reach the solution alone.
I'm sorry if I have any typos, I'm using a translator.
    package br.com.testejsoup.eu.testejsoup;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private ListView conteudo;
    String[] aniNomes;
    String[] aniLinks;
    ArrayAdapter<String> adaptador;
    Document doc;

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

        conteudo = findViewById(R.id.html_conteudo);

        new doit().execute();

        conteudo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int posicao = position;

                Intent intent = new Intent(MainActivity.this, Episodio.class);
                intent.putExtra("aniLinks", aniLinks[posicao]);
                //Toast.makeText(getApplicationContext(), aniLinks[posicao], Toast.LENGTH_LONG).show();
                startActivity(intent);
            }
        });

    }

    public class doit extends AsyncTask<Void, Void, Void>{
        String URL = "http://www.URL.com/lancamentos?page=";
        String nomeExp;
        Elements nome;
        Elements links;
        int paginas = 5;

        @Override
        protected Void doInBackground(Void... voids) {

            try {

                for (int i=1; i<= paginas;i++) {
                    String new_URL = URL + i;
                    doc = Jsoup.connect(new_URL).get();
                    nome = doc.select("div.nome-thumb a.tt");
                    links = doc.select("div.nome-thumb a.tt");
                    aniNomes = new String[nome.size()];
                    aniLinks = new String[links.size()];

                    for(Element nomeTemp : nome){
                        nomeExp = nomeTemp.text();
                        adaptador.add(nomeExp);
                    }
                }

                    for (int i = 0; i < nome.size(); i++) {
                        aniNomes[i] = nome.get(i).text();
                    }
                    for (int i = 0; i < links.size(); i++) {
                        aniLinks[i] = links.get(i).attr("abs:HREF");
                    }
                    adaptador = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, aniNomes);

            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            conteudo.setAdapter(adaptador);

        }
    }

}

New code after the proposed modification.
THANKS FOR THE HELP!!!
    package br.com.testejsoup.eu.testejsoup;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ListView conteudo;
    ArrayList<String> aniNomes = new ArrayList<>();
    ArrayList<String> aniLinks = new ArrayList<>();
    ArrayAdapter<String> adaptador;
    Document doc;

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

        conteudo = findViewById(R.id.html_conteudo);

        new doit().execute();

        conteudo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int posicao = position;

                Intent intent = new Intent(MainActivity.this, Episodio.class);
                intent.putExtra("aniLinks", aniLinks.get(position));
                //Toast.makeText(getApplicationContext(), aniLinks[posicao], Toast.LENGTH_LONG).show();
                startActivity(intent);
            }
        });

    }

    public class doit extends AsyncTask<Void, Void, Void>{
        String URL = "http://www.URL.com/lancamentos?page=";
        String nomeExp;
        Elements nome;
        Elements links;
        int paginas = 5;

        @Override
        protected Void doInBackground(Void... voids) {

            try {

                for (int i=1; i<= paginas;i++) {
                    String new_URL = URL + i;
                    doc = Jsoup.connect(new_URL).get();
                    nome = doc.select("div.nome-thumb a.tt");
                    links = doc.select("div.nome-thumb a.tt");
                    for (Element nomeT : nome){
                        aniNomes.add(nomeT.text());
                    }
                    for (Element linkT : links){
                        aniLinks.add(linkT.attr("abs:HREF"));
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            adaptador = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, aniNomes);
            conteudo.setAdapter(adaptador);

        }
    }

}

A: Its because you're creating a new adapter in your asynctask and then in your onPostExecute method you're calling setAdapter which swaps out the old adapter and its entries with the new adapter and its new entries.
Rather than creating a new adapter in your asynctask I would just create an array/arraylist, add the new entries to it and then in your onPostExecute just append the entries from this array/list into the one and only adapter entry set.