text:
Q: jQuery mobile tap event triggered for twice I tested with jquery mobile 'tap' event and found it fired two times, everytime it is triggered. Code as below for a html page:
<!DOCTYPE html>

    <title>Demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

        tapped me

More irony is when I test this over jsfiddle, it only fired the event for one time.
Here's the link.
http://jsfiddle.net/mochatony/tzQ6D/6/
After further testing I found out the bug has gone away with placing the javascript at header section.
<!DOCTYPE html>

    <title>Demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

        tapped me

I couldn't explained why the placement at the body and header section make this different.

A: You are experiencing the ghost click issue... It's a known "bug" and hard to resolve.
More infos there :
http://forum.jquery.com/topic/tap-fires-twice-with-live-tap
https://developers.google.com/mobile/articles/fast_buttons
http://philosopherdeveloper.wordpress.com/2011/11/01/ghost-clicks-in-jquery-mobile/
In the first link you will find a hack that does the trick. As far as I know, there is no easy solution :(
BTW: Even if it won't solve your problem, @Sagiv is right. JQuery mobile often use ajax for changing page and so does not trigger a document.ready event.

A: from the jQuery Mobile page:

Important: Use $(document).bind('pageinit'), not $(document).ready()
  The first thing you learn in jQuery is to call code inside the
  $(document).ready() function so everything will execute as soon as the
  DOM is loaded. However, in jQuery Mobile, Ajax is used to load the
  contents of each page into the DOM as you navigate, and the DOM ready
  handler only executes for the first page. To execute code whenever a
  new page is loaded and created, you can bind to the pageinit event.
  This event is explained in detail at the bottom of this page.

so skip the $(document).ready(). more info here.

A: related with this question, I was getting two events 'tap' and 'click' one just after the other one. All ideas here were inspiring, but I ended up finding another solution. I added the following code to my JavaScript controller to discriminate consecutive duplicated events based on the timestamp that, fortunately, is exactly the same for the two duplicated events. Basically, what I do is to store the last used timestamp if I decide to consume the event. The second time an event with the same timestamp I just discarded it.

var _lastEventTimestamp;
var checkAndPreventDuplicatedEvent = function (e) {
    if (e.timeStamp === _lastEventTimestamp) return true;
    else _lastEventTimestamp = e.timeStamp;
    return false;
}

then, in each of my handlers I added this filtering code in the beginning:

var onTapSomething = function (e) {
   if (checkAndPreventDuplicatedEvent(e)) return;
   //do here whatever you would do in the case of legitimate event...
}

A: I forget where I saw this, but the issue is that jQuery Mobile is binding to both touch and mouse events in order to simulate "tap," and in some circumstances Android will fire both.
The trick that has worked for me is to call preventDefault on the event in your event handler. That will keep the duplicate event from firing.
As far as why this is the case only sometimes, I know that mobile browsers will try to only fire the mouse version of the event if someone isn't listening to the touch version. There may be an issue with detection or jQuery's delegation that is confusing that heuristic.

A: $("#buttonID").tap(function(event){
        if(localStorage.JQMGostClick == 0 || localStorage.JQMGostClick == "" || typeof(localStorage.JQMGostClick) === "undefined")
            localStorage.JQMGostClick = 1;
        else if(localStorage.JQMGostClick == 1){
            localStorage.JQMGostClick = 0;
            return false;
        }
.....
});

It works for me, since if you are using a mobile environment then probably you are using a kind of storage

A: I found out that in my case the addition of data-role="page" to my page container prevented tap events from being fired twice.

A: I experienced something like this before and it was due to the fact that my form was not inside a data-role="page"
What I would suggest is to wrap your code with jQuery Mobile html structure so your could should look like this instead

        tapped me

A: This may not be the best solution and will only work in some cases but what worked for me was immediately after the click event starts set the CSS 'pointer-events' for that element to 'none'. Then using JS's setTimeout reset the 'pointer-events' to auto after 500ms.
For me 300ms was enough for Android devices but iPhone needed 500ms to prevent the double click.

function yourEvent(evt){

  $(el).css('pointer-events', 'none');

  setTimeout(function(){
      $(el).css('pointer-events', 'auto');
  }, 500);

  //do you stuff

}


text:
Q: How do you convert a text file into a 2D character array? I am trying to convert a text file into a 2 dimensional character array. I am part of the way there but the last line of my array is not fully correct. Here's my code:
protected void readMap(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    char[] chars;
    int lines=0;
    while (br.readLine() != null) {
        lines++;
    }
    File file = new File(fileName);
    try (FileReader reader = new FileReader(file)) {
        chars = new char[(int) file.length()];
        reader.read(chars);
        reader.close();
    } catch (IOException e) {
    }

    int columns = ((int) file.length())/lines;

    map = new char[lines][columns];
    for(int i=0; i<lines;i++){
        for(int j=0;j<columns;j++){
           map[i][j] = chars[j%columns+i*columns];
        }
    }

    for(int ro=0; ro<map.length; ro++){
                for(int colum=0; colum<(map[0].length); colum++){
                    System.out.print(map[ro][colum]);
                }
            }
    return null;
    }

Here's the output:
##########################
#........................#
#.....###........###.....#
#......G..........G......#
#........................#
#...........E............#
#......G.........G.......#
#........G.....G.........#
#..........###...........#
#........................#
#################
                 ^missing #'s here

I'm very confused on why this is occuring. I've tried changing how I print the array but i'm pretty sure its how its to do with how i've converted the 1d 'chars' array to the 2d 'map' array.
I'm really lost so any help would be much appreciated! Thank you.

A: I've just executed the code and the map prints as expected. The issue may be down to the file itself as that is the uncommon factor.
edit:
The results you have observed is because you may have a new line character, or other special character, at the end of or somewhere in the file. Removing this you should see the consistent map you want.
Alternative
protected static void readMap(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    String line = "";
    List<String> lines = new ArrayList<>();
    while ((line = br.readLine()) != null) {
        lines.add(line);
    }

    char[][] chars = new char[lines.size()][];
    for (int col = 0; col < lines.size(); col++) {
        for (int row = 0; row < lines.get(col).length(); row++) {
            chars[col] = lines.get(col).toCharArray();
        }
    }

    for (int col = 0; col < chars.length; col++) {
        for (int row = 0; row < chars[col].length; row++) {
            System.out.print(chars[col][row]);
        }
        System.out.println();
    }
}//My rows and cols may be back to front

Few other notes:

*

*You shouldn't be returning a value from a void method, even null (You'll want to return null if the return type is Void).

*Your compiler may complain if you don't initialize chars initially, as mine did. char[] chars = null; would do it in this scenario.

A: I'm guessing your file looks something like this
##########################
#........................#
#.....###........###.....#
#......G..........G......#
#........................#
#...........E............#
#......G.........G.......#
#........G.....G.........#
#..........###...........#
#........................#
##########################

