text:
Q: Alert Dialog positive button issue I am developing an app that asks the user to type task's name, description....,but when the user intends to leave the edit page without saving the task I need to pop up a dialog to confirm leaving, so if he clicked abandon changes he must return to the home page of the app otherwise he will stay at the same page.
I have problem with this, when the user clicks abandon changes the dialog dismisses and he stays at the edit page.
MainActivity.kt
package muhabalafandi.example.tasktimer

import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*

private const val TAG = "MainActivity"
private const val DIALOG_ID_CANCEL_EDIT = 1

class MainActivity : AppCompatActivity(), AddEditFragment.OnSaveClicked,
    MainActivityFragment.OnTaskEdit,
    AppDialog.DialogEvents {

    // Whether or the activity is in 2-pane mode
    // i.e. running in landscape, or on a tablet.
    private var mTwoPane = false

    override fun onCreate(savedInstanceState: Bundle?) {
        Log.d(TAG, "onCreate: starts")
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        mTwoPane = resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
        Log.d(TAG, "onCreate: twoPane is $mTwoPane")

        val fragment = findFragmentById(R.id.task_details_container)
        if (fragment != null) {
            // There was an existing fragment to edit a task, make sure the panes are set correctly
            showEditPane()
        } else {
            task_details_container.visibility = if (mTwoPane) View.INVISIBLE else View.GONE
            mainFragment.visibility = View.VISIBLE
        }
        Log.d(TAG, "onCreate: finished")
    }

    private fun showEditPane() {
        task_details_container.visibility = View.VISIBLE
        // hide the left hand pane, if in single pane view
        mainFragment.visibility = if (mTwoPane) View.VISIBLE else View.GONE

    }

    private fun removeEditPane(fragment: Fragment? = null) {
        Log.d(TAG, "removeEditPane called")
        if (fragment != null) {
//            supportFragmentManager.beginTransaction()
//                .remove(fragment)
//                .commit()
            removeFragment(fragment)
        }

        // Set the visibility of the right hand pane
        task_details_container.visibility = if (mTwoPane) View.INVISIBLE else View.GONE
        // and show the left hand pane
        mainFragment.visibility = View.VISIBLE

        supportActionBar?.setDisplayHomeAsUpEnabled(false)

    }

    override fun onSaveClicked() {
        Log.d(TAG, "onSaveClicked: called")
        removeEditPane(findFragmentById(R.id.task_details_container))
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        when (item.itemId) {
            R.id.menuMain_addTask -> taskEditRequest(null)
//            R.id.menuMain_settings -> true
            android.R.id.home -> {
                Log.d(TAG, "onOptionsItemSelected: home button pressed")
                val fragment = findFragmentById(R.id.task_details_container)
//                removeEditPane(fragment)
                if ((fragment is AddEditFragment) && fragment.isDirty()) {
                    showConfirmationDialog(
                        DIALOG_ID_CANCEL_EDIT,
                        getString(R.string.cancelEditDialogMessage),
                        R.string.cancelEditDialogPositiveCaption,
                        R.string.cancelEditDialogNegativeCaption
                    )
                    Log.d(TAG, "dialogId : $DIALOG_ID_CANCEL_EDIT")
                } else {
                    removeEditPane(fragment)
                }
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onTaskEdit(task: Task) {
        taskEditRequest(task)
    }

    private fun taskEditRequest(task: Task?) {
        Log.d(TAG, "taskEditRequest: starts")

        // Create a new fragment to edit the task
//        val newFragment = AddEditFragment.newInstance(task)
//        supportFragmentManager.beginTransaction()
//            .replace(R.id.task_details_container, newFragment)
//            .commit()
        replaceFragment(AddEditFragment.newInstance(task), R.id.task_details_container)
        showEditPane()

        Log.d(TAG, "Exiting taskEditRequest")
    }

    override fun onBackPressed() {
        val fragment = findFragmentById(R.id.task_details_container)
        if (fragment == null || mTwoPane) {
            super.onBackPressed()
        } else {
//            removeEditPane(fragment)
            if ((fragment is AddEditFragment) && fragment.isDirty()) {
                showConfirmationDialog(
                    DIALOG_ID_CANCEL_EDIT,
                    getString(R.string.cancelEditDialogMessage),
                    R.string.cancelEditDialogPositiveCaption,
                    R.string.cancelEditDialogNegativeCaption
                )
            } else {
                removeEditPane(fragment)
            }
        }
    }

    override fun onPositiveDialogResult(dialogId: Int, args: Bundle) {
        Log.d(TAG, "onPositiveDialogResult: called with dialogId $dialogId")
        if (dialogId == DIALOG_ID_CANCEL_EDIT) {
            val fragment = findFragmentById(R.id.task_details_container)
            removeEditPane(fragment)
        }
    }

    override fun onStart() {
        Log.d(TAG, "onStart: called")
        super.onStart()
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        Log.d(TAG, "onRestoreInstanceState: called")
        super.onRestoreInstanceState(savedInstanceState)
    }

    override fun onResume() {
        Log.d(TAG, "onResume: called")
        super.onResume()
    }

    override fun onPause() {
        Log.d(TAG, "onPause: called")
        super.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        Log.d(TAG, "onSaveInstanceState: called")
        super.onSaveInstanceState(outState)
    }

    override fun onStop() {
        Log.d(TAG, "onStop: called")
        super.onStop()
    }

    override fun onDestroy() {
        Log.d(TAG, "onDestroy: called")
        super.onDestroy()
    }
}

AppDialog.kt
package muhabalafandi.example.tasktimer

import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.DialogFragment

private const val TAG = "AppDialog"

const val DIALOG_ID = "id"
const val DIALOG_MESSAGE = "message"
const val DIALOG_POSITIVE_RID = "positive_rid"
const val DIALOG_NEGATIVE_RID = "negative_rid"

class AppDialog : DialogFragment() {

    private var dialogEvents: DialogEvents? = null

    internal interface DialogEvents {
        fun onPositiveDialogResult(dialogId: Int, args: Bundle)
//        fun onNegativeDialogResult(dialogId: Int, args: Bundle)
//        fun onDialogCancelled(dialogId: Int)
    }

    override fun onAttach(context: Context) {
        Log.d(TAG, "onAttach called: context is $context")
        super.onAttach(context)

        // Activities/Fragments containing this fragment must implement its callbacks.
        dialogEvents = try {
            // Is there a parent fragment? If so, that will be what we call back
            parentFragment as? DialogEvents
        } catch (e: TypeCastException) {
            try {
                // No parent fragment, so call back the Activity instead
                context as DialogEvents
            } catch (e: ClassCastException) {
                // Activity doesn't implement the interface
                throw ClassCastException("Activity $context must implement AppDialog.DialogEvents interface")
            }
        } catch (e: ClassCastException) {
            // Parent fragment doesn't implement the interface
            throw ClassCastException("Fragment $parentFragment must implement AppDialog.DialogEvents interface")
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        Log.d(TAG, "onCreateDialog called")

        val builder = AlertDialog.Builder(requireContext())

        // fix "smart cast to Bundle is impossible, because 'arguments' is a mutable property that could have been changed by this time"
        val arguments = arguments
        val dialogId: Int
        val messageString: String?
        var positiveStringId: Int
        var negativeStringId: Int

        if (arguments != null) {
            dialogId = arguments.getInt(DIALOG_ID)
            messageString = arguments.getString(DIALOG_MESSAGE)

            if (dialogId == 0 || messageString == null) {
                throw IllegalArgumentException("DIALOG_ID and/or DIALOG_MESSAGE not present in the bundle")
            }

            positiveStringId = arguments.getInt(DIALOG_POSITIVE_RID)
            if (positiveStringId == 0) {
                positiveStringId = R.string.ok
            }
            negativeStringId = arguments.getInt(DIALOG_NEGATIVE_RID)
            if (negativeStringId == 0) {
                negativeStringId = R.string.cancel
            }
        } else {
            throw IllegalArgumentException("Must pass DIALOG_ID and DIALOG_MESSAGE in the bundle")
        }

        return builder.setMessage(messageString).setPositiveButton(positiveStringId) { _, _ ->
            // callback positive result function
            dialogEvents?.onPositiveDialogResult(dialogId, arguments)
        }.setNegativeButton(negativeStringId) { _, _ ->
            // callback negative result function, if you want to implement it.
            // dialogEvents?.onNegativeDialogResult(dialogId, arguments)
        }.create()
    }

    override fun onDetach() {
        Log.d(TAG, "onDetach called")
        super.onDetach()

        // Reset the active callbacks interface, because we're no longer attached.
        dialogEvents = null
    }

    override fun onCancel(dialog: DialogInterface) {
        Log.d(TAG, "onCancel called")
        val dialogId = requireArguments().getInt(DIALOG_ID)
//        dialogEvents?.onDialogCancelled(dialogId)
    }
}

A: buttonYes.setOnClickListener {
     findNavController().popBackStack()
     findNavController().popBackStack()
 {


text: Q: SciFi book with man and woman traveling across planets in a three seater cycle, with their pet dog I remember reading a SciFi book as a child! It involved a man and a woman, possibly sibilings traveling across different planets in a three seater cycle along with their pet dog! The book must be from the early 90s!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Definitive if check Consider this kind of if-statment in a function:
int Foo( void )
{
    if ( HostCPUInfo::IsSSE3Supported() )
        // SSE3 intrinsic
    else
        // C code
}

I check during the runtime if SSE3 instructions are supported by the host CPU to permit the use of faster intrinsic. But, as I doubt the the return of  HostCPUInfo::IsSSE3Supported() is going to change during the life of my program, is there a way to only make this kind of checks once (maybe during the initialization) ?

A: Here's one way with function pointers:
int (*foo)() = synthetic_foo;

void init() {
    if (HostCPUInfo::IsSSE3Supported()) {
        foo = sse3_foo;
    }
}

A: You could use a function pointer that is initialized to a function that performs the test. This way, you don't have to call a special initialization function before using foo():
int foo_init (void);
int foo1 (void);
int foo2 (void);

int (*Foo) (void) = foo_init;

int foo_init (void)
{
  Foo = (HostCPUInfo::IsSSE3Supported() ? foo1 : foo2);
  return Foo();
}

...

int main (void)
{
  Foo();

  ...
}

This might have implications for performance if the compiler is unable to inline the foo functions.

A: Check HostCPUInfo::IsSSE3Supported() once before entering Foo and set some boolean depending on the return value.
Then in Foo check only that boolean, which will always remain the same regardless of whether the return value of HostCPUInfo::IsSSE3Supported() changes.


text:
Q: Spring parent container I came up with the parent/child-container concept. I have the spring's param defined in web.xml file as follows:
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/applicationContext-site-dao.xml
        /WEB-INF/applicationContext-site-security.xml
        /WEB-INF/applicationContext-mailing.xml
        classpath:**/applicationContext-*.xml
        classpath*:META-INF/applicationContext-*.xml
    </param-value>
</context-param>

Is that configuration is going to create 5 child containers of 1 big parent container?

A: Given that your asking about a context-param, I'm going to assume you're asking about the ContextLoaderListener.
The ContextLoaderListener will create a single ConfigurableWebApplicationContext and use its ConfigurableWebApplicationContext#setConfigLocation(String) method to set the configuration location(s), separated by white space.
This is a single Spring container (ApplicationContext). It has no parents.
Spring will then create another WebApplicationContext through the DispatcherServlet which will use the ContextLoaderListener's as a parent.


text:
Q: Setup websockets with Python/Django Is there some way I could setup my architecture like this for my web application:
Backend - Django + DRF (Rest API)
Frontend - React

And on the backend setup a websocket Client to listen to an external websocket Server and then forward the data from the Client to a new Server that I will create. So in React I could listen to this websocket Server that I have created?
I tried implementing this in React to listen to an external websocket Server, but it just gave me headaches trying to use proxy to avoid CORS problems.
How should I approach this? Am I thinking straight here?

A: Hello Marcus C and welcome to StackOverflow!
Since you didn't post any code yourself I can't give you any concrete examples, but I can point you in the right direction. As you said yourself trying to use an external WebSockets server (such as Node.js with socket.io) is a pain. For this purpose the Django Channels library exists. It is really useful as it allows direct access to database and other Django-related stuff.
If you run Django in a Docker container, the best way to use Channels is to run two separate containers, one with say gunicorn or uWSGI servers for the synchronous part and another with Channels' recommended Daphne server for asynchronous part, both proxied by nginx. Standard (or rather common) way is to use /ws path prefix for the asynchronous endpoints.


text:
Q: Client Timberline Office Integration from a .NET Web Application I have an ASP.NET application where I need to push data from the ASP.NET application into the client's Timberline Office database at the users request.  I need to do this by connecting to the client's Pervasive ODBC Driver to insert data into the Timberline data structures.
I would like to build a component (ActiveX, or something like that) that would work in IE at a minimum, and also the Firefox and Chrome browsers if possible.  I would like to build this component using VB.NET and Visual Studio 2008 if possible.
Can anyone provide any resources (web sites, code examples) to help me with this?
Thanks


text:
Q: Why chaining on String.trim() throws Exception? Sorry if it's a stupid question, but I can't find an explanation.
I have a String like this :
String str ="This is 50 test. Try it !!";

I want to get the number just before test.
If I do :
str = str.substring(0, str.indexOf("test")).trim();
str = str.substring(str.lastIndexOf(" ")).trim();
System.out.println(str);

I get : "50"
However if I do this :
str = str.substring(0, str.indexOf("test")).trim().substring(str.lastIndexOf(" ")).trim();

I get : Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -13
Since trim() returns a copy of the string, with leading and trailing whitespace omitted, why this exception is thrown ? Why can't I chain my methods call on str ? I can't understand.

A: str = str.substring(0, str.indexOf("test")).trim().substring(str.lastIndexOf(" ")).trim();
                                                             ^

This str refers to the original string.

str = str.substring(0, str.indexOf("test")).trim();  // first operation
str = str.substring(str.lastIndexOf(" ")).trim();
                    ^

This str refers to the string after the first operation is applied. Therefore, the two approaches are not equivalent.


text:
Q: PYTHON- PYGAME: How do I know if a mouse clicked on an image? I'm making a basic level game where if i click a card, a picture will show. The pictures are randomly chosen. and so far, I have assigned random pictures to a card and the cards are shown face down. So if i click the card, i want the assigned picture (which is in a dictionary) to show.
I want to know how I can detect if I've clicked on an image (of the card) because the x,y coordinates of the image is on the top left. Right now, I'm trying to figure out a way to use the xy coordinates of the mouse click to detect if the image has been clicked on. Is there a way I could use 'collide' or is that making things too complicated? I'm a beginner programmer so I'm still trying to learn python and pygame :|

A: Instead of hardcoding coords / using range, use the collision functions:
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            # Set the x, y postions of the mouse click
            x, y = event.pos
            if ball.get_rect().collidepoint(x, y):
                # do swap


text:
Q: How to run Java source code within a Java program I have wrote some code to compile a Java source code. It then produces the .class file. The problem is how do I run it?
For example, I am ok with the name of the program and class being set, I've used prog p = new prog(), in this case, however, the class file does not yet exist until I compile it. Not really sure what to do. Can someone give me an advice?
btw, the class looks like this:
public void compile{
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  int compilationResult = compiler.run(null, null, null, fileToCompile);
}

public void run(){
  Prog prog = new Prog();
  prog.run();
}

A: If you just want to run it, you could launch a java process using
Runtime.exec or ProcessBuilder. These will create a seperate java process to run your java program. This is more likely what you want. You can essentially do the equivelant of:
>java someClass

from within your application. This link may help.
If you want to actually load the classfile and use it in your current application, I think something along the lines of this, or dynamically loading Java Classes ought to help. Basically (directly from the link, slightly modified):
public class MainClass {

  public static void main(String[] args){

    ClassLoader classLoader = MainClass.class.getClassLoader();

    try {
        Class aClass = classLoader.loadClass("MyClass");
        System.out.println("aClass.getName() = " + aClass.getName());
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

}

Once you loaded the class, you have a Class object, and you can create an instance of the class represented by aClass by calling aClass.newInstance(), which is like
MyClass newObj = new MyClass()
Or you can use any of the other methods the Class object exposes.
As pointed out by davmac, the code sample above presumes that the code you're loading is on your applications classpath. If the class files you want to run are not in your classpath, you might want to look into URLClassLoader

A: Load it by URLClassLoader.
File root = new File("/java"); // The package root.
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
Class<?> cls = Class.forName("test.Test", true, classLoader); // Assuming package test and class Test.
Object instance = cls.newInstance();
// ...

See also:

*

*How do I instantiate a class dynamically in Java?

A: You need to create a classloader (a URLClassLoader will probably be fine) which will load the just-compiled class file. (So for a URLClassLoader, the compilation output path should be one of the URLs).
Then, load the compiled class using the classloader, and execute it using reflection.
Class c = cl.loadClass("ClassName");
... etc.


text:
Q: Xcode & wxWidgets Framework I've downloaded wxWidgets - wxwidgets.org
I ran the configure file using terminal.
How can I use this framework with Xcode C++ project?
Thanks!

A: Please take a look at the following documentation, or consider pin pointing down a more specific question about using the framework (ie, what problems you may have run into).
http://wiki.wxwidgets.org/Development:_wxMac
http://wiki.wxwidgets.org/Guides_%26_Tutorials#Mac_OS
http://wiki.wxwidgets.org/Creating_Xcode_projects_for_wxWidgets_applications (Out of date, but may still help you. As someone who used wxWidgets in the past, I can tell you that the code is correct).


text:
Q: I don't understand why the contrapositive part of the proof of continuity holds So, assuming whoever can answer this knows the first part of this proof, that is, showing that for all$ \epsilon\gt0$ and for all $ p\in M$ there is  a $\delta\gt0$. Also there is an $ x\in M$ such that $d_M(x,p)\lt\delta\implies d_N(f(x),f(p))\lt \epsilon$. I may not have this perfectly right but I'd assume you can understand. Now I get and understand this. But what I don't understand is the showing that the contrapositive leads to a contradiction. So my book (using Real Analysis by Charles Pugh) says this as the proof:

If $f$ is not continuous then it does not preserve convergence. $f$ being not continuous means that for some $p\in M$ there is an $\epsilon\gt 0$ such that no matter how small we take $\delta$, there will always be points $x\in M$ with $d(x,p)\lt \delta$ but $d(fx,fp)\ge \epsilon$. Take $\delta_1=1, \delta_2=\frac12,... \delta_n=\frac1n$. For each $\delta_n$ there is a point $x_n$ with $d(x_n,p)\lt \delta_n=\frac1n$ and $d(f(x_n),fp)\ge \epsilon$. Thus $$\lim_{n\to \infty}x_n=p$$ but $f(x_n)$ does not converge to $fp$.

My main confusion is why the fact that $d(x,p)\lt \delta \implies d(fx,fp)\ge \epsilon$. Why is it that just because we decide to make $\delta$ really small then $d(fx,fp)$ is all of a sudden bigger than $\epsilon$?

A: $f$ is continuous on $M$ if and only if
$$
\forall p\in M\,\forall\varepsilon>0\,\exists\delta>0\,\forall x\in M:d_N(x,p)<\delta\Rightarrow d_M(f(x),f(p))<\varepsilon
$$
so $f$ is not continuous on $M$ if the contrapositive holds, that is
$$
\exists p\in M\,\exists\varepsilon>0\,\forall \delta>0\,\exists x\in M: d_N(x,p)<\delta\wedge d_M(f(x),f(p))\geq \varepsilon.
$$
Now assume $f$ is not continuous, and let $p\in M$ and $\varepsilon>0$ be the $p$ and $\varepsilon$ that we know exist from above. Then for any $\delta>0$ in particular for $\delta_n=\frac{1}{n}$ we know that there exists an $x\in M$ (call this $x_n$) such that
$$
d_N(x_n,p)<\delta \wedge d_M(f(x_n),f(p))\geq \varepsilon.
$$


text:
Q: JavaScript Taking in values from text box store into an array create new array to sort Hey guys i have some code here that dynamically creates text boxes when a button is clicked however, i would like to take in the text box values by using getElementByClassName, Retrieve all of the "listitem" text fields into an array.Then I code a loop to find the values of each of those elements (ex. what the user entered) and put those values in an array. Then sort that array. I will then display them later on...
Any help is appericated!
Javascript:
var $ = function (id)
{
  return document.getElementById(id);
}

var sortItem = function ()
{
  var myDisplayItems = "";
  myDisplayItems.innerHTML = "";

  var myClassTag = document.getElementsByClassName("listitem");
  for (index in myClassTag)
  {
    myDisplayItems += "
" + myClassTag[index];
  }
  //sort Array

 }
 var addItem = function()
 {
 var myToDoList = $("todolist");

  var myInput = document.createElement("input");
  myInput.setAttribute("type", "text");
  myInput.setAttribute("class", "listitem");
  myToDoList.appendChild(myInput);

  var myBr = document.createElement("br");
  myDoToList.appendChild(myBr);
 }

 window.onload = function ()
 {
   $("additem").onclick = addItem;
   $("sortitems").onclick = sortItem;
 }

HTML:

ToDo List - Date:

    <input type="button" id="additem" value="Add Item">

    <input type="button" id="sortitems" value="Sort and Display Items">

A: A bit modified original code
HTML

ToDo List - Date:

<input type="button" id="additem" value="Add Item" />

<input type="button" id="sortitems" value="Sort and Display Items" />

Javascript
var sortItem = function(){
    var myClassTag = document.getElementsByClassName("listitem");
    //convert nodelist ot array
    myClassTag     = Array.prototype.slice.call(myClassTag, 0);
    //let the sort function sort it for you
    myClassTag.sort(function(a, b){
        return a.value > b.value ? 1 : -1;
    });

    var myToDoList = document.getElementById('todolist');
    //update items position
    update(myToDoList, myClassTag);
}
//update items position, reappending will do the job
function update(target, listOfItems){
    for(var i = 0; i < listOfItems.length; i++){
        target.appendChild(listOfItems[i]);
    }
}

var addItem = function(){
     var myToDoList = document.getElementById('todolist');
     var myInput    = document.createElement("input");

     myInput.setAttribute("type", "text");
     myInput.setAttribute("class", "listitem");
     myToDoList.appendChild(myInput);

     var myBr = document.createElement("br");
     myToDoList.appendChild(myBr);
}

window.onload = function(){
     document.getElementById('additem').addEventListener('click', addItem);
     document.getElementById('sortitems').addEventListener('click', sortItem);
}

UPD
You can modify update function, to make it works as you wanted, ex:
for(var i = 0; i < listOfItems.length; i++){
    var child = document.createElement('span');
    child.innerText = listOfItems[i].value;
    target.appendChild(child);
}


text:
Q: Coding to print PDF files from file paths in query results I'm not new to Access, but am very new to VBA coding. Our management software is horrible, but it's the best that is available in the industry and I have created many many reports using Access, but have new problem now.
Attachments in the system are stored in one central location and then the file name stored in a SQL table. I have created queries to pull the full file path including the file name. Would it be possible to use some VBA coding to print all the existing PDFs in sequence from the paths returned in the query?
Thank you for any and all help!

A: Native VBA controls the collections of methods and attributes from Office.
An existent PDF is not the case (Access can create one or open, but not open and print).
To open a file with full path you will need to perform a select from table and perform a loop to shell open file, after that, sendkeys ^P.
But I strongly recomend to use another tool to do it, like Auto Hotkey or AutoIt.


text:
Q: How can I get a column with random samples, based on weights contained in a pandas dataframe? I have a dataframe with over a million rows. For every row I have 4 columns, containing the weights. How can I efficiently sample for every row with their corresponding weights? I would just like to choose a number 1,2,3 or 4 for every row using the weights of each row. Right now I have this for-loop but that will take way too long.
df = pd.DataFrame({
    '1': [0.155, 0.138, ...],
    '2': [0.473, 0.307, ...],
    '3': [0.291, 0.490, ...],
    '4': [0.080, 0.064, ...],
    'pick': ['']

})

for i in range(0, len(df)):
    df['pick'][i] = random.choices([1,2,3,4], weights=[df['1'][i], df['2'][i], df['3'][i], df['4'][i]], k=1)

A: Try with numpy, it is generally faster:
for i in range(len(df)):
    df['pick'][i]=np.random.choice([1,2,3,4], 1, p=list(df.iloc[i,:4]))

However, as your weights do not always add to 1, change some column (eg 4th) this way, before:
df['4']=1-(df['1']+df['2']+df['3'])

Output:
       1      2      3      4  pick
0  0.155  0.473  0.291  0.081     2
1  0.138  0.307  0.490  0.065     4

A: To add to the previous answer:
You could use the apply function in stead of iterating over all the rows (which is generally slower).
First define a (lambda) function, then apply the function to each row:
pick_function = lambda row_vals : np.random.choice([1,2,3,4], p=row_vals)

df['pick'] = df.apply(pick_function,axis=1) # axis=1 -> passes the row's values as the argument

As an aside, the lambda function does the same as this:
def pick_function(row_vals):
    rand_value = np.random.choice([1,2,3,4], p=row_vals)
    return rand_value


text:
Q: Flex: Popup Window - Get [ok] or [cancel] I've done a lot of C# programming with both Winforms and WPF. I'm working on a Flex/Air app now for cross platform support. But this is my first flex project, so I'm learning as I go.
I've got a window that I want to popup, that the user will fill out a form, then hit OK or CANCEL. I set it up the same way I would've in C#, but it doesn't work, and I can't really see a way to make it do what I want.
EDIT:
So I'm trying events now, the events just don't seem to be handled...
EDIT again:
Oh, It's because the popup manager seems to create a new instance of the Form object, rather than using the one I created already.
so in the showWindow method, I put in this code rather than the popup manager:
parent.addChild(this);

then I remove it when I close it. The only problem is, it doesn't disable the rest of the parent like the popup manager does. Any suggestions on that?
PARENT:
private function btnAdd_Clicked():void
{
        var form:Form = new Form();
        form.addEventListener(CloseEvent.CLOSE, onFormClosed, false, 0, true);

        recipeForm.showWindow(this);
}

private function onFormClosed(e:CloseEvent):void
{
    //none of these Alerts are ever shown. I also tried breakpoints in debug to try an follow the code, with no luck
    Alert.show("Closed");
    if(e.detail == Alert.OK)
    {
        Alert.show("OK");
    }
    else if(e.detail == Alert.CANCEL)
    {
        Alert.show("Cancel");
    }
}

CHILD:
private function btnCancel_Clicked():void
{
    okClicked = false;
    closeWindow();
}

public function closeWindow():void
{
    var e:CloseEvent = new CloseEvent(CloseEvent.CLOSE);
    e.detail = okClicked ? Alert.OK : Alert.CANCEL;
    dispatchEvent(e);
    PopUpManager.removePopUp(this);
}

public function showWindow(parent:WindowedApplication):void
{
    var window:IFlexDisplayObject = PopUpManager.createPopUp(parent, RecipeForm, true);
    PopUpManager.centerPopUp(window);
}

A: You can do this at least two different ways:
FIRST WAY: Using events
Let your Form class dispatch an event when either of the buttons is clicked. After Form is instantiated from the parent view, add an eventListener for the event(s) it's known to dispatch. When the Form dispatches the event, the eventListener will be invoked. You can even reuse Flex's CloseEvent and set the "detail" property to either Alert.OK or Alert.CANCEL before dispatching it.
In Form:
var e:CloseEvent = new CloseEvent(CloseEvent.CLOSE);
e.detail = okClicked ? Alert.OK : Alert.CANCEL;
dispatchEvent(e);

In parent:
var f:Form = new Form();
f.addEventListener(CloseEvent.CLOSE, onClose, false, 0, true);
...
private function onClose(e:CloseEvent):void
{
    if (e.detail == Alert.OK)
        // do something
    else if (e.detail == Alert.CANCEL)
        // do something else
}

SECOND WAY: Using callbacks
Add a public var of type "Function" to your Form class and supply a callback function from the parent. This does basically the same thing as #1 except with little less abstraction / indirection.
I would recommend #1 since the event model in Flex is pretty well-conceived and more flexible than the callback.

A: In Form:
var e:CloseEvent = new CloseEvent(CloseEvent.CLOSE);
e.detail = okClicked ? Alert.OK : Alert.CANCEL;
dispatchEvent(e);

In parent:
var f:Form = new Form();
f.addEventListener(CloseEvent.CLOSE, onClose, false, 0, true);
...
private function onClose(e:CloseEvent):void
{
    if (e.detail == Alert.OK)
        // do something
    else if (e.detail == Alert.CANCEL)
        // do something else
}

A: Not sure if this is still an open issue.  I ran into this very same problem and I think I figured out what is wrong.  At least I did for my problem.
I implemented things exactly as you did.  I also have the close attribute set to closeWindow (I'm using a TitleWindow for my dialog).
So when the window is closed via the X at the top, it will call closeWindow, also if you click on the Cancel button, it will also call closeWindow.
The problem for me was that clicking cancel, dispatches a CloseEvent which seems to be caught by a Listener which calls closeWindow again (possibly via the close attribute which probably creates its own internal listener).  I'm not sure if its an infinite loop but Flex does not like this.
My solution was to create two functions, one for the X close window to call and one for the Cancel button to dispatch a CloseEvent of its own.  This seemed to work for me.  Hope it helps you.


text:
Q: python - should I dispose a socket after sending udp data? I have a a method which listens to events, and everytime an event happens, it should send data to a socket (its udp, so I don't check if the data was received).
what I have in the event_handler is this:
    socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    socket.sendto(data, (IP, PORT))

It seems to me that I need to create a new socket everytime the event is called, because I don't know how much time will pass between two events, So having a global socket variable and send data on the event doesn't guarantee the socket is still up.
The thing is, because I create the socket everytime, should I dispose/close it after sending the data? what is the best way to dispose or close the socket after use?

A: As already explained by Rob, you do not necessarily need to create a new socket every time.
As per the documentation (https://docs.python.org/3/library/socket.html):

Sockets are automatically closed when they are garbage-collected, but
  it is recommended to close() them explicitly, or to use a with
  statement around them.

Hence, if you choose to create/close every time, you could do something like this:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as socket:
    socket.sendto(data, (IP, PORT))

A:
It seems to me that I need to create a new socket everytime the event is called,

No, it is OK to reuse the previous socket. Remember UDP sockekts are connectionless, so your concern about being disconnected doesn't apply.

The thing is, because I create the socket everytime, should I dispose/close it after sending the data?

Yes, if you are going to create a zillion sockets, please close them as you go. Otherwise you will run out of file descriptor slots, a limited resource in your process.


text:
Q: Rails ActiveAdmin Change Collection By Param I'm working on a project that has 'users' and 'reviews' activeadmin resources:  In the 'users' tab when you show a user I need to have a link to the specific user's reviews .
Currently there's a sidebar that links to the reviews
#(user.rb)
div do
  link_to "Reviews - #{user.reviews.count}", admin_reviews_path(q: {user_id_eq: user.id})
end

But this just leads to the reviews tab and doesn't show the specific user's reviews (the param seems to be meaningless).
Any advice on how I can change the index method in reviews tab to render a different collection by the param?
 #somehow make this action return all reviews that belong to a user if the param is there
 #(reviews.rb)

  index do
  selectable_column
  column :reviewer
  column :product
   ...

A: Try something like this:
div do
  Review.where(reviews_id: resource).collect do |review|
    link_to User.find_by(user_id_eq: user.id), admin_review_path(Person.find_by(user_id_eq: user.id))
  end
end


text:
Q: What is the reason for Windows IP address conflict? I get this message once in a while when using the Internet from a PC with Windows 7:
Windows has detected an IP address conflict.
Image of the error:

Thanks for any pointers.

A: Introduction:
If you have DHCP enabled on your router, then it assigns every device that makes a DHCP request a unique LAN IP address. If there's a device on your network that has DHCP disabled (static IP assigned to it) it will not request a DHCP IP. So what happens is this:
You have a device that initiates a DHCP request to your router, say it got the IP x.x.x.2, then afterwards you (or someone) have powered on or connected a device that that was otherwise powered off or disconnected; that recently-connected device has DHCP turned off and is statically assigned x.x.x.2 in its network settings, so now you have two devices with the same LAN IP address, and there's the conflict.
Solution:
Go to your control panel > Networks [something] > Network Connections > right-click your active network (wireless or local area) > properties > Networking tab > look for "Internet Protocol Version 4" choice on the white scrolling box > click it > Continue on one of two cases:
1- "Obtain IP address automatically" is chosen > SOLUTION: just reconnect to your network (disconnect and connect again)
2- "Use following IP address" is chosen > SOLUTION: either change the last number in the IP address field (first line) or simply chose the "Obtain IP address automatically"

A: One of the computers on your network has an ip address manually set (static) in the tcip/ip settings for one of the network cards.  It's simply a case of finding the culprit and setting it to dynamically get an ip from your router.  This assumes you're on a small network.  On a large network you could be in for a headache lol.

A: *

*go to Control Panel\Network and Internet\Network and Sharing Center.

*disconnect network.

*click icon of network rightmost.

*set network properties will appear.

*click merge or delete network locations.

*in dialog opened if possible delete all network locations.

*close dialog.

*List item

*now connect network.


text:
Q: How can I set a variable from a promise/observable in Angular after the subscription has completed? I am making one call to PokeApi to get a list of Pokemon back. I then need to make  a second call to return the sprite images for each Pokemon.
I am able to return the list of Pokemon correctly using rxjs Observables. When this returns the Pokemon name I make a second call to the Pokemon detail to return the sprites. However the second call does not complete in time to return the Pokemon Sprites.
public getListOfPokemon(page: number): Observable<Pokemon[]> {
let apiUrl = `${this.apiBaseUrl}/pokemon/?limit=1`;

if (page > 0) {
  let offset = page * 42;

  apiUrl = `${this.apiBaseUrl}/pokemon/?offset=${offset}&limit=42`;
}

return this._httpClient.get(apiUrl).pipe(
  map((resp: any) => {
    if (resp.results.length == 0) {
      this.lastPageOfResults = resp.next == null;
      this.router.navigate(['/404']);
    }

    this.lastPageOfResults = resp.next == null;

    let pkmnList = _.map(resp.results, (pkmn) => {
      let frontSprite: string;
      let shinySprite: string;

      new Promise(resolve => {
        resolve(this.getPokemonSprites(pkmn.name).subscribe(sprite => {
          return sprite;
        }))
      }).then((value) => {
        console.log(value);
      });

      let singlePkmn = new Pokemon(pkmn.name, frontSprite, shinySprite);

      return singlePkmn;
    });

    return pkmnList;
  })
)

}
frontSprite and shinySprite are not set when we return the new Pokemon.
EDIT
Here is the getPokemonSprites method for more clarification
private getPokemonSprites(name: string): Observable<any> {
let apiUrl = `${this.apiBaseUrl}/pokemon/${name}`;

return this._httpClient.get(apiUrl).pipe(
  map((pkmnDetail: any) => {
    console.log('hi');
    return pkmnDetail.sprites;
  })
)

}

A: It happens because promise.then() performs an async operation. Therefore when you return new Pokemon(), the sprite variables may not always be set. So you need to wait for the async operations to complete.
So, for the second mapping, instead of map you can use switchMap of rxjs to subscribe to an inner observable / chain observables. And in switchMap you can combine an array of observables with combineLatest to get responses of observables as an array.Like below:
getPokemons = () => {

    return this._httpClient.get(apiUrl).pipe(
      map((resp: any) => {
        if (resp.results.length == 0) {
          this.lastPageOfResults = resp.next == null;
          this.router.navigate(['/404']);
        }

        this.lastPageOfResults = resp.next == null;

        return resp.results;
      }),

      switchMap((pokemonList) => {

        const listOfObservables = [];

        _.map(pokemonList, (pkmn) => {
          let frontSprite: string;
          let shinySprite: string;

          const spriteObservable = this.getPokemonSprites(pkmn.name).pipe(
            map((sprite) => {
               let frontSprite = sprite.front_default;
               let shinySprite = sprite.front_shiny;
               return new Pokemon(pkmn.name, frontSprite, shinySprite);
            })
          )

          listOfObservables.push(spriteObservable);

        });

        return combineLatest(listOfObservables);
      })
    )
}

Then when you call the getPokemons (I named it to show how to use) method, it returns a chained observable. When you subscribe, it returns an array of Pokemon:
getPokemons.subscribe((pokemonList: Array<Pokemon>) => {
    // do the fancy stuff with pokemonList array
})

Hope this helps.

References:
combineLatest: https://www.learnrxjs.io/operators/combination/combinelatest.html
switchMap: https://www.learnrxjs.io/operators/transformation/switchmap.html


text:
Q: Return null by reference via __get() Quick specs:
PHP 5.3
error_reporting(-1) // the highest

I'm using the __get() by reference trick to magically access arbitrarily deep array elements in an object.
Quick example:
public function &__get($key){
    return isset($this->_data[$key])
        ? $this->_data[$key]
        : null;
}

This doesn't work as when the $key isn't set, it tries to return null by reference, which of course throws Only variable references should be returned by reference ... I tried modifying it as follows:
public function &__get($key){
    $null = null;
    return isset($this->_data[$key])
        ? $this->_data[$key]
        : $null;
}

Still doesn't work though, I'm assuming that setting $null to null essentially unset()s it.
What can I do? Thanks!

Just figured I'd promote this question, as it's somewhat relevant (PHP magic and references); __callStatic(), call_user_func_array(), references, and PHP 5.3.1. I've yet to find an answer ...besides modifying the PHP core.

A: I had this problem, but I ended up realizing that I shouldn't return null when the key wasn't found, but throw an exception (because I was accessing an unknown attribute after all).
But maybe that's not what you want to do, I just wanted to share that.

A: Why return null explicitly? If $key doesn't exist in $this->_data it's going to return NULL anyway?
I recommend using the following and adjust your logic on the other end. You're probably already checking for null now. You could change it to empty() or some other variant. Or use exceptions as suggested by Matthieu.
public function &__get($key){
    return $this->_data[$key];
}

A: This has nothing to do with null, but rather the ternary operator:
Rewriting it with an if/else won't throw the notice:
public function &__get($key)
{
    $null = null;
    if (isset($this->_data[$key])) {
        return $this->_data[$key];
    } else {
        return $null;
    }
}

Ternary operators cannot result in references. They can only return values.


text:
Q: JSON format log files for Spring BootP I am using Spring Boot with Curator (https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator). For monitoring I wan't to use the ELK stack. So I need to send my log files to LogStash, and the easiest way to do this is to use logback to preformat the logfile to json. By using the default logger - logstash-logback-encoder i can get the logfiles as json, but if the message in the log is also json, i do not get a big json file, i just get a field with the json and the message as a text field

A: The solution is use a different interface when sending logs.
You need to use the following import:
import net.logstash.logback.argument.StructuredArguments._
This adds the option to pass arguments to the log file interface. The arguments are then added as a json object and not as a string field. In the code you then use the log as follows:
val res = RequestFactory.getRestContent(s"http://localhost:$serverPort/metrics")
meticLogger.info("",raw("metric",res))
For further information see:
http://javaandroidandrest.blogspot.co.il/2015/11/spring-boot-curator-and-elk.html


text:
Q: Scanalyze install I am trying to install Scanalyze.
I downloaded the source code, and in the compilation instructions for Ubuntu, he has mentioned that for later versions of gcc (mine is 4+), there is a separate patched source, and the link for download is provided.
I used that link to download my source, and while I tried to compile using make I got the following error
    cc1plus: error: unrecognized command line option '-fwritable-strings'

Could you please help me how to overcome this and what changes I should make to install this efficiently? I am using Ubuntu 11.10.
This is the complete display after the make.
    make -j 1      scanalyze.debug BUILD=debug \
    --directory=OBJS/debug --makefile=../../Makefile -I../.. SKIPCVS=1
    make[1]: Entering directory `/home/siddarth/scanalyze-1.0.3/OBJS/debug'
    g++ -fno-for-scope -fpermissive -fwritable-strings -w -g -I../.. -
    I../../auxlibs/include/tnt -march=i686 -MMD -o plvMain.o -c ../../plvMain.cc
    cc1plus: error: unrecognized command line option '-fwritable-strings'
    make[1]: *** [plvMain.o] Error 1
    make[1]: Leaving directory `/home/siddarth/scanalyze-1.0.3/OBJS/debug'
    make: *** [debug] Error 2

A: Please remove the "-fwritable-strings" in file "Makedefs.Linux"
the next problem will be "pnt3.h" :) .. please keep asking
I'm try to build scanalyze too.


text:
Q: Got SecurityException when call getLastKnownLocation in JUnit test I have simple method for getting last known location from standard LocationManager:
fun getLastKnownLocation(context: Context): SimpleLocation {
        val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val criteria = Criteria()
        criteria.accuracy = Criteria.ACCURACY_FINE
        val location: android.location.Location?
            location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true))
        if (location == null) {
            return SimpleLocation.create(0.0, 0.0)
        }
        return SimpleLocation.create(location.latitude, location.longitude)
    }

And after that write simple test for it:
class LocationUtilTest {
    private val locationUtil: LocationUtil = spyk()
    private val context = InstrumentationRegistry.getInstrumentation().context

    @Test
    fun getLastKnownLocation() {
         val l = locationUtil.getLastKnownLocation(context)
         assertNotNull(l)
    }
    }

When I run this test, it throws SecurityException:
NOTE!
I replaced my application package name by app_package_name below in stackstace(my test package name is app_package_name.test)
java.lang.SecurityException: invalid package name: **app_package_name**.test
at android.os.Parcel.createException(Parcel.java:1950)
at android.os.Parcel.readException(Parcel.java:1918)
at android.os.Parcel.readException(Parcel.java:1868)
at android.location.ILocationManager$Stub$Proxy.getLastLocation(ILocationManager.java:866)
at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1434)
at com.ziuon.trasher.utils.LocationUtil.getLastKnownLocation(LocationUtil.kt:77)
at java.lang.reflect.Method.invoke(Native Method)
at io.mockk.proxy.android.advice.Advice$SuperMethodCall.call(Advice.kt:135)
at io.mockk.impl.instantiation.JvmMockFactoryHelper.handleOriginalCall(JvmMockFactoryHelper.kt:83)
at io.mockk.impl.instantiation.JvmMockFactoryHelper.access$handleOriginalCall(JvmMockFactoryHelper.kt:20)
at io.mockk.impl.instantiation.JvmMockFactoryHelper$mockHandler$1$invocation$$inlined$stdFunctions$lambda$1.invoke(JvmMockFactoryHelper.kt:28)
at io.mockk.impl.stub.MockKStub$handleInvocation$originalPlusToString$1.invoke(MockKStub.kt:227)
at io.mockk.impl.stub.SpyKStub.defaultAnswer(SpyKStub.kt:15)
at io.mockk.impl.stub.MockKStub.answer(MockKStub.kt:42)
at io.mockk.impl.recording.states.AnsweringState.call(AnsweringState.kt:16)
at io.mockk.impl.recording.CommonCallRecorder.call(CommonCallRecorder.kt:53)
at io.mockk.impl.stub.MockKStub.handleInvocation(MockKStub.kt:263)
at io.mockk.impl.instantiation.JvmMockFactoryHelper$mockHandler$1.invocation(JvmMockFactoryHelper.kt:25)
at io.mockk.proxy.android.advice.Advice$handle$1.call(Advice.kt:77)
at com.ziuon.trasher.utils.LocationUtil.getLastKnownLocation(Unknown Source:40)
at com.ziuon.trasher.utils.LocationUtilTest.getLastKnownLocation(LocationUtilTest.kt:55)
at java.lang.reflect.Method.invoke(Native Method)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:392)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2152)
Caused by: android.os.RemoteException: Remote stack trace:
at com.android.server.LocationManagerService.checkPackageName(LocationManagerService.java:2047)
at com.android.server.LocationManagerService.getLastLocation(LocationManagerService.java:2228)
at android.location.ILocationManager$Stub.onTransact(ILocationManager.java:159)
at android.os.Binder.execTransact(Binder.java:731)

All permissions and uses-feature are indicated in manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.location.gps"
              android:required="false"
/>

Is it throw because I use InstrumentationRegistry.getInstrumentation().context? Or why?
Thank you!
NOTE
I figured out this and this. It not helps me.

A: Theres something wrong with your package name or structure. When the JVM tries to load your class, it recognizes its package name as invalid and throw a SecurityException.
For reference see https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html


text:
Q: JdbcTestUtils and transaction context tests I have this problem that is causing me not to use JdbcTestUtils when running tests with a Transactional context.
If I wrap my test with @Transactional annotation and use a JdbcTemplate/DataSource it looks like the transactions used in the production code and by the JdbcTestUtils are not the same, so if I query the db in the then section the assertion fails.
This is a pseudo test:
@SpringBootTest
class TestClass {

  @Autowired
  private WebApplicationContext context;

  @BeforeEach
  void setup() {
    RestAssuredMockMvc.webAppContextSetup(context, springSecurity());
  }

  @Test
  @Transactional
  @DisplayName("test1")
  void test1(@Autowired DataSource dataSource) {
    //given
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    assertThat(countRowsInTable(jdbcTemplate, "some_tbl")).isEqualTo(1);

    //when
    // Execute app code here that adds a record to some_tbl

    //then
    assertThat(countRowsInTable(jdbcTemplate, "some_tbl")).isEqualTo(2); //<- Assertion fails.
  }

As a workaround, I need to use Spring contexted test repositories to retrieve data in the test, but that feels like a bad idea, and I need to maintain these repositories.
Below you will find a simple spring-boot project to show the issue.
https://github.com/Marek00Malik/JdbcTestUtils-sample

A: I cloned your project and could verify the failing test on my machine.
The reason for your test failure within the assertion of the test failingTestStoringNewObject:
assertThat(countRowsInTable(jdbcTemplate, "sample_table")).isEqualTo(1);

is that the EntityManger of JPA (the Spring Data JPA repositories use this under the hood) follows a write-behind strategy and keeps changes to JPA entities in its first-level cache (in-memory). Flushing the changes to the database does not always happen when your code executes .save() or any other database operation using the EntityManager.
The EntityManger tries to postpone flushing and therefore synchronizing its first-level cache with the database as late as possible. There is a lot to read about this and I can recommend Vlad Mihalcea's guide on this.
In your case, as you annotate your test with @Transactional, your changes will be rolled back after the test and therefore never committed to the database. You can see this in the log of the test:
2020-07-20 09:59:57.754  INFO 12648 --- [    Test worker] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@2b8ade2d testClass = SimpleObjectResourceHttpTest, testInstance = pl.code.house.example.jdbc.template.jdbctemplatetest.SimpleObjectResourceHttpTest@

For more visualization on this, you can also enable SQL logging for your tests with
spring:
  jpa:
    show-sql: on

You'll see that there is actually no INSERT statement executed, but a call to fetch the primary key of your entity.
If you temporarily use repository.saveAndFlush(newObj).toDto(); inside your SimpleObjectFacade, you'll see that it works.
I would use the SimpleObjectRepository for your integration test and use the .count() method of it. In this case, the underlying EntityManager recognizes a call to the same table and will flush its current changes before that and you'll get your expected result. Because if you use the JdbcTemplate there is no interaction with the EntityManager and therefore the EntityManager does not flush it changes as you go directly to the database with a SELECT COUNT(0) ....
UPDATE: If you don't want to make any adjustments and still use the JdbcTemplate in conjunction with Hibernate and the JpaRepositories, you could set the following flush mode for your tests only:
spring.jpa.properties.org.hibernate.flushMode=ALWAYS

This ensures to always flush the persistence context


text:
Q: UICollectionViewDataSource methods are not getting called when data-source is a separate class I created a UICollectionView inside a UITableViewCell and a separate data-source class DataSource for this collection-view.
DataSource conforms to the UICollectionViewDataSource protocol and I have also assigned the dataSource of an instance of DataSource in my collection-view container class.
But none of the data-source methods in DataSource are getting called.
It was working fine before I created a separate class for UICollectionView data-source.

A: Resolved!
It was a stupid mistake. I hadn't created the instance variable to retain the instance of DataSource in my collection-view container class, so it was getting released as soon as the method where it was getting alloc-inited finished.


text:
Q: Does gremlin support the bulkloader with neptune? Neptune's newest update includes bulkload with a CSV file. Does the js lv of Gremlin support this?

A: I am not sure I fully understand your question but Amazon Neptune has always had a Bulk Loader that can load vertices and edges that are stored in CSV files. Once loaded you will have a property graph that any of the Gremlin GLV clients can work with. The documentation is located here:
https://docs.aws.amazon.com/neptune/latest/userguide/bulk-load.html
EDITED to add that the bulk loader is controlled by an HTTP/REST endpoint so you could invoke it from within you code but not using the g.io() step currently.


text:
Q: Firebase Database Child Values Showing null When i upload my Post object with an array of image URLs to Firebase Database, some of the child values are showing empty. I have also tried uploading the Post Object without array that contains image urls and everything worked just fine. I think the array's causing child values to show empty. But i couldn't find a way to solve this problem. Any idea on this issue?
Database nodes
JSON file

{
  "post_images" : {
    "-MKRuWXlc_C9_XTlHbpC" : {
      "firstItem" : "https://firebasestorage.googleapis.com/v0/b/sattimgitti-c6e5d.appspot.com/o/posts%2Fusers%2FF81LLbqVlpY75m1puEThf5yTXAE2%2F-MKRuWXlc_C9_XTlHbpC%2Fpost_image%2FImagesimage%3A15387?alt=media&token=5ea88271-524f-4cff-b900-c2555b7bcffd",
      "postImages" : [ "https://firebasestorage.googleapis.com/v0/b/sattimgitti-c6e5d.appspot.com/o/posts%2Fusers%2FF81LLbqVlpY75m1puEThf5yTXAE2%2F-MKRuWXlc_C9_XTlHbpC%2Fpost_image%2FImagesimage%3A15387?alt=media&token=5ea88271-524f-4cff-b900-c2555b7bcffd", "https://firebasestorage.googleapis.com/v0/b/sattimgitti-c6e5d.appspot.com/o/posts%2Fusers%2FF81LLbqVlpY75m1puEThf5yTXAE2%2F-MKRuWXlc_C9_XTlHbpC%2Fpost_image%2FImagesimage%3A15389?alt=media&token=b831db94-4633-44f5-aae7-89fa800e6f8b", "https://firebasestorage.googleapis.com/v0/b/sattimgitti-c6e5d.appspot.com/o/posts%2Fusers%2FF81LLbqVlpY75m1puEThf5yTXAE2%2F-MKRuWXlc_C9_XTlHbpC%2Fpost_image%2FImagesimage%3A15382?alt=media&token=4c8ea5f3-2bb2-4830-a245-7141154160cf" ]
    },
    "-MKRw2rzTdpsn1SZSyDp" : {
      "firstItem" : "https://firebasestorage.googleapis.com/v0/b/sattimgitti-c6e5d.appspot.com/o/posts%2Fusers%2FF81LLbqVlpY75m1puEThf5yTXAE2%2F-MKRw2rzTdpsn1SZSyDp%2Fpost_image%2FImagesimage%3A15355?alt=media&token=df288b1d-724c-486b-b037-7fc93cdd05a1",
      "postImages" : [ "https://firebasestorage.googleapis.com/v0/b/sattimgitti-c6e5d.appspot.com/o/posts%2Fusers%2FF81LLbqVlpY75m1puEThf5yTXAE2%2F-MKRw2rzTdpsn1SZSyDp%2Fpost_image%2FImagesimage%3A15355?alt=media&token=df288b1d-724c-486b-b037-7fc93cdd05a1", "https://firebasestorage.googleapis.com/v0/b/sattimgitti-c6e5d.appspot.com/o/posts%2Fusers%2FF81LLbqVlpY75m1puEThf5yTXAE2%2F-MKRw2rzTdpsn1SZSyDp%2Fpost_image%2FImagesimage%3A15354?alt=media&token=c2059e03-62f5-464d-9708-79f95c43bff1", "https://firebasestorage.googleapis.com/v0/b/sattimgitti-c6e5d.appspot.com/o/posts%2Fusers%2FF81LLbqVlpY75m1puEThf5yTXAE2%2F-MKRw2rzTdpsn1SZSyDp%2Fpost_image%2FImagesimage%3A15257?alt=media&token=d1eec3a8-6517-455c-8140-14fe731a6764", "https://firebasestorage.googleapis.com/v0/b/sattimgitti-c6e5d.appspot.com/o/posts%2Fusers%2FF81LLbqVlpY75m1puEThf5yTXAE2%2F-MKRw2rzTdpsn1SZSyDp%2Fpost_image%2FImagesimage%3A15244?alt=media&token=18496985-1991-44a7-88b7-08125cf788ee" ]
    },
    "posts" : {
      "-MKS3CIuGKMPwoPdqeev" : {
        "city" : "",
        "description" : "",
        "image" : "https://firebasestorage.googleapis.com/v0/b/sattimgitti-c6e5d.appspot.com/o/posts%2Fusers%2FF81LLbqVlpY75m1puEThf5yTXAE2%2F-MKS3CIuGKMPwoPdqeev%2Fpost_image%2FImagesimage%3A15384?alt=media&token=5a7ab620-2bfc-4dd8-9a18-f395917b72bb",
        "post_id" : "-MKS3CIuGKMPwoPdqeev",
        "price" : "",
        "title" : "",
        "user_id" : "F81LLbqVlpY75m1puEThf5yTXAE2"
      },
      "-MKSClUrxJKFTBP_FhvR" : {
        "city" : "",
        "description" : "",
        "postImages" : [ "https://firebasestorage.googleapis.com/v0/b/sattimgitti-c6e5d.appspot.com/o/posts%2Fusers%2FF81LLbqVlpY75m1puEThf5yTXAE2%2F-MKSClUrxJKFTBP_FhvR%2Fpost_image%2FImagesimage%3A15387?alt=media&token=9e410ab2-740a-48a1-9b51-51fb2011aa53", "https://firebasestorage.googleapis.com/v0/b/sattimgitti-c6e5d.appspot.com/o/posts%2Fusers%2FF81LLbqVlpY75m1puEThf5yTXAE2%2F-MKSClUrxJKFTBP_FhvR%2Fpost_image%2FImagesimage%3A15382?alt=media&token=ba1302e0-9bc6-4c06-9352-81ec995a5246", "https://firebasestorage.googleapis.com/v0/b/sattimgitti-c6e5d.appspot.com/o/posts%2Fusers%2FF81LLbqVlpY75m1puEThf5yTXAE2%2F-MKSClUrxJKFTBP_FhvR%2Fpost_image%2FImagesimage%3A15383?alt=media&token=cc9c664c-a2dd-4e0d-9d1d-207252742e83", "https://firebasestorage.googleapis.com/v0/b/sattimgitti-c6e5d.appspot.com/o/posts%2Fusers%2FF81LLbqVlpY75m1puEThf5yTXAE2%2F-MKSClUrxJKFTBP_FhvR%2Fpost_image%2FImagesimage%3A15384?alt=media&token=90c4db1c-66d7-4aa4-932f-ab585d0a93ba" ],
        "post_id" : "-MKSClUrxJKFTBP_FhvR",
        "price" : "",
        "title" : "",
        "user_id" : "F81LLbqVlpY75m1puEThf5yTXAE2"
      }
    }
}

Post Object

public class Post  {
    private String post_id;
    private String user_id;
    private String  image;
    private String title;
    private String description;
    private String price;
    private String city;
    private ArrayList<String> postImages;

    public Post(String post_id, String user_id, String  image, String title, String description, String price, String city, ArrayList<String> postImages) {
        this.post_id = post_id;
        this.user_id = user_id;
        this.image = image;
        this.title = title;
        this.description = description;
        this.price = price;
        this.city = city;
        this.postImages = postImages;
    }

    public String getPost_id() {
        return post_id;
    }

    public void setPost_id(String post_id) {
        this.post_id = post_id;
    }

    public String getUser_id() {
        return user_id;
    }

    public void setUser_id(String user_id) {
        this.user_id = user_id;
    }

    public String  getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public ArrayList<String> getPostImages(){
        return postImages;
    }

    public void setUrlArray(ArrayList<String> postImages){
        this.postImages = postImages;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Post(){

    }

    @Override
    public String toString() {
        return "Post{" +
                "post_id='" + post_id + '\'' +
                ", user_id='" + user_id + '\'' +
                ", image='" + image + '\'' +
                ", title='" + title + '\'' +
                ", description='" + description + '\'' +
                ", price='" + price + '\'' +
                ", urlArray='" + postImages + '\'' +
                ", city='" + city + '\'' +
                '}';
    }

}

PostActivity.java (this method contains all the relevant pieces)

private void uploadPostwithImages(){

        postId = FirebaseDatabase.getInstance().getReference().push().getKey();
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("post_images");
        final StorageReference storageReference = FirebaseStorage.getInstance().getReference()
                .child("posts/users/" + FirebaseAuth.getInstance().getCurrentUser().getUid() +
                        "/" + postId + "/post_image");

        int upload_count = 0;
        urlStrings = new ArrayList<>();
        for (upload_count = 0; upload_count < mArrayUri.size(); upload_count++) {

            IndividualImage = mArrayUri.get(upload_count);
            final StorageReference ImageName = storageReference.child("Images" + IndividualImage.getLastPathSegment());

            ImageName.putFile(IndividualImage).addOnSuccessListener(
                    new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                            Task<Uri> firebaseUri = taskSnapshot.getMetadata().getReference().getDownloadUrl();

                            firebaseUri.addOnSuccessListener(
                                    new OnSuccessListener<Uri>() {
                                        @Override
                                        public void onSuccess(Uri uri) {

                                            urlStrings.add(String.valueOf(uri));

                                            Post post = new Post();

                                            if (urlStrings.size() == mArrayUri.size()){
                                                //storeLink(urlStrings);
                                                post.setUrlArray(urlStrings);
                                            }

                                            post.setCity(inputCity.getText().toString());
                                            post.setDescription(inputDesc.getText().toString());
                                            post.setPost_id(postId);
                                            post.setPrice(inputPrice.getText().toString());
                                            post.setTitle(inputTitle.getText().toString());
                                            post.setUser_id(FirebaseAuth.getInstance().getCurrentUser().getUid());
                                            reference.child(getString(R.string.node_posts))
                                                    .child(postId)
                                                    .setValue(post);

                                        }
                                    }
                            );
                        }
                    }
            );
        }
    }


text:
Q: java junit testing in a loop I have a JUnit test that I would like to run from a main method.  I would like to retrieve multiple records from a database (within the main method) and pass each record into the JUnit, using a data object, so that each record can be tested. Can I pass a data object into the run method of JUnit. If not what is the best way to accomplish this.  There are so many different scenarios that I would like to use actual data from the database. There could be as many as 5000 or more records to test.
Thanks
Doug

A: You want to use JUnit's Parameterized Tests. There's really no way to run a main method in a JUnit test case.
On top of the docs, here's a blog post which explains it a little better: http://ourcraft.wordpress.com/2008/08/27/writing-a-parameterized-junit-test/

A: Surely you are looking for Parameterized test case. You can do it easily by using JUnit instead of using main() method.
You need Parameterized to run your test.
It will run your test with different parameters by passing parameters via constructor.
Here is an easy article how to do that. You can also try the example in the documentation also, to understand how it works.

A: I think that testing your main method is more along the lines of an integration test or a functional test. The same can be said for testing your database data.  If you really want a unit test the firs step would be to refactor your main method using Extract Method to pull out the business logic you want to test.
Doing this gives you a few benefits.  First can test your code in isolation (which is one of the more important properties of a good unit test).  If you refactor out the business logic you'll know that you are only testing that code and that no other code is affecting your test.  Second by having an isolated method you'll be able to easily mock the test data you are looking at by passing in different parameters to the method and make your assertions based on the known mock data.


text:
Q: UDP over TCP, windows platforms I have read: UDP traffic through SSH tunnel a number of times, but I don't think it directly answers this question:
I am looking to forward UDP traffic (udp Port 8004): https://en.wikipedia.org/wiki/Common_Image_Generator_Interface
From a windows 10 computer (server in a private cloud) to windows 10 computer (client).
My prefered solution would be an existing program that I could run on both the client and the cloud computer.
The issue is that UDP traffic the private cloud is limited to RDP and TCP connections. UDP data is not forwarded.
Can I tunnel the UDP traffic over a TCP connection, and then have the data appear as local UDP packets on the client.
I am not sure if either of the below solutions will work, or if they are for a different problem.

*

*https://securesocketfunneling.github.io/ssf/#home

*https://github.com/BarbaTunnelCoder/BarbaTunnel/
Getting our I.T. department to approve a true VPN between the private cloud and client computers might take years :-(


text:
Q: Why is NA greater than an integer? I have looked at an old question that discusses how to find the psum. I used the data in that question to gain a better understanding of the pmin and pmax functions.
The data:
x = c(1,3,NA,5)
y = c(2,NA,4,1)

Now, running pmax(x,y) returns:
2 NA NA  5

while I expected 3 and 4 instead of NAs.
Running pmin(x,y) on the other hand returns:
1 NA NA  1

The question is: Why is NA considered greater than 3 and 4 in pmax?


text:
Q: Selecting from a subquery instead of an entity with NHibernate Is this possible using QueryOver or CreateCriteria:
SELECT FooName, SUM(FooAmount)
FROM (
     SELECT
         (SELECT Name FROM Foo
         WHERE Foo.BarId = Bar.Id) as FooName,
         FooAmount
     FROM Bar
) as inner_query
GROUP BY FooName

Please note that this query has been constructed for demonstration purposes. I am not interested in adding relationships between entities, rewriting the query itself etc. Also, the app is setup to take advantage of query construction using CreateCriteria - it is not possible to change it to HQL.
It is possible to construct the inner query in NHibernate as a detatched criteria. The problem is getting NHibernate to select from the inner query, instead of over an entity. Does anyone know if this is possible?

A: NHibernate - as typical ORM tool - provides query/domain manipulation language(es) (HQL, QueryOver, Criteria...) on top of object model. FROM clause is always defined by the Object mapping.
The options you have

*

*introduce new readonly object mapped to view (or subselect instead of table)

*use session.CreateSQLQuery() to get full access to underlying structured query language (SQL)


text:
Q: Getting KeyError in pandas.hashtable I have a folder on my desktop with a bunch of 5 minutes periodic timeseries data with datetime in txt format such as ;
...
Apr 29 12:51 file_2020-04-29_12:45:00.txt
Apr 29 12:55 file_2020-04-29_12:50:00.txt
Apr 29 13:01 file_2020-04-29_12:55:00.txt
Apr 29 13:06 file_2020-04-29_13:00:00.txt
Apr 29 13:11 file_2020-04-29_13:05:00.txt
Apr 29 13:16 file_2020-04-29_13:10:00.txt
Apr 29 13:21 file_2020-04-29_13:15:00.txt
Apr 29 13:26 file_2020-04-29_13:20:00.txt
Apr 29 13:31 file_2020-04-29_13:25:00.txt
Apr 29 13:36 file_2020-04-29_13:30:00.txt
Apr 29 13:41 file_2020-04-29_13:35:00.txt
Apr 29 13:46 file_2020-04-29_13:40:00.txt
Apr 29 13:51 file_2020-04-29_13:45:00.txt
Apr 29 13:56 file_2020-04-29_13:50:00.txt

Content of each file like ;
[neg@nik:/cnp-cnx]# head file_2020-04-29_13:55:00.txt
2020-04-29 13:55:00,BSKHDEA1_SPS/Diameter Link:Link name=bskhdea1_bskhdra1_lnk01,True,1753359343,2374.0,1753359344,2375.0
2020-04-29 13:55:00,BSKHDEA1_SPS/Diameter Link:Link name=bskhdea1_bskhdra1_lnk02,True,1753359343,2371.0,1753359344,2370.0
2020-04-29 13:55:00,BSKHDEA1_SPS/Diameter Link:Link name=bskhdea1_bskhdra1_lnk03,True,1753359343,2374.0,1753359344,2376.0
2020-04-29 13:55:00,BSKHDEA1_SPS/Diameter Link:Link name=bskhdea1_bvhdra01_lnk01,True,1753359343,2377.0,1753359344,2377.0
2020-04-29 13:55:00,BSKHDEA1_SPS/Diameter Link:Link name=bskhdea1_bvhdra01_lnk02,True,1753359343,2369.0,1753359344,2364.0
2020-04-29 13:55:00,BSKHDEA1_SPS/Diameter Link:Link name=bskhdea1_bvhdra01_lnk03,True,1753359343,2362.0,1753359344,2361.0
2020-04-29 13:55:00,BSKHDEA1_SPS/Diameter Link:Link name=bskhdea1_mbhdra01_lnk01,True,1753359343,1629.0,1753359344,1631.0
2020-04-29 13:55:00,BSKHDEA1_SPS/Diameter Link:Link name=bskhdea1_mbhdra01_lnk02,True,1753359343,1634.0,1753359344,1632.0
2020-04-29 13:55:00,BSKHDEA1_SPS/Diameter Link:Link name=bskhdea1_mbhdra01_lnk03,True,1753359343,1633.0,1753359344,1632.0
2020-04-29 13:55:00,BSKHDEA1_SPS/Diameter Link:Link name=bskhdea1_ipx_ibasis1_asd_lnk02,True,1753359343,3871.0,1753359344,3869.0

I am trying to put all the file contents into mysql database with this method ;
import mysql.connector
import glob
import os
import pandas as pd

list_of_files = glob.glob('/cnp-cnx*.txt')
latest_file = max(list_of_files, key=os.path.getctime)

cnx = mysql.connector.connect(user='user', password='password',host='10.10.1.10',database='database')
cur = cnx.cursor(buffered=True)

for i in list_of_files:
  data = pd.read_csv(i, header=None)
  cur.execute("""INSERT INTO table1 (DATETIME, NODE, COND, COUNTER1, C1753359343, COUNTER2, C1753359344) VALUES ( %s,%s,%s,%s,'%s',%s,'%s' )""", ( data[0].values, data[1].values, data[2].values,data[3].values, data[4].values, data[5].values,data[6].values, data[7].values ) )

And i receive the error below, could you please tell me where is my mistake ?
>>> import glob
>>> import os
>>> import pandas as pd
>>> import mysql.connector
>>> list_of_files = glob.glob('/cnp-cnx*.txt')
>>> latest_file = max(list_of_files, key=os.path.getctime)
>>>
>>> cnx = mysql.connector.connect(user='user', password='password',host='10.10.1.10',database='database')
>>> cur = cnx.cursor(buffered=True)
>>>
>>> for i in list_of_files:
...   data = pd.read_csv(i, header=None)
...   cur.execute("""INSERT INTO table1 (DATETIME, NODE, COND, COUNTER1, C1753359343, COUNTER2, C1753359344) VALUES ( %s,%s,%s,%s,'%s',%s,'%s' )""", ( data[0].values, data[1].values, data[2].values,data[3].values, data[4].values, data[5].values,data[6].values, data[7].values ) )
...
Traceback (most recent call last):
  File "/opt/rh/rh-python36/root/usr/lib64/python3.6/site-packages/pandas/core/indexes/base.py", line 2657, in get_loc
    return self._engine.get_loc(key)
  File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 987, in pandas._libs.hashtable.Int64HashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 993, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 7

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "/opt/rh/rh-python36/root/usr/lib64/python3.6/site-packages/pandas/core/frame.py", line 2927, in __getitem__
    indexer = self.columns.get_loc(key)
  File "/opt/rh/rh-python36/root/usr/lib64/python3.6/site-packages/pandas/core/indexes/base.py", line 2659, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 987, in pandas._libs.hashtable.Int64HashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 993, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 7
>>>
>>>


text:
Q: Dailyrollingfileappender not creating backup of more than 1 day My log config is as follows,but i can see only 1 backup file being created and all the other backup just goes off / deleted.
log4j.appender.application=org.apache.log4j.DailyRollingFileAppender
log4j.appender.application.File=${log.root.path}/test.log
log4j.appender.application.DatePattern='.'yyyy-MM-dd
log4j.appender.application.layout=org.apache.log4j.PatternLayout
log4j.appender.application.layout.ConversionPattern=%d{dd MMM
HH\:mm\:ss\:SSS} [%t] %-5p [%c\:%M\:%L]  srcIp=%X{srcIp} -
remoteHost=%X{remoteHost} -port=%X{port} - activityType=%X{activitytype} -
activityStatus=%X{activitystatus} -applicationUser=%X{applicationUser} -
APITXNID=%X{apiTxnId} -CustomerRefNum=%X{CustomerRefNum} -%m%n%n

A: Your configuration looks fine, there are several thing you could try to do:

*

*Try replace log4j.appender.application.DatePattern from '.'yyyy-MM-dd to '.'yyyy-MM-dd-HH-mm and see if files would be created every minute. If it works, chances are that some external cleanup script deletes old logs.

*Add -Dlog4jdebug.true to VM options to verify what is effective log4j conf file is used.

*Also consider using  API Documentation warning

DailyRollingFileAppender has been observed to exhibit synchronization issues and data loss. The log4j extras companion includes alternatives which should be considered for new deployments and which are discussed in the documentation for org.apache.log4j.rolling.RollingFileAppender.

You can have the same effect as your config above, by replacing log4j dependency with apache-log4j-extras, which implements log4j 1.2.x, but has extra features, such as org.apache.log4j.rolling.RollingFileAppender with TimeBasedRollingPolicy
Then replace in your log4j.properties
log4j.appender.application=org.apache.log4j.DailyRollingFileAppender
log4j.appender.application.File=${log.root.path}/test.log
log4j.appender.application.DatePattern='.'yyyy-MM-dd

with
log4j.appender.application=org.apache.log4j.rolling.RollingFileAppender
log4j.appender.application.rollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.application.rollingPolicy.FileNamePattern=${log.root.path}/test.log.%d{yyyy-MM-dd-HH-mm}
log4j.appender.application.File=${log.root.path}/test.log


text:
Q: Grant all privs of a user to another user in Oracle I have a user named A having some privileges. How can I grant all privileges which A is having and grant to user B?
Thanks in advance

A: Get all privileges from user A
 SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT','A') FROM DUAL;

 SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT','A') FROM DUAL;

 SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT','A') FROM DUAL;

Change the DDL commands with the user 'B' and execute.


text:
Q: How to display the recent added data to the top of the recycler view I'm creating an app where i am storing data to firebase and retriving it to my reclycler view and but   issue is, i want to display the most recent added data to the top of the recycler view. I am trying to get the latest data and I had done all possibly Solution still I am not getting.
please see the following code....
here is my Mainclass:
public class ShowDetails extends AppCompatActivity {

ProgressDialog progressDialog;
List<DataClass> list = new ArrayList<>();
RecyclerView recyclerView;
RecyclerView.Adapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_details);

    recyclerView = findViewById(R.id.erecyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(ShowDetails.this));
    progressDialog = new ProgressDialog(ShowDetails.this);
    progressDialog.setMessage("Loading Data from Firebase Database");
    progressDialog.show();

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setApplicationId("1:102738125513:android:3042292623f0448c") // Required for Analytics.
            .setApiKey("AIzaSyAZbWBpPzjAkrg23riK9kwk2T0tDf47dko") // Required for Auth.
            .setDatabaseUrl("https://citycare-fed31.firebaseio.com/") // Required for RTDB.
            .build();
    FirebaseApp.initializeApp(this);
            // Retrieve my other app.
            FirebaseApp app = FirebaseApp.getInstance("[DEFAULT]");
    // Get the database for the other app.
    FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(app);
    DatabaseReference data = secondaryDatabase.getInstance().getReference("Electricity");
    data.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot ds : dataSnapshot.getChildren()) {

                for (DataSnapshot dSnapshot : ds.getChildren()) {

                    DataClass DataClass = dSnapshot.getValue(DataClass.class);

                    Log.d("Show", DataClass.getEname() == null ? "" : DataClass.getEname());
                    list.add(DataClass);

                }
                adapter = new ShowDetails.DataAdapter(ShowDetails.this, list);
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                progressDialog.dismiss();
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            progressDialog.dismiss();
        }
    });

}

and this is my Adapter class:
 private class DataAdapter extends RecyclerView.Adapter<ShowDetails.DataAdapter.ViewHolder>  {

    Context context;
    List<DataClass> listData;

    public DataAdapter(Context context, List<DataClass> list) {

        this.context = context;
        this.listData = list;
    }

    @Override
    public ShowDetails.DataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_items, parent, false);
        ShowDetails.DataAdapter.ViewHolder viewHolder = new ShowDetails.DataAdapter.ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ShowDetails.DataAdapter.ViewHolder holder, int position) {

        final DataClass AllDetails = listData.get(position);
        holder.NameTextView.setText(AllDetails.getEname());
        holder.EmailTextView.setText(AllDetails.getEemail());
        holder.DateTextView.setText(AllDetails.getEdate());
        holder.LocationTextView.setText(AllDetails.getElocation());
        holder.TypeTextView.setText(AllDetails.getEtype());
        Picasso.with(context).load(AllDetails.getImgurl()).resize(120, 60).into(holder.ImageTextView);

        holder.ImageTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(ShowDetails.this, ShowImage.class);
                i.putExtra("img", AllDetails.getImgurl());
                startActivity(i);
            }
        });
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(ShowDetails.this, Email_Activity.class);
                i.putExtra("txt", AllDetails.getEemail());
                startActivity(i);
            }
        });
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        public TextView NameTextView;
        public TextView EmailTextView;
        public TextView DateTextView;
        public TextView LocationTextView;
        public TextView TypeTextView;
        public ImageView ImageTextView;
        public ViewHolder(View itemView) {

            super(itemView);
            NameTextView = itemView.findViewById(R.id.ShowNameTextView);
            EmailTextView = itemView.findViewById(R.id.ShowEmailTextView);
            DateTextView = itemView.findViewById(R.id.ShowDateTextView);
            LocationTextView = itemView.findViewById(R.id.ShowLocationTextView);
            TypeTextView = itemView.findViewById(R.id.ShowTypeTextView);
            ImageTextView = itemView.findViewById(R.id.ShowImageView);
        }
    }
}

