text:
Q: Displaying data as listview And Getting an error NullPointerException My problem is that I don't know how exactly I can display data from the database.
Here is my DatabaseHelper activity ( I've cut not needed code ), which open/close database and create tables.
final static String PN_TABLE = "Tablica_Poniedzialek";
    static final String PN_KEY_ID = "_id";
    final static String PN_KEY_TYPE_OF_SESSION ="type_of_session";
    final static String PN_KEY_START_TIME ="start_time";
    final static String PN_KEY_END_TIME ="end_time";
    final static String PN_KEY_NAME ="name";
    final static String PN_KEY_ROOM ="room";

Creating and adding data to the database works fine. The problem is that I don't know how exactly I should display data inserted into the database. I've tried using Cursors and List Adapter, but it seems that I've messed up something since application is forced to close every time I am launching it in an Emulator.
This is my activity which is responsible for getting data from Database and then displaying it. I have no clue how actually I can display data as a list view. I am not sure which method would be better, the one which creates list ( I believe that it does ) or one that simply fetch data from database. But, let's say that the first one is correct, then the question is how can I actually display all the data ?
    package com.projekt;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;

public class PoniedzialekActivity extends ListActivity implements OnClickListener{

    private Button butPnAdd;
    private DatabaseHelper dbhelper;
    private SQLiteDatabase db;
    Cursor cursor;

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_poniedzialek);

        butPnAdd = (Button) findViewById(R.id.butPnAdd);
        butPnAdd.setOnClickListener(this);

        List<Poniedzialek> lista_poniedzialek = getAllPnSession();
        this.setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, lista_poniedzialek));

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.butPnAdd){
        Intent i = new Intent(PoniedzialekActivity.this,dodawaniePoniedzialek.class);
        startActivity(i);
        }
    }
    public List<Poniedzialek> getAllPnSession() {
        List<Poniedzialek> pnsessionList = new ArrayList<Poniedzialek>();
        // Wybierz cale Query
        String selectQuery = "SELECT  * FROM " + DatabaseHelper.PN_TABLE;
        dbhelper.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // petla po wszystkich rzedach & dodawanie ich do listy
        if (cursor.moveToFirst()) {
            do {
                Poniedzialek pn = new Poniedzialek();

                pn.setID(Integer.parseInt(cursor.getString(0)));
                pn.setTypeOfSession(cursor.getString(1));
                pn.setName(cursor.getString(2));
                pn.setStartTime(cursor.getString(3));
                pn.setEndTime(cursor.getString(4));
                pn.setRoom(cursor.getString(5));

                // Dodawanie sesji do listy
                pnsessionList.add(pn);
            } while (cursor.moveToNext());
        }
        cursor.close();
        // return contact list
        return pnsessionList;
    }
    public Cursor fetchPn() {
        SQLiteDatabase db = dbhelper.getWritableDatabase();
        return db.query(DatabaseHelper.PN_TABLE, new String[] {DatabaseHelper.PN_KEY_TYPE_OF_SESSION, DatabaseHelper.PN_KEY_START_TIME,
                DatabaseHelper.PN_KEY_END_TIME, DatabaseHelper.PN_KEY_NAME, DatabaseHelper.PN_KEY_ROOM}, null, null, null, null, null);
    }

} // end PoniedzialekActivity

This is layout_poniedzialek:
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/butPnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/add_pn"
        />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/tab1"
        />

    <ListView
        android:id="@+id/pnListView"
        android:layout_width="304dp"
        android:layout_height="380dp"
        android:layout_gravity="center_horizontal" >

    </ListView>

</LinearLayout>

E D I T
Now I keep getting an error: NullPointerException. This is what I've implemented in poniedzialekActivity ( Please note that DatabaseHelper is the name of class where I keep open/close and static final string attributes - here I am creating 5 tablets )
PoniedzialekActivity class:
public class PoniedzialekActivity extends ListActivity implements OnClickListener{

    private Button butPnAdd;
    private DatabaseHelper dbhelper;
    private SQLiteDatabase db;
    Cursor c;

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_poniedzialek);

        butPnAdd = (Button) findViewById(R.id.butPnAdd);
        butPnAdd.setOnClickListener(this);

        dbhelper = new DatabaseHelper(this);
        dbhelper.open();
        c = dbhelper.fetchPn();
        String[] columns = new String[] { DatabaseHelper.PN_KEY_TYPE_OF_SESSION, DatabaseHelper.PN_KEY_START_TIME, DatabaseHelper.PN_KEY_END_TIME,
                DatabaseHelper.PN_KEY_NAME, DatabaseHelper.PN_KEY_ROOM};
        int[] to = new int[] { R.id.textSession, R.id.textStartTime, R.id.textEndTime, R.id.textName, R.id.textRoom };
        new SimpleCursorAdapter(PoniedzialekActivity.this, R.layout.entry, c, columns, to);
        ListView list = getListView();
        list.setAdapter(new SimpleCursorAdapter(PoniedzialekActivity.this, R.layout.entry, c, columns, to));

    }
    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.butPnAdd){
        Intent i = new Intent(PoniedzialekActivity.this,dodawaniePoniedzialek.class);
        startActivity(i);
        }
    }
}

DatabaseHelper.class
public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "database.db";
    private static final int DATABASE_VERSION = 1;
    public static final String TAG = "ProjectDatabase";

    static final String PN_TABLE = "Tablica_Poniedzialek";
    static final String PN_KEY_ID = "_id";
    static final String PN_KEY_TYPE_OF_SESSION ="type_of_session";
    static final String PN_KEY_START_TIME ="start_time";
    static final String PN_KEY_END_TIME ="end_time";
    static final String PN_KEY_NAME ="name";
    static final String PN_KEY_ROOM ="room";

    static final String WT_TABLE = "Tablica_Wtorek";
    static final String WT_KEY_ID = "_id";
    static final String WT_KEY_TYPE_OF_SESSION ="type_of_session";
    static final String WT_KEY_START_TIME ="start_time";
    static final String WT_KEY_END_TIME ="end_time";
    static final String WT_KEY_NAME ="name";
    static final String WT_KEY_ROOM ="room";

    static final String SR_TABLE = "Tablica_Sroda";
    static final String SR_KEY_ID = "_id";
    static final String SR_KEY_TYPE_OF_SESSION ="type_of_session";
    static final String SR_KEY_START_TIME ="start_time";
    static final String SR_KEY_END_TIME ="end_time";
    static final String SR_KEY_NAME ="name";
    static final String SR_KEY_ROOM ="room";

    static final String CZ_TABLE = "Tablica_Czwartek";
    static final String CZ_KEY_ID = "_id";
    static final String CZ_KEY_TYPE_OF_SESSION ="type_of_session";
    static final String CZ_KEY_START_TIME ="start_time";
    static final String CZ_KEY_END_TIME ="end_time";
    static final String CZ_KEY_NAME ="name";
    static final String CZ_KEY_ROOM ="room";

    static final String PT_TABLE = "Tablica_Piatek";
    static final String PT_KEY_ID = "_id";
    static final String PT_KEY_TYPE_OF_SESSION ="type_of_session";
    static final String PT_KEY_START_TIME ="start_time";
    static final String PT_KEY_END_TIME ="end_time";
    static final String PT_KEY_NAME ="name";
    static final String PT_KEY_ROOM ="room";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    private DatabaseHelper dbhelper;
    private SQLiteDatabase db;

    @Override
    public void onCreate(SQLiteDatabase db) {

        String pn_sql = "CREATE TABLE " + PN_TABLE +
                        "(" + PN_KEY_ID + " integer primary key autoincrement, " +
                        PN_KEY_TYPE_OF_SESSION + " text, " +
                        PN_KEY_NAME + " text, " +
                        PN_KEY_START_TIME + " text, " +
                        PN_KEY_END_TIME + " text, " +
                        PN_KEY_ROOM + " text);";
        String wt_sql = "CREATE TABLE " + WT_TABLE +
                        "(" + WT_KEY_ID + " integer primary key autoincrement, " +
                        WT_KEY_TYPE_OF_SESSION + " text, " +
                        WT_KEY_NAME + " text, " +
                        WT_KEY_START_TIME + " text, " +
                        WT_KEY_END_TIME + " text, " +
                        WT_KEY_ROOM + " text);";
        String sr_sql = "CREATE TABLE " + SR_TABLE +
                        "(" + SR_KEY_ID + " integer primary key autoincrement, " +
                        SR_KEY_TYPE_OF_SESSION + " text, " +
                        SR_KEY_NAME + " text, " +
                        SR_KEY_START_TIME + " text, " +
                        SR_KEY_END_TIME + " text, " +
                        SR_KEY_ROOM + " text);";
        String cz_sql = "CREATE TABLE " + CZ_TABLE +
                        "(" + CZ_KEY_ID + " integer primary key autoincrement, " +
                        CZ_KEY_TYPE_OF_SESSION + " text, " +
                        CZ_KEY_NAME + " text, " +
                        CZ_KEY_START_TIME + " text, " +
                        CZ_KEY_END_TIME + " text, " +
                        CZ_KEY_ROOM + " text);";
        String pt_sql = "CREATE TABLE " + PT_TABLE +
                        "(" + PT_KEY_ID + " integer primary key autoincrement, " +
                        PT_KEY_TYPE_OF_SESSION + " text, " +
                        PT_KEY_NAME + " text, " +
                        PT_KEY_START_TIME + " text, " +
                        PT_KEY_END_TIME + " text, " +
                        PT_KEY_ROOM + " text);";

        db.execSQL(pn_sql);
        db.execSQL(wt_sql);
        db.execSQL(sr_sql);
        db.execSQL(cz_sql);
        db.execSQL(pt_sql);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w("Projekt", "aktualizacja z wersji " + oldVersion
              + " do wersji " + newVersion + " ( stare dane ulegna usunieciu ) ");
                 db.execSQL("DROP TABLE IF EXISTS" + PN_TABLE);
                 db.execSQL("DROP TABLE IF EXISTS" + WT_TABLE);
                 db.execSQL("DROP TABLE IF EXISTS" + SR_TABLE);
                 db.execSQL("DROP TABLE IF EXISTS" + CZ_TABLE);
                 db.execSQL("DROP TABLE IF EXISTS" + PT_TABLE);
        onCreate(db);
    }
    public void open()
    {
            dbhelper.open();
    }
    public void close()
        {
            dbhelper.close();
        }
    public Cursor fetchPn() {
        return db.query(PN_TABLE, new String[] {PN_KEY_TYPE_OF_SESSION, PN_KEY_START_TIME,
                PN_KEY_END_TIME, PN_KEY_NAME, PN_KEY_ROOM}, null, null, null, null, null);
    }
}