If you print the file length, you will see that the file length is 296
As Your code row = 11 and columns = 26
When you are copying to map you are copying up to 11 * 26 = 286
Try the UPDATED code below
public void readMap(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    int lines = 0, columns = 0;
    String str;
    List<String> lineList = new ArrayList<>();
    while ((str = br.readLine()) != null && str.length() != 0) {
        lines++;
        columns = Math.max(columns, str.length()); // as it's not fixed
        lineList.add(str);
    }
    System.out.println("Row : " + lines);
    System.out.println("Columns : " + columns);

    char[][] map = new char[lines][columns];
    for (int i = 0; i < lines; i++) {
        String currentLine = lineList.get(i);
        int idx = 0;
        for (int j = 0; j < currentLine.length(); j++) {
            map[i][j] = currentLine.charAt(idx++);
        }
    }
    for (int r = 0; r < map.length; r++) {
        for (int c = 0; c < (map[0].length); c++) {
            System.out.print(map[r][c]);
        }
        System.out.println();
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the function of the four pins on my SSD? While searching for an answer, I found this question on SU what is the purpose of this 4 pin interface on sata hdds and why doesnt it exist on SSDs?
Well, on my Kingston HyperX SSD drive, they do exist.

So if Spread Spectrum Clocking and reduced power spin up is not needed, what would be the function of these four pins?
All of my search attempts show only a few variants that apply to 2.5" spinning platter drives depending on vendor and none for SSD, to include the attached SU question.
Any ideas?

A: Partial Answer
I emailed Kingston technical support to get their answer on the subject

Thanks for contacting Kingston technical support.   For those 4 pins, basically they do not have any function.  Only SATA connector and power connector of SSD will be connected and used.

I Pushed for more information and got this in reply

Thanks for your reply.  Our apologies but they are intended for any use or purpose.

I will make note that in the footer from the email It had 下午 2:02 (下午/xiawu means afternoon in chinese) so this information has come from china and I believe the first point of contact team is trying to say is that the port is not intended for any use or purpose but have done so in poor English however this is an assumption.

Personal thoughts:
I suspect that they are for development/recovery use as I noticed on a picture of a stripped down OCZ Vertex 3 SSD they had 4 un-soldered points on the board in the same location as OP's SSD labeled vcc, tx, rx, gnd

*

*VCC - Power supply pin

*GND - Ground

*TX - Transmission of data

*RX - Receives data

Note: This SSD is using the same NAND controller SandForce 2281 as the drive shown by OP as per OCZ Vertex 3 tech specs

A: The pins are manufacturer specific and used by both the manufacturer and data recovery experts to access the System Area of the drive.  Sometimes those pins support a serial interface, in which case you can attach a 4 pin cable (power, ground, transmit, receive) and talk to the hard drive.  Data Recovery hardware, such as a PC-3000, might use these pins to update/repair the firmware on drive, remove an ATA password, or modify/clear the G-list.


text:
Q: how can we decrypting 128 bit AES encrypted text in php with cipher mode ECB and padding mode PKCS7 i fetched such problem in my project
how can we decrypting 128 bit AES encrypted text in php  with cipher mode ECB and padding mode PKCS7

A: You can probably use mcrypt.
But may I ask why you're encrypting with ECB mode at all? Remember the known problems with that?

A: mcrypt_decrypt('rijndael-128', $key, $data, 'ecb');

You will have to manually remove the padding.


text:
Q: Htaccess - redirect every request to a single page. Side effects? I am creating my own mvc framework to use in little projects and by default, I am rewriting the url so that every single request goes to index.php. Index.php is only 4-5 lines, which calls the application class and then, the application class calls the corresponding controller and so on.
Basically, this is my htaccess file and index.php:
Options +FollowSymLinks
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?rt=$1 [L,QSA]

index.php:
<?php
include 'config.php';
$app = new Application();
?>

What I'd like to learn is whether this method has or could have any negative effects in the future in terms of speed and bandwidth. I appreciate your answers and comments.

A: Why redirect and not url rewrite?
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

as for example, this is used by a lot of applications/websites, and you have absolute control of the URL accessed.
And yes, redirecting is another call to the server.

A: If the class is there just to wrap you bootstrap stage, then it is pointless. simply have a plain file, which initializes application, load configuration and does all the wiring.
You could also want the index.php file to only contain one line: something that includes file outside DOCUMENT_ROOT. This way, if something goes tits-up with PHP extension, you won't show everyone your DB password and other sensitive details about your code.
As for your current .htaccess setup - no , it will not cause any additional bandwidth usage, but you might think about utilizing browser's cache for image and other assets.


text:
Q: update database when I change in dataGridView I m new in VB. I want to update my database when I make any change in dataGridView. Can anyone give me details about this?
the scenario is I will change value from datagridview and after I click update button I should change the database value.code is
Private Sub btnModify_Click(sender As Object, e As EventArgs) Handles btnModify.Click
    Dim cmdbuilder As New Odbc.OdbcCommandBuilder(da)

    ds = gridDisplay(cmbxState.SelectedItem)

    Try
        da.Update(ds.Tables("districtMaster"))

    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

A: You must define an InsertCommand in your DataAdapter. Then you'll need to call the Update method of the adapter when you want to save the changes.
Populating the DataGridView on Form Load
Private myConString As String
Private con As OleDbConnection = New OleDbConnection
Private Dadapter As OleDbDataAdapter
Private DSet As DataSet

Private Sub Form_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    myConString = "Your connection string here"
    con.ConnectionString = myConString
    con.Open()
    Dadapter = New OleDbDataAdapter("SELECT * from Table", con)
    DSet = New DataSet
    Dadapter.Fill(DSet, "Table")
    DataGridView1.DataSource = DSet.Tables("Table")
    con.Close()
End Sub

Updating the database
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Using con = new New OleDbConnection(myConString)
    con.Open()
    Dadapter.Update(DSet, "Table")
End Using
End Sub

From the Docs:
http://msdn.microsoft.com/en-us/library/system.data.common.dataadapter.update%28v=VS.100%29.aspx


text:
Q: How do I iterate a list and then return a new column using sqlContext in databricks I am trying to iterate through a list and create a df using a SQL query. Since sqlContext.sql returns a SQL db I figured using union would be a decent idea to combine them all into one db but I am running into a problem that I described below. If anyone has any ideas on how to do this better or how to fix it I would really appreciate it.
This is the loop I am using to iterate the list:
for idx, f in enumerate(row_list):
  if idx ==0:
     test = (sqlContext.sql(f" SELECT concat(domain,'_',quality,'.',sink),tablename FROM config.uploader LIKE LOWER ('%{f}%'))")
  else:
     test = (sqlContext.sql(f" SELECT concat(domain,'_',quality,'.',sink),tablename FROM config.uploader LIKE LOWER ('%{f}%'))")
  df = df.unionAll(test)

The expected output would be as such if say tables are named blah,blah1,blah2,blah3 etc...
datalake_table    | tablename
------------------+----------
leads_silver.blah | blah
leads_bronze.blah1| blah1
leads_gold.blah2  | blah2
etc...

Instead, the output I get is like this
datalake_table     | tablename
-------------------+----------
leads_bronze.blah4 | blah4
leads_bronze.blah4 | blah4
leads_bronze.blah4 | blah4
leads_bronze.blah4 | blah4
leads_bronze.blah4 | blah4
leads_bronze.blah4 | blah4

Basically, the last item in the list is writing over everything else I can't figure out what I did wrong could anyone help?

A: Your , implementation seems correct , however can also collect each test result inside a list. Then finally union them to get your desired results.
from functools import reduce

res = []

for idx, f in enumerate(row_list):
  if idx ==0:
     test = (sqlContext.sql(f" SELECT concat(domain,'_',quality,'.',sink),tablename FROM config.uploader LIKE LOWER ('%{f}%'))")
  else:
     test = (sqlContext.sql(f" SELECT concat(domain,'_',quality,'.',sink),tablename FROM config.uploader LIKE LOWER ('%{f}%'))")

  res += [ test ]

df = reduce(lambda x,y: x.union(y),res)


text:
Q: How to change Rectanlge Left/Top/Right/Bottom I have two rectangles InnerRectangle and OuterRectangle. I want to verify if four corners of InnerRectangle i.e, Lett, Top, Right, Bottom are completely inside of
OuterRectangle. If those are outside I want change the ones that are outside. If I change Left/Top/Right/Bottom, how much should I change the width or height?
Please let me know how to implement this.
if (InnerRectangle.Left < OuterRectangle.Left)
{
    // what should I put here
}
if (InnerRectangle.Top < OuterRectangle.Top)
{
    // what should I put here
}
if (InnerRectangle.Right < OuterRectangle.Right)
{
    // what should I put here
}
if (InnerRectangle.Bottom < OuterRectangle.Bottom)
{
    // what should I put here
}

Appreciate your help..

A: To check whether rectangle InnerRectangle is completely contained inside OuterRectangle:
if (OuterRectangle.Contains(InnerRectangle))
{
    // ...
}

To fix InnerRectangle so that it is really inside OuterRectangle:
InnerRectangle = InnerRectangle.Intersect(OuterRectangle);


text:
Q: div same height with floats It seems this issue has been addressed earlier, but none of the solutions seem to work for me.
My current situation:
container div set as display:table-row
children are set as display:table-cell
all the children now have the same height, as I want to.
My problem:
when the window gets resized, not all the divs are visible. How can I make sure the divs are always visible. examples:
Resize progress:
DIV#1 ---- DIV#2 ---- DIV#3 ---- DIV#4 ---- DIV#5

DIV#1 ---- DIV#2 ---- DIV#3 ---- DIV#4
DIV#5

DIV#1 ---- DIV#2 ---- DIV#3
DIV#4 ---- DIV#5

http://jsfiddle.net/9BC53/2/
I hope this can be solved without the use of JavaScript
EDIT I don't want to specify any height. The div's must be as long as the longest sibling.

A: There is no need to use display: table-row or display: table-cell.
CSS
div#main {
    display: inline-block;
    /* to clear float */
    overflow: hidden;
}
div.elem {
    float: left;
    background:#ff0000;
    /* same height as intented */
    text-align: center;
    width: 80px;
}
div.elem div {
    width:40px;
}
div#one div {
    background:#111;
}
div#two div {
    background:#444;
}
div#three div {
    background:#777;
}
div#four div {
    background:#aaa;
}
div#five div {
    background:#ddd;
}

Javascript:
var main = document.getElementById('main');
var height = main.offsetHeight + "px";
var children = main.children;
for (var i = 0; i < children.length; i++) {
    var c = children[i];
    c.style.height = height;
}

Working Fiddle


text:
Q: CodeValue (Lookup) Table into multiple Entities I am beginning work to re-write a software that would deal with a pre-existing SQL 2005 database (that was originally created in SQL 6.5, then migrated to SQL 2005).
One of the tables is a "lookup table" (contains code-values for multiple picklists (statuses, Qualifiers, Types of this, types of that, etc).  In all, 16 categories.
dbo.ReferenceItem
   ReferenceItem_ID int (PK)
   ReferenceTable_ID int (items for a picklist have the same ID, 16 different values - for the 16 picklists)
   Description varchar(30) --> This is the display value for the picklist
How would I go about making separate entities in EF 5.0 ?
I would like to have an EF entity for each category (ReferenceTable_ID) within the ReferenceItem table.
I was looking into Table-per-Hierarchy Inheritance, but hit a wall in the Table Mapping.
Could anyone gently guide me as to how this could be accomplished within EF 5 ?   If possible, I don't want to modify the database.
Thank you in advence.


text:
Q: Check string for email with regular expressions or other way I've tried the following code, but it gives me nomatch.
re:run("qw@qc.com", "\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b").

regexp i got here http://www.regular-expressions.info/email.html
EDITED:
Next doesnt work to
re:run("345345", "\b[0-9]+\b").

If you got just en email in string when that one will match
re:run("qw@qc.com", "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$").

A: I hesitate to answer this question, since I believe it relies on an incorrect assumption - that you can determine whether an email address is valid or not with a regular expression.  See this question for more details; from a short glance I'd note that the regexp in your question doesn't accept the .museum and .рф top-level domains.
That said, you need to escape the backslashes.  You want the string to contain backslashes, but in Erlang, backslashes are used inside strings to escape various characters, so any literal backslash needs to be written as \\.  Try this:
3> re:run("qw@qc.com", "\\b[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}\\b").
{match,[{0,9}]}

Or even better, this:
8> re:run("qw@qc.com", "\\b[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*\\b").
{match,[{0,9}]}

That's the regexp used in the HTML 5 standard, modified to use \\b instead of ^ and $.

A: Looks like you need a case-insensitive match ?
Currently [A-Z0-9._%+-] (for example) only matches upper-case characters (plus numbers etc).
One solution is to specify [A-Za-z]. Another solution is to convert your email address to uppercase prior to matching.


text:
Q: How to generate slugs? I have the following situation. I accidentally updated post_name column in wp_posts tables for all rows. Now I need to update those back somehow. I have researched that WP uses this function to generate slugs wp_unique_post_slug.
Can anyone please provide me with steps how to do this? I have no idea of PHP, plugins etc. What will I need to do this?

A: As @toscho already answered here, yes this is possible.
You just need to copy this code into the functions.php of your theme, and there you go.
// get all posts
$posts = get_posts( array (  'numberposts' => -1 ) );

foreach ( $posts as $post )
{
    // check the slug and run an update if necessary
    $new_slug = sanitize_title( $post->post_title );

    // use this line if you have multiple posts with the same title
    $new_slug = wp_unique_post_slug( $new_slug, $post->ID, $post->post_status, $post->post_type, $post->post_parent );

    if ( $post->post_name != $new_slug )
    {
        wp_update_post(
            array (
                'ID'        => $post->ID,
                'post_name' => $new_slug
            )
        );
    }
}

You can also create a plugin for that, if you create a yourplugin.php file in your plugins folder, with a valid plugin header and the above code:
<?php
    /*
    Plugin Name: Your Plugin
    Plugin URI: http://www.example.com
    Description: description
    Version: 0.1
    Author: thatsyou
    Author URI: http://www.yourdomain.com
    License: MIT
    */

    //yourcode
?>

Please be aware that if you copy this code into your functions.php or your activate the plugin, it is executed all the time. You can get some ideas on how to execute code only once here: Best Practices


text:
Q: MySQL to refer to row from same table I have a table named tblMitigation, which has several columns:
Headcode, Time, Origin, Destination, Mitigation, Next Service.
The Next Service column refers to another Headcode value in the same table. How can I use MySQL to look up the Mitigation column for that other service?
Thanks
Chris

A: You could JOIN the table to itself. Use a LEFT JOIN in case there is no Next Service as yet. The COALESCE will ensure the value of Next_Mitigation is something different in that case e.g. N/A
SELECT current.*, COALESCE(next.Mitigation, 'N/A') AS Next_Mitigation
FROM tblMitigation current
LEFT JOIN tblMitigation next ON next.Headcode = current.`Next Service`


text:
Q: Non-inverting Lowpass Filter with Capacitor in Feedback I am looking for a circuit that I expected to find everywhere but I don't. The "active" lowpass filter I often see in the web uses an RC filter with a buffer in series.

simulate this circuit – Schematic created using CircuitLab
The alternativ version I found quite often is, in my opinion, not a true one pole lowpass but a lowpass shelving filter. The capacitor in the feedback is paired with a parallel resistor.

simulate this circuit
Now my question is, why don't I see the second variant without the additional parallel resistor in the feedback path more often? Are there any major disadvantages to the RC - buffer implementation?

A: If you are asking why you don't see the second circuit with no R2, that's because it has (with ideal components) infinite DC gain.  At DC the impedance of C1 is infinite and the gain will be (one plus) the ratio of the feedback impedance to R3.
Also, in this non-inverting configuration, the minimum stop-band gain is unity.
In the inverting configuration, you do in fact sometimes see the circuit without the parallel resistor, when integrating low-frequency signals over a finite period of time.   With a short enough period of time, the very high DC gain will not have time to dominate, assuming the DC component is sufficiently small.


text:
Q: Read Windows Logged in User to understand role I want to know the best way to implement it. I have a asp.net web app which does not have any login page/options. But I need to populate different options in the web page based on User roles (admin, Member etc..).
How can I know what is the role of current user logged in on the windows machine.
Can I do this in my Java script page? or is there a way to retrieve it from IIS?

A: You can fetch certain details using environment variables. Follow - https://weblogs.asp.net/owscott/viewing-all-server-variables-for-a-site
To test it out, create a test.aspx page under the same application on IIS and copy-paste the C# code mentioned in the article. Try accessing the page from a client machine and check what results you get.


text:
Q: Bcrypt em java e php não corresponde Eu tenho uma aplicação em Php que faz um registo de uma pessoa e quando a pessoa poe a password, a password fica armazenada na base de dados em forma de hash, com o seguinte código
password_hash($password, PASSWORD_BCRYPT)

depois, tenho uma aplicação em Java e queria verificar uma password com a hash que está na base de dados, eu pus o seguinte código
BCrypt.hashpw(passTxt.getText(),BCrypt.gensalt())

o problema é que não correspondem as hashes. já me disseram que pode ser do SALT que tem que ser o mesmo, mas como faço para por o mesmo SALT?

A: em PHP
<?php
 /**
 * Note that the salt here is randomly generated.
 * Never use a static salt or one that is not randomly generated.
 *
 * For the VAST majority of use-cases, let password_hash generate the salt randomly for you
 */
    $options = [
        'cost' => 11,
        'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
    ];
echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options)."\n";
?>