here is my database
firebase data structure
here is my API response after removing extra for loop
API response
please help me out i am new to programming

A: You can add your data to list's first iterator in loop,
and move setadapter out of loops:
for (DataSnapshot ds : dataSnapshot.getChildren()) {
   for (DataSnapshot dSnapshot : ds.getChildren()) {
      DataClass DataClass = dSnapshot.getValue(DataClass.class);
      list.add(0, DataClass);
   }
}
adapter = new ShowDetails.DataAdapter(ShowDetails.this, list);
recyclerView.setAdapter(adapter);
progressDialog.dismiss();

A: NOTE: If your recycler view is displaying the data in reverse order..you can use the following method.
this will display in order if above condition meets
in your layout manager of your recycler view
LinearLayoutManager lm = new LinearLayoutManager(mActivity, RecyclerView.VERTICAL, true);
recyclerView.setLayoutManager(lm);

this should solve your problem


text:
Q: Disable Ordering Columns after initialization (init complete) in datatables I would disable order possibility to user after datatables is draw.
I have a datatable, and I would order a data and remove possibility, for an user, to order data manually.
How can I do it?
I used below code:
table = $('#tbl-1').DataTable({
            "info": false,
            "searching": true,
            "paging": false,
            "iDisplayLength": 25,
            "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "Tutti"]],
            "language": {"url": "include/it_IT.txt"},
            "order": [[1,"desc"]],
            //"ordering": false,
            //"orderFixed": {"pre": [ 1, "desc" ]},
             "fnInitComplete": function(oSettings, json) {
                    //alert( 'DataTables has finished its initialisation.' );
                    this.fnFilter("<?php echo $_POST['search'];?>");
                  },
            }).on('init.dt', function (e, settings, data) {
                wrappa(); //after custom function
            });

