text:
Q: How to use Fetch API for GET request I want to GET JSON from the endpoint https://api.brawlstars.com/v1/brawlers.
(https://api.brawlstars.com/v1/brawlers?Authorization="Bearer%20[My API Key]")
Here's my Code:
let url = 'https://api.brawlstars.com/v1/brawlers'
    fetch(url, {
        method: "GET",
        headers: {
            "Authorization": "Bearer **USER'S API KEY GOES HERE**"
        }
    }).then((response) => {
        let json = response.json();
        console.log(json);
    }).catch((err) => {
        console.error(err)
    });

This is the output (error):
Access to fetch at 'https://api.brawlstars.com/v1/brawlers' from origin 'http://127.0.0.1:8887' has been
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If
an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS
disabled.
sketch.js:3 GET https://api.brawlstars.com/v1/brawlers net::ERR_FAILED
127.0.0.1/:1 Uncaught (in promise) TypeError: Failed to fetch

What am I missing?

A: In your header, you need to enable CORS like CBroe said :
  headers.append('Access-Control-Allow-Origin', 'http://127.0.0.1:8887');
  headers.append('Access-Control-Allow-Credentials', 'true');

Edit :
The server (that the POST request is sent to) needs to include the Access-Control-Allow-Headers header (etc) in its response. Putting them in your request from the client has no effect.
This is because it is up to the server to specify that it accepts cross-origin requests (and that it permits the Content-Type request header, and so on) – the client cannot decide for itself that a given server should allow CORS.


text:
Q: How do I Install Adobe Flex 3.6 Data Visualization Components for Flex Builder 3 on a Mac? I just updated my Flex Builder 3 SDK to 3.6. I'm on a Mac.
Now, I'm trying to install the 3.6 Data Visualization Components. The link is found here: www.adobe.com/cfusion/entitlement/index.cfm?e=flex3sdk.
Adobe refers you to the release notes here for instructions on how to install the Components. Unfortunately, I don't understand what I'm supposed to do. I unzipped the file. I made a directory called 3.0 as a sub-directory of sdks. I put the data visualization components in  Adobe Flex Builder 3/sdks/3.0/data_visualization_sdk3.6.
a) What do I need to do next?
b) I don't have anything in the 3.0 directory. Should I have put the data_visualization_sdk3.6 folder in sdks/3.6 instead?
c) After I get it set-up , how do import or load samples/explorer?
Any suggestions?
Thank you!
-Laxmidi

A: The name of the folder you put them into doesn't matter.
The Data Visualization Components are just a Flex library; so all you need to do to use it in a Flex project is to add the SWC to the library path.
The instructions your reading are for combining the data visualization package with the Flex 3.5 SDK. You don't need to do that to use them.
As far as I knew, there are no samples to load or import related to this.  But, if you Google around or look at the Adobe documentation you may find some.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using a Facebook Pixel, how does one trigger the activated app event using the JS SDK? How do you get a FB pixel to fire when an app is installed or activated using the javascript SDK?
Based on the FB documentation, we are using:
FB.AppEvents.activateApp();

We have verified that the SDK is loaded, and the FB.AppEvents object and activateApp function exist.
We are able to log events using:
fbq('track','xxx');

When we use the helper tool provided by FB to test the pixel:
https://developers.facebook.com/tools/app-ads-helper/
it indicates that the app is setup, but that 'no installs were recorded in the past 7 days', even though we know that there have been installs, and they should have fired the call above.
Thanks.

A: As far as I've been able to tell, it's only possible to do this for iOS or Android apps using the native SDK or one of the cordova plugins (eg currently cordova-plugin-facebook4).  If someone knows how to do this with the JS SDK, please post.


text:
Q: Algorithm for remainder operation in verilog that executes in a single clock cycle Any links to literature discussing the algorithm would suffice.
I am working on a verilog code in xilinx. It uses verilog's inbuilt % operator. The problem is that % cannot be synthesized in xilinx.
Thanks in advance!

A: In most tools, % can be simulated but not synthesized.
For example, if you need m % n, if n is a fixed number, especially it is 2's power, you can write one easily.
If n is not 2's power, but the value range of m is small enough, you can build a table and do parallel comparisons to do the modulation.
Normally if m is random or n is not fixed, it is pretty difficult to do in hardware.
Probably it is better to change your hardware algorithm to avoid this modulation if possible.
Most of the time, you don't need an accurate modulation, reducing the precision of m and n would help.


text:
Q: how receive http response of binary pdf and show it. angular 2 - ionic2 I am tring to recive a pdf convert to binary(64) from a rest service, and show it in ionic 2, i try this:
I am tring to recive a pdf convert to binary(64) from a rest service, and show it in ionic 2, i try this:
    in service
    function(token:String, docCaseNumber: String){
      this.setTokenHeaders(token);
      this.headers.append('Accept', 'application/octet-stream');
      let options = new RequestOptions({ headers: this.headers });
      return new Promise(resolve => {
        this.http.get(url, options)
        .map(res => res)
        .subscribe(data => {
          //console.log(data);
            resolve(data.text());
          }, err => {
            resolve("connException");
          });
        });
    }
       in component
     getXX(){
      this.miservice.functoin(this.token, 'H17-09601').then(
          (data) => {
              var blob = data;
              console.log(blob);

              this.base64ToUint8Array(data);

              //this.getBase64(data);

              var converted = new Blob([blob], {type:'application/pdf'});
              this.convertToBase64(converted);
              //this.base64ToUint8Array(converted);
              //this.fileURL = URL.createObjectURL(converted);
              //window.open(fileURL);
              var pdf = pdfMake.createPdf(this.buildPdf(converted));

              pdf.getBase64(function (output) {
                this.base64ToUint8Array(output);
              });
              //console.log(pdf);
              pdf.open;
              //console.log(data);
    });
  }

A: here is the answer. You can use this for show pdf
Modify according to your needs ;)
 return new Promise(resolve => {
            let xhr = new XMLHttpRequest();
            xhr.open('get', url, true);
            xhr.setRequestHeader("Access-Control-Allow-Origin", '*');
            xhr.setRequestHeader('Accept', 'application/octet-stream');
            xhr.setRequestHeader('Authorization', 'Bearer ' + token);
            // xhr.overrideMimeType('text/xml; charset=iso-8859-1');
            xhr.overrideMimeType('text/xml; charset=iso-8859-1');
            xhr.responseType = "arraybuffer";
            xhr.onreadystatechange= function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        console.log(JSON.stringify((xhr.response)));
                        resolve(new Blob([xhr.response], { type: 'application/pdf' }));
                    } else {
                        //do something
                    }
                }
            }
            xhr.send();
            });
then use it like this:

    your-function.then(
              (blob :Blob) => {
                var downloadUrl = URL.createObjectURL(blob);
                var downloadLink      = document.createElement('a');
                downloadLink.href = downloadUrl;
                downloadLink.target   = '_blank';
                document.body.appendChild(downloadLink);
                downloadLink.click();

              });


text:
Q: camel when/otherwise for activemq and seda I have a route where I'd like to compute if "from" is activemq or something else. I found replaceFromWith, but it seems to be used for testing only. I tried using camel's choice when/otherwise to switch between "from activemq" and "from seda", but that errors out as invalid syntax. I'm looking for something that would do the following:
<route id="doPost">
    <choice>
        <when>
            <groovy>exchange.getIn().getHeader("sometest") != null</groovy>
            <from uri="activemq:doPost?..."/>
        </when>
        <otherwise>
            <from uri="seda:doPost?....."/>
        </otherwise>
    </choice>

Thanks in advance, appreciate the help.

A: You cannot dynamically select a consumer based on the exchange, the exchange wont exist before consuming it using the <from .../> tag.
Instead, you can construct a route for each consumer, normalize the exchange you receive from different types of consumers, and forward them to a common route for processing.
<route id="activemqConsumerRoute">
  <from uri="activemq:doPost?..."/>
  <!-- normalize the exchange to be understandable by the next route -->
  <to uri="direct:commonProcessingRoute" />
</route>

<route id="sedaConsumerRoute">
  <from uri="seda:doPost?....."/>
  <!-- normalize the exchange to be understandable by the next route -->
  <to uri="direct:commonProcessingRoute" />
</route>

<route id="commonProccessingRoute">
  <from uri="direct:commonProcessingRoute" />
  <!-- whatever business logic you have -->
</route>


text:
Q: Improving "How to ask" page readability This proposal comes in two parts.
First of all, I think that "How to ask" page lacks readability at the moment and therefore is ignored by most new users. A simple CSS change will make things much better, as shown in included images. They use the following values:
h2 {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 30px;
    margin-top: 55px;
}

.subheader h1 {
    color: #242729;
    font-size: 27px;
    line-height: 2.22;
}

p {
    font-size: 150%;
    line-height: 150%;
}

Current page:

Proposed changes:

The second part is about an ability to customize "How to ask" pages for each site. Is there any updates on this long-time requested feature? On serverfault we got an every day problem with people whos first question is an offtopic/gets closed. If we could include this guide along with standard page, it would really improve new user experience, since most of them can't clearly understand difference between superuser, askubuntu & serverfault...


text:
Q: Windows 10 rebooting in a loop to install updates -but already updated to 1903 hopefully someone can help.
I had a client whose HP laptop - tried to install 1803 update and failed into a reboot loop - troubleshoot - system restore enables access to the desktop.
I downloaded 1903 media creator and brought the laptop uptodate. All seemed ok on restart and left the laptop with the client.
Now the laptop has gone back into a "installing update" loop even though it has 1903 update (successful so earlier updates not needed?) -
Question is why windows can't figure out it is uptodate and where in the reboot process is it being told to try and install an update not needed? I need to break this loop - any ideas?
Thanks Andy