This is my MainActivity class, which holds TabHost:
public class MainActivity extends TabActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //--- TABHOST ---//
        Resources res = getResources(); // Resource object to get Drawables
        TabHost tabHost = getTabHost();  // The activity TabHost
        TabHost.TabSpec spec;  // Resusable TabSpec for each tab
        Intent intent;  // Reusable Intent for each tab

        // Create an Intent to launch an Activity for the tab (to be reused)
        intent = new Intent().setClass(this, PoniedzialekActivity.class);
        // Initialize a TabSpec for each tab and add it to the TabHost
        spec = tabHost.newTabSpec("Pn").setIndicator("Pn",
                          res.getDrawable(R.drawable.ic_launcher))
                      .setContent(intent);
        tabHost.addTab(spec);

        // Do the same for the other tabs
        intent = new Intent().setClass(this, WtorekActivity.class);
        spec = tabHost.newTabSpec("Wt").setIndicator("Wt",
                          res.getDrawable(R.drawable.ic_launcher))
                      .setContent(intent);
        tabHost.addTab(spec);

        intent = new Intent().setClass(this, SrodaActivity.class);
        spec = tabHost.newTabSpec("Sr").setIndicator("Sr",
                          res.getDrawable(R.drawable.ic_launcher))
                      .setContent(intent);
        tabHost.addTab(spec);

        intent = new Intent().setClass(this, CzwartekActivity.class);
        spec = tabHost.newTabSpec("Cz").setIndicator("Cz",
                          res.getDrawable(R.drawable.ic_launcher))
                      .setContent(intent);
        tabHost.addTab(spec);

        intent = new Intent().setClass(this, PiatekActivity.class);
        spec = tabHost.newTabSpec("Pt").setIndicator("Pt",
                          res.getDrawable(R.drawable.ic_launcher))
                      .setContent(intent);
        tabHost.addTab(spec);

        tabHost.setCurrentTab(1);
        //--- END OF TABHOST ---//

    }
}

A: setListAdapter() isn't defined for Activity... so I'm not sure how your code even compiles.
You need to inflate your layout, find the ListView using findViewById, and then set its adapter.
ListView lv = (ListView) findViewById(R.id.pnListView);
lv.setAdapter(...);


text:
Q: Python with pytesseract - How to get the same output for pytesseract.image_to_data in a searchable PDF? I have this piece of code in Python that makes use of pytesseract (method pytesseract.image_to_data).
This gives me great text information and coordinates that are saved in a text file that is fed to a third party software. It works perfectly for PDF files that have been scanned
data = pytesseract.image_to_data(Image.open('file-001-page-001.png')))

The issue now is that I have a demand for output in the exact same structure for PDFs that already contain text. It's possible to keep the same code and continue as if the PDF had no text, extracting images and doing OCR, but it doesn't seem like the right solution...
Is it possible to achieve this with pytesseract?
Suggestions are welcome

A: You can use this:
import pytesseract
from PIL import Image

# Open the PDF file
with open('file.pdf', 'rb') as f:
    # Extract text from the PDF file and save it to a variable
    text = pytesseract.image_to_pdf_or_hocr(f, extension='hocr', lang='eng', config='--oem 3 --psm 6')

# Save the extracted text to a file in the desired format
with open('output.hocr', 'w')as f:
    f.write(text)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Resizing image in Core Graphics I am trying to resize a CGImageRef so I can draw it on screen with the size I want.
So I have this code:
CGColorSpaceRef colorspace = CGImageGetColorSpace(originalImage);

CGContextRef context = CGBitmapContextCreate(NULL,
                                             CGImageGetWidth(originalImage),
                                             CGImageGetHeight(originalImage),
                                             CGImageGetBitsPerComponent(originalImage),
                                             CGImageGetBytesPerRow(originalImage),
                                             colorspace,
                                             CGImageGetAlphaInfo(originalImage));

if(context == NULL)
    return nil;

CGRect clippedRect = CGRectMake(CGContextGetClipBoundingBox(context).origin.x,
                                CGContextGetClipBoundingBox(context).origin.y,
                                toWidth,
                                toHeight);
CGContextClipToRect(context, clippedRect);

// draw image to context
CGContextDrawImage(context, clippedRect, originalImage);

// extract resulting image from context
CGImageRef imgRef = CGBitmapContextCreateImage(context);

So this code allows me to apparently draw the image to the size I want, and that's good.
The problem is that the actual image I'm getting once resized even though it looks resized on the screen it is not actually resized. When I do:
CGImageGetWidth(imgRef);
It actually returns the original width of the image and not the width that I see on screen.
So how can I actually create an image that is actually resized and not only drawn the right size I want??
Thanks

A: The issue is that you're creating the context with the same size as the image.  You want to make the context the new size.  And then clipping is unnecessary.
Try this:
CGColorSpaceRef colorspace = CGImageGetColorSpace(originalImage);

CGContextRef context = CGBitmapContextCreate(NULL,
                                             toWidth, // Changed this
                                             toHeight, // Changed this
                                             CGImageGetBitsPerComponent(originalImage),
                                             CGImageGetBytesPerRow(originalImage)/CGImageGetWidth(originalImage)*toWidth, // Changed this
                                             colorspace,
                                             CGImageGetAlphaInfo(originalImage));

if(context == NULL)
    return nil;

// Removed clipping code

// draw image to context
CGContextDrawImage(context, CGContextGetClipBoundingBox(context), originalImage);

// extract resulting image from context
CGImageRef imgRef = CGBitmapContextCreateImage(context);

I didn't actually test it, but it should at least give you the idea of what needs to change.


text:
Q: Natural Sorting of list of string in descending order C# I would like to ask how to sort a List<string> in descending order using the Natural Sort Comparer library.
I would like to ask if you someone have use this library
https://www.codeproject.com/Articles/22517/Natural-Sort-Comparer
to sort a List<string>?
This is the code snippets for ascending
public List<string> contents = new List<string>{ "a,b,c,d,e,f" };
public void sorting()
{
   using (NaturalSortComparer comparer = new NaturalSortComparer())
   {
      contents.Sort(comparer);
   }
}

I'm able to make it work to sort as ascending, but not descending.
Any ideas?

A: Let's implement a simple extension method:
  public static partial class ComparerExtensions {
    public static IComparer<T> Reverse<T>(this IComparer<T> comparer) {
      if (null == comparer)
        throw new ArgumentNullException(nameof(comparer));

      return Comparer<T>.Create((left, right) => comparer.Compare(right, left));
    }
  }

Then you can reverse any comparer (ICompare<T>) you like:
 MyList.Sort(YourCustomComparer.Reverse());

In your case (a bit strange implmentation with comparer implementing IDisposable):
 using (var naturalComparer = new NaturalComparer()) {
   contents.Sort(naturalComparer.Reverse());
 }

Edit: In case of C# 4.0 or earlier version (which doesn't have Comparer<T>.Create) we can implement the extension method like this:
  public static partial class ComparerExtensions {
    private sealed class ReversedComparer<T> : IComparer<T> {
      private readonly IComparer<T> m_Comparer;

      public ReversedComparer(IComparer<T> comparer) {
        m_Comparer = comparer;
      }

      public int Compare(T x, T y) {
        return m_Comparer.Compare(y, x);
      }
    }

    public static IComparer<T> Reverse<T>(this IComparer<T> comparer) {
      if (null == comparer)
        throw new ArgumentNullException(nameof(comparer));

      return new ReversedComparer<T>(comparer);
    }
  }

A: You have two options:

*

*Horrible, never do this: use the ascending order and then simply call Reverse() method (I'm only listing this option as a warning because, believe it or not, I've seen it more than once in production code).

*The good way: Implement an IComparer<string> that simply returns the negative of the "ascending" comparer (or switches the argument order) and pass it into your sorting method.

But nº2 is already built in the framework for you; its the extension method OrderByDescending:
var ss = new[] {"a1", "a03", ... }
var descending = ss.OrderByDescending(
    s => s,
    new NaturalComparer());

UPDATE: Your updated question seems to imply you want to use List.Sort. In that case the way to go is #2, OrderBy will not sort in place.


text:
Q: Getting data by value I'm messing around with XPath in Java and I seem to hit a wall. I've got the following XML document
<?xml version="1.0" encoding="UTF-8"?>
<database>

    <student>
        <index>1234</index>
        <courselist>
            <course name="analiza matematyczna 1" grade="5.0"/>
            <course name="kurs programowania" grade="5.5"/>
            <course name="logika i struktury formalne" grade="4.0"/>
        </courselist>
    </student>

    <student>
        <index>5678</index>
        <courselist>
            <course name="logika i struktury formalne" grade="5.0"/>
            <course name="algebra z geometrią analityczną" grade="5.0"/>
            <course name="kurs programowania" grade="5.5"/>
        </courselist>
    </student>

</database>

and I want to retrieve all the index number that have at least one 4.0 grade. I can do those task separately but not altogether. I tried
/database/student/courselist/course[@grade='4.0']/@name | /database/student/index/text()