A: old post but still not handled by dt api. Removing the events won't work if wanting to temporarily disable sorting. Instead use jquery to add and later remove a class onto each th, and in this class specify "pointer-events: none".

A: Due to the fact that the API does not have a way to do this, I would suggest the following approach
Declare your table at first
var table = $('#myTable').DataTable();

Re-Initialize your dataTable with to disable ordering
//Destroy your table before
table.destroy();
$('#myTable').dataTable( {
  "ordering": false
} );

reference:
https://datatables.net/reference/option/ordering


text:
Q: JS functions in GWT how use this simple js functions in GWT? (picture animation script for example)
<script type="text/javascript">
var cSpeed=4;
var cWidth=64;
var cHeight=64;
var cTotalFrames=8;
var cFrameWidth=64;
var cImageSrc='images/sprites.gif';

var cImageTimeout=false;
var cIndex=0;
var cXpos=0;
var cPreloaderTimeout=false;
var SECONDS_BETWEEN_FRAMES=0;

function startAnimation(){

    document.getElementById('loaderImage').style.backgroundImage='url('+cImageSrc+')';
    document.getElementById('loaderImage').style.width=cWidth+'px';
    document.getElementById('loaderImage').style.height=cHeight+'px';

    //FPS = Math.round(100/(maxSpeed+2-speed));
    FPS = Math.round(100/cSpeed);
    SECONDS_BETWEEN_FRAMES = 1 / FPS;

    cPreloaderTimeout=setTimeout('continueAnimation()', SECONDS_BETWEEN_FRAMES/1000);

}