A: update: the problem was linked to w/r fails on the HDD - consequently it failed to a RAW state - completely losing the partition. Customer had good backups so only took a few hours to rebuild... installed 1809 update and all looks good.


text:
Q: Track Keywords from Google Adwords and GA and store them I run an adword campaign on google.
Users type in keywords and come to my landing pages via few ad's they see. Now my landing page has some 2 pages. One has informational which brings a user directly to the landing page after ad click - second is a signup form. Now I wish to capture the keywords he has typed in and then come into this form so that we know how users are reacting to our ads and what do they type to get to us.
The complex part is how can we use the GA - API to track this down. Since user will landing on /page and may signup finally from /page1 so we need to store those kewyords from his url (which is done via the Value Track codes in the url) and then store in the cookies so that when he later comes to /page1 and is signing up the same keywords can be passed and stored in the backed?
Is this possible and some can please help with this - where to look for how to accomplish this.
Thanks

A: I append a code to my ad's URL in AdWords:
www.example.com/?code=some-unique-id

On the landing page I check for the query string parameter, and if found store it in a cookie.
Any subsequent pages can access the cookie, and get the code from the original landing page.
This is only ad-group level, but it's a start.


text:
Q: How Do I fetch multiple rows from MySQL and and make them the value of checkbox(es) to be inserted to a another table in the database, in php? I have a table named subjects and another named classes. The design of the app am building is such that the user first fills a form to send subjects offered in a school to my table "subjects". Then he fills another form to create classes in the school, selecting what subjects (from those is table "subjects") are offered in the new class being created. On form submission, their inputs go to a table "classes" which has the following rows; id, className, classSubjects.
Here is my code:
<?php require_once 'controller/connect.php'; ?>

<!DOCTYPE html>
<title>TTApp</title>

<form action="controller/classReg.php" method="post">
Class Name
<input type="text" name="className" required="true">

Subjects Offered

        <?php
        $sql = "SELECT * FROM subjects";
        $result = $connect->query($sql);

        if($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                echo "<input type='checkbox' name='classSubjects' value=".$row['title'].">
                   ".$row['title']." ";
            }
        }
        ?>

<input type="submit" name="submit" value="Register Class">
</form>

And the controller/classReg.php here:
<?php
    require_once 'connect.php';

    if($_POST) {
        if(isset($_POST['className'])) {
            $className= $_POST['className'];
        }

        if(isset($_POST['classSubjects'])) {
            $classSubjects  = array($_POST['classSubjects']);
            echo $classSubjects;
        } else {
            echo "no class subject";
        }

        $sql = "INSERT INTO classes (className, classSubjects) VALUES ('$className', '$classSubjects')";
        if($connect->query($sql) === TRUE) {
            echo "
New Record Successfully Created
";
            echo "<button type='button'>Back</button>";
            echo "<button type='button'>Home</button>";
        } else {
            echo "Error " . $sql . ' ' . $connect->connect_error;
        }

        $connect->close();
    }

?>

This isn't working. is correctly displayed loading all subjects in table "subjects" but only the last subject gets to the table "classes". Am feeling I need to use arrays somewhere but stuck.

A: First change this line :
echo "<input type='checkbox' name='classSubjects' value=".$row['title'].">
To:
echo "<input type='checkbox' name='classSubjects[]' value=".$row['title'].">

Then your controller/classReg.php here:
<?php
require_once 'connect.php';

    if ($_POST) {
        if (isset($_POST['className'])) {
            $className = $_POST['className'];
        }

        if (isset($_POST['classSubjects'])) {
            $classSubjects = $_POST['classSubjects'];
        }else {
            echo "no class subject";
        }

        $sql  = "INSERT INTO classes (className, classSubjects) VALUES (?, ?)";
        $stmt = $connect->prepare($sql);

        foreach ($classSubjects as $key => $subject) {
            $stmt->bind_param("ss", $className, $subject);
        }
        if ($stmt->execute()) {

            echo "
New Record Successfully Created
";
            echo "<button type='button'>Back</button>";
            echo "<button type='button'>Home</button>";
        } else {

            echo "Error " . $connect->error;

        }

        $stmt->close();
        $connect->close();
    }

    ?>


text:
Q: Android sqlite database null pointer exception I am getting a null pointer exception when I try to insert data into my sqlite database in my Android application.  I've looked at the code and everything seems to be in order and I'm baffled as to why I'm getting the null pointer exception. The code is as follows:
import java.sql.Blob;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {

    public static final String KEY_ROWID = "id";
    public static final String KEY_STUDENTNAME = "studentname";
    public static final String KEY_DOB = "dob";
    public static final String KEY_ADDRESS1 = "address1";
    public static final String KEY_ADDRESS2 = "address2";
    public static final String KEY_TOWN = "town";
    public static final String KEY_POSTCODE = "postcode";
    public static final String KEY_PHONE = "phone";
    public static final String KEY_STUDENT_PIC = "studentpic";

    private static final String TAG = "DBAdapter";

    private static final String DATABASE_NAME = "studentDB3";
    private static final String DATABASE_TABLE = "tblstudents";
    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_CREATE =
        "create table tblstudents (id integer primary key autoincrement, "
        + "studentname text not null, dob text not null, "
        + "address1 text not null, address2 text not null, "
        + "town text not null, postcode text not null, "
        + " phone text not null, studentpic blob);";

    private final Context context;

    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public DBAdapter(Context ctx)
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context)
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion,
        int newVersion)
        {
            Log.w(TAG, "Upgrading database from version " + oldVersion
                    + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS tblStudents");
            onCreate(db);
        }
    }

    //---opens the database---
    public DBAdapter open() throws SQLException
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    //---closes the database---
    public void close()
    {
        DBHelper.close();
    }

    //---insert a title into the database---
    public long insertStudent(String studentname, String dob, String address1, String address2, String town, String postcode, String phone, byte[] studentpic)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_STUDENTNAME, studentname);
        initialValues.put(KEY_DOB, dob);
        initialValues.put(KEY_ADDRESS1, address1);
        initialValues.put(KEY_ADDRESS2, address2);
        initialValues.put(KEY_TOWN, town);
        initialValues.put(KEY_POSTCODE, postcode);
        initialValues.put(KEY_PHONE, phone);
        initialValues.put(KEY_STUDENT_PIC, studentpic);

        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    //---deletes a particular title---
    public boolean deleteTitle(long rowId)
    {
        return db.delete(DATABASE_TABLE, KEY_ROWID +
                "=" + rowId, null) > 0;
    }

    //---retrieves all the titles---
    public Cursor getAllStudents()
    {
        return db.query(DATABASE_TABLE, new String[] {
                KEY_ROWID,
                KEY_STUDENTNAME,
                KEY_DOB,
                KEY_ADDRESS1,
                KEY_ADDRESS2,
                KEY_TOWN,
                KEY_POSTCODE,
                KEY_PHONE,
                KEY_STUDENT_PIC
                            },
                null,
                null,
                null,
                null,
                null);
    }

    //---retrieves a particular title---
    public Cursor getStudent(long rowId) throws SQLException
    {
        Cursor mCursor =
                db.query(true, DATABASE_TABLE, new String[] {
                        KEY_ROWID,
                        KEY_STUDENTNAME,
                        KEY_DOB,
                        KEY_ADDRESS1,
                        KEY_ADDRESS2,
                        KEY_TOWN,
                        KEY_POSTCODE,
                        KEY_PHONE,
                        KEY_STUDENT_PIC
                        },
                        KEY_ROWID + "=" + rowId,
                        null,
                        null,
                        null,
                        null,
                        null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    //---updates a student---
    public boolean updateStudent(long rowId, String studentname,
    String dob, String address1, String address2, String town,
    String postcode, String phone, byte[] studentpic)
    {
        ContentValues args = new ContentValues();
        args.put(KEY_STUDENTNAME, studentname);
        args.put(KEY_DOB, dob);
        args.put(KEY_ADDRESS1, address1);
        args.put(KEY_ADDRESS2, address2);
        args.put(KEY_TOWN, town);
        args.put(KEY_POSTCODE, postcode);
        args.put(KEY_PHONE, phone);
        args.put(KEY_STUDENT_PIC, studentpic);

        return db.update(DATABASE_TABLE, args,
                         KEY_ROWID + "=" + rowId, null) > 0;
    }

}

A: In Android, the ID column should be _id, not id as you have set:
public static final String KEY_ROWID = "id";

It may be worth looking at.


text:
Q: find row in ruby array I have a mysql query that returns this type of data:
{"id"=>1, "serviceCode"=>"1D00", "price"=>9.19}
{"id"=>2, "serviceCode"=>"1D01", "price"=>9.65}

I need to return the id field based on a match of the serviceCode.
i.e. I need a method like this
def findID(serviceCode)
    find the row that has the service code and return the ID
end

I was thinking of having a serviceCodes.each do |row| method and loop through and essentially go
if row == serviceCode
  return row['id']
end

is there a faster / easier way?

A: You can use the method Enumerable#find:
service_codes = [
  {"id"=>1, "serviceCode"=>"1D00", "price"=>9.19},
  {"id"=>2, "serviceCode"=>"1D01", "price"=>9.65}
]

service_codes.find { |row| row['serviceCode'] == '1D00' }
# => {"id"=>1, "serviceCode"=>"1D00", "price"=>9.19}

A: If you use Rails Active Record as ORM and your Model named Product (only for example),
you can use something like this:
def findID(serviceCode)
  Product.select(:id).where(serviceCode: serviceCode).first
end

If you have plain SQL Query in plain ruby class (not recommended), you should change this query to get only the id, as Luiggi mentioned. But aware of SQL Injections if your serviceCode coming from external Requests.


text:
Q: Fetch permissions from identity server during authorization I am using identity server 4 for authentication and authorization, and user permissions are saved in JWT and then used on API-s to check if users has required permission.
But the problem is that JWT got too big and I would like to remove permissions from it, and make custom authorization on API-s so that its fetches permissions from identity server instead of getting it from JWT.
API would get only userId from JWT and then based on that fetch additional information from identity server. Is it possible to do something like that?

A: We basically have a similar problem in our application.
The way to solve this problem is using an event which is raised at the level of the API resource (the API which you are protecting by using JWT bearer tokens authentication) once the JWT token has been read from the incoming request and validated.
This event is called OnTokenValidated, see here for more details.
This is the top level plan:

*

*keep your JWT bearer token minimal. At the very minimum it contains the subject id, which is the unique identifier of the user at the identity provider level. You can put other claims there, but the idea is that the JWT bearer token must be small

*implement a way to get the user permissions given the user unique identifier (you can use the subject id as an identifier or any other id which makes sense in your system)

*make the user permissions fetch mechanism of the previous point accessible via api call. Caching this API is a good idea, because usually permissions are stable. Defining a smart way to evict this cache is beyond the scope of this answer, but it's something you should definitely think about.

*once you have fetched the user permissions (via an API call) you need to make them available to the ASP.NET core authorization framework. The simplest way to do so is create a custom claim type (for instance: "app_permission") and create one user claim per each user permission. Each of these permission claims has the custom claim type ("app_permission") and the permission name as the claim value. For instance a user having the two permissions "read-content" and "write-content" will have two claims both having "app_permission" as the claim type, the first one having "read-content" as the claim value and the second one having "write-content" as the claim value.

*the permissions claims defined at the previous point can be injected in the user identity (at the API resource level) by defining an additional ClaimsIdentity for the user and by adding it to the current user identity. The process depicted here is quite similar to a claims transformation done by an MVC application using cookie authentication.

In the Startup class of your API resource, in the point where you register the authentication services, you can do something like this:
            services
              .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
              .AddJwtBearer(options =>
              {
                options.Authority = "https://localhost:8080";
                options.Audience = "sample-api";

                options.RequireHttpsMetadata = false;

                // register callbacks for events
                options.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                       if (!context.Principal.Identity.IsAuthenticated)
                       {
                         return;
                       }

                       var subjectId = context.Principal.FindFirst(JwtClaimTypes.Subject)?.Value;
                       if (string.IsNullOrWhiteSpace(subjectId))
                       {
                         return;
                       }

                       // do whatever you want with the user subjectId in order to get user permissions.
                       //You can resolve services by using context.HttpContext.RequestServices which is an instance of IServiceProvider
                       //Usually you will perform an API call to fetch user permissions by using the subject id as the user unique identifier

                       // User permissions are usually transformed in additional user claims, so that they are accessible from ASP.NET core authorization handlers
                       var identity = new ClaimsIdentity(userPermissionsClaims);
                       context.Principal.AddIdentity(identity);
                    }
                };
              });

