text:
Q: Filtering roles by name Discord I have an array with all the roles in a Discord server, and I want to filter it to show me only the roles which have a specific name. I've used the filter() function before for filtering members with a specific role, but I am having trouble adapting it to this situation.
The code for filtering a list of members:
const membersWithRole = members.filter(m => !!m.roles.find(r => r === sheet.rows[i].fields.role_id));

A: I really don't get what you really trying to do but I guess you must be trying to get role that starts with or contains certain name.
For starts with certain name:

let roleName = "filtering_name"
const role = guild.roles.cache.find(r => r.name.startsWith(roleName))

For contains certain name:

let roleName = "filtering_name"
const role = guild.roles.cache.find(r => r.name.includes(roleName))


text:
Q: why doesn't this jquery html() function work? I created this very basic example of a jquery html() function but it doesn't work:

View on JSBin
Any idea what the issue might be?

A: You miss put it on docmuent ready

A: put your script after div tag
or if you want to keep the script within the head tag then you need to included it in $(), like so:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there an easy way to use glom to get an unknown key from a dictionary? Is there an easy way to use glom to get an unknown key from a dictionary?
the ??? represents random data that I am trying to capture from an API
    book = {"???":[{ "globalIdenity":208565940},{"globalIdenity":228049454}]}

    spec =
    output_data = glom(book, spec)
    print(output_data)

A: Use an iterator for values then use the next call to get the value
book = {"???":[{ "globalIdenity":208565940},{"globalIdenity":228049454}]}

result = next(iter(book.values()))

print(result)

#output
[{'globalIdenity': 208565940}, {'globalIdenity': 228049454}]


text:
Q: Define a function to parse an email adress I need to write a function parse_email that, given an email address s, returns a tuple, (user-id, domain) corresponding to the user name and domain name.
For instance, given richie@cc.gatech.edu it should return (richie, cc.gatech.edu).
The function should parse the email only if it exactly matches the email specification. For example, if there are leading or trailing spaces, the function should not match those. Also, the start of the function should be an alphabet as well as the end. In case it is not an alphabet, it should get an error as well as if the string contains any space.
I tried the following function:
def parse_email (s):
    """Parses a string as an email address, returning an (id, domain) pair."""
    try:
        return(re.match(r'\S([\w\.+_-]+)@([\w\._-]+)',s).groups())
    except:
        pass

Can someone help me in completing the function where if there are spaces in the start of the string, it gives an error.
def parse_email (s):
    try:
            return(re.match(r'\S([\w\.+_-]+)@([\w\._-]+)',s).groups())
    except:
        pass

A: Regular expressions are entirely the wrong tool  here. Python 3.6+ has a library function which does exactly this.
from email.policy import default as email_default_policy
from email import message_from_string

msg = message_from_string('To: {}'.format(s), policy=email_default_policy)
for addr in msg['to'].addresses:
    yield addr.username, addr.domain

The email.headerregistry library offers a structured representation of a parsed email address.  The email.policy.default object is required to enable the 3.6+ email parsing functionality (though the documentation alleges that it will become the default policy eventually, at which point you should no longer need to specify it explicitly).
There are demonstrations of RFC822 header parsers in pure regex. The canonical one is roughly a full page of text: Mail::RFC822::Address Regex

A: Split can be used:
def parse_email (s):
    try:
        x=re.split('@',s)
        return (x[0],x[1])
    except:
        pass

Happy coding :)

A: I would recommend you simply split the input string on @ after trimming any whitespace. As mentioned in the comments, you can encounter more than one @ symbol in an e-mail address, so it's important to split on the right one.
Building regular expressions for "valid" e-mail addresses is a nightmare, and you're bound to get it wrong. This article explains why:
https://hackernoon.com/the-100-correct-way-to-validate-email-addresses-7c4818f24643
Below is some code, with tests, that show how this works, but you it doesn't cope with multiple @ symbols.
import pytest

def parse_email(s):
  parts = s.strip().split('@', 1)
  if len(parts) == 2:
    return (parts[0], parts[1])
  else:
    raise ValueError()

def test_parse_simple_email():
  parts = parse_email("cheese@peas.com")
  assert len(parts) == 2
  assert parts[0] == "cheese"
  assert parts[1] == "peas.com"

def test_invalid_email():
  with pytest.raises(ValueError):
    parts = parse_email("this is not an e-mail address")

def test_parse_email_with_whitespace():
  parts = parse_email(" cheese@peas.com ")
  assert len(parts) == 2
  assert parts[0] == "cheese"
  assert parts[1] == "peas.com"

A: I think the following codE and function should do the job:
def parse_email (s):
    try:
        z = re.fullmatch(r'\b([a-zA-Z])([\w.+-]+)@([\w.-]+)([a-zA-Z])\b',s).groups()
        return(z[0]+z[1],z[2]+z[3])
    except AttributeError:
        raise ValueError


text: Q: ZK Device Web Service Мне нужно разработать веб сервис который сможет получать информацию с ZK Finger Device. В сети есть существующие библиотеки написаны на Python 2 (https://pypi.org/project/zklib/)  нужно аналогичное реализовать на ASP.Net. Может кто-нибудь посоветовать с чего начать, структуру проекта, заранее благодарен?


text:
Q: Date conversion from yyyy-MM-dd HH:mm:ss to ISO date yyyy-MM-dd'T'HH:mm:ssXXX format issue I'm trying to convert date format from yyyy-MM-dd HH:mm:ss to ISO date format yyyy-MM-dd'T'HH:mm:ss+5:30, and tested it by below code and it was working fine when ran on eclipse and causing an issue on deployment to server through jar.
The issue is date(input: 2016-01-08 10:22:03) is converted to something like, 2016-01-08T10:22:03Z instead of 2016-01-08T10:22:03+5:30.
Note: I'm using Java 8.
Following is the code used to convert the date,
 SimpleDateFormat outputDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
 SimpleDateFormat inputDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 String FinalDate = outputDate.format(inputDate.parse(pickupDate));
 System.out.println(finalDate);

Other weird experience is, on some machine the issue is not reproducible and in some machine the issue exists. Is it something machine or JVM dependent? Please help.
Thank you in advance.

A: As by documentation of SimpleDateFormat:

For formatting, if the offset value from GMT is 0, "Z" is produced. If
  the number of pattern letters is 1, any fraction of an hour is
  ignored. For example, if the pattern is "X" and the time zone is
  "GMT+05:30", "+05" is produced.

So my guess is probably to check the timezone of your server. Since it thinks that the timezone of the entered date is GMT 0.

A: java.time
If using Java 8 or later, you should be using the java.time classes rather than those notoriously troublesome date-time classes, java.util.Date/.Calendar.
ISO 8601
Your input strings are close to the standard ISO 8601 format. The java.time classes use these standard formats by default when parsing and generating textual representations of date-time values. No need to define a coded parsing pattern for such standard inputs.
To fully comply with ISO 8601, replace that SPACE in the middle with a T.
String inputStandardized = "2016-01-08 10:22:03".replace( " " , "T" );

Parsing Without Time Zone Or Offset
This string has no offset-from-UTC or time zone, so we first create a LocalDateTime.
LocalDateTime localDateTime = LocalDateTime.parse( inputStandardized );

Such objects are a vague idea of a date-time but are not really on the timeline. To define a real moment on the timeline we must apply a time zone.
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = localDateTime.atZone( zoneId );

Apply Time Zone
Note that that particular date + time may not be valid in the specified time zone; java.time adjusts as necessary. Be sure to read the documentation to understand the adjustment behavior.
Formatted Strings
The toString method on ZonedDateTime by default generates a String in the format you desire, except extended to append the name of the time zone in square brackets.
String output = zdt.toString();

2016-01-08T10:22:03+05:30[Asia/Kolkata]

This extension to include time zone name makes much sense. A time zone is not just an offset-from-UTC, it also includes the present and historical rules for handling anomalies such as Daylight Saving Time (DST).
If you really do not want that appended time zone name, against my advice, you can use an alternate formatting pattern, ISO_OFFSET_DATE_TIME, already defined in java.time as a constant.
DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME ;
String output = zdt.format( formatter );

2016-01-08T10:22:03+05:30

Pad Hour Of Offset
By the way, you can avoid problems by always including a leading padding zero in the hours of your offset-from-UTC. So use +05:30 rather than +5:30 as seen in the Question.


text:
Q: Why is my @SuppressWarnings("unchecked") ignored? Why is Javac ignoring my @SuppressWarnings annotation in the code below?
@Override
@Transactional(readOnly = true, timeout = 10)
public List<Item> findAllDue() {
    Query query = getSession().createQuery("from Item item where item.status = :status");
    @SuppressWarnings("unchecked")
    List<Item> list = query.setString("status", ItemState.MY_STRING_STATUS).list(); //This is line 43.  yes, I know it can be an Enum instead
    return list;
}

After compiling with Xlint, here is the warning:
Warning:(43, 106) java: unchecked cast
  required: java.util.List<com.company.domain.Item>
  found:    java.util.List

The code builds successfully with this warning.  It probably doesn't matter, but this is Spring 4 and Hibernate 4.
Update, based on comments:
I attempted to edit my example for a general case rather than providing company specific code.   For those quick to downvote, as supporting evidence: here is the actual output from my editor and the actual code, using Java 7 with the company name redacted.

Below is the terminal output, without using an editor, but javac with ant:

A: Update:
This is a javac bug that affects the versions: 6u51, 7u21, 8. That was reported and fixed here:JDK-8016099.
Other related reports are:  JDK-8022144 and JDK-8016636 but they are all marked as duplicate to the first one.
That was fixed in 1.8.0u65.

A: TL; DR: Declare the evaluated static String before the method as a workaround.
I am able to clear the warnings in a rather unorthodox way and it may be a bug - or some ridiculous "feature" :).
The examples that follow describe the behavior.  Each one uses the @SuppressWarnings annotation.
If I use the evaluated String as in (a), no warning is shown.
If I declare the String prior to the method call as in (b), no warning is shown.
Making the string a private member in the same class has no effect and still produces the compiler warning (b).

If we evaluate the constant first, it produces no warning, as in (d):


text:
Q: Best approach to get ipv4 last octet I know substring can handle this but, is there a better way to get last octet from an IP ?
Ex.:
192.168.1.100
I want 100
Tks

A: just for fun:
Console.WriteLine(IPAddress.Parse("192.168.1.33").GetAddressBytes()[3]);

A: Just for fun I wrote the version which would have the least overhead (string manipulation etc.). @rushui has the correct answer though.
static void Main(string[] args)
{
    Console.WriteLine(OctetInIP("10.1.1.100", 0));
    Console.ReadLine();
}

static byte OctetInIP(string ip, int octet)
{
    var octCount = 0;
    var result = 0;

    // Loop through each character.
    for (var i = 0; i < ip.Length; i++)
    {
        var c = ip[i];

        // If we hit a full stop.
        if (c == '.')
        {
            // Return the value if we are on the correct octet.
            if (octCount == octet)
                return (byte)result;
            octCount++;
        }
        else if (octCount == octet)
        {
            // Convert the current octet to a number.
            result *= 10;
            switch (c)
            {
                case '0': break;
                case '1': result += 1; break;
                case '2': result += 2; break;
                case '3': result += 3; break;
                case '4': result += 4; break;
                case '5': result += 5; break;
                case '6': result += 6; break;
                case '7': result += 7; break;
                case '8': result += 8; break;
                case '9': result += 9; break;
                default:
                    throw new FormatException();
            }

            if (result > 255)
                throw new FormatException();
        }
    }

    if (octCount != octet)
        throw new FormatException();

    return (byte)result;
}

A: It may be overkill, but a simple regex would also do the trick:
(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})