function continueAnimation(){

    cXpos += cFrameWidth;
    //increase the index so we know which frame of our animation we are currently on
    cIndex += 1;

    //if our cIndex is higher than our total number of frames, we're at the end and should restart
    if (cIndex >= cTotalFrames) {
        cXpos =0;
        cIndex=0;
    }

    if(document.getElementById('loaderImage'))
        document.getElementById('loaderImage').style.backgroundPosition=(-cXpos)+'px 0';

    cPreloaderTimeout=setTimeout('continueAnimation()', SECONDS_BETWEEN_FRAMES*1000);
}

function stopAnimation(){//stops animation
    clearTimeout(cPreloaderTimeout);
    cPreloaderTimeout=false;
}

function imageLoader(s, fun)//Pre-loads the sprites image
{
    clearTimeout(cImageTimeout);
    cImageTimeout=0;
    genImage = new Image();
    genImage.onload=function (){cImageTimeout=setTimeout(fun, 0)};
    genImage.onerror=new Function('alert(\'Could not load the image\')');
    genImage.src=s;
}

//The following code starts the animation
new imageLoader(cImageSrc, 'startAnimation()');

tried wrapping
    public static native void anim()
/*-{
   js here
}-*/;

but Uncaught ReferenceError: startAnimation is not defined
i've seen
http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html
but didn't find examples for js functions