A: +1 for the accepted answer but I would just like to offer an alternative solution to this problem. If your permissions are pretty simple like readResource or writeResource then you could define all your permissions as enum and use integers instead of strings in JWT, that would reduce JWT size.
If permission list is still huge then you could also group permissions together so that the permission list is smaller for some customers e.g. merge readResource, writeResource, updateResource, deleteResource into one permission called crudResource.


text:
Q: 2D array of ImageIcon's displays inconsistently and only partially in JPanel I'm trying to create a screen full of 16x16 floor tiles using ImageIcons, JLabels, and a JPanel. My issue is that whenever I try to display these tiles using a 2D array, - even when looping the drawing method repeatedly - they don't display entirely. Rather, they only display a few tiles as opposed to the full arrays worth. Furthermore, the number of displayed tiles changes each time I run the program!
Here's the code I'm using:
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JFrameTest {

    static BufferedImage buf;
    static JPanel panel;

    public static void main(String[] args) {
        createWindow();
        loadImage();
        showImage();
    }

    public static void createWindow() {
        JFrame frame = new JFrame();
        panel = new JPanel();
        frame.setSize(1000, 1000);
        frame.setTitle("Tester");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.add(panel);
        frame.setVisible(true);
        panel.setLayout(null);

    }

    public static void loadImage() {
        try {
            buf = ImageIO.read(new File("res/test.png"));
        } catch (IOException ex) {
            System.out.println("NOT FOUND");
        }

    }

    public static void showImage() {

        final int[][] MAP =
                {
                        {1, 1, 1, 1, 1, 1, 1, 1, 1},
                        {1, 1, 1, 1, 1, 1, 1, 1, 1},
                        {1, 1, 1, 1, 1, 1, 1, 1, 1},
                        {1, 1, 1, 1, 1, 1, 1, 1, 1},
                        {1, 1, 1, 1, 1, 1, 1, 1, 1},
                        {1, 1, 1, 1, 1, 1, 1, 1, 1},
                        {1, 1, 1, 1, 1, 1, 1, 1, 1},
                        {1, 1, 1, 1, 1, 1, 1, 1, 1},
                        {1, 1, 1, 1, 1, 1, 1, 1, 1},
                        {1, 1, 1, 1, 1, 1, 1, 1, 1}
                };

        ImageIcon test = new ImageIcon(buf);

        panel.setBackground(Color.WHITE);
        System.out.println(test.getIconWidth());
        System.out.println(test.getIconHeight());

        JLabel[][] labelGrid = new JLabel[MAP.length][MAP[0].length];

        for (int r = 0; r < labelGrid.length; r++) {
            for (int c = 0; c < labelGrid[r].length; c++) {
                labelGrid[r][c] = new JLabel();
                labelGrid[r][c].setSize(test.getIconWidth(), test.getIconWidth());
                labelGrid[r][c].setLocation(test.getIconWidth() * r, test.getIconHeight() * c);
                labelGrid[r][c].setIcon(test);
                panel.add(labelGrid[r][c]);
            }
        }
        panel.revalidate();
    }

}

Here about what's normally printed:

It seems that the program just gives up in displaying the images. However, note that the number of displayed images changes every time! Some times only five images may appear, other times 22.
When I try using a smaller map such as:,
final int[][] MAP =
                {
                        {1, 1, 1},
                        {1, 1, 1},
                        {1, 1, 1}
                };

the entire 3x3 grid of images will appear about half the time, only one or two images being displayed the other half.
What work around can be implemented to solve this problem?
Computer specs:
Windows 10
i8-8700
1080 ti
16gb ram

A: Your basic problem is one of misunderstanding ... and welcome to my world
Using panel.setLayout(null); means you are taking full responsibility for the layout, which is fine, when you know what you are doing.
Compound that with calling setVisible before you've established the UI and using revalidate which is used to run a layout pass and you're setting yourself up for trouble.
Instead of revalidate, you should be using repaint, to trigger a new paint pass (note, in the normal course of events, you should use both when updating the the UI, but since you're no longer using a layout manager, you don't need revalidate)
Possibly a better solution is to use a custom painting route, for example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class TestPane extends JPanel {

        protected static final int[][] MAP
                = {
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1}
                };
        protected static Dimension GRID_SIZE = new Dimension(20, 20);
        private Rectangle buf; // This represents your image

        private Dimension preferredSize;
        public TestPane() {
            buf = new Rectangle(0, 0, GRID_SIZE.width, GRID_SIZE.height);

            int max = 0;
            for (int row = 0; row < MAP.length; row++) {
                max = Math.max(max, MAP[row].length);
            }
            preferredSize = new Dimension(GRID_SIZE.width * MAP.length, GRID_SIZE.height * max);
        }

        @Override
        public Dimension getPreferredSize() {
            return preferredSize;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            for (int row = 0; row < MAP.length; row++) {
                for (int col = 0; col < MAP[row].length; col++) {
                    int x = GRID_SIZE.width * row;
                    int y = GRID_SIZE.height * col;
                    Graphics2D translated = (Graphics2D) g2d.create();
                    translated.translate(x, y);
                    translated.draw(buf);
                    translated.dispose();
                }
            }
            g2d.dispose();
        }

    }
}

GridLayout
Another option is to use GridLayout
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class TestPane extends JPanel {

        protected static final int[][] MAP
                = {
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1}
                };
        protected static Dimension GRID_SIZE = new Dimension(20, 20);
        private BufferedImage buf; // This represents your image

        public TestPane() {
            int max = 0;
            for (int row = 0; row < MAP.length; row++) {
                max = Math.max(max, MAP[row].length);
            }

            setLayout(new GridLayout(MAP.length, max));

            buf = makeBuffer();
            for (int row = 0; row < MAP.length; row++) {
                for (int col = 0; col < MAP[row].length; col++) {
                    add(new JLabel(new ImageIcon(buf)));
                }
            }
        }

        protected BufferedImage makeBuffer() {
            BufferedImage img = new BufferedImage(GRID_SIZE.width, GRID_SIZE.height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = img.createGraphics();
            g2d.setColor(Color.DARK_GRAY);
            g2d.drawRect(0, 0, img.getWidth() - 1, img.getHeight() - 1);
            g2d.dispose();
            return img;
        }

    }
}

but this will resize the cells, which might not be desirable in which you could use a ...
GridBagLayout
This will honour the preferred size of the components better and, based on the way it's currently configured, won't resize the components when the window size changes
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class TestPane extends JPanel {

        protected static final int[][] MAP
                = {
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1, 1}
                };
        protected static Dimension GRID_SIZE = new Dimension(20, 20);
        private BufferedImage buf; // This represents your image

        public TestPane() {
            int max = 0;
            for (int row = 0; row < MAP.length; row++) {
                max = Math.max(max, MAP[row].length);
            }

            setLayout(new GridBagLayout());

            buf = makeBuffer();
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridy = 0;
            for (int row = 0; row < MAP.length; row++) {
                gbc.gridx = 0;
                for (int col = 0; col < MAP[row].length; col++) {
                    add(new JLabel(new ImageIcon(buf)), gbc);
                    gbc.gridx++;
                }
                gbc.gridy++;
            }
        }

        protected BufferedImage makeBuffer() {
            BufferedImage img = new BufferedImage(GRID_SIZE.width, GRID_SIZE.height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = img.createGraphics();
            g2d.setColor(Color.DARK_GRAY);
            g2d.drawRect(0, 0, img.getWidth() - 1, img.getHeight() - 1);
            g2d.dispose();
            return img;
        }

    }
}


