text:
Q: unable to read the package and display the dataset within the package when i select the dataset from the selectinput I am unable to read the dataset of a package and display the content of it, i am trying to display the dataset content from 'dataset2' output.
I am using the libraries as mentioned in the code. I am able to see the content of the 'dataset1', only issue is with contents of 'dataset2'. Could you please help me how to resolve it
UI Part

library(shiny)
library(magrittr)
library(tidyverse)
library(DT)

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Package with datasets and functions"),

    # Sidebar with a slider input for number of bins
    sidebarLayout(
        sidebarPanel(
            textInput('pkg','Package Name', value = NULL),
            actionButton("update", "Update View"),
            helpText('Please enter the package name for which you want to see the list of datasets and functions (with parameters)'),
            br(),
            # br(),
            selectInput('dat','Datasets', choices = NULL, selected = NULL)
        ),

        # Show a plot of the generated distribution
        mainPanel(
            DTOutput("dataset1"),
            DTOutput("dataset2")
        )
    )
)

server part

# Define server logic required to draw a histogram
server <- function(input, output, session) {

  pkgs <- reactive({input$pkg})
  #
  # if (!is.null(pkgs())){
  df <- reactive({
  data_name1 <- data(package=input$pkg)
  data_name2 <- as_tibble(data_name1$results) %>% rename(name=Item, label=Title) %>% select(-LibPath)
  data_name2
    })
  # }

  obse <- eventReactive(input$update, { df() })

# if (!is.null(pkg1())){
  observe({
    req(obse())
    updateSelectInput(session, inputId = "dat", label = "Datasets", choices = c(df()$name), selected = df()$name[1])

  })
# }

  df2 <- reactive({
    req(obse())
    data(package = input$pkg)
    library(package = input$pkg)
    input$dat
    # new <- input$dat
    # data(new, package = input$pkg)
    # cat(new)
  })

    output$dataset1 <- renderDataTable({
      DT::datatable(obse())
    })

    output$dataset2 <- renderDataTable({
      df2()
    })
}

# Run the application
# undebug(shinyApp)
shinyApp(ui = ui, server = server)

A: In the data, we may need list and in library we can specify character.only = TRUE
ui <- fluidPage(

  # Application title
  titlePanel("Package with datasets and functions"),

  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
      textInput('pkg','Package Name', value = NULL),
      actionButton("update", "Update View"),
      helpText('Please enter the package name for which you want to see the list of datasets and functions (with parameters)'),
      br(),
      # br(),
      selectInput('dat','Datasets', choices = NULL, selected = NULL)
    ),

    # Show a plot of the generated distribution
    mainPanel(
      DTOutput("dataset1"),
      DTOutput("dataset2")
    )
  )
)

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

  pkgs <- reactive({input$pkg})
  #
  # if (!is.null(pkgs())){
  df <- reactive({
    data_name1 <- data(package=input$pkg)
    data_name2 <- as_tibble(data_name1$results) %>% rename(name=Item, label=Title) %>% select(-LibPath)
    data_name2
  })
  # }

  obse <- eventReactive(input$update, { df() })

  # if (!is.null(pkg1())){
  observe({
    req(obse())
    updateSelectInput(session, inputId = "dat", label = "Datasets", choices = c(df()$name), selected = df()$name[1])

  })

  df2 <- reactive({
    req(obse())
    e <- new.env()
    library(package = input$pkg, character.only = TRUE)
    out <- data(list = input$dat, package = input$pkg, envir = e)
    e[[out]]

  })

  output$dataset1 <- renderDataTable({
    DT::datatable(obse())
  })

  output$dataset2 <- renderDataTable({
    df2()
  })
}
}

# Run the application
# undebug(shinyApp)
shinyApp(ui = ui, server = server)

-output


text:
Q: Why is removing the 1st entry from a ConcurrentHashMap not immediately reflected in the iterator, but removing the 2nd or subsequent entries is? I created an iterator() and then removed the 1st entry from the map before iterating it. I always get the 1st item returned from the iterator. But when I remove the 2nd or subsequent entries, the current iterator does not return that entry.
Example of removing 1st entry from map:
    Map<Integer,Integer> m1 = new ConcurrentHashMap<>();
    m1.put(4, 1);
    m1.put(5, 2);
    m1.put(6, 3);
    Iterator i1 = m1.entrySet().iterator();
    m1.remove(4);        // remove entry from map
    while (i1.hasNext())
        System.out.println("value :: "+i1.next()); //still shows entry 4=1

and the output is:
value :: 4=1
value :: 5=2
value :: 6=3

Example of removing 3rd entry from map:
    Map<Integer,Integer> m1 = new ConcurrentHashMap<>();
    m1.put(4, 1);
    m1.put(5, 2);
    m1.put(6, 3);
    Iterator i1 = m1.entrySet().iterator();
    m1.remove(6);        // remove entry from map
    while (i1.hasNext())
        System.out.println("value :: "+i1.next()); //does not show entry 6=3

and the output is:
value :: 4=1
value :: 5=2

Why is removing the 1st entry from the map not reflected in the iterator, but removing the 2nd or subsequent entry is?
The Java documentation says:

Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException.

That means, its iterators reflect the state of the hash table at the point of creation of the iterator.
And when we add or remove an entry to or from the Map, the Iterator will show the original entries?

A: According to this iterators and spliterators are weakly consistent. The definition of "weakly consistent" can be found here:

Most concurrent Collection implementations (including most Queues)
  also differ from the usual java.util conventions in that their
  Iterators and Spliterators provide weakly consistent rather than
  fast-fail traversal:

*

*they may proceed concurrently with other operations

*they will never throw ConcurrentModificationException

*they are guaranteed to traverse
  elements as they existed upon construction exactly once, and may (but
  are not guaranteed to) reflect any modifications subsequent to
  construction.

Which means that any modifications made after an iterator has been created may be reflected, but it's not guaranteed. That's just a normal behaviour of a concurrent iterator\spliterator.

A: To achieve exactly once iteration behavior, when you remove an element via the Iterator object, the iterator data structure would need to be updated to keep it in step with what has happened to the collection. This is not possible in the current implementations because they don't keep links to the outstanding iterators. And if they did, they would need to use Reference objects or risk memory leaks.
The iterator is guaranteed to reflect the state of the map at the time of it's creation. Further changes may be reflected in the iterator, but they do not have to be.
Think Iterator as a LinkedList and you have head reference with you. If you happen to remove the head from linked list and does not reset the head.next value and start iterating from head you still be traversing the from the same head because you are using an outdated head reference. But when you remove non-head elements the prior element.next is updated.

A: The answer is in the documentation you quoted:

Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration.

At OR since. The iterator might or might not show changes to the map since the iterator's creation.
It is not practical for the designers to enforce more precise behavior during concurrent modification and iteration, but it is not broken.

A: Actual value check is done in next(),
public final Map.Entry<K,V> next() {
    Node<K,V> p;
    if ((p = next) == null)
        throw new NoSuchElementException();
    K k = p.key;
    V v = p.val;
    lastReturned = p;
    advance();
    return new MapEntry<K,V>(k, v, map);
}

advance method advances if possible, returning next valid node, or null if none.
So for first entry K k = 4; V v = 1; even if it is removed. But for subsequent k,v would decided with update fromadvance()
So if you call next() after remove, it won't be there(which is obvious),
Map<Integer,Integer> m1 = new ConcurrentHashMap<>();
m1.put(4, 1);
m1.put(5, 2);
m1.put(6, 3);
Iterator<Map.Entry<Integer, Integer>> i1 = m1.entrySet().iterator();
m1.remove(4);        // remove entry from map
i1.next();

while (i1.hasNext())
    System.out.println("value :: "+i1.next());

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamic ploting in R shiny I have table with n columns (all the columns are categorical variables). I want to plot pie charts for each column using plotly and R-shiny.
The code is as follows:
Server.R
df_data<-read.csv("file.csv")

df_data_num <- df_data[,sapply(df_data,is.numeric)]

var_list <- data.frame(colnames(df_data_num))

shinyServer(function(input, output) {

output$plots <- renderUI({
plot_output_list <- lapply(1:nrow(var_list), function(i) {
  plotname <- paste("plot", i, sep="")
  plotOutput(plotname, height = 280, width = 250)
})

do.call(tagList, plot_output_list)
})

for (i in var_list) {
  local({
  w = table(df_data_num$i ,exclude = NULL)
  sort(w)
  t= as.data.frame(w)
  plotname <- paste("plot", i, sep="")

  output[[plotname]] <- renderPlot({
    plot_ly(t, labels = "var1", values = "Freq", type = "pie") %>%
    layout(title = paste("Plot for",my_i))

    })
  })
}
})

Ui.R
shinyUI(pageWithSidebar(

     headerPanel("Dynamic number of plots"),

     sidebarPanel(),
     mainPanel(
    # This is the dynamic UI for the plots
      uiOutput("plots")
    )
   ))