A: You need to add $wnd to access JavaScript which is included directly in your HTML host page.
$wnd.startAnimation();

A: You can use JSNI:
Method 1: if you ALWAYS call imageLoader with fun = 'startAnimation()', i mean, you always use imageLoader this way: imageLoader(s, 'startAnimation()');
class YourMethods
{
    public static native void imageLoader(String s) /*-{
    imageLoader(s, 'startAnimation()');
    }-*/;
}

You can call this method like this:
YourMethods::imageLoader(s);

Method 2: if you fun parameter change (is not always 'startAnimation()'), BUT ALWAYS IS A TYPE STRING
class YourMethods
{
    public static native void imageLoader(String s, String fun) /*-{
    imageLoader(s, fun);
    }-*/;
}

In this case: you define second parameter like "javascript name of function", and call it this way:
YourMethods::imageLoader(s, "startAnimation()");

And GWT understand fun parameter like name of javascript function, and type string
Method 3: convert ALL your javascript code to GWT


text:
Q: Javadoc reference param from another method I don't want to write redundant javadoc comments. As you can see, @param x is in a way redundant. Is there a javadoc markup to set a reference from @param x in class B to @param x in class A or am I allowed to just leave it out?
/**
 * Class A constructor
 *
 * @param x  position on x-axis
 */