text:
Q: Extjs 1st combobox select loads data to 2nd combo box extjs4 listeners:{select:{fn:function(combo, value) {
                           var attribute = Ext.getCmp('attributes');
                           var feature = Ext.getCmp('features');
                           var store = Ext.getStore('product.CategoryAttributeComboBox');

                           attribute.setValue('');
                           attribute.setDisabled(false);
                           attribute.store.load({
                           params: {id: 5}
                         });
}}}

Above is my code to load the data to 2nd combo box.But when I click on first combo it does not populate data to 2nd one,and if I select the 1st combo again it loads data to 2nd combo.Dont really find whats is happening with code.Is there something happens with the "mode" feature local or remote.I have setup my mode to local.

A: A long time ago I was simular issue and write simple plugin for combobox. May be can help for you. See example on github.
Note: "change", "keyup" events not processing, edit if you need it.

A: Here is another full example of two combo boxes interacting:
http://extjs.wima.co.uk/example/1


text:
Q: I can not give id value in the modal part

  ....

      {{ i + 1 }}
      {{ product.name }}
      {{ product.category }}
      {{ product.price }}
      {{ product.quantity ? "not over" : "it's over" }}

        <button
          class="btn btn-warning ml-2"
          data-toggle="modal"
          data-target="#updateProduct"
          (click)="fetchProduct(product._id, updateModal)"
        >
          UPDATE
        </button>
        <button
          class="btn btn-danger ml-2"
          data-toggle="modal"
          data-target="#deleteProduct"

        >
          DELETE
        </button>

   ....

Are you sure you want to delete?

        <button
          type="button"
          class="btn btn-secondary ml-2 mr-2"
          data-dismiss="modal"
        >
          CANCEL
        </button>
        <button
          type="button"
          class="btn btn-primary ml-2 mr-2"
          (click)="deleteProduct(product._id)"
        >
          DELETE
        </button>

These two blocks of code are in the same HTML page.
My goal is to remove a warning modal when the delete key is pressed in the table. And then press the delete button on the modal to delete the existing line.
But I can't get the id value I returned here in the modal part.
Normally when I do this without a modal in the table it works fine because I can take the id value and delete it directly. But I don't know how to give this id value when I am out.
How can I solve this?

A: in your ts create new variable:
deleteID : any;

in your html add below code:(inside ngFor)
<button
          class="btn btn-danger ml-2"
          data-toggle="modal"
          data-target="#deleteProduct"
(click)="deleteID= product._id"
        >
          DELETE
        </button>

inside modal:
<button
          type="button"
          class="btn btn-primary ml-2 mr-2"
          (click)="deleteProduct(deleteID)"
        >
          DELETE
        </button>

hope it will be help.


text:
Q: how to develop a drop down menu in django based on a foreign key field in a model I am developing a Django form to upload files. The form is based on a model(files). The model(files) has a foreign key field (repo_id). This repo_id is the primary key in the Repository model.
I want users to be able to choose which repo_id to put the file in. I need to insert a value to this field using a drop-down list in the form.
in the HTML template, the dropdown list is showing as "Repository object(repo_id)"
I have developed the two models (files and repository) in models.py, views.py, forms.py and HTML template following a tutorial. The form is working and it saves data in the database table as well.
I want to update the drop-down menu only to show indicator names in the repository model, not a repository object.
Here are my codes.
models.py

from django.db import models

# Create your models here.
class Repository(models.Model):
    source = models.TextField(db_column='source', blank=True, null=True)  # Field name made lowercase.
    indicator = models.TextField(db_column='indicator', blank=True, null=True)  # Field name made lowercase.
    key_aspect = models.TextField(db_column='key_aspect', blank=True, null=True)
    category = models.TextField(db_column = 'category')
    table_id = models.TextField(db_column='table_id', blank=True, null=True)
    data_returning = models.TextField(db_column='data_returning', blank=True, null=True)
    data_source = models.TextField(db_column='data_source', blank=True, null=True)
    value = models.TextField(db_column='value', blank=True, null=True)  # Field name made lowercase.
    year = models.TextField(db_column='year', blank=True, null=True)  # Field name made lowercase.
    location = models.TextField(db_column='location', blank=True, null=True)  # Field name made lowercase.

class files(models.Model):
    repo_id = models.ForeignKey(Repository, on_delete = models.CASCADE)
    username = models.CharField(db_column='username',max_length = 45)
    date = models.DateTimeField(auto_now_add=True, db_column = 'date')
    file = models.FileField(upload_to='documents/', db_column = 'file')
    username = models.CharField(db_column='username',max_length = 45)

    def __unicode__(self):
        return self.indicator_name

forms.py
class DocumentForm(forms.ModelForm):
class Meta:
    model = files
    fields = ('username',  'file', 'repo_id')

views.py
@login_required
def file_upload(request):
     websiterepository = Repository
     #indicator_queryset = websiterepository.objects.filter(category = 'P').values_list('id','indicator')

    if request.method == 'POST':
         documentform = DocumentForm(request.POST, request.FILES)

         if documentform.is_valid():
             documentform.save()
         return redirect('file_upload')
    else:
         form = DocumentForm()
         #documentform = DocumentForm(prefix = 'documentform')
         #searchform = SearchForm(indicator_queryset = indicator_queryset, prefix = 'searchform')
         #form = {'documentform':documentform, 'searchform':searchform}
         #return render(request, 'form_file_upload.html', form )
         return render(request, 'form_file_upload.html', {'form':form })

I know this is a lenthly post. I would be really grateful if you colud help me to figure this out.Thanks

A: Change the models to below code
class Repository(models.Model):
    source = models.TextField(db_column='source', blank=True, null=True)  # Field name made lowercase.
    indicator = models.TextField(db_column='indicator', blank=True, null=True)  # Field name made lowercase.
    key_aspect = models.TextField(db_column='key_aspect', blank=True, null=True)
    category = models.TextField(db_column = 'category')
    table_id = models.TextField(db_column='table_id', blank=True, null=True)
    data_returning = models.TextField(db_column='data_returning', blank=True, null=True)
    data_source = models.TextField(db_column='data_source', blank=True, null=True)
    value = models.TextField(db_column='value', blank=True, null=True)  # Field name made lowercase.
    year = models.TextField(db_column='year', blank=True, null=True)  # Field name made lowercase.
    location = models.TextField(db_column='location', blank=True, null=True)  # Field name made lowercase.

    def __str__(self):
       return self.indicator

If you want model to return field value , you have to define a self function or else it will return the respective object .


text:
Q: Laravel APP_LOCALE in spanish In Laravel 5.4,  in .env I have:
APP_LOCALE=es
APP_FALLBACK_LOCALE=en
APP_LOCALE_PHP=es_US