Em Java jBCrypt
// Hash a password for the first time
String hashed = BCrypt.hashpw(password, BCrypt.gensalt());

// gensalt's log_rounds parameter determines the complexity
// the work factor is 2**log_rounds, and the default is 10
String hashed = BCrypt.hashpw(password, BCrypt.gensalt(12));

// Check that an unencrypted password matches one that has
// previously been hashed
if (BCrypt.checkpw(candidate, hashed))
    System.out.println("It matches");
else
    System.out.println("It does not match");

pode ser o salt diferente então estou colocando como mudar o salt dos 2.
fonte stack inglês
O bcrypt normal não vai resultar o que você busca nativamente mas a jBcrypt pode lhe trazer olhar o stack em ingles lhe traz o resto da resposta.


text:
Q: Why we can use the divergence theorem for electric/gravitational fields if they have singular point? If we were to calculate the surface flux of the total field, we would only require the vector field to be continuous on the boundary. But in order to replace the surface integral by a volume integral of the divergence, don't we require that the field is continuous a have derivatives in the whole volume?
But the electric and gravitational have singularities at the place of every point charge, I would like to know why we can still use the divergence theorem in this case?

A: The divergence theorem is stated (using vector calculus notation)
$$\iiint_{V} \vec{\nabla} \cdot \vec{F}\ dV = \iint_{\partial V} \vec{F} \cdot \vec{n}\ dS$$
For some $C^1$ vector field $\vec{F}$. If we consider, say, the electric field of a point particle :
$$\vec{E} = \alpha \frac{\vec{e_r}}{r^2}$$
for some constant $\alpha$, then $E$ isn't differentiable (or even defined) at $r = 0$.
So here are two ways of dealing with this :
Remove the point
We can simply consider our volume to be $V = B_{0, R} \setminus B_{0, \varepsilon}$, and then consider the limit $\varepsilon \to 0$. We could take $\varepsilon = 0$ directly, but then we'd be integrating a divergence on a set of measure zero, which is also not a great idea.
The boundary is just the two spheres that delimit those regions. Let's see what happens. First, using the formula for the divergence in spherical coordinates (this is simple enough since there is radial symmetry),
\begin{eqnarray}
\vec{\nabla} \cdot \vec{E} &=& 0
\end{eqnarray}
This isn't too surprising : outside of $r = 0$, there are no charges. On the other hand, consider the integral on the boundary. The normal vector is simply $\pm\vec{e}_r$, the sign depending on which sphere we're considering (the normal vector has to point away from the volume).
\begin{eqnarray}
\iint_{S_{0,R} \cup S_{0, \varepsilon}} (\vec{E} \cdot \vec{n})\ r^2 \sin\theta d\theta d\varphi &=& \iint_{S_{0,R}} (\vec{E} \cdot \vec{n})\ r^2 \sin\theta d\theta d\varphi + \iint_{S_{0, \varepsilon}} (\vec{E} \cdot \vec{n})\ r^2 \sin\theta d\theta d\varphi\\
&=& \iint_{S_{0,R}} E_r\ r^2 \sin\theta d\theta d\varphi - \iint_{S_{0, \varepsilon}} E_r\ r^2 \sin\theta d\theta d\varphi
\end{eqnarray}
The $r^2$ of the integral volume measure cancels out with the $r^2$ from the field, and everything only depends on the solid angle of our spheres. As both of them are full spheres, this is just
\begin{eqnarray}
4 \pi - 4 \pi = 0
\end{eqnarray}
All is well : for any neighbourhood that doesn't include the origin, at an arbitrarily small distance $\varepsilon$, the divergence theorem holds. This doesn't help us much with computing though.
Use distributions
Functions aren't well-equipped to deal with point-charges. What we technically have is that those integrals should be equal to the charge $Q$, but as the charge distribution is on $r = 0$, a set of measure zero, any integral should be zero. So instead, we consider the Dirac delta distribution.
A distribution is a linear map from smooth functions of compact support to $\mathbb{R}$. ie, if you have a distribution $f$ and a smooth function of compact support $\phi$, then $f[\phi] \in \mathbb{R}$. There is a map defined thusly : if $f$ is a function, then you can define a distribution from it using the identity
$$f[\phi] = \int f(x) \phi(x) dx$$
In particular, the Dirac delta function is defined by
$$\delta_{\vec{x}}[\phi] = \phi(\vec{x})$$
Applying the Dirac distribution on a function returns the value of that function at a fixed point $\vec{x}$. In our case, this is just $\delta_0$.
Derivatives on distributions (called weak derivatives) are defined by the fact that, if $f$ is a distribution, $f'$ acts on $\phi$ as
$$f'[\phi] = - f[\phi']$$
This corresponds to integrating by part. Now let's consider $F$ as a distribution (or three distributions for every component, this doesn't matter too much). The left-hand of the divergence theorem would roughly correspond to $(\vec{\nabla} \cdot \vec{E})[\phi]$. Now $\vec{E}$ itself is a function, as divergent as it may be. We can find its weak derivative by considering the formula above. Since $E_r$ is a function (We can drop the other components since they are all zero)
\begin{eqnarray}
\frac{1}{r^2} \frac{\partial (r^2 E_r)}{\partial r} [\phi] &=& - E_r [\partial_r \phi]\\
&=& -\int \frac{\alpha}{r^2} (\partial_r \phi ) r^2 \sin\theta dr d\theta d\varphi\\
&=& -\int (\partial_r \phi) \sin\theta dr d\theta d\varphi\\
&=& -4\pi [\phi]^\infty_0\\
&=& 4\pi \phi(0)
\end{eqnarray}
This is because 1) the fundamental theorem of calculus 2) as the function is of compact support, $\phi(\infty) = 0$. Therefore, the derivative of $E_r[\phi]$ gives $4\pi \phi(0)$, so it is $4\pi \delta_0$.
Of course, usually physicists pretend that $\delta$ is a function, with the property
$$\int \delta(x) f(x) dx = f(0)$$
While this is Bad, it makes everything much simpler to deal with. There is a proper theory to deal with the divergence theorem with distributions, but I'll leave you to read it if you really want the proper proof of this. For the more casual proof, we simply have that
\begin{eqnarray}
\iiint_{B_{0,R}} \vec{\nabla} \cdot \vec{E}\ dV &=& \iiint_{V} 4\pi \alpha \delta(x)\ dV\\
&=& 4\pi \alpha\\
\iint_{\partial S_{0,R}} \vec{E} \cdot \vec{n}\ dS &=& \iint_{\partial S_{0,R}} \frac{\alpha}{R^2} \ R^2 \sin\theta d\theta d\varphi\\
&=& 4\pi \alpha
\end{eqnarray}
All is well and good.
A third method somewhere between the two would have been to consider the limit of a charge distribution which approaches that of a point charge, such as a normal distribution in the limit $\sigma \to 0$, as distributions can also be considered as the limit of sequences of functions as well.

A: Proceed as follows.
First accept that the notion of a point charge (with a finite amount of charge but no volume) is itself a mathematical abstraction which may or may not be useful or appropriate in dealing with any given piece of analysis.
Next, treat a small charged region, say a sphere, with finite charge density and finite fields.
Finally, let the size of that region tend to zero and retain whichever are the leading terms in the quantities you are interested in.


text:
Q: Bluetooth notification for incoming file recently I wanted to send one file from my phone to my Ubuntu 18.04 notebook, everything went well except that the PC didn't ask me if I wanted to recieve the file, it just began recieving. What if that was some malicious file named same as the file I wanted to send(MITM attack, or something)?
Is that normal?


text:
Q: Copy file from system storage(/data/data...) to external storage I want to copy a file from /data/data... to the external SDCARD! However, i'm finding this problem:
Log message: 04-04 12:01:19.271: DEBUG/Carburant(9623): /username.usercar.settings.dat (No such file or directory)
I guess that i can't simply access to this file without an "extra" code.
Here is my code(the necessary lines):
File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File (sdCard.getAbsolutePath() + "/Carburant/");
    dir.mkdirs();
    copyfile(nom,sdCard.getAbsolutePath() + "/Carburant/storeddata.dat");

public Import(Context context,String nom) {
        this.context = context;
        this.nom=nom;
       }

The lines where the function is called:
case R.id.exporter:
            final SharedPreferences preferences = PreferenceManager
            .getDefaultSharedPreferences(context);
    String fileName = getResources().getString(R.string.fileName);
    fileDir = "" + preferences.getString("login", "") + "."+ preferences.getString("marque", "") + ".";
    Import myImport = new Import(this,fileDir+fileName);
            myImport.transfer();
            return true;

Android Manifest(necessary code):
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="carburant.android.com"
      android:versionCode="1" android:versionName="0.1">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-sdk android:minSdkVersion="8" />

Copy file func:
private void copyfile(String srFile, String dtFile){
        try{
            File f1 = new File(srFile);
            File f2 = new File(dtFile);
          InputStream in = new FileInputStream(f1);
          OutputStream out = new FileOutputStream(f2);

          byte[] buf = new byte[4096];
          int len;
          while ((len = in.read(buf)) > 0){
            out.write(buf, 0, len);
          }
          in.close();
          out.close();
          Toast.makeText(context, "Export effectué", Toast.LENGTH_SHORT).show();
        }
        catch(FileNotFoundException ex){
            Toast.makeText(context, "File Not found", Toast.LENGTH_SHORT).show();
            String x=ex.getMessage();
            Log.d("Carburant", x);
        }
        catch(IOException e){
            Toast.makeText(context, "Echec", Toast.LENGTH_SHORT).show();
        }
      }