A: Remember what an IP address is, it is a 32-bit (4 byte) number. So masking the address with the subnet mask would actually be the correct way to do it. If you always want a subnet mask of 255.255.255.0, as your question implies, you can & the number with 0xFF to get the number.
But, if you don't care about efficiency, and only have the address as a string, the split on "." is just fine... :)


text:
Q: R Shiny REST API communication I have a shiny app that takes a JSON input file, runs it through a classifier and returns a classified JSON object.
I want the app to be able to communicate with an API. I want the API to post a file to the Shiny App which will do its work and return a classified object.
Basically I want the Shiny app to sit in the background until a file is posted and then do its work.
I know that I can use GET from the httr package to get a file from a url. I can put this in the shiny.server file which is fine if I know the file name for the get command
However the filenames coming from the API will be different. So is there any way that I can make this dynamic according to the Post request that comes from the API.

A: By now library(plumber) needs to be mentioned as an alternative in this context, however the following example is showing how to handle POST requests directly in shiny.
It is based on Joe Cheng's gist here, which suggests to add an attribute "http_methods_supported" to the UI and use httpResponse to answer the requests.
The below code starts a shiny app in a background R process (This is done only to have a single single file MRE - of course, you can put the app in a separate file and remove the r_bg-line). After the app is launched the parent process sends the iris data.frame to the UI.
In the UI function the req$PATH_INFO is checked (see uiPattern = ".*"), then the numerical columns are multiplied by 10 (query_params$factor) and send back as a json string.
library(shiny)
library(jsonlite)
library(callr)
library(datasets)

ui <- function(req) {
  # The `req` object is a Rook environment
  # See https://github.com/jeffreyhorner/Rook#the-environment
  if (identical(req$REQUEST_METHOD, "GET")) {
    fluidPage(
      h1("Accepting POST requests from Shiny")
    )
  } else if (identical(req$REQUEST_METHOD, "POST")) {
    # Handle the POST
    query_params <- parseQueryString(req$QUERY_STRING)
    body_bytes <- req$rook.input$read(-1)
    if(req$PATH_INFO == "/iris"){
      postedIris <- jsonlite::fromJSON(rawToChar(body_bytes))
      modifiedIris <- postedIris[sapply(iris, class) == "numeric"]*as.numeric(query_params$factor)
      httpResponse(
        status = 200L,
        content_type = "application/json",
        content = jsonlite::toJSON(modifiedIris, dataframe = "columns")
      )
    } else {
      httpResponse(
        status = 200L,
        content_type = "application/json",
        content = '{"status": "ok"}'
      )
    }
  }
}
attr(ui, "http_methods_supported") <- c("GET", "POST")

server <- function(input, output, session) {}

app <- shinyApp(ui, server, uiPattern = ".*")
# shiny::runApp(app, port = 80, launch.browser = FALSE, host = "0.0.0.0")
shiny_process <- r_bg(function(x){ shiny::runApp(x, port = 80, launch.browser = FALSE, host = "0.0.0.0") }, args = list(x = app))

library(httr)
r <- POST(url = "http://127.0.0.1/iris?factor=10", body = iris, encode = "json", verbose())
recievedIris <- as.data.frame(fromJSON(rawToChar(r$content)))
print(recievedIris)
shiny_process$kill()

Please also check this related PR which is providing further examples (also showing how to use session$registerDataObj) and is aiming at a better description of the httpResponse function.

A: If you do not have to use Shiny, you can use openCPU. OpenCPU provides each of your R packages as REST service automatically. I work with OpenCPU and it works fine! It is the easiest way to use R from another program.


text:
Q: How does VFlib process .GF and .PK bitmap file formats? Recently I made a small helping module in FreeType for my research work. This module is mainly responsible for processing a METAFONT input by client application. I used FTVIEW as my client application that takes a METAFONT file to display styled text on screen.
I am using the Mftrace program for converting any METAFONT request into its corresponding Type1 format and then, using the default Type1 driver module, I am processing it and displaying results on screen. It's working fine.
Now what I want is to use the mf program (the default compiler of METAFONT) instead of Mftrace, to process METAFONT using FreeType. The mf program takes a .mf file as input and returns a .tfm and .gf file. This .gf file is then converted using GFtoPK or GFtoDVI into .pk or .dvi files respectively and then can be used for displaying.
As FreeType engine doesn't support .gf and pk files respectively, I came to know that there is an old library called VFlib that actually supports these two types of files. I have read about VFlib and got to know that it is also a font library that handles many font types and can make glyphs as bitmaps from these different font formats like .ttf, .pfb, .gf, .pk etc.
As .gf and .pk files are actually bitmap font formats (the later is the more compressed file of .gf file which can be obtained by using programs like GFToPK), my question is: how does this VFlib library actually support .gf and .pk formats? What is the main task of this library if a .gf or .pk file is input?

A: After reading some papers on this
 VFlib library i got my answer.
Primary purpose of GF and PK font driver is that application programmer dont need to know the internal data representation in GF and PK font files. VFlib converts bitmaps in a common format. The term "common format" means VF_Bitmap structure defined in VFlib. That is the common data structure for representing bitmap data in VFlib. Regardless data style (bitmap/outline) of fonts, VFlib uses the VF_Bitmap structure to represent bitmap of a character in font.
Another purpose of gf and pk support is that. Because they are in bitmap form, we must prepare many files for different magnification and resolution. For example, when we use "cmr10" font, we must select appropreate font files generated by MetaFont.
For example,
 - Mangification 1.00, 300 dpi --> "cmr10.300pk"
 - Mangification 1.20, 300 dpi --> "cmr10.360pk"
 - Mangification 1.00, 600 dpi --> "cmr10.600pk"
 - Mangification 1.20, 600 dpi --> "cmr10.720pk"

Selecting appropriate file name is tedious, and VFlib does the messy things. Given parameters fontname (e.g., "cmr10.pk"), device resolution (e.g., 300), and magnification (e.g., 1.20), VFlib PK driver internally computes appropriate file
 ame (e.g., "cmr10.360pk") and find its location in filesystem. Application
 programmer need not to care about actual font file names and font directories.
 Refrence 1
 Refrence 2


text:
Q: Save return as  I'm saving a textarea to a to a file using php and then want to then use in a
include 'text.txt';. How can I have all the textarea's returns save as <br>?
Thanks for any help

A: The function nl2br does exactly that, so call it on the input before saving it.


text:
Q: how to denied some folder in core api I have a core api project.
I want to get static files with full path within the project. I want to prevent access to the directory where the file is located and the directories above it.
How can I do that?
enter image description here
enter image description here


text:
Q: How to save input value after submit form? I am working on a Asp.net core 2 project. As part of my project, I need to look at the results with the paging. look at image please

after submitted search form the value of input deleted.

And when I Click on page 2, I can not see the rest of the results
How can i save input value after submitted form?
Controller
 public IActionResult SearchResult(string txtsearch, int page = 1)
    {
        var model = new IndexModel();
        if (txtsearch != null)
        {
            //Paging/////////////////////////////////////////////////////////////////////////
            int paresh = (page - 1) * 3;
            int count = _iuw.NewsRepositoryUW.Get(n => n.Title.Contains(txtsearch)).Count();

            ViewBag.PageID = page;
            double counter = count % 3;
            if (counter != 0)
            {
                ViewBag.PageCount = (count / 3) + 1;
            }
            else
            {
                ViewBag.PageCount = count / 3;
            }

            model.searchModel = _iuw.NewsRepositoryUW.Get(n => n.Title.Contains(txtsearch)).Skip(paresh).Take(3).ToList();
            if (model.searchModel.Count() > 0)
            {
                ViewBag.searchVal = txtsearch;
                return View("Searchresult", model);
            }
            else
            {
                model.searchModel = null;
            }
        }
        return View("Searchresult", model);
    }

search form
             <form class="navbar-form navbar-left" asp-action="SearchResult" asp-controller="Home" method="get">

                <div class="form-group">
                    <input type="text" id="txtsearch" name="txtsearch" class="form-control" placeholder="Search">
                </div>
                <button type="submit" class="btn btn-default">Search</button>
            </form>

A: As @Stephen Muecke suggested , you can add search property to your model and use TagHelper for the search property .
If you want to implement your requirement without using model binding , base on your codes, you could try :
 <input type="text" id="txtsearch" name="txtsearch" class="form-control" placeholder="Search" value="@(ViewBag.txtsearch ?? String.Empty)">

And set value in controller :
ViewBag.txtsearch = txtsearch;


text:
Q: Reading values sequential from a table in SQL I have following table structure which is generated based on the selection from a UI and it is stored as it has been generated from UI. This is basically store query sequence.
e.g

(( Condition AND Condition) OR ( Condition ))

Id  ConditionType Value         Brackets
 1     NULL        NULL           (
 2     NULL        NULL           (
 3     NULL        Condition      NULL
 4     AND         NULL           NULL
 5     NULL        Condition      NULL
 6     NULL        NULL           )
 7     OR          NULL           NULL
 8     NULL        NULL           (
 9     NULL        Condition      NULL
10     NULL        NULL           )
11     NULL        NULL           )

From the above information I need to generate an index as :

Id  StartIndex   EndIndex
1     1           11
2     2            6
3     8           10

Any ideas on how to do this?

A: Edit: In the 1st version, I missed taking into account the nested levels.  This one I tested :)
I work on DB2, so you'll likely have to refactor this for sql-server if it doesn't support a LATERAL join, but this one produced the correct results with your set of values on DB2:
with CTE_ONLY_BRACKETS as (
  select *
  from   MYLIST
  where  Brackets in('(',')')
) ,

CTE_NEST_INCREMENT as (
  select   Id
          ,Brackets
          ,case when Brackets = '(' then 1 else -1 end as NEST_INCREMENT
  from     CTE_ONLY_BRACKETS
) ,

CTE_NEST_LEVEL as (
  select    Id
           ,Brackets
           ,S.NEST_LEVEL
  from      CTE_NEST_INCREMENT C
  cross join lateral (
    select  sum( NEST_INCREMENT ) as NEST_LEVEL
    from    CTE_NEST_INCREMENT S
    where   S.Id <= C.Id
  ) as S

)

select   row_number() over() as Id
        ,L.Id as StartIndex
        ,R.Id as EndIndex
from     CTE_NEST_LEVEL R

cross join lateral (
  select L.Id
  from   CTE_NEST_LEVEL L
  where  L.Brackets = '('
    and  L.Id < R.Id
    and  L.NEST_LEVEL = R.NEST_LEVEL + 1
  order by L.Id desc
  fetch  first row only
) as L

where    R.Brackets = ')'

order by L.Id

A: You can try this.
DECLARE @SampleDate TABLE (Id INT, ConditionType VARCHAR(10), Value VARCHAR(10), Brackets VARCHAR(10))
INSERT INTO @SampleDate VALUES
(  1, NULL , NULL           , '('),
(  2, NULL , NULL           , '('),
(  3, NULL , 'Condition'    , NULL),
(  4, 'AND', NULL           , NULL),
(  5, NULL , 'Condition'      , NULL),
(  6, NULL , NULL           , ')'),
(  7, 'OR' , NULL           , NULL),
(  8, NULL , NULL           , '('),
(  9, NULL , 'Condition'    , NULL),
( 10, NULL , NULL           , ')'),
( 11, NULL , NULL           , ')')

;WITH CTE AS (
    SELECT * FROM @SampleDate T1
        OUTER APPLY ( SELECT SUM (CASE
                            WHEN Brackets = '(' THEN 1 WHEN Brackets = ')' THEN -1 ELSE 0 END) Inx
                FROM @SampleDate T2
                WHERE T1.Id >= T2.Id ) X
)
SELECT
    ROW_NUMBER() OVER(ORDER BY X1.Id) AS Id,
    X1.Id StartIndex,
    T.Id EndIndex
