text:
Q: How to reference array results into Chartjs dataset in Javascript I have managed to get a count of items in list by status, but cant seem to figure out how to add the data into Chart.js. I have tried referencing my dataset from within the chart but that does not seem to work. Any assistance would be greatly appreciated. I have pieced together some code to try to get this to work but cant seem to get this last piece. ps. This code is being used in content editor in SharePoint.
Thank you,

<button onclick="GetListItems();" type="button">Get All List Items</button>

  <canvas id="myChart"></canvas>

A: That should do what's you expect. I cannot test because data ajax call is not public.

<button onclick="GetListItems();" type="button">Get All List Items</button>

    <canvas id="myChart"></canvas>

A: You specify 3 labels and provide 7 element in data.
To resolve your problem, try with a simple config
const config = {
    type: 'bar',
    labels: labels // Your array of label
    data: {
        datasets: [{
          data: [1, 2, 3], // Random data
        }],
    }
};

When that display something, try to add complexity.

By guessing, I believe you want something like that

const config = {
    type: 'bar',
    labels: labels, // Your array of label
    data: {
        datasets: [{
            data: [
                {x:'New', y:1},{x:'Completed', y:10},{x:'Inproccess', y:100},
                {x:'New', y:2},{x:'Completed', y:20},{x:'Inproccess', y:200},
                {x:'New', y:3},{x:'Completed', y:30},{x:'Inproccess', y:300},
             ]
        }]
    }
};

It's hard to help you as you didn't specify what kind of result chart you want to see...

your code working (snippet)

  const labels = ['New', 'Completed', 'Inproccess'];

  const config = {
      type: 'bar',
      labels: labels,
      data: {
          datasets: [{
              label : 'Chart1',
              data: [
                  {x:'New', y:1},{x:'Completed', y:10},{x:'Inproccess', y:100},
                  {x:'New', y:2},{x:'Completed', y:20},{x:'Inproccess', y:200},
                  {x:'New', y:3},{x:'Completed', y:30},{x:'Inproccess', y:300},
              ]
          }]
      }
  };

  const myChart = new Chart(
    document.getElementById('myChart'),
    config
  );

  <canvas id="myChart"></canvas>


text:
Q: Calculate total call duration In React Component using starttime and endtime props I need to display the total time of call, the timelineData has already been getting from the props, I have tried to calculate the same using EndDate-StartDate but this logic does not seem to be correct.
import React from 'react'
import { Timeline, Typography, Col, Row } from 'antd'
import { connect } from 'react-redux'

const { Text } = Typography

export class DispositionTimeline extends React.Component {
  render() {
    return (
      <Row className="dispopage">
        <Col span={24}>
          <Row>
            <Col className="timeLineItem" span={24}>
              <Row color="transparent">
                <Col span={14}></Col>
                <Col
                  style={{
                    paddingLeft: '8px',
                    fontWeight: '500'
                  }}
                  span={5}
                >
                  Start Time
                </Col>
                <Col
                  style={{
                    paddingLeft: '8px',
                    fontWeight: '500'
                  }}
                  span={5}
                >
                  End Time
                </Col>
              </Row>
              <br />
              <Timeline>
                {this.props?.timeLineData?.map((value, index) => {
                  return (
                    <Timeline.Item>
                      <Col
                        className="timelineLabel"
                        span={14}
                        style={{
                          paddingRight: '16px'
                        }}
                      >
                        {value.name}
                      </Col>
                      <Col span={5}>
                        {/* {value.startTime} */}
                        {value.name !== 'End Call' && value.startTime}
                      </Col>
                      <Col span={5}>
                        {value.name === 'End Call' && value.startTime}
                        {value.endTime ? `  ${value.endTime}` : ''}
                      </Col>
                    </Timeline.Item>
                  )
                })}
              </Timeline>
            </Col>
          </Row>

          <Row>
            {this.props?.secondAgent?.anotherAgent === 'Primary Agent' ? (
              <>
                <Col className="timeLineEnd" span={18}>
                  <Text>Total Call Duration</Text>
                </Col>
                <Col className="timeLineEnd timeLineEndRight" span={6}>
                  <Text> {[...this.props?.timeLineData].pop()?.startTime}</Text>
                </Col>
              </>
            ) : (
              ''
            )}
          </Row>
        </Col>
      </Row>
    )
  }
}

export const mapStateToProps = (state, ownProps) => {
  return {
    timeLineData: ownProps?.timeLineData ? ownProps.timeLineData : state.timeLineData?.timeLineData,
    totalDuration: state?.timeLineData?.payload,
    secondAgent: state?.secondAgent?.secondAgent
  }
}

export default connect(mapStateToProps, null)(DispositionTimeline)

The expression {[...this.props?.timeLineData].pop()?.startTime} is only displaying the startTime of Call. but I want to show the total time, I,e difference between end time and start time

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue in FileHandler I'm trying to initialize a FileHandler to write to the given filename, with optional append using the foll syntax:
FileHandler fh = null;
fh = new FileHandler("C:\\Users\\Desktop\\New_folder\\logs\\slate\\TodayLoad-2013-10-24.log",true);

But I'm getting the exception as:
java.io.IOException: Couldn't get lock for  C:\Users\Desktop\New_folder\logs\slate\TodayLoad-2013-10-24.log
    at java.util.logging.FileHandler.openFiles(Unknown Source)
    at java.util.logging.FileHandler.<init>(Unknown Source)
    at TodayLoad.Load.<init>(SlateSheetLoad.java:173)
    at TodayLoad.Load.SlateSheetLoad.main(SlateSheetLoad.java:423)

How can I solve this issue.

A: Probably your file is getting accessed by another process.
See this post that can help you
couldn't get lock for .log file in Java

A: You will find that you get the error after 100 log files have been written. The root cause is a bug in Java. See, for example,
System Property Controls the java.util.logging.FileHandler's MAX_LOCKS Limit
and
Increase java.util.logging.FileHandler MAX_LOCKS limit
These references also suggest a solution: set the system property "jdk.internal.FileHandlerLogging.maxLocks" well before the code that does the logging. For example, by means of
 // Set maxLocks to 200. The default is 100.
 System.setProperty("jdk.internal.FileHandlerLogging.maxLocks", "200");


text:
Q: Rethrowing exception not being caught I have an extension method that runs a Task in the background and I put it in a try-catch block to handle any exception that it throws. The problem is that visual studio always stops on the rethrow portion of my code and I am not sure why.
try {
    task.RunInBackground();
} catch (Exception e) {
    // do something
}

A: You need to await the task like this:
try {
    await task.RunInBackground();
} catch (Exception e) {
    // do something
}

Avoid as much as possible using async void. Remove the async void by replacing it with async Task like below :
public static async Task RunInBackground(this Task task) {
    // ....
}

If you need to know why to avoid async void check this link from msdn.

A: You can do the following:
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
task.RunInBackground().ContinueWith(t =>
{
    throw t.Exception;
},
    CancellationToken.None,
    TaskContinuationOptions.OnlyOnFaulted,
    TaskScheduler.FromCurrentSynchronizationContext()
).ConfigureAwait(false);

This code will not stop for the task, until an exception was thrown by that task.


text:
Q: ASP.NET Core send parameter validation using filters I have controller method which have 2 input parameters : DateTime dFrom, dtTo.
So, now I check interval like this:
public async Task<ActionResult> GetValues([FromQuery] DateTime dtFrom, [FromQuery] DateTime dtTo)
{
    if (dtFrom > dtTo)
    {
        return BadRequest($"{nameof(dtFrom)} < {nameof(dtTo)}");
    }
}

But, I want to make validation like this:
[DateFilterAttribute(dtFrom,dtTo)]
public async Task<ActionResult> GetValues([FromQuery] DateTime dtFrom, [FromQuery] DateTime dtTo)
{
    if (dtFrom > dtTo)
    {
        return BadRequest($"{nameof(dtFrom)} < {nameof(dtTo)}");
    }
}

Where DateFilterAttribute:
 public class DateFilterAttribute : ActionFilterAttribute
 {
    private DateTime _fromDt;
    private DateTime _dtTo;
    public DateFilterAttribute(DateTime fromDt, DateTime dtTo)
    {
        _fromDt = fromDt;
        _dtTo = dtTo;
    }

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        context.HttpContext.Response.StatusCode = 400;
        var errorStr = $"{nameof(_fromDt)} < {nameof(_dtTo)}";
        context.HttpContext.Response.Headers.Add("Error", new string[] { errorStr });
    }
  }

But, I can not use input parameters at attribute.
So, can I do this? And is it right way?

A: For parameters passed in query string you can use the HttpContext.Request.Query directly and so you don't need to pass anything to your DateFilterAttribute constructor:
public class DateFilterAttribute : ActionFilterAttribute
{
    private DateTime _fromDt;
    private DateTime _dtTo;

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        _fromDt = Convert.ToDateTime(context.HttpContext.Request.Query["dtFrom"]);
        _dtTo = Convert.ToDateTime(context.HttpContext.Request.Query["dtTo"]);

        context.HttpContext.Response.StatusCode = 400;
        var errorStr = $"{nameof(_fromDt)} < {nameof(_dtTo)}";
        context.HttpContext.Response.Headers.Add("Error", new string[] { errorStr });
    }
}

Now your GetValues shoud looks like this:
[DateFilterAttribute]
public async Task<ActionResult> GetValues([FromQuery] DateTime dtFrom,
                                          [FromQuery] DateTime dtTo)
{
    //The rest of the code
}

A: We can use the ActionArguments property, which has entries for each parameter used in our action.
public class DateRangeAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var fromKey = "fromDate";
        var toKey = "toDate";

        if (!context.ActionArguments.ContainsKey(fromKey) ||
            !context.ActionArguments.ContainsKey(toKey))
        {
            context.Result = new BadRequestResult();
            return;
        }

        if (!(context.ActionArguments[fromKey] is DateTime fromDate))
        {
            context.Result = new BadRequestResult();
            return;
        }

        if (!(context.ActionArguments[toKey] is DateTime toDate))
        {
            context.Result = new BadRequestResult();
            return;
        }

        if (fromDate > toDate)
        {
            context.Result = new BadRequestObjectResult(new
            {
                Error = "Bad date range"
            });
            return;
        }

        base.OnActionExecuting(context);
    }
}

In our action
[DateRangeAttribute]
public IActionResult Index(DateTime fromDate, DateTime toDate)
{
    return View();
}


text:
Q: Parameter index out of range (0 < 1 ) I've been trying figuring this out
ps.setString(1,fname);
ps.setString(2,lname);
ps.setString(3,uname);
ps.setString(4,pass);
ps.setString(5,gender);
ps.setString(6, phone);
ps.setString(7,brdate);
ps.setString(8,address );

it would send another message at the bottom:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''java_login_register'('fname', 'lname', 'uname', 'pass','gender','phono','bdate'' at line 1

connection to the database or localhost
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/uinterface_?serverTimezone=UTC","root","");
            ps = con.prepareStatement("INSERT INTO 'login_register'('fname', 'lname', 'uname', 'pass','gender','phono','bdate','address') VALUES (?,?,?,?,?,?,?,?)");


text:
Q: Benefit to keeping a record in the database, rather than deleting it, for performance issues? So I have a client that I am building a Rails app for....I am using PostgreSQL.
He made this comment about preferring to hide records, rather than delete them, and given that this is the first time I have heard about this I figured I would ask you guys to hear your thoughts.