So, what misses?
Thanks.

A: To get you file located in the "files" dir (assuming its name is settings.dat), use the following method:
String filePath = this.getFilesDir().getAbsolutePath() + File.separator + "settings.dat";
Import myImport = new Import(this,filePath);

If the file itself is a raw resource, follow the answer to this question to copy it.
(make sure you have permission to write to external storage...)


text:
Q: Creating a custom quasi-Newton Optimizer in Python for Tensorflow I am trying to optimize a convolutional neural network using both Adam and L-BFGS for comparison purposes. However, I am having a hard time implementing the wrap around function in order to be able to use a Keras Sequential model inside the TensorFlow Probability lbfgs_minimize function (https://www.tensorflow.org/probability/api_docs/python/tfp/optimizer/lbfgs_minimize).
Can anyone please provide me with some direction, here is the reference on the wrap around function:
https://pychao.com/2019/11/02/optimize-tensorflow-keras-models-with-l-bfgs-from-tensorflow-probability/


text:
Q: How do I convert 4 bytes of a ByteString to an Int? How can I convert a ByteString to an Int?
I have the following 4 bytes that I want to convert (it represents the size in bytes of a .bmp file):
"v\SOH\NUL\NUL"
which I know equals 374

A: For binary parsing, have a look at the binary package - http://hackage.haskell.org/package/binary
It defines a Get monad, so you can write something like:
data Header { ftype :: ByteString, size_ :: Word32, reserved_ :: ByteString, offset_ :: Word32 }
parseHeader = do
  ft <- getByteString 2
  size <- getWord32le
  reserved <- getByteString 4
  offset <- getWord32le
  return $ Header ft size reserved offset

and later:
main = do
  bytes <- hGetContents handle
  let header = runGet parseHeader bytes
  ...

A: I managed to get a small functions working that demonstrates the idea
import qualified Data.ByteString.Lazy.Char8 as B

lEBsToInt :: B.ByteString -> Int -- littleEndianByteStringToInt
lEBsToInt bs = let bsI = B.take 4 bs in -- 1.
    fst $ B.foldl (\(s,i) b -> let shiftBy = i * 8 in -- 2.
        (s + (ord b `shiftL` shiftBy), i + 1)) (0,0) bsI --3.

*

*Get the first 4 bytes of a ByteString

*Calculate the amount to shift by

*Fold over the ByteString, summing the result of shifting the current byte by the current offset

lEBsToInt "v\SOH\NUL\NUL" = 374
This could definitely be improved, but I was happy with it


text:
Q: To what values are GLSL variables initialized by default? I know that in c and c++, the variables are uninitialized by default. On the other hand in java they are initialized to 0 or null by default.
What is the corresponding default initialization in GLSL?
Specifically, what are the default values when we create the following variables?
int val;
vec4 arr[20];

A: It depends on the storage qualifier of the variable in question. uniform variables are always initialized to 0/false. const-qualified variables cannot be uninitialized. All other uninitialized variables either get their contents from external resources (UBOs and the like) or have undefined values.


text:
Q: Como retornar várias valores de uma classe? Segue código:
Controller:
public ActionResult teste1(int num1, int num2)
{
  // Aqui quero obter os valores da variável model1 e model2  da classe MyClass
  var result = MyClass.Teste2(num1 , num2);
}

Model:
public class MyClass
{
  public static Teste2(int num1, int num2)
  {
     var model1 = new AspNetUser();
     var model2 = new AspNetUser1();

     using (var ctx = new Entities())
     {
        model1 = ctx.Table.Where( x => ...).FirstOrDefault();
        model2 = ctx.Table.Where( x => ...).FirstOrDefault();
     }

     //aqui: como retornar com "model1" e "model2" para ação "ActionResult" onde tem variável "result"?
  }
}

Como posso retornar com variáveis model1 e model2 para variável result ? Porque o AspNetUser e AspNetUser tbm são classes criado com ADO.NET Entity Data Model. Já tentei fazer um ToArray ou ToList e não consegui. Estou tendo dificuldade de retornar.
Alguém pode me ajudar ?

A: A maneira correta é definindo um ViewModel:
public class UsuariosViewModel
{
    public AspNetUser Model1 { get; set; }
    public AspNetUser1 Model2 { get; set; }
}

Ou seja, você pode fazer um Helper assim (Model é outra coisa):
public static class MyClass
{
  public static UsuariosViewModel Teste2(int num1, int num2)
  {
     using (var ctx = new Entities())
     {
        return new UsuariosViewModel
        {
            Model1 = ctx.Table.FirstOrDefault(x => ...),
            Model2 = ctx.Table.FirstOrDefault(x => ...)
        };
     }
  }
}

E o retorno para a View:
public ActionResult teste1(int num1, int num2)
{
  // Aqui quero obter os valores da variável model1 e model2  da classe MyClass
  var result = MyClass.Teste2(num1 , num2);
  return View(result); // result será UsuariosViewModel.
}


text:
Q: C# Winforms change taskbar icon I have an old legacy system that uses Winforms and is published with the built in One click,
I look after 3 different installs and each one has its own database it connects to, so its been set up that when a different system is click, it check isCompany1 and will set the Favicon accordingly
so when depoyment is done in the application window the Icon and Manifest is set to the correct ICO, when installed the .exe icon will be what is set there,
However i am trying to bring these all inline as when we debug a drop asks which database we would like to connect to, and depending on that it will set things up differently.
When running in VS the icons in the taskbar will change accoring to the dynamic Favicon however when its depolyed with this new selection it wont change, (it will change once on first load, then wont again)
The issue is some users need access to the different instances so would like different icons at the bottom, but its not changing the task menu, but everything else such as ALT-TAB and the control panel icon is changing,
all forms link into a baseform and call this :
if (App.IsCompany1)
{
    this.Icon = new Icon("Resources\\Company1.ico");
}
else if (App.Company2)
{
    this.Icon = new Icon("Resources\\Company2.ico");
}
else if (App.Company3)
{
    this.Icon = new Icon("Resources\\Company3.ico");
}

AS i said this will change everything but not the Taskbar, but will from VS debugging,
I have made sure the .ico has all sizes, by writing their sizes on each one, and they display correctly the Taskbar and ALT-TAB both use 32x32

A: If it's any consolation, I couldn't reproduce your complaint.
I put 3 icons in resources, a single button on a form, this code:
    private int iconum = 0;
    private Icon[] icons = new[] { Properties.Resources.icon1, Properties.Resources.icon2, Properties.Resources.icon3 };

    private void button1_Click(object sender, EventArgs e)
    {
        this.Icon = icons[iconum++ % icons.Length];
    }

And it cycled through the icons in the main form title bar and the windows task bar over and over on every button click (made sure to run a release built exe too, not a debug start):

Note: the thing in the top right is my taskbar


text:
Q: Как узнать в Си расширении, сколько всего аргументов передано в Питон функцию, все их просуммировать и вернуть результат? Привет. Самообучаюсь написанию модулей на C для Python по этому адресу https://docs.python.org/3/c-api/arg.html (скоро по работе может пригодиться).
Легко написал пример модуля с функцией add, которая суммирует два целых числа.
Как получить количество аргументов, переданных в функцию, чтобы она все их просуммировала и вернула результат? Что и как изменить в коде?
mymod.c:
#include <Python.h>

static PyObject *
mymod_add(PyObject *self, PyObject *args)
{
    int a = 0, b = 0;
    PyArg_ParseTuple(args, "i|i", &a, &b);
    return Py_BuildValue("i", a + b);
}

static PyMethodDef mymod_methods[] = {
    {"add",  mymod_add, METH_VARARGS, "The method adds two ints."},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef mymod_definition = {
    PyModuleDef_HEAD_INIT,
    "mymod",
    "My test Python module.",
    -1,
    mymod_methods
};

PyMODINIT_FUNC PyInit_mymod(void)
{
    Py_Initialize();
    return PyModule_Create(&mymod_definition);
}

test.py:
import sys
sys.path.append('.')
import mymod
print(mymod.add(1, 2))
print(mymod.add(1))

Makefile (на всякий случай):
all: mymod.so

mymod.so: mymod.c Makefile
    gcc -shared -fPIC -o mymod.so mymod.c `python3-config --includes --libs --cflags --ldflags`

clean:
    -rm mymod.so

Кроме прочего, меня смущает, что когда не передаешь второй аргумент, функция PyArg_ParseTuple все равно его поганит непонятно чем, хотя он изначально 0. Как с этим бороться?
Упс, PyArg_ParseTuple перестала поганить второй аргумент. Наверное, забыл сделать make перед запуском test.py. Но это не снимает основного вопроса.

A: Для сравнения, вот C версия, реализующая Питон-функцию:
def add(*args, init=0):
    for s in args:
        init += s
    return init

которая пытается ссылки считать (чтобы память не утекала) и не игнорировать возможные ошибки (чтобы исключение получить, а не segfault):
static PyObject* mymod_add(PyObject *self, PyObject *args, PyObject *kwds)
{
  // parse only keyword args
  PyObject *init = NULL;
  static char *kwlist[] = {"init", NULL};

  PyObject *emptytuple = PyTuple_New(0);
  if (emptytuple == NULL)
    return NULL;
  int ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|O", kwlist, &init);
  Py_DECREF(emptytuple);
  if (!ret)
    return NULL;

  if (init == NULL) { // default
    init = PyLong_FromLong(0); // init=0
    if (init == NULL)
      return NULL;
  }
  else {
    Py_INCREF(init); // get ownership
  }

  // sum args
  Py_ssize_t tuplesize = PyTuple_Size(args);
  Py_ssize_t i = 0;
  for ( ; i < tuplesize; ++i) {
    PyObject *item = PyTuple_GetItem(args, i); // borrowed ref
    if (item == NULL) {
      Py_DECREF(init);
      return NULL;
    }

    //NOTE: assume tuple is immutable: no Py_INCREF(item)/Py_DECREF(item)
    PyObject *temp = PyNumber_InPlaceAdd(init, item); // new ref
    Py_DECREF(init);
    if (temp == NULL)
      return NULL;
    init = temp;
  }
  return init;
}

static PyMethodDef module_functions[] = {
  {"add", (PyCFunction)mymod_add, METH_VARARGS | METH_KEYWORDS, "add arguments"},
  {NULL, NULL, 0, NULL}
};

A: Что типа этого надо:
static PyObject *
mymod_add(PyObject *self, PyObject *args) {
    double sum = 0;
    PyObject *iterator = PyObject_GetIter(args);
    if (iterator == NULL)
        return -1;

    while (true) {
        PyObject* value = PyIter_Next(iterator);
        if (value == NULL)
            break;
        sum += PyLong_AsDouble(value);
        Py_DECREF(value);
    }
    Py_DECREF(iterator);
    return PyLong_FromDouble(sum);
}

A: Вариант с итератором, конечно, интереснее. Но приведу и свой код.
#include <stdio.h>

static PyObject *
mymod_add(PyObject *self, PyObject *args)
{
    PyObject *item;
    int size;
    long sum = 0;

    size = PyTuple_Size(args);
    fprintf(stdout, "Arguments count: %d\n", size);

    for(int i=0; i < size; i++) {
        if(PyLong_Check(item = PyTuple_GetItem(args, i)))
            sum += PyLong_AsLong(item);
        else
            fprintf(stderr, "Failed arg № %d\n", i);
    }
    return Py_BuildValue("l", sum);
}


text:
Q: Android Studio - Need to edit Manifest, Menu XML files manually I am new to Android studio. Unlike eclipse with ADT plugin, in Android studio I end up manually writing full XMLs for menus, manifest files etc. I am not getting the GUI to enter values so that it will automatically populate XML files. Only text view view is getting displayed. I believe there should be a plugin or a way similar to eclipse GUI to edit these files.
I spent enough time searching for it but could not find anything useful.Any thoughts?


text:
Q: eclipselink metamodel with gradle and groovy How i can get generate metamodel classes from org.eclipse.persistence.jpa.modelgen.processor in gradle?
In maven i use someone like
<plugin>
     <artifactId>maven-compiler-plugin</artifactId>
     <dependencies>
         <dependency>
             <groupId>org.eclipse.persistence</groupId>                 <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
             <version>${eclipselink.version}</version>
         </dependency>
      </dependencies>
      <configuration>
          <compilerArgs>
              <compilerArg>-Aeclipselink.persistenceunits=unit-name
              </compilerArg>
          </compilerArgs>
      </configuration>
 </plugin>
Thanks for any advice.

A: Probably too late for you to be useful, but wanted to share how I solved the problem. The following will generate metamodel every time you compile. Note, if you remove the line with delete, the compiler will probably complain.
ext {
    metamodelPath="$buildDir/generated-sources/metamodel"
}
compileJava {

    doFirst {
        file(metamodelPath).delete()
        file(metamodelPath).mkdirs()
    }
    options.compilerArgs += ['-Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml', '-s', metamodelPath ]
}

A: Unfortunately the previous solution does not work for me. But it was a good starting point. The dependencies closure is missing.
This works under Gradle 5.6.1 and Groovy 2.5.4:
ext {
    eclipselink='2.7.3'
    metamodelPath="$buildDir/generated/sources/metamodel/java/main"
    persistenceXMLLocation="src/main/resources/META-INF/persistence.xml"
}

compileJava {
    doFirst {
        file(metamodelPath).delete()
        file(metamodelPath).mkdirs()
    }
    options.compilerArgs += ["-Aeclipselink.persistencexml=${new File(project.projectDir, persistenceXMLLocation).absolutePath}", '-s', metamodelPath]
}

dependencies {
    api "org.eclipse.persistence:eclipselink:$eclipselink"
    annotationProcessor "org.eclipse.persistence:org.eclipse.persistence.jpa.modelgen.processor:$eclipselink"
}


text:
Q: How to implement an "augmented reality" feature detection on Android with Javascript? I'm currently implementing a web-app with a button that opens the native "augmented reality"-view directly by clicking on a link. The link, as well as the feature detection for iOS is pretty straight-forward:
function isARSupported() {
    const a = document.createElement('a');
    return a.relList.supports('ar');
}

However, I couldn't find a way on Android to check whether the browser/device supports AR or not.
Is there a way how to implement that feature detection for AR-support in Google and Firefox, on Android?


text:
Q: isinstance(object, type) is giving me an error - Also, flattening a nested list I am a beginner programmer, and I attempted to solve one of the prolog questions which was to flatten a nested list. My attempt:
a = [1, 2, 3, [1, 2, 3], 4, 5]

def flatten(list):
    new = []
    for i in list:
        new.append(','.join(int(i)) for i in list)
    for ele in list:
        if isinstance(ele, list):
            flatten(ele)
            return new
        else:
            pass
        return new

flatten(a)

I get an error saying:
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types.

I thought I implemented it correctly since I passed on ele (the object) and list (type)? It worked in the interpreter, but not here.
Also any advice for the code in terms of trying to flatten a nested list?

A: By doing def flatten(list), you used list as the name of your function parameter, which blocks access to the builtin type named list.  Use a different name for your variable.
As for how to flatten nested lists, googling that question will give you dozens if not hundreds of answers.

A: You are defining list as variable in your flatten(list) function.
Please avoid to use variable name of data type. Please change it to flatten(my_list) it will work.

A: there are some flaw in your code:
1 never use list as variable name
2 new.append(','.join(int(i)) for i in list)
   `join` wont take int type, will raise TypeError
    it should be new.append(','.join(str(i)))
3 you are using `return` once it returned , it come out of the function


text:
Q: Quasi affine scheme universal embedding Suppose $X$ is quasi affine scheme, it is well known that it open embeds in $Y=\mathrm{Spec}(\mathcal{O}(X))$. In fact, by adjunction, any map into an affine scheme factors uniquely through $Y$. Is it true that for any open embedding $X \to Z$, $Z$ affine, the induced map $Y \to Z$ is open embedding?

A: No, this is not true. Consider $X=\Bbb A^2\setminus (0,0)$, so that $Y=\Bbb A^2$. Let $Z$ be the union of the $xy$-plane and the $z$-axis inside $\Bbb A^3$. Then $X\hookrightarrow Z$ by $(x,y)\mapsto (x,y,0)$ is an open embedding, but the induced map $Y\to Z$ does not have open image.


text:
Q: Feign throw error instead of return ResponseEntity, how to go back to the caller method I would like to understand how to do with the following,
I have a microservice who need to get a product:
    @RequestMapping("/details-produit/{id}")
    public String ficheProduit(@PathVariable int id,  Model model){

      ResponseEntity<ProductBean> produit = ProduitsProxy.recupererUnProduit(id);
      model.addAttribute("produit", produit.getBody());

        return "FicheProduit";
    }

my feign class:
    @GetMapping( value = "/Produits/{id}")
    ResponseEntity<ProductBean> recupererUnProduit(@PathVariable("id") int id);

And my CustomErrorDecoder:
    @Override
    public Exception decode(String invoqueur, Response reponse) {

        if (reponse.status() == 400) {
            return new ProductBadRequestException("Requête incorrecte ");
        } else if (reponse.status() == 404) {
            return new ProductNotFoundException("Produit non trouvé ");
        }

        return defaultErrorDecoder.decode(invoqueur, reponse);
    }

What I would like to understand it's, how to get back to the caller method for do like this:

    @RequestMapping("/details-produit/{id}")
    public String ficheProduit(@PathVariable int id,  Model model){

ResponseEntity<ProductBean> productBeanResponseEntity = ProduitsProxy.recupererUnProduit(id);

        if (productBeanResponseEntity.getStatusCode() == HttpStatus.OK) {
            model.addAttribute("produit", productBeanResponseEntity.getBody());
        } else {
            **// Do something here**
        }
        return "FicheProduit";
    }

For the moment, the only wawy I found was to do like this :
        try {

            ResponseEntity<ProductBean> produit = ProduitsProxy.recupererUnProduit(id);

            model.addAttribute("produit", produit.getBody());
        } catch (ProductNotFoundException e) {
            log.error(e.getMessage());
        }

But I would like to handle of kind of error and continue the process of the caller method.
How can I handle it ?
Thanks !

A: You can write method which will catch exceptions or return product. Also it's not necessary to get ResponseEntity return type into feign client for no special reason. Snippets below:
@GetMapping(value = "/Produits/{id}")
ProductBean recupererUnProduit(@PathVariable("id") int id);

private ProductBean getProduct(int productId) {
   try {
       return produitsProxy.recupererUnProduit(productId);
   } catch (ProductNotFoundException e) {
       log.error(e.getMessage());
   }
}


text:
Q: PHP-unable to download a .pdf file from database , file content is stored in mysql database i have written a code in php which will echo a pdf file.whenever i am trying to echo that pdf,the browser page is changing into gray colors and the loading icon at the bottom left side corner is appearing and after that it fails to show that pdf file.
what i can assure you that code upto fetching the data from databse is perfect.there is no error or mistake.after fetching the data i have used following headers to echo that file.i am not sure about these headers.
$mimetype = 'application/pdf';
$disposition = 'attachment';
header('Content-type: $mimetype');
header('Content-Disposition: inline; filename="$question"');
header('Content-Transfer-Encoding: binary');
header('Content-length: ' . strlen($question));
header('Accept-Ranges: bytes');
echo "$question";

NOTE: I have used .pdf extension in content-decomposition.but that was not fruitful to me.also used readfile() function and it was also not helpful to me. Can anyone tell me what's wrong there?

A: The main reason why page is changing into gray colors is that the browser is unable to detect content type correctly.
Try this:
header("Content-type: $mimetype");
header('Content-Disposition: inline; filename="'.$question.'"'); // Filename should be there, not the content

Instead of :
header('Content-type: $mimetype');
header('Content-Disposition: inline; filename="$question"');

It seems that you have invalid quotes, so the content type is not specified correctly.
EDIT
To clear out, let's assume that $question is the binary PDF content.
That is what your code should be:
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename=anything.pdf');
header('Content-Transfer-Encoding: binary');
echo $question;

ERRORS EXPLAINED
Let's discuss your original code and your errors.
$mimetype = 'application/pdf';
$disposition = 'attachment';

// First error: you have single quotes here. So output is 'Content-type: $mimetype' instead of the 'Content-type: application/pdf'
header('Content-type: $mimetype');

// Second error. Quotes again. Additionally, $question is CONTENT of your PDF, why is it here?
header('Content-Disposition: inline; filename="$question"');

header('Content-Transfer-Encoding: binary');

// Also bad: strlen() for binary content? What for?
header('Content-length: ' . strlen($question));

header('Accept-Ranges: bytes');
echo "$question";

ONE MORE EDIT

i have another query...i want to change the filename into $year.pdf..$
  year may have values like 2007..how can i do that???

Try this :
$year = '2013'; // Assign value
header('Content-Disposition: inline; filename='.$year.'.pdf');

Instead of:
header('Content-Disposition: inline; filename=anything.pdf');


text:
Q: Double Quotes getting duplicated while writing CSV file with OpenCSV I am trying to write a simple CSVWriter code using OpenCSV library but having a strange issue with it.

Code:

public class Test {

    public static void main(String[] args) throws IOException {

       String[] header = {"ONE", "\"TWO\"", "\"THREE\"", "\"FOUR\""};

       CSVWriter writer = new CSVWriter(new FileWriter("C:/test.csv"), '|', CSVWriter.NO_QUOTE_CHARACTER);

       writer.writeNext(header);

       writer.flush();
       writer.close();
    }
}

Expected Output:

ONE|"TWO"|"THREE"|"FOUR"

Real Output:

ONE|""TWO""|""THREE""|""FOUR""
As we can see there are Double Quotes surrounding TWO, THREE and FOUR but in the output the double quotes are duplicated.
I do not want this, have tried several options and constructor of CSVWriter class but did not able to sort this out.
Anyone faced similar issue or know a way out?
Thanks

A: Got it working, the below constructor worked:
CSVWriter writer = new CSVWriter(new FileWriter("C:/test.csv"), '|', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER);

Reason I see that the CSVWriter was considering " as a Escape Character by default and thus if it comes in String, it was will trying to Escape that " with DEFAULT_ESCAPE_CHARACTER which is not anything but " itself.
By passing CSVWriter.NO_ESCAPE_CHARACTER, the Writer will not worry about checking if there are anything that needed to be in between Escapes.

A: If you are using com.opencsv.bean.StatefulBeanToCsv builded by com.opencsv.bean.StatefulBeanToCsvBuilder instead com.opencsv.CSVWriter;
you can't set directly the options as constructor params, but you have to set it calling the respective methods: .withQuotechar() and .withEscapechar()
Like this:
StatefulBeanToCsvBuilder btcsvBuilder = new StatefulBeanToCsvBuilder(myOutputStreamWriter);
StatefulBeanToCsv btcsv = btcsvBuilder.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withEscapechar(CSVWriter.NO_ESCAPE_CHARACTER).withMappingStrategy(myMapStrategy).withSeparator(',').build();


text:
Q: Django html email I am working a project where need to send html email . A url need to insert the html content, like

Password Change Link

My domain name , dealerfunnel.com. If I put any valid url except http://dealerfunnel.com then email is sending. Like If I put
google.com
then email is sending. But when I put dealerfunnel.com , email is not sending and do not get any error.
Please review my code:
from dealerfunnel.funnel.view.base import *
from django.template.loader import get_template
from django.core.mail import EmailMessage
import sys

class debug():
    def sendmail(self,request):
        message = get_template('mail/forgot.html').render(Context({"name":"Khalid Hossain"}))
       try:
            msg = EmailMessage('Password Change',message, to=['khalidrashed@gmail.com'], from_email='support@domainname')
            msg.content_subtype = 'html'
            msg.send()
            return HttpResponse(message)
        except :
            e = sys.exc_info()[0]
            return HttpResponse(e)

A: Here is what u can do
def send_notification_email(template, **kwargs):
    subject = "Your subject here"
    context = Your_Context
    email = Your_Email
    body = render_to_string(template, {'context':context})
    return send_mail(subject, body, settings.EMAIL_HOST_USER, [email], fail_silently=True)

This is if your are calling this function from your view..
If not then you can use template explicitely in send_mail method.
Now in your template you cann write anything you want and the mail should be send


text:
Q: How can OSGi and Akka benefit from each other? How is this structured? Following up my rather illogical question, asking to use OSGi or Akka, I was advised that the two can be used together, and that they each solve a different problem. I could use OSGi to provide modularity and updatability, and Akka to provide scalability and performance. As there hasn't been a lot of experimenting with combining OSGi and Akka, I still have a couple of questions.
How can OSGi and Akka be used together and benefit from each other? How is this structured? Do all your actors reside in one OSGi bundle, do they each get a separate bundle, is there a hybrid solution or isn't there really a 'right' way to do it?
I would divide the big components in different OSGi bundles. Each bundle exists of different Akka actors. Each bundle can then be scaled separately from each other in function of the load on that bundle. In each bundle transparent load balancing can be used to spread the load over different actors.
Would this be a correct and realistic way of doing this?
EDIT
Thoughts after implementation:
They clearly complement each other! I divided my application into big blocks, which I then injected into parts of the application using Spring. Inside the big blocks I solely used Akka. The gates to the blocks are Typed Actors. To make my system completely asynchronous I had to implement some extra functionality. So no blocking calls remain all interface methods should return the void type. Couldn't find any other way. You can then pass a message through the interface as an attribute that gets carried around for the whole journey of the request, which gets registered into a "Responder" at the beginning of the request. At the end a DeferredResult object gets successfully returned or an error/timeout is returned.

A: Here's how I use the two together.
Think of it like this...
Object-Oriented Programming introduced new layers of encapsulation. At the object level (with private members). OSGi just enables JAR-level encapsulation. Without OSGi, as soon as its compiled, it all melts into one pot. OSGi enforces the interface at the JAR level. And because of that, you have cleaner modularity and better code (for the same reasons any type of encapsulation is good).
I only use OSGi to do the JAR-level encapsulation. Any features that overlap such as scaling up certain modules based on usage, I do in Akka, because the API is higher-level and so easier to do and maintain.
But, many things about them don't overlap, so you should be able to see what goes where pretty easily with that rule of thumb in mind.
OSGi is to me just very useful for enforcing a good design, because it has rules for how I can consume a service... enforcing an interface at the JAR-level.
I'd say your last paragraph explains it well. Just modularize it like you would for any large-scale software. But now they are OSGi bundles instead.
If you have follow-up questions, please do comment. I can edit to say more. I've been using the two together for a while now.
Edit: Response to comments
Reading your question, it seems you may know some things I don't. Which I can't be sure of, so let me know if this post misses its mark. I'm an Akka guy who later did some OSGi, if you did that the other way around, you may be aware of options that I am not.
sharing the actor system is trivial. OSGi bundles don't cause inversion of control like a framework. You just call it like any other library code.
Wherever you are creating the actor uses system.actorOf calling the class of an actor in another bundle, and that's it. Your question seems to imply you know more about other OSGi options or perhaps are thinking that OSGi will do inversion of control and so each bundle would be stuck with its own actor system.
If it's still unclear, I'd recommend a quick prototype. Just pass the first end-to-end test that uses the design and then refactor adding in OSGi.


text:
Q: Misunderstood quote from Learn JavaFX 17 I am going through the book "Learn JavaFX 17" and it has been very helpful so far.  However, I came across something on page 92 which seems to fly in the face of the examples.  Just after the tip the authors say:

It is allowed, but not advisable, to change the content of a ListProperty whose content has been bound to another ObservableList. In such cases, the bound ListProperty will not be synchronized with its target list.

Yet the very next example seems to show a ListProperty, bound to another whose content changes, and the bound ListProperty changes as well.
I think I have missed the point of this quote entirely.  I expect there is some subtle distinction being made that I am not seeing.
Can anyone shed light on this?

A: I don't have the book, but that quote mentions bound "content", and so the only reasonable thing it could be talking about is the #bindContent(ObservableList)1 method. If you call that method, then changes to the ObservableList will be reflected in the ListProperty2 but not vice versa.
For example:
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

public class Main {

    public static void main(String[] args) {
        ObservableList<String> foo = FXCollections.observableArrayList();
        ObservableList<String> bar = FXCollections.observableArrayList();

        ListProperty<String> property = new SimpleListProperty<>(foo);
        property.bindContent(bar);

        bar.add("Hello");
        // same as 'property.get().add("World")' (i.e., adds directly to 'foo')
        property.add("World");

        System.out.println("FOO: " + foo);
        System.out.println("BAR: " + bar);
    }
}

Output:
FOO: [Hello, World]
BAR: [Hello]

You can use the #bindContentBidirectional(ObservableList)1 method instead if you want changes to be reflected in both directions.
For example:
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

public class Main {

    public static void main(String[] args) {
        ObservableList<String> foo = FXCollections.observableArrayList();
        ObservableList<String> bar = FXCollections.observableArrayList();

        ListProperty<String> property = new SimpleListProperty<>(foo);
        // only change from previous example
        property.bindContentBidirectional(bar);

        bar.add("Hello");
        // same as 'property.get().add("World")' (i.e., adds directly to 'foo')
        property.add("World");

        System.out.println("FOO: " + foo);
        System.out.println("BAR: " + bar);
    }
}

Output:
FOO: [Hello, World]
BAR: [Hello, World]

1. These methods are declared in the ReadOnlyListProperty class. Note the "read-only" bit only refers the ability to change the value of the property; the list remains modifiable (unless you initialize/set the value to an unmodifiable list).
2. More specifically, the underlying ObservableList value of the ListProperty is synchronized with the given ObservableList. Though this happens "via the ListProperty".


text:
Q: Pass value to SOAP API complex type I'm calling a SOAP API using Server Reference, there is a complex type which requires weight values. I'm setting the values using the following code:
parcel objpcl = new parcel();
objpcl.weight = 10;
objpcl.length = 10;
objpcl.width = 10;
objpcl.depth = 10;
objpcl.girth = 10;
objpcl.combinedDimension = 10;
objpcl.volume = 10;
objpcl.value = 100;

The response returns and error stating "Invalid Weight". Here are the WSDL details:
  <xs:complexType name="parcel">
    <xs:sequence>
      <xs:element minOccurs="0" name="weight" type="xs:decimal" />
      <xs:element minOccurs="0" name="length" type="xs:decimal" />
      <xs:element minOccurs="0" name="width" type="xs:decimal" />
      <xs:element minOccurs="0" name="depth" type="xs:decimal" />
      <xs:element minOccurs="0" name="girth" type="xs:decimal" />
      <xs:element minOccurs="0" name="combinedDimension" type="xs:decimal" />
      <xs:element minOccurs="0" name="volume" type="xs:decimal" />
      <xs:element minOccurs="0" name="currency" type="xs:string" />
      <xs:element minOccurs="0" name="value" type="xs:decimal" />
      <xs:element minOccurs="0" name="numberOfParts" type="xs:decimal" />
      <xs:element minOccurs="0" name="numberOfItems" type="xs:decimal" />
      <xs:element minOccurs="0" name="hangingGarment" type="xs:boolean" />
      <xs:element minOccurs="0" name="theftRisk" type="xs:boolean" />
      <xs:element minOccurs="0" name="multipleParts" type="xs:boolean" />
      <xs:element minOccurs="0" name="catalogue" type="xs:boolean" />
      <xs:element minOccurs="0" name="description" type="xs:string" />
      <xs:element minOccurs="0" name="originOfParcel" type="xs:string" />
    </xs:sequence>
  </xs:complexType>

When I make the call using SOAPUI the call completes without an error. Below is the complete code, I'm hard coding the values for now to complete my testing, so any recommendation will have to account for the fact that I will be populating from database values.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HermesWebService;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        RoutingWebServiceClient objHermesWebService = new RoutingWebServiceClient();
        objHermesWebService.ClientCredentials.UserName.UserName = "ababab";
        objHermesWebService.ClientCredentials.UserName.Password = "abababa";

        deliveryRoutingRequest objRoutingRequest = new deliveryRoutingRequest();
        objRoutingRequest.clientId = "aba";
        objRoutingRequest.clientName = "aba";
        objRoutingRequest.userId = "abababa";
        objRoutingRequest.sourceOfRequest = "ababab";

        delRoutingRequestEntry objReqEntry = new delRoutingRequestEntry();
                objReqEntry.expectedDespatchDate = Convert.ToDateTime("2015-04-10T00:00:00");
    objReqEntry.countryOfOrigin = "US";

        customer objCust = new customer();
        objCust.customerReference1 = "12345";

        address objadr = new address();
        objadr.lastName = "Robinson";
        objadr.streetName = "Eastern Perimeter Road";
        objadr.addressLine1 = "London Heathrow Airport";
        objadr.city = "London";
        objadr.region = "Hounslow";
        objadr.postCode = "TW6 2GE";
        objadr.countryCode = "GB";

        parcel objpcl = new parcel();
        objpcl.weight = 10m;
        objpcl.length = 10m;
        objpcl.width = 10m;
        objpcl.depth = 10m;
        objpcl.girth = 10m;
        objpcl.combinedDimension = 10m;
        objpcl.volume = 10m;
        objpcl.value = 100;

        objCust.address = objadr;
        objReqEntry.customer = objCust;
        objReqEntry.parcel = objpcl;

        objRoutingRequest.deliveryRoutingRequestEntries = new [] {objReqEntry};

        //var request = new delroutingrequestentry
        //{
        //    addressvalidationrequired = false
        //};

        //request.parcel = objpcl;
        //objroutingrequest.deliveryroutingrequestentries[0] = request;

        var x = objHermesWebService.validateDeliveryAddress(objRoutingRequest);

    }
}