FROM CTE X1
OUTER APPLY (SELECT TOP 1 * FROM CTE X2
                WHERE X2.Brackets =')' AND X2.Id > X1.Id AND X2.Inx = X1.Inx - 1 ORDER BY X2.Id ) AS T
WHERE
    X1.Brackets ='('

Result:
Id                   StartIndex  EndIndex
-------------------- ----------- -----------
1                    1           11
2                    2           6
3                    8           10


text:
Q: The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'. Dart Issue in Grouping the List according to date I am trying to group the API data according to date.
But I am getting this error:
The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'.

The error is on this line:

groupBy(prayerDetails, (obj) => obj['msgdate'].toString());

How can I resolve this error?
This is my code:
var groupByDate =
          groupBy(prayerDetails, (obj) => obj!(obj as Object)['msgdate'].toString());
      groupByDate.forEach((date, list) {
        print('Grouped Date');
        print('$date:');

        list.forEach((listItem) {
          print('${listItem["msgdate"]}, ${listItem["message"]}');
        });

        print('\n');
      });


text:
Q: How to show loading image and disable button for 3 sec before start send post data from another page using ajax post? How to show loading image and disable button for 3 sec before start send post data from another page using ajax post ?
After press ok button i want to display loading image and disable
<input type="button" value="Check" onclick="doajax_products_check()"/>
for 3 sec and then start send requests to data.php
How can i do that ?
index.php
<form name="form1" method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);" style=" margin: 0px; " >
<input type="text" name="products_id" value="1294759">
<input type="text" name="products_color" value="red">
<input type="text" name="products_type" value="electronic">
<input type="button" value="Check" onclick="doajax_products_check()"/>

</form>

data.php
<?PHP
if(isset($_POST['products_color']))
    {
        if ( $_POST['products_id'] != '' )
            {
                if ( $_POST['products_type'] != '' )
                    {
?>
PRODUCTS DATA OK
<?PHP
         }
         else
         {
?>
NO PRODUCTS type
<?PHP
       }
    }
    else
    {

?>
   NO PRODUCTS ID

      }
    }
        else
            {
       ?>
       NO PRODUCTS COLOR

            }
        ?>

A: You could use settimeout function to delay the action.
function your_function() {
    // send requests to data.php
    }

$(document).ready(function() {
       setTimeout(your_function,3000);
       // the function you called by setTimeout.
    });

A: Try this JQuery code:
function buttonClicked()
{
    $('#your_buttons_id').off('click'); // Disable button click
    $('#your_loader_element').show(); // Show loading element
    setTimeout(function(){
        $('#your_loader_element').hide(); // Hide loading element
        $('#your_buttons_id').click(buttonClicked); // Enable button click
    }, 3000);
    doajax_products_check(your_data); // Call to ajax
}

$(function(){
    $('#your_buttons_id').click(buttonClicked); // Enable button click on page load
});

A: try to use blockui http://malsup.com/jquery/block/
Block ui gives you the same effect and also is extendable to many views


text:
Q: Attribute is required but not set (Unable to create snapshot class for interface) My Liferay 7 server was using SomeModule happily, until I deployed a new version of SomeModule which has an additional required field favoriteColor.
Now whenever I try to load the portlet Liferay says:
java.lang.RuntimeException: Unable to create snapshot class for interface some.SomeModuleConfiguration
        at com.liferay.portal.configuration.metatype.bnd.util.ConfigurableUtil._createConfigurableSnapshot(ConfigurableUtil.java:77)
        at com.liferay.portal.configuration.metatype.bnd.util.ConfigurableUtil.createConfigurable(ConfigurableUtil.java:51)
        at some.SomeModule.activate(SomeModule.java:50)
...
aused by: java.lang.IllegalStateException: Attribute is required but not set favoriteColor
        at aQute.bnd.annotation.metatype.Configurable$ConfigurableHandler.invoke(Configurable.java:75)
        at com.sun.proxy.$Proxy1220.favoriteColor(Unknown Source)
        at some.SomeModuleConfigurationSnapshot407.<init>(Unknown Source)

The configuration UI for SomeModule does not show anything about favoriteColor.
How to fix that, for instance by setting favoriteColor to its default value?

A: If you are lucky enough to have the source code of the module, you can solve this problem like this:

*

*Temporarily make the new field optional, but replacing required = true to required = false in SomeModuleConfiguration.java.

*Deploy the module.

*Load the configuration page, save.

*Restore to required = true.

*Deploy again.

Alternative answers welcome!

A: An alternative path would be using a OSGi configuration file to set defaults and missing values. You can use those files as you do for those modules that come with liferay; e.g., elasticsearch config. (check your osgi/configs directory)


text:
Q: Assigning __str__ method in __init__ not working as expected in Python I tried to conditionally create the
__str__

method in a python class, as recommended here and here and I understand that is is not recommended to do this. But for my understanding, doing:
from types import MethodType

def str_fcn(self):
    return self.a

class A(object):
    def __init__(self, a=None):
        if a is not None:
            self.a = a
            self.__str__ = MethodType(str_fcn, self)
            self.test = MethodType(str_fcn, self)

a = A(a="name")

print(a)
print(a.test())

Does not seem to work for magic methods. The last print call at the end prints "name" as I expect, but the first uses the default string representation. Why?


text:
Q: Do I need to include a textdomain if my theme doesn't support translation? According to the codex

Themes are required to use theme-slug (or a reasonable facsimile) as textdomain for translation

Does this mean that my theme needs to include a textdomain even if my theme doesn't support translation? ... and also is there any harm in including a textdomain in style.css if there are no translation options.

A: If your code, be it a theme or a plugin, does not support translation, then don't use the translation functions. And if you don't use these functions, you cannot use a text domain. :)
There is a very common error that looks like this:
echo __( 'Portfolio' );

Portfolio is not part of WordPress' core strings, so this code will waste an expensive look-up in the list of translated words without result.
Another side effect is a partial translation when some of these function calls without text domain match core strings. Imagine a navigation where the link to the previous page is in Japanese and the link to the next page in English. This is worse than no translation at all.
So text domains are not your problem, the use of translation functions is important.


text:
Q: TeamCity agent returning 502 bad gateway I'm getting this when starting up a TeamCity agent. To expose TC Server on EC2 I'm using Application request routing, Created a Server Farm and route 80 to 8080 internally. I can see mention of Port 9090 in below logs - I'm wondering if I would need to create a second application request route for 9090 - I haven't seen mention of this in any docs - anyone have XP with this?
[2014-02-09 07:31:35,994]   INFO - buildServer.AGENT.registration - Registering on
server http://team.xxxx.com.au, AgentDetails{Name='WIN-IXXX',
AgentId=null, BuildId=null, AgentOwnAddress='null', AlternativeAddresses=
[10.xxx.xxx.xxx, 54.xxx.xxx.xxx], Port=9090, Version='27767', PluginsVersion='NA',
 AvailableRunners=[], AvailableVcs=[], AuthorizationToken=''}

[2014-02-09 07:32:08,567]   WARN - buildServer.AGENT.registration - Call
http://team.xxxx.com.au/RPC2 buildServer.registerAgent3:
org.apache.xmlrpc.XmlRpcClientException: Server returned incorrect status code: 502 Bad
Gateway

A: The TeamCity server needs to be able to open HTTP connections to the agent via the ownPort property of the buildAgent.properties file. That port is, by default, 9090.
You can read more here:
TeamCity - Setting Up Additional Build Agents


text:
Q: How do I drill down and find out which System processes are generating lots (10Mb/s) of network traffic? Symptoms

*

*Every night around 7-9pm my network traffic jumps up from about 100 kb/s (with nothing upr or downloading) to about 10Mb/s.  95% of that is reported as the System process. And it stays there until I restart either my "server" (Windows 7 Pro) or my primary computer (also Windows 7 Pro).  (This does not affect other PCs on my network.

*Also when the system is in this state, copying files between the two PCs is very slow: takes about 10 to 100 times longer. Transfer rates drop to about 1 Mb/s or less. (I've gotten 10 Mb/s+ transfer rates routinely)
What I've tried:

*

*I've looked for items in the Task Scheduler on both computers and removed them, then restarted, and it happened again.

*Disabled every Process that didn't seem necessary (on Server and main PC). Didn't affect anything.


text:
Q: sbt package error on leftJoinWithCassandraTable spark cassandra spark-cassandra function leftJoinWithCassandraTable works fine in spark-shell but while packaging in sbt I am getting below mentioned error.
My scala code snippet
case class time_struct(id: String, month: Int, day: Int, platform: String, type_1: String, title:String,
                      time: Long)
val rdd = time_data.mapPartitions( data =>
          data.map( row =>
              time_struct(row.getString(0),row.getInt(1),row.getInt(2),row.getString(3),row.getString(4),row.getString(5),row.getDouble(6).toLong)))
val join = rdd.leftJoinWithCassandraTable("ks1", "tbl1",SomeColumns("time" ),
           SomeColumns("id"))

$ sbt package
[error] Test.scala:187: could not find implicit value for parameter rwf: com.datastax.spark.connector.writer.RowWriterFactory[time_struct]
[error]     val join = rdd.leftJoinWithCassandraTable("ks1", "tbl1",SomeColumns("time" ),
[error]                                              ^

build.sbt
scalaVersion := "2.11.8"
scalacOptions := Seq("-unchecked", "-deprecation", "-encoding", "utf8")

libraryDependencies ++= {
  val sparkV = "2.1.0"

  Seq(
    "org.apache.spark" %% "spark-core" % sparkV % "provided",
    "org.apache.spark" %% "spark-sql" % sparkV % "provided",

    "com.datastax.spark" % "spark-cassandra-connector_2.11" % "2.0.0-RC1",
    "com.databricks" %% "spark-csv" % "1.5.0"
)
}

libraryDependencies += "org.apache.hadoop" % "hadoop-aws" % "2.7.1"

Environment :
scala 2.11.8
spark 2.1.0
sbt 0.13.13

A: I got my mistake i had declared the case class inside the main function.
After i moved the case class definition out of main function it compiled successfully.


text:
Q: How to suppress InMemoryEventId.TransactionIgnoredWarning when unit testing with in-memory database with transactions? I'm using an EF Core in-memory database and I'm trying to run a unit test on a method that uses transactions:
using (var transaction = await _context.Database.BeginTransactionAsync())
{
    _context.Update(item);
    result = await _context.SaveChangesAsync();

    // some other stuff

    transaction.Commit();
}

However, I'm getting this error from the test runner:

System.InvalidOperationException: Warning as error exception for
warning 'InMemoryEventId.TransactionIgnoredWarning': Transactions are
not supported by the in-memory store. See
http://go.microsoft.com/fwlink/?LinkId=800142 To suppress this
Exception use the DbContextOptionsBuilder.ConfigureWarnings API.
ConfigureWarnings can be used when overriding the
DbContext.OnConfiguring method or using AddDbContext on the
application service provider.

How do I suppress that error?

A: I used the answer from @tomRedox but varied it for use in an ASP.NET Core 2.0 startup.cs file.
services.AddDbContext<MyDbContext>(options =>
{
    options.UseInMemoryDatabase("TestDb");
    options.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning));
});

A: In the code where you declare the in-memory database, configure the context to ignore that error as follows:
public MyDbContext GetContextWithInMemoryDb()
{
    var options = new DbContextOptionsBuilder<MyDbContext>()
        .UseInMemoryDatabase(Guid.NewGuid().ToString())
        // don't raise the error warning us that the in memory db doesn't support transactions
        .ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning))
        .Options;

    return new MyDbContext(options);
}