Error
Warning: Error in [[: no such index at level 1

Stack trace (innermost first):
    51: .subset2(x, "impl")$defineOutput

    50: [[<-.shinyoutput

    49: [[<- [C:\Users\Desktop/server.R#73]

    48: eval [C:\Users\Desktop/server.R#73]

    47: eval

    46: eval

    45: eval

    44: eval.parent

    43: local

    42: server [C:\Users\Desktop/server.R#64]

     1: runApp

     Error in private$.outputs[[name]] : no such index at level 1

Please help.

A: Try code like this !
library(plotly)

# You have to import data in environment
df_data<-read.csv("file.csv")
df_data_num <- df_data[,sapply(df_data,is.numeric)]
df_data_num <- data.frame(df_data_num)

shinyUI(pageWithSidebar(
  headerPanel("Dynamic number of plots"), # Application title
  sidebarPanel(
     sliderInput(inputId = "colname",
                 label = "Choose a column",
                 min = 1,
                 max = n, # Choose the good number of column !
                 value = 1)
   ),
     mainPanel(
         plotlyOutput("plots") #If you want to use plotly, you need this.
   )
 )
)

shinyServer(function(input, output) {
   output$plots <- renderPlotly({  # Same thing
   p <- plot_ly(df_data_num, labels = ~input$colname, type = 'pie') %>%
     layout(title = 'Pie Chart')
   })
})


text:
Q: Negating a custom RSpec matcher that contains expectations I have a custom RSpec matcher that checks that a job is scheduled. It's used like so:
expect { subject }.to schedule_job(TestJob)
schedule_job.rb:
class ScheduleJob
  include RSpec::Mocks::ExampleMethods

  def initialize(job_class)
     @job_class = job_class
  end

  ...

 def matches?(proc)
   job = double
   expect(job_class).to receive(:new).and_return job
   expect(Delayed::Job).to receive(:enqueue).with(job)
   proc.call
   true
 end

This works fine for positive matching. But it does not work for negative matching. e.g:
expect { subject }.not_to schedule_job(TestJob) #does not work
For the above to work, the matches? method needs to return false when the expectations are not met. The problem is that even if it returns false, the expectations have been created regardless and so the test fails incorrectly.
Any ideas on how to make something like this work?

A: I had to look for it, but I think it's nicely described here in the rspec documentation
Format (from the docs) for separate logic when using expect.not_to:
RSpec::Matchers.define :contain do |*expected|
  match do |actual|
    expected.all? { |e| actual.include?(e) }
  end

  match_when_negated do |actual|
    expected.none? { |e| actual.include?(e) }
  end
end

RSpec.describe [1, 2, 3] do
  it { is_expected.to contain(1, 2) }
  it { is_expected.not_to contain(4, 5, 6) }

  # deliberate failures
  it { is_expected.to contain(1, 4) }
  it { is_expected.not_to contain(1, 4) }
end


text:
Q: Error in reading result of Celery Task using SQLAlchemy I have a Flask app and I'm using Celery(v5.1.2) with SQLAlchemy to run background tasks with my worker.
This is how I am creating my Celery worker...
backend_url = 'mysql://{}:{}@{}/{}'.format(username, password, hostname, db_name)
broker_url = 'sqla+' + backend_url
db_backend_url = 'db+' + backend_url

celery = Celery(
    app.import_name,
    backend=backend_url,
    broker_url=broker_url,
    result_backend=db_backend_url,
    cache_backend=db_backend_url,
    task_serializer='json',
    result_serializer='json',
    include=['my_blueprints.profile'])

It works fine to initialise and run my tasks. The problem happens when I try to read the state of my result using:
bg_task = current_app.celery.AsyncResult(MY_TASK_ID)
bg_task_state = bg_task.state

I get the ERROR: _pickle.UnpicklingError: pickle data was truncated when trying to run bg_task.state
I assume this has something to do with the fact that the task returns a large file of 1MB. While the task is running a can successfully read the task state using the two-line above, but that fails when the task is completed.
task_serializer and result_serializer are both set to 'json' so I cannot understand why this is happening.

A: In its default backend, celery uses a BLOB column to store its result in the celery_taskmeta table which is limited to 64K in mysql. Somewhere in your celery logs you're probably also seeing a truncation warning from mysql when the result is being written to that table.
The celery result isn't really intended for passing around large files, but more just to hold some minimal details about the result of your task.
You don't give many details about your use case, but generally writing such a large binary blob to your database is a smell, or at least a headache waiting to happen some day.
A decent workaround would be to write the file to the file system or upload it to your favorite elastic storage area then return the file name in the task's result.  The concern there would be to make sure your worker node has access to the same file system as the node that needs the result.
You might also be able to get away with altering the celery_taskmeta table to allow a MEDIUMBLOB or LONGBLOB to be stored in the table, but my instincts are that you'll eventually wish you weren't storing the files in the RDBMS anyway. You'll have to make sure that alteration is made every time you deploy your application from scratch.


text:
Q: TypeError: Cannot read property 'openModalDialog' of undefined this is my .ts file, when ever if condition fails and comes to else  i want to display the request modal box so there is a function openModalDialog() , but it is showing undefined.
please help me thanks in advance
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { RequestModalComponent } from '../../request-modal/request-modal.component';
import axios from 'axios';

@Component({
 selector: 'app-shared-scheduled',
 templateUrl: './shared-scheduled.component.html',
 styleUrls: ['./shared-scheduled.component.css'],
})

  export class SharedOndatetimeScheduledComponent implements OnInit {
    bsModalRef: BsModalRef;
    constructor( private modalService: BsModalService ) { }

    ngOnInit(): void {
    }

   openModalDialog() {
    console.log("callling this method.......")
     this.bsModalRef = this.modalService.show(RequestModalComponent);
   }

 navigateToTeleApp = () => {
   axios.get("*******").then(function (res) {
  console.log("response ...", res)
  if (res.data.message == "Not Found"){
    console.log("this condition....")
  }
  else {
    console.log("this condition....222");
    this.openModalDialog();
  }
  });
 }

A: i think its because get method from axis where you using function keyword to handle a callback and its not bnded so this getting undefined try to use lamda function over there.
    navigateToTeleApp = () => {
// below line changed from function to lamda function
       axios.get("*******").then((res) => {
      console.log("response ...", res)
      if (res.data.message == "Not Found"){
        console.log("this condition....")
      }
      else {
        console.log("this condition....222");
        this.openModalDialog();
      }
      });
     }


text:
Q: docker is not in the `container ls` or `ps` after docker run I am running a docker container for a react application.
frontend.Dockerfile
FROM node:14 as builder

RUN mkdir -p /client

WORKDIR /client

COPY package.json /client

RUN npm install

COPY . /client

# copying the crt, key files for https
# COPY ../secret/website_com_au.key ../secret/website_com_au_chain.crt /client

RUN npm run build

FROM nginx

RUN rm /etc/nginx/conf.d/default.conf

COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=builder /client/build /usr/share/nginx/html

EXPOSE 80

RUN chown nginx.nginx /usr/share/nginx/html/ -R

I am building the dockerfile without any error.
sudo docker build -t nabil/website:webclient . -f frontend.Dockerfile
There is also no error after docker run,
sudo docker run -d --net=host nabil/website:webclient
But when I run docker ps or docker container ls, I don't see the docker container there.

A: docker ps -a to see all containers even container was dead.
Check docker logs container_id to see the reason why container was dead.

A: Check the status of container created:
docker ps -a (OR)
docker container ls -a
Check container logs for failing:
docker logs <container id/container name> (OR)
docker container logs <container id/container name>


text: Q: How can I scale a ui web view differently on iPad than iPhone in Xcode The UIWebview takes up the entire screen on iPhone. I'd like the UIWebview to retain the same height to width dimensions on the iPad...but Xcode makes the webview adjust to the entire screen of the iPad. If I change the dimensions on the iPad storyboard, the webview no longer fits within the bounds of the different iPhone screens.


text:
Q: Reading csv with Python breaks on square bracket I have a csv that I'm trying to read with Python, which has lines that look like the following:
10x org il,"["Modiin, Israel"]","["no current price posted"]","["Modiin: no current size posted"]","{ "Python Bootcamp": {"Price: ","["http://www.10x.org.il/"]","[{ "j": 31.9077, "C": 35.0076 }]"

but it breaks on the first square bracket of this: "[{ "j": 31.9077, "C": 35.0076 }]" with the error message SyntaxError: invalid syntax
I am using the following python to read the file:
import csv

with open('programming_bootcamps_csv.csv', 'rb') as csvfile:
     reader = csv.DictReader(csvfile)
     for row in reader:
         print(row["campName"])

I have been reading through some documents on why a square bracket would break this, and haven't come to any conclusions on what the issue is or how to fix it.

A: Don't manually pre-process data unless absolutely necessary
I have reconstructed your data according to the comments as follows:
col1,col2,col3,col4,col5,col6,col7
10x org il,"[""Modiin, Israel""]","[""no current price posted""]","[""Modiin: no current size posted""]","{ ""Python Bootcamp"": {""Price: ","[""http://www.10x.org.il/""]","[{ ""j"": 31.9077, ""C"": 35.0076 }]"

Now everything works as expected.
import csv

with open('data.csv', 'rb') as csvfile:
     reader = csv.DictReader(csvfile)
     for row in reader:
         for key, value in row.items():
            print "{}: {}".format(key, value)

output:
col6: ["http://www.10x.org.il/"]
col7: [{ "j": 31.9077, "C": 35.0076 }]
col4: ["Modiin: no current size posted"]
col5: { "Python Bootcamp": {"Price:
col2: ["Modiin, Israel"]
col3: ["no current price posted"]
col1: 10x org il

It looks like the curious format is a broken mixture of json and csv. Your curly brackets don't match up and there is no consistency. Since it looks like it was generated automatically I would strongly suggest fixing the data format upstream in the program that generated the file.
However, if you can't fix the data upstream then further processing should be simple, possibly using json.loads() or if necessary with brute force.

A: Instead of using DictReader, write your own parser.
def dict_reader(fn, header=None):
    for line in open(fn):
        row = []
        while line:
            field,_, line = line.partition(",")
            while field.startswith('"["') and not field.endswith('"]"'):
                rest, _, line = line.partition(",")
                field += rest
            row.append(field)
        if header is None:
            header = row
            continue
        yield dict(zip(header, row))


text:
Q: Empty EKEventStore calendar list after authentication I would like to grab the names of my calendars on my Mac. I have 1 that's listed as "On My Mac", another (Birthdays) under "Other", and 4 that are pulled in from Google Calendar.
let eventStore = EKEventStore()
    eventStore.requestAccess(to: EKEntityType.event) { (accessGranted, error) in
    if (accessGranted) {
        let calendars = eventStore.calendars(for: .event)
        print(calendars)
    }
}

The goal is to determine how many days remain until the next event across all selected calendars.
Using the above code, I'm getting back an empty array. How can I access these calendars?


text:
Q: Which Database to prefer for tree traversal? I am trying to create a smart interface where when user enter a street name, they get suggestion for locality,city(all cities containing same street name), state, country etc.
Right now I am trying to make it work on MongoDB, but have doubt on its performance.
I will appreciate any suggestion on, how to use MongoDB effectively or other databases better suitable for this purpose. i`m using Nosql as we need high efficiency.
Note. above example is hypothetical one, i need for multiple purpose, where connection can be complex.

A: NoSQL databases are not the most efficient when you have relationships, they are most useful for having retrieval by key and denormalized databases, if you have relations in your data model the most efficient is a relational database (SQL)


text:
Q: I'm having an error in my COCO JSON file when I start training my RCNN model TypeError: coordinate list must contain at least 2 coordinates [1][my json file look like this {"id": 1049, "dataset_id": 34, "category_ids": [], "path": "/datasets/son/Dental (other) - 199.jpg", "width": 2126, "height": 860, "file_name": "D.jpg", "annotated": false, "annotating": [], "num_annotations": 0, "metadata": {}, "deleted": false, "milliseconds": 0, "events": [], "regenerate_thumbnail": false}],
"categories": [{"id": 1, "name": "teeth", "supercategory": "", "color": "#06c0c2", "metadata": {}, "keypoint_colors": []}], "annotations":
{"id": 3705, "image_id": 979, "category_id": 1,
"segmentation": [[326.4, 520.4, 311.9, 516.7, 309.6, 513.0, 309.6, 505.5]], "area": 20499, "bbox": [295.0, 299.0, 217.0, 221.0], "iscrowd": false, "isbbox": false, "color": "#f57865", "metadata": {}},


text:
Q: python filter letters in a string I need a command in python which filters the letters in a string but not deleting them for example:
string =raw_input("Enter the string:")
if string.startswith("a") and string.endswith("aaa"):
    print "String accepted"
else: print "String not accepted"
if "ba" in string:
    print "String accepted"
else :
    print "String is not accepted"

What should I add to ban other letters except a and b in the string

A: You can simply replace them with the empty string and check whether there's anything left:
string = raw_input("Enter the string:")
if string.replace('a','').replace('b',''):
    print "String not accepted"
else:
    print "String accepted"

The original string string will not be modified.

A: You can use a set , convert your string to a set and check if its a subset of a set with only a and b. Example -
s = raw_input("Enter the string:")
validset = set('ab')
if set(s).issubset(validset):
    print "String accepted"
else:
    print "String not accepted"

Demo -
>>> s = "abbba"
>>> validset = set(['a','b'])
>>> if set(s).issubset(validset):
...     print "String accepted"
... else: print "String not accepted"
...
String accepted

>>> s = "abbbac"
>>> if set(s).issubset(validset):
...     print "String accepted"
... else: print "String not accepted"
...
String not accepted

Or as indicated in the comments you can use set.issuperset() instead . Example -
s = raw_input("Enter the string:")
validset = set('ab')
if validset.issuperset(s):
    print "String accepted"
else:
    print "String not accepted"

A: This is a good use of regular expressions:
import re
my_string = raw_input("Enter the string:")
if re.match('^[ab]+$', my_string):
    print "String accepted"
else :
    print "String is not accepted"

This will match strings which contain only the characters a and b, of non-zero length. If you want to match zero-length strings, use * instead of +.

A: You could use a regex to search for letters and combinations you want to filter.
^((?![abcd]).)*$ will match things that don't contain a, b, c or d.

A: Try something like this. It lets you set multiple letters, symbols, etc
valid_char = ['a', 'b']

def validate(s):
    for char in s:
        if char not in valid_char:
            return False
    return True

if validate(input("Enter the string:")):
    print('Sting Accepted')
else:
    print('Sting not Accepted')


text:
Q: PHP $_POST[] not void after redirect I'm opening myself to honest critizism and sugggestions.
The issue is with the function $_POST[void] being valid after a redirect. Quotes.add.php is a form that directs to quotes.done.php, submitted to mysql and redirected back to quotes.add.php with an echo $msg and reset to be filled out again.
Is header(); the best method in this case?
quotes.done.php
else{
    include 'data.php';
    $query = "INSERT INTO quotes (`id`, `quotes`, `artist`, `date`) VALUES ('null', '$_POST[text]', '$_POST[artist]', 'null')";
    $result = mysql_query($query) or die (mysql_error());

    $_POST['void'] = "$_POST[artist] Was Added Successfully to database";
    unset ($_POST['artist']);

    //var_dump($_POST['void']);
    //exit;
    header ("location: quotes.add.php");
    exit;
}

quotes.add.php
if (isset($_POST['void'])) {
    $msg = $_POST['void'];
}else{
    $msg = "Please insert artist";
}

A: If you do a redirect i think you have to use $_SESSION.
I'd do:
session_start();
$_SESSION['msg'] =  "$_POST[artist] Was Added Successfully to database";
header ("location: quotes.add.php");
exit;

and then
session_start();
if (isset($_SESSION['msg'])) {
    $msg = $_SESSION['msg'];
    unset($_SESSION['msg'];
}else{
    $msg = "Please insert artist";
}

A: This is the clean, proper, and secure way to do it:
quotes.done.php
<?php
else{
    include 'data.php';

    // escape the input, to avoid SQL injection
    $text   =   mysql_real_escape_string($_POST['text']);
    $artist =   mysql_real_escape_string($_POST['artist']);

    $query  = "INSERT INTO quotes (`id`, `quotes`, `artist`, `date`) VALUES ('null', '{$text}', '{$artist}', 'null')";
    $result = mysql_query($query);

    // always set your variables to a default value
    $success = false;

    // did the query execute successfully?
    if($result){
        $success = true;
    }

    header('Location: quotes.add.php?result=addedquote&artist='.urlencode($_POST['artist']).'&success='.urlencode($success));
    exit;
}
?>

quotes.add.php
<?php
$msg = '';
if(isset($_GET['result']) && $_GET['result'] == 'addedquote') {
    $artist     =   htmlentities(urldecode($_GET['artist']), ENT_QUOTES, 'UTF-8', false);
    $success    =   (bool) urldecode($_GET['success']);
    if($success){
        $msg = "$artist Was Added Successfully to database";
    } else{
        $msg = "Failed to Add $artist to database";
    }
} else{
    $msg = "Please insert artist";
}
?>

A couple of things for you to note here:

*

*If you are not using a wrapper for running your db queries with prepared parameterized statements, you should use at least mysql_real_escape_string() to remove the nasty stuff in order to prevent SQL injection.

*As noted by others header() will do a GET request, hence why you are not getting the $_POST[void] on the page you are redirecting. That's why you will use variables on your url to transfer them to the redirected page, and then fetch them with $_GET.

*$_POST[somename] and $_POST['somename'] are two different things. They will work, because PHP will try to see if there is a constant named somename, if there isn't one, you are lucky, but if there is one, then all sky falls down.

A: If you want to keep the $_POST variables, don't redirect. A redirect causes the client's browser to re-request the page with only $_GET params.
Save the record to the database. Get the new record ID, redirect to a page and pass in the ID. Then use the ID to fetch and display the record.

A: Redirecting will not POST a value to the page. You could use session or GET.
$message = urlencode("$_POST[artist] Was Added Successfully to database");
header ("location: quotes.add.php?message=" . $message);

On your quotes.add.php page
echo $_GET['message'];


text:
Q: Dropdown menu in firefox being displayed horizontally I have a simple dropdown menu that looks like this in firefox:

When I click on the dropdown menu, the menu renders very strangely:

It renders fine in Chrome:

As far as I can tell, the HTML is ok...
<select class="date">

    <option value="Mon Oct 21 2013 15:08:57 GMT+0100 (BST)">
        Today

    </option>

    <option value="Tue Oct 22 2013 15:08:57 GMT+0100 (BST)">
        Tomorrow

    </option>

    <option selected="" value="Wed Oct 23 2013 15:08:57 GMT+0100 (BST)">

            Wednesday

    </option>

    <option value="Thu Oct 24 2013 15:08:57 GMT+0100 (BST)">

            Thursday

    </option>

    <option value="Fri Oct 25 2013 15:08:57 GMT+0100 (BST)">

            Friday

    </option>

    <option value="Sat Oct 26 2013 15:08:57 GMT+0100 (BST)">

            Saturday

    </option>

    <option value="Sun Oct 27 2013 14:08:57 GMT+0000 (GMT)">

            Sunday

    </option>

</select>

I've never seen a dropdown render like that before and am pretty confused as to what's going on, would appreciate any help.


text:
Q: C# - Same Calculation Slower Using Int vs Long? I've run into something really strange while working my way through some practice problems using dotnetfiddle. I have a program that applies a mathematical sequence (different calculations each step depending on whether the current step is even or odd):
using System;

public class Program
{

    public static void Main()
    {
        int ceiling = 1000000;

        int maxMoves = 0;
        int maxStart = 0;
        int testNumber;

        for(int i = 1; i <= ceiling; i++){
            testNumber = i;
            int moves = 1;
            while(testNumber != 1){
                if(testNumber % 2 == 0){
                    testNumber = testNumber / 2;
                    moves++;
                } else {
                    testNumber = (3 * testNumber) + 1;
                    moves++;
                }
            }
            if(moves > maxMoves){
                maxMoves = moves;
                maxStart = i;
            }
        }

        Console.WriteLine(maxStart);
        Console.WriteLine(maxMoves);
    }

}

As written, the execution time limit gets exceeded. However, if I change the declaration of test number to a long instead of an int, the program runs:
int maxMoves = 0;
int maxStart = 0;
**long** testNumber;

Why would making this change, which requires recasting i from an int to a long each increment of the for loop (at testNumber = i), be faster than leaving this as an int? Is performing the mathematical operations faster on a long value?

A: The reason seems to be an overflow. If you run that code enclosed in a
checked
{
    // your code
}

you get an OverflowException when running with testNumber as int.
The reason is that eventually 3*testNumber+1 exceeds the boundary of an int. In an unchecked context this does not throw an exception, but leads to negative values for testNumber.
At this point your sequence (I think it's Collatz, right?) does not work anymore and the calculation takes (probably infinitly) longer, because you never reach 1 (or at least it takes you a whole lot more iterations to reach 1).


text:
Q: Ubuntu 16.04 LTS and Oracle Instant Client - C++ linking error I'm not sure if the problem is more suitable for StackOverflow or AskUbuntu, but I will ask.
I have two virtual machines. On one Ubuntu 14.04 LTS and the other Ubuntu 16.04 LST. On both installed Oracle Instant Client 12.1 in the following way:
arkadiuszg@ubuntu:~/install/oracle$ ls -1
oracle-instantclient12.1-basic-12.1.0.2.0-1.x86_64.rpm
oracle-instantclient12.1-devel-12.1.0.2.0-1.x86_64.rpm

arkadiuszg@ubuntu:~/install/oracle$ sudo alien -i oracle-instantclient12.1-*

arkadiuszg@ubuntu:~/install/oracle$ cd /etc/ld.so.conf.d/

arkadiuszg@ubuntu:/etc/ld.so.conf.d$ sudo touch oracle-instantclient12.1.conf

arkadiuszg@ubuntu:/etc/ld.so.conf.d$ sudo vi oracle-instantclient12.1.conf

In created file I type:
/usr/lib/oracle/12.1/client64/lib

And finally:
arkadiuszg@ubuntu:/etc/ld.so.conf.d$ sudo ldconfig

I am using C++ tools like: g++, make, gdb. Compiling the project runs on both machines correctly, but the problem is linking on Ubuntu 16.04. I keep getting the following errors:
DbConnection.cpp:(.text+0x536): undefined reference to `oracle::occi::Date::toText(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) const'
build/Release/GNU-Linux/database/DbConnection.o: In function `CDbConnection::connect()':
DbConnection.cpp:(.text+0x1314): undefined reference to `oracle::occi::Environment::createEnvironment(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, oracle::occi::Environment::Mode, void*, void* (*)(void*, unsigned long), void* (*)(void*, void*, unsigned long), void (*)(void*, void*))'
collect2: error: ld returned 1 exit status

When I do exactly this same on Ubuntu 14.04, then everything is OK. Compiling and linking ends with success.
Can anybody help me, please...

A: It is because of the compiler version.
oracle occi is compatible with gcc 4.8.2
check the compiler version to see the differences


text:
Q: Set environment variable when generating dockerfile within gradle? I am generating my dockerfile in gradle before I do the docker build command. I know you normally set an environment variable when writing your own dockerfile, you would do it like this:
ENV JAVA_HOME /path/to/java

But when you try to get gradle to create the dockerfile, that syntax doesn't work. Here is my current task in gradle.build :
task createDockerFile(type: Dockerfile) {
    destFile = project.file('build/docker/Dockerfile')
    from 'openjdk:10-jdk-slim'
    addFile "./build/libs/MyRestAPI-${project.version}-SNAPSHOT.jar", "MyRestAPI.jar"
    runCommand 'sh -c \'touch /MyRestAPI.jar\''
    exposePort 9080
    entryPoint 'java', '-jar', '/MyRestAPI.jar'
    ENV 'JAVA_HOME /opt/jdk10'
}

When I run this using ./gradlew createDockerFile, I get this error :
unexpected token: JAVA_HOME @ line 54, column 9.
         ENV 'JAVA_HOME /opt/jdk10'
             ^


text:
Q: Allowing both moving and copying a returned class member I'm trying to write a class that contains a function returning one of the class members, and I want to allow the caller to either move or copy the returned value. I wrote some dummy structs to test this; and after trying different variations, this seems to give me what I want.
#include <iostream>
using namespace std;

struct S {
  int x;
  S() : x(10) { cout << "ctor called\n"; }
  S(const S& s) : x(s.x) { cout << "copy ctor called\n"; }
  S(S&& s) : x(s.x) { cout << "move ctor called\n"; }
  // I'm implementing move and copy the same way since x is an int.
  // I just want to know which one gets called.
};

struct T {
  S s;
  T() : s() {}
  S&& Test() && {
    return move(s);
  }
  const S& Test() & {
    return s;
  }
};

int main() {
  T t;
  auto v = move(t).Test();
  cout << v.x << "\n";
  T t2;
  auto w = t2.Test();
  cout << w.x << "\n";
  return 0;
}

The code prints out (with clang++-5.0 c++14):
ctor called
move ctor called
10
ctor called
copy ctor called
10

Is this an acceptable way to implement what I want? I have a few questions:

*

*In the first Test function, I tried both S&& and S for the return type and it doesn't change the output. Does && mean anything for the (non-template) returned type?

*Is it guaranteed that auto v = move(t).Test() would only invalidate the "moved" member? If struct T had other member variables, can I assume this call wouldn't invalidate them?

A:
In the first Test function, I tried both S&& and S for the return type and it doesn't change the output. Does && mean anything for the (non-template) returned type?

There are little differences:

*

*S&& is a (r-value) reference, so object is not yet moved.

*returning S would move-construct S, so member is moved once the method is called.

For move(t).Test();, return ingS&& does nothing whereas returning S would move the member.

Is it guaranteed that auto v = move(t).Test() would only invalidate the "moved" member? If struct T had other member variables, can I assume this call wouldn't invalidate them?

Yes, only T::s is moved. std::move is just a cast to rvalue.

A: Yes it is acceptable way to implement this.

*

*It does the same thing because returned value is temporary object, thus rvalue.

*Depends on what you mean by invalidating


text:
Q: How to save files to a foreign key model in django I am using a django model to save user uploaded images. I want each image to be stored in the productimage model that is a foreign key model to the product model which is a foreign key model to the user model. What I mean is:
User -----> Product ------> Productimage
I want to create a new instance of the productimage model but can't seem to figure out how to since it is a foreign key to another foreign key.
I do not know how to target a foreign key within a foreign key to create. For example I've tried:
request.user.product.productimage.create()
request.user.product_set.productimage_set.create()
request.user.product.productimage_set.create()
Nothing seems to create a new instance of the productimage model.
class product(models.Model):
 user = models.ForeignKey(User, on_delete=models.CASCADE)
 product_title =  models.CharField(max_length=100, blank=True)
 product_price =  models.CharField(max_length=30, blank=True)
 product_description =  models.CharField(max_length=1000, blank=True)

class productimage(models.Model):
product = models.ForeignKey(product, on_delete=models.CASCADE)
product_images = models.FileField(blank=True)

def add(request):
if request.method == "POST":
    product_title = request.POST.get("product_title")
    product_price = request.POST.get("product_price")
    product_description = request.POST.get("product_description")
    request.user.product_set.create(product_title = product_title,product_price =product_price, product_description = product_description,)
    for file in request.FILES.getlist("filepond"):
        product_images = file
        request.user.product_set.productimage_set.create()###trying to create a new instance of productimage model for each file
return render(request,"main/add.html")

A: You've already created your product just a few lines earlier; you just have to use that.
product = request.user.product_set.create(product_title = product_title,product_price =product_price, product_description = product_description,)
for file in request.FILES.getlist("filepond"):
    product_images = file
    product.productimage_set.create()


text:
Q: Shell Variables are empty when called in a file name but not when echo'd or called elsewhere I have 4 shell variables set
remote_account="raccname"
remote_machine="server"
First_Name="firstname"
Last_Name="lastname"

when I call remote_account or remote_machine in my script they get used fine
echo "What directory shall you choose?"
  read dir
  scp -r ~/csc60/$dir $remote_account@$remote_machine:directoryA
  exit;;

but when I call the other two as such
echo "What directory shall you choose?"
  read dir
  scp $remote_account@$remote_machine:tars/$Last_Name_$First_Name_$dir.tar.z ~/tars
  exit;;

it grabs the tars file from tars/$dir.tar.z completely skipping $Last_Name_$First_Name_
when I throw an echo $Last_Name in it still shows it as "lastname"
Is there some rule using "_" between variables or something, or am I just missing something obvious?

A: _ is a valid character for variable names, therefore you have to qualify which part is the variable.
scp "$remote_account@$remote_machine:tars/${Last_Name}_${First_Name}_$dir.tar.z" ~/tars

A: You need to delimit your variable value using  ${}, as  you declared $Last_Name_$First_Name_$dir is  treated as one variable and shell put value for it. As in your case you did not defined value for it . It will be intepreted as "".
use  ${LAST_NAME}_${FIRST_NAME}


text:
Q: How do I determine which css media type is being requested on my page? I'm looking to alter the way my asp .net webpage is output to the browser depending on the css media type being used.
Although the css is generally taking care of the differences in appearance between screen and print mode I would also like to make some minor adjustments to the markup when print mode is required. I would simply be dropping a floated section down below its sibling rather than as a 2 col approach which is to used during screen layout in the browser.

A: This is not possible. No browser exposes this information in a way that will let you change markup on the server side (i.e. before sending to the browser).
The browser can determine what CSS to use according to what it is going to do with that page (print, display, read...), but you can't know which it will be.
Consider changing your markup so it will work well with both screen and print css.
Another option is to create a print link that will link to a print optimized version of the page.

A: Not a very nice method, but you could just add in the floated section down below its sibling and hide this section in the Screen CSS file. Then in the Print CSS file you could show this hidden section and hide the other one which you do not then want in the print page.
This would cause your page to have extra html, but depending on what this floated section is, it could be an option.

A: If your markup is written in that order in order to float your column, but the actual format of the document makes more sense a different way round, you need to fix your markup and your screen CSS.
MNarkup shouldn't be dependant on CSS. Mark up your document first so that it makes sense without the CSS - which, reading between the lines, is the way you want it to display for print. Once you've done that, style the column layout based on that source order.

A: So your goal was to present a browser page that mimics "Print Preview"? As answered previously, the browser does not expose the media type, so it's not possible to query that ahead of time to alter the output to the browser. In your particular case, my understanding from W3C docs is that the 'print' media type is only triggered for "paged material and for documents viewed on screen in print preview mode." Meaning the only way to activate the 'print' media type for screen display is to choose 'Print Preview' anyway.
Of course, once you're in 'Print Preview', using media queries to see an altered layout works just fine. Here's a super simple example that does what you wanted to do:
The styles:

and the HTML:

Sibling 1

Sibling 2


text:
Q: ETL and QA testing I have few questions on ETL which I am not crystal clear which are as follows:
1)What are the components of test plan vs test strategy in detail?
2)What is the difference between ODS vs staging area in ETL? Are both present in ETL between source and target database (data warehouse) or only one present? If both are present which comes first?

A: ODS : Operational Data store.
It is a collection of integrated databases designed to support operational monitoring. Unlike the OLTP databases, the data in the ODS are integrated, subject oriented and enterprise wide data
Staging Area: Which comes after ODS, where it cleans operational data before loading the
data into Data warehouse.


text:
Q: PHP imagefilter question Why does IMG_FILTER_CONTRAST in example 1 produce a brighter image then in example 2 can someone explain the IMG_FILTER_CONTRAST parameter in more detail me as why this happens?
Example 1
imagefilter($image, IMG_FILTER_CONTRAST, 255);

Example 2
imagefilter($image, IMG_FILTER_CONTRAST, 100);

A: According to PHP: imagefilter - Manual, it looks like 255 is outside of the range of values for IMG_FILTER_CONTRAST.

The documentation misses the exact meaning and valid ranges of the arguments for ImageFilter(). According to the 5.2.0 sources the arguments are:
  ...
IMG_FILTER_CONTRAST
  -100 = max contrast, 0 = no change, +100 = min contrast (note the direction!)

A: As PanuWorld outlines in a comment in the docs - link
"...IMG_FILTER_CONTRAST
-100 = max contrast, 0 = no change, +100 = min contrast (note the direction!)
"...

A: What do you want to hear from us as the manual says it is the constrast level and you are using different values in both calls.
That's why the output is different.

A: IMG_FILTER_CONTRAST: Changes the contrast of the image. Use arg1 to set the level of contrast.
IMG_FILTER_CONTRAST: Contrast level.
http://en.wikipedia.org/wiki/Contrast_(vision)


text:
Q: Change order when applying templates? For example i have the following xml:
<items>
  <item value="1">
  <item value="2">
  <item value="3" start="true">
  <item value="4">
  <item value="5">
</items>

And xsl like this:

  <xsl:apply-templates select="item"/>

<xsl:template match="item">

<xsl:value-of select="@value"/>

</xsl:template>

This outputs the items in document order. However I would like it to start at the specified position, so the order of the output would be 3, 4, 5, 1, 2. It this possible without having to change the order in the document?
Thanks!
Edit:
The following works:
<xsl:apply-templates select="item">
  <xsl:sort data-type="number" select="position()-count(../item[@start]/preceding-sibling::item)+count(../item)*boolean(position()<=count(../item[@start]/preceding-sibling::item)"/>
</xsl:apply-templates>

A: You could change:

  <xsl:apply-templates select="item"/>

to:

    <xsl:apply-templates select="item[@start='true']"/>
    <xsl:apply-templates select="item[@start='true']/following-sibling::item"/>
    <xsl:apply-templates select="item[@start='true']/preceding-sibling::item"/>

That will produce the expected result in the given example. Whether that's the rule you want to apply in general is not clear to me.

Added:

What about if the start tag is optional? So if there isn't one it
  outputs in document order but if there is one it starts there?

Well, you could split the decision tree like this:

    <xsl:choose>
        <xsl:when test="item[@start='true']">
            <xsl:apply-templates select="item[@start='true']"/>
            <xsl:apply-templates select="item[@start='true']/following-sibling::item"/>
            <xsl:apply-templates select="item[@start='true']/preceding-sibling::item"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:apply-templates select="item"/>
        </xsl:otherwise>
    </xsl:choose>

Or, if you prefer, you could shorten this to:

    <xsl:apply-templates select="item[@start='true']"/>
    <xsl:apply-templates select="item[@start='true']/following-sibling::item"/>
    <xsl:apply-templates select="item[@start='true']/preceding-sibling::item"/>
    <xsl:apply-templates select="item[not(../item[@start='true'])]"/>

Both of these avoid the potentially expensive xsl:sort instruction - not to mention the insanely convoluted calculation such sort would require.


text:
Q: Using different databases with Entity Framework 6 I have a problem with using different databases in a mvc application with Entity Framework 6. Our client will use a database of their own which could be a MySQL, PostgreSQL or Oracle database.
I have made an .edmx file for MySQL and PostgreSQL, these models work individually but if possible I want to use only one model for all databases. The databases will have identical tables and columns.
So want to make something like this:
using (var connection = new DbConnection())
{
    string id = connection.Set<user>().First().Id;
}

The DbConnection has to be a connection to the right database (you can see which database to use in a resource file)
I am encountering the following problem with a database first approach:
I have read http://www.codeproject.com/Articles/82017/Preparing-an-Entity-Framework-model-for-multi-prov.aspx and when I followed the instructions I got a

MetadataException: Unable to load the specified metadata resource exception.

I have tried everything to find the .ssdl file but I just can't find it.
Am I doing it the right way or does anyone know if there is a better way to do this?

A: I tried doing exactly what you are trying to do but with MS SQL and Vista DB.  I followed that tutorial and ran into the same problem.
By following the tutorial, you will have a separate ssdl file for each DB.  Make sure you have set it to copy to output directory and then updated your connection string accordingly.
To set it to copy to the output folder, right click on the ssdl file in Solution Explorer and change "Copy to OUtput Directory" to "Copy if Newer".
Then change the metadata part of your connection string to something like this:
metadata=res://*/DataModel.csdl|c:\dev\program\bin\debug\DataModel.VistaDB.ssdl|res://*/DataModel.msl;

Notice the path to the ssdl is a folder path.  The path I have hear is the path I used.  You will need to change it accordingly


text:
Q: Updating the (GC) Garbage Collection policy of IBM Websphere (WAS) v8 We have a Java EE application that runs on Websphere (IBM WebSphere Application Server v8.5.5.1)
According to IBM (http://www.ibm.com/developerworks/websphere/techjournal/1106_bailey/1106_bailey.html), the default GC policy of WAS v8 is -Xgcpolicy:gencon
I need to change this default to -Xgcpolicy:balanced
I have searched online and here on stackoverflow but haven't found any instruction how I can achieve this.
Any thoughts?

A: That's just a JVM property.  Have you tried setting that JVM argument in the WAS Admin console?
Middleware servers > server-name > Process definition > Java Virtual Machine
And of course do a save/synch and stop/start of the server to pick up the changes.


text:
Q: Rails 4 CSV Generation of Index View without Code Duplication How can I export my namespaced/resouce/index.html.erb content, which uses a partial for each row on the index page, into a CSV file, without duplicating code in the viewfile for the CSV (or in whichever method outputs the CSV)?
The controller looks like this:
class Namespaced::ResourceController < AncestorController
  def index
    @rows = current_object.rows.some_scope.page(params[:page])

    respond_to do |format|
      format.html
      format.csv do
        headers['Content-Disposition'] = "attachment; filename=\"filename.csv\""
        headers['Content-Type'] ||= 'text/csv'
     end
    end
  end
end

The index view just lists table headers:

                  Order ID

                  Order Date

                  Description

                  Price

                  Shipping

                  Tax

                  Total

                  Status

              <%= render partial: "row", collection: @rows %>

          Download: <%= link_to 'CSV', namespaced_resource_path(format: :csv) %>

The partial HTML view looks as follows:

    <%= row.order_id %>

    <%= row.row_date %>

    <%= row.description %>

    <%= row.price %>

    <%= row.shipping %>

    <%= row.tax %>

    <%= row.calculate_total %>

    <%= row.status %>

...and the CSV view is as such:
<%- headers = ['Order ID', 'Order Date', 'Description', 'Price', 'Shipping', 'Tax', 'Total', 'Status'] -%>
<%= CSV.generate_line headers %>
<%- @rows.each do |entry| -%>
  <%= CSV.generate_line([
    row.order_id,
    row.row_date,
    row.description,
    row.price,
    row.shipping,
    row.tax,
    row.calculate_total,
    row.status
  ]) -%>
<%- end -%>

Note the same properties/callbacks used for the partial HTML view, and the  CSV view. Some of those are relatively complex decorator/helper callbacks, and might change / be omitted / have more added in the future. The headers are also added in both places (and they aren't all just attributes of the data model). So basically, this partial view and the CSV view exhibit code duplication.
While I can think of some techniques to populate the column headers and use the same callback functions, I'm not sure if it's conventional. I have a hunch there is a simple way to accomplish this that is built into the framework.
What is the most Rails-4-ish way to DRY this up? How can I have one single partial view that works for both the HTML index view and the CSV view?


text:
Q: Parsing XML using NSXMLParser in Swift can you please help me out for this one,  I tried it out in xcode 6 beta 5 and it is working
fine, Now i updated to the latest version xcode 6 beta 7 and now i got a error EXC_BAD_ACCESS
Here's my code:
var url = NSURL(string: NEWSPAGE)
        let operation = AFHTTPRequestOperation(request: NSMutableURLRequest(URL: url))
        operation .setCompletionBlockWithSuccess({(operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in

        // Start parsing Data

        var parser = NSXMLParser(data:responseObject as NSData)
        parser.delegate = self
        parser.parse()

    }, failure: {(operation: AFHTTPRequestOperation!,error: NSError!) in

        NSLog("%@", error)

    })

    operation.start()

You're Help will be greatly appreciated
Thanks.

A: Did you make a clean build after upgrading to beta 7?
Do:
Product->Clean
Product (hold down Alt key)->Clean build directory
Window->Organizer->Delete derived data
After that, run your app again


text:
Q: Opening urls in Avaloniaui Android Avalonia.Android was recently launched, for creating apps with the AvaloniaUI interface. I was in doubt: is there a way to open website links in an android application made in Avaloniaui?
I tried several ways to implement this functionality, even using Process in C#, but without success. It would be a lot of help if someone showed how to implement the url


text:
Q: Datatables 1.10.3 Ajax Load Columns Width i have the following problem:
In my mvc-application, i have to load the data with an ajaxload. This works very fine. But in the datatable the blabla has a shorter lenghts like the column in the ajax call { "data": "blablablablabla" }. So in the table it is shown like:
blabla (header)
blabl-
ablab-
labla-
...
So i want to set the column width longer as the !!!
Here my code snippets:

                            ID
                            ArtID
                            MarkennameRad
                            MarkennameMotor
                            MarkennameZusatz
                            TypSchlüssel
......
......

And the ajax call:
$('#Artikelstamm').DataTable({
            "processing": true,
            "serverSide": true,
            "lengthMenu": [[100, 125, 150], [100, 125, 150]],
            "ajax": {
                "url": "@Url.Action("List1", "DFS_Akustik")",
                "type": "POST"
            },
            "columns": [
                { "data": "ID" },
                { "data": "ArtID" },
                { "data": "MarkennameRad" },
                { "data": "MarkennameMotor" },
                { "data": "MarkennameZusatz" },
                { "data": "TypSchluessel" },

Sorry i can't set an image here...
I want that it is: ZN050-SDL.4F.V7P7
and not:
ZN050-
SDL.4F.V7P7
I hope you can help me. Thank you very much.
Greetz
Vegeta_77


text:
Q: How to set Data Display Key to from JSON API a variably I'm trying to make a HTML form that shows data from JSON APIs.But I need to set the data-display key to a variable , because I will use two dependent drop lists and I have to log the selected from the first list and use it's value as the data display key of the second one.
html:
<form>

      Select payment
      <select
      class="form-control"
      name="payment"
      id="payment"
      data-source="https://sheetdb.io/api/v1/ptnaed3a6a4nr"
      data-displayKey="Client_Name">
      </select>
    </form>

JS :
 $('select[data-source]').each(function select() {
  var $select = $(this);

  $select.append('<option></option>');

  $.ajax({
    url: $select.attr('data-source'),
  }).then(function select(options) {
    options.map(function select(option) {
      var $option = $('<option>');

      $option
        .text(option[$select.attr('data-displayKey')]);

      $select.append($option);
    });
  });
});

A: I See you using JQuery you can use
$.getJSON( "url", function( data ) {
    var items = [];
    $.each( data, function( key, val ) {
         items.push( "<option value='" + key + "'>" + val + "</option >" );
    });
    $( "<selector>", {
       "class": "my-new-list",
        html: items.join( "" )
        }).appendTo( "selector" );
     });

for more info check this url 1


text:
Q: How to validate date only in this format mm/dd/yy? Can you please tell me how to validate date only when in this format mm/dd/yy ? I actually found a solution but it also returns true when mm-dd-yy.
I need only it return true when the format is mm/dd/yy.
Here is my fiddle
:
http://jsfiddle.net/naveennsit/Hk2tc/
alert(isDate("1/12/1234"));

function isDate(txtDate)

{

  var currVal = txtDate;

  if(currVal == '')

    return false;

  //Declare Regex

  var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;

  var dtArray = currVal.match(rxDatePattern); // is format OK?

  if (dtArray == null)

     return false;

  //Checks for mm/dd/yyyy format.

  dtMonth = dtArray[1];

  dtDay= dtArray[3];

  dtYear = dtArray[5];

  if (dtMonth < 1 || dtMonth > 12)

      return false;

  else if (dtDay < 1 || dtDay> 31)

      return false;

  else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)

      return false;

  else if (dtMonth == 2)

  {

     var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));

     if (dtDay> 29 || (dtDay ==29 && !isleap))

          return false;

  }

  return true;

}

A: your problem is your regex... it also accept the / char.
Change to
 var rxDatePattern = /^(\d{1,2})(-)(\d{1,2})(-)(\d{4})$/;

however, this regex also accepts dates like 40-40-9999...
and of course, you don't have the day 40 in the 40th month ;)
check this link for help
http://www.regular-expressions.info/dates.html

A: Your issue is in the regex...
(\/|-) means "accept either / or - character".
Try changing this line:
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;

To this:
var rxDatePattern = /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/;

The difference is that both occurrences of (\/|-) were replaced with (\/), which only matches /.

A: You are using - in var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;.
You are not filtering -.
Check this Updated  fiddle


text:
Q: Most "pythonic" way of organising class attributes, constructor arguments and subclass constructor defaults? Being relatively new to Python 2, I'm uncertain how best to organise my class files in the most 'pythonic' way. I wouldn't be asking this but for the fact that Python seems to have quite a few ways of doing things that are very different to what I have come to expect from the languages I am used to.
Initially, I was just treating classes how I'd usually treat them in C# or PHP, which of course made me trip up all over the place when I eventually discovered the mutable values gotcha:
class Pants(object):
    pockets = 2
    pocketcontents = []

class CargoPants(Pants):
    pockets = 200

p1 = Pants()
p1.pocketcontents.append("Magical ten dollar bill")
p2 = CargoPants()

print p2.pocketcontents

Yikes! Didn't expect that!
I've spent a lot of time searching the web and through some source for other projects for hints on how best to arrange my classes, and one of the things I noticed was that people seem to declare a lot of their instance variables - mutable or otherwise - in the constructor, and also pile the default constructor arguments on quite thickly.
After developing like this for a while, I'm still left scratching my head a bit about the unfamiliarity of it. Considering the lengths to which the python language goes to to make things seem more intuitive and obvious, it seems outright odd to me in the few cases where I've got quite a lot of attributes or a lot of default constructor arguments, especially when I'm subclassing:
class ClassWithLotsOfAttributes(object):
    def __init__(self, jeebus, coolness='lots', python='isgoodfun',
             pythonic='nebulous', duck='goose', pants=None,
             magictenbucks=4, datawad=None, dataload=None,
             datacatastrophe=None):

        if pants is None: pants = []
        if datawad is None: datawad = []
        if dataload is None: dataload = []
        if datacatastrophe is None: datacatastrophe = []
        self.coolness = coolness
        self.python = python
        self.pythonic = pythonic
        self.duck = duck
        self.pants = pants
        self.magictenbucks = magictenbucks
        self.datawad = datawad
        self.dataload = dataload
        self.datacatastrophe = datacatastrophe
        self.bigness = None
        self.awesomeitude = None
        self.genius = None
        self.fatness = None
        self.topwise = None
        self.brillant = False
        self.strangenessfactor = 3
        self.noisiness = 12
        self.whatever = None
        self.yougettheidea = True

class Dog(ClassWithLotsOfAttributes):
    def __init__(self, coolness='lots', python='isgoodfun', pythonic='nebulous', duck='goose', pants=None, magictenbucks=4, datawad=None, dataload=None, datacatastrophe=None):
        super(ClassWithLotsOfAttributes, self).__init__(coolness, python, pythonic, duck, pants, magictenbucks, datawad, dataload, datacatastrophe)
        self.noisiness = 1000000

    def quack(self):
        print "woof"

Mild silliness aside (I can't really help myself when cooking up these artificial example classes), assuming I have a real-world need for a set of classes with this many attributes, I suppose my questions are:

*

*What is the most, uhh, 'pythonic' way of declaring a class with that many attributes? Is it best to put them against the class if the default is immutable, ala Pants.pockets, or is it better to put them in the constructor, ala ClassWithLotsOfAttributes.noisiness?

*Is there a way to eliminate the need to redeclare the defaults for all of the subclass constructor arguments, as in Dog.__init__? Should I even be including this many arguments with defaults anyway?

A: *

*If attributes will vary from instance
to instance make them instance
attribute i.e. create them
inside__init__ using self else if they need to
be shared between class instances
like a constant, put them at class
level.

*If your class really need to pass, so
many arguments in __init__, let
derive class use argument list and
keyword arguments e.g.
class Dog(ClassWithLotsOfAttributes):
    def __init__(self, *args , **kwargs):
        super(ClassWithLotsOfAttributes,    self).__init__(*args , **kwargs)
        self.coolness = "really cool!!!

*

*No need of passing all variables except few important ones, in
__init__, class can assume some
defaults and user can change them
later on if needed.

*Use 4 spaces instead of tab.

*if you need to add an extra arg bite, to Dog and keyword arg old too
class CoolDog(ClassWithLotsOfAttributes):
    def __init__(self, bite, *args , **kwargs):
        self.old = kwargs.pop('old', False) # this way we can access base class args too
        super(ClassWithLotsOfAttributes,    self).__init__(*args , **kwargs)
        self.bite = bite
        self.coolness = "really really cool!!!
various ways you useCoolDog
CoolDog(True)
CoolDog(True, old=False)
CoolDog(bite=True, old=True)
CoolDog(old=True, bite=False)


text:
Q: Working of Auth0 with Zuul and Eureka client I have 5 services:

*

*Zuul service

*Auth service

*Discovery Service
other two are resource services

I do not understand how the validation of token takes place.
I understand the following:

*

*Resource service and Auth will be going to register in Discovery Service

*Zuul Service will act as a gateway service

For the 1st request

UI (will call) --> Zuul service (will call) --> Auth service = will return token

For the 2nd request

UI (having token inside Header)-->Zuul service -->Auth service(to
validate token) --> Resource service = Return to UI

or

UI (having token inside Header)-->Zuul service --> Resource service = Return to UI

I want to know which flow is right. If the 2nd is right then how does token validation take place?


text:
Q: How to check if value exists in Firebase Realtime Database (Dart/Flutter)? How can I check if a certain value exists in a Firebase Realtime Database?
I am using the following command but it is not working:
Future<bool> rootFirebaseIsExists(DatabaseReference databaseReference) async{
  DataSnapshot snapshot = await databaseReference.once();
  if( snapshot == null ){
    print("Item doesn't exist in the db");
  }else{
    print("Item exists in the db");
  }
  return snapshot !=null;
}
print("exists?");
rootFirebaseIsExists(FirebaseDatabase.instance.reference().child("users").child('userid000').child('pushTokens').child("field_to_check"));

The problem is that even when the node doesn't exist the the snapshot is not null and then the function returns that the item exists in the db.
Thanks!

A: once() always yields a DataSnapshot object.  You have to check if that snapshot contains any data by looking at its value property.
  if (snapshot.value == null) {
    print("Item doesn't exist in the db");
  } else {
    print("Item exists in the db");
  }


text:
Q: Ubuntu 13.04 Screen Brightness Only Changes Via Hotkeys This is a new problem I'm facing in 13.04, and is not related to what worked for 12.10 or earlier.
In 12.10, I had the acpi_backlight=vendor in my grub in order to make the brightness setting work. However, this does not work on 13.04. I don't even see a brightness bar.
To change that, I tried acpi_osi= and the brightness bar appeared in the system settings. Moving it doesn't change the brightness, but using my hotkeys does.
Since Ubuntu doesn't remember the brightness settings between boots, I had a script that would adjust it during startup. Now, even that doesn't seem to work. Only my hotkeys work at the moment.
Laptop information:

*

*Model: Acer Aspire E1-571

*Processor: Intel® Core™ i3-3110M CPU @ 2.40GHz × 4

*Graphics: Intel® Ivybridge Mobile

*OS type: 64bits

Things I've tried

*

*acpi_osi= using this makes my hotkeys work, but the brightness slider doesn't work

*acpi_osi=Linux

*acpi_osi='!Windows 2012'

*acpi_osi='!Windows 2012' acpi_backlight=vendor

*acpi_backlight=vendor

A: Try using acpi_osi='!Windows 2012' the same way you would use acpi_backlight=vendor
that fixed it for me, another one to try is acpi_osi=Linux

A: As a temporary(?) solution I boot Ubuntu 13.04 64bit with my latest Ubunt 12.10 64bit kernel ( so I boot with 3.5.0-27-generic, not with the newest 3.8.0-19-generic)
I've also kept the old /etc/default/grub file that I used in 12.10 (where I had to add acpi_backlight=vendor to make my brightness keys Fn-leftt and Fn-right function)


text:
Q: fatfs: after f_stat the directory is created The Fatfs is R0.08b. What I do is detecting whether a dir is existed. I use f_stat to check the status.
The problem is: if I clear the /root directory and then call :

sprintf(p, "%s", "0:/testdir");
frs = f_stat(p, NULL);

the frs will return FR_OK. And then I can find there is a /testdir created. However, the /testdir can't be open until I re-mount the SD card.
Any idea?


text:
Q: iPhone achieve smooth animation using progress bar timer I am trying to implement a simple quiz app on the iphone in the spirit of learning, part of this app is a timer.
I want my timer to count down from 10 to 0.  I had a simple NSTimer that repeats and calls a method every second and in this method I update a label which displays the remaining time, which works nicely.
Now instead of displaying the timer using a label I wanted to use a graphical progress bar, so I created ten images, one full in length (representing 10), the next 9/10 of the size and so on, and in my repeating timer method instead of updating a label I update a UIImage with the appropriate image so over time the progress bar gets smaller and smaller.
My problem is that due to the way I have implemented the progress bar, it doesn't look very smooth when it updates every second.  Is there another way I should approach developing this kind of functionality?  I have heard that you could use a stretchable image to get a smoother effect but I couldn't see any good examples of that.
Any advice and code samples welcome, just trying to learn here.

A: After investigating a few options I have decided to use a UIProgressView (suggested by sudo in comments) coupled with a NSTimer which updates the progress ten times a second for ten seconds, I used this solution because:

*

*It is a standard element provided by apple.

*This option doesn't have the overhead of creating and loading 100 images (as suggested by Krypton in the comments).

*By the NSTimer I can add a check to the function updateProgressBar to add some feedback to the user when the timer is reaching low, e.e. vibrate for the last three seconds etc (using animation I don't think I would have that option).

Using the code below assume I have a UIProgressView variable named 'progressView', an NSTimer named 'timer' and a floating point variable named 'time', then:
-(void)updateProgressBar
{
    if(time <= 0.0f)
    {
        //Invalidate timer when time reaches 0
        [timer invalidate];
    }
    else
    {
        time -= 0.01;
        progressView.progress = time;
    }
}

-(void)animateProgressView2
{
    progressView.progress = 1;
    time = 1;
    timer = [NSTimer scheduledTimerWithTimeInterval: 0.1f
                                             target: self
                                           selector: @selector(updateProgressBar)
                                           userInfo: nil
                                            repeats: YES];
}

Another way I investigated (after seeing Disco's comments) but decided against was to use animation.  In this instance I created two png images, named 'redbar.png' and 'greenbar.png', the idea bring they would be placed over each other (the green bar being on top/in the foreground), and over the duration of the animation the green bar shrinks, revealing the red bar in the background.
UIImage *green= [UIImage imageNamed:@"greenbar.png"];
UIImage *red= [UIImage imageNamed:@"redbar.png"];

redBar.image = red; // allocate the red image to the UIImageView
redBar.frame = CGRectMake(20,250,220,30);// set the size of the red image

greenBar.image = green; // allocate the green image to the UIImageView
greenBar.frame = CGRectMake(20,250,220,30);//set the size of the green image

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:10]; //the time you want the animation to last for
[UIView setAnimationDidStopSelector:@selector(animationFinished)];//the method to be called once the animation is finished
    //at the end of the animation we want the greenBar frame to disappear
    greenBar.frame = CGRectMake(20,250,0,30);
[UIView commitAnimations];

An ideal solution would be to combine the UIProgressView and the UIAnimation block, but this is not currently an option (see this question animate a UIProgressView's change).
Hope this helps someone in the future.
EDIT::
It appears the ideal solution I mention above is now available in iOS5, taken from the apple reference site:
setProgress:animated:
Adjusts the current progress shown by the receiver, optionally animating the change.

*

*(void)setProgress:(float)progress animated:(BOOL)animated

A: May not be what you're looking for but may help you.
Why not have a UIImageView with your image at full size then apply some UIView animations to it over a set duration? This way the shrinking will be smooth.
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"YourImage.png"]];
imageView.frame = CGRectMake(0,0,320,30);//starts big
[self.view addSubview:imageView];
[UIView beginAnimations:@"Progress Bar Animation" Context:nil];
[UIView setAnimationDuration:10]; //whatever time you want
imageView.frame = CGRectMake(0,0,10,30);//ends small
[UIView commitAnimations];

This may be what you're looking for, I'm not sure. Just seems a bit easier than using ten different images.

A: I did by increasing the setting progress from (0.01 - 1.00) to (0.001 - 1.000) and decrease the time difference between setting progress values.
Here is my below code  with three different speeds of animation.
 -(void)setProgressViewProgress
{
    //Check for completion
    if(progress > 1.0)
    {
        [self progressCompleted];
        return;
    }
    //Diffrent speed for range
    CGFloat speed;
    //From 0.000 to 0.500 speed is 500*0.007 = 3.5 seconds    0.007(sec) => x(sec) = Total time in range(sec) / 500.0 ==> 3.5/500.0 = 0.07
    if(progress<0.50)
    {
        speed = 0.007;
    }
    //From 0.500 to 0.750 speed is 250*0.005 = 1.25 seconds 0.005(sec) => x(sec) = Total time in range(sec) / 500.0 ==> 1.25/250.0 = 0.05
    else if(progress<0.75)
    {
        speed = 0.005;
    }
    //From 0.750 to 1.0 speed is 250*0.002 = 0.5 seconds 0.002(sec) => x(sec) = Total time in range(sec) / 500.0 ==> 0.5/250.0 = 0.02
    else
    {
        speed = 0.002;
    }
    //Increase the progress view by 1/1000  for smooth animation
    progress+=0.001;
    [progressView setProgress:progress];
    [self performSelector:@selector(setProgressViewProgress) withObject:nil afterDelay:speed];
}


text:
Q: How to make same js library work in both browser and react native? I have a js library that I want to be usable both in the browser and react native. Most of the code is reusable, but some parts need platform conditioning. Something like:
if (react_native) {
  do rn stuff
} else {
  do browser stuff
}

I've seen flags like this used in open source projects but I'm not sure how to get access to them?

A: the global object window only exists in the browser environment so you can check to see if it is defined you are in a browser if not it can any other environment such as react-native, node.js, etc.


text:
Q: how to take the files from the path given in jtextfield in java GUI I have to create an exe file using java GUI in eclipse. In this tool I have a jButton and a jTextField. In the jTextField I will give the source path where new/updated file is there. I want that when I click the jbutton the files in the path should fetched for further processing. Please help me in doing this.

A: Add an event listener to the JButton
showDialogButton.addActionListener(new ActionListener() {
  public void action(ActionEvent e)
  {
     ProcessFile(textField.getText());
  }

});

You process file function could look something like this
void ProcessFile(string fileName) {

    File folder = new File(fileName);
    File[] listOfFiles = folder.listFiles();

    for (File file : listOfFiles) {
      if (file.isFile()) {
          System.out.println(file.getName());
      }
    }
}

Please provide some examples of what you have tried before posting.


text:
Q: How to read HttpResponseMessege StringContent in react I'm working on an app for a school project. I'm trying to fetch a string in react, the backend has been build with C#. In the backend i'm sending a HttpResponseMessage with StringContent to the client side. But i can't seem to read the StringContent at the client side.
The Api at server side:
[HttpGet("{id}")]
        public async Task<HttpResponseMessage> downloadDocument(int id)
        {
            try
            {
                string base64String = await this.DocumentService.downloadDocument(id);
                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StringContent(base64String);
                return response;
            }
            catch (Exception ex)
            {
                var response = new HttpResponseMessage(HttpStatusCode.ExpectationFailed);
                response.Content = new StringContent(ex.Message);
                return response;
            }
        }

The Client side code
function downloadDocument(param: any) {
        fetch(process.env.REACT_APP_API_URL + 'document/' + param.row.id, {
            method: "GET",
            headers: {
                "Content-Type": "application/json"
            }
        })
        .then((response) => response.json())
        .then((data) => {
            console.log(data);
        })
    }

Where i log data to the console i get the following:

I can see the content object there. but how do i get the string i've added in the HttpResponseMessage with new StringContent(base64String);


text:
Q: Flexbox row layout with ul followed by input I have a layout with an unordered list followed by an input element.  I would like the layout to be one continuous row, where the input would be right after item 5.  It would also determine if the minimum width of the input would allow it to go right after item 5, or if it needs to go on the next line of the row.
I could obviously achieve this by putting the input in the ul, and I could also change the ul to be a bunch of divs, but all of this takes away from the semantics.  How would I achieve what I want with Flexbox?

div {
  display: flex;
  width: 160px;
  flex-wrap: wrap;
}

ul {
  list-style: none;
  display: flex;
  margin: 0;
  padding: 0;
  flex-wrap: wrap;
}

li {
  border: 1px solid gray;
  padding: 2px;
}

input {
  min-width: 40px;
}

Item 1

Item 2

Item 3

Item 4

Item 5

  <input>

A: display: contents; on the ul then flex:1 for the input

div {
  display: flex;
  width: 160px;
  flex-wrap: wrap;
}

ul {
  list-style: none;
  display: contents;
  margin: 0;
  padding: 0;
}

li {
  border: 1px solid gray;
  padding: 2px;
}

input {
  min-width: 40px;
  flex: 1;
}

Item 1

Item 2

Item 3

Item 4

Item 5

  <input>

A: Remove the width and use inline-flex and the container will only be as wide as it needs to be.

div {
  display: inline-flex;
}

ul {
  list-style: none;
  display: flex;
  margin: 0;
  padding: 0;
  flex-wrap: wrap;
}

li {
  border: 1px solid gray;
  padding: 2px;
}

input {
  min-width: 40px;
}

Item 1

Item 2

Item 3

Item 4

Item 5

  <input>

A: I'd use flex-flow: row nowrap; so the items are arranged in a single row but would cause the container to overflow unless you set a max width to each li.

div {
  display: flex;
  width: 160px;
  flex-flow: row nowrap;
}

ul {
  list-style: none;
  display: flex;
  margin: 0;
  padding: 0;
  flex-flow: row nowrap;
}

li {
  border: 1px solid gray;
  padding: 2px;
}

input {
  min-width: 40px;
}

Item 1

Item 2

Item 3

Item 4

Item 5

  <input>


text:
Q: How to measure time in Python? I want to start my program, measure the time when the program starts and then wait some seconds, push a button (K_RIGHT) and messure the time when I push the button. I am using Pygame to registrate the Keydown. But in my code below it does not registrate my Keydown. What I am doing wrong here?
start = time.time()
for e in pygame.event.get():
    if e.type == pygame.KEYDOWN:
        if e.key == pygame.K_RIGHT:
           end= time.time()
           diff = end-start

A: Here's a minimal, complete example that prints the correct time difference. The passed time is just the difference between time.time() (now) and the start time.
You could use pygame.time.get_ticks instead of time.time as well (it returns the time in milliseconds instead of seconds).
import time
import pygame as pg

pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')

start = time.time()

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_RIGHT:
                diff = time.time() - start
                print(diff)

    screen.fill(BG_COLOR)
    pg.display.flip()
    clock.tick(60)

pg.quit()


text:
Q: alert is not cooperating with input I know to do so that you can create user but I do not want php to find out if there is content in the input or not, why should I have done it with jquery,
The problem is that jquery does not come back and tell me what's wrong? and The problem is that it does not come back and show my Alert in some manner whatsoever. or what I lack of add to it.
jQuery
$(function () {
    var $opretbruger = $(".opretbruger"),
        $pwd = $("#pass2"),
        $usr = $("#brugernavn");
        $navn = $("#fornavn");
        $efter = $("#efternavn");
        $tjek = $("#tjek");

    $opretbruger.on("submit", function (event) {
        var msg = "Husk ",
            usr = ($usr.val().trim() !== ""),
            pwd = ($pwd.val().trim() !== "");
            navn = ($navn.val().trim() !== "");
            efter = ($efter.val().trim() !== "");
            tjek = ($tjek.val().trim() !== "");

        msg += !usr ? "brugernavn" : "";
        msg += !usr && !pwd ? " og " : "";
        msg += !pwd ? "kodeord" : "";
        msg += !usr && !pwd && !navn ? " og " : "";
        msg += !navn ? "fornavn" : "";
        msg += !usr && !pwd && !navn && !efter ? " og " : "";
        msg += !efter ? "efternavn" : "";
        msg += !usr && !pwd && !navn && !efter && !tjek ? " og " : "";
        msg += !tjek ? "Jeg godkender brugerbetingelserne!" : "";

        (pwd && usr && navn && efter && tjek) || alert(msg);

        return (pwd && usr && navn && efter && tjek);
    });
});

Html
<form name="opretbruger" action="<?php $_SERVER['PHP_SELF'];?>" method="post" id="opretbruger">

        Brugernavn
        <input type="email" name="email" class="opretbar" id="brugernavn">

        Password
        <input type="password" name="pa2" class="opretbar" id="pass2">

        Fornavn
        <input type="text" name="fornavn" class="opretbar" id="fornavn">

        Efternavn
        <input type="text" name="efternavn" class="opretbar" id="efternavn">

        Betingelserne
        <input type="checkbox" name="tjek" id="tjek"> Jeg godkender brugerbetingelserne

        <input type="submit" name="tilmelddiggratis" value="Opret bruger" class="click opretbruger">

    </form>

Would have liked it to be so certain email and password missing so it must just come forward and tell it that that lack it.

A: The form selector should be $opretbruger = $('form[name="opretbruger"]') because opretbruger is the name of the form not class
var $opretbruger = $('form[name="opretbruger"]')

Demo: Fiddle
Also don't instead of evaluating the validity twice, cache the value like
    var valid = pwd && usr && navn && efter && tjek;
    if (!valid) {
        alert(msg);
    }

    return valid;

Demo: Fiddle

A: I'm trying to figure out what this line is supposed to do:
 (pwd && usr && navn && efter && tjek) || alert(msg);

Did you mean
if (pwd && usr && navn && efter && tjek) alert(msg);

?

A: There's a lot wrong here but you definitely won't be submitting that form anywhere unless you replace:
<form ... action="<?php $_SERVER['PHP_SELF'];?>"

with
<form ... action="<?php print $_SERVER['PHP_SELF']; ?>"

And change this:
var $opretbruger = $(".opretbruger")

to this
var $opretbruger = $("#opretbruger")

And finally make your submit look like this:
$opretbruger.on("submit", function (evt) {
    var e = evt || window.event;
    e.preventDefault();
    ...
    // at the bottom - replace return with:
    $(this).submit();
});

A: Not
var $opretbruger = $(".opretbruger"),

But
var $opretbruger = $("#opretbruger"),

As
<form ...   id="opretbruger">

A: Put the variable declarations inside the event function.  Otherwise it's only grabbing the vars once.  Also don't reuse the variables to hold both string and boolean data.
$opretbruger.on("submit", function (event) {

   var $opretbruger = $(".opretbruger"),
    $pwd = $("#pass2"),
    $usr = $("#brugernavn");
    $navn = $("#fornavn");
    $efter = $("#efternavn");
    $tjek = $("#tjek");

    var msg = "Husk ",
        usr = ($usr.val().trim() !== ""),
        pwd = ($pwd.val().trim() !== "");
        navn = ($navn.val().trim() !== "");
        efter = ($efter.val().trim() !== "");
        tjek = ($tjek.val().trim() !== "");

Style points: use if() instead of short circuits.  Avoid comma.  Makes it confusing to read.

A: Seems to have a typo in the variable declarations. You are using ; instead of ,
var $opretbruger = $(".opretbruger"),
        $pwd = $("#pass2"),
        $usr = $("#brugernavn"),
        $navn = $("#fornavn"),
        $efter = $("#efternavn"),
        $tjek = $("#tjek");

And also:
var msg = "Husk ",
    usr = ($usr.val().trim() !== ""),
    pwd = ($pwd.val().trim() !== ""),
    navn = ($navn.val().trim() !== ""),
    efter = ($efter.val().trim() !== ""),
    tjek = ($tjek.val().trim() !== "");

You should try to use jshint to help you against those kind of issue.


text:
Q: Chart.js zoom instantly zooms in fully on first point no matter what type of zoom used After adding zoom to my line chart no matter what I do it instantly zooms in to the first point without the option to zoom back out (outside of the reset zoom function). The zoom out function also doesnt work, zoom in function results in the same problem.
Normal
After any attempt to zoom
const pdmdata = JSON.parse(document.getElementById('div_pdmdata').dataset.chart);
const ctx = document.getElementById('canvasChart_1').getContext("2d");
const radars = {'hidden': 'hidden'};
let linechartData = {
    datasets: [{
        label: 'Constant',
        data: pdmdata[0],
        borderWidth: 1
    }]
};
for (let i = 0; i < Object.keys(pdmdata[1]).length; i++) {
    linechartData.datasets.push({
        label: radars[Object.keys(pdmdata[1])[i]],
        data: pdmdata[1][Object.keys(pdmdata[1])[i]],
        borderWidth: 1,
        tension: 0.1
    });
}
const config = {
    type: 'line',
    data: linechartData,
    options: {
        maintainAspectRatio: false,
        interaction: {
            mode: 'index',
            intersect: false,
        },
        stacked: false,
        plugins: {
            title: {
                display: true,
                text: 'Mode S'
            },
            zoom: {
                zoom: {
                    drag: {
                        enabled: true,
                        // mode: 'x',
                        threshold: 24
                    },
                    mode: 'x'
                }
            }
        },
        scales: {
            x: {
                reverse: true
            }
        },
        elements: {
            point: {
                radius: 0
            }
        }
    },
};
myChart = new Chart(ctx, config);
function resetZoom(){
    myChart.resetZoom();
}

I've tried all the zoom types; zoom, drag and pan. Even using drag in the middle of the chart makes it end up like the zoomed image above. No errors in console whatsoever. I've also tried setting the speed to 0.001 but to no avail. Weirdest thing is when I make a duplicate of this chart below it that one does zoom as intended. I have no idea why it would though.

A: Okay so I found my issue, chartjs-zoom does not like objects as data without also setting labels yourself. Here's an example: (Only used 1 dataset while testing to make it easier to test)
This works:
    let linechartData = {
        label: ['one', 'two', 'three', 'four', 'five'],
        datasets: [{
            label: 'Constant',
            data: [1, 2, 3, 4, 5],
            borderWidth: 1
        }]
    };

This does not work:
    let linechartData = {
        datasets: [{
            label: 'Constant',
            data: {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5},
            borderWidth: 1
        }]
    };

But this does:
    let linechartData = {
        label: ['one', 'two', 'three', 'four', 'five'],
        datasets: [{
            label: 'Constant',
            data: {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5},
            borderWidth: 1
        }]
    };

So conclusion, when using chartjs-zoom always assign the labels beforehand instead of letting a dataset data object assign them automatically, which works just fine for normal charts without zoom. Never figured out why if I made a 2nd chart with the exact same config that chart did work though.


text:
Q: Understanding Courant min-max theorem and question on achieving the minimum I am trying to understand this theorem better and show simple application of it.
For $A$ symmetric $n \times n$ matrix with Eigenvalues $\lambda_1 \leq \lambda_2 \leq \dots \leq \lambda_n$ then the $k$th largest eigenvalue can be written in the form:
$$\lambda_k = \min_{v_1,\dots,v_{k-1}} \max_{f \perp v_1,\dots,v_{k-1}} \frac{f^TAf}{ff}$$
So, what I am understanding is that if we fix $v_i$ to something specific say the standard basis then we have:
$$\lambda_k = \min_{v_1,\dots,v_{k-1}} \max_{f \perp v_1,\dots,v_{k-1}} \frac{f^TAf}{ff} \leq \max_{f \perp e_1,\dots e_{k-1}} \frac{f^TAf}{ff}$$
My question/ application is that I read that the minimum is achieved when we fix $v_i = u_i$ where $u_i$ are orthonormal eigenvectors of $A$ i.e.
$$\lambda_k = \min_{v_1,\dots,v_{k-1}} \max_{f \perp v_1,\dots,v_{k-1}} \frac{f^TAf}{ff}=\max_{f \perp u_1,\dots u_{k-1}} \frac{f^TAf}{ff}$$
This is not so obvious to me and would really appreciate if someone explains it to me. The source where I got this is https://en.wikipedia.org/wiki/Min-max_theorem more specifically on the proof for compact operators.


text:
Q: Is it possible to express "$x$" in this equation using only "$a$"? I have following equations:
$$\frac{(x-1)}{(a-1)}=\frac{(y-1)}{(b-1)}$$
$$\frac{(y-1)}{(b-1)}=\frac{(z-1)}{(c-1)}$$
$$\frac{1}{x} + \frac{1}{y} + \frac{1}{z} = k$$
$$\frac{1}{a} + \frac{1}{b} + \frac{1}{c} = 1$$
I need to solve by $x$ from this equation where $(x,y,z,a,b,c,k \in \mathbb{R})$, and the best I can get is this:
$$\frac{1}{x} + \frac{1}{\frac{(x - 1) (b - 1)}{a - 1} + 1} +
  \frac{1}{\frac{(x - 1) (c - 1)}{a - 1} + 1} = k$$
which can be transformed to this (by replacing $a$):
$$\frac{1}{x} + \frac{1}{\frac{(x - 1) (b - 1)}{\frac{b*c}{b*c - c - b} - 1} + 1} +
  \frac{1}{\frac{(x - 1) (c - 1)}{\frac{b*c}{b*c - c - b} - 1} + 1} = k$$
Is it possible to somehow remove those $b$ and $c$ and leave only $a$ in equation?

A: You can't. If this were possible, then the value of $x$ would depend only by $a$, independently by the values of $b,c$.
But now, fix any value of $k$, and consider the two cases

*

*$a=2, b=c=4$
your equation becomes
$$\frac{1}{x}+\frac{1}{\frac{3(x-1)}{1}+1}+\frac{1}{\frac{3(x-1)}{1}+1}=k $$
which gives you some solution $x_1$.

*$a=2, b=3, c=6$
your equation becomes
$$\frac{1}{x}+\frac{1}{\frac{2(x-1)}{1}+1}+\frac{1}{\frac{5(x-1)}{1}+1}=k $$
which gives you a different solution $x_2 \neq x_1$.
Thus knowing $a=2$ in both cases cannot give you explicitely the value of $x$.


text:
Q: How to remember the value from the pull down menu of what user selected? I prompt the user to select the date and click enter, but I am having difficulty to display what the user selected. In other words, date menu goes back to the default value. Here is the code:
Select the Starting Date
<select name="startmonth">
        <option value="1"> January </option>
        <option value="2"> February </option>
        <option value="3"> March </option>
        <option value="4"> April </option>
        <option value="5"> May </option>
        <option value="6"> June </option>
        <option value="7"> July </option>
        <option value="8"> August </option>
        <option value="9"> September </option>
        <option value="10"> October </option>
        <option value="11"> November </option>
        <option value="12"> December </option>
</select>
<select name="startyear">
        <option value="2010"> 2010 </option>
        <option value="2011"> 2011 </option>
        <option value="2012"> 2012 </option>
        <option value="2013"> 2013 </option>
        <option value="2014"> 2014 </option>
</select>

<input type = "submit" name="EnteredDate" value = "Enter">

A: Since you're using CGI, observe the following cgi script.  It outputs the two select boxes that you've demonstrated, but will autofill their values upon a submit.
#!/usr/bin/perl

use CGI;

use warnings;
use strict;

my $q = CGI->new;

print $q->header();

print qq{<form method="post">};

print $q->popup_menu(
    -name   => 'startmonth',
    -values => [1..12],
    -labels => {qw(1 January 2 February 3 March 4 April 5 May 6 June 7 July 8 August 9 September 10 October 11 November 12 December)},
);

print $q->popup_menu(
    -name   => 'startyear',
    -values => [2010..2014],
);

print qq{<input type="submit" value="submit" /></form>};

1;

__END__


text:
Q: Cadenas de caracteres - Verificar que una palabra NO se encuentra dentro de una cadena tengo la siguiente consulta... ¿Cómo verifico que una palabra no se encuentra dentro de una cadena de caracteres?. Por ejemplo, para verificar si está puedo hacer esto:
if palabra in cadena:
         print(...)

Ahora, si yo quiero checkear lo contrario, que la palabra no esté en la cadena ¿Cómo sería?.
De antemano muchas gracias!! Saludos.

A: Para chequear que una cadena cualquiera no es parte de otra:
if palabra not in cadena:
    print(...)

Eso no más.


text:
Q: Getting Failure when starting JFR on_vm_start after installing java 11 I have installed java version 11, after installing when I am checking java -version I am getting below error.
C:\Users\lenovo>java -version
Error occurred during initialization of VM
Failure when starting JFR on_vm_start
Please, someone, help on this

A: So let's revive this, because I stumbled on a possible solution:
Depending on the Java version you are coming from you might have to check the vm arguments for the flight recorder. Some time in the past they shifted some options from -XX:FlightRecorderOptions to -XX:StartFlightRecording. But usually the jvm will tell you that.
In my case I also had a spelling error in one of the options, which led to your error message without any further explanation so that might have been your problem, too.
Of course this will be of little help to the SO, but maybe it can be a hint for someone else.


text:
Q: Razorpay payment with promo code What is the way to use promo code concept in Razorpay?
Note 1: Razorpay payment works on client side.
Note 2: Promo code can be applied only once.
Note 3: How to manage two parallel payments with promo code applied? (Accept one payment and stop another payment without deducting amount from bank.)

A: Razor pay deals only with payment
promocode has nothing to do with it
you should start payment only after the promocode logic is executed


text: Q: CRUD use case and <>  I made a use case diagram for store management system. I identified a few CRUD use cases as you can see on diagram. Can I extend CRUD use case, like here: Manage transactions from Manage Suppliers, or just leave it as another use case? Any advice?


text:
Q: $I_n=\int_0^1 \frac{x^n}{\sqrt{1+x^2}}$, find $nI_n$ Let $$I_n=\int_0^1 \frac{x^n}{\sqrt{1+x^2}} dx$$ for $n\in \mathbb{N}$
Find $$\lim_{n\to \infty} nI_n$$
My approach:
Let me explain my observations briefly.
Note that $I_{n-1}-I_n=\int_0^1 \frac{x^{n-1}(1-x)}{\sqrt{1+x^2}} dx \ge 0$
Hence $I_n$ is decreasing.Also $I_n\ge 0$.So, $I_n$ is convergent. Let $\lim_{n\to \infty} I_n =l$
Now $I_n+I_{n-2} =\frac{\sqrt{2}}{n-1} -\frac{2}{n-1} I_n$
(By parts +little bit calculation)
Applying limit to the above equation we get,
$l=0$.
Also from the above equation we have,
$(n-1)I_n+(n-1)I_{n-2}=\sqrt{2}-2I_n$.
If $J_n := nI_n$, then
$\frac{n-1}{n} J_n +\frac{n-1}{n-2} J_{n-2}=\sqrt{2}-2I_n$
Yes I am only now one step away from getting $\lim_{n\to \infty} J_n=\frac{1}{\sqrt{2}}$
But I am unable to prove that $J_n$ is convergent

Any idea??

A: [Write $\frac {nx^{n}} {\sqrt {1+x^{2}}}$ as $ ({nx^{n-1}}) ( \frac x{\sqrt {1+x^{2}}})$]. Integration by parts gives $\int_0^{1}\frac {nx^{n}} {\sqrt {1+x^{2}}} dx=x^{n}\frac x {\sqrt {1+x^{2}}}|_0^{1}-\int_0^{1} x^{n}\frac d {dx} \frac x {\sqrt {1+x^{2}}}dx$. DCT shows that the second term tends to $0$. Hence the limit is $\frac 1 {\sqrt 2}$.


text:
Q: PHP Form in JQuery ColourBox I'm trying to implement popup search window in a PHP project. I included JQuery and ColorBox & have managed to open the Search popup inline (using ColorBox plugin).
This is my code to open popup window
$(document).ready(function(){
    $(".inline").colorbox({inline:true, transition:'none',speed:'10', close:'close', opacity:'0.6'});
});

Popup div has a separate <form> element to POST data.
<?php
if (isset($_POST['btnSearch']))
{
    //Code to search data
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"
    enctype="multipart/form-data">
//Some Page Content

<input type="submit" name="btnSearch" Value="Search"
    class="button">

</form>

The problem is when I click the 'Search' button it POST the form but closes the popup. How can I retain popup window opened even after the button click?

A: AJAX is what you're looking for. jQuery has built in AJAX support which you can read about HERE
It's real easy to use so you shouldn't have any problems implementing it