After running the Microsoft Service Trace Viewer it appears that the Parcel element is not making it to the API call, here is a copy of part of the trace viewer log:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<ActivityId CorrelationId="58ef72b0-fd4d-475f-9347-5f1ba25f5987" xmlns="http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics">7f7337fb-8db5-4b84-8e6c-44d7f43d561a</ActivityId>
</s:Header>
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<validateDeliveryAddress xmlns="http://v2.web.domain.routing.hermes.co.uk/">
<deliveryRoutingRequest>
<clientId xmlns="">aba</clientId>
<clientName xmlns="">aba</clientName>
<userId xmlns="">ababab</userId>
<sourceOfRequest xmlns="">ababab</sourceOfRequest>
<deliveryRoutingRequestEntries xmlns="">
<deliveryRoutingRequestEntry>
<customer>
<address>
<lastName>Robinson</lastName>
<streetName>Eastern Perimeter Road</streetName>
<addressLine1>London Heathrow Airport</addressLine1>
<city>London</city>
<region>Hounslow</region>
<postCode>TW6 2GE</postCode>
<countryCode>GB</countryCode>
</address>
<customerReference1>12345</customerReference1>
</customer>
<parcel></parcel>
<expectedDespatchDate>2015-04-10</expectedDespatchDate>
<countryOfOrigin>US</countryOfOrigin>
</deliveryRoutingRequestEntry>
</deliveryRoutingRequestEntries>
</deliveryRoutingRequest>
</validateDeliveryAddress>
</s:Body>
</s:Envelope>