and in config/app.php:
'locale' => env('APP_LOCALE', 'es'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'locale_php' => env('APP_LOCALE_PHP', 'en_US'),

But I want to set as spanish. For example, In a controller I have:
$mydate = date('d F Y', strtotime($data->created));

$data->created is a string that comes from database, from column created_at. This way it show as:
14 August 2017

English, so ¿how can I get it in spanish?
I test APP_LOCALES with esnothing happens. I tried to setlocale(LC_TIME, "es"); right before the $mydate, and it's the same. I'm saving the changes and doing php artisan config:cache by the way.

A: I suggest you to use Carbon, that provides handy primitives for DateTime operations and it is fully supported by Laravel out of the box (so no additional packages or composer require actions). To format a localized date you need just few lines of code:
use \Carbon\Carbon;

...

setlocale(LC_TIME, 'es_ES.UTF-8');
Carbon::setLocale('es');
$mydate = Carbon::parse($data->created)->formatLocalized('%d %B %Y');

If you want to skip the Carbon steps just setting the time locale with setlocale will work out of the box. To get the list of installed locales in your UNIX machine run the command
$ locale -a

in your terminal or if you need to add a locale to your machine uncomment the line corresponding to you locale in /etc/locale.gen (e.g. es_ES.UTF8) then run the the following command in your terminal to generate the locale
$ sudo locale-gen es_ES.UTF-8

then update the locale list in your machine typing
$ sudo update-locale

hope it helps.


text:
Q: libraries for auto orientation - c# Am looking for any recommendation for libraries that will allow me to auto orient images. My project is in C#. I am looking for either open source or commercial libraries.
I want to use these libraries on either documents that are scanned or faxed as such my images will be lacking of EXIF data
The image will contain mostly English text. I looked at the OCR that MODI provides, can't go that route as the customer apparently is not running Office 2007.

A: If you mean to extract the image orientation from the EXIF data and to rotate the image accordingly then you might want to have a look at ImageMagick's auto-orient feature.
You can either automate ImageMagick via the command line or use the available .NET wrapper.
If you don't have EXIF information available, an automatic detection of the orientation will most likely only work if your image contains mainly text in lines (I assume this is the case for faxes). You could then make use of an OCR engine and use the orientation detected by the engine.

A: If you don't have EXIF data and your images are scanned/faxed documents then I think you're only solution is to check the height and width of the image and rotate based on that.
Documents are most likely to be in portrait format (taller than they are wide), so if the height is greater than the width then do don't have to do anything.
If the height is less than the width then rotate through 90 degrees. However, without analysing the image in some way you won't know which way to rotate it (left or right) and so could end up with the image upside down.
How many images are there going to be? If there aren't too many you could perform the rotation and then present the image to the user and ask if it's upside down or not. If it is rotate though 180 degrees. Not an ideal solution though.

A: It's not a managed solution, but I've had acceptable results using Dan Bloomberg's leptonlib C library, which comes with a VC9 project and an example of using the library from C# via a managed C++ wrapper.  It includes an implementation of orientation detection, but I  have found its accuracy is only good when the images are mostly mixed-case alpha text in non-uniform layouts (paragraphs and discrete text rather than tables/grids).  Using additional preprocessing and heuristic analysis (based on other methods in the same library) I have managed to improve the accuracy on the edge cases as well, though it still only hits around 87% total accuracy on my (fairly large) sample set.


text:
Q: Is there an option to let DSolve output exponential functions in preference to trigonometric functions as default results? For example,
DSolve[y''[x] + y[x] == 0, y[x], x]

gives
{{y[x] -> C[1] Cos[x] + C[2] Sin[x]}}

as the result.
Can we add any option(s) to make us get
{{y[x] -> C[1] E^(I x) + C[2] E^(-I x)}}

instead?
Maybe TrigToExp would be suggested, but it will lead to extra 1/2 factor in the solutions.
Update1: Admittedly, combination of TrigToExp and GeneratedParameters -> (2 C[#] &) can realize the expected output. However, I actually want a pure option of DSolve that can do the job.
So, there is none of such an option? And does this state of affairs mean that MMA regards trigonometric functions as more fundamental than exponential functions?


text:
Q: Command + C does not always work on first try on MacOS Command + C does not always work on first try on any of my four Macs.  I often highlight text, press Command + C, head to another window, press Command + V only to find that the original text did not copy.
I recently installed a fresh copy of macOS High Sierra and I continue to run into this issue, particularly in RStudio.* The issue never occurs on my PCs.
Do others have this issue? How can I resolve this?
*I use bettersnaptool and enable three finger dragging, but the issue still appears when I disable them.

A: I think it's possible for Apple's Continuity Universal Clipboard feature to cause something like this, depending on the quality of the signal connection with any nearby iOS devices.
Perhaps try turning off "Allow Handoff between this Mac and your iCloud devices" in System Preferences > General and see if that helps.

A: I've found a cause of the same problem. An app may use it as a hotkey. In my case, I use a dictionary app (Eudic), which will read the clipboard if cmd+c is pressed twice.
An easy way to check whether it is caused by an app is to activate the Guest account, which usually has few autostart apps, and to check whether the problem still exists.

A: This issue is real and I think every mac user experience it on a weekly basis, but likely people continue to doubt themselves over if they actually command c or not properly.
The fix. If you are using Karabiner like real hacker should:
Just add this to your karabiner complex configurations:
[
    {
        "from": {
            "key_code": "c",
            "modifiers": {
                "mandatory": [
                    "left_command"
                ]
            }
        },
        "to": [
            {
                "key_code": "c",
                "modifiers": [
                    "left_command"
                ]
            },
            {
                "key_code": "c",
                "modifiers": [
                    "left_command"
                ]
            },
            {
                "key_code": "c",
                "modifiers": [
                    "left_command"
                ]
            }
        ],
        "type": "basic"
    }
]

Now that should make the copy flash a few times in the menu.
You can increase or decrease as much as you want. Personally I have a few more.


text:
Q: Using Like in Rails SQL I got a little problem using the LIKE sentence on rails i know that this next sentence works:
Brand.find(:all, :joins=>[:cars], :conditions=>["brandname LIKE ?","%ford%"])

But it's any way around that I could to something like this:
Brand.find(:all, :joins=>[:cars], :conditions=>["brandname LIKE '%ford%'"])

Its because i already have a function that returns all conditions on a single string, but i require to support search in strings and i don't really how to get it work.
Any help will be appreciated.

A: I'm not entirely certain that I understand what you're talking about.  Are you trying to pass in a variable into the conditions?
I would re-write this query just a tad.
Brand.all.joins(:cars).where("brandname LIKE ?", "%#{some_variable}%")

Of course selecting all can be bad for performance if you get a lot of records so you may want to consider limiting that or paginating the results somehow.
I would recommend the guides.  Using an array would be great in this instance
Brand.all.joins(:cars).where("brandname LIKE ?", "%#{params[:brand_search]}%")


text:
Q: Regex to remove everything between two characters I have the following string:
"dog-00.jpg|image/jpeg   [remove]
dog-01.docx|application/vnd.openxmlformats-officedocument.wordprocessingml.document   [remove]
dog-02.png|image/png   [remove]"

If you were to format that nicely, you'll see something like this:
dog-00.jpg|image/jpeg
 [remove]

dog-01.docx|application/vnd.openxmlformats-officedocument.wordprocessingml.document
 [remove]

dog-02.png|image/png
 [remove]

So I have a bunch of anchor tags with breaks between them. In each anchor's text, I want to remove the pipe character and the file type:

dog-00.jpg|image/jpeg

becomes

dog-00.jpg

And the regex ought to work for all future file types too, for example:

dog-01.docx|application/vnd.openxmlformats-officedocument.wordprocessingml.document

becomes

dog-01.docx

I still need the full anchors, so after removing the file type, the text becomes:
dog-00.jpg
 [remove]

dog-01.docx
 [remove]

I am not very good at Regex, but I tried various combinations that all failed to match

A: Don't use regex to parse complex HTML, you can use HtmlAgilityPack. I'd also use string methods like Contains, IndexOf and Remove instead of regex:
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html); // pass in your HTML string

foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
{
    string text = link.InnerText;
    if (text.Contains('|'))
        link.InnerHtml = text.Remove(text.IndexOf('|')); // you can't modify InnerText directly but this works
}

string result = doc.DocumentNode.OuterHtml; // your desired result

A: Input:
dog-00.jpg|image/jpeg
Regex that matches only the part before the | pipe:
([^|]+)
description:
The above regex matches everything until the first pipe-character occurs.
C# code:
var input = @"dog-00.jpg|image/jpeg";
var regex = new Regex(@"([^|]+)");
var m = regex.Match(input);
string name = null;
if (m.Success)
{
     name = m.Groups[1].Value;
}

EDIT:
If this is only about spliting the string by the pipe-character, Dylan Nicholson's variant with input.Split (or .Substring + .IndexOf) might be more performant that regular expressions...
EDIT2:
Are regular expressions required? If not, try the following:
public static string Clean(string input)
{
    var sb = new StringBuilder(input);
    int m1 = -1, m2 = -1;
    for(var i = 0; i < sb.Length; i++)
    {
        if (sb[i] == '|')
            m1 = i;
        if (sb[i] == '<')
            m2 = i;
        if (m1 > -1 && m2 > -1 && m2 > m1)
        {
            sb.Remove(m1, m2 - m1);
            i = m1;
            m1 = -1;
            m2 = -1;
        }
    }
    return sb.ToString();
}

A: Updated
You can use this regex:
(?<=]*>[^|]+?)\|.*?(?=)

For C#:
 your_string = Regex.Replace(your_string, "(?<=]*>[^|]+?)\\|.*?(?=)", "",
    RegexOptions.IgnoreCase | RegexOptions.Multiline);

Just replace the string using this regex.


text:
Q: I can't figure out why my code is making a white space separating my header and content I can't figure out why my code is making a white space separating my header and content.
Also, I want the yellow background of my sidebar to extend to the bottom of the page, not after I'm done with the links. How can I fix these things?!
Here's a picture of what it looks like:

Here's my HTML code:
<!DOCTYPE html>

<title>DownloadThis</title>
<link href="myStyle.css" rel="stylesheet" type="text/css">

DownloadThis Music Store

Home

Search

Shopping Cart

Logout

And my CSS:
.container {
    width: 80%;
    height:100%;
    max-width: 1260px;
    min-width: 780px;
    background-color: #FFF;
    margin: 0 auto;
}

.header {
    background-color: rgba(255,130,255,.8);
    height:100%;
    margin: 0 auto;
}

.sidebar {
    float: left;
    width: 20%;
    height:100%;
    background-color: #FFFF99;
}

.content {
    width: 80%;
    height: 100%;
    background-color: rgba(238,233,233,.8);
    text-align: left;
    padding: 10px 0;
    float: left;
}

A: Here is how I would approach your layout:
http://jsfiddle.net/xfaTA/
HTML

          DownloadThis
          Music Store

Home

Search

Shopping Cart

Logout

            content

CSS
.container {
    width: 80%;
    height:100%;
    max-width: 1260px;
    min-width: 780px;
    background-color: #FFF;
    margin: 0 auto;
}

.header {
    background-color: rgba(255,130,255,.8);
    height:100%;
    margin: 0 auto;
}

.header h1 span {color:#fff;}

.sidebar-content-container { overflow:hidden; }

.sidebar {
    float: left;
    width: 20%;
    height:100%;
    background-color: #FFFF99;
}

.content {
    width: 80%;
    height: 100%;
    background-color: rgba(238,233,233,.8);
    text-align: left;
    padding: 10px 0;
    float: left;
}

A: The space between header and content is because of h1's margins
.header h1 {
    margin: 0;
}

You can find similar bugs in future using Firebug or Opera Dragonfly or other similar tool.
height: 100% can't solve the problem, because it just means "100% of parent element". So with that you just can't get stretching and flexible height of the whole document.
I'd change your code this way:

DownloadThis Music Store

Home

Search

Shopping Cart

Logout

CSS (deleted properties marked by hyphens):
.container {
    width: 80%;
    -height:100%;
    max-width: 1260px;
    min-width: 780px;
    background-color: #FFF;
    margin: 0 auto;
}
.header {
    background-color: rgba(255,130,255,.8);
    -height:100%;
    margin: 0 auto;
}
.sidebar {
    -float: left;
    width: 20%;
    -height:100%;
    background-color: #FFFF99;
}
.content {
    width: 80%;
    -height: 100%;
    background-color: rgba(238,233,233,.8);
    text-align: left;
    padding: 10px 0;
    -float: left;
}

/* to be added */
.header{
    width: 80%;
    max-width: 1260px;
    min-width: 780px;
}
.container {
    display: table;
}
.sidebar, .content{
    display: table-cell;
}

BTW, floats are evil. Don't put them everywhere. They should be used only if really needed.

A: Try setting your content and sidebar margins to
margin-top:0;

A: Add position: absolute; to the .sidebar. As for the white space it seems to be sometihing to do with the image on the header.
Demo


text:
Q: How to add TXT record in route 53 without domain name in end I have a hosted zone for eg. "example.com". I want to add a txt record with name "@" sign only. But in route 53 while creating a new record set it defaults come with the domain name in the end.
So, It adds a new record set with "@.example.com" rather than just "@" as a name.
Is it possible to add just "@" or is that "@" resolves to "@.example.com" on backend of creating a new record.

A: Route 53 doesn't treat @ as special character.  What you will want to do is remove the @ character and leave the name value empty.


text:
Q: Breeze where query for many-to-many with intermediate entity in EF I am using EF6, WebApi2, AngularJS and BreezeJs.
I have the following entities:
Person
{
   public string Name { get; set;}
   public virtual ICollection<GenericProfileCountry> Countries { get; protected set; }
}

public class GenericProfileCountry
{
    public string PersonId{ get; set; }
    public virtual Person Person{ get; set; }
    public string CountryIso { get; set; }
    public virtual Country Country { get; set; }
}

public class Country
{
    public string Iso { get; set; }
    public string Name { get; set; }
}

Now I have a query that brings all Persons through breeze as follows:
return zEntityQuery.from('Contacts').expand('Profile, Countries')
        .orderBy(contactOrderBy)
        .toType(entityName)
        .using(self.manager).execute()
        .to$q(querySucceeded, self._queryFailed);

What I would like to do is perform a where statement on the above query with criteria that are on the intermediate entity. So say I want to bring only contacts that their first country (a person can have multiple countries) iso code is equal to 'GB'.
In Linq it would be something like Contacts.Where(contact => contact.Countries.First().CountryIso == 'GB')
Could something similar be expressed in the where(predicate) of breeze? I thought of going the other way (start from the intermediate table and filter from there), but not sure if that is the correct approach.

A: You can achieve that by creating a predicate with the keyword any or all
.where('Countries','any','CountryIso','eq','GB')

In case you want to create a predicate on grand children : BreezeJS Predicates on 2nd level expanded entities
Edit
If you want to get the first contacts whose countries Isos start with 'GB', you can achieve that by:

*

*Jay's suggestion.

*using Linq at Breeze controller:
public IQueryable<Person> ContactsWithFilteredCountryIso(string CountryIso)
    {
        return _contextProvider.Context.Persons.Where(p => p.Countries.First().CountryIso== CountryIso);
     }

Then on the client:
return zEntityQuery.from('Contacts')
        .withParameters({ CountryIso: "GB"})
        .expand('Profile, Countries')
        .orderBy(contactOrderBy)
        .toType(entityName)
        .using(self.manager).execute()
        .to$q(querySucceeded, self._queryFailed);

A: Writing a select projection on countries with bringing up Contacts can be implemented by issuing a Breeze query on countries and expanding contact:
return zEntityQuery.from('Countries').expand('Contact')
        .select('Country.name')
        .where('CountryIso','eq','GB')
        .orderBy(contactOrderBy)
        .toType(entityName)
        .using(self.manager).execute()
        .to$q(querySucceeded, self._queryFailed);


text:
Q: How to print 5 random alphanumeric strings on one click in Javascript? I am able to create single alphanumeric string at a time by clicking on a button by using Math.random() function.
But i need to print 5 alphanumeric random values at a time by clicking on button.
Please help me out I am beginner in javascript and got stuck.
I really need some solution for that

A: This works by generating random numbers in base 10 then converting them to base 36, where digits include both numbers and letters (10 digits + 26 letters = 36).

'use strict';
document.querySelector('button').onclick = function () {
  const strings = new Array(5)
    .fill()
    .map(() => Math.random() * 10000)
    .map((n) => n.toString(36).replace(/\./, ''));
  console.log(strings);
}
<button>Click</button>

A: This works: Generating random number with Math.random between 65 and 100 (ASCII: A-Z and 10 more for the digits) and useString.fromCharCode to convert it to char. For getting the number subtratct the differnce in ASCII if the random is greater 90.  Use a for-loop and add the chars.

document.getElementById('btn').addEventListener('click', () => {
    let random = '';
    for (let x = 0; x < 5; x++) {
        let randInt = Math.floor((Math.random() * 35) + 65);
        random += String.fromCharCode((randInt<=90) ? randInt : randInt-43);
    }
    document.getElementById('random').textContent=random;
});
<button id='btn'>Random</button>


text:
Q: Maya 2018 splash screen disappear - wont start I had problem that Maya 2018 gave me the following error message when I tried to start it:

"maya" could not load the qt platform plugin "windows" in "".

Then I have downloaded the 2018.5 Update via the Autodesk Desktop App.
But now Maya gives me the splash screen and says it is loading and then it disappears and it won't start.
The message under the version number, so "Maya loading.", does not change.
How do I fix that?
Splash screen:

A: Recently I wanted to try to develop a plugin for Maya and messed with the Windows' environment location for MAYA_LOCATION and DEVKIT_LOCATION. I just remembered this and deleted them after this page(https://www.techjunkie.com/environment-variables-windows-10/).
For the setup for the environment variables I used your documentation(https://help.autodesk.com/view/MAYAUL/2019/ENU/?guid=__developer_Setting_up_your_build_Windows_envir...).
Now Maya 2017, Maya 2018 starts properly, Maya 2019 as before!


text:
Q: Minimum number of observations needed for penalized regression? I'm wondering what should be the minimum sample size to perform ridge, lasso or elastic net regression. I have a binomial outcome that I want to relate with a set of features (18 features in some cases and 36 in some others).
I'm performing a repeated analysis on subgroups of a population (penalized regression). Some of this subgroups have a moderate-large sample size (103 individuals). Some others have a total number of observations of 1, 4, 5 ,7 ,9 , 19 and so on.
From which sample size should I start consider the use of ridge/lasso/elastic net?
Thanks in advance!

A: Penalized estimation can be used for very small sample sizes; it's just that the estimates will be shrunk to the mean very heavily, so the estimates will be conservative.  But the intercept in the model is not shrunk, and for binary $Y$ the minimum sample size needed just to estimate the intercept in a logistic model is $n=96$ yielding a margin of error of $\pm 0.1$ in estimating the probability.  If you want to make subgroup-specific estimates that translates to 96 observations per subgroup.
I assume your outcome is Bernoulli, not binomial.

A: First, a comment on you overall design. You will almost certainly be better off if you analyze all your fields together. Even if "the plants field[s] are compatible only if they have the same age and ground material," that doesn't mean that you have to partition the data for analysis. You could include variables for age, ground material, etc in your model to account for these differences. That is typically much more powerful (in the statistical sense) than is analyzing separate subgroups.
Second, it's not completely clear how you intend to structure the form of the regression model. However you do this, make sure that you include information about the total number of plants in each field, not just the number or proportion that got the disease.
Third, to your question about sample sizes for penalized regression. I find it helpful to start with how many variables you can consider with a standard regression model. In your case, the number of plants that got the disease would be a guide: about 1 variable per 15 diseased plants if less than half of plants got the disease. (If you insist on doing separate subgroup analyses, then this limit would apply to each separate analysis. That's another reason to do a combined analysis in which you examine all fields together and include variables like age and ground material that characterize different fields.) So if you have 18 continuous variables plus a variable for the age of fields and one for each of a small number of ground types for the fields, something on the order of 300 diseased plants might be sufficient to consider even a standard non-penalized regression (300/15 = 20 variables), if the relations of the variables to outcome (in the appropriate scale) are linear and there are no interactions among predictors with respect to outcome.
One way to think about penalized regression methods is that they reduce the effective degrees of freedom used by the model. For the non-penalized regression, these degrees of freedom equal the number of predictor variables, including any dummy variables for multi-level categorical variables, interaction terms, and so forth. (The 15 diseased plants per variable guideline above is more precisely per degree of freedom.) Increasing the penalty used for ridge, LASSO, or their hybrid elastic net decreases the effective degrees of freedom, allowing consideration of more variables for the same data set.
If you set the penalty high enough, you can go as low as you want in terms of effective degrees of freedom. So from that perspective there really is no minimum number of samples you need before you apply these penalized methods. The problem is that with small numbers of samples the amount of penalization that you need to get a reliable model may be so great that you have only limited predictive power. After cross-validation to choose the penalty value, bootstrapping to evaluate the final model will provide information on how well the model might be expected to generalize outside your data sample.


text:
Q: jquery, dont execute script code on html() I've this code
jQuery('#div').html('<script>alert("aaa")</script>')

I remember that in the past this was a problem because script was not executed, but now it's executed, how I can make it don't execute?

A: Not sure what you would need to use this for but you could put it in a function, then call that function when you want to execute.

A: One solution is to use the DOM element innerHTML.
jQuery('#maincontent').get(0).innerHTML = ('<script>alert("aaa")</script> ')

This way the script is not being evaled, not sure how to disable that behavior on jquery thoguht

A: you can add a fake type and then remove it
$('#div').html('<script type="text/none">alert("aaa")</script>')
$('#div').removeAttr('type')


text:
Q: How to compile jar file containing only .java source files into .jar files containing .class files with Eclipse I have a .zip file that contains a package that holds the different source code files generated from http://www.jsonschema2pojo.org/.
I initially thought I'd be able to add the generated code (contained in .zip file) to my build path directly, however I discovered that I cannot work with .java files in my project, as importing the .zip file into my project shows the package path to be empty.
It turns out that I cannot use this .zip file because it is full of .java source files and it has no .class files.. which is why when I attempt to reference the file from my project, it says it can't resolve it to a type.
I know I can just go through the zip file, create the package and classes and copy/paste the source code, compile all of that, and then reference that in my program. However, there has to be an easier way than just doing all of this manually.
How do I convert a .zip file full of source into a .zip file full of class files directly referenceable from my Eclipse?

A: There is no easy way of achieving what you are looking for, I would recommend to write up a utility program which can take input as ZIP file, iterate the file list, read and create the package folder structure and copy the file to the location. Before executing this program, you have to create eclipse Java project so that the extracted files can be copied to the workspace. This way it functions properly when program generates the file and then you can extract this package in .jar file.


text:
Q: Having trouble trying to display multiple simplepie rss feeds, as well as one merged So here is the main simplepie code I'm trying to use, and I don't really understand how to initialize the other feeds I have set up. Basically what I'm trying to do is place each of those $feeds into different divs so the first div displays all 3 feeds, and then one div for each after that.
<?php
// Include the SimplePie library
require_once('simplepie.inc');

// Because we're using multiple feeds, let's just set the headers here.
header('Content-type:text/html; charset=utf-8');

// These are the feeds we want to use
$feeds = array(
    'SITE ONE URL',
    'SITE TWO URL',
    'SITE THREE URL');

$feeds2 = array(
    'SITE ONE URL');

$feeds3 = array(
    'SITE TWO URL');

$feeds4 = array(
    'SITE THREE URL');

// This array will hold the items we'll be grabbing.
$first_items = array();

// Let's go through the array, feed by feed, and store the items we want.
foreach ($feeds as $url)
{
    // Use the long syntax
    $feed = new SimplePie();
    $feed->set_feed_url($url);
    $feed->init();

    // How many items per feed should we try to grab?
    $items_per_feed = 3;

    // As long as we're not trying to grab more items than the feed has, go through them one by one and add them to the array.
    for ($x = 0; $x < $feed->get_item_quantity($items_per_feed); $x++)
    {
        $first_items[] = $feed->get_item($x);
    }

    // We're done with this feed, so let's release some memory.
    unset($feed);
}

// We need to sort the items by date with a user-defined sorting function.  Since usort() won't accept "SimplePie::sort_items", we need to wrap it in a new function.
function sort_items($a, $b)
{
    return SimplePie::sort_items($a, $b);
}

// Now we can sort $first_items with our custom sorting function.
usort($first_items, "sort_items");

// Begin the (X)HTML page.
?>

A: I would like to help but need to understand better what you are trying to do. As per my understanding you want to populate a top div with ALL THE CONTENTS OF THE THREE FEEDS and, then, below, have a separate div with each of the feeds contents. Like:

 feed1-content-1
 feed1-content-2
 feed1-content-3
 feed2-content-1
 feed2-content-2
 feed2-content-3
 feed3-content-1
 feed3-content-2
 feed3-content-3

 feed1-content-1
 feed1-content-2
 feed1-content-3

 feed2-content-1
 feed2-content-2
 feed2-content-3

 feed3-content-1
 feed3-content-2
 feed3-content-3

If that is what you want, I would like to throw in my 2cents: why the redundancy? However, only the coder really knows what (s)he wants to achieve. My suggestion is simple: just append a paragraph into the divs:
$('#feeds').append('
'+feed+'
');
and the appropriate feed into the appropriate div in the same way.


text:
Q: Does std::move helps with objects on stack? I just saw a college doing this optimization today:

i.e., change this:
std::string somestring =  "somestring";
std::map<std::string, int> myglobalmap;

std::string myfunction( const std::string& mystring, int myint )
{
    myglobalmap.insert( std::pair<std::string, int>( mystring, myint ) );
}
myfunction(somestring, 10)

To:
std::string somestring =  "somestring";
std::map<std::string, int> myglobalmap;

std::string myfunction( std::string mystring, int myint )
{
    myglobalmap[ std::move(mystring) ] = myint;
}
myfunction(somestring, 10)

He claimed that passing the value mystring by copy instead of passing it as a constant reference would be faster because the move operation would be only performed with objects on the stack. But I could not see why this would help. I searched about the move operator and I found out it does not move anything, it just makes my expression to return a reference.
Then, if this is true, passing the value by copy would not be slower than passing it by reference and calling std::move or does calling std::move help with objects on the stack in this case? If I understand correctly, std::move should only help with objects on the heap. Then, calling it with something on the stack should not help or it does?
Related questions:

*

*What is std::move(), and when should it be used?

*Is it possible to std::move local stack variables?

A:
and I found out it does not move anything, it just makes my expression to return a reference.

This is correct. Crucially, the result of the function is an xvalue.

Then, if this is true, passing the value by copy would not be slower than passing it by reference and calling std::move or does calling std::move

In case of std::string (assuming the contained string isn't trivially small), a copy and a move is slower than indirection through a reference and move.

In your first example, you indirect through a reference and always make a copy.
In the second example, you copy only if the function argument is an lvalue. Second is faster than the fist when the argument is an rvalue (as long as the stored string is long enough for the difference to be significant).

Both versions have undefined behaviour because the functions are declared to return non-void, but do not return a value.

A: First, I'd like to say that this changes the behavior of myfunction.  The first version does not insert the integer if the key already exists in the map.  The second version replaces the integer with the new value.
That said, In the case where the passed string is not already in the map, and hence it would have made a copy, this could be slightly more efficient.  If myfunction is passed a temporary, the compiler could move construct (or even optimize the move out), and that would then be moved into the map.  While std::move doesn't move anything, using it causes the map::operator[] to use the rvalue reference overload, which can in turn invoke the move constructor on std::string.
However, in cases where the key already exists, it might cause the creation of an extra copy that's not needed.

A: I had missed an important point in the question, there was a lock right before myglobalmap.insert( and the new myglobalmap[.
i.e., the change was this:
std::string somestring =  "somestring";
std::map<std::string, int> myglobalmap;
std::mutex g_pages_mutex;

std::string myfunction( const std::string& mystring, int myint )
{
    std::lock_guard<std::mutex> guard(g_pages_mutex);
    myglobalmap.insert( std::pair<std::string, int>( mystring, myint ) );
    return "";
}
myfunction(somestring, 10)

To:
std::string somestring =  "somestring";
std::map<std::string, int> myglobalmap;
std::mutex g_pages_mutex;

std::string myfunction( std::string mystring, int myint )
{
    std::lock_guard<std::mutex> guard(g_pages_mutex);
    myglobalmap[ std::move(mystring) ] = myint;
    return "";
}
myfunction(somestring, 10)

So in extension to the answer provided by @eerorika, the optimization performed was to call the copy constructor before getting the lock. Meaning the second version should be faster as the copy is performed without holding a lock.


text:
Q: Difference between EKEvent's eventIdentifier and calendarItemExternalIdentifier Reading Apple's docs, I'm still confused as to what the difference is between EKCalenderItem's calendarItemExternalIdentifier and EKEvent's eventIdentifier, and which one we should use to identify calendar events across different devices. Specifically:

EKCalendarItem calendarItemExternalIdentifier
  The calendar item's external identifier as provided by the calendar server. (read-only)

and

EKEvent eventIdentifier: A unique identifier for the event. (read-only)

EKCalendarItem calendarItemExternalIdentifier was added in iOS6, and I would have thought this would be the identifier I need to save to call later in EKEventStore eventWithIdenfier: since it claims:

This identifier allows you to access the same event or reminder across
  multiple devices.

But in my own testing, it seems that when I create and save a new EKEvent, the eventIdenifier I get from the EKEvent object is unique and useful, and the calendarItemExternalIdentifier I get doesn't seem to work with EKEventStore eventWithIdenfier:
If someone has a conclusive answer, I would love to know.

A: calendarItemExternalIdentifier is the event's RFC 5545 globally unique identifier. It is not specific to EKEventStore, and indeed it represents that event across devices (as well as across non-iOS clients). If you were to open up an .ics attachment from your inbox, this value would be shown in the UID field of the invite.
That said, you cannot directly look up EKEventStore events based on this identifier. Instead, you'll need to do a predicate search on the event store and check the calendarItemExternalIdentifier on each event.

A: calendarItemExternalIdentifier can be looked up with
func calendarItemsWithExternalIdentifier(externalIdentifier: String) -> [EKCalendarItem]

Although availibility is marked with iOS 6.0,
it may be undocumented (even private api) until recently.
The interesting thing is, that you can get multiple Items back,
so it should be possible to get all occurences of a recurring event
(not yet tested)
Also the documentation of calendarItemExternalIdentifier seems to be updated,
just for the sake of completeness, here it is:

This identifier allows you to access the same event or reminder across multiple devices.
   There are some cases where duplicate copies of a calendar item can exist in the same database:
A calendar item was imported from an ICS file into multiple calendars
An event was created in a calendar shared with the user and the user
  was also invited to the event
The user is a delegate of a calendar that also has this event
A subscribed calendar was added to multiple accounts
In such cases, you should choose between calendar items based on other
  factors, such as the calendar or source.
Recurring event identifiers are the same for all occurrences. If you
  wish to differentiate between occurrences, you may want to use the
  start date.
For Exchange servers, the identifier is different between iOS and OS X
  and different between devices for reminders.


text: Q: Shortcut to jump to first Google Search result I have read a couple of different sources but nothing has worked for me. Does anyone know how to use the keyboard to directly jump with the key selector to the first search result on Google (in Chrome)? TAB (only with multiple presses), ENTER, DOWN all didn't work for me.


text:
Q: auth_info in janrain authentication I am trying to use janrain to handle authentication fir many providers in my Android app. After a successful provider login I get the auth_info data from janrain.
I am trying to understand the details in it but I can't find anything in the documentation. Specifically I am interested in the "device_token" and the "token" variables.
Providing excerpts from two providers:
Google+ provider:
{device_token=fb95763f605f13f8d71cd5d18ec9a5275xxxxxx, token=04c858ede0e14035a4d17c3ccab987b91xxxxxx, stat=ok, profile={providerSpecifier=googleplus, googleUserId=xxxxxxxx
.
.
.
}
Facebook provider:
{device_token=986e9c441cfec5093f608a5c7a672981cxxxxxx, token=748b628d2e82d593fdc271793e9672c9axxxxxx, stat=ok, profile={providerSpecifier=facebook, providerName=Facebook
.
.
.
}
Can anyone explain why I need the two tokens?

A: "device_token" is for Social Sharing.
"token" is a one-time use token that is used with the auth_info endpoint.
So if you don't have Social Sharing, then you wouldn't really need to use the "device_token".
Here is the Janrain Mobile SDK repo, as well as documentation: https://github.com/janrain/jump.android/blob/master/Docs/Jump_Integration_Guide.md


text:
Q: Проблема при отправке на проверку Ребят, кто может объяснить, что за используемые права и как устранить?  Интегрировал приложение с healthkit, из приложения передаю только время тренировки и калории, в приложение никаких данных из healthkit не принимаю.

A: Тебе в info.plist (или в настройках таргета на вкладке Info) нужно добавить ключ (это будет массив) UIRequiredDeviceCapabilities с элементом-строкой healthkit. Это разрешит ставить программу только на девайсы, поддерживающие healthkit.
PS: правильный ответ - в апдейте существующего приложения нельзя ограничивать семейства или какие-то модели девайсов, которые поддерживались раньше. Нужно или регистрировать новое приложение или проверять наличие классов и методов из кода.


text:
Q: Watir-webdriver, can't "cast" an element to subtype even though it's found I'm having a really strange issue with watir-webdriver.
Here's a snapshot of the input tag I'm trying to reach (couldn't figure out a way to get the source after the javascripts created the popup, lol)

Anyway here's some of my code that uses xpath to locate these elements (there is two text fields and a select tag)
firstname = b.element(:xpath, "//div[@class='ap_popover']/input[@name='firstName']")
lastname =  b.element(:xpath, "//div[@class='ap_popover']/input[@name='lastName']")
authorselector = b.element(:xpath, "//div[@class='ap_popover']/select")
puts firstname
puts lastname
puts authorselector

This code successfully returns the watir element objects. However when I try to cast them:
puts firstname.to_subtype

it freaks out:

C:/Ruby192/lib/ruby/gems/1.9.1/gems/watir-webdriver-0.4.1/lib/watir-webdriver/elements/element.rb:262:in
  `assert_exists': unable to locate element, using
  {:xpath=>"//div[@class='ap_popover']/input[@name='lastName']"}
  (Watir::Exception::UnknownObjectException)

So, what's going on? It can find them via xpath no problem but then when I try to cast them all of a sudden xpath search fails?
It's worth mentioning the html I'm perusing through is created in it's entirety by javascript, hence why I couldn't just copy\paste it here and had to take a screenshot.
Thanks!

A: xpath is evil  avoid it if at all possible. it's too easy to make mistakes, hard to read, and generally slower.
Have you tried something like
b.div(:id => 'contributors-table').textfield(:name => 'firstName')

If you have some wacky invalid HTML where they have two copies of all this stuff (and thus duplicated ID values which is not valid for HTML standard) then you can add in the INDEX of the element, which in this case might be needed both for the div container, and then maybe also for the input field if there are more than one of them.
b.divs(id => 'contributors-table').size  #how many are there?

#example, second instance of the contributors table, third instance in that table of an text input field with the name 'firstName'
b.div(:id => 'contributors-table', :index => 1).textfield(:name => 'firstName', :index => 2)


text:
Q: Swift JSONDecoder replace all missing keys by default value? I want to set up a remote configuration file for staged feature releases, seasonal changes, offers etc. that wouldn't be worth going through App Review for.
I used to use a \n separated text file but for multi-line strings this gets a bit awkward real quick.
Instead of importing some bloated framework like Firebase for this, I am currently writing a small singleton that parses a configuration file from a remote URL.
I am however facing one issue now:
If the remote json contains a key that's not defined in my Codable struct everything works fine, I still get my object with all the defined keys. Not so much the other way around, if the json is missing a key defined in the struct, JSONDecoder is not able to decode. Example:
    let testJSON = """
{"version":1,"includedB":"B","___notIncludedC":"C"}
"""

struct DefaultConfiguration : Codable {
    var version = 1
    var includedB = "2"
    var notIncludedC = "3"
}

I can make the decoding """work""" by defining the notIncludedC to be of an optional String? - this however makes the result be nil after decoding instead of keeping its predefined default value.
All the answers on SO mention defining custom methods for each key, but I would rather like to use a "skip unknown and keep the value" approach because for big JSON's that would come with a lot of overhead code.

A: As a it was described in the comments you will have to write your own init() since the synthesized one can not provide the behavior you need:
let testJSON = """
{"version":1,"includedB":"B","notIncludedC":"C"}
"""

struct DefaultConfiguration : Codable {
    var version = 1
    var includedB = "2"
    var notIncludedC = "3"

    enum CodingKeys: String, CodingKey {
        case version
        case includedB
        case notIncludedC
     }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        version = try container.decode(Int.self, forKey: .version)
        includedB = try container.decode(String.self, forKey: .includedB)
        notIncludedC = try container.decodeIfPresent(String.self, forKey: .notIncludedC) ?? "3"
    }
}


text:
Q: JUPYTER AND CONDA FOR R I want to use R in Jupyter in windows 7. I have installed anaconda and tried to install "R Essentials" following the directions given in this link. But I am getting  "SSL verification error, package not found error" as shown in the screenshot. . I have been using R in Jupyter in windows 8,10 and Mac. I am not sure why it is failing in windows 7.

A: I set conda to not verify following this answer as shown below and everything worked fine.
       conda config --set ssl_verify false
       conda update requests
       conda install -c r r-essentials


text:
Q: Bottom Sheet in fragment behind BottomNavigationView In my fragment, on a button click I need to show a bottom sheet dialog but it must appear from behind the bottom navigation bar. A similar problem has already been addressed here but
due to some strains, I need to create the bottom sheet by extending BottomSheetDialogFragment only.
activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/navigationHost"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavigation"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/navigation" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigation"
        android:layout_width="match_parent"
        android:layout_height="61dp"
        android:layout_marginStart="14dp"
        android:layout_marginEnd="14dp"
        android:layout_marginBottom="30dp"
        android:background="@drawable/bg_bottom_nav_rounded"
        app:itemIconTint="@color/selector_bottom_navigation_text"
        app:itemTextColor="@color/selector_bottom_navigation_text"
        app:labelVisibilityMode="labeled"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/navigationHost"
        app:menu="@menu/dashboard_navigation_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>

fragment_home.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/darker_gray">

    <Button
        android:id="@+id/openBottomSheet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

FragmentHome.kt
class FragmentHome : Fragment(R.layout.fragment_home) {
    private val binding by viewBinding(FragmentHomeBinding::bind)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.openBottomSheet.setOnClickListener {
            val bottomSheetDialog: BottomSheetDialog = BottomSheetDialog()
            bottomSheetDialog.show(requireActivity().supportFragmentManager, "TEST")
            bottomSheetDialog.enterTransition
        }
    }
}

BottomSheetDialog.kt
  public class BottomSheetDialog extends BottomSheetDialogFragment {
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            super.onCreateView(inflater, container, savedInstanceState);
            return inflater.inflate(R.layout.bottomsheet_login, container, false);
        }

        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
        }
    }

UPDATE:
Screenshots

A: This is a common problem with BottomSheet or Snackbar, you need to add a CoordinatorLayout as a parent root view on the activity. Put a CoordinatorLayout as a parent, and inside that put your ConstraintLayout


text:
Q: Getting ad status without other meta data Is there a way to get Facebook ad status (adgroup_status & ad_status) without getting all the targeting and creative information. From the documentation it seems like one can only get status when making the following call  /{adgroup-id} which returns all the meta data about the ad.
The above call you return the following data
{
   "id":"6004196911039",
   "data":{
      "adgroups":{
         "6004196911039":{
            "adgroup_id":6004196911039,
            "ad_id":6004196911039,
            "campaign_id":6003417011234,
            "name":"test",
            "ad_status":4,
            "adgroup_status":4,
            "bid_type":1,
            "max_bid":"30",
            "bid_info":{
               "1":"30"
            },
            "account_id":368811234,
            "id":"6004196911039",
            "creative_ids":[
               6004196615439
            ],
            "targeting":{
               "countries":[
                  "US"
               ],
               "friends_of_connections":[
                  {
                     "id":"6004008089439",
                     "name":null
                  }
               ]
            },
            "start_time":null,
            "end_time":null,
            "updated_time":1328021899
         }
      },
      "creatives":{
         "6004196615439":{
            "type":25,
            "action_spec":"{'action.type':'like', 'post':10150420410887685}",
            "related_fan_page":1,
            "cluster_id":6004008089439,
            "name":"Sponsored story #6004196615439",
            "run_status":1,
            "preview_url":"http:\/\/www.facebook.com\/ads\/api\/creative_preview.php?cid=6004196615439",
            "count_current_adgroups":2,
            "id":"6004196615439",
            "creative_id":"6004196615439"
         }
      }
   }
}

Getting just the status would be less costly for groups of ads.

A: Answering for other folks who might be searching for the answer.
Yes, you can do this by providing specific fields you want to query as part of your call, for example you can append this to your call:
?fields=adgroup_status,ad_status
And the graph API will only return the specific fields.