text:
Q: Вывод данных из 3-х таблиц в одну (mysql, php) Подскажите, пожалуйста, как правильно вывести данные из трех таблиц в одну?
Ниже прикладываю скрины таблиц:
1 таблица - tb_clients:

2 таблица - tb_orders:

3 таблица - tb_items

Необходимо получить таблицу следующего вида:

Попробовал разные запросы, толком ничего не получилось. Возможно таблицы не верно составлены, но пытался сделать по следующей логике - завожу клиента, к клиенту цепляю заказ, к заказу цепляю позиции.
Программка работает корректно, но вот вывести так сказать сводную табличку со всеми заказами в таком виде не получается.
Если не трудно подскажите советом куда копать.
Заранее спасибо!


text:
Q: React-Google-Maps DirectionsRenderer Panel When using the react-google-maps wrapper, does anyone know how to use "panel" as a prop in the directions renderer to display a panel that shows text instructions for a route that has been mapped.
https://tomchentw.github.io/react-google-maps/#directionsrenderer

A: Was able to render a directions panel by setting props to:
(props =>
  <GoogleMap defaultZoom={7}>
    {props.directions && <DirectionsRenderer directions={props.directions}
    panel={ document.getElementById('panel') } />}

  </GoogleMap>
);


text:
Q: Android Webservice do not return expected data in listview I want to fetch a listview from webservice in Android app. I managed to get the data when i tried to break my code. But this is what I get when i break the code in the array list:
[com.xxx.example.Hotels@41319dc0, com.xxx.example.Hotels@4131a518, com.xxx.example.Hotels@4132fec8, com.xxx.example.Hotels@413323a0]
Below is my code that called the list.
mainListView = (ListView) findViewById(R.id.lview);
    WebService2 cs = new WebService2();
    listHt = cs.selectAllHotels();
    listAdapter = new HotelArrayAdapter(this, listHt);
    mainListView.setAdapter(listAdapter);