A: I had a feeling the problem had a simple solution that I was overlooking. Each decimal field has a corresponding field which ends in Specified. The Specified field is a boolean which must be set to true in order for the field value to be sent during the serialization. There are additional post (XmlSerializer, "Specified" suffix and IReflect) which define better ways of accomplishing this; for now I manually specify:
    var objpcl = new parcel
    {
        weight = 10, weightSpecified = true,
        length = 10, lengthSpecified = true,
        width = 10, widthSpecified = true,
        depth = 10, depthSpecified = true,
        girth = 10, girthSpecified = true,
        combinedDimension = 10, combinedDimensionSpecified = true,
        volume = 10, volumeSpecified = true,
        value = 100, valueSpecified = true,
        numberOfParts = 1, numberOfPartsSpecified = true,
        numberOfItems = 10, numberOfItemsSpecified = true,
        description = "Test Package",
        originOfParcel = "US",
    };

If I spent a little more time reviewing the WSDL file I would have noticed the following:
    [XmlElement(Form = XmlSchemaForm.Unqualified, Order = 0)]
    public decimal weight { get; set; }
    [XmlIgnore]
    public bool weightSpecified { get; set; }

/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool weightSpecified
{
    get
    {
        return this.weightFieldSpecified;
    }
    set
    {
        this.weightFieldSpecified = value;
        this.RaisePropertyChanged("weightSpecified");
    }
}