but the result is quite far from desired
[#text: 1234]    #good
name="logika i struktury formalne"    #even better, I can display where 4.0 was achieved
[#text: 5678]    #bad, this student doesn't have even one 4.0

My question is if such a query is even possible in XPath? Of course I would be extremely grateful for a working example :)

A: Your current implementation gives 5678 as well, because the | operator in XPath means "and": it selects both the result of the left hand side and the result of the right hand side.
What you want is something like this:
/database/student[courselist/course[@grade='4.0']]/index/text()

Which reads as "give me all student elements having a courselist with a course with grade=4.0, and then give me the text contents of their index element.


text:
Q: Able to iterate through c++ map from stl, but unable to asign values or print out class variables I am currently trying to use the map provided from the c++ stl.  My key value pair are both a pointer to a custom object.  I am able to store data into the map, and also successfully iterate through all the keys and values of the map.  However, whenever I attempt to access one of the values member variables in the map through its key I get the following runtime error:
Segmentation fault (core dumped)
I am using a custom comparator for the map.  I believe this is where the issue is arising. I believe this becasue whenever I run the code without the custom comparator the error goes away.
Note that the use of the Eigen library is just being used for linear algebra purposes.  Please try to look past it in the example code, as it is just being used in my particular implementation to the problem I am trying to solve.
Please use the following code for context:

#include <iostream>
#include <map>
#include <Eigen/Dense>
#include <vector>
#include "A_star.h"

using namespace std;

struct NodeCostPointer {
    bool operator()(star::Node* const& a,star::Node* const& b){
        return a->f_cost >= b->f_cost;

int main() {

    Eigen::Matrix<float,3,3> obj;
    obj(0,0) = 3360;
    obj(1,0) = 3360;
    obj(2,0) = 3360;
    obj(0,1) = 7000;
    obj(1,1) = 7000;
    obj(2,1) = 7000;
    obj(0,2) = 5280;
    obj(1,2) = 5280;
    obj(2,2) = 5280;

    Eigen::Matrix<float,3,1> end;
    end(0) = 12300;
    end(1) = 12300;
    end(2) = 12300;

    Eigen::Matrix<float,3,1> start;
    start(0) = -.8;
    start(1) = -.8;
    start(2) = -.8;

    map<star::Node*,star::Node*, NodeCostPointer> test;

    star::Node* nodetest = new star::Node(start,6,0);

    star::Node* nodetest2 = new star::Node(end,6,0);

    star::Node* nodetest3 = new star::Node(start,5,std::numeric_limits<float>::infinity());

    test[nodetest] = nodetest3;

    test[nodetest2] = nodetest3;

    // error occurs here:
    cout << test[nodetest]->f_cost << endl;
    // or
    test[nodetest]->f_cost = 4;

    map<star::Node*,star::Node*,NodeCostPointer>::iterator itt;
    for(itt=test.begin();itt!=test.end();itt++){
        cout << itt->first->cordinates << endl;

        cout << "  \n";
    }

return 0;

Implementation of Node class:

star::Node::Node(Eigen::Matrix<float,3,1> _cordinates, float _h_cost, float _g_cost) : cordinates {_cordinates}, h_cost {_h_cost}, g_cost {_g_cost}{
    f_cost = h_cost+g_cost;
    obstical = false;
    closedNode = false;
};

A: Thank you @timl and others for pointing me the correct direction. The problem was due to not satisfying the strict weak ordering requirement for comparison.  Changing the comparator to the following seems to have made everything work:
struct NodeCostPointer {
    bool operator()(star::Node* const& a,star::Node* const& b){
        return std::tie(a->f_cost,a->h_cost,a->cordinates(0)) < std::tie(b->f_cost,b->h_cost,b->cordinates(0));
}

After learning about how this notation works I decided to add additional things for comparison i.e. h_cost and coordinates. However, not including them would have of course also worked.


text:
Q: Powershell command not recognized when calling from C# This is in continuation to this Question here, I have a PowerShell command which I have created and am able to call the command in a PowerShell window, but when trying to call from C# method, I am getting error as the cmdlet is not recognized, I tried with other existing commands and get same error, so I suspect issue in Importing the Module, though I don't get that error in streams. Error. The only error I get is "Get-RowAndPartitionKey is not a recognized cmndlt, please check the spelling.....".
Would like to know if there is any other way, I should try it or if I can debug more here to see if my Module fetches all command or not. right now I am clueless how to fix this.
 public string RunScript( string contentScript, Dictionary<string, EntityProperty> parameters )
    {
        List<string> parameterList = new List<string>();
        foreach( var item in parameters )
        {
            parameterList.Add( item.Value.ToString() );
        }
        using( PowerShell ps = PowerShell.Create() )

        {
            IAsyncResult async =
             ps.AddCommand( "Import-Module" ).AddArgument( @"C:\Users\...\.D.PowerShell.dll" )
               .AddStatement()
               .AddCommand( "Get-RowAndPartitionKey" ).AddParameter( "Properties", "test" )
               .BeginInvoke();

            StringBuilder stringBuilder = new StringBuilder();
            foreach( PSObject result in ps.EndInvoke( async ) )
            {
                stringBuilder.AppendLine( result.ToString() );
            }
            return stringBuilder.ToString();
        }
    }
}

Below method do not return any error in Streams.Error or Verbose but no output also:
public async Task<IEnumerable<object>> RunScript( string scriptContents, List<string> scriptParameters )
        {
            // create a new hosted PowerShell instance using the default runspace.
            // wrap in a using statement to ensure resources are cleaned up.

            using( PowerShell ps = PowerShell.Create() )
            {
                // specify the script code to run.
                ps.AddScript( scriptContents );

                // specify the parameters to pass into the script.
                ps.AddParameter( "Properties" ,"test") ;

                // execute the script and await the result.
                var pipelineObjects = await ps.InvokeAsync().ConfigureAwait( false );
                return pipelineObjects;
            }
        }

scriptContent
 "\"$path = 'C:\\Users...\\.TabularData.PowerShell.dll'\\r\\nImport-Module $path\\r\\nGet-RowAndPartitionKeys\""

A: The following is self-contained PowerShell sample code that uses on-demand compilation of C# code:

*

*It shows that the approach works in principle, as described in this answer to your original question.

*

*Prerequisites: The PowerShell SDK package and .NET runtime used in the C# project that calls your custom Get-RowAndPartitionKey" cmdlet must be compatible with the PowerShell SDK and .NET runtime that you used to compile the assembly DLL that houses that cmdlet, to be imported via Import-Module.

*The sample code below ensures that implicitly, by running directly from PowerShell, using the Add-Type cmdlet to compile C# code on demand - it works in Windows PowerShell as well as in PowerShell (Core) 7+.

*

*In practice I've found that a .NET Framework-compiled DLL (from Windows PowerShell) also works in PowerShell (Core) (.NET (Core) 5.0), but not vice versa.

*It shows troubleshooting techniques, namely:

*

*Adding the -Verbose switch to the Import-Module call to produce verbose output that lists the commands being imported from the given module (DLL).

*Printing these verbose messages (look for // --- TROUBLESHOOTING CODE)

*Printing any non-terminating PowerShell errors that occurred (as opposed to exceptions that you'd have to handle in C# code).

# Create a (temporary) assembly containing cmdlet "Get-RowAndPartitionKey".
# This assembly can directly be imported as a module from PowerShell.
# The cmdlet simply outputs "Hi from Get-RowAndPartitionKey" and
# echoes the elements of the list passed to -Properties, one by one.
$tempModuleDll = Join-Path ([IO.Path]::GetTempPath()) "TempModule_$PID.dll"
Remove-Item -ErrorAction Ignore $tempModuleDll
Add-Type @'
  using System.Management.Automation;
  using System.Collections.Generic;
  [Cmdlet("Get", "RowAndPartitionKey")]
  public class GetRowAndPartitionKeyCmdlet : PSCmdlet {
    [Parameter] public List<string> Properties { get; set; }
    protected override void ProcessRecord() {
      WriteObject("Hi from Get-RowAndPartitionKey: ");
      WriteObject(Properties, true);
    }
  }
'@ -ErrorAction Stop -OutputAssembly $tempModuleDll

# Compile a C# class ad hoc to simulate your project, and call its static
# method, which imports the module and effectively calls
#   Get-RowAndPartitionKey -Properties "foo", "bar"
(Add-Type @"
  using System;
  using System.Management.Automation;
  using System.Collections.Generic;
  using System.Text;

  public static class Foo {
    public static string RunScript(List<string> parameterList)
    {
      using (System.Management.Automation.PowerShell ps = PowerShell.Create())
      {
        IAsyncResult async =
          // Add -Verbose to the Import-Module call, so that the list of
          // commands being imported is written to the verbose output stream.
          ps.AddCommand("Import-Module").AddArgument(@"$tempModuleDll").AddParameter("Verbose", true)
            .AddStatement()
            .AddCommand("Get-RowAndPartitionKey").AddParameter("Properties", parameterList)
            .BeginInvoke();

        StringBuilder stringBuilder = new StringBuilder();
        foreach (PSObject result in ps.EndInvoke(async))
        {
          stringBuilder.AppendLine(result.ToString());
        }

        // --- TROUBLESHOOTING CODE

        // Print verbose output from the Import-Module call
        foreach (var v in ps.Streams.Verbose) { Console.WriteLine("VERBOSE: " + v.ToString()); }

        // Print any errors.
        foreach (var e in ps.Streams.Error) { Console.WriteLine("ERROR: " + e.ToString()); }

        // ---

        return stringBuilder.ToString();
      }
    }
  }
"@ -ErrorAction Stop -PassThru)::RunScript(("foo", "bar"))

# Clean-up instructions:
if ($env:OS -eq 'Windows_NT') {
  Write-Verbose -vb "NOTE: Re-running this code requires you to start a NEW SESSION."
  Write-Verbose -vb "After exiting this session, you can delete the temporary module DLL(s) with:`n`n  Remove-Item $($tempModuleDll -replace '_.+', '_*.dll')`n "
} else {
  Write-Verbose -vb "NOTE: Re-running this code after modifying the embedded C# code requires you to start a NEW SESSION."
  Remove-Item $tempModuleDll
}

On my Windows 10 machine, both from PowerShell (Core) 7.0.5 and Windows PowerShell 5.1, the above yields (clean-up instructions omitted) the following, showing that everything worked as intended:
VERBOSE: Loading module from path 'C:\Users\jdoe\AppData\Local\Temp\TempModule_11876.dll'.
VERBOSE: Importing cmdlet 'Get-RowAndPartitionKey'.
Hi from Get-RowAndPartitionKey:
foo
bar

Specifically, line VERBOSE: Importing cmdlet 'Get-RowAndPartitionKey'. indicates that the custom cmdlet was successfully imported into the session.


text:
Q: Volume generated by rotating around y-axis, curve $y=x^3$ and the lines $y=0$ and $x=2$
Find the volume of the solid generated by revolving about the y-axis the region bounded by the curve $y=x^3$ and the lines $y=0$ and $x=2$

I first found what $x=2$ would be in terms of y.
$$y= (2)^3
\\ = 8$$
And in terms of y, the original equation becomes:
$$y=x^3
\\ x= y^{1 \over 3}$$
So,
$$V= \int^8_0 (y^{1 \over 3})^2 \pi dy
\\ = \pi \int_0^8 y^{2\over 3}dy
\\ =\pi \bigg[ y^{5\over 3} ({3 \over 5}) \bigg]^8_0
\\ = (8^{5 \over 3})({3 \over 5})\pi
\\ = {96 \over 5} \pi$$
Therefore the answer is ${96 \over 5} \pi$ units $^3$
However, the answer is supposed to be ${64 \over 5} \pi$ units${^3}$
What went wrong?

A: The shell method would be easiest to use here:
$$
V=2\pi\int_{0}^{2}x\cdot x^3\,dx=2\pi\int_{0}^{2}x^4\,dx=
2\pi\frac{x^5}{5}\bigg|_{0}^{2}=\\
\frac{2\pi}{5}\left(2^5-0^5\right)=
\frac{2\pi}{5}\cdot 32=\frac{64\pi}{5}\ \text{cubic units}.
$$
Or you can use the washer method which is going to be a bit messier. In that case, you're subtracting the volume of a cylinder of radius $2$ and height $8$ from the volume you get by revolving the curve $x=\sqrt[3]{y}$ around the $y$-axis:
$$
V=\int_{0}^{8}\left(\pi\cdot 2^2-\pi\left(\sqrt[3]{y}\right)^2\right)\,dy=
\pi\int_{0}^{8}\left(4-y^{\frac{2}{3}}\right)\,dy=\frac{64\pi}{5}\ \text{cubic units}.
$$
Wolfram Alpha check.

A: The volume required is between the lines y=0, x=2 and curve y=x^3.
If you visualize it, the required volume is :
V1-V2
where V1 = the volume of cylinder formed by line y=2 and x=2.
V2 = the volume enclosed by the curve y=x^3 around y axis.
V1 = pi*r^2*h.
r=2, h = 8.
so V1 = 4*8*pi = 32 pi
V2 = 96/5 pi
V1-V2 = 32pi - 96/5pi = 64/5 pi
Please pardon me as I dont know the mathML.

A: You are calculating the empty volume between the rotated function and the y-axis. This is because for every y-value, you are summing the distance between the y-axis and the function y=x^3, rather than the distance between the function y=x^3 and your boundary of x=2. As mentioned by someone in the comments, you want
$$V = \int_0^8 4-y^{2/3}dy$$

A: Washer method is quite easy. Express the washer area including its hole and extrude it along $y$.
$$
V=\pi\int_{0}^{8}\left(2^2-x^2\right)\,dy=\pi\int_{0}^{2}\left(2^2-x^2\right)\,3x^2 dx= $$
$$
V=3\pi\int_{0}^{2}\left(4-x^2\right)\, \cdot x^2 \, dx = ... = \frac{64 \pi}{5}$$


text:
Q: Elements rendering in Chrome but not Firefox? This is solved!
Turns out the body tag didn't have a height as 100% but rather two width settings.
School boy error, sorry guys.
This is solved.
I've created a US flag using only web elements and text.
It renders fine in Chrome in full colour but only shows the stars and the black body background in Firefox.
Could someone perhaps highlight what's going wrong here? Putting the Doctype on the page actually created the same issue Firefox is having with the Chrome rendering of the page.
Link to the flag
Any help is much appreciated.

        <title>FLAG</title>

            * * * * * *

                * * * * *

            * * * * * *

                * * * * *

            * * * * * *

                * * * * *

            * * * * * *

                * * * * *

            * * * * * *

A: This is not the issue, however it is a good practice to set a DOCTYPE, without it the browser renders the webpage in quirks mode, also setting a charset is a good practice as well.
To fix your problem try this: (first erase the stray center tag after your stripes wrapper container)
HTML:

CSS:
Add this to your css:
html {
    height: 100%;
}

Add 100% height to the body wrapper:
body {
    position: relative;
    background: #000;
    font-family: Arial, Helvetica, sans-serif;
    font-size: small;
    color: #fff;
    margin: 0;
    height: 100%;
}

Add height 100% to stripes wrapper:
#stripes_wrapper {
    width: 100%;
    height: 100%;
}

This should work

A:


text:
Q: JavaFX make imageView go in direction it is facing I want to make an imageView object move into the direction it is facing.
I made it move on X/Y axis and also made it rotate but I literally do not know how to approach this issue of moving into the direction it is facing (for example, in my code I use a car, I just want it to move in the direction its facing)
I appreciate any ideas or tutorials where I could learn this.
public class Main extends Application {

    private static final double W = 800;
    private static final double H = 600;
    private boolean goNorth, goSouth, goWest, goEast;
    private ImageView hero;
    private int toAngle = 0;

    @Override
    public void start(Stage primaryStage) throws FileNotFoundException {
        FileInputStream hero_image_input = new FileInputStream("C:\\Users\\A650262\\Desktop\\police-310208_1280.png");
        Image hero_image = new Image(hero_image_input);
        hero = new ImageView(hero_image);

        hero.setFitHeight(120);
        hero.setFitWidth(200);

        BorderPane root = new BorderPane();
        Scene scene = new Scene(root,800,800);

        scene.setOnKeyPressed(new EventHandler<KeyEvent>(){
            @Override
            public void handle(KeyEvent event)
            {
                switch(event.getCode())
                {
                case UP: goNorth = true; break;
                case DOWN: goSouth = true; break;
                case LEFT: goWest = true; break;
                case RIGHT: goEast = true; break;
                }
            }
        });

        scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event)
            {
                switch(event.getCode())
                {
                case UP: goNorth = false; break;
                case DOWN: goSouth = false; break;
                case LEFT: goWest = false; break;
                case RIGHT: goEast = false; break;
                }
            }
        });

        root.getChildren().addAll(hero);
        primaryStage.setScene(scene);
        primaryStage.show();

        AnimationTimer timer = new AnimationTimer() {
            @Override
            public void handle(long now) {
                int dx = 0, dy = 0;

                if (goNorth) dy -= 5;
                if (goSouth) dy += 5;
                if (goEast) rotate(3);
                if (goWest)  rotate(-3);

                moveHeroBy(dx, dy);
            }
        };
        timer.start();
    }

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

    private void moveHeroBy(int dx, int dy) {
        if (dx == 0 && dy == 0) return;
        double x = dx + hero.getLayoutX();
        double y = dy + hero.getLayoutY();
        moveHeroTo(x,y);

    }

    private void moveHeroTo(double x, double y) {
        hero.relocate(x, y);
        System.out.println(hero.getNodeOrientation() + " " + hero.getEffectiveNodeOrientation());

    }

    public void rotate(int angle){

        toAngle = toAngle + angle;
        if (toAngle == 360)
        {
            toAngle = 0;
        }
        hero.setRotate(toAngle);
    }

}

A: Use Rotate and Translate transforms to move the image. This way you can use the Rotate to transform the direction the car initially faces to the current one.
private final Rotate rotate = new Rotate();
private final Translate translate = new Translate();

// upwards facing direction TODO: adjust
private final Point2D initialDirection = new Point2D(0, -1);

rotate.setPivotX(hero.getFitWidth() / 2);
rotate.setPivotY(hero.getFitHeight() / 2);
hero.getTransforms().addAll(translate, rotate);

AnimationTimer timer = new AnimationTimer() {
    @Override
    public void handle(long now) {
        double delta = 0;

        if (goNorth) {
            delta += 5;
        }
        if (goSouth) {
            delta -= 5;
        }
        if (goEast) {
            rotate(3);
        }
        if (goWest) {
            rotate(-3);
        }

        Point2D pt = rotate.deltaTransform(initialDirection.multiply(delta));

        moveHeroBy(pt.getX(), pt.getY());
    }
};

private void moveHeroBy(double dx, double dy) {
    if (dx == 0 && dy == 0) {
        return;
    }
    double x = dx + translate.getX();
    double y = dy + translate.getY();
    translate.setX(x);
    translate.setY(y);
}

public void rotate(int angle) {
    angle += rotate.getAngle();
    if (angle == 360) {
        angle = 0;
    }
    rotate.setAngle(angle);
}


text:
Q: Excel rank formula issue Formula
RANK(F2,$F$2:$F$5)

Output:

**sr  rank  name     sub1  sub2   sum      percentage**
1     1     jaydeep  60    65     326      163
2     1     manish   70    63     326      163
3     3     jay 60   65    325.5  162.75

Want:
In rank column I get 3rd rank but actually it is 2nd rank.
Any way to get 2nd rank using formula because of sheet contain many data.
Thanks.

A: What I think you want is called a Dense Rank
Try this formula:
=SUMPRODUCT( (FREQUENCY($F$2:$F$4,$F$2:$F$4) > 0) * (F2 <= $F$2:$F$5) )

Note that range within the FREQUENCY function is the same as the range to be ranked; and the range at the end has one additional row.


text:
Q: Are WINE applications sandboxed? I want to run a small Windows program that has no reputation. I can always scan it, but I can't get feedback from other users on its performance or if it is at all malicious.
Rather than go through the pains of creating a virtual machine, would installing the program in WINE be safe? Would the program be sandboxed from the rest of my system? Can a malicious Windows program even harm a Ubuntu system?


text:
Q: How to find Duplicate selectors between multiple css files using stylelint I want to find duplicate selectors between multiple css files. i can't merge those files into single one. as i need to results for each file, which will be easy for removing duplicates.

A: I don't believe this is possible with stylelint as it operates on sources individually.


text:
Q: Arithmetic Expressions as argument to macro in c using macro with preprocessor directive #define I have written the following two codes.

*

*first code passes the expression e.g. a+b

_valid_pagesize(a+b)

*

*in second code

c=a+b

and then passed this c as an argument to macro.

_valid_pagesize(c)

the second code runs perfectly whereas the first code doesn't.
can we not pass expressions as arguments to macro like the way we can in case of a function..?
why not..?
the code passing expression as argument :
#include<stdio.h>
#include<stdlib.h>

#define _valid_pagesize(_newsize) (!(_newsize % 0x80000000)?1:      \
        (!(_newsize % 0x40000000)?1:      \
        (!(_newsize % 0x10000000)?1:      \
        (!(_newsize % 0x4000000) ?1:0))))

int main(int argc, char* argv[]){
    uint64_t size[2];
    size[0]=atoi(argv[1]);
    size[1]=atoi(argv[2]);

    if(_valid_pagesize(size[0]+size[1])){
            printf("success\n");
            }
    return 0;
}

A: Rule #1 with macros is to enclose all arguments in parentheses, to avoid exactly the problem that you're seeing.
#define _valid_pagesize(_newsize) (!((_newsize) % 0x80000000)?1:      \
    (!((_newsize) % 0x40000000)?1:      \
    (!((_newsize) % 0x10000000)?1:      \
    (!((_newsize) % 0x4000000) ?1:0))))

When you pass a+b to the macro, it expands to
a + b % 0x40000000

and since % has higher precedence than +, you don't get the result you expect. By enclosing the argument in parentheses, the macro expands to
(a + b) % 0x40000000

which works as expected.

A: Macro parameters aren't evaluated prior to being passed to the macro, since macro expansion occurs prior to compilation. Instead, the actual expression is passed unchanged into the macro, and is substituted into all occurrences of the parameter name. Therefore, _valid_pagesize(a+b) expands to this:
(!(a+b % 0x80000000)?1:      \
    (!(a+b % 0x40000000)?1:      \
    (!(a+b % 0x10000000)?1:      \
    (!(a+b % 0x4000000) ?1:0))))

Now, the reason it produces wrong answers is hopefully obvious. Follow user3386109's advice about enclosing the parameter in parentheses.

A: Put _newsize inside braces in the macro expansion


text:
Q: When to use the updateFeature() method? I am using QGIS 3.12 and I want to update the content of a field by storing the feature's X and Y coordinates. The following code works given that a point layer is in the layer panel. The function works when the layer.updateFeature(feat.id()) statement is blocked, and so I could not understand the use of this method?
layer = iface.activeLayer()
layer.startEditing()
all_features = layer.getFeatures()
for feat in all_features:
    geom = feat.geometry()
    x = geom.asPoint().x()
    y = geom.asPoint().y()

    new_x = {feat.fieldNameIndex('x'): x}
    layer.dataProvider().changeAttributeValues({feat.id(): new_x })

    new_y = {feat.fieldNameIndex('y'): y}
    layer.dataProvider().changeAttributeValues({feat.id(): new_y })

    #layer.updateFeature(feat.id()) #?

# Commit changes
layer.commitChanges()

A: You need to either use only the .dataProvider() (QgsVectorDataProvider) methods which call the underlying data and modify it or use the edit methods of QgsVectorLayer.
so, either :
layer = iface.activeLayer()
layer.startEditing()
all_features = layer.getFeatures()
for feat in all_features:
    geom = feat.geometry()
    x = geom.asPoint().x()
    y = geom.asPoint().y()

    feat.setAttribute('x', x)
    feat.setAttribute('y', y)

    layer.updateFeature(feat)

# Commit changes
layer.commitChanges()

or
layer = iface.activeLayer()
all_features = layer.getFeatures()
for feat in all_features:
    geom = feat.geometry()
    x = geom.asPoint().x()
    y = geom.asPoint().y()

    new_xy = {
        feat.fieldNameIndex('x'): x,
        feat.fieldNameIndex('y'): y
    }
    layer.dataProvider().changeAttributeValues({feat.id(): new_xy }


text:
Q: How to emulate a curl request using node-fetch module i have an e-commerce application and trying to reach out to the paypal rest api, "paypal for partners" service specifically, i did read the Paypal Documentation and its all good but the problem is that they mentioned the request example using curl like this   :
curl -v https://api.sandbox.paypal.com/v1/oauth2/token \
   -H "Accept: application/json" \
   -H "Accept-Language: en_US" \
   -u "client_id:secret" \
   -d "grant_type=client_credentials"

Or
using postman with basic Auth:

*

*Username:    Your client ID.

*Password:    Your secret.
iam trying to implement the same thing but using node-fetch from node.js
const fetch = require('node-fetch');

function authenticatePaypal() {
    fetch('https://api.sandbox.paypal.com/v1/oauth2/token', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Accept-Language': 'en_US',
            'client_id': 'secret'
        },
        body: {
            "grant_type": "client_credentials"
        }
    }).then(reply => {
        console.log('success');
        console.log(reply);
    }).catch(err => {
        console.log('error');
        console.log(err);
    });
}