Below is the code called the webservice.
public ArrayList<Hotels> selectAllHotels() {
    ArrayList<Hotels> lst = new ArrayList<Hotels>();
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    SoapObject table = null;
    SoapObject responseBody = null;

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    try {

        androidHttpTransport.call(SOAP_ACTION, envelope);
        responseBody = (SoapObject) envelope.getResponse();

        responseBody = (SoapObject) responseBody.getProperty(1);
        table = (SoapObject) responseBody.getProperty(0);

        for (int i = 0; i < table.getPropertyCount(); i++) {
            Hotels dto = new Hotels();
            SoapObject row = (SoapObject) table.getProperty(i);
            dto.setName(row.getProperty("HOTELNAME").toString());
            lst.add(dto);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return lst;
}


text:
Q: The Maximal Ergodic Theorem more than once Suppose we have a dynamical system and a sequence of functions $0=f_0\leq f_1\leq\cdots\leq f_k$.  Define $J_{r,\lambda}$ to be the set of points $x$ such that there are $j_0<j_1<\cdots<j_r$ so that, for each $i<r$, $\sup_n A_n(f_{j_{i+1}}-f_{j_i})(x)>\lambda$.  Using the maximal ergodic theorem, we see that $\mu(J_{1,\lambda})\leq ||f_k||_1/\lambda$.  Is there a similar bound on $\mu(J_{r,\lambda})$ (maybe even $||f_k||_1/r\lambda$)?
Note that this doesn't seem to trivially reduce to multiple applications of the maximal ergodic theorem, because the sequences of $j$'s might overlap between different points, and one point might see $r$ jumps from $0$ to $j_r$, while another point doesn't see any jumps until some $j'>j_r$.
(We have some ideas that might show this, at least for a slightly more restrictive definition of $J_{r,\lambda}$---that there are $n_0<\cdots<n_{r-1}$ so that, for each $i<r$, $A_{n_i}(f_{j_{i+1}}-f_{j_i})(x)>\lambda$---but they're messy, and it seems like a clever use of the maximal ergodic theorem should give a slick proof, but we don't see how to do it.)

A: You can't do substantially better than $\|f_k\|_\lambda$. Here's a simple example: Consider $X=\{0,1,\ldots,2^{N}-1\}$, equipped with normalized counting measure. The transformation is $T(x)=x+1\bmod 2^{N}$. The functions are
$$
f_i(x)=\begin{cases}
2&\text{if $x<i$;}\\
0&\text{otherwise.}
\end{cases}
$$
for $i=0,\ldots,2^{N}$.
Let $\lambda=1$. Now if $j<2^N-2^{N/2}$ and $1\le n\le N/2$, consider $f_{j+2^{n}}-f_{j+2^{n-1}}$. This takes values 2 on the range $j+2^{n-1}$ to $j+2^n-1$
and 0's elsewhere. The maximum of the Birkhoff averages evaluated at $j$ is therefore 1. Hence for each $j\in \{0,\ldots,2^N-2^{N/2}-1\}$, $j\in J_{N/2,1}$. That is, $\mu(J_{N/2,1})\ge 1-2^{-N/2}$, but $\|f_{2^N}\|=2$. You cannot do better than $\mu(J_{r,\lambda})\le \|f_k\|/(2\lambda)$.


text:
Q: I can't replace properly with javascript and regex I have this string:
var value = recordsArray_f006b490[]=1&recordsArray_9715b841[]=1&recordsArray_afb085e2[]=1&recordsArray_fc542e23[]=1&recordsArray_19490084[]=1&recordsArray_615a5055[]=1&recordsArray_32841aa6[]=1&recordsArray_a02a35c7[]=1&recordsArray_d32b5b88[]=1&recordsArray_d32d5339[]=1&recordsArray_56c2b8e10[]=1&recordsArray_8ce9f4211[]=1&recordsArray_5a87afc12[]=1&recordsArray_2b13c0113[]=1&recordsArray_afb085e14[]=1&recordsArray_51db9f216[]=1&recordsArray_2a7470415[]=1&recordsArray_d51057a17[]=1&recordsArray_b274ee918[]=1&recordsArray_d0812dd19[]=1&recordsArray_b1ede8920[]=1&recordsArray_9d76ae821[]=1&recordsArray_0ae779d22[]=1&recordsArray_871777923[]=1&recordsArray_9e22c9f24[]=220236&recordsArray_787c57e25[]=220236&recordsArray_499e25726[]=1&recordsArray_a0600da27[]=220236&recordsArray_9ef1fca28[]=220236&recordsArray_67eee1929[]=220236&recordsArray_24c3a0b30[]=220236&recordsArray_5d2090831[]=220236

And I want to replace "[]=" with "_" and I have the next javascript code:
var regex = new RegExp("[]=", "g");
alert(value.replace(regex, "_"));

but it doesnt change anything, how can I do it? Thanks!

A: Escape the first [ to indicate its not defining a character class;
 var regex = new RegExp("\\[]=", "g");

A: Square brackets are reserved in regex.  You need to escape them for matching
var regex = new RegExp("\\[\\]=", "g");

A: escape the brackets as they has special meaning.
var regex = new RegExp("\\[\\]=", "g");

A: As others have noted, you need to escape the square brackets, as they have special meaning in regex. I want to note, also, that the most clear and terse way to do this is with JavaScript's regex literal notation:
 var regex = /\[]=/g;

You also only need to escape the opening [ bracket. Closing brackets (the ] character) only have a special meaning inside a character class, just as [ only has special meaning outside one.

A: You can't include brackets in regexp. Use \\[ for this.


text:
Q: HTML async and defer The documentation says that with async or defer attribute defined for the external script

the file can be downloaded while the HTML document is still parsing

Does this mean that the browser fires extra thread when the parser reaches the script tag
? If so how does it relate to the statment

JavaScript is single threaded

as stated on this site?

A:
Does this mean that the browser fires extra thread when the parser reaches the script tag?

That's an implementation detail.

If so how does it relate to the statment

JavaScript is single threaded

It doesn't relate to it at all.
"Downloading an HTTP resource" and "Running a JavaScript program" are completely different things.


text:
Q: array.some is not a function in My Laravel Vue Js Project I Practicing laravel & Vue js project. Here i have a wishlist button.
<button
:class="wishlists.some(wishlist => wishlist.product_id === productId) ? activeClass:deactiveClass"
v-html="wishlists.some(wishlist => wishlist.product_id === productId) ? activeText:deactiveText"
@click="wishlistStatus(productId)" >
</button>

This is working perfectly but this is throwing also 2 errors.

[Vue warn]: Error in render: "TypeError: _vm.wishlists.some is not a function
and
TypeError: _vm.wishlists.some is not a function.
Now How I fix this

A: To use the 'some' method, your 'wishlists' variable must be an array.
If at the time your component initializes, that variable is not yet an array, then your application is going to crash.
This usually happens when you initialize your variable, for example, to null and then make a call to the server to fetch the data.
data() {
  whislists: null,
  ...
}

There are several ways to fix this:

*

*The simplest is to initialize your variable as an array.

data() {
  whislists: [],
  ...
}

*Another way to solve it would be to wait for your variable to become an array and then render your button, You can achieve this using a v-if.

<button
  v-if="wishlists && wishlists.length"
  :class="wishlists.some(wishlist => wishlist.product_id === productId) ?
  activeClass:deactiveClass"
  v-html="wishlists.some(wishlist => wishlist.product_id === productId) ?
  activeText:deactiveText"
  @click="wishlistStatus(productId)" >
</button>

This may be just one of the reasons why your problem occurs.
Other reasons could be:
You are assigning to your variable 'wishlists' data that is not an array without realizing it.


text:
Q: Proper change of coordinates It's a really easy one for you guys.
I'm performing a simple cylindrical change of variable from Cartesian coordinates, but I want to write it out properly and I'm stuck with the differential matrices. I won't get into details on everything here but I'll focus on my issue.
I consider the diffeomorphism $\Psi$ matching the cylindrical change of coordinates $\Psi : (r, \phi, z) \rightarrow (r\cos{\phi}, r\sin{\phi}, z)$
And I compute its jacobian $D\Psi$ as well as its inverse $(D\Psi)^{-1}$.
Now, for any vector field $A : (x, y, z) \rightarrow (A_x(x, y, z), A_y(x, y, z), A_z(x, y, z))$ and $\hat{A}  : (r, \phi, z) \rightarrow (A_r(r, \phi, z), A_\phi(r, \phi, z), A_z(r, \phi, z))$ I would like to set clearly the link between partial derivatives of these two vector fields in a matrix form such that, $D\hat{A}(r, \theta, z) = DA(\Psi(r, \phi, z))\circ D\Psi(r, \phi, z)$,
(edit) Where $D$ is the jacobian matrix.
My final goal would be to get $\partial_x A$ in function of the partial derivatives $\partial_r, \partial_\phi, \partial_z$ of $\hat{A}$ in order to express the differential operators such as curl or divergence in the new coordinate system, but I'm not sure how to do it. Thus, could someone help me out to clarify the procedure of this change of coordinates.
(edit) A confusing point I think is that we need to be cautious about the basis in which matrices are expressed. This is why I have trouble apprehending the matrix formulation, I don't know if we can get something like $J(A)_{x, y, x} = T J(\hat{A})_{r, \phi, z}$ where $J$ is the jacobian, and $T$ a matrix to be computed.
I'm a bit ashamed to ask it here, but sometimes you just can't figure out basic stuff.
Thanks in advance.

A: I'm not as familiar with the Jacobian-based methods, although all methods for answering this are equivalent. Here's what I would do.
Ignore the $z$-coordinate, since it is the same for both coordinate systems, and because coordinate basis vector fields are linearly independent (i.e., if $e_x,e_y,e_z$ is the Cartesian basis then the vector fields that form it are linearly independent; the same holds for any other basis; however if $e_r,e_\phi,e_z$ is the polar basis then there can be a relationship between, e.g., $e_r,$ $e_x$ and $e_y$). Therefore just look at polars $r,\phi$ in the $x,y$-plane. Write down the conversion formulae (you already have them implicitly in your diffeo):
\begin{align} x   &= r \cos (\phi), \\
              y   &= r \sin (\phi). \end{align}
This gives
\begin{align} r    &= (x^2 + y^2)^{1/2}, \\
              \phi &= \tan^{-1} (\frac{y}{x}). \end{align}
Hence we have $\partial r / \partial y = \frac{y}{(x^2 + y^2)^{1/2}} = \sin(\phi)$ and $\partial \phi / \partial y = \frac{x}{x^2 + y^2} = \frac{\cos(\phi)}{r}$. You should find that these two results are exactly two of the terms in the Jacobian of the transformation (similarly for the derivatives w.r.t. $x$). The chain rule of multi-variable calculus then gives that, e.g.,
\begin{align} \frac{\partial}{\partial y} &= \frac{\partial r}{\partial y} \frac{\partial}{\partial r} + \frac{\partial \phi}{\partial y} \frac{\partial}{\partial \phi} \\
&= \sin(\phi) \frac{\partial}{\partial r} + \frac{\cos(\phi)}{r} \frac{\partial}{\partial \phi}. \end{align}
This is, I believe, the operator you sought in your final answer; you can then apply this to an arbitrary vector field, ideally given using the same cylindrical polar coordinates.


text:
Q: Delete list with a list comprehension How can I delete list inside list with list comprehension :
delete_canceled = [a_order for a_order in signal_order_position for c_order in signal_order_canceled if
             (a_order[0][0] in c_order[0][0] and a_order[0][1] in c_order[0][1] and a_order[0][4] in c_order[0][4])]

without using this:
    for delete_can in delete_canceled:
        signal_order_position.remove(delete_can)
        print "removed by canceled"


text:
Q: escape single quote in stored proc in oracle I have a requirement where I have extact the ddl for materialized view and execute it. I have create script for a materialized view as follows :
 CREATE MATERIALIZED VIEW "XXX"."AUD_MV_DCST" ("BUCKET", "ID", "SUM")
  ORGANIZATION HEAP PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
 NOCOMPRESS LOGGING
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "USERS"
  BUILD IMMEDIATE
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "USERS"
  REFRESH FAST ON COMMIT
  USING DEFAULT LOCAL ROLLBACK SEGMENT
  USING ENFORCED CONSTRAINTS ENABLE QUERY REWRITE
  AS SELECT TRUNC(STATUS_TIMESTAMP, 'HH24') BUCKET, ID, SUM(1)
  .....

I tried the below replace statement, but it does not work:
select replace(create_script, '''','''''') from dual

What is breaking this is
'HH24')

The opening and closing braces. I get the error:
ORA-00907: missing right parenthesis
ORA-06512: at "XXX.createProc", line 67
ORA-06512: at line 2

Here is the stored procedure that is executing this :
create or replace PROCEDURE procPrintOutput
IS
  -- var declarations ....

  BEGIN

    DECLARE
      -- Get the list of Materialized views.
      CURSOR LIST_OF_MatViews
      IS select *
         from user_mviews
         where MVIEW_NAME = 'TEAM_AUD_MV_NR';
      CURSOR CREATE_MatViews
      IS SELECT *
         FROM temp;
    BEGIN
      FOR Mat_View IN LIST_OF_MatViews
      LOOP
        BEGIN
          DBMS_OUTPUT.PUT_LINE('owner : ' || Mat_View.OWNER || ' - name : ' || Mat_View.MVIEW_NAME);

          -- save the create script of views to temp table.
          l_stmt := 'insert into temp SELECT SYS.DBMS_METADATA.get_ddl (''MATERIALIZED_VIEW'', '''
                    || Mat_View.MVIEW_NAME || ''') from dual';

          EXECUTE IMMEDIATE (l_stmt);
          DBMS_OUTPUT.PUT_LINE('inserted ... ');
          -- drop the view.
          --EXECUTE IMMEDIATE (drop_mat_view_logs_stmt || Mat_View.MVIEW_NAME);
          --DBMS_OUTPUT.PUT_LINE('view log dropped ... ');
        END;
      END LOOP;

      -- recreate view using the create script generated in the previous step.
      FOR MV_CREATE_SCRIPT IN CREATE_MatViews
      LOOP
        BEGIN
          DBMS_OUTPUT.PUT_LINE('SCRIPT : ' || MV_CREATE_SCRIPT.matViewLogQuery);
          replace_stmt := 'select replace(''' || MV_CREATE_SCRIPT.matViewLogQuery || ''','';'','' '') from dual';
          DBMS_OUTPUT.PUT_LINE('replace_stmt : ' || replace_stmt);

          EXECUTE IMMEDIATE (replace_stmt) INTO updated_stmt;
          DBMS_OUTPUT.PUT_LINE('Updated SCRIPT ?? ' || updated_stmt);
          --EXECUTE IMMEDIATE(updated_stmt);
          --DBMS_OUTPUT.PUT_LINE('view recreated ... ');
        END;
      END LOOP;
    END;
  END;

Any suggestions as to how this can be worked out ??

A: I tried the following and had no issues:
SQL> select trunc(current_timestamp, 'HH24') BUCKET from dual;

BUCKET
------------------
20-NOV-15

SQL>

Try just leaving off the precision specifier and use:
SQL> select trunc(current_timestamp) BUCKET from dual;

BUCKET
------------------
20-NOV-15

SQL>

HTH


text:
Q: Intermediate field of a Galois extension Let $N/K$ be a finite Galois extension such that $G = Gal(N/K)$ is an abelian group, and let $M$ be an intermediate field of $N/K$. Show that $M/K$ is normal and that $Gal(M/K)$ is abelian.
Here is what I have:
Let $\alpha \in N$ have the minimal polynomial $f(x)$ over $K$, and the minimal polynomial $g(x)$ over $M$. Then $g(x)$ divides $f(x)$. Now as $N/K$ is normal and has one root $\alpha \in N$ we know that $f(x)$ splits into linear factors over $N$ and that these factors are all distinct. Therefore $g(x)$ splits into distinct factors in $N$, meaning $N/M$ is normal and separable.
Also, if $\alpha \in M$ then $f(x)$ can't have a repeated root in $M$ since it doesn't in $N$, meaning $M/K$ is separable.
To prove that $M/K$ is normal we need to show that $M$ contains all of the roots of $f(x)$, but I'm not sure where to go from here.

A: Hint: it is always the case that $N/M$ is Galois, as you observe. The fundamental theorem of Galois theory says that the extension $M/K$ is Galois if and only if $\mathrm{Gal}(N/M)$ is a normal subgroup of $\mathrm{Gal}(N/K)$. Furthermore, it tells you that $\mathrm{Gal}(N/K)/\mathrm{Gal}(N/M) \cong \mathrm{Gal}(M/K)$. Can you see how to use the information you're given now?


text:
Q: solution for touch screen select option(html Select tag) I need help on solution for touch screen select option(html Select tag).
select option like select country and state are very hard to select in big touch screen. like mobile android(have image attached) and IOS using wrapper to expand select option, I need similar solution which I can use in my application.
any help will be appreciated.

A: this is one of example of POS made in Java for touch screen design and its open source
check it out http://www.openbravo.com/product/pos/


text:
Q: Let $K=${$(12)(34),(13)(24),(14)(23),1$} .Prove that $K$ is a normal subgroup of $S_4$. Now we need to prove that $gKg^{-1}=K$.So, we try to see the following that $g(12)(34)g^{-1}=g(1)g(2)g(3)g(4) \in K$.Although there are many hints to the problem,I particularly have a problem in one thing - If we take $g(1)g(2)$ as a cycle and $g(3)g(4)$ as a cycle then we try to find the number of possible $2-cycles$in $S_4$.
The possible 2-cycles are of the form $(ab)(cd)$ where the element $a$ has $4$ choices $b$ has $3$ choices .Now the $(ab)$ is the same as $(ba)$ , so we divide $(4×3)/2$ Similarly for the other part we get $(2×1)/2$ Now$(ab)(cd)$ has the same representation as $(cd)(ab)$so we divide the answer by $2$ to get $3$.Hence the number of cycles is .$3$ So they are in $K$.
Now my question is can we choose $g$ in such a way that the conjugate is a $4$ cycle .

A: An important equality in $\mathcal S_n$ is that if $(a_1 \ a_2 \dots \ a_k)$ is a cycle and $\sigma$ any element of $\mathcal S_n$ then
$$\sigma (a_1 \ a_2 \dots \ a_k) \sigma^{-1} = (\sigma(a_1) \ \sigma(a_2) \dots \ \sigma(a_k))$$
This is used in many areas when dealing with permutations.
Using that, you can prove that the cycle structure of any permutation is preserved by conjugacy.


text:
Q: Project Manager Software 2PLAN not launching on UBUNTU 14.04LTS. I need a help, please! I downloaded the software 2PLAN from their website, unzipped and trying to launch on UBUNTU 14.04LTS and the software not launch properly.
Usually, I used that software on UBUNTU 12.04LTS with no problem, just installing JAVA JDK 7 from Ubuntu software Center. But, that not working for UBUNTU 14.04LTS.
When I click on 2PLAN icon to launch the software, appears the "splash" screen and then the question to locate the WORKSPACE, but the software close after that, registering an error inside the 2PLAN FOLDER.
What I need to do to use the software on UBUNTU 14.04LTS?
Thank you very much for attention and help.


text:
Q: Ubuntu 20.04 will not install on 120GiB SSD I'm unable to install Ubuntu 20.04 on a 120GiB SSD because the device is not included in the list of devices available for install.
The SSD does show in gparted, with no partitions allocated, and an msdos partition table. The system is BIOS, not UEFI.
Subsequently, I've formatted the SSD with ext4, and can write to it - so there's no problem with the SSD itself.
What would prevent Ubuntu installer from seeing the SSD as a device it can install to?

A: Should have looked in syslog first...
ubuntu ubiquity: ERROR: pdc: wrong # of devices in RAID set "pdc_bffhbdggee" [1/2]

The BIOS was not configured for RAID, but the SSD had previously been used in a RAID configuration (so is the RAID information stored on the disk??? where???)
The fix was to configure the BIOS for RAID, delete the RAID configuration, then set the BIOS back to non-RAID. Then I was able to install to the SSD.
Another lesson learned was to disconnect all (5) unnecessary drives during install, because the install syslog is filled with irrelevant information about them - making is much harder to spot the one, crucial error message.


text:
Q: Usage of JWT after logout I have a query, is it possible to use current JWT after the user is logged out?
Scenario: I have a set of private APIs that needs authorization token to access the endpoints. Here I have a web application where I need to log in and get the JWT. I keep the token aside and from the active session I press the logout button and my session is needed to expiry even though I am able to use the JWT to access the endpoints, how will this happening is this the right approach or can I raise this as a bug?

A: How this is happening?
The session details might be stored in JWT itself and there is no server side state for the same. Every time you are sending the JWT, they are trying to decrypt it, then validating the claims present in it and providing the required access. Since, the JWT itself contains its expiry information, they are unable to invalidate it. It will be expired after specified time decided at the time of token creation. They might be just clearing the cookie at the time of logout.
Is this the right approach?
Depends. It's tradeoff between speed and security. In order to revoke the token access, there should be a server state maintaining the set of access/revoked tokens. If the application is not storing any confidential/sensitive information, its a design call for them to opt for a server state. If the site is on https and free from XSS, the only way to get the token somehow is by gaining physical access to the device. If the expiry time of access token is less than 20 min, the risk is minimal. But it mostly depends on the nature of application. For example, this is not a right approach for a banking application.
Can I raise a bug?
You should to confirm the hypothesis. There can be a possibility that they actually have an infrastructure to revoke the access tokens but its faulty as of now.


text:
Q: Python convertion of list of strings to list of tuples How to convert following list
['abc,cde,eg,ba', 'abc,cde,ba']

in to list of tuples?
[('abc','cde','eg','ba'), ('abc','cde','ba')]

What I have tried
output = []

for item in my_list:
    a = "','".join((item.split(',')))
    output.append(a)

A: In your loop, you are splitting the string (which will give you a list), but then you are joining it back with a ,, which is returning to you the same string:
 >>> 'a,b'.split(',')
 ['a', 'b']
 >>> ','.join('a,b'.split(','))
'a,b'

You can convert a list to a tuple by passing it to the the built-in tuple() method.
Combining the above with a list comprehension (which is an expression that evaluates to a list), gives you what you need:
>>> [tuple(i.split(',')) for i in ['abc,cde,eg,ba', 'abc,cde,ba']]
[('abc', 'cde', 'eg', 'ba'), ('abc', 'cde', 'ba')]

The longhand way of writing that is:
result = []
for i in ['abc,cde,eg,ba', 'abc,cde,ba']:
    result.append(tuple(i.split(',')))
print(result)

A: t=['abc,cde,eg,ba', 'abc,cde,ba']

for i in t:
    print tuple(i.split(','))

A: you can split the 2 elements. Here is my code
['abc,cde,eg,ba', 'abc,cde,ba']
a='abc,cde,eg,ba'
b='abc,cde,ba'
c=[]
c.append(tuple(a.split(',')))
c.append(tuple(b.split(',')))
print c


text:
Q: htaccess and AJAX POST values I am new to htaccess and I am having trouble with POST values through AJAX.
Everything worked before I started playing with htaccess so it is probably a simple fix.
My post values are being lost through AJAX and I think it is because I have rewritten the urls to remove the suffix (php) using htaccess. I had some trouble with POST values on the normal scripts (ie login) which was solved by adding a rewrite condition.
Please see below my code:
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]

RewriteCond %{REQUEST_METHOD} !POST
RewriteRule ^index.php / [L,R=301]

A: The problem is your R tag. This causes a redirect. Unfortunately early web browsers didn't follow the HTTP specifications and used GET to request the new URL they were given. THis has led to HTTP being changed (e.g. the 308 code introduced).
Basically, you can't reliably issue an external redirect for anything other than a GET request. Use internal redirects (re-writes) instead. i.e, leave off the R tag from the end of your first RewriteRule.


text:
Q: Flash AS3, how to index a hashmap with integer keys Here's the deal.
Right now I have a dictionary of game states
history = new Dictionary();

Each state's key being a timestamp(int)
history[100] = currentState;
history[500] = currentState;
history[699] = currentState;

My question is, how can I find the most recent game state. Let's say I want to know what the state was like at 670, I want the most recent history that's not greater than 670 (I don't want to show the future). This would be history[500].
Right now I'm looping through every key, to find the most recent one. Is there some way I can index these timestamps, so I can search faster than linear time? (I'll have a lot of keys!) Maybe I don't want a dictionary?

A: You can use a binary search (divide and conquer) approach where you save the states in a sorted array, and you recursively:

*

*divide the array into two halves

*if the array contains one item, return that item

*determine which half would contain the correct result

*go to step 1

This should find the result in logarithmic time. (Note that log2(1,000) ~ 10 and log2(10,000) ~ 13)

Here is a draft (and non tested) implementation:
class HistoryEntry
{
    public var timestamp:int;
    public var state:GameState;

    public function HistoryEntry(timestamp:int, state:GameState)
    {
        this.timestamp = timestamp;
        this.state = state;
    }
}

class History
{
    private var states:Array;

    public function History()
    {
        super();
        states = [];
    }

    public function addState(state:State):void
    {
        var timestamp:int = getTimer();
        var entry:HistoryEntry = new HistoryEntry(timestamp, state);
        states.push(entry);
    }

    public function getStateBefore(timestamp:int):State
    {
        return doGetStateBefore(timestamp, 0, states.length - 1);
    }

    // Recursive function
    private function doGetStateBefore(timestamp:int, beginIndex:int, endIndex:int):State
    {
        if (beginIndex == endIndex) {
            return states[beginIndex];
        }

        var beginEntry:HistoryEntry = states[beginIndex];
        var endEntry:HistoryEntry = states[endIndex];
        if (beginEntry.timestamp == timestamp) {
            return beginEntry.state;
        }
        if (endEntry.timestamp == timestamp) {
            return endEntry.state;
        }

        var middleIndex:int = (beginIndex + endIndex) / 2;
        var middleEntry:HistoryEntry = states[middleIndex];
        if (midleEntry.timestamp >= timestamp) {
            return doGetStateBefore(timestamp, beginIndex, middleIndex);
        } else {
            return doGetStateBefore(timestamp, middleIndex + 1, endIndex);
        }
    }
}

I introduced the class HistoryEntry so that I get typed objects from the array because using dynamic objects will have a negative impact on performance.


text:
Q: Knockout observableArray data binding not being updated I have a very simple model set up where I have a list of email addresses stored in an observableArray.   These are editable via a foreach data binding, but the binding only seems to be one way.  When I change the value in the text box, the change is not reflected in the model.  However, if I update another field outside of the array, that update is triggering foreach binding update.
I have a fiddle demonstrating this here:
http://jsfiddle.net/xeLcy/1/
And the relevant html is here

  <input type="text" data-bind="value: $rawData.address, valueUpdate: 'input'" />
  <button data-bind="click: $parent.removeAddress">Remove</button>

Where the model is
var Model = function() {
  var self = this;
  self.modelName = ko.observable("modelName");
  self.maxCount = 4;
  self.addresses = ko.observableArray();

  self.addUser = function(email) {
    self.addresses.push({address: email});
  };

  self.removeAddress = function(email) {
     self.addresses.remove(email);
  };

  self.hasEmpty = ko.computed(function() {
      var hasBlank = false;
      ko.utils.arrayForEach(self.addresses(), function(item){
         if (item.address === ""){
           hasBlank = true;
           return;
         }
      });
      return hasBlank;
  });

  self.allowAddMore = ko.computed(function() {
    return self.hasEmpty() === false && self.addresses.length <= self.maxCount;
  });

  self.addNew = function() {
    if (!self.hasEmpty()){
      self.addresses.push({address: ''});
    }
  };
};

A: Your address is not an observable. Change your addUser to :
self.addUser = function(email) {
    self.addresses.push({address: ko.observable(email)});
};

See updated fiddle: http://jsfiddle.net/nyothecat/xeLcy/2/


text:
Q: A common, ambiguous matrix operation (flanking matrices) There is a certain matrix operation that I've seen performed in several proofs/derivations, but I've never been able to find a clear rule for it. I'm not even sure how to search for it online. It looks like this:
A + BCD
= B(A + C)D
For a working example, see (eq. 1) here.
Under what conditions is this true? Do A, B, and/or D have to meet some criteria? Is there a rule for this that I've missed somewhere? It seems like there would be, given the number of times I've encountered it.


text:
Q: Couldn't find nested source for path when running inner hit query for has parent query we are migrating to elastic search 8 and when we are trying to fetch the data of parent document inner hits using has parent query .elastic search returning exception when runnning innerhits for has parent query.

https://discuss.elastic.co/t/inner-hits-in-has-parent-giving-error-couldnt-find-nested-source-for-path-currentcompany/318232

A: I had the same problem
bellow query giving me same error:, I had to pick parent document by using a field instead of _id
GET /user_data_factory/_search?from=0&size=20
{
   "query": {
        "bool": {
          "must": [
            {
              "match": {
                "relation_type": "uinsp"
              }
            },
            {
              "bool": {
                "minimum_should_match": 1,
                "should": [
                  {
                    "bool": {
                      "must": [
                        {
                          "match": {
                            "userInspirer": "63bef9f9a8c98000126589eb"
                          }
                        },
                        {
                          "bool": {
                            "minimum_should_match": 1,
                            "should": [
                               {
                                "has_parent": {
                                  "parent_type": "user",
                                  "query": {
                                    "match": {
                                      "_id": "63bd1ff29510390012760322"
                                    }
                                  },
                                   "inner_hits": {
                                    "_source": ["id"]
                                  }
                                }
                              }]

                          }
                        }
                      ]
                    }
                  }]

              }
            }
          ]
        }
      }
}

using field instead of _id
GET /user_data_factory/_search?from=0&size=20
{
   "query": {
        "bool": {
          "must": [
            {
              "match": {
                "relation_type": "uinsp"
              }
            },
            {
              "bool": {
                "minimum_should_match": 1,
                "should": [
                  {
                    "bool": {
                      "must": [
                        {
                          "match": {
                            "userInspirer": "63bef9f9a8c98000126589eb"
                          }
                        },
                        {
                          "bool": {
                            "minimum_should_match": 1,
                            "should": [
                               {
                                "has_parent": {
                                  "parent_type": "user",
                                  "query": {
                                    "match": {
                                      "id": "63bd1ff29510390012760322"
                                    }
                                  },
                                   "inner_hits": {
                                    "_source": ["id"]
                                  }
                                }
                              }]

                          }
                        }
                      ]
                    }
                  }]

              }
            }
          ]
        }
      }
}


text:
Q: Cannot resolve method 'setText(java.lang.String[])' Anyone please tell me where and how should i correct this
public class Book_Activity extends AppCompatActivity {
private TextView tvtitle,tvdescription,tvcategory;
private ImageView img;

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

    tvtitle =  findViewById(R.id.txttitle);
   TextView tvdescription = findViewById(R.id.txtdes);
    tvcategory = findViewById(R.id.txtcat);
    img = findViewById(R.id.bookthumbnail);

    // Recieve data
    Intent intent = getIntent();
    String Title = intent.getExtras().getString("Title");
    String Category = intent.getExtras().getString("Category");
    String[] Description = intent.getExtras().getStringArray("Description");
    int image = intent.getExtras().getInt("Thumbnail") ;

    // Setting values

    tvtitle.setText(Title);
    tvcategory.setText(Category);
    tvdescription.setText(Description);
    img.setImageResource(image);

A: You are passing Description as string [] tp a tvdescription text view but text view only support to string. That was an issue.
So, first you need to correct that process. For example, you need to identify which data need to show in the text view from the string array that you used.
OR,
If you want to show string array on text view you should set that string array to string. For that, you could try below solutions,
Solution 1
String[] Description = { "first", "second", "third"}
// Print as [first, second, third ]
tvdescription.setText(Arrays.toString(Description));

// Print as first, second, third
tvdescription.setText(Arrays.toString(Description).replaceAll("\\[|\\]", ""));

Solution 2
String[] Description = { "first", "second", "third"}

StringBuilder descriptionText = new StringBuilder();
for (String s: Description) {
    descriptionText.append(s);
    descriptionText.append(" ");
}

tvdescription.setText(descriptionText.toString().trim());


text:
Q: Mod rewrite into subdirectory I have been having some trouble getting the following to work:
<IfModule mod_rewrite.c>
    DirectoryIndex index.php

    Options +FollowSymLinks

    RewriteEngine On

    # If the file is not found in web

    RewriteCond  web/$1 -f [NC] #<-- This line seems to be the problem.
    RewriteRule  ^(.*)$  web/$1  [L]

    # Then rewrite it to index.php

    RewriteRule ^(.*)$ index.php [L,QSA]
</IfModule>

The idea is to check if the file exists in the web directory, and if it doesn't, route the request to index.php.
The problematic line above seems to pick up the correct URL, but it does not recognize that the file exists.
For example:
http://localhost/img.gif --> /www/web/img.gif
http://localhost/subdir/file.doc --> /www/web/subdir/file.doc
http://localhost/user/add --> /www/index.php
http://localhost/invalidurl --> /www/index.php

However, I cannot get static resources to be served correctly, they are all routed to index.php.
I also want to keep all URLs relative; so I can make this code reusable without editing it.
The following .htaccess gives an Internal Server Error, if I visit img.gif:
<IfModule mod_rewrite.c>
    DirectoryIndex index.php

    Options +FollowSymLinks

    RewriteEngine On

    # If the file is not found in web

    #RewriteCond  web/$1 -f [NC] #<-- This line seems to be the problem.
    RewriteRule  ^(.*)$  web/$1  [L]

    # Then rewrite it to index.php

    #RewriteRule ^(.*)$ index.php [L,QSA]
</IfModule>

This .htaccess redirects to http://localhost/C:/absolute/path/to/web/img.gif, when visiting img.gif:
<IfModule mod_rewrite.c>
    DirectoryIndex index.php

    Options +FollowSymLinks

    RewriteEngine On

    # If the file is not found in web

    #RewriteCond  web/$1 -f [NC] #<-- This line seems to be the problem.
    RewriteRule  ^(.*)$  web/$1  [R]

    # Then rewrite it to index.php

    #RewriteRule ^(.*)$ index.php [L,QSA]
</IfModule>

My conclusion from this would be that it's getting the path correct, but some weirdness is causing it to do something completely weird (I don't even know why it has an internal server error - Should be 404 not found).

A: Ok I got it:
When you do a rewrite, then keep in mind that the rewritten URL is called internally.
So you basically have to reprocess the .htaccess with mostly different values.
So in your example : http://localhost/img.gif is directed to http://localhost/web/img.gif and then to http://localhost/index.php by the last rule.
I would try this (replace the last rule by: )
RewriteCond %{SCRIPT_NAME} !^/web/
RewriteRule ^(.*)$ index.php [L]

(NB: [QSA] is not needed since you don't touch the query string, so it is passed as is.)
Edit : What about
# If the file is not found in web
RewriteCond  web/$1 !-f [NC]
# And we don't ask for /web/something at the beginning (Avoid infinite loops since you'll try to call web/image.gif and we don't want to test /web/web/image.gif and fail to index.php
RewriteCond %{SCRIPT_NAME} !^/web/
#Rewrite it to index.php
RewriteRule  ^(.*)$  index.php  [R,L]

# If the file is found in web
RewriteCond  web/$1 -f [NC]
# And we don't ask for /web/something at the beginning (Avoid infinite loops since you'll try to call web/image.gif and we don't want to test /web/web/image.gif and fail to index.php
RewriteCond %{SCRIPT_NAME} !^/web/
#Then point to web/image.gif
RewriteRule ^(.*)$ web/$1 [L]


text:
Q: What will be the area which is bounded by $x=0,y=\pi/4$ and $y=\arctan (x)$? What will be the area which is bounded by $x=0,y=\pi/4$ and $y=\arctan (x)$? I know that I have to compute $$\int_{0}^{\infty} \arctan x\ dx$$ but how does it go in this case?

A: The integral in the question diverges. Notice how the integrand approaches $\pi/2$ and $x \to \infty$. However from the comments I'm guessing you mean,
$$\int_0^1 \arctan x \mathrm dx$$
(as $\tan \pi/4= 1$) From here you can use integration by parts. Remember,
$$\frac{\mathrm d(\arctan x)}{\mathrm dx} = \frac 1 {1+x^2}$$
So, with $\mathrm du=1$, $v = \arctan x$ $\implies$ $u=x$, $\mathrm dv = 1/(1+x^2)$,
$$\int_0^1 \arctan x \mathrm dx = [x\arctan x]_0^1 - \int_0^1 \frac x {1+x^2} \mathrm dx$$
I'm assuming you can take it from here.

A: The area of the figure you have described is:
$$
\int_0^{\pi/4}\tan y\, dy=\left[-\log|\cos y|\right]_0^{\pi/4}={\small\frac{1}{2}}\log2.
$$

A: Your essentially trying to find the area of the first picture with the arctan(x) graph, which is the same as the area of the second picture with the tan(x) graph, soon enough both are just themselves reflected across y=x.
The area of the second graph is
$\int_0^\frac{π}{4} tan(x) dx $
$\int tan(x) dx = ln(sec(x))+C$
$[ln(sec(x))]_0^\frac{π}{4}$
$ln(sec(\frac{π}4))-ln(sec(0))$
$ln(\sqrt{2})-ln(1)$
$\frac{ln(2)}2$
I know this is easy and has already received enough answers, but I just couldn't resist.


text:
Q: How do I configure my graphics drivers? I'm running Linux Mint 9 gnome on a Toshiba Satellite A105-S4211
With this,
inxi -G Graphics: Card Intel Mobile 945GM/GMS 943/940GML Express Integrated Graphics Controller X.Org 1.7.6 Res: 1280x800@60.0hz GLX Renderer Mesa DRI Intel 945GM GEM 20091221 2009Q4 x86/MMX/SSE2 GLX Version 1.4 Mesa 7.7.
And I want to know how to configure the monitor/graphic/video/driver/gamma settings.
What I really want to do is change the gamma settings on my computer. I was told that I can do this using the video card driver.
I want to know how to do that.

A: You should be able to adjust the gamma using the xgamma command.

A: I think the program you are looking for is xvidtune.


text:
Q: How to change the background series colour of Highcharts Radar chart I'm trying to change the background colour of my Highchart radar chart.

As you can see there's just the border lines for the area. I want that area filled with the same colour as the border. I thought to add backgroundColor: 'Red' to the series I.E.
series: [{
        name: 'Similar',
        data: [100, 100, 100, 100, 100, 100],
        pointPlacement: 'on',
        backgroundColor: 'Red'
    }, { ... }

Instead this has no effect and the chart looks the exact same as above. How can I fill this area with a colour, what am I missing?

A: The "radar chart" (aka "spiderweb") in Highcharts is just a regular chart with polar: true.
This means that the series themselves are of the regular types like "line", "area", etc. In your case you seem to be using "line". Instead switch to using type: 'area' which will then fill the area below the line. Optionally supply a fillOpacity if you want the background to be solid.
As an example (JSFiddle):
Highcharts.chart('container', {
    chart: {
        polar: true
    }
    series: [{
        type: 'area',
        fillOpacity: 1.0,
        data: [43000, 19000, 60000, 35000, 17000, 10000]
    }
});

The series type can be set either for each individual series or globally in chart.


text:
Q: Multiply column values by itself using awk I would like to multiply column values by itself using awk. How can I do that?
example
1  5 1
2  6 0
3  7 3
4  8 5

output
1X5X1 =5                  1  5 1 5
X X X
2X6X0 =0      ===>        2  6 0 0
X X X
3X7X3 =63                 3  7 3 63
X X X
4X8X5 =160                4  8 5 160
| | |                     | | |
V V V                     V V V
24 1680 0                 24 1680 0

I know how to sum the values using awk but how I can multiply it?
awk '{sum2+=$2;  ... etc} END {print sum2,... etc}'

A: If you know the number of columns in advance:
BEGIN { p1 = p2 = p3 = 1 }
{ p1 *= $1; p2 *= $2; p3 *= $3; print $0, $1 * $2 * $3 }
END { print p1, p2, p3 }

This should handle files where any row can have any number of columns:
{
        for(i = p = 1; i <= NF; i++){
                s[i] = s[i] == "" ? $i : s[i] * $i; p *= $i
        }
        print $0, ":", p
        if(NF > mf) mf = NF
}
END {
        ORS="";
        for(i = 1; i < mf; i++) print s[i] FS;
        print s[i] RS
}

In this case, the product of fields from a line is appended to the line following a ":", in order to distinguish it from a normal field.


text:
Q: He was born into a once-proud family. (What's the meaning?)
He was born into a once-proud family.

What's the meaning of, especially, "a once-proud family."?

A: 'Once', can mean 'at some time in the past', either on one occasion, or for a continuous period.
'Proud' in this sense, could mean 'standing out', as in the case of a family of great wealth, fame, or power, or equally, that the family had great pride in their position.
So, 'once-proud' means a family who at one time stood out for some reason, but no longer does.


text:
Q: Error: "Dimension too large..." when plotting exponentials with TikZ Despite having read answers to 4-5 relate questions, I still can't get why my code does not compile. Here it is:
\documentclass[11pt,twoside]{book}
\usepackage[paperheight=24cm, paperwidth=35cm, margin=0pt, %
voffset=-50cm, hoffset=-1.4cm]{geometry}
\usepackage{tikz}

\usetikzlibrary{calc}

\begin{document}

\pagestyle{empty}

\begin{figure}[!h]
\centering\begin{tikzpicture}[xscale=1,yscale=1]
\draw[very thick,yellow,samples=500,domain=-6*pi:6*pi]
plot (\x, {cos((3*\x r)+pi/2)+\x*sin(3*\x r)});
\draw[very thick,orange,samples=500,domain=-6*pi:6*pi]
plot (\x, {-0.25*(pow(\x,2)*cos(\x r)-\x*sin(\x r))});
\draw[very thick,green,samples=500,domain=-6*pi:6*pi]
plot (\x, {cos(\x r)+\x});
\draw[very thick,magenta,samples=500,domain=-6*pi:6*pi]%%          error!
plot (\x, {0.5*(pow(10,-11)*exp(-3*\x)-cos(\x r)+3*sin(\x r))});%% error!
\draw[very thick,blue,samples=500,domain=-6*pi:6*pi]%%             error!
plot (\x, {pow(10,-15)*exp(3*\x)});%%                              error!
\end{tikzpicture}
\end{figure}

\end{document}

The latest two of five plots - as I showed in comments - are driving me mad.
Please notice the massive voffset too. Is it related?
Obviously I tried several local modifications (e.g. radiants, etc.).
This was just a test but now I'm seriously curious.

A: Percusse has answered accordingly to the question. (I think his answer should be marked as "accepted", by the way). I took the liberty to propose a MetaPost solution, however.
Until quite recently, this kind of function drawing would have been impossible to do with MetaPost, since it was based only on quite limited fixed-point numerics. But since its version 1.8 the user can switch to floating-point numerics at will, by setting the internal variable numbersystem to double. It's still a bit rough around the edges (the default units has not yet been adapted, for example) but it's quite functional, and I couldn't resist to use it for this problem. The following program makes use of LuaLaTeX and its luamplib package as a very convenient interface to MetaPost. It calls the Metafun format of MetaPost, which defines the necessary auxiliary functions (cos, sin, exp…)
\documentclass[11pt]{standalone}
\usepackage{unicode-math}
\usepackage{luamplib}
  \mplibsetformat{metafun}
  \mplibtextextlabel{enable}
  \mplibnumbersystem{double}
\begin{document}
\begin{mplibcode}
  input mpcolornames;
  % pi, cm (and mm) as accurate as possible
  %(defaults settings are too inaccurate: pi = 3.14159265, cm = 28.34645)
  pi:= 3.141592653589793;
  cm := 3600/127; mm := 360/127;
  % Unit lengths
  u = .5cm; v = mm;
  % Graphs boundaries
  xmin = -6pi; xmax = -xmin; xsep = (xmax - xmin)/1000; ymin = -80; ymax = 100;
  % Axes settings
  Xmin = -20; Xmax = -Xmin; Ymin = -85; Ymax = 110;
  % Macro building the graph of a given function f
  vardef graph_of_function (suffix f) (expr xmin, xmax, xsep) =
    for x = xmin step xsep until xmax: (x, f(x)) .. endfor (xmax, f(xmax))
  enddef ;
  % Functions to be graphed
  vardef e(expr x) = cos(pi/2 + 3x) + x*sin 3x enddef;
  vardef f(expr x) = -.25(x**2)*cos x - x*sin x enddef;
  vardef g(expr x) = x + cos x enddef;
  vardef h(expr x) = .5(-cos x + 3sin x + 1e-11exp -3x) enddef;
  vardef i(expr x) = 1e-15exp 3x enddef;
  %
  beginfig(0);
    % Drawing of the given functions
    pickup pencircle scaled 1.25bp;
    draw (graph_of_function(e)(xmin, xmax, xsep)) xyscaled (u, v) withcolor yellow;
    draw (graph_of_function(f)(xmin, xmax, xsep)) xyscaled (u, v) withcolor Orange;
    draw (graph_of_function(g)(xmin, xmax, xsep)) xyscaled (u, v) withcolor green;
    draw (graph_of_function(h)(xmin, xmax, xsep)) xyscaled (u, v) withcolor magenta;
    draw (graph_of_function(i)(xmin, xmax, xsep)) xyscaled (u, v) withcolor blue;
    % Clipping
    clip currentpicture to
      ((xmin, ymin) -- (xmax, ymin) -- (xmax, ymax) -- (xmin, ymax) -- cycle)
        xyscaled (u, v);
    % Axes and labels
    pickup pencircle scaled .5bp;
    drawarrow (Xmin*u, 0) -- (Xmax*u, 0); drawarrow (0, Ymin*v) -- (0, Ymax*v);
    label.llft("$O$", origin);
    label.lft("$y$", (0, Ymax*v)); label.bot("$x$", (Xmax*u, 0));
    % Marking…
    labeloffset := 6bp;
    % … on the horizontal axis
    draw (u*pi, -3bp) -- (u*pi, 3bp); draw (-u*pi, -3bp) -- (-u*pi, 3bp);
    label.bot("$\pi$", (pi*u, 0)); label.bot("$-\pi$", (-pi*u, 0));
    for i = 2 upto 6:
      draw (i*pi*u, -3bp)-- (i*pi*u, 3bp);
      label.bot("$" & decimal i & "\pi$", (i*pi*u, 0));
      draw (-i*pi*u, -3bp)-- (-i*pi*u, 3bp);
      label.bot("$" & decimal -i & "\pi$", (-i*pi*u, 0));
    endfor;
    % … on the vertical axis
    for i = 20 step 20 until 80:
      label.lft("$" & decimal i & "$", (0, i*v));
      label.lft("$" & decimal -i & "$", (0, -i*v));
      draw (-3bp, i*v) -- (3bp, i*v);
      draw (-3bp, -i*v) -- (3bp, -i*v);
    endfor;
    label.lft("$100$", (0, 100v)); draw (-3bp, 100v) -- (3bp, 100v);
    % Preventing possible cropping of labels at the figure boundaries
    setbounds currentpicture to boundingbox currentpicture enlarged .5cm;
  endfig;
\end{mplibcode}
\end{document}

A: Just simply use pgfplots. TikZ in this case is hopeless to deal with such precision. In fact, I just copy pasted and replaced commands. Also adjusted the y domain to make the plots seen.
\documentclass[11pt,twoside]{book}
\usepackage{pgfplots}

\begin{document}

\begin{figure}
\centering
\begin{tikzpicture}
\begin{axis}[samples=500,domain=-6*pi:6*pi,restrict y to domain =-20:100]
\addplot[very thick,yellow ]plot (\x, {cos((3*\x r)+pi/2)+\x*sin(3*\x r)});
\addplot[very thick,orange ]plot (\x, {-0.25*(pow(\x,2)*cos(\x r)-\x*sin(\x r))});
\addplot[very thick,green  ]plot (\x, {cos(\x r)+\x});
\addplot[very thick,magenta] plot (\x, {0.5*(pow(10,-11)*exp(-3*\x)-cos(\x r)+3*sin(\x r))});
\addplot[very thick,blue   ] plot (\x, {pow(10,-15)*exp(3*\x)});
\end{axis}
\end{tikzpicture}
\end{figure}

\end{document}

A: I was really forgetting to post how I finally handled it: functions domains modified where necessary (see %% error! in the question code).
\documentclass[11pt,twoside]{book}
\usepackage[paperheight=24cm, paperwidth=35cm, margin=0pt, %
    voffset=-140cm, hoffset=-1.4cm]{geometry}
\usepackage{tikz}

\usetikzlibrary{calc}

\begin{document}

\pagestyle{empty}

\begin{figure}[!h]
\centering\begin{tikzpicture}%[xscale=1,yscale=1]
\draw[very thick,yellow,samples=500,domain=-6*pi:6*pi]
plot (\x, {cos((3*\x r)+pi/2)+\x*sin(3*\x r)});

\draw[very thick,orange,samples=500,domain=-6*pi:6*pi]
plot (\x, {-0.25*(pow(\x,2)*cos(\x r)-\x*sin(\x r))});

\draw[very thick,green,samples=500,domain=-6*pi:6*pi]
plot (\x, {cos(\x r)+\x});

\draw[very thick,magenta,samples=500,domain=-pi:6*pi]
plot (\x, {0.5*(pow(10,-2)*exp(-3*\x)-cos(\x r)+3*sin(\x r))});%

\draw[very thick,blue,samples=500,domain=-6*pi:.8*pi]
plot (\x+1, {exp(2*\x)});%
\end{tikzpicture}
\end{figure}

\end{document}

By the way I think this could be made even better by using standalone documentclass and TikZ command clip. I'll post an update next time I must make a plot picture for a full book sleeve!


text:
Q: can't use SIFT on a numpy array image I open a Brain MRI scan:
path = os.path.join(r"C:\temp\generated_noisy\patients",
lst_of_filenames[index_of_filename])
scan = nib.load(path)
data = scan.get_data()
data = data[14:168,18:205,98]

so now "data" is a numpy array (the elemnts in it are "numpy.float64"):
print(pic.shape)
print(type(pic))
print(type(pic[50,50]))

(154, 187)
<class 'numpy.ndarray'>
<class 'numpy.float64'>

Allright, now I try to use SIFT:
    kp,des = sift.detectAndCompute(pic,None)
and I get this error:
OpenCV(3.4.2) C:\projects\opencv-
python\opencv_contrib\modules\xfeatures2d\src\sift.cpp:1121: error: (-5:Bad
argument) image is empty or has incorrect depth (!=CV_8U) in function
'cv::xfeatures2d::SIFT_Impl::detectAndCompute'

Anyone know how to solve this? I can't seem to find any help online...

A: SIFT expects the data type to be uint8.  However, you won't be able to just convert the array to uint8 if the values are not in the correct range, such as being greater than 255 or in the range 0-1.  Before converting, you could scale the values so the values are in the range 0-255.  For example, the following will subtract the minimum value so the minimum is zero, then scale so the max is 255.  Then you can convert to type uint8 without corrupting the image.
data = (data - np.min(data)) * 255 / np.max(data)
data = data.astype(np.uint8)


text:
Q: Type 'Any?' has no subscript members I am trying to retrieve email id after fb login in my app. However I am getting an error when i try to get the value from result.
The error is:Type 'Any?' has no subscript members.
func fetchProfile()
{
    print("Fetch Profile")
    let parameters = ["fields": "email, first_name, last_name,  picture.type(large)"]
    FBSDKGraphRequest(graphPath: "me", parameters: parameters).start { (connection, result, error) in

        let email = result["email"] as? String  //Type 'Any?' has no subscript members error occurs here.
    }
}

A: For Swift 3.
change this-->
let email = result["email"] as? String

Into -->
if let fbemail = (result as AnyObject)["email"]! as? String
{
   print(fbemail)
}

A: change this
 let email = result["email"] as? String

into
  guard let resultNew = result as? [String:Any]

 let email = resultNew["email"]  as! String

full answer
let parameters = ["fields": "email, first_name, last_name,  picture.type(large)"]
    FBSDKGraphRequest(graphPath: "me", parameters: parameters).start { (connection, result, error) in

        guard let resultNew = result as? [String:Any]

       let email = resultNew["email"]  as! String
    }


text:
Q: How to save 2 strings on an android app? I'm a relatively new programmer, and I haven't really worked with xml before other than writing layouts for android applications.
I want to be able to have a user save an int value (figured it'd be easier to save the int as a string, however), so that way it is usable whenever they use my app.  (For example, I have a start time and end time I want them to be able to save instead of inserting everytime they open the app).
I was thinking the easiest way to go about this would be to save the file to an xml file, but after looking at android tutorials, the only coding I could understand about xml files was how to load the resource files from the files, but nothing on how to save (or edit) these strings.
I don't have access to a database for this project, so it needs to be able to be saved directly on the phone.
What's the easiest way to save 2 strings for an android app?

A: Look at SharedPreferences. You ask for a shared preferences by name, which creates it if it doesn't exist, you then get an editor to it, then add some named values to it.
At some other point you get the shared preferences and pull your values out by name, you can also add a listener to it so that you are notified of changes to your shared preferences object.
Getting your shared prefs:
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);

Saving a value:
SharedPreferences.Editor e = myPrefs.edit();
e.putInt("someValue", 50); // add or overwrite someValue
e.commit(); // this saves to disk and notifies observers

Retrieving a value:
int i = myPrefs.getInt("someValue", 0); // return 0 if someValue doesn't exist

A: You should use SharedPreferences to achieve that, in something like this:
public class Calc extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle state){
       super.onCreate(state);
       . . .

       // Restore preferences
       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       boolean silent = settings.getBoolean("silentMode", false);
       setSilent(silent);
    }

    @Override
    protected void onStop(){
       super.onStop();

      // We need an Editor object to make preference changes.
      // All objects are from android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", mSilentMode);

      // Commit the edits!
      editor.commit();
    }
}

Just in your situation you should use the get and put methods for String and for Integer
This example and more information can be found at Android Developer website here.


text:
Q: ASP.NET MVC multi-site SSO using OpenID I am putting a plan together for a series of sites that will share user account information among them. The idea is that once a user logs in using their OpenID, they can access any of the sites and it will know who they are.
What are the common patterns/best practices that i could employ to achieve this?

A: If all the sites share a common hostname in their URL then you can set an auth cookie (FormsAuthentication.SetAuthCookie) specifying the path of the cookie to be "/" so that all sites can see the user is logged in.
If the sites are not sharing a common host name, I think the only way to get a truly "once signed in, signed in everywhere [within your ring of web sites]" would be for all authentication to happen at just one site (perhaps one dedicated to authenticating the user) and for the other sites to redirect the user to that site for authentication and then that site would redirect back.  In essence, that auth site becomes an identity provider, and almost exactly fills the role of an OpenID Provider (in fact DotNetOpenAuth could be used here for this exact purpose).  Since it sounds like your goal is to let the user log in with their OpenID, your OpenID Provider on that one auth site could itself use OpenID to authenticate the user.  Your own pure-delegation OpenID Provider could be written such that it always responds immediately to checkid_immediate requests as long as the Realm in the auth request is one of your trusted ring of sites.  Thus you could effect single-sign-on across all your sites.

A: Please consider the following Patterns & Practices on Web Service Security from Microsoft:
Brokered Authentication - http://msdn.microsoft.com/en-us/library/aa480560.aspx
The main topic is - Web Service Security
Scenarios, Patterns, and Implementation Guidance for Web Services Enhancements (WSE) 3.0
http://msdn.microsoft.com/en-us/library/aa480545.aspx
Ultimately theres lots of ways you could do it. I achieved a simple single sign on by building a url with a token from one website pointing to another domain. The encoded & encrypted token contained details to submit back to the previous domain. Upon receiving an incoming request on the second domain, an underlying web service checks that the incoming request's token is valid with the previous domain using a shared private secret, known to both domains.