I'd rather hide than delete because deletions in tables eventually lead to table index havoc that causes queries to take longer than expected (much worse than Inserts or Updates).  This won't be a problem in the beginning of the site (it gets exponentially worse over time), but seems like an easy issue to never encounter by just not deleting anything (yet) as part of the "everyday" web application functionality.  We can always handle deletions much later as part of a Data Optimization & Maintenance process and re-index tables in that process on some (yet to be determined) scheduled basis.

In all the Rails apps I have built, I have never had an issue with records being deleted and it affecting the index.
Am I missing something? Is this a problem that used to exist, but modern RDBMS products have fixed it?

A: Other reasons for not deleting the records.

*

*you don't have to worry about cascading a delete through various other tables in the database that reference the row you are deleting

*Every bit of data is useful. Debugging and auditing becomes easy.

*Easier to rollback if needed.

A: There may be functional reasons for preferring that records not be deleted, but reasons relating to some form of table index "havoc" are almost certainly bogus unless supported by some technical evidence.
You hear this sort of thing quite often in the Oracle world -- that indexes do not re-use space freed up by deletions. It's usually based on some misinterpretation of the facts (eg. that index blocks are not freed for re-use until they are completely empty). Hence you end up with people giving advice to periodically rebuild indexes. If you give these issues some thought, you wonder why the RDBMS developers would not have fixed such an issue, given that it supposedly harms the system performance.
So there may be some piece of Postgres-related, possibly obsolete, information on which this is based, but the onus is really on the person objecting to a perfectly normal type of database operation to come with evidence to support their position.
Another thought: I believe that in Postgres an update is implemented as a delete and insert, hence the advice to vacuum frequently on heavily updated tables. Based on that, updates should also cause the same index problems that are supposed to be associated with deletes.

A: Create an deleted column in your table and dont index that one.
If you update that record with deleted = 1 or deleted = o only the data needs to be rewriten,  the index doesnt have to be updated that saves lots off IO reads and IO writes
This advies goes for all modern RDBMS when they make use of B tree indexes. B tree is an very good algorithm for searching but not for updating and deleting because off high number off IO reads and IO writes thats needed to insert or update node in the node or delete notes from the tree this is also the reason why you should not "over index" your table
"Delete" an record like this
UPDATE table SET deleted = 1 WHERE id = 1 -- if deleted not is indexed assuming id is index as an primary key this also should be fast

Check if an record is deleted
SELECT * FROM table WHERE id = 1 and deleted = 1 -- assuming id is index as an primary key this also should be fast

Check if an record not is deleted
SELECT * FROM table WHERE id = 1 and deleted = 0 -- assuming id is index as an primary key this also should be fast


text:
Q: Show JQuery JDialog after 5 seconds and autoclose How to open the JQuery JDialog window if response take more than 5 seconds.
Below is my code
$("#Dialog").dialog(
       {
           autoOpen: false,
           modal: true,
           height: 175,
           position: 'center',
           bgiframe: true,
           display: 'visible',
           width: 400
       });

I want to show the above dialog if response time (AJAX) takes more than 5 seconds and auto close once i get the response (AJAX).
Any help would be helpful.
Thanks

A: You can use setTimeout() to start a timer that will open your dialog after 5 seconds. This method returns a reference to the timer that it creates. Do that in the "beforeSend" callback, which is executed before the request starts.
In the complete callback (or the success + error callback), clear the timer with clearTimeout() and close the dialog.
var timer;

$.ajax({
    ...
    beforeSend: function() {
        timer = setTimeout(function() {
            $("#Dialog").dialog('open');
        }, 5000);
    },
    complete: function() {
        clearTimeout(timer);
        $("#Dialog").dialog('close');
    }
});


text:
Q: Search form in Google App Engine with Mako Template The script is in data.py and template file is search.mako. The search form is in MainPage method (not included in the code below). I enter the search term but nothing happens. Can you help understand what I am doing wrong? Thank you.
class Pet(db.Model):
    name = db.StringProperty()

class Search(webapp.RequestHandler):
    def post(self):
        query = Pet.all()
        results = self.request.get('searchquery')
        q = query.filter('name =', 'results')

        template_values = {'q': q,}

        path = os.path.join(os.path.dirname(__file__), 'search.mako')
        templ = Template(filename=path)
        self.response.out.write(templ.render(**template_values))

And this is the search.mako
<html>
<body>

% for cat in q:
  <p>${cat.name}</p>
% endfor

</html>
</body>

A: Adding fetch() fixed the problem:
class Search(webapp.RequestHandler):
    def post(self):
        query = Pet.all()
        q = query.filter('name =', self.request.get('searchquery')).fetch(10)


text:
Q: Ruby on Rails Model.find generates a MySQL error I have Product model and it has many categories with a has_many :through association
In my controller I am trying to do a find by with categories.category but it comes up with a mysql error.
Model.find(:all, :conditions => ['categories.category_id = ?', @category.id ])

Ideas?

A: If you're doing you're find on the Product model, you're either going to need to remove the categories. part of your :conditions statement, or add a :joins => :categroies to your finder.
Some more help would certainly narrow down the problem, however.


text:
Q: Retrieving custom fields with $wpdb->get_results I'm trying to use $wpdb->get_results to retrieve an array of all posts including custom fields. I can retrieve the meta_key and meta_value columns like this:
[meta_key] => state [meta_value] => california

but I'm trying to list them in the object like this:
[meta_key] => meta_value [state] => california [city] => san francisco

The Query:
global $wpdb;
$query = "
SELECT ID, post_date, post_title, post_content, guid, meta_key, meta_value
FROM wp_posts INNER JOIN wp_postmeta
ON (wp_posts.ID = wp_postmeta.post_id)
";

$results = $wpdb->get_results($query);

foreach($results as $result) {
    print_r($result);
}

Is it possible to use an alias and/or subquery to achieve this?
SELECT ID, post_date, post_title, post_content, guid, meta_value AS (subquery here??)