module.exports = {
    authenticatePaypal: authenticatePaypal
};

and i get this response of 401 Unauthorized:
Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]:
   { body:
      PassThrough {
        _readableState: [ReadableState],
        readable: true,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _writableState: [WritableState],
        writable: false,
        allowHalfOpen: true,
        _transformState: [Object] },
     disturbed: false,
     error: null },
  [Symbol(Response internals)]:
   { url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
     status: 401,
     statusText: 'Unauthorized',
     headers: Headers { [Symbol(map)]: [Object] } } }

i tried post man and it worked in postman, i know that there is something wrong in my node-fetch implementation, this is my first time dealing with basic Auth in json format.

A: Authorization header is wrong.
-u "client_id:secret"

says that curl is using a Basic Authentication.
You should add authorization header
Authorization: Basic <base64 encoded "client_id:secret">

A: Solution using yours as base, since I struggled a few minutes to have it working.
// get the client_id and secret from https://developer.paypal.com/developer/applications/
const clientIdAndSecret = <client_id:secret>
const base64 = Buffer.from(clientIdAndSecret).toString('base64')

fetch('https://api.sandbox.paypal.com/v1/oauth2/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept-Language': 'en_US',
        'Accept': 'application/json',
        'Authorization': `Basic ${base64}`,
      },
      body: 'grant_type=client_credentials'
})