Hope this helps.


text:
Q: Are there any CORS workaround without server side change in Javascript? I am trying to access a publicily shared google drive video file from my react website , since google drive file is not a absolute downloadable file,I am trying to play google drive video with a Custom Player ,so before showing the video in the player , I need to extract absolute file url with an XHR request.But I cannot access googledrive.com with XHR beacause it will only get CORS errors.Is there a way to request other server domains from a client domain without any serverside changes?

A: Short Answer
No. It's impossible to get around CORS without modifying server-side code.
Long Answer
CORS (Cross Origin Resource Sharing) is a browser's way of letting developers connect to external APIs from your website.
But that is an obvious security risk, not all APIs are meant to be public. To fix this risk, CORS only allows you to communicate to servers that have CORS enabled.
Unless the owners of the server suddenly decide to enable CORS, you cannot make a request from your website to the server.
The only way
The only way to achieve your goal is to send the request from a server. When making requests from server to server, there is no CORS (it only exists on browsers).
You would have to create a server yourself, make the request there, and send the response to the client.


text:
Q: How to make a Python Discord bot await a certain answer to a quiz? I want my bot to recognize if the user got the right or wrong answer, but the bot returns the wrong answer message no matter what. Here is my code:
@bot.command()
async def trivia(ctx):
  trivfile = open("questions.txt")
  allines = trivfile.readlines()
  for i in allines:
    qlist.append(i)
  qnum = random.randint(1,len(qlist)-1)
  del qlist[:]
  line = (allines[qnum-1])
  words = line.split()
  embed = discord.Embed(
    title = "Are you ready?",
    description = f"``{questions[qnum-1]}``\n **:regional_indicator_a:{words[0]}\n :regional_indicator_b:{words[1]}\n :regional_indicator_c:{words[2]}\n :regional_indicator_d:{words[3]}\n**",
    color = discord.Colour.red()
  )
  embed.set_thumbnail(url="https://www.budgetbytes.com/wp-content/uploads/2013/07/Creamy-Tomato-and-Spinach-Pasta-skillet-1-500x480.jpg")
  await ctx.send(embed=embed)
  def check(m):
    return m.content == 'a' or 'A' or 'b' or 'B' or 'c' or 'C' or 'd' or 'D'
  answer =  await bot.wait_for('message',check=check)
  if answer == words[4] or answer == words[5]:
    await ctx.send(f"Congrats, {ctx.author.name}! That was the correct answer gg man")
  else:
    await ctx.send(f"Wrong, the correct answer was {words[5]}. smh big noob")

and here is my .txt file containing the answers:
Achgabat Kabul Islamabad Bruhcity a A
1936 1914 1918 1890 b B
Jackson Astley Stalin Mercury b B

Thanks.

A: Bot.wait_for returns arguments that mirror the parameters passed to the relevant event handler.
In this case, since you're waiting for a message event, it will return a Message object that's assigned to answer. You'll want to use the Message.content attribute for comparisons.


text:
Q: Turn URL into Anchor tag using Regular Expression I want the following different input types to be converted into the following anchor tag:
http://www.stackoverflow.com
https://www.stackoverflow.com
www.stackoverflow.com

Replaced with:
www.stackoverflow.com

I think I could probably write something similar myself, but I'd like to know if there is a standard script for doing this which has been throughly tested?
Many Thanks!

A: Found this function:
   Public Shared Function ConvertUrlsToLinks(ByVal msg As String) As String
        Dim regex As String = "((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])"
        Dim r As New Regex(regex, RegexOptions.IgnoreCase)
        Return r.Replace(msg, "$1").Replace("href=""www", "href=""http://www")
    End Function


text:
Q: d3.js multiple line chart highlighting datapoints only I don´t quite get the hang out of the bisect function in d3.js in order to highlight the values by a vertical line.
I already got it working for one line/path but the performance is poor, at least in google chrome. Probably because my function calculates every point on the path instead of the datapoints only, which is what I actually need.
Here is the code:
/*create svg element*/
var svg = d3.select('.linechart')
.append('svg')
.attr('width', w)
.attr('height', h)
.attr('id', 'chart');

/*x scale*/
var xScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) {
  return d[0];
})])
.range([padding, w - padding]);

/*y scale*/
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) {
  return d[1];
})])
.range([h - padding, padding]);

/*x axis*/
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.ticks(20)
.tickSize(0, 0)
//.tickPadding(padding);

/*append x axis*/
svg.append('g')
.attr({
  'class': 'xaxis',
  //'transform': 'translate(0,' + (h - padding) + ')'
  'transform': 'translate(0,' + 0 + ')'
})
.call(xAxis);

/*y axis*/
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left')
.tickSize(0, 0)
.tickValues([0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]);

/*append y axis*/
svg.append('g')
.attr({
  'class': 'yaxis',
  'transform': 'translate(' + padding + ',0)'
})
.call(yAxis);

/*define line*/
var lines = d3.svg.line()
.x(function(d) {
  return xScale(d[0])
})
.y(function(d) {
  return yScale(d[1])
})
.interpolate('monotone');

/*append line*/
var path = svg.append('path')
.attr({
  'd': lines(dataset),
  'fill': 'none',
  'class': 'lineChart'
});

/*get length*/
var length = svg.select('.lineChart').node().getTotalLength();

/*animate line chart*/
svg.select('.lineChart')
.attr("stroke-dasharray", length + " " + length)
.attr("stroke-dashoffset", length)
.transition()
.ease('linear')
.delay(function(d) {
  return dataset.length * 100;
})
.duration(3000)
.attr("stroke-dashoffset", 0);

/*add points*/
var points = svg.selectAll('circle')
.data(dataset)
.enter()
.append('circle');

/*point attributes*/
points.attr('cy', function(d) {
  return yScale(d[1])
})
.style('opacity', 0)
.transition()
.duration(1000)
.ease('elastic')
.delay(function(d, i) {
  return i * 100;
})
.attr({
  'cx': function(d) {
    return xScale(d[0]);
  },
  'cy': function(d) {
    return yScale(d[1]);
  },
  'r': 5,
  'class': 'datapoint',
  'id': function(d, i) {
    return i;
  }
})

.style('opacity', 1);

//  LINES INDIVIDUAL
function drawIndividualLines (){

  /*define line*/
  var linesIndividual = d3.svg.line()
  .x(function(d) {
    return xScale(d[0])
  })
  .y(function(d) {
    return yScale(d[1])
  })
  .interpolate('monotone');

  /*append line*/
  var pathIndividual = svg.append('path')
  .attr({
    //'d': linesIndividual(datasetIndividual),
    'd': linesIndividual(datasetIndividual),
    'fill': 'none',
    'class': 'lineChartIndividual'
  });

  /*get length*/
  var lengthIndividual = svg.select('.lineChartIndividual').node().getTotalLength();

  /*animate line chart*/
  svg.select('.lineChartIndividual')
  .attr("stroke-dasharray", lengthIndividual + " " + lengthIndividual)
  .attr("stroke-dashoffset", lengthIndividual)
  .transition()
  .ease('linear')
  .delay(function(d) {
    return datasetIndividual.length * 100;
  })
  .duration(3000)
  .attr("stroke-dashoffset", 0);

  /*add points*/
  var pointsIndividual = svg.selectAll('circleIndividual')
  .data(datasetIndividual)
  .enter()
  .append('circle');

  /*point attributes*/
  pointsIndividual.attr('cy', function(d) {
    return yScale(d[1])
  })
  .style('opacity', 0)
  .transition()
  .duration(1000)
  .ease('elastic')
  .delay(function(d, i) {
    return i * 100;
  })
  .attr({
    'cx': function(d) {
      return xScale(d[0]);
    },
    'cy': function(d) {
      return yScale(d[1]);
    },
    'r': 5,
    'class': 'datapointIndividual',
    'id': function(d, i) {
      return i;
    }
  })

  .style('opacity', 1);
};

$(".individual").click(function() {
  drawIndividualLines();
  drawIndividualLegend();
  swapShifts();
});

var mouseG = svg.append("g")
.attr("class", "mouse-over-effects");

mouseG.append("path") // this is the white vertical line to follow mouse
.attr("class", "mouse-line")
.style("stroke", "white")
.style("stroke-width", "1px")
.style("opacity", "0");

var linesForMouse = document.getElementsByClassName('lineChart');
var linesIndividualForMouse = document.getElementsByClassName('lineChartIndividual');

var mousePerLine = mouseG.selectAll('.mouse-per-line')
.data(dataset)
.enter()
.append("g")
.attr("class", "mouse-per-line");