A: Note, before going further: Take care about portability and security:
function wpse50056_get_post_meta()
{
    global $wpdb;

    $results = $wpdb->get_results( "
        SELECT
            ID,
            post_date,
            post_title,
            post_content,
            meta_key,
            meta_value
        FROM {$wpdb->posts}
            INNER JOIN {$wpdb->postmeta}
        ON ( $wpdb->posts.ID = {$wpdb->postmeta}.post_id )
    " );

    foreach( $results as $result )
    {
        printf( '
%s
', htmlspecialchars( var_export( $result, true ) ) );
    }
}
add_action( 'shutdown', 'wpse50056_get_post_meta' );

A: Just for clarity, to not get the extra quotes that benhass was talking about (i still get them with the code provided by kaiser and WP 3.7.1), don't use the prepare method at all (ok in this case, as we only use parameters provided by the $wpdb object itself):
function wpse50056_get_post_meta() {
    global $wpdb;

    $query =
    "   SELECT
            ID,
            post_date,
            post_title,
            post_content,
            meta_key,
            meta_value
        FROM $wpdb->posts
            INNER JOIN $wpdb->postmeta
        ON (  $wpdb->posts.ID = $wpdb->postmeta.post_id)
    ";

    $results = $wpdb->get_results( $query );

    foreach( $results as $result ) {
        echo '
'; print_r( $result ); echo '
';
    }
}
add_action( 'shutdown', 'wpse50056_get_post_meta' );

But of course, REMEMBER, as soon as you use other parameters in the query, the use of $wpdb->prepare is recommended to prevent SQL injection.


text:
Q: "tilde" glyph is copied incorrectly from LM-fonts Copy the text from resulting pdf and paste it somewhere:
\font\tentt=rm-lmtt10 \tentt
a\char'176 b
\font\tentt=cmtt10 \tentt
c\char'176 d
\bye

For me (TeX Live 2015) the first tilde is inserted with a shift forward.
Why the tilde is copied incorrectly from LM-fonts? Is it a bug?

A: A PFB file can (and usually does) contain a CMap resource that's used for establishing a mapping from glyphs in the PDF file to Unicode; when one selects a glyph in the PDF file and does a "copy", the code point provided by the mapping is stored for later choosing what character to paste.
The CMap resource in cmtt10.pfb maps the glyph resulting from the character is slot 0x7E (octal 176) to U+007E (I don't know if it actually has such a resource, but it's not really important).
The resource in lmtt10.pfb maps the same glyph to U+0303 (COMBINING TILDE) which may be regarded as a more sensible choice, looking at plain.tex that defines
\def\~#1{{\accent"7E #1}}

So it's not a bug, but a designer's choice.
Can one change this from the TeX side? Maybe, by replacing the CMap resource at font loading time (see https://tex.stackexchange.com/a/22551/4427 for an example).


text:
Q: Does Wordpress support opening multiple post through the 'Quick Edit' link? There is a needed feature where clicking one post using the 'Quick Edit' should not 'force close' other posts already opened. But I think, there is no possible way to do this at the moment because the inlineEditPost object only accepts an 'id' parameter. I came to this conclusion for I have done a custom hook recently - that shows the fields of a custom post in the 'Quick Edit' area.
How can I support this claim? I have no strong reference/documentation to present for this?


text:
Q: Can a PWA published as an Android app (using bubblewrap) track geolocation when phone screen is closed? I'm creating a TWA using bubblewrap out of my PWA. While the app is open, we need to track the users location to notify them when they're near the destination.
Can a PWA wrapped as a TWA, downloaded from Google Play, can still run when the phone screen is off?

A: Short answer is that it's not currently possible.
PWAs wrapped inside a Trusted Web Activity can use any Web Platform APIs available, but don't have access to platform-specific APIs. That said, there isn't a web platform APIs that would allow to tracking the user's location in the background at the moment.


text:
Q: Regex replace only inside a pattern I want to replace all dashes that are inside square brackets but leave the ones that aren't.
String: dont-change-this[only-change-inside-brackets]
Result: dont-change-this[only_change_inside_brackets]
The way I'm currently doing it is by capturing everything in the square brackets and then replacing.
regex = /(\[([a-z-]+)\])/
testString = "dont-change-this[only-change-inside-brackets]"

testString.match regex
testString.sub(regex, $1.gsub(/-/, '_'))

It works, but I was wondering if there is a way to do this in just one expression.

A: You can use sub (or gsub) with a block:
my_string.sub(/\[.*?\]/){|x|x.tr('-','_')}

A: Its a suggestion and i dont think its an ideal way, but you can actually split the sentence and then match the second element of the array returned.
2.0.0p247 :079 > str = "dont-change-this[only-change-inside-brackets]"
=> "dont-change-this[only-change-inside-brackets]"
2.0.0p247 :080 > s = str.split("[")
=> ["dont-change-this", "only-change-inside-brackets]"]
2.0.0p247 :081 > s[1].gsub(/-/, '_')
=> "only_change_inside_brackets]"


text:
Q: Impact of sticky service in an application with huge monolith code base in Android? As we all know,Java memory model consists of data (or code), stack and heap segments. I presume that the same is the case with Android. I have a single monolith application (let's consider the code base of this application to be too huge). When I start the application the activities and fragments within the application gets loaded into Dalvik JVM and offloaded. When this is the case, how this works with Service? Let's say I have a STICKY_SERVICE like,
public class CountingNumberService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        for(int i=0; i<100; i++) {
            //Do something
        }
        return Service.START_STICKY;
    }
    @Override
    public IBinder onBind(Intent intent) {
        /**
         * This has to do with some inter process communication
         */
        return null;
    }
}

Since the service is STICKY it makes the process behave like a persistent process and it is always running. Now consider I stopped using my application and as a user I believed that application is closed (I'm closing it or clearing it from recents) but since my service is STICKY it would always be running and I assume I would have the following impact,

*

*I would eat user's battery.

*Some additional code (other than service) will be running along with the application (?)  not sure though. If it's the entire application sitting within data segment then it will not allow other application to run smoothly.

I'm kinda confused on STICKY service on a process (a huge monolith code) and it's impact. Can someone clarify me on this please?

A:
Since the service is STICKY it makes the process behave like a persistent process and it is always running.

No, it does not.

but since my service is STICKY it would always be running

No, it will not.
Quoting the documentation for START_STICKY:

if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service.

Android is still welcome to terminate your process as it sees fit. All START_STICKY does is encourage Android to restart your service (forking a fresh process along the way) when conditions allow.


text:
Q: Concatenating Strings, based on Case Statement I need to append notes onto a daily report where notes are stored in a different table based on the values.
i.e. The notes are stored in a notes table, on multiple records, a LineNo Column with values 1,2,3 etc. based on the Number of Records in the Notes. The number of notes line is variable
I want to Select the Notes and Concatenate these 3 fields together in the output as a single column;
i.e.:
Select (Concat Notes Line1, Notes Line2 Notes Line3),
       UserName,
       NotesDate
From   notes
Where  NoteType=2
and    RefNo in (SELECT RefNo from Report);

I've looked at various solutions using Case and Concat but none seem to work. There is already a Join in the stored procedure to create the report.

A: The following should work:
Select Line1 || Line2 || Line3,
       UserName,
       NotesDate
From   notes
Where  NoteType=2
and    RefNo in (SELECT RefNo from Report)
If you insist on using the concat command (which is functionally equal to ||), the following would work:
Select concat(concat(Line1,Line2),Line3),
       UserName,
       NotesDate
From   notes
Where  NoteType=2
and    RefNo in (SELECT RefNo from Report)
The concat() command in DB2 can only handle two arguments, which is why a nested concat() is needed.


text:
Q: Idiomatic way to do list/dict in Cython? My problem: I've found that processing large data sets with raw C++ using the STL map and vector can often be considerably faster (and with lower memory footprint) than using Cython.
I figure that part of this speed penalty is due to using Python lists and dicts, and that there might be some tricks to use less encumbered data structures in Cython. For example, this page (http://wiki.cython.org/tutorials/numpy) shows how to make numpy arrays very fast in Cython by predefining the size and types of the ND array.
Question: Is there any way to do something similar with lists/dicts, e.g. by stating roughly how many elements or (key,value) pairs you expect to have in them? That is, is there an idiomatic way to convert lists/dicts to (fast) data structures in Cython?
If not I guess I'll just have to write it in C++ and wrap in a Cython import.

A: C++ is fast not just because of the static declarations of the vector and the elements that go into it, but crucially because using templates/generics one specifies that the vector will only contain elements of a certain type, e.g. vector with tuples of three elements. Cython can't do this last thing and it sounds nontrivial -- it would have to be enforced at compile time, somehow (typechecking at runtime is what Python already does). So right now when you pop something off a list in Cython there is no way of knowing in advance what type it is , and putting it in a typed variable only adds a typecheck, not speed. This means that there is no way of bypassing the Python interpreter in this regard, and it seems to me it's the most crucial shortcoming of Cython for non-numerical tasks.
The manual way of solving this is to subclass the python list/dict (or perhaps std::vector) with a cdef class for a specific type of element or key-value combination. This would amount to the same thing as the code that templates are generating. As long as you use the resulting class in Cython code it should provide an improvement.
Using databases or arrays just solves a different problem, because this is about putting arbitrary objects (but with a specific type, and preferably a cdef class) in containers.
And std::map shouldn't be compared to dict; std::map maintains keys in sorted order because it is a balanced tree, dict solves a different problem. A better comparison would be dict and Google's hashtable.

A: Cython now has template support, and comes with declarations for some of the STL containers.
See http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html#standard-library
Here's the example they give:
from libcpp.vector cimport vector

cdef vector[int] vect
cdef int i
for i in range(10):
    vect.push_back(i)
for i in range(10):
    print vect[i]

A: Doing similar operations in Python as in C++ can often be slower. list and dict are actually implemented very well, but you gain a lot of overhead using Python objects, which are more abstract than C++ objects and require a lot more lookup at runtime.
Incidentally, std::vector is implemented in a pretty similar way to list. std::map, though, is actually implemented in a way that many operations are slower than dict as its size gets large. For suitably large examples of each, dict overcomes the constant factor by which it's slower than std::map and will actually do operations like lookup, insertion, etc. faster.
If you want to use std::map and std::vector, nothing is stopping you. You'll have to wrap them yourself if you want to expose them to Python. Do not be shocked if this wrapping consumes all or much of the time you were hoping to save. I am not aware of any tools that make this automatic for you.
There are C API calls for controlling the creation of objects with some detail. You can say "Make a list with at least this many elements", but this doesn't improve the overall complexity of your list creation-and-filling operation. It certainly doesn't change much later as you try to change your list.
My general advice is

*

*If you want a fixed-size array (you talk about specifying the size of a list), you may actually want something like a numpy array.

*I doubt you are going to get any speedup you want out of using std::vector over list for a general replacement in your code. If you want to use it behind the scenes, it may give you a satisfying size and space improvement (I of course don't know without measuring, nor do you. ;) ).

*dict actually does its job really well. I definitely wouldn't try introducing a new general-purpose type for use in Python based on std::map, which has worse algorithmic complexity in time for many important operations and—in at least some implementations—leaves some optimisations to the user that dict already has.
If I did want something that worked a little more like std::map, I'd probably use a database. This is generally what I do if stuff I want to store in a dict (or for that matter, stuff I store in a list) gets too big for me to feel comfortable storing in memory. Python has sqlite3 in the stdlib and drivers for all other major databases available.

A: You can take a look at the standard array module for Python if this is appropriate for your Cython setting. I'm not sure since I have never used Cython.

A: There is no way to get native Python lists/dicts up to the speed of a C++ map/vector or even anywhere close. It has nothing to do with allocation or type declaration but rather paying the interpreter overhead. The example you mention (numpy) is a C extension and is written in C for precisely this reason.

A: Just because it was not mentioned here: You can easily wrap for example a C++ vector in a custom extension type.
from libcpp.vector cimport vector

cdef class pyvector:
    """Extension type wrapping a vector"""
    cdef vector[long] _data

    cpdef void push_back(self, long x):
        self._data.push_back(x)

    @property
    def data(self):
        return self._data

In this way, you can store your data in a vector allowing fast Cython operations while still being able to access the data (with some overhead) from the Python side.


text:
Q: Navigation div not visible over flexslider Navigation div is not visible over flexslider div althought I have set greater z-index.
Pls help.
I isolated issue here:

/*! CSS Used from: http://localhost:59746/Content/css/normalize.css */
div,span,h2,a,img,strong,ul,li,input,select{margin:0;padding:0;border:0;outline:0;vertical-align:baseline;}
ul,li{list-style:none;}
a{text-decoration:none;}
a:hover{text-decoration:none;}
strong{font-weight:bold;}
img{height:auto;}
input:focus,select:focus{outline:none;}
input[type="text"],input[type="password"]{-webkit-appearance:none;}
.clearfix:after{visibility:hidden;display:block;font-size:0;content:" ";clear:both;height:0;}
.clearfix{display:inline-block;}
.clearfix{display:block;}
/*! CSS Used from: http://localhost:59746/Content/images/content_images.sprite.css */
.content_images{background-image:url(http://localhost:59746/Content/images/content_images.sprite.png);background-repeat:no-repeat;display:inline-block;}
.content_images.card-number-img{width:30px;height:31px;background-position:-10px -97px;}
/*! CSS Used from: http://localhost:59746/Content/css/global.css */
h2{color:#0e1714;}
h2{font-size:3em;font-weight:normal;line-height:112%;margin-bottom:11px;}
a{color:#FF6B03;}
a:hover{text-decoration:none;}
input[type="text"],input[type="password"]{font-size:1.3em;color:#565656;}
input[type="text"]{border:1px solid #f0f0f0;padding:11px 10px;box-shadow:0px 2px 3px 1px #dadada inset;-moz-box-shadow:0px 2px 3px 1px #dadada inset;-webkit-box-shadow:0px 2px 3px 1px #dadada inset;}
input[type="password"]{border:1px solid #f0f0f0;padding:11px 10px;box-shadow:0px 2px 3px 1px #dadada inset;-moz-box-shadow:0px 2px 3px 1px #dadada inset;-webkit-box-shadow:0px 2px 3px 1px #dadada inset;}
.btn{color:#fff;background:#ff6b03;font-weight:bold;font-size:1.5em;padding:4px 14px;box-shadow:1px 1px 1px 0 #8A8A8A;-moz-box-shadow:1px 1px 1px 0 #8A8A8A;-webkit-box-shadow:1px 1px 1px 0 #8A8A8A;}
.page{width:100%;max-width:1160px;margin:0 auto;position:relative;}
.text-color{color:#fc2222;}
.card-number{position:absolute;top:14px;right:4px;width:30px;height:31px;color:#000;font-size:1.4em;font-weight:bold;padding-top:5px;}
.products-worth .card-number,.worth-headding,.products-worth .sort-by{float:left;}
.worth-headding{display:inline-block;}
.order-bg{box-shadow:0px 11px 5px -3px #e0e0e0;-moz-box-shadow:0px 11px 5px -3px #e0e0e0;-webkit-box-shadow:0px 11px 5px -3px #e0e0e0;}
.products-worth{-webkit-transform:translateZ(0);}
.products-worth{padding:24px 7px 10px;}
.worth-headding{font-size:1.3em;margin-left:41px;margin-right:2px;padding-top:5px;}
.products-worth .card-number{height:25px;left:14px;margin-right:5px;text-align:center;top:25px;}
.order-bg{background:url(http://localhost:59746/Content/images/total-bg.jpg) repeat-x top;width:100%;}
.box-content .products-worth{margin-bottom:20px;}
.products-worth .sort-by{margin-right:7px;}
.box-content{width:100%;background:#fff;}
.box-content .worth-headding{margin-right:30px;}
.box-content .flexslider .slides > li{width:92px!important;height:92px;padding:0 26px;}
.box-content .card-number{top:23px;left:437px;}
.flex-viewport{z-index:9;}
.box-content .flex-direction-nav{display:block;}
.order-bg ul{padding-left:298px;}
.order-bg li{float:left;padding:18px 28px 18px 15px;border-left:1px solid #e5e6e6;border-right:1px solid #e5e6e6;}
.order-bg li img,.order-bg li a{float:left;}
.order-bg li img{margin:0 10px;}
.order-bg li a{font-size:1.4em;padding:9px 0 0 0;font-weight:bold;}
.slider-menu{display:none;box-shadow:1px 1px 5px 0px #ccc;-moz-box-shadow:1px 1px 5px 0px #ccc;-webkit-box-shadow:1px 1px 5px 0px #ccc;position:absolute;top:57px;background:#fff;left:22px;}
.slider-menu li{padding:10px 20px;border-bottom:1px solid #dbdbdb;text-align:center;}
.slider-menu li a{font-size:1.4em;line-height:131%;}
.slider-menu li:hover a{color:#fff;}
.slider-menu li:hover{background:#ff6b03;}
.box-content .flexslider .slides > li:hover{position:relative;}
.slider-menu-content{background:#FFFFFF;display:block;position:absolute;top:54px;width:200px;z-index:9999;box-shadow:1px 1px 5px 0px #ccc;-moz-box-shadow:1px 1px 5px 0px #ccc;-webkit-box-shadow:1px 1px 5px 0px #ccc;}
.slider-menu-content li{padding:10px;border-bottom:1px solid #dbdbdb;text-align:left;}
.slider-menu-content li a{font-size:1.4em;line-height:131%;display:block;}
.slider-menu-content-product-title{color:Gray;}
.slider-menu-content li:hover a{color:#fff;}
.slider-menu-content li:hover{background:#ff6b03;}
.img_price_notif{float:right;margin-right:10px!important;z-index:999;position:absolute;width:16px!important;}
@media only screen and (max-width: 920px){
.order-bg li{width:190px;}
.order-bg li img{display:none;}
}
@media only screen and (max-width: 1073px){
.sort-by{margin-right:50px;}
}
/*! CSS Used from: http://localhost:59746/Content/css/style.css */
#carousel .flex-viewport{margin-bottom:-10px;}
.box-content #carousel li{font-size:1.3em;text-align:center;}
.price-Choose h2{font-size:1.4em;font-weight:bold;letter-spacing:-1px;}
.price-Choose h2{border-bottom:1px solid #dbdbdb;padding-bottom:17px;}
.enter-email{font-size:1.3em;line-height:173%;}
.enter-email .btn{float:right;font-size:115%;}
.email-descp{color:#616161;font-size:102%;font-style:italic;line-height:71%;margin-top:25px;}
.sort-by strong{padding-top:3px;font-size:1.3em;float:left;}
.sort-by{float:right;clear:both;}
.sort-by strong{padding-left:40px;}
.sort-by select{border:1px solid;margin-top:-6px;padding:5px 7px;width:150px;}
.close span{font-size:131%;}
.close span{color:#0e1714;}
.close span{padding-right:10px;display:inline-block;}
.close{float:right;width:80px;cursor:pointer;}
.close-btn{background-position:-2px -178px!important;width:20px;height:21px;display:block;float:right;margin-top:-4px;}
.close-btn.add{padding-right:6px;}
.flex-direction-nav{display:none;}
.sbHolder{border:1px solid #dadada;float:right;font-family:sans-serif;font-size:12px;font-weight:normal;height:27px;margin-top:-4px;position:relative;width:155px;}
.sbSelector{display:block;height:30px;left:0;line-height:30px;outline:none;overflow:hidden;position:absolute;text-indent:10px;top:0;width:183px;}
.sbSelector:link,.sbSelector:visited,.sbSelector:hover{color:#0e1714;outline:none;text-decoration:none;font-size:114%;}
.sbToggle{background:url(http://localhost:59746/Content/images/select-icons.png) 0 -119px no-repeat;display:block;height:30px;outline:none;position:absolute;right:0;top:0;width:30px;}
.sbToggle:hover{background:url(http://localhost:59746/Content/images/select-icons.png) -120px no-repeat;}
.sbToggleOpen{background:url(http://localhost:59746/Content/images/select-icons.png) 0 -19px no-repeat;}
.sbToggleOpen:hover{background:url(http://localhost:59746/Content/images/select-icons.png) 0 -69px no-repeat;}
.sbOptions{background:#fff;border:solid 1px #dadada;list-style:none;left:-1px;margin:0;padding:0;position:absolute;top:30px;width:185px;z-index:999;overflow-y:auto;}
.sbOptions li{padding:0 7px;}
.sbOptions a{border-bottom:solid 1px #dcdcdc;display:block;outline:none;padding:7px 0 7px 3px;}
.sbOptions a:link,.sbOptions a:visited{color:#0e1714;text-decoration:none;}
.sbOptions a:hover,.sbOptions a:focus,.sbOptions a.sbFocus{color:#FF6B03;}
.close-btn{background:url(http://localhost:59746/Content/images/sprite-2.png) left top no-repeat;}
.product-title{color:rgb(14,23,20);font-size:1.3em;font-weight:bold;float:left;margin-top:3px;margin-bottom:20px;}
.form-head{overflow:hidden;display:block;}
#carousel li{width:auto!important;}
.fl{float:left;}
.fr{float:right;}
.flexslider .slides li{backface-visibility:hidden;}
/*! CSS Used from: http://localhost:59746/Content/js/flexslider_2_6_1/flexslider.css */
.slides,.slides > li,.flex-direction-nav{margin:0;padding:0;list-style:none;}
.flexslider{margin:0;padding:0;}
.flexslider .slides > li{display:none;-webkit-backface-visibility:hidden;}
.flexslider .slides img{width:100%;display:block;}
.flexslider .slides:after{content:"\0020";display:block;clear:both;visibility:hidden;line-height:0;height:0;}
html[xmlns] .flexslider .slides{display:block;}
.flexslider{margin:0 0 60px;background:#fff;border:4px solid #fff;position:relative;zoom:1;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:'' 0 1px 4px rgba(0, 0, 0, 0.2);-moz-box-shadow:'' 0 1px 4px rgba(0, 0, 0, 0.2);-o-box-shadow:'' 0 1px 4px rgba(0, 0, 0, 0.2);box-shadow:'' 0 1px 4px rgba(0, 0, 0, 0.2);}
.flexslider .slides{zoom:1;}
.flexslider .slides img{height:auto;-moz-user-select:none;}
.flex-viewport{max-height:2000px;-webkit-transition:all 1s ease;-moz-transition:all 1s ease;-ms-transition:all 1s ease;-o-transition:all 1s ease;transition:all 1s ease;}
.flex-direction-nav{*height:0;}
.flex-direction-nav a{text-decoration:none;display:block;width:40px;height:40px;margin:-20px 0 0;position:absolute;top:50%;z-index:10;overflow:hidden;opacity:0;cursor:pointer;color:rgba(0, 0, 0, 0.8);text-shadow:1px 1px 0 rgba(255, 255, 255, 0.3);-webkit-transition:all 0.3s ease-in-out;-moz-transition:all 0.3s ease-in-out;-ms-transition:all 0.3s ease-in-out;-o-transition:all 0.3s ease-in-out;transition:all 0.3s ease-in-out;}
.flex-direction-nav a:before{font-family:"flexslider-icon";font-size:40px;display:inline-block;content:'\f001';color:rgba(0, 0, 0, 0.8);text-shadow:1px 1px 0 rgba(255, 255, 255, 0.3);}
.flex-direction-nav a.flex-next:before{content:'\f002';}
.flex-direction-nav .flex-prev{left:-50px;}
.flex-direction-nav .flex-next{right:-50px;text-align:right;}
.flexslider:hover .flex-direction-nav .flex-prev{opacity:0.7;left:10px;}
.flexslider:hover .flex-direction-nav .flex-prev:hover{opacity:1;}
.flexslider:hover .flex-direction-nav .flex-next{opacity:0.7;right:10px;}
.flexslider:hover .flex-direction-nav .flex-next:hover{opacity:1;}
@media screen and (max-width: 860px){
.flex-direction-nav .flex-prev{opacity:1;left:10px;}
.flex-direction-nav .flex-next{opacity:1;right:10px;}
}
/*! CSS Used from: http://localhost:59746/Content/css/responsive.css */
@media only screen and (min-width: 768px) and (max-width: 1160px){
.content_images.card-number-img{width:26px;height:18px;background-position:-11px -97px;}
.card-number{top:17px;right:-13px;}
.order-bg ul{padding-left:0;}
.order-bg li{width:33%;text-align:center;padding:18px 0px 18px 0px;}
.order-bg li a{float:none;display:inline-block;padding:0;}
.order-bg li img{float:none;vertical-align:middle;display:inline-block;}
.fl{width:42%;}
.fl:nth-child(2){margin-left:2%!important;}
}
@media only screen and (min-width: 320px) and (max-width: 767px){
.card-number{top:-2px;right:-8px;font-size:1.2em;}
.order-bg{background-size:contain;}
.order-bg li{min-height:66px;padding:18px 0px 18px 0px;width:32.6%;text-align:center;}
.order-bg li img{display:block;float:none;margin:0 auto;}
.order-bg li a{float:none;display:block;font-size:1.2em;}
.order-bg ul{padding-left:0;}
.box-content .card-number{top:52px;left:170px;}
.close{padding-top:5px;}
.sbHolder{position:absolute;top:30px;left:0;}
.products-worth .sort-by{position:relative;margin-right:0;margin-left:0;}
.fl{margin-right:6%;}
.worth-headding{padding-top:5px;}
.box-content .worth-headding{margin-left:0;margin-right:0;display:none;}
.sort-by strong{padding-left:0;}
.box-content .products-worth{margin-bottom:30px;z-index:99;}
.worth-headding{margin-left:23px;}
.products-worth .card-number{left:0;top:13px;}
.products-worth{padding:13px 7px 10px;}
.content_images.card-number-img{width:27px;height:18px;}
.fl{float:none;margin-right:0;margin-left:0!important;}
.products-worth{padding:10px 0px 10px;}
#schranka_items_count_in_list{left:192px;top:39px;display:none;}
.sort-by{margin-right:5px;}
.flexslider .slides li{margin-right:-6px;}
.products-worth .sbHolder{top:0;left:111px;width:117px;}
}
/*! CSS Used fontfaces */
@font-face{font-family:'flexslider-icon';src:url(http://localhost:59746/Content/js/flexslider_2_6_1/fonts/flexslider-icon.eot);src:url(http://localhost:59746/Content/js/flexslider_2_6_1/fonts/flexslider-icon.eot#iefix) format('embedded-opentype'), url(http://localhost:59746/Content/js/flexslider_2_6_1/fonts/flexslider-icon.woff) format('woff'), url(http://localhost:59746/Content/js/flexslider_2_6_1/fonts/flexslider-icon.ttf) format('truetype'), url(http://localhost:59746/Content/js/flexslider_2_6_1/fonts/flexslider-icon.svg#flexslider-icon) format('svg');font-weight:normal;font-style:normal;}

          List:
          <select id="listNames" tabindex="1" style="position: relative; display: none;" sb="88543365">
            <option value="-1">basic</option>
            <option value="telky">normal</option>
            <option value="-4">extended</option>
          </select>

          základný

              základný

              telky

              navštívené

363.89

278.90

39.90

37.67

472.77

489.00

46.70

A: Try this
.products-worth {
    position: relative;
    z-index: 99;
}


text:
Q: Print PrettyTable data to QPlainTextEdit My setup is Windows 10, Python 3.7, PyQt5
The goal is to print a formatted table to a QPlainTextEdit.
I have some data in a PrettyTable object. When I print this data to stdout, the table gets printed perfectly! But when printing to QPlainTextEdit (using table.get_string())... it looses the correct format.
A small code to show the issue:
import sys

from PyQt5.QtWidgets import (
    QApplication, QLabel, QPlainTextEdit, QVBoxLayout, QWidget)
from prettytable import PrettyTable

class Example(QWidget):

def __init__(self):
    super().__init__()

self.initUI()

def initUI(self):
    hbox = QVBoxLayout(self)

qpt = QPlainTextEdit(self)
qpt.setReadOnly(True)

x = PrettyTable()
x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
x.add_rows(
    [
        ["Adelaide", 1295, 1158259, 600.5],
        ["Brisbane", 5905, 1857594, 1146.4],
        ["Darwin", 112, 120900, 1714.7],
        ["Hobart", 1357, 205556, 619.5],
        ["Sydney", 2058, 4336374, 1214.8],
        ["Melbourne", 1566, 3806092, 646.9],
        ["Perth", 5386, 1554769, 869.4],
    ]
)
qpt.appendPlainText(x.get_string())

hbox.addWidget(qpt)

self.resize(400, 300)
self.setWindowTitle('QPlainTextEdit')
self.show()

def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

How to achieve the correct format for the table?

A: Found the answer in this post.
Keeping it short:
font = QFont("Monospace")
font.setStyleHint(QFont.TypeWriter)
my_plain_text_edit.setFont(font)


text:
Q: pass variable to php modal I am having this trouble whereby I want to delete items based on their ids. However, in modal, it doesn't get the specific id for me to delete. Instead, it gets the the ids which are the lowest first. For example, if I delete a product with an id of 88, it will deletes the id before it first such as number before 88. How can I delete specifically items with the right id?
<?php
ob_flush();
session_start();
include('includes/header.php');
include('includes/navbar.php');
if($_SESSION['admin_name']){
    //do nothing
}
else{
echo ""; exit;
}
$admin_name = $_SESSION['admin_name'];
?>
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href=" http://localhost/CarRentalv3/img/CarRent.ico">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css">
    <title>Admin Panel | Admin List</title>

Add Admin Data

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

      <form action="process.php" method="POST">

                Admin Name
                <input type="text" name="username" class="form-control" placeholder="Enter Username">

                Email
                <input type="email" name="email" class="form-control" placeholder="Enter Email">

                Position
                <input type="text" name="position" class="form-control" placeholder="Enter Position">

                Password
                <input type="password" name="password" class="form-control" placeholder="Enter Password">

                Confirm Password
                <input type="password" name="confirmpassword" class="form-control" placeholder="Confirm Password">

            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="submit" name="register_btn" class="btn btn-primary">Save</button>

      </form>

Admin Profile
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addadminprofile">
              Add Admin Profile
            </button>

<?php
if(isset($_SESSION['success'])&& $_SESSION['success']!=''){
    echo '
'.$_SESSION['success'].'
';
    unset ($_SESSION['success']);
}
if(isset($_SESSION['status'])&& $_SESSION['status']!=''){
    echo ''.'
'.$_SESSION['status'].''.'
';
    unset ($_SESSION['status']);
}
?>

    <?php
    $connection = mysqli_connect("localhost","root","","admindb");
    $query = "select * from admin";
    $query_run = mysqli_query($connection, $query);

    ?>

             ID
             ADMIN NAME
            EMAIL
            POSITION
            EDIT
            DELETE

     <?php if (mysqli_num_rows($query_run)>0){
         while($rows= mysqli_fetch_assoc($query_run)){
                        ?>

            <?php echo $rows['id'];?>
            <?php echo $rows['admin_name'];?>
            <?php echo $rows['admin_email'];?>
             <?php echo $rows['admin_position'];?>

                <form action="register_edit.php" method="post">
                    <input type="hidden" name="edit_id" value="<?php echo $rows['id'];?>">
                    <button  type="submit" name="edit_btn" class="btn btn-success"> EDIT</button>
                </form>

                             <form action="process.php" method="POST">
                             <input type="text" id="id"  readonly value="<?php echo $rows['id'];?> ">
                <button type="button" name="delete" onclick="myFunction();"id="delete" class="btn btn-danger" data-toggle="modal" data-target="#deleteModal">Delete</button>

                    <?php
         }
     }
     else{
         echo "no record found!";
     }
        ?>

PIN Required

                      <button type="button" class="close" data-dismiss="modal">×</button>

                     PIN
                    <input type="text" id="print" readonly  >
                     <input type="password" name="pin" id="password" class="form-control" />

                     <button type="submit" name="delete_btn" id="pin_button" class="btn btn-warning">Confirm</button>

 </form>

<?php
ob_end_flush();
include('includes/script.php');
include('includes/footer.php');
?>

A: You are creating buttons with id="delete" inside your while loop. So you end up with a lot of buttons with the same id which is both invalid html and creates your problem here.
You also open your  tag inside your while loop and you close it in your modal. That will also create invalid html since you'll be opening a lot of form tags and only closing one of them.
Without having seen the code on your process.php file it is not 100% that the fixes here will solve your issue so bear that in mind.
First of all change

    <form action="process.php" method="POST">
    <input type="text" id="id"  readonly value="<?php echo $rows['id'];?> ">
    <button type="button" name="delete" onclick="myFunction();" id="delete" class="btn btn-danger" data-toggle="modal" data-target="#deleteModal">Delete</button>

to

    <button type="button" name="delete" onclick="myFunction('<?php echo $rows['id'];?>');" class="btn btn-danger" data-toggle="modal" data-target="#deleteModal">Delete</button>

Then change your function
function myFunction(print_value) {
  document.getElementById("print").value = print_value;
}

Lastly change your modal body
<form action="process.php" method="POST">
    PIN
    <input type="text" id="print" readonly  >
    <input type="password" name="pin" id="password" class="form-control" />

    <button type="submit" name="delete_btn" id="pin_button" class="btn btn-warning">Confirm</button>
</form>

and remove the other closing form tag </form> you have before


text:
Q: Hibernate generates invalid query I am using Spring Data @Query annotation to select some values from the database. The query look like this (simplified)
@Query("from #{#entityName} where :myParam is null or someAttribute not in :myParam")

This should create equivalent SQL that should return all records from the table if the myParam value is null, however hibernate create the where clause like this
... where :myParam = null or ...

which does not return anything.
I am using Microsoft SQL Server 2017 (RTM).
Hibernate configuration is like this:
spring.datasource.driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.database-platform: org.hibernate.dialect.SQLServer2012Dialect

How can I ensure that the Hibernate generates correct query (i.e. using 'is' instead of '=')?

A: since JPA supports coalesce why not
@Query("from #{#entityName} where coalesce(someAttribute, :myParam) = :myParam)
?

A: If you don't add nativeQuery = true to @Query annotation, the query must be a valid JPQL query and it's the JPA's implementor's responsability (hibernate) to translate JPQL queries to underlying database SQL dialect.
With nativeQuery = true you must supply a valid SQL query that conforms to the underlying database dialect.

A: I'd be really surprised if this is really what is happening. My guess, your @Query annotation is not picked up and Spring Data uses the method name convention or you didn't share the correct query. Either way, if this really is a hibernate bug(maybe you are using a very old hibernate version), you should create an issue with a test case that reproduces the issue: http://hibernate.atlassian.net


text:
Q: Dask - map_partition I have a Dask DataFrame with sets of latitudes and longitudes (~32m records). I am trying to calculate the distance between the lat/lon using a function like below:
import numpy as np
from geopy import distance

def calc_distance(df, lat_col_name_1, lon_col_name_1, lat_col_name_2, lon_col_name_2):
if df[lat_col_name_1] != np.nan and df[lon_col_name_1] != np.nan and df[lat_col_name_2] != np.nan and df[lon_col_name_2] != np.nan:
    return distance.distance((df[lat_col_name_1], df[lon_col_name_1]), (df[lat_col_name_2], df[lon_col_name_2])).miles
else:
    return np.nan

I have tried calling this function using map_partitions (to create a DataFrame of index and distance as well as calling map_paritions with assign. I would like to use assign so I can avoid joining the DataFrames back together (seems costly). It does not like the np.nan checks. I get a

ValueError: The truth value of a Series is ambiguous. Use a.empty,
a.bool(), a.item(), a.any() or a.all().

I have records with null lat/lon so I need to account for that when calculating the distance.
Using map_partitions
distance = big_df.map_partitions(calc_distance,
                                    lat_col_name_1='latitude_1',
                                    lon_col_name_1='longitude_1',
                                    lat_col_name_2='latitude_2',
                                    lon_col_name_2='longitude_2',
                                    meta={'distance': np.float64})

Using map_partitions and assign
def calc_distance_miles(lat1, lon1, lat2, lon2):
    if lat1 != np.nan and lon1 != np.nan and lat2 != np.nan and lon2 != np.nan:
        return distance.distance((lat1, lon1), (lat2, lon2)).miles
    else:
        return np.nan

big_df = big_df.map_partitions(lambda df: df.assign(
    distance=calc_distance_miles(df['latitude_1'], df['longitude_1'], df['latitude_2'], df['longitude_2'])
), meta={'distance': np.float64}
)

A: map_partitions isn't like df.apply - the function calc_distance is being called with a partition of the dask.dataframe, which has type pd.DataFrame.
Therefore, df[lat_col_name_1] is a Series and df[lat_col_name_1] != np.nan is a boolean series (which will always return this error - see e.g. Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()).
There are faster array ways of computing a distance than element-wise, but the dask.dataframe analogue to what you're trying to do is to use map_partitions and then apply:
def calc_distance(series, lat_col_name_1, lon_col_name_1, lat_col_name_2, lon_col_name_2):
    if series[
        [lat_col_name_1, lon_col_name_1, lat_col_name_2, lon_col_name_2]
    ].notnull().all():

        return distance.distance(
            (series[lat_col_name_1], series[lon_col_name_1]),
            (series[lat_col_name_2], series[lon_col_name_2]),
        ).miles

    else:
        return np.nan

def calc_distance_df(df, **kwargs):
    return df.apply(calc_distance, axis=1, **kwargs)

distances = big_df.map_partitions(
    calc_distance_df,
    meta=np.float64,
    lat_col_name_1=lat_col_name_1,
    lon_col_name_1=lon_col_name_1,
    lat_col_name_2=lat_col_name_2,
    lon_col_name_2=lon_col_name_2,
)


text:
Q: Why does only one instance of checkbox work if there are multiple I have one application that multiple instances of it exists in the same page. I have one sort of slide show within the application that uses the input to show corresponding data. However the label and input only works with one instance in the page. so if there are to instance of the same application within the page, only the first one works.
Here is a demo: JSFiddle

$.fn.MP = function(options) {
  var settings = $.extend({
    // These are the defaults
    text: ""
  }, options);

  $(this).on("click tap", "input", function() {
    $(this).parent().siblings().find("input").prop("checked", false);
  });
};

$("#item1").MP({});
$("#item2").MP({});
input[type="checkbox"] {
  position: absolute;
  opacity: 0;
}

.panelTop > div div {
  display: none;
}

.panelTop > div input[type="checkbox"]:checked ~ div {
  display: block;
}

.panel {
  width: 400px;
  height: 100px;
  border: 1px solid black;
}

.panel > .panelTop {
  width: 100%;
  height: 49px;
  border-bottom: 1px dashed black;
}

.panel > .panelBottom {
  width: 100%;
  height: 50px;
}

.panel > .panelTop > div div {
  width: 24px;
  height: 24px;
  float: right;
  margin: 0px 9px 0 0;
  border: 1px dashed black;
}

.panel > .panelBottom > div {
  width: 32px;
  height: 32px;
  float: right;
  margin: 9px 9px 0 0;
  border: 1px solid black;
  text-align: center;
  font-size: 22px;
}

    Dependant Buttons:

      <input id="box-1" type="checkbox" checked>

1.1

1.2

1.3

      <input id="box-2" type="checkbox">

2.1

2.2

2.3

      <input id="box-3" type="checkbox">

3.1

3.2

3.3

    Main Buttons:
    1
    2
    3

    Dependant Buttons:

      <input id="box-1" type="checkbox">

1.1

1.2

1.3

      <input id="box-2" type="checkbox">

2.1

2.2

2.3

      <input id="box-3" type="checkbox">

3.1

3.2

3.3

    Main Buttons:
    1
    2
    3

So as you can see in the demo, there are two instances of the application, clicking on buttons of the 1, 2 or 3 makes change in the first instance even if you click on the second instance.
I want to make each instance work correctly and each radio button work only if it is pressed.
Any idea?

A: As @dryden-long already mentioned, IDs must be unique. Fix that, and modify the corresponding for attributes accordingly, and your issue is resolved.
EDIT: Per your comment, since the id values of your div.panel elements are already unique, you could do something like the following, which dynamically generates unique id values for your input elements, and updates the for values of the corresponding label elements accordingly:

$.fn.MP = function(options) {
  var settings = $.extend({
    // These are the defaults
    text: ""
  }, options);

  $(this).on("click tap", "input", function() {
    $(this).parent().siblings().find("input").prop("checked", false);
  });
};

// dynamically-generate id/for values
$('div.panel').each(function(index, el) {
    var $panel = $(el);
    var panelId = $panel.attr('id');
    var $panelBottom = $('div.panelBottom', $panel);

    $('div.panelTop > div > input', $panel).each(function(indexInput, elInput) {
        var $input = $(elInput);
        var inputId = panelId + '-box-' + indexInput;

        $input.attr('id', inputId);
        $('label:nth(' + indexInput + ')', $panelBottom).attr('for', inputId);
    });
});

$("#item1").MP({});
$("#item2").MP({});
input[type="checkbox"] {
  position: absolute;
  opacity: 0;
}

.panelTop > div div {
  display: none;
}

.panelTop > div input[type="checkbox"]:checked ~ div {
  display: block;
}

.panel {
  width: 400px;
  height: 100px;
  border: 1px solid black;
}

.panel > .panelTop {
  width: 100%;
  height: 49px;
  border-bottom: 1px dashed black;
}

.panel > .panelBottom {
  width: 100%;
  height: 50px;
}

.panel > .panelTop > div div {
  width: 24px;
  height: 24px;
  float: right;
  margin: 0px 9px 0 0;
  border: 1px dashed black;
}

.panel > .panelBottom > div {
  width: 32px;
  height: 32px;
  float: right;
  margin: 9px 9px 0 0;
  border: 1px solid black;
  text-align: center;
  font-size: 22px;
}

    Dependant Buttons:

      <input type="checkbox">

1.1

1.2

1.3

      <input type="checkbox">

2.1

2.2

2.3

      <input type="checkbox">

3.1

3.2

3.3

    Main Buttons:
    1
    2
    3

    Dependant Buttons:

      <input type="checkbox">

1.1

1.2

1.3

      <input type="checkbox">

2.1

2.2

2.3

      <input type="checkbox">

3.1

3.2

3.3

    Main Buttons:
    1
    2
    3


text:
Q: Can't dismiss mail composer using dismiss(animated: true, completion: nil) and dismissViewControllerAnimated doesn't come up as an option I've imported MessageUI and created an extension to include MFMailComposeViewControllerDelegate which includes dismiss(animated: true, completion: nil) and this doesn't close the VC that pops up to send the message however this is the only option that comes up when typing dismiss.  I can't tell if that's what's required with the a newer Swift version as all other examples show dismissViewControllerAnimated.  Not sure what I'm missing?
Action Button Code
    @IBAction func sendTapped(_ sender: UIButton) {

    let toRecipient = ["\(Constants.SubmitFeedback.feedbackEmail)"]

    let mc = MFMailComposeViewController()
    mc.mailComposeDelegate = self

    mc.setToRecipients(toRecipient)
    mc.setSubject("Feedback for Gallery App")

    mc.setMessageBody("Name: \(String(describing: nameTextField.text!)) \nEmail: \(String(describing: emailTextField.text!)) \n\nMessage: \n\(String(describing: messageTextField.text!))", isHTML: false)

    self.present(mc, animated: true, completion: nil)

}

Extension with 'dismiss' command
extension FeedViewController: MFMailComposeViewControllerDelegate {

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    switch result.rawValue {
    case MFMailComposeResult.cancelled.rawValue:
        print("Cancelled")
    case MFMailComposeResult.failed.rawValue:
        print("Failed")
    case MFMailComposeResult.saved.rawValue:
        print("Saved")
    case MFMailComposeResult.sent.rawValue:
        print("Sent")
    default:
        break
    }

    dismiss(animated: true, completion: nil)
}

}

A: from the docs

call this method on the presented view controller

i'm sure we all made the same mistake first time we used that api :-)


text:
Q: Getting Apache 2.4 and mod_authn_dbd to work with a Wordpress user database Has anybody managed to use a Wordpress wp_users table as input for apache's mod_authn_dbd ? This used to work for the apache 2.2 mod_auth_mysql, which had
Auth_MySQL_Encryption_Types PHPass PHP_MD5
but after a lot of searching, I still fail to understand how I can possibly make  mod_authn_dbd to match the "$P$B / md5" passwords it gets from the wp_users table.
Here's the base config I'm starting with:
DBDriver mysql
DBDParams "dbname=wp_test host=127.0.0.1 port=3306 user=root pass=rootpass"
DBDMin  2
DBDKeep 4
DBDMax  10
DBDExptime 300

Alias /test /home/test/test
<Directory "/home/test/test">
    Options +Indexes
    AuthType Basic
    AuthName "Authentication required"
    AuthBasicProvider dbd
    AuthDBDUserPWQuery "SELECT user_pass as password FROM wp_users WHERE user_login = %s"
    Require valid-user
</Directory>

The error I'm getting is
[auth_basic:error] [pid 14812] [client 192.168.0.2:57126] AH01617: user test: authentication failure for "/test/": Password Mismatch

So it's obvious that apache uses a different hash format as wordpress - but is there any way to match these 2 up for the required comparison?

A: Actually, the solution is to install a WP plugin like PHP native password hash - that changes the passwords to bcrypt which is in turn recognized by apache.


text:
Q: Converting TFS2012 XAML MSBuild build definitions to TFS2017 MSBuild definition We recently migrated/upgraded TFS2012 to TFS2017.  In TFS2017 XAML MSBuild definitions have been depreciated but are still functional.  We have plans to upgrade to TFS2018 next year and need to convert approx. 300 XAML build definitions to the new TFS MSBuild engine format.  Unfortunately we have de-commissioned our old TFS 2012 platform & the XAML editor.  Has anyone done these conversions or going thru the manual process of creating a new build definition from scratch? Is there a tool for conversion or clone that I am not seeing in TFS2017?  I searched all the TFS tags for this issue and have found none.  We have a year to convert 300 build definitions & I don't want to wait until last minute. Appreciate any feedback.

A: For the web-based, cross-platform build system--vNext build, that is the only model we support in TFS2018. XAML builds are not supported in TFS 2018. We encourage you to migrate your XAML builds. If you're not yet ready to migrate and need to continue using XAML builds, then you should not upgrade to TFS 2018.

When you upgrade to TFS 2018:

*

*If you have any XAML build data in your team project collection,    you'll get a warning about the removal of XAML build features.

*In TFS 2018, you'll be able to view completed XAML builds, but you    won't be able to queue new ones.

*There's no new version of the XAML build controller or agent in TFS    2018, and you can't configure an older version of the XAML build
  controller or agent to work with TFS 2018.

However, for migrating from XAML to vNext, there is no general purpose automated way to do this.  The systems are different enough that you really just need to create new build definitions that do what you want.  For people who have done heavy customizations (like writing custom workflow tasks), this will be real work.  The good news is that the newer system has a wide array of easy to use tasks – both "in the box" and available in the marketplace.
Here are some docs on migrating old XAML and creating new vNext build definitions:

*

*Migrate from XAML builds to new builds

*Create your first Hello world build definition

*Create build definitions for your various app types

A: The two build systems are fundamentally different. There is no way to automatically convert XAML build definitions to the newer build system.
If you're just using stock XAML build templates, the built-in templates in the new build system will result in roughly equivalent behavior.


text:
Q: Is there a software that can change my videos into just audio? I  have a youtube downloader, and it downloads videos incredibly well. Amazing quality, names them properly, and its fast. It even does playlist's. The downfall is if you just want the audio you need to pay for it.
I'm wondering if there is a software that can rip the audio into mp3 from a whole bunch of videos?

A: ffmpeg can convert many file types. Usually I just have to run this command (in a terminal/command prompt, depending on what OS you use):
ffmpeg -i INPUT_FILE OUTPUT_FILE.mp3

If you're not choosy about the output quality, this should do it for you. (I'm not choosy, knowing nothing about audio quality, so it works for me.)
On Linux, ffmpeg can be installed from your package manager. On Mac OS X, I have installed it via MacPorts. I've also installed it on Windows; I don't remember where, but it's ultimately linked from the ffmpeg homepage.

A: If you are on OS X, the new Lion version of QuickTime can strip audio from video.

A: I had some success with http://www.listentoyoutube.com/ but googling for "youtube mp3" returns many results.

A: The free, web-based service Zamzar will do video > audio conversions.

A: You may try this YouTube downloader, I know it can help you download youtube video to computer for free. You can also use it to extract the audio from YouTube video as MP3 songs.

A: Try Handbrake. It combines the FOSS tools like ffmpeg into nice multi-platform GUI package, and can do pretty much any conversion, including separating audio and video tracks.


text:
Q: My footer keeps overlapping I've searching over the internet and I've added that was recommenced but it seems like the footer is still over lapping my page. Would anyone know why?
footer {
    background: rgba(0, 0, 0, .93);

So, on the forums I went on they said to set the min hight to 100%
    min-height: 100%;

Set the position but the same result is coming up.
    position: relative;
}
h4 {
    text-align: center;
    font-family: 'open_sansbold', sans-serif;
    font-size: 30px;
    font-weight: 700;
    color: white;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    margin-bottom: 10px;
    padding-top: 13em;
}
footer p {
    text-align: center;
    font-family: 'open_sansbold', sans-serif;
    font-size: 18px;
    font-weight: 700;
    color: white;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    margin-bottom: 5px;
    padding-top: 0.5em;
}

A: A simple way of making sure is to add an empty div above it about the same size as the footer.  this will push the footer down and remove the overlay.

A: I'm not sure of the exact desired outcome, and I didn't see overlapping (after fixing the h4 tag... but changing your height and padding-bottom (if desired) fixes the size.  http://jsfiddle.net/dsbf72tp/
footer {

    background: rgba(0, 0, 0, .93);
    height: auto;
    position: relative;
    clear:both;
    padding-bottom: 50px;
    }


text:
Q: MSI x99 motherboard cannot detect nvme after clr CMOS My Intel 600p nvme drive with Win 10 installed was working fine until I reset the BIOS.
I pressed the CLR CMOS button by accident when trying to plug in a cable.
Now the computer doesn't boot at all.
Going to the MSI BIOS, I can't find the NVME drive at all in boot or in storage.  M.2. shows "Not Detected."
I have the latest BIOS.  What could be the problem here?  Why can't the BIOS detect my Intel NVME SSD that already has Win 10 installed?
Thanks a lot for any help!

A: Hitting the CLR CMOS button should clear all the settings in BIOS.  If you bought the computer from a company, you could just call them to have them tell you the proper settings for the BIOS.


text:
Q: How to achieve cascade dropdown functionality for List using KnockoutJs HTML:

JS:
function view_model() {
  var self = this;
  self.all_consultants = ko.observableArray();
  self.selected_Auth = ko.observable("all Author");
  self.selected_Book = ko.observable("all books");
  self.selectList = ko.observableArray([{
    name: "J.K R",
    DscName: [
      "HP1", "HP2", "HP3"
    ]
  }, {
    name: "shakespeare",
    DscName: [
      "Hamlet", "Othello"
    ]
  }]);

  //if (self.auth_header()) {
  //  get_list_data();
  //}

  self.rightList = ko.observable();
  self.addToRightList = function(list) {
    self.rightList(list);
  };

}
ko.applyBindings(new view_model());

Need Dropdown like functionality On 1st list Author selection populate 2 list with Books and if there is only 1 book then it should be autoselected.

A: The reason you have not gotten much help with your question is that it came across as "write some code for me" rather than "I am trying to do this and running into a particular problem." StackOverflow is about helping you understand things, not just putting up some code to have other people make it work.
The code you presented had many errors. I edited your question to get rid of the syntax errors so that it at least could run. Below I have worked out some of the problems to make the dependency you were looking for.
Some things to note:

*

*You cannot use toLowerCase directly on an observable, you have to get at its contents, so it's selected_Book().toLowerCase(), not selected_Book.toLowerCase()

*You must pay attention to binding contexts. rightList does not contain a selectList member; it has a DscName, which is what should be used in the 2nd foreach. Binding contexts are the reason I had to put $root on a number of things.

*When you have a problem like this with multiple requirements, break it down. Maybe the first thing you should have worked out was how to successfully display two lists. Then work on building the second list from the first.

function view_model() {
  var self = this;
  self.all_consultants = ko.observableArray();
  self.selected_Auth = ko.observable("all Author");
  self.selected_Book = ko.observable("all books");
  self.selectList = ko.observableArray([{
    name: "J.K R",
    DscName: [
      "HP1", "HP2", "HP3"
    ]
  }, {
    name: "shakespeare",
    DscName: [
      "Hamlet", "Othello"
    ]
  }]);

  //if (self.auth_header()) {
  //  get_list_data();
  //}

  self.rightList = ko.observable();
  self.addToRightList = function(list) {
    self.rightList(list);
  };

}
ko.applyBindings(new view_model());


text:
Q: about 2-sylow subgroups of group of the form $G \times H$ suppose $G$ and $H$ are finite groups,consider the group $G \times H$ ,and suppose $G_1$ is 2-sylow subgroup of $G$ and $H_1$ is 2-sylow subgroup of $H$ ,

*

*does $ G_1 \times H_1$ is 2-sylow subgroup of $G \times H$ ?

*do all 2-sylow subgroups of $G \times H$ are the form $G_1 \times H_1$ ?

*if one of $G$ or $H$ ,or both of them don't have 2-sylow subgroups ,does $G \times H$ have any 2-sylow subgroups ?
for 1 and 2 my guess is yes,by definition of 2-sylow subgroups; but I thought that maybe there is a counterexample.
for 3 my guess is no,but I have no Idea how.
by the construction of $G \times H$ this answers came to my mind at the first place but then I filled with doubts.
this three questions is important for the project I am working,so it will be great if you help me or giving me references to study subjects like this,thanks a lot.


text:
Q: KeyListener not working with JPanel I am trying to make a menu class for a small game I'm making, and it all works fine, except now, the KeyListener does not work at all, I tried applying it to JFrame and JPanel, but nothing is working...
Here is my MainClass:
package bombermangame;

import javax.swing.JFrame;

public class MainClass {

    public static int WIDTH = 870, HEIGHT = 800;

    public static JFrame frame = new JFrame();
    public static Menu menu = new Menu();

    public static void main(String[] args) {
        frame.setContentPane(menu);
        frame.pack();
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("BomberMan V0.3");
        frame.setSize(WIDTH, HEIGHT);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
`

And here is my Menu class:
package bombermangame;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JButton;
import javax.swing.JPanel;

public class Menu extends JPanel implements ActionListener {
    private static final long serialVersionUID = 1L;

    private JButton startButton = new JButton("Play");

    private int x = 0, y = 500;

    private boolean down = false;
    private boolean up = true;

    private Timer timer = new Timer();

    public Menu() {
        setBackground(Color.blue);
        startButton = new JButton("Start");
        startButton.setBounds(0,0, 100, 40);
        startButton.setPreferredSize(new Dimension(100, 40));
        startButton.addActionListener(this);
        startButton.setFocusPainted(true);
        add(startButton);

    }

    public void actionPerformed(ActionEvent ae) {
        Object a = ae.getSource();
        Game game = new Game();
        Listener keys = new Listener();

        if (a == startButton) {
            timer.cancel();
            MainClass.frame.remove(MainClass.menu);
            MainClass.frame.setContentPane(game);
            MainClass.frame.addKeyListener(keys);
            game.addKeyListener(keys);
            game.setBackground(Color.BLACK);
            game.setDoubleBuffered(true);
            game.setBounds(0, 0, WIDTH, HEIGHT);
            Game.running = true;
        }
    }

}


text:
Q: Visual Studio 2013 not handling Doxygen multi-line comments correctly I am using Visual Studio 2013 (C++) with the Atomineer Utils add-in.
Coming from a Java background, I was interested in the Doxygen style of documentation, so I configured Atomineer to use the Doxygen (Javadoc) style, which looks like this basically:
/**
 * @brief adds two numbers together
 */
void add(int x, int y);

However, let's say I want to start a multi-line comment. Coming from IntelliJ IDEA, I assumed this would work:
/**

enter
/**
 *

or better yet:
/**

enter
/**
 *
 */

In reality, this produces the strangest results:
/**

# autocompletes to

/**/

enter
/**
/* /

Hopefully you can understand how unhelpful that sort of autocomplete behavior is.
On top of that, if you manage to get a complete Doxygen comment on, extending that comment only works if (from my observations):

*

*You aren't selecting the beginning of the comment (/**)

*You are selecting after the asterisk before hitting enter, and not the space that automatically generates after it: (| represents the cursor)
/**
 *|
 */

then hitting enter would work, but not
/**
 * |
 */

*OR you type something on that line and hit enter
Now on to how I would prefer to solve the problem: to somehow fix the multi-line comment generation and automatic extension to be similar to what I expect.
However, if you guys are certain that that kind of solution does not exist, then I am aware that Atomineer generates documentation automatically if I type /// (but why not /**!?) and I can use that instead as a sort of work-around.
What I have tried so far:

*

*Disabled Complete Multiline Comments under Options -> Text Editor -> C/C++ -> Advanced (this disables it AND Atomineer's documentation generator)

*Disabled Generate XML documentation comments for /// under Options -> Text Editor -> C# -> Advanced (We're talking C++ here so obviously this didn't do anything)

A: (Apologies for the late answer, I didn't spot this question earlier)
The simple work-around would have been to type /// or ctrl+shift+D to generate the comment. However, Atomineer has since been updated, and also now allows you to type /** to generate a comment.


text:
Q: Expecation of a funciton of hypergeometric r.v. Got this question:
Let X be Hypergeometric with parameters w, b, n, find E${x \choose 2}$ by thinking, without any complicated calculations.
So I guess there must be some story proof here, but I can not think of any. Could someone help on this?
Thanks.

A: I can't match your parameter names with the parameter names in Hypergeometric Distribution wikipedia page, so I'll have to use their parameters.
Specifically, we can use $\binom{x}{2}\cdot \binom{K}{x} = \binom{K}{2}\cdot \binom{K-2}{x-2}$ to simplify the sum in the expected value as
$$\begin{align*}
\text{E}\binom{X}{2} &= \sum_{k=2}^n \binom{k}{2} \cdot \frac{\binom{K}{k}\binom{N-K}{n-k}}{\binom{N}{n}} \\
&= \frac{\binom{K}{2}}{\binom{N}{n}}\sum_{k=2}^{n} \binom{K-2}{k-2}\binom{(N-2)-(K-2)}{(n-2)-(k-2)} \\
&= \frac{\binom{K}{2}\binom{N-2}{n-2}}{\binom{N}{n}}\sum_{k=0}^{n-2} \frac{\binom{K-2}{k}\binom{(N-2)-(K-2)}{(n-2)-k}}{\binom{N-2}{n-2}} \\
&= \frac{\binom{K}{2}\binom{N-2}{n-2}}{\binom{N}{n}}
\end{align*}$$
Here, the last equation follows because the last sum is the sum of probabilities of a hypergeometric random variables with parameters $N-2, K-2, n-2.$


text:
Q: PDO & MSSQL - How to change the timezone per connection I'm looking to set the timezone (per session) on a PDO-MSSQL connection so that getdate() can be used to store and return local times of a user rather than the servers default (Europe/London)
Google returns hundreds of results for MYSQL; but nothing for MSSQL. So it looks like this is the answer for MYSQL:
$PDO->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND=>"SET time_zone = 'Europe/London'
Is there an equivalent for MSSQL?
Thanks
Chris

A: Microsoft SQL Server does not have the concept of a session time zone, so the answer to your question is simply - No.
However, there are solutions for working with time zones in SQL Server.  With SQL Server 2016, support was added for AT TIME ZONE so one can convert data elements between time zones (similar to MySQL's CONVERT_TZ function).  This uses Microsoft Windows time zone identifiers though, not standard IANA / TZDB identifiers.  If you want support for those (such as Europe/London you mentioned), then you'll need to use something like my SQL Server Time Zone Support open-source project.
Either of those approaches is only required if you really need to do time zone conversions at the database layer.  In the vast majority of cases, you don't actually need to do that.  Instead, handle time zone conversions at the application layer.  PHP has really good support for time zones, so you shouldn't need to do it in the database.
If you had a specific scenario in mind, then ask a new question about that (after searching to see if it's already been asked).


text:
Q: How to detect if a web URL contains a feed or not? I have seen in some browsers (Firefox for example), the RSS feed icon gets activated only when a page contains a RSS/Atom feed. How the browser detects whether the page contains a feed or not?

A: Just look at the code for this page.  You'll see this after some javascript in the header:
<link rel="alternate" type="application/atom+xml" title="Feed for question 'How to detect if a web URL contains a feed or not?'" href="/feeds/question/3020295">

Alternatively, many blogs use
<link rel="alternate" type="application/rss+xml" title="Post Title" href="link-to-post">


text:
Q: Displaying user input from a form in verification email I'm having a little problem with my registration form: I am trying to get the UserID field displayed as inputted by the user when the verification email is sent for the user to activate the account.
Currently, I only need the User provided UserID and randomly generated PIN to be displayed in the verification email. Please can anyone correct this for me, as the PIN is displayed properly in the email, but not the UserID.
Below is my code:

        <?php

            mysql_connect("localhost", "root", "") or die(mysql_error()); // Connect to database server(localhost) with root .
            mysql_select_db("registrations") or die(mysql_error()); // Select registration database.

            $email="";

            if( isset($_POST['fullname']) // Is the name field being posted; it does not matter whether it's empty or filled.
    && // This is the same as the AND in our statement; it allows you to check multiple statements.
    !empty($_POST['fullname']) // Verify if the field name is not empty
    AND isset($_POST['email']) // Is the email field being posted; it does not matter if it's empty or filled.
    && // This is the same as the AND in our statement; it allows you to check multiple statements.
    !empty($_POST['email']) ) // Verify if the field email is not empty
      {

                $fullname = mysql_real_escape_string($_POST['fullname']);
                $email = mysql_real_escape_string($_POST['email']);

                }
                if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email)){
                    // Return Error - Invalid Email
                    $msg = 'The email you have entered is invalid, please try again.';
                }else{
                    // Return Success - Valid Email
                    $msg = 'Your account has been created,
 please verify it by clicking the activation link that has been send to your email.';
                    }

                    $hash = md5( rand(0,1000) ); // Generate random 32 character hash and assign it to a local variable.

                    $PIN = rand(1000,5000); // Generate random number between 1000 and 5000 and assign it to a local variable.

$to      = $email; // Send email to our user
$subject = 'Signup | Verification of your BFS Account'; // Give the email a subject
$message = 'Thanks for signing up!
Your account has been created, you can login with the following credentials after you have activated your account by clicking the url below.
------------------------
USER ID: '.$UserID.' // **THIS IS WHERE I HAVE THE PROBLEM DISPLAYING USER ID**
PIN: '.$PIN.'
------------------------
Please click this link to activate your account:
http://www.website.com/verify.php?email='.$email.'&hash='.$hash.'
'; // Our message above including the link
$headers = 'From:noreply@website.com' . "\r\n"; // Set from headers
mail($to, $subject, $message, $headers); // Send our email

        ?>

A: You are not assigning anything to $UserID. As a wild guess you may need to:
$UserID = $_POST['userid']; //  or
$UserID = $_POST['user_id'];

P.S Please work on your code indentation.


text:
Q: Is it possible to find out what theme a specific web site is using? I just want to know is there a way to find out (by inspecting links or etc.) to find out what theme a specific web site is using?
P.s. I do not own the sites that I want to check.
Regards,

A: You could probably view source and find out where the main stylesheet is located. Most likely it will look something like this:
<link rel="stylesheet" type="text/css" media="all"
href="http://sitename.com/wp-content/themes/theme-name/style.css" />

Where theme-name is the name you are probably looking for. Cheers.


text:
Q: Emulating VFACE Semantic in PS_2_0 Shader I am doing a bit of work on some of our HLSL shaders, trying to get them to work in SM2.0. I've nearly succeeded but one of our shaders accepts a parameter:
float alignment : VFACE

My understanding from MSDN is this is an automatic var calculated in case I need it, but it's not supported under SM2.0... so, how might I reproduce this? I'm not a shader programmer so any (pseudo) code would be really helpful. I understand what VFACE does, but not how I might calculate it myself in a pixel shader, or in a VS and pass it into the PS. Calculating it per-pixel sounds expensive so maybe someone can show a skeleton to calculate it in a VS and use it in a PS?

A: You can't. Because VFACE means orientation of the triangle (back or front) and the VS or PS stages have not access to the whole primitive (like in SM4/5 GS stage).
The only way is to render your geometry in two passes (one with back face culling, the other with front face culling) and pass a constant value to the shader matching VFACE meaning.


text:
Q: (click) action does not work inside of [innerHTML] Angular I'm using Angular 6. I have a variable named chatConversations that I add html codes in to it. And in front-side I show data by this code:

The problem is in some of HTML codes that I`m injecting into it, I have some click action like :
do it

But it does not work when I inject it into the chatConversations. How can I make functional the (click) elements that I inject into the [innerHTML]?


text:
Q: How can I replicate compile time hex string interpretation at run time!? c++ In my code the following line gives me data that performs the task its meant for:
const char *key = "\xf1`\xf8\a\\\x9cT\x82z\x18\x5\xb9\xbc\x80\xca\x15";

The problem is that it gets converted at compile time according to rules that I don't fully understand.  How does "\x" work in a String?
What I'd like to do is to get the same result but from a string exactly like that fed in at run time. I have tried a lot of things and looked for answers but none that match closely enough for me to be able to apply.
I understand that \x denotes a hex number. But I don't know in which form that gets 'baked out' by the compiler (gcc).
What does that ` translate into?
Does the "\a" do something similar to "\x"?

A: This is indeed provided by the compiler, but this part is not member of the standard library. That means that you are left with 3 ways:

*

*dynamically write a C++ source file containing the string, and writing it on its standard output. Compile it and (providing popen is available) execute it from your main program and read its input. Pretty ugly isn't it...

*use the source of an existing compiler, or directly its internal libraries. Clang is probably a good starting point because it has been designed to be modular. But it could require a good amount of work to find where that damned specific point is coded and how to use that...

*just mimic what the compiler does, and write your own parser by hand. It is not that hard, and will learn you why tests are useful...

If it was not clear until here, I strongly urge you to use the third way ;-)

A: If you want to translate "escape" codes in strings that you get as input at run-time then you need to do it yourself, explicitly.
One way is to read the input into one string. Then copy the characters from that source string into a new destination string, one by one. If you see a backslash then you discard it, fetch the next character, and if it's an x you can use e.g. std::stoi to convert the next few characters into its corresponding integer value, and append that number to the destination string (either adding it with std::to_string, or using output string streams and the normal "output" operator <<).


text:
Q: safe 301 redirection using htaccess for two domains I have two domains, a new domain (newdomain.com) and and old legacy domain (olddomain.com). I want to safely redirect the old domain to the new domain. Easy enough.
At the moment I am doing this using htaccess ModReWrite like so
# Redirect WWW's
RewriteEngine On
RewriteCond %{HTTP_HOST} !^newdomain\.com$ [NC]
RewriteRule ^(.*)$ http://newdomain.com/$1 [R=301,L]

Which basically says rewrite any domain that isn't the new one, to the new one. I'm not 100% sure if this is safe for search engines? Should I redirect the old domain separately?

A: This is correct for SEO. Search engines will update their database that the old URL has changed to the new URL. You should leave it active like that for at least several months to they all get a chance to update, and visitors can still use the old URL.

A: You may find this blog post helpful
http://www.realestatewebmasters.com/blogs/morgan-carey/9408/show/


text:
Q: Como compartir en facebook un texto desde cualquier URL Buenos días a todos.
Tengo un Widget escrito en JAVASCRIPT, que se puede integrar en cualquier web de nuestros clientes y permite realizar acciones a través de este Widget a nuestra página.
Para aclarar un poco mas.
Tenemos el widget JS en nuestro servidor que le llamamos origen.net y el cliente puede insertar mediante una llamada, el script en su Web que la llamaremos cliente.com con un codigo similar a este:
<script type="text/javascript" src="origen.net/wwidget.js?id=2ZVdFF5UWM3cmVXR3IxVWZ2OHUrUVpXSkxFQ"></script>

Toda la ejecución del script funciona correctamente. El problema viene cuando quiero que el usuario pueda utilizar el botón COMPARTIR CON FACEBOOK definido dentro del Widget. Este botón sólo tiene que publicar un texto simple y la URL del cliente.
Facebook obliga a crear un ID de aplicación, el cual tengo hecho y obliga a definir el dominio o dominios desde donde se pueden compartir. No es posible definir dentro de Facebook todos y cada uno de los dominios donde los clientes pondrán el Widget y si comparto desde la Web del cliente, Facebook lanza este error:

No se puede cargar la URL: El dominio de esta URL no está incluido en los dominios de la aplicación. Para poder cargar esta URL, agrega todos los dominios y subdominios de tu aplicación en el campo "Dominios de la aplicación" en la configuración de la aplicación.

He intentado crear una página en mi servidor origen.net, para que muestre la información que quiero y la comparta en facebook, pero todas las URL e informaciones que se comparten en Facebook van a nuestro servidor y quiero que vayan a la Web del cliente.
¿Conocéis alguna forma o configuración para compartir anónimamente un texto simple a Facebook, con una url del cliente y que no me de el error?
¿Alguien tiene una idea de como crear un compartir que envíe la información a Facebook sin que sea una URL a una Web (solo quiero texto y url del cliente como información adicional)?
Gracias anticipadas.


text:
Q: match() is not working with Number field I'm trying to perform an action on rows that have specific words in email column by filtering it using the regular expression.

Problem is that match() produces the following error
TypeError: Cannot find function match in object 1234. (line 25, file "Code")
My code
    function smartDelete() {
    // smartDelete settings goes here,
    var badDomains = ["bad\\.com", "red\\.com"];

    var emailColumnNumber = 2;

    var regExpModifiers = "i";

    // Gain access data in the sheet
    var sheet = SpreadsheetApp.getActiveSheet();
    var rows = sheet.getDataRange();
    var numRows = rows.getNumRows();
    var values = rows.getValues();
    var rowsDeleted = 0;
    var Action = false;

    // delete procedure
    for (var i = 0; i <= numRows - 1; i++) {
        var row = values[i];
        Action = false;

        // check bad domains
        for (var j = 0; j <= badDomains.length - 1; j++) {
            var myPattern = new RegExp(badDomains[j], regExpModifiers);
            var status = row[emailColumnNumber].match(myPattern);
            if (status) {
                // match found, mark this row for delete
                Action = true;
                break;
            };
        };

        // execute delete.
        if (Action) {
            sheet.deleteRow((parseInt(i) + 1) - rowsDeleted);
            rowsDeleted++;
        };
    };
}

A: match() has to receive a string, cell C4 produces a Number, hence the error.
Change this line,
var status = row[emailColumnNumber].match(myPattern);
Into the following should fix the TypeError

Notice the .toString() method ahead of .match()

var status = row[emailColumnNumber].toString().match(myPattern);


text:
Q: How to get Ridoff from those Method Details in the Javascript Object This is My Console. Look this is the object containing Data and Method details(AFTER A220)
While I Trying Convert the object into an array this method details also got convert into separate array.
This is the Out Put (Look it Converts that things into an array)
    <script>

    var app = angular.module("myApp", ['restangular']);
        app.controller("myCtrl", function($scope,Restangular) {
            $scope.clickme=function(){
        Restangular.setBaseUrl('http://localhost:8080/StrutsREST/api');
        Restangular.all('interfaces').doGET().then(function(data) {
        console.log(data);
            let arr=Object.entries(data);
        console.log(arr);
            })
        }
        });
</script>


text:
Q: Ruby on Rails - Normalize-rails gem I have installed normalise-rails gem in my project and it all seems to work fine.
But I notice there is no css file generated in the app and I'm curious to know how this is working.
This is not a problem and such but it will be good to know what has happened in the background.

A: Look, to make it work you added to application.css these lines:
*= require_self
*= require normalize-rails
*= require_tree .

And middle line just requires normalize-rails.scss file that you can found in gem's vendor/assets/stylesheets directory.

A: That's because the gem isn't downloaded in your project. All the gems are installed in your INSTALLATION DIRECTORY - more info.
If you want to use an edited version of normalize.css, then just download the stylesheet and save it in your app's
vendor/assets/stylesheets/

folder and include that file in your
app/assets/stylesheets/application.css

, like:
/*
 *= require_tree .
 *= require normalize
 *= require_self
*/