text:
Q: Error page styles not loading I was attempting to customize Magento's 503 and Maintenance error pages (404 is set up and works fine), but Magento can't load the stylesheets for the error pages.
If I put Magento in maintenance mode, or force some kind of DB error, it does load the appropriate page, but when it attempts to load css/styles.css that page, too, returns the error page instead if the css file.
How can I fix this?
Edit:
My folder structure, as requested
errors/
errors/404.php
errors/503.php
errors/design.xml
errors/local.xml
errors/processor.php
errors/report.php
errors/default/
errors/default/404.phtml
errors/default/503.phtml
errors/default/page.phtml
errors/default/report.phtml
errors/default/css/styles.css
errors/default/images/

I use maintenance.flag to force Magento to give me an error page. It tries to load http://localhost/css/styles.css but that returns a 503, so I get an unstyled error page.
If I access http://localhost/errors/default/css/styles.css I get the Magento error page, but it is styled (its able to load stylesheets). Loading any random url starting with the path http://localhost/errors/default/ loads the error page correctly, so it seems to have something to do with how magento is building the error pages...

A: First of all make sure that you customized error pages in proper way.
Follow simple steps:

*

*Go to /errors and create new folder for example custom.

*Copy /errors/default content into /errors/custom.

*Edit /errors/design.xml and set custom skin
<config>
    <skin>default</skin>
</config>

Now customize html files in /errors/custom end styles in /errors/custom/styles.css.
If you want to access your styles through browser http://localhost/errors/custom/styles.css
Also I recommend you to read this article.


text:
Q: How do I secure my hls link so that no other site will use it I made a streaming server using Nginx RTMP.
I installed it and tested it and it works fine but when I broadcast and use the m3u8 link on my site, I find that some sites can take it and put it there and it will work and this will consume my server resources.
I created a live streaming server using Nginx, according to the explanation in this link: Create a secure adaptive bit-rate HLS stream with Nginx/RTMP/Ffmpeg on Ubuntu 20.04 (2021).
I streamed on the server and used the file extracted from the stream
I mean this, for example: https://mydomain/hls/stream/index.m3u8
I put it in the video player on my site and it works fine.
The problem here is that anyone who uses the m3u8 file or link and puts it in a player on their site works.
I don't want that... I just want the broadcast to work on my website
I've seen many sites use this method to protect broadcasts from being stolen from other sites
I want when I open this link: https://mydomain/hls/stream/index.m3u8 it doesn't work
I only want it to work if I add it in the video player inside my site.
My question is: How do I make the m3u8 link work only on sites I own?

A: To restrict your web-server to serving your own sites only, block in
the firewall all sites except to the IP addresses of your sites.
You may do that on the computer or in the router.
More specific advice depends on your software.


text:
Q: Missing Microsoft.Data.Tools.Schema.Sql.UnitTesting. Again The bug is very old but MS didn't fix it so far.
I had a VS2015 solution (many projects, with main ASP.NET one) and I opened it in VS 2017.
Here is what I saw when I tried to build it:

So, I figured, okay, some referenced broke, I went into Project References, removed those two (...Sql.UnitTesting and ...Tools.Components), and tried to add them back. What did I saw? Of course, this:

The version is wrong, its 15.1.0.0 instead of previous 15.0.0.0 (for both DLLs). Big deal, you say, but it still doesn't compile:

It tells me that the versions are mismatched and I have to create some assembly-bindings in the web.config file. Which I did, first manually, then via the double-click on the warning, as it suggested. Nothing changed. I still can't get my project build.
Previous SO questions (Automatic reference to Microsoft.Data.Tools.Schema.Sql.UnitTesting, Where is the Microsoft.VisualStudio.TestTools.UnitTesting namespace on VS2010?) don't help much, I cannot remove SSDT component, as it breaks the loading of the web-project completely. And my project isn't any sort of SQL Testing project. It is just a regular ASP.NET 4 web app.
What can I do to fix this?

A:
Select NO and the Identity and Path should automatically resolve.

A: In your test project file, remove this code:
<Import Project="$(SQLDBExtensionsRefPath)\Microsoft.Data.Tools.Schema.Sql.UnitTesting.targets" Condition="'$(SQLDBExtensionsRefPath)' != ''" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\SSDT\Microsoft.Data.Tools.Schema.Sql.UnitTesting.targets" Condition="'$(SQLDBExtensionsRefPath)' == ''" />
<PropertyGroup>
    <SsdtUnitTestVersion>2.0</SsdtUnitTestVersion>
</PropertyGroup>

And replace it with this:
<ItemGroup Condition="$(VisualStudioVersion) == '15.0'">
    <Reference Include="Microsoft.Data.Tools.Schema.Sql, Version=13.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <HintPath>$(SSDTPath)\Microsoft.Data.Tools.Schema.Sql.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="Microsoft.Data.Tools.Schema.Sql.UnitTesting, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <HintPath>$(SSDTUnitTestPath)\Microsoft.Data.Tools.Schema.Sql.UnitTesting.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="Microsoft.Data.Tools.Schema.Sql.UnitTestingAdapter, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <HintPath>$(SSDTUnitTestPath)\Microsoft.Data.Tools.Schema.Sql.UnitTestingAdapter.dll</HintPath>
      <Private>True</Private>
    </Reference>
  </ItemGroup>
<PropertyGroup>
    <SsdtUnitTestVersion>3.1</SsdtUnitTestVersion>
  </PropertyGroup>
 <Import Project="$(SQLDBExtensionsRefPath)\Microsoft.Data.Tools.Schema.Sql.UnitTesting.targets" Condition="$(VisualStudioVersion) != '15.0' And '$(SQLDBExtensionsRefPath)' != ''" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\SSDT\Microsoft.Data.Tools.Schema.Sql.UnitTesting.targets" Condition="$(VisualStudioVersion) != '15.0' And '$(SQLDBExtensionsRefPath)' == ''" />

This is as per the official microsoft dev community help thread here.
Although for me it didn't work. Had to add propertygroup tags around ssdt version. You might want to keep it or remove it as per your project configurations.

A: I have searched the project's file and found this:
<Import Project="$(SQLDBExtensionsRefPath)\Microsoft.Data.Tools.Schema.Sql.UnitTesting.targets" Condition="'$(SQLDBExtensionsRefPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\SSDT\Microsoft.Data.Tools.Schema.Sql.UnitTesting.targets" Condition="'$(SQLDBExtensionsRefPath)' == ''" />

Then I searched the PC for Microsoft.Data.Tools.Schema.Sql.UnitTesting.targets and I found some interesting results (clickable):

So, my previous studio, VS2015, had the v14 version of the file and the referenced were of 14 version as well, which is fine.
But the new VS2017's had references to the 15.0.0.0, according to the file contents:

But the actual folder, which should contain these files has 15.1.0.0 version! And the binding redirects in my web.config file just doesn't work for some reason.
I see two solutions from here, change the Microsoft.Data.Tools.Schema.Sql.UnitTesting.targets file so that it would contain 15.1.0.0 version, or replace 15.1.0.0 with 15.0.0.0 ones. I'll go with former now. Update soon.
Update
It still didn't help. No there are no build errors but the project build failed.
I also tried to remove those two XML lines from project's file and it kinda worked. Not so sure, because it now behaves even more weird.
It gave me a strange "missing ','" error on a line with somemethod(out Ticket ticket); (new C#7 feature), which is fine and doesn't have any errors, the error itself disappeared after 1 seconds after I saw it, but when I switched it back to C#6 way, it all finally built without problems. I'll try to run the project now.
Update
Yeah, just as I thought, dear Microsoft. Now it gives me this:

So, there are some changes are yet to be made for me to finish my manual upgrade a simple webapp from vs2015 to vs2017.


text:
Q: XML parse it into a collection object I was able to parse the following XML into an object thanks MikeH.
When I parse the XML file into an object it only fills the last row into the object.  How could I parse all the rows into a collection object.  The rows should fill into a collection.  In this case all 5-records should be in the collection not just the last record ().  I spent most of the day and I must be missing something on how to get all the rows into the object.
  - <ROW>
    <CELL INDEX="0">033331111</CELL>
    <CELL INDEX="1">Agency 5 LTD</CELL>
    <CELL INDEX="2">14 Some AVENUE North Brook, FL 65432 3827</CELL>
    <CELL INDEX="3">A</CELL>
    <CELL INDEX="4">4412034564</CELL>
    <CELL INDEX="5" />
    <CELL INDEX="6">A - Active</CELL>
    <CELL INDEX="7">6/1/2008 12:00:00 AM</CELL>
    </ROW>

With Visual Studio 2012 or greater:
Copy the XML to your clipboard
From within Visual Studio: Edit --> Paste Special --> Paste XML As Classes
Then you'll need to serialize the data from XML to your newly created class to create a new object:
var myObject = LoadFromXmlString<DATA_PROVIDERS>(xmlData);

public static T LoadFromXmlString<T>(string xml)
{
  T retval = default(T);
  try
  {
    XmlSerializer s = new XmlSerializer(typeof(T));
    MemoryStream ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(xml));
    retval = (T)s.Deserialize(ms);
    ms.Close();
  }
  catch (Exception ex)
  {
    ex.Data.Add("Xml String", xml);
    throw new Exception("Error loading from XML string.  See data.", ex);
  }
  return retval;

}