mousePerLine.append("circle")
.attr("r", 7)
.style("stroke", "#A0B1AB")
.style("fill", "none")
.style("stroke-width", "1px")
.style("opacity", "0");

mousePerLine.append("text")
.attr("transform", "translate(10,3)");

mouseG.append('svg:rect') // append a rect to catch mouse movements on canvas
.attr('width', w) // can't catch mouse events on a g element
.attr('height', h)
.attr('fill', 'none')
.attr('pointer-events', 'all')
.on('mouseout', function() { // on mouse out hide line, circles and text
  d3.select(".mouse-line")
  .style("opacity", "0");
  d3.selectAll(".mouse-per-line circle")
  .style("opacity", "0");
  d3.selectAll(".mouse-per-line text")
  .style("opacity", "0");
})
.on('mouseover', function() { // on mouse in show line, circles and text
  d3.select(".mouse-line")
  .style("opacity", "1");
  d3.selectAll(".mouse-per-line circle")
  .style("opacity", "1");
  d3.selectAll(".mouse-per-line text")
  .style("opacity", "1");
})
.on('mousemove', function() { // mouse moving over canvas
  var mouse = d3.mouse(this);
  d3.select(".mouse-line")
  .attr("d", function() {
    var d = "M" + mouse[0] + "," + height;
    d += " " + mouse[0] + "," + 0;
    return d;
  });

  d3.selectAll(".mouse-per-line")
  .attr("transform", function(d, i) {
    //console.log(w/mouse[0])
    //var xDate = xScale.invert(mouse[0]),
    //bisect = d3.bisector(function(d) { return d.date; }).right;
    //      idx = bisect(d.values, xDate);

    var beginning = 0,
    end = length,
    target = null
    console.log(end);

    while (true) {
      target = Math.floor((beginning + end) / 2);
      //pos = linesForMouse[i].getPointAtLength(target);
      pos = svg.select('.lineChart').node().getPointAtLength(target);
      //console.log(pos);
      if ((target === end || target === beginning) && pos.x !== mouse[0]) {
        break;
      }
      if (pos.x > mouse[0]) end = target;
      else if (pos.x < mouse[0]) beginning = target;
      else break; //position found
    }

    d3.select(this).select('text')
    .text(yScale.invert(pos.y).toFixed(2))
    .attr("fill", "#fff");

    return "translate(" + mouse[0] + "," + pos.y + ")";
  });
});

Here is a Fiddle:
https://jsfiddle.net/mindcraft/vk2w7k2f/2/
So my questions are:
How do I manage to highlight the datapoints only? (Through the bisect function I don´t understand yet, I guess…)
How can I apply the same functionality to the second line (visible after clicking the "Show individual"-button in a more efficient way?
Thank you in advance!

A: Let me see if I can explain d3.bisector() for you. It will give you a huge performance improvement over searching every value between your two data points. A bisector is a form of array search for use on sorted data. But instead of searching for a particular value, you are searching for the proper index at which to insert an arbitrary value x in order to maintain sort order (a bisector bisects your array into two halves, one with values less than or equal to x and one with values greater than x). This index also gives you the closest values in your dataset to the new value (namely, index and index-1. This is how bisector() is really useful in your example. It will basically return the two closest values in your dataset to the location of the mouse. All you have to do is the arithmetic to find which of the two is the closest.
Here is an example of the process from https://bl.ocks.org/micahstubbs/e4f5c830c264d26621b80b754219ae1b with my comments mapping to my above explanation:
function mousemove() {
  //convert absolute coordinates to the proper scale
  const x0 = x.invert(d3.mouse(this)[0]);
  //bisect the data
  const i = bisectDate(data, x0, 1);
  //get the two closest elements to the mouse
  const d0 = data[i - 1];
  const d1 = data[i];
  //check which one is actually the closest
  const d = x0 - d0.date > d1.date - x0 ? d1 : d0;
  //draw your lines
  focus.attr('transform', `translate(${x(d.date)}, ${y(d.close)})`);
  focus.select('line.x')
    .attr('x1', 0)
    .attr('x2', -x(d.date))
    .attr('y1', 0)
    .attr('y2', 0);

  focus.select('line.y')
    .attr('x1', 0)
    .attr('x2', 0)
    .attr('y1', 0)
    .attr('y2', height - y(d.close));

  focus.select('text').text(formatCurrency(d.close));
}


text:
Q: Strange alias tracking problem, some not tracking even though it's there, query to correct
See image above. See how there are two links, but the link appears 4 times once with a LinkName (alias), once without. Now the link did appear in the email twice, once on an image, and once on text, but both times it had an alias, yet the alias did not track on one of them. Is it because the alias was exactly the same on both links? I have submitted a case to marketing cloud support about this, but in the meantime, I'm trying to find a way to remap the correct alias.
Is there a way with SQL to look for LinkName fields that are blank, then look at the left column to get the url, then search that same column for the same url, then fill in the LinkName column with the alias from the url that has it. (Hope that makes sense) I've provided a diagram below to help.

A: This is what I needed
SELECT n.LinkContent,
CASE WHEN LEN(n.LinkName)>0 THEN
    n.LinkName
ELSE
    n2.LinkName
END as LinkName
FROM [Newsletter Link Ranking Past month] n with (NOLOCK)
JOIN (
    SELECT LinkContent, LinkName
    FROM [Newsletter Link Ranking Past month] with (NOLOCK)
    WHERE LinkName IS NOT NULL
) n2
ON n.LinkContent = n2.LinkContent


text:
Q: Report generation I am writing a web app using TurboGears, and in that app the users must be able to generate different reports.
The data the reports need is stored in a database (MySQL).
The reports must be returned either as a easily printable html document, or a pdf file.
I have previously used jasper and iReport for creating the documents, but if I can avoid having to fire up Java to create the report I would be happy.
Ideally I would like to specify reports in a easily readable markup language and then just feed the template data with some kind of library that produces the report.
I gladly accept any kind of hints on how I should go about generating these reports!

A: Pod is my favorite solution to your problem.

A: You can build some fancy PDFs from Python with the ReportLab toolkit.

A: A partial answer: the easily readable format you are looking for might be DocBook. From there it is very easy to go to PDF, html, RTF, etc. etc.


text:
Q: Android : Issue deleting last item from RecyclerView I am using the RecyclerView in the following manner to show a list of Places items that are updated in SQLite DB .
The items are deleted fine and updated as i swipe them .
But when I swipe to delete the last item , it comes back in the view . When i close the app and reopen the app , the item is deleted though .
But when item is swiped to delete , in that instance of app running , the item is not deleted from view even after swiping multiple times .
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
     int swipedPosition = viewHolder.getAdapterPosition();
     PlaceListAdapter adapter = (PlaceListAdapter) mRecyclerView.getAdapter();

     int pos = viewHolder.getAdapterPosition();
     // Build appropriate uri with String row id appended
     String stringId = places.get(pos).getId();

     Log.d("testhro", stringId);

     Uri uri = PlaceContract.PlaceEntry.CONTENT_URI;
     uri = uri.buildUpon().appendPath(stringId).build();

     Log.d("testhhd", uri.toString());
     // COMPLETED (2) Delete a single row of data using a ContentResolver
     getContentResolver().delete(uri, null, null);
     mAdapter.notifyDataSetChanged();
     refreshPlacesData();

}

refreshPlacesData()
 private void refreshPlacesData() {
        Uri uri = PlaceContract.PlaceEntry.CONTENT_URI;
        Cursor data = getContentResolver().query(
                uri,
                null,
                null,
                null,
                null);

        if (data == null || data.getCount() == 0) return;

        Log.d("countIs", String.valueOf(data.getCount()));

        List<String> guids = new ArrayList<String>();
        while (data.moveToNext()) {
            guids.add(data.getString(data.getColumnIndex(PlaceContract.PlaceEntry.COLUMN_PLACE_ID)));
        }
        PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi.getPlaceById(mClient,
                guids.toArray(new String[guids.size()]));
        placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
            @Override
            public void onResult(@NonNull PlaceBuffer places) {
                mAdapter.swapPlaces(places);
                MainActivity.this.places = places;
                mGeofencing.updateGeofencesList(places);
                if (mIsEnabled) mGeofencing.registerAllGeofences();
            }
        });
    }

Am I missing something? Thanks.
EDIT :
i tried updating adapter instead of mAdapter , but still no change
EDIT 2
public void swapPlaces(PlaceBuffer newPlaces) {
        mPlaces = newPlaces;
        if (mPlaces != null) {
            // Force the RecyclerView to refresh
            this.notifyDataSetChanged();

        }
    }

Note : I also verified the loggers :
D/countIsZero: true (inside refreshPlacesData())

A: You should refresh your View after changing dataset.
   MainActivity.this.places = places; // Data set changed
   PlaceListAdapter adapter = (PlaceListAdapter) mRecyclerView.getAdapter();
   adapter.notifyDataSetChanged();

or you should change order of
   mAdapter.notifyDataSetChanged(); // Notify later
   refreshPlacesData(); // Refresh first

Firstly change dataset and then notify adapter.

A: Solved..
As i was deleting the last item , the data count would become 0 , in which case i was currently just returning.
So instead of that , following is my addition inside refreshPlacesData() :
  if (data.getCount() == 0) {
            Log.d("countIsZero","true");
            mAdapter.swapPlaces(null);
            return;
        }

and
 public void swapPlaces(PlaceBuffer newPlaces) {
        mPlaces = newPlaces;

        if(mPlaces==null)
        {
            Log.d("mPlaceNull","true");
            this.notifyDataSetChanged();
            return;
        }

Weirdly , only thing happening here is this.notifyDataSetChanged(); being called on adapter object , but if i use it this way and skip calling of swapPlaces() , it does not work i.e
if (data.getCount() == 0) {
            Log.d("countIsZero","true");
            mAdapter.notifyDataSetChanged();
            return;
        }

doesn't work.


text:
Q: Power supply Circuit for school and will like to add LEDs I am trying to add LEDs to a power supply to light up when it comes on I am wondering how to do this and how it will affect the voltage output for the power supply itself?

simulate this circuit – Schematic created using CircuitLab

A: First, as shown your supply will not work. Your transformer secondary needs the center tap grounded.
Second, with the center tap grounded, you'll get less ripple if you tie the two diode anodes together.
Third, don't use 1N4148s as rectifiers (although that may just be the default part number in the schematic entry. Be aware that you can edit this - just double-click on the part and edit as you wish.)
Fourth, the connection point for your LEDs will depend on exactly what you want to show. If all you want to show is that part of the circuit is live, one of the two input capacitors (C1 or C2) is a good place to start. Of course, if either of the regulators fails, or you've shorted an output, your LEDs won't reflect that fact.
Fifth, depending on just how much load current you're drawing, your capacitor voltage will be in the range of 12 to 17 volts. You'll need to increase your LED current limiting resistor to keep the LED current appropriate. I can't tell you a value, since LEDs can drop anywhere from 1.5 to 3.5 volts each, depending on what kind you use.
By the same token, if you're using white LEDs with a 3.5 volt drop, you can't use 3 of them to display either of your regulated outputs, since your string of LEDs will need at least 10.5 volts to light up.

A: A Typical single led string with a current of 20mA would likely not affect the regulated circuit in any important manner. A 24V 2A transformer will provide enough for both. Just ensure you use the correct resistor for 20mA at 24 Volts