public A(final int x) {
    this.x = x;
}

/**
 * Class B constructor
 *
 * @param x  position on x-axis
 * @param y  position on y-axis
 */
public B(final int x, final int y) {
    super(x);
    this.y = y
}

A: You can't leave it out, javadoc isn't smart, it just parses the comments, he can't say that the x parameter for the B constructor is the same than the A constructor even if there is inheritance in play.
I don't think there's a way to "factorize" this either. You'll just have to write all of them, sorry...

A: With methods it should work: if you overwrite or implement a method, the parameters are copied if not provided.
Constructors are not inherited, and even less to a constructor with other parameter types. Javadoc has no way to know that you pass the parameter to another constructor, since it does not interpret the contents of the methods/constructors, only the outer interface.
So, I suppose you are out of luck, if you don't want to write your own doclet or change the standard doclet (and even then you would have to somehow say which constructor to inherit the params from). (This would be a useful addition, also for multiple similar methods in the same class, I think.)

A: If you're overriding a parent method, if you don't include the javadoc most IDEs will show the javadoc for the parent method instead. Otherwise there's no way to define/refer to variables in the javadoc syntax.


text:
Q: Adding a counter I'm trying to add a counter to this, so when a number is clicked, it should display "You've selected 1 out of 5" meaning the person has to select 5 numbers. But if the same number is clicked, it should deselect and then go back to "You've selected 0 out of 5". So you could essentially click 1,5,7 but then it should display "You've selected 3 out of 5"
<!DOCTYPE html>

      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Gaarith</title>

               You've selected: none.