<?xml version="1.0" encoding="UTF-8" ?>
-<DATA_PROVIDERS UID="Providers|REP" FORCE_REFRESH="FALSE" DATA_PROVIDER="" FORMATTED="FALSE" REFRESH="TRUE">
 -<DATA_PROVIDER NAME="Prov" SOURCE="Provider" DATE="11/18/2014" DURATION="9s" REFRESH="TRUE" CUBE="1">
  <COLUMN INDEX="0" ID="119" TYPE="String" FORMAT="">Prov ID</COLUMN>
  <COLUMN INDEX="1" ID="118" TYPE="String" FORMAT="">Prov Name</COLUMN>
  <COLUMN INDEX="2" ID="113" TYPE="String" FORMAT="">Address Info</COLUMN>
  <COLUMN INDEX="3" ID="110" TYPE="String" FORMAT="">Enroll Status Code</COLUMN>
  <COLUMN INDEX="4" ID="119" TYPE="String" FORMAT="">Phone</COLUMN>
  <COLUMN INDEX="5" ID="110" TYPE="String" FORMAT="">Fax</COLUMN>
  <COLUMN INDEX="6" ID="109" TYPE="String" FORMAT="">Provider Status</COLUMN>
  <COLUMN INDEX="7" ID="150" TYPE="Date" FORMAT="m/d/yyyy h:mm:ss am/pm">Provider Start Date</COLUMN>
  - <ROW>
    <CELL INDEX="0">004042111</CELL>
    <CELL INDEX="1">CONTOSO West INC</CELL>
    <CELL INDEX="2">1234 Random Rd. SOMECITY, ZZ 12345 9876</CELL>
    <CELL INDEX="3">F</CELL>
    <CELL INDEX="4">5555551234123</CELL>
    <CELL INDEX="5">5555551234</CELL>
    <CELL INDEX="6">F - Agency Action</CELL>
    <CELL INDEX="7">5/31/2011 12:00:00 AM</CELL>
    </ROW>
  - <ROW>
    <CELL INDEX="0">004011117</CELL>
    <CELL INDEX="1">CONTOSO North INC</CELL>
    <CELL INDEX="2">4321 Random Rd. SOMECITY, ZZ 12345 9876</CELL>
    <CELL INDEX="3">F</CELL>
    <CELL INDEX="4">5555551234123</CELL>
    <CELL INDEX="5">5555551234</CELL>
    <CELL INDEX="6">F - Agency Action</CELL>
    <CELL INDEX="7">5/31/2011 12:00:00 AM</CELL>
    </ROW>
  - <ROW>
    <CELL INDEX="0">033337111</CELL>
    <CELL INDEX="1">Agency 3 INC</CELL>
    <CELL INDEX="2">200 street 5F Cityabc, NY 12033</CELL>
    <CELL INDEX="3">A</CELL>
    <CELL INDEX="4">2128545555</CELL>
    <CELL INDEX="5" />
    <CELL INDEX="6">A - Active</CELL>
    <CELL INDEX="7">10/27/2003 12:00:00 AM</CELL>
    </ROW>
  - <ROW>
    <CELL INDEX="0">033334111</CELL>
    <CELL INDEX="1">Agency 4 LLC</CELL>
    <CELL INDEX="2">419 street Town, CT 17033 3945</CELL>
    <CELL INDEX="3">U</CELL>
    <CELL INDEX="4" />
    <CELL INDEX="5">7172304056</CELL>
    <CELL INDEX="6">X - Did Not Re-enroll</CELL>
    <CELL INDEX="7">2/24/2009 12:00:00 AM</CELL>
    </ROW>
  - <ROW>
    <CELL INDEX="0">033331111</CELL>
    <CELL INDEX="1">Agency 5 LTD</CELL>
    <CELL INDEX="2">14 Some AVENUE North Brook, FL 65432 3827</CELL>
    <CELL INDEX="3">A</CELL>
    <CELL INDEX="4">4412034564</CELL>
    <CELL INDEX="5" />
    <CELL INDEX="6">A - Active</CELL>
    <CELL INDEX="7">6/1/2008 12:00:00 AM</CELL>
    </ROW>
 </DATA_PROVIDER>
</DATA_PROVIDERS>

A: What you need to do is to mark your Cells collection with the XmlElement("CELLS") attribute to inform XmlSerializer that the collection should be serialized as a sequence of identically named elements, rather than a single element with nested subelements, like so:
public class Cell
{
    [XmlText]
    public string Text { get; set; }

    [XmlAttribute("INDEX")]
    public int Index { get; set; }
}

[XmlRoot("ROW")]
public class Row
{
    [XmlElement("CELL")]
    public List<Cell> Cells { get; set; }
}

In addition, I notice your Cell objects contain their array index as an attribute, which seems redundant since the position of each cell in its list of cells also conveys this information.  Do you actually want that in your run-time classes -- or would you rather that this information be generated for serialization only?  If you prefer the latter, you may serialize & deserialize the cells as an array of proxies that contain the array index as an attribute property, like so:
public class Cell
{
    public Cell() {}

    public Cell(Cell other)
    {
        this.Text = other.Text;
    }

    [XmlText]
    public string Text { get; set; }
}

public class XmlCell : Cell // For serialization
{
    public XmlCell() : base() {}

    public XmlCell(Cell other, int index) : base(other)
    {
        this.Index = index;
    }

    [XmlAttribute("INDEX")]
    public int Index { get; set; }
}

[XmlRoot("ROW")]
public class Row
{
    List<Cell> cells;

    [XmlIgnore]
    public List<Cell> Cells
    {
        get
        {
            if (cells == null)
                Interlocked.CompareExchange(ref cells, new List<Cell>(), null);
            return cells;
        }
    }

    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    [XmlElement("CELL")]
    public XmlCell[] XmlCells // proxy array for serialization.
    {
        get
        {
            var xmlCells = new XmlCell[Cells.Count];
            for (int iCell = 0; iCell < xmlCells.Length; iCell++)
                xmlCells[iCell] = new XmlCell(Cells[iCell], iCell);
            return xmlCells;
        }
        set
        {
            Cells.Clear();
            foreach (var xmlCell in value)
            {
                Cells.EnsureCount(xmlCell.Index + 1);
                Cells[xmlCell.Index] = new Cell(xmlCell);
            }
        }
    }
}

Finally a couple extension methods:
public static class ListExtensions
{
    public static void Resize<T>(this List<T> list, int count)
    {
        if (list == null || count < 0)
            throw new ArgumentException();
        int oldCount = list.Count;
        if (count > oldCount)
        {
            list.Capacity = count;
            for (int i = oldCount; i < count; i++)
                list.Add(default(T));
        }
        else if (count < oldCount)
        {
            for (int i = oldCount - 1; i >= count; i--)
                list.RemoveAt(i);
        }
    }

    public static void EnsureCount<T>(this List<T> list, int count)
    {
        if (list == null || count < 0)
            throw new ArgumentException();
        if (count > list.Count)
            list.Resize(count);
    }
}


text:
Q: Missing DLC bug I recently purchased the season pass and super saints outfit pack, but I'm not seeing either of them in-game. I've seen people on the steam forums talking about missing DLC bugs but does anyone know how to fix this issue?
How can I first check to see if the DLC is actually installed or not, and if it is installed how can I be sure it is "active" in the game when I go to play it?


text:
Q: Which table in TFS db has Team Name data of TFS? We are working on TFS databases (TFS_Warehouse, TFS_FabrikamFibreCollection) to create some report related to TFS activities. We need to generate reports based on Team Name.
TFS maintained
following hierarchies for projects:
ProjectCollection
Project
Team
We are able to map ProjectCollections and Projects in the TFS_Warehouse database, they are in DimTeamProject.
But ee are not able to map Team Name in TFS_Warehouse / TFS_FabrikamFibreCollection database.
If you have any idea about Team Name mappings with DB tables please let me know.

A: This is the closest solution I found for your question:
SELECT map.[TeamId]
      ,map.[ProjectId]
      ,proj.[ProjectNodeName] AS [Team Project Name]
      ,ado.[SamAccountName] AS [Team Name]
  FROM [Tfs_FabrikamFibreCollection].[dbo].[tbl_TempTeamProjectMapping] map
  JOIN [Tfs_Warehouse].[dbo].[DimTeamProject] proj ON map.[ProjectId] = proj.[ProjectNodeGUID]
  JOIN [Tfs_FabrikamFibreCollection].[dbo].[ADObjects] ado ON map.[TeamId] = ado.[TeamFoundationId]

For some reason, the [tbl_TempTeamProjectMapping] table includes the default security groups (Readers, Contributors, Project Administrators, etc.) but these can easily be filtered out of the results.

A: We don't suggest handle database directly. You can create Excel reports instead. Usually, when we create a Team, we'll create an area path with the name of the team. So you can try to select Area Path in the field:

A: I'd recommend staying away from the SQL and use the TFS API. The following PowerShell invokes the TFS client namespace and brings back the collections and projects.
#region Get-TfsSummary
function Get-TfsSummary{
param(
    [parameter(Position=0,HelpMessage='    Full server name. e.g. tfsServer.domain.net',Mandatory)]
    [string]
    $serverFQDN, # eg 'tfsServer.domain.net'

    [parameter(Position=1,HelpMessage='    port used to access the TFS server e.g. 8080')]
    [string]
    $serverPort, # eg '8080'

    [parameter(Position=2,HelpMessage='    The root virtual directory for TFS. Default is tfs e.g. tfs ')]
    [string]
    $tfsRootNode # eg 'tfs'
)
Add-Type -AssemblyName "Microsoft.TeamFoundation.Client, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
$tfsUri = 'http://' + $serverFQDN + ':' + $serverPort +'/' + $tfsRootNode + '/'
$tfsConfigurationServer = [Microsoft.TeamFoundation.Client.TfsConfigurationServerFactory]::GetConfigurationServer($tfsUri)
$tpcService = $tfsConfigurationServer.GetService("Microsoft.TeamFoundation.Framework.Client.ITeamProjectCollectionService")
$sortedCollections = $tpcService.GetCollections() | Sort-Object -Property Name
$numberOfProjects = 0
$numberOfStoppedCollections = 0
$numberOfStartedProjects = 0
$numberOfStoppedProjects = 0
$isStopped = ''

foreach($collection in $sortedCollections) {
  $collectionUri = $tfsUri + "/" + $collection.Name
  $tfsTeamProject = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($collectionUri)

  try {
    $cssService = $tfsTeamProject.GetService("Microsoft.TeamFoundation.Server.ICommonStructureService4")

  }catch{}
    $sortedProjects = $cssService.ListProjects() | Sort-Object -Property Name

  if($collection.State -eq 'Stopped'){
    $isStopped = ' but is stopped'
    $numberOfStoppedCollections++
    $numberOfStoppedProjects += $sortedProjects.Count
  }

  Write-Host "`n" $collection.Name "(" $collection.Id ")- contains" $sortedProjects.Count "project(s)$isStopped"
  $isStopped = ''

  foreach($project in $sortedProjects)
  {
    $numberOfProjects++
    Write-Host (" - " + $project.Name + " (" + $project.Uri +  ")")
  }

}

$numberOfStartedProjects =  $numberOfProjects - $numberOfStoppedProjects
Write-Host
Write-Host "Number of stopped collections          " $numberOfStoppedCollections
Write-Host "Total number of project collections    " $sortedCollections.Count
Write-Host "Online projects                        " $numberOfStartedProjects
Write-Host "Total number of projects               " $numberOfProjects
}
#endregion Get-TfsSummary


text:
Q: Symfony Form from other Controller I have a view that shows the attributes of my parent entity. This Entity will have other child entities. I want the create form for those childs to be placed in my show.html.twig of the parent.
How do I place the create form of those childs in my parents view? How do I combine two controllers of two different entities?

A: You can create forms for any entity in any controller. Since you didn't post any code it's hard to guess how your controller looks like, but here an example that might help:
public function showMainEntityAction(MainEntity $mainEntity){

    ...

    $childEntity = new ChildEntity();
    $childEntity->setMainEntity($mainEntity);

    $childEntityForm = $this->createForm(new ChildEntityType(), $childEntity);

    ...

    return $this->render('...show.twig.html', array(
        'entity' => $mainEntity,
        'childEntityForm' => $childEntityForm
    );
}

Of course you have to define a form type for the child entities and add form_widget(childEntityForm) to your template.


text:
Q: Why do int keys of a python dict turn into strings when using json.dumps? According to this conversion table, Python ints get written as JSON numbers when serialized using the JSON module--as I would expect and desire.
I have a dictionary with an integer key and integer value:
>>> d = {1:2}
>>> type(d.items()[0][0])
<type 'int'>
>>> type(d.items()[0][1])
<type 'int'>

When I use the json module to serialize this to a JSON string, the value is written as a number, but the key is written as a string:
>>> json.dumps(d)
'{"1": 2}'

This isn't the behavior I want, and it seems particularly broken since it breaks json.dumps/json.loads round-tripping:
>>> d == json.loads(json.dumps(d))
False

Why does this happen, and is there a way I can force the key to be written as a number?

A: The simple reason is that JSON does not allow integer keys.
object
    {}
    { members }
members
    pair
    pair , members
pair
    string : value  # Keys *must* be strings.

As to how to get around this limitation - you will first need to ensure that the receiving implementation can handle the technically-invalid JSON.  Then you can either replace all of the quote marks or use a custom serializer.

A: If you really want to, you can check keys for being convertable to integers again using:
def pythonify(json_data):
    for key, value in json_data.iteritems():
        if isinstance(value, list):
            value = [ pythonify(item) if isinstance(item, dict) else item for item in value ]
        elif isinstance(value, dict):
            value = pythonify(value)
        try:
            newkey = int(key)
            del json_data[key]
            key = newkey
        except TypeError:
            pass
        json_data[key] = value
    return json_data

A: This function will recursively cast all string-keys to int-keys, if possible. If not possible the key-type will remain unchanged.
I adjusted JLT's example below slightly. With some of my huge nested dictionaries that code made the size of the dictionary change, ending with an exception. Anyhow, credit goes to JLT!
def pythonify(json_data):

    correctedDict = {}

    for key, value in json_data.items():
        if isinstance(value, list):
            value = [pythonify(item) if isinstance(item, dict) else item for item in value]
        elif isinstance(value, dict):
            value = pythonify(value)
        try:
            key = int(key)
        except Exception as ex:
            pass
        correctedDict[key] = value

    return correctedDict


text:
Q: How to make a copy(Deep Copy) of an Object of type List> by value? I tried many ways to copy an object without referencing it, and it's seems to me all of them shallow copy not deep.
Let's say I have sent an Object of type java List<List<Integer>> using parameters from main to a method.
void reverseMatrix(List<List<Integer> > grid)
{

}

so I defined List> tempGrid= new ArrayList<>(); inside this method above, and I want to copy all the values(by value not by reference.)
I tried Iterator as below :
Iterator<List<Integer>> iterator = grid.iterator();
        while(iterator.hasNext()){
            tempGrid.add(iterator.next());
        }

after applying the code above it, still, change the parent object(grid) not tempGrid.
If I applied this code java tempGrid.get(0).set(0,1);
it will change grid too.
I saw some subject about iterate by values.
        List<Integer> temp1 = new ArrayList<>();

   for(List<Integer> list: grid){
          for(Integer numb: list) {
              temp1.add(numb);
          }
          tempGrid.add(temp1);
      }

I tried to use Collections.copy, but give me error, that des size not fit to source.
I expect to get a new object not get effected by operations on the old object.

A: Integer objects are immutable so you don't need to deep copy them.
Both the outer and inner lists are mutable, so they need to be copied. Assuming we don't need to retain the list type, e.g. ArrayList vs LinkedList, we can simply use the ArrayList(Collection) constructor to copy the inner lists.
Using code that doesn't require Java 8:
static void deepCopy(List<List<Integer>> input) {
    List<List<Integer>> output = new ArrayList<>(input.size());
    for (List<Integer> inner : input)
        output.add(new ArrayList<>(inner));
    return output;
}


text:
Q: snowflake_table to add column-level comments using Terraform As a data modeler, I have fully annotated my data model and would like to create my snowflake table(s) with column-level comments.
I would like to use the snowflake_table resource to create a table with column level comments.
From pure-DDL perspective, I would like this:
CREATE TABLE MYDB.MYSCHEMA.MYTBL
    (COL1 STRING comment 'hello'
   , COL2 INT comment 'goodbye' )
COMMENT = 'test table'

To be supported while preparing Terraform DDLs in the nested schema for column (as such):
resource "snowflake_table" "my_tbl" {
  name     = "MYTBL"
  database = "MYDB"
  schema   = "MYSCHEMA"
  column   {
            name = "COL1"
            type = "STRING"
            comment = "hello"
  }
  column   {
            name = "COL2"
            type = "INT"
            comment = "goodbye"
  }
  comment  = "test table"

  depends_on = [snowflake_schema.schema]
}

It generate error while executing through Terraform however it works perfect without Terraform. Anyone has used Terraform to push DDLs into Snowflake or any DB/Schema with addition to column level comments?

A: Below worked with terraform-provider-snowflake 0.25.15
resource snowflake_table table2 {
  database            = snowflake_database.database.name
  schema              = snowflake_schema.schema.name
  name                = var.table2_name

  column {
    name     = "id"
    type     = "NUMBER(38,0)"
    nullable = true
    comment = "id column comment"
  }

  column {
    name     = "data"
    type     = "VARCHAR(16777216)"
    nullable = false
    comment = "data column comment"
  }
  comment = "table comment"
}


text:
Q: how to remove pagination after the datatable is rendered with pagination My requirement is to have an 'All' button that shows all records of a paginated jquery datatable. Can I manipulate the same datatable, or must I create a new one to display all records without pagination?

A: You have to make use of
fnLengthChange as detailed on the API:
http://datatables.net/plug-ins/api#fnLengthChange
For example:
$(document).ready(function() {
    var oTable = $('#example').dataTable();
    oTable.fnLengthChange( 10000 ); //big limit to show All
} );


text:
Q: Projective planes question Question: Let $P(U1)$ and $P(U2)$ be two non-intersecting lines in the 3-dimensional projective space $RP^3 = P(\Re^4)$. Show that $R^4$ equals the direct sum $U1 ⊕ U2$.
This is a question from my problem sheet. I am not sure I understand it quite right, though.
My questions:
How do we define a line in $P(\Re^4)$? $P(\Re^4)$ should be the set of all lines through the origin, am I right? Is it the union of points $[a,b,c,d]$ which determine the lines through the origin?
Now, after that, we should define $U_1$ and $U_2$ by taking the lines through each point on the lines $P(U_1)$ and $P(U_2)$ to get $2$ planes, right?
Also, any help for the rest of the problem will be appreciated.

A: A line $P(U)$ in $\mathbb RP^3$ is by definition a linear plane $U \subset \mathbb R^4$, or more precisely the projection of such a plane by the projection map $P : \mathbb R^4 \to \mathbb RP^3$. If you want, you can also use parametrization : for example a line is given by $[s:t:s+t:0]$ where $s,t \in \mathbb R$, corresponding to the plane spanned by the vectors $(1,0,1,0)$ and $(0,1,1,0)$.
Now, how can you translate on $U_1,U_2$ the hypothesis that $P(U_1) \cap P(U_2) = \emptyset$ ?


text:
Q: What is the Alternative for Form Tag in React Fluent-UI? I am currently developing Microsoft Addin with react. I have added TextField to the AddIn.
But I couldn't get the value from inputs because there is no Form tag in fluent-ui.
What can I do to resolve this?
This is the component.
<Stack>
  <TextField placeholder="User Name" />
  <TextField placeholder="Password" type="password" />
  <PrimaryButton className="ms-welcome__action" iconProps={{ iconName: "ChevronRight" }}>
    Sign In
  </PrimaryButton>
</Stack>

A: I don't know if it is the best way to solve you're problem, but you can add a value to each TextField that is linked to a prop in your component, like that :
<Stack>
  <TextField placeholder="User Name" value={userName} onChange={(e) => setUserName(e.target.value)} />
  <TextField placeholder="Password" type="password" value={passWord} onChange={(e) => setPassWord(e.target.value)} />
  <PrimaryButton className="ms-welcome__action" iconProps={{ iconName: "ChevronRight" }}>
    Sign In
  </PrimaryButton>
</Stack>

The onChange handler reset the prop the user is modifying.
Don't forget to declare userName and passWord via the useState hook :
const [userName, setUserName] = useState("");
const [passWord, setPassWord] = useState("");


text:
Q: Special Relativity Frame Ambiguity If I have some predefined coordinate system — "my rest frame," then I pick an "inertial frame" moving at some velocity with respect to my "rest frame." Special relativity states that in the rest frame, the speed of an object can not exceed the speed of light — however I could pick any velocity for my inertial frame, say $99.9$% or even $200$% $c$, then say that my ship is traveling at $99.9$% $c$ in the inertial frame, and now I have a ship moving at $199.8$% or $299.9$% $c$ relative to the original rest frame?
Isn't there some sort of self-contradiction here? Is the proposition that no object cannot exceed the speed of light simply a phenomenon resulting from observation assuming that time "runs" at the same rate for both observers, not from the motion of the actual object?

A: The postulates of special relativity are

*

*The laws of physics are the same in all inertial frames of reference.

*As measured in any inertial frame of reference, light is always propagated in empty space with a definite velocity $c$ that is independent of the state of motion of the emitting body.

The first postulate ensures that there is no preferred inertial frame of reference; all inertial frames are the same and the laws of physics are invariant.
The second one speaks about the invariance of $c$, the speed of light. In other words, the speed of light in free space has the same value in all inertial frames of reference.

...however I could pick any velocity for my inertial frame, say 99.9% or even 200% c...

By definition, you cannot choose an inertial reference frame which is moving at any arbitrary speed $> c$. It just does not exist.
Why does it not exist? Because the special relativity respects Lorentz transformation and not Galilean. Said in simpler words, the valid frames consist solely of those in which speed of light is precisely $c$, all of which are linked by Lorentz transformation.
If you still want to define a frame which is moving at $200\% c$, you cannot use this theory. However, keep in mind that special relativity has been far more successful when space-time curvature is flat. A surprisingly large number of papers, going all the way back to the birth of relativity, have been written by people trying to find a way to extend the Lorentz transformations to superluminal speeds, and these have all turned out to be failures [ref].

...then say that my ship is travelling at 99.9% c in the inertial frame, and now I have a ship moving at 199.8% or 299.9% c relative to the original rest frame?

Neither of them. You need to use Einstein's law for addition. For a ship moving at velocity $u'$ in the frame $S'$ and the velocity of inertial frame $S'$ w.r.t to another inertial frame $S$ is $v$, then someone in $S$ would observe the velocity of ship as $u$ given by
$$u = {v+u'\over 1+(v u'/c^2)} < c$$
Galaxies moving faster than light requires General Relativity. For more about that, read this and this along with links therein.


text:
Q: raspberry pico: failed to build I used pico_project.py to generate a project but  failed to build it with vscode.

I can build it with ubuntu terminal,just use the command "make".I want to vscode to program the raspberry pico.
my computer:HP Zhan66 Pro G1  Ubuntu20.04
I just bought the raspberry pico yesterday.I think it shouldn't be a problem.


text:
Q: Problem with a local utility used as a dependency in a product Here's the problem. I have mynamespace.mypackage that has as a dependency mynamespace.mydependencypackage, that is a local utility. It's registered using component registry.
In config.py from mynamespace.mypackage, I have
DEPENDENCIES = ['mynamespace.mydependencypackage']

And in my mynamespace.mypackage's setuphandlers.py this dependency is installed if not already installed.
Problem is: if I reinstall mynamespace.mypackage through ZMI, everything seems to perfectly install (since no errors are shown) but I keep getting a ComponentLookupError when using methods in mynamespace.mypackage that gets the utility:
Module zope.component._api, line 207, in getUtility
ComponentLookupError: (<InterfaceClass MY_UTILITY_INTERFACE, '')