1

2

3

4

5

6

7

8

9

10

11

12

A: You are currently displaying the array of selected items. Just display the length instead.
You can just change
$("#select-result").text(liSelected.length === 0 ? "none" : liSelected.join(", "));
to
$("#select-result").text(liSelected.length === 0 ? "none" : (liSelected.length + ' out of 5'));


text:
Q: Using jQuery to apply CSS properties to headers with a specific font family? I'm working on a custom Wordpress theme that includes 2 different fonts used for header tags throughout the site. The one font is cursive and needs to be have normal text-transform properties. The other font needs to always be displayed in text-transform:uppercase;.
I can't apply text-transform:uppercase; to all of the header tags because it will also apply to the cursive font - which I do not want.
Since it's Wordpress, the client will be able to add headers in TinyMCE and change the font family on a case-by-case basis, so using a class to apply the cursive font that also applies text-transform:normal; is also out.
I was wondering if there is a way to use jQuery to apply the 'text-transform' property to anything with a specific font family?
So, for example, I want to have any header that is font-family:"Cinzel"; to also have text-transform:uppercase; applied to it, but any headers with font-family:"Dancing Script"; need to remain text-transform:normal;.

A: You could just filter the header tags based on font-family, and then apply the text-transform

$('header').filter(function() {
    return $(this).css('font-family').replace("'",'') === 'Cinzel';
}).css('text-transform', 'uppercase');
.cinz {font-family : "Cinzel"}