I can 'fix' this problem, by reinstalling the mynamespace.mydependencypackage in my setuphandlers.py or through the ZMI as well when reinstalling mynamespace.mypackage, but this doesn't seem the best solution for me.
What am I missing about Generic Setup here? I didn't make this utility persist any value on ZODB whatsoever. I can just forget about all these problems and create a BrowserView with utilities methods, but I want to understand first why am I having these problems.
EDIT: Now, I have a bigger problem. The TypeError: ('object.__new__(MyClass) is not safe, use Persistence.Persistent.__new__()', <function _reconstructor at 0xb7783e9c>, (<class 'mynamespace.mydependencypackage.package.MyClass'>, <type 'object'>, None)) is being shown. Full traceback:
Traceback (innermost last):
  Module ZPublisher.Publish, line 110, in publish
  Module ZPublisher.BaseRequest, line 429, in traverse
  Module ZPublisher.BeforeTraverse, line 99, in __call__
  Module Products.CMFCore.PortalObject, line 94, in __before_publishing_traverse__
  Module zope.event, line 23, in notify
  Module zope.component.event, line 26, in dispatch
  Module zope.component._api, line 130, in subscribers
  Module zope.component.registry, line 290, in subscribers
  Module zope.interface.adapter, line 535, in subscribers
  Module zope.component.event, line 33, in objectEventNotify
  Module zope.component._api, line 130, in subscribers
  Module zope.component.registry, line 290, in subscribers
  Module zope.interface.adapter, line 535, in subscribers
  Module zope.app.component.site, line 375, in threadSiteSubscriber
  Module zope.app.component.hooks, line 61, in setSite
  Module Products.CMFCore.PortalObject, line 75, in getSiteManager
  Module ZODB.Connection, line 761, in setstate
  Module ZODB.Connection, line 819, in _setstate
  Module ZODB.serialize, line 604, in setGhostState
  Module ZODB.serialize, line 597, in getState
  Module copy_reg, line 48, in _reconstructor
TypeError: ('object.__new__(MyClass) is not safe, use Persistence.Persistent.__new__()', <function _reconstructor at 0xb7783e9c>, (<class 'mynamespace.mydependencypackage.package.MyClass'>, <type 'object'>, None))

A: It sounds like you have custom Python code in your setuphandlers.py file to install the dependency. Is there a reason you don't note the dependency in the metadata.xml file? Or can you show us that code?
When activating an add-on in Plone, it does a before/after comparison of various entities to support deactivation. Among these are local persistent utilities, as defined by the componentregistry.xml file. Note: anything defined in GenericSetup xml files results in persistent changes - if you want non-persistent utilities, use ZCML files to register them.
So when you have custom code to add a local utility in your setuphandlers.py code, Plone thinks this utility belongs to your main add-on. If you reinstall that add-on the utility gets removed alongside anything else and then everything is installed again.
I'm guessing your "is it already installed" check fails after the reinstall and the utility isn't added again.
You can avoid all of this, by simple giving both the dependency and main add-on their own GenericSetup profiles and than noting a dependency in the main's metadata.xml, like:
<?xml version="1.0"?>
<metadata>
  <version>1</version>
  <dependencies>
    <dependency>profile-my.dependency:default</dependency>
  </dependencies>
</metadata>

Once you do that the dependencies profile will be activated independently and Plone keeps track of it on its own. If you then decide to reinstall the main add-on, the dependency won't be touched at all and remains intact.


text:
Q: Sorting list of string with constraints of complexity I need to sort a list of strings, where each string is of length k, and each string consists only of the characters {'a', 'b', 'c', 'd', 'e'}.
I do have the limitations of:

*

*I cannot use any sorting methods include the methods that come with python.

*Comparing 2 strings is of complexity O(k).

*Sorting is not in-place, a new sorted list needs to be returned.

*Space complexity is O(k) [w/o considering the return list of length n].

*Time complexity is O(n*k*(5^k)).

The function receives lst, k which are the list to sort and the length of each string in the list. I have 2 methods string_to_int(), int_to_string() that convert a string of length k to a number in the range [0,5^k) and vice-versa, the methods are bijections. Each of these methods are of time complexity of O(k).
My best attempt was:
def sort_strings(lst, k):
  int_lst = []
  for item in lst:
      int_lst.append(string_to_int(item))
  sorted_lst = []
  for i in range(5**k):
      if i in int_lst:
          sorted_lst.append(int_to_string(k, i))

  return sorted_lst

But here I create int_lst which is of space complexity of O(n) and not O(k).
Any hints of how to approach that?

A: You have a really long time limit. That's enough time to go through every possible length-k string, in order, and compare those strings against every string in your input list.
What can you do with that?

A: Try to reuse int_list as the output, along the lines
    replace = 0

    for i in range(5 ** k):
        if i in int_list[replace:]:
            int_list[replace] = int_to_string(i, k)
            replace += 1

    return int_list

Edit: In case input list contains duplicates, consider while i in int_list[replace:]: instead of if .....


text:
Q: Create Prepared SQL Statement where in the SQL Statement already equal values (SQL Injection) created a form that gets posts by user id. my question is:
how do you convert this to a prepared statement. seen where you assign a var for a value, however how would you prepare a SQL statement that already equals a value in the request? Statement is:
 $sql = "SELECT * FROM posts, users WHERE posts.user_id = users.id AND
 posts.user_id = ".$_GET['uid'];"

Complete PHP Statement
          this code also runs "PHP functions" but should not be needed for writeup (I suspect)
                                    If it does please let me know and I can supply them.
<?php
if(isset($_GET['uid'])) {
    $sql="SELECT * FROM posts, users WHERE posts.user_id = users.id
                    AND posts.user_id = ".$_GET['uid'];
} else {
    $sql="SELECT * FROM posts, users WHERE posts.user_id = users.id
                    ORDER BY post_id DESC";
}

include_once('dbconnect.php');
$result=mysql_query($sql);
if(!$result) {
    error_reporting(1);
    echo mysql_error();
}

$postID=$_GET['pid'];
while($row=mysql_fetch_array($result)) {
    echo $row['post_id'].$row['post_title'].$row['username'];
    if(isset($_SESSION['id'])) {
        if(getSessionUserId() == $row['user_id']) {
            echo $row['post_id'].$row['post_id'];
        }
    }
    echo substr($row['post_content'], 0, 200).$row['post_id'];
}
?>

A: (1) found out that I needed to create an array that set names to UTF8; once that was done I was able to connect to Server. (2) then needed to send call to server.  (3) then fetch results from server [fetchAll()]
<?php
    $dsn = 'mysql:host=HOST;dbname=DATABASE';
    $username = 'USERNAME';
    $password = 'PASSWORD';
    $options = array(
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', PDO::ATTR_PERSISTENT => false
    );

    try
    {
        $dbh = new PDO($dsn, $username, $password, $options);
        echo '
PDO connection created Successfully
';
        print '
Connection Info:

'.$dsn.'
';
        print '
Username: '.$username.'

';
    }

    catch(PDOException $e)
    {
        echo '
'.$e->getMessage().'
';
        die();
    }

    $dbh = new PDO($dsn, $username, $password);
    $stmt = $dbh->prepare('SELECT * FROM posts, users WHERE posts.user_id = users.id ORDER BY post_id DESC');
    $stmt->execute();
    $result = $stmt->fetchAll();

    foreach($result as $row)
    {
        echo '
'.$row['post_title'].'
';  #Post Title
        echo '
 Author: '.$row['username'].'
';
        echo '
'.substr($row['post_content'], 0, 200).' ...More

';
    }
?>

Works Great now! See it at Create Prepared SQL Statement: Demo.


text:
Q: Replace values in columns of a data frame after match a pattern in another column Is there an intuitive way to replace values in two columns of a data frame if patterns in one column of the same differ from the desired one? Specifically, my data frame looks like:
   Col1              Value1      Value2
   my_HD_SAMPLE      34          0.34
   my_HD_T_SAMPLE    6           0.6
   my_BD_NAME        94          0.94
   my_LE_NAME        1           0.1
   my_TS_SAMPLE      74          0.74

I would like to replace the values in columns 2 and 3 with 0 if the row in Col1 does not match the pattern BD|HD. The desired output should be:
   Col1              Value1     Value2
   my_HD_SAMPLE      34         0.34
   my_HD_T_SAMPLE    6          0.6
   my_BD_NAME        94         0.94
   my_LE_NAME        0          0
   my_TS_SAMPLE      0          0

I tried this:
mydf = mydf$"Col1"[!grepl('BD|HD',mydf$"Col1")] <- 0

And I got this warning message:
In [<-.factor`(`*tmp*`, !grepl("BD|HD", mydf$Col1), value = c(`NA` = NA,  :
  invalid factor level, NA generated

How can I solve this problem?

A: Seems to me Col1 is a factor. Try:
# Convert to character first.
rows <- !grepl("BD|HD", as.character(mydf$`Col1`))
mfdf$`Value1`[rows] <- 0
mfdf$`Value2`[rows] <- 0

A: Try This
mydf[!grepl('BD|HD',mydf$"Col1"),][2:ncol(mydf)] <- 0

> mydf
            Col1 Value1 Value2
1   my_HD_SAMPLE     34   0.34
2 my_HD_T_SAMPLE      6   0.60
3     my_BD_NAME     94   0.94
4     my_LE_NAME      0   0.00
5   my_TS_SAMPLE      0   0.00


text:
Q: Can you use an eventlet pool within another eventlet pool? I'm using an eventlet celery worker and want to know if it's safe to use a pool of greenthreads inside one of my tasks.

A: Sure, it is safe. In unlikely event you experience any issues, please report them here https://github.com/eventlet/eventlet/issues/new


text:
Q: How to set vue component property based on if parent element has a specific class? I have this stucture in my parent Component:

    <VRVideoPage :isActive="false"></VRVideoPage>

Via a third-party tool it's possible that the "section"-div gets a css class named "active" added.
I now want to toggle the ":isActive" property on the VRVideoPage component to true, whenever the active class is applied to its parent.
Is this achivable via the vue template syntax?

A: You can try like this but it is not a good practice and may not work:

    <VRVideoPage ref="video" :isActive="$refs.video.$el.parentNode.classList.contains('active')"></VRVideoPage>


text:
Q: If the ledger of peer is tampered in hyperledger fabric network, how can be the previous state of ledger restored? My hyperledger fabric network consists of 1 orderer, 1 organization and 3 peers. I tampered ledger of first peer and then tried to do another transaction on the same peer, then the following error was thrown:
"Error: deliver completed with status (SERVICE_UNAVAILABLE) before txid received - proposal response: "
But the transaction was executed and also the block was added in tampered ledger of peer. But the tampered data was not restored to previous state.
With the reference of the answer in this link - "https://intellipaat.com/community/17752/in-hyperledger-fabric-blocks-locations-and-validity-criteria", I came to know that if the tampering is done, "the state database can be dropped and rebuilt from the blockchain". So this process of dropping and rebuilding the database is done automatically by peer or we need to do it manually?
In short, if tampering is done in ledger of peer, how can be the previous state of ledger restored?

A: If the state data is in doubt, you can stop peer, drop state database, and upon restart peer will rebuild state database. When peer is stopped, the command peer node rebuild-dbs will drop state database for you. See the command documentation.
If the blockchain ledger itself is in doubt, you will need to either replace the peer or reset the peer to genesis blocks using peer node reset command. See the command documentation.