this should be uppercase
this shouldn't


text:
Q: Show that $H \mathrel{\unlhd} SU(2)$ contains matrices with all possible traces between $2$ and $2\cos \varphi_0 $. Let $H \mathrel{\unlhd} SU(2)$ that contains an element $A$ such that $\text{tr}(A)=2\cos \varphi_0 \neq \pm2$.
Use i),ii) to show that $H \mathrel{\unlhd} SU(2)$ contains matrices with all possible traces between $2$ and $2\cos \varphi_0 $.
i) Any element $A\in SU(2)$ is conjugate to a diagonal matrix $U_{\varphi}=\begin{bmatrix}
 e^{i\varphi }& 0 \\
 0&  e^{-i\varphi }\\
\end{bmatrix}$. $A$ uniquely determines $\varphi \in [0,\pi]$, and $\varphi=\cos ^{-1}(\text{tr}(A/2))$.
ii) If $B = \begin{bmatrix}
 \alpha & -\beta \\
 \overline{\beta} &  \overline{\alpha}\\
\end{bmatrix}$, $\text{tr}(BU_{\varphi}B^{-1}U_{\varphi}^{-1})=2(\alpha \overline{\alpha} + \beta\overline{\beta} \cos 2\varphi)$.
I think I have to show that $U_{\varphi_0} \in H$ first. Then, it would be possible to say that $BU_{\varphi_0}B^{-1} \in H$ for any $B \in SU(2)$ so that $BU_{\varphi_0}B^{-1}U_{\varphi_0}^{-1} := C \in H$. And, as $B$ can be any matrix, we can let $||\alpha||^2 = t \in [0,1] $ vary, and I can get the desired result. But, how do I show that $U_{\varphi_0} \in H$?
Edit: I showed that $U_{\varphi_0} \in H$. And, got the desired result.
Now, I would like to show that $H = SU(2)$ with the result I got and i), ii). So, I'm trying to show that "If $B \in SU(2)$, then $B \in H$." But, I'm stuck. Can I get some help with this?
My Approach:
Let $B \in SU(2)$.
Then, $\exists U_{\theta}$ s.t $P^{-1}BP = U_{\theta}$ for some $P \in SU(2)$.
Let $G_{U_{\theta}} \leq SU(2)$ that is generated by $U_{\theta}$.
Then, for any $n \in \mathbb{N}$, $(U_{\theta})^n = P^{-1}B^n P \in G_{U_{\theta}}$.
But, note that $\exists n \in \mathbb{N}$ s.t $\text{tr} ((U_{\theta})^n)=\text{tr} (B^n) = 2 \cos n\theta \in [2\cos 2\varphi_0,2]$
Then, by the previous result, $B^n \in H$.
How do I show that $B \in H$ from here?