text:
Q: How to define structure in a tag-based organization? [former title: Is there a way to force a relationship structure on a tag-based organizational methodology?]
I have some entities, and they have a series of attributes. Some of the attributes affect what other attributes the entity can have, many of the attributes are organized into groups, and occasionally entities are requited to have certain numbers of attributes from certain groups, or possibly a range of attributes from certain groups.
Is there a way to model these sorts of tag-to-tag relationships, such as requirement, grouping, exclusion, etc. using a database, or is this only possible with programmed "business rules"? Ideally, I would like the possible tags and their relationships to be easily configurable, and hence highly flexible.
One of the ways I have considered is to have the tags and possible relationships, and then you get a tag-tag-applied relationship sort of table, but this seems like a rather brittle approach.
So, is this possible in a more rigorous fashion, and if so, how would I even begin to go about it?

A: edit: Your description of variable attributes that apply only depending on the values in other attributes is a non-relational, non-normalized design.  RDBMS may not be the best solution for storing this kind of data.  Probably RDF would be a good solution for data that requires this level of flexibility.
My earlier answer, pertaining to RDBMS solutions, is below:

Some people model flexible attributes with the Entity-Attribute-Value design, but this is often too unstructured and you end up fighting with data integrity problems.  Use this only if you need a virtually limitless number of entity sub-types.
Other people use Single Table Inheritance, where you put all attribute columns used by all sub-types into one very wide table, and leave them NULL on rows where the attribute is irrelevant to the sub-type.  But this has limits because the table can grow too wide, and you lose the ability to make any attributes mandatory, because they must all be nullable.
If you have a relatively small number of entity sub-types, I would recommend creating a dependent table for each group of required attributes.  Define the dependent table's primary key as a foreign key to the parent table, so you get a one-to-one relationship.
CREATE TABLE Vehicles (
  vehicle_id INT PRIMARY KEY
  ...attributes common to all vehicles...
);

CREATE TABLE Automobiles (
  vehicle_id INT PRIMARY KEY,
  ...attributes specific to autos...
  FOREIGN KEY (vehicle_id) REFERENCES Vehicles(vehicle_id)
);

You can also provide a little more data integrity by encoding the subtype in the primary key of the parent table.  That's to make sure a row in Automobiles cannot reference a motorcycle in Vehicles.
CREATE TABLE Vehicles (
  vehicle_id INT,
  vehicle_type VARCHAR(10),
  ...attributes common to all vehicles...
  PRIMARY KEY (vehicle_id, vehicle_type),
  FOREIGN KEY (vehicle_type) REFERENCES VehicleTypes (vehicle_type)
);

CREATE TABLE Automobiles (
  vehicle_id INT,
  vehicle_type VARCHAR(10) CHECK (vehicle_type = 'Automobile'),
  ...attributes specific to autos...
  FOREIGN KEY (vehicle_id, vehicle_type)
    REFERENCES Vehicles(vehicle_id, vehicle_type)
);

Of course, you need to create a new dependent table each time you define a new sub-type, but this design does give you a lot more structure to enforce data integrity, NOT NULL attributes, and so on.
The only part you need to enforce in application logic is that to make sure to create a row in Automobiles for each row in Vehicles with vehicle_type = 'Automobile'.

A: There's no difference between using databases to enforce your rules or using source code elsewhere.  Code is data.  That's the esoteric Lisp answer.
The real question you're asking is whether this is easier in a relational database or in (I assume) an Algol family language.  You didn't specify a RDBMS, so I'm going to assume ANSI.  That makes this hard.
BTW, this is easy in Prolog.  But that's neither here nor there.
I would say to use check constraints for everything.  The mental shift needed for this approach is to realize that your UI will need a way to define these tag relationships.  Traditionally, you would issue CRUD statements from the UI to the DB.  Instead, you need to issue ALTER TABLE statements to CRUD check constraints.
There are two problems with this approach:

*

*Such statements are not parameterizable in most RDBMS's.  Think SQL injection.

*Implementations vary in their support for full ANSI check constraints.  If subqueries aren't supported, forget it.

If you could clarify your question with a specific RDBMS, then we can give you a better answer.


text:
Q: Provider org.glassfish.json.JsonProviderImpl not found at javax.json.spi.JsonProvider.provider(JsonProvider.java:97) How to run Java API for JSON Processing(JSR 374) in eclipse?I am trying to parse JSON string to JsonParser(javax.json.stream.JsonParser). Also added javax.json-api-1.0.jar in the build path. At runtime, there is an exception.
My code is
import java.io.StringReader;
import javax.json.Json;
import javax.json.JsonReader;
import javax.json.JsonStructure;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;
import javax.json.JsonReader;
import javax.json.JsonStructure;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;
public class jsonnn {
public class jsonnn {
public static void main(String[] args) {
        // Parse back
        final String result = "{\"name\":\"Falco\",\"age\":3,\"bitable\":false}";
        final JsonParser parser = Json.createParser(new StringReader(result));
        String key = null;
        String value = null;
        while (parser.hasNext()) {
            final Event event = parser.next();
            switch (event) {
            case KEY_NAME:
                key = parser.getString();
                System.out.println(key);
                break;
            case VALUE_STRING:
                value = parser.getString();
                System.out.println(value);
                break;
            }
        }
        parser.close();
    }
}

And the exception is
Exception in thread "main" javax.json.JsonException: Provider org.glassfish.json.JsonProviderImpl not found
at javax.json.spi.JsonProvider.provider(JsonProvider.java:97)
at javax.json.Json.createParser(Json.java:90)
at jsonnn.main(jsonnn.java:14)
Caused by: java.lang.ClassNotFoundException: org.glassfish.json.JsonProviderImpl
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at javax.json.spi.JsonProvider.provider(JsonProvider.java:94)
... 2 more

A: You're developing against an API and have no implementation for that API. You need to make sure you have an implementation of the JSON-P specification to actually run the code you're trying to use.
In the JSR 374 official website Getting Started guide, it shows that you need two Maven dependencies - one for the API and one for the reference implementation - before you can use JSON-P 1.1:
<dependency>
    <groupId>javax.json</groupId>
    <artifactId>javax.json-api</artifactId>
    <version>1.1</version>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
</dependency>

Since it looks like you're not using Maven, you will need to download the implementation JAR from Maven Central manually:
https://repo1.maven.org/maven2/org/glassfish/javax.json/1.1/
Or just click this direct link to download the JAR: javax.json-1.1.jar

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do i get a Fragment to send onClickListener result back to the main activity I've got a Main activity that when first started displays a fragment which displays a list view of Paired Bluetooth devices. I don't want to use a ListFragment as I want to display a TextView at the top.
I've created an onItemClickListener that sets strings with the MAC address and Name of the device selected. This is showing ok in the LOG
I want to send these Strings back to the Main activity for that then to open a different Fragment which uses these to connect to the Bluetooth device.
I've alredy got this working using all Activities, but want to change to Fragments.
My Main Activity is.
 import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    // MAC-address of Bluetooth module (you must edit this line)
    private static String address = "No Device Selected";
    private static String itemName = "No Device Selected";

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

}

the Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        class="com.ming.pondcontroller.AddressFragment"
        android:id="@+id/main_frag"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

My Address Fragment
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Set;

public class AddressFragment extends Fragment {

    private static final String TAG = "get address Activity";
    private BluetoothAdapter BA = null;
    private Set<BluetoothDevice> pairedDevices;
    LayoutInflater inflater2;
    ListView lv;
    String address;
    String itemName;
    String itemString;

    public AddressFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        inflater2 = inflater;
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_address, container, false);
    }

    @Override
    public void onStart(){
        super.onStart();
        lv = (ListView)getView().findViewById(R.id.listView);
        BA = BluetoothAdapter.getDefaultAdapter();
        checkBTState();

        // get paired devices
        pairedDevices = BA.getBondedDevices();
        ArrayList list = new ArrayList();
        // get a list of paired devices
        for(BluetoothDevice bt:pairedDevices){
            list.add(bt.getName()+"\n"+bt.getAddress());
        }
        // display the list in the list view
        final ArrayAdapter adapter = new ArrayAdapter(inflater2.getContext(),android.R.layout.simple_list_item_1,list);
        lv.setAdapter(adapter);

        // onItemClick Listener
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView,View view, int position, long l){
                // get the text of the item clicked from position
                itemString = (String)(lv.getItemAtPosition(position));
                // get last 17 characters for MAC address
                address = itemString.substring(itemString.length()-17);
                itemName = itemString.substring(0,itemString.length()-17);
                Log.d(TAG,address);

            }
        }); //end of onClickListener
    }

    private void checkBTState() {
        // Check for Bluetooth support and then check to make sure it is turned on
        // Emulator doesn't support Bluetooth and will return null
        if(BA==null) {
            Log.d("Fatal Error", "Bluetooth not support");
        } else {
            if (BA.isEnabled()) {
                Log.d(TAG, "...Bluetooth ON...");
            } else {
                //Prompt user to turn on Bluetooth
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);
            }
        }
    }
}

And its layout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorMainBack"
    tools:context="com.ming.pondcontroller.AddressFragment">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:id="@+id/textView"
        android:background="@color/colorPrimary"
        android:textColor="@color/colorWhite"
        android:textSize="20dp"
        android:text="Select Device"/>
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/textView"
        android:background="@color/colorTextBack">
    </ListView> />
</RelativeLayout>

I've looked at loads of examples of callbacks, listeners and interfaces but can't seem to find the right thing without using listFragment.

A: Make an interface that your Activity will implement, then set that as a member variable in your Fragment in onAttach():
Interface Class:
interface BluetoothItemSelected {
    void onBluetoothItemSelected(String itemName, String itemAddress);
}

MainActivity implementation:
public class MainActivity extends AppCompatActivity implements BluetoothItemSelected {

    // MAC-address of Bluetooth module (you must edit this line)
    private static String address = "No Device Selected";
    private static String itemName = "No Device Selected";

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

    @Override
    public void onBluetoothItemSelected(String itemName, String itemAddress) {
        // TODO do your work here
    }

    // your other Activity code...

}

Fragment implementation:
public class AddressFragment extends Fragment {

    private static final String TAG = "get address Activity";
    private BluetoothAdapter BA = null;
    private Set<BluetoothDevice> pairedDevices;
    LayoutInflater inflater2;
    ListView lv;
    String address;
    String itemName;
    String itemString;

    BluetoothItemListener btItemListener;

    @Override
    public void onAttach(Context activity) {
        if (activity instanceof BluetoothItemListener) {
            btItemListener = (BluetoothItemListener) activity;
        }
    }

    @Override
    public void onDetach() {
        // remove the reference to your Activity
        btItemListener = null;
    }

    @Override
    public void onStart(){
        super.onStart();
        lv = (ListView)getView().findViewById(R.id.listView);
        BA = BluetoothAdapter.getDefaultAdapter();
        checkBTState();

        // get paired devices
        pairedDevices = BA.getBondedDevices();
        ArrayList list = new ArrayList();
        // get a list of paired devices
        for(BluetoothDevice bt:pairedDevices){
            list.add(bt.getName()+"\n"+bt.getAddress());
        }
        // display the list in the list view
        final ArrayAdapter adapter = new ArrayAdapter(inflater2.getContext(),android.R.layout.simple_list_item_1,list);
        lv.setAdapter(adapter);

        // onItemClick Listener
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView,View view, int position, long l){
                // get the text of the item clicked from position
                itemString = (String)(lv.getItemAtPosition(position));
                // get last 17 characters for MAC address
                address = itemString.substring(itemString.length()-17);
                itemName = itemString.substring(0,itemString.length()-17);
                Log.d(TAG,address);
                // call your interface here
                if (btItemListener != null) {
                    btItemListener.onBluetoothItemSelected(itemName, address);
                }
            }
        }); //end of onClickListener
    }

    // your other Fragment code ...
}

A: When I need to do this in my code, I use LocalBroadcastManager to broadcast local messages with intents that are picked up by the activity using a BroadcastReceiver.
https://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html
https://developer.android.com/reference/android/content/BroadcastReceiver.html
I am not sure if it is the best way, but it works nicely for my purposes.

A: What I would suggest is in your Activity you implement a listener.  Then in your fragment you call that listener in the onClick
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    try {
        yourActivityListener = (IActivityListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement IActivityListener");
    }
}

in your onItemClicked method you can call it this way
yourActivityListener.onItemClicked();

this will be sent to your activity to know what item got clicked.

A: Fragment:
public static class AddressFragment extends Fragment {

    OnAddressListener mListener;

    // Container Activity must implement this interface
    public interface OnAddressListener {
        public void onAddressChanged(String address);
    }

    // Use : mListener.onAddressChanged(address)

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnAddressListener ) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnAddressListener");
        }
    }
}

Activity:
public class MyActivity extends Activity implements OnAddressListener{

    @Override
    public void onAddressChanged(String address){
           // Set your address
    }

}


text:
Q: WordPress ACF Relation field loop out pages I have created a Relation field to create a little menu with a few links in it.
I've selected my pages and wrote the loop with the help of the documentation provided on the ACF website. The problem is the loop doesn't seem to be working. I get no errors and there's nothing to see, when I try to debug and dump the variable that is supposed to get the data it says NULL.
Anyone knows what is going wrong here? Been trying to fix it for multiple days now :/
Here's my loop:
<?php

    $posts = get_field('field_56ebc552c03cb');

    if( $posts ): ?>

        <?php foreach( $posts as $p ): ?>

                <a href="<?php echo get_permalink( $p->ID ); ?>"><?php echo get_the_title( $p->ID ); ?>

        <?php endforeach; ?>

    <?php endif; ?>

A: I' ve found the issue, since I am using a field in my custom options page to retrieve the data I should use this:

$menu_posts = get_field('footer_links', 'option');

And my loop should look like this:
<?php

    $menu_posts = get_field('footer_links', 'option');

    if( $menu_posts ): ?>

        <?php foreach( $menu_posts as $p ): ?>

                <a href="<?php echo get_permalink( $p ); ?>"><?php echo get_the_title( $p ); ?>

        <?php endforeach; ?>

    <?php endif; ?>


text:
Q: How to load a large array of strings in to an MFC combobox control fast as possible? I have an array of 1000 strings to load into a combo box. What is the fastest way to load the array of strings into the combo box?
Is there some way other than iterating over the list of strings, putting each string into the combo box one at a time?
And how to copy the combo box data once loaded to some 10 other combo boxes?

A: If you have 1,000 strings repeated in 10 comboboxes, you may want to consider using an owner drawn combobox, which draws the strings on the fly based on indices into your array, rather than storing them in the combobox at all.  Way faster, way more memory efficient.  Check out the DrawItem method and DRAWITEMSTRUCT structure in the on-line help. Basically, you would do something like using InitStorage and InsertString (as mentioned by NuSonic) to create your 1000 blank items in your combobx, and override DrawItem to extract and draw the required string, based on index, as it needs to be drawn.

A: I'm not aware of any way to load multiple strings atomically, but there are a couple of things that you can do to make the process more efficient:

*

*Call CComboBox::InitStorage before adding items to pre-allocate memory

*Use InsertString instead of AddString to prevent triggering a sort on each addition (assuming the CBS_SORT style is enabled)

A: Possibly faster than CComboBox with DrawItem would be an owner data CListCtrl.
This would also serve your goal of duplicating a subset of the items into other lists, since a common data source could be used.
I suggest this because a 1000-item CComboBox isn't going to be very usable.

A: I will consider using a pick list instead of a combo box for performance.
A general rule of thumb to improve performance when inserting many item in a UI list is to call before the insertion and setting it back to true after.
Here's the correct syntax
#define NB_ITEM 1000
#define ITEM_LENGTH 10

void CMFCComboDlg::InitMyCombo()
{
    CString _strData;
    m_cbMyCombo.SetRedraw( FALSE );

    m_cbMyCombo.Clear();

    m_cbMyCombo.InitStorage(NB_ITEM, ITEM_LENGTH);

    for( int i = 0; i < NB_ITEM; i++ )
    {
        _strData.Format( L"Test %ld", i );
        m_cbMyCombo.InsertString( i, _strData );
    }

    m_cbMyCombo.SetCurSel(0);

    m_cbMyCombo.SetRedraw( TRUE );
}

EDIT: Improve the solution to include smacl suggestion

A: I had this issue and solved it in two ways, depending on the # items.  Setting to not draw and init storage made no difference whatsoever to me.  Making an owner draw one is also viable, but I had a ton of comboboxes.  Assuming a fixed list for each combobox, that does not change contents, list is set once.
Very large # Items:
Made the combo box just be Simple/Disabled with SetWindowText to set initial string, and a little button next to it opened a dialog that let you choose the item from a list control in Report mode of the data that would've been in the combo box (could be anything done in dialog).
Moderate # Items:
Made a custom derived combobox class that overrides AddString, SelectString, and handles OnDropDown.  When you add items, it puts them into a temporary vector, and then on SelectString (could do SetCurSel override too), it adds one item it finds and selects.  When dropping down, then it resets the combobox and adds all the items the and selects currently selected one.  There is slight slowdown on dropping the combobox, but on low amounts of items is not noticeable.
It made my dialogs load much faster and still be fully functional without owner draw.


text:
Q: How to proof the convolution product with the Fourier integral? One should prove the following:
$\mathcal{F}_k^{-1}[\tilde f (k)\tilde g (k)](x)=\frac{1}{\sqrt{2\pi}}(f * g)(x)$
I have absolutely no idea how to solve this exercise. I researched for articles and websites regarding this topic, but couldn't find anything similar :( I would be very thankful for any help!

A: $$\begin{align}
\int (f*g)(x) \, e^{-ix\xi} \, dx
&= \int \left( \int f(x-y)\,g(y)\,dy \right) \, e^{-ix\xi} \, dx
\\
&= \iint f(x-y)\,g(y)\,e^{-ix\xi}\,dy\,dx
\\
&= \int \left( \int f(x-y) \, e^{-ix\xi} \, dx \right) g(y) \, dy
\\
&\stackrel{z:=x-y}{=} \int \left( \int f(z) \, e^{-i(y+z)\xi} \, dz \right) g(y) \, dy
\\
&= \int \left( \int f(z) \, e^{-iz\xi} \, dz \right) g(y) e^{-iy\xi} \, dy
\\
&= \left( \int f(z) \, e^{-iz\xi} \, dz \right) \left( \int  g(y) e^{-iy\xi} \, dy \right)\end{align}
$$


text:
Q: Check when the application has gone fullscreen. (DXGI/DirectX10) this is my question...
There is a way to check when the application has gone fullscreen in DXGI (DX10/11).
For going Fullscreen I mean that the system has COMPLETED the mode change.
Cause i need it for my application to prevent deadlock and to adjust timing. (I have a multithreaded engine and the Present is not on the message pump thread causing deadlock on mode-change randomly))
Actually I make it wait 1 second continuing to process messages on the message pump thread and it work, but i want something more DETERMINISTIC that says to me "hey, the mode change is complete, you are now in fullscreen mode". :D
Any idea?

A: Is there any reason you can't run the rendering and message pump threads as the same thread?
According to the docs there is nothing that tells you the change is complete.
Strangely, though, DXGI relies on getting responses back from internal SendMessage calls (which occur via the message pump in a multi-threaded environment).  So I don't see how delaying your message pump fixes problems.  All it will do is make DXGI wait an extra second before continuing to do its stuff.  A dead-lock usually implies that you are doing something that causes the message pump to block waiting for the rendering thread to do something.


text:
Q: loopback format result in afterRemote hook I have two models Book.json and Department.json. When I fetch book details, we are also fetching corresponding department through relation.
Output is :
[{
"title": "Python",
"department": {
    "name": "Software"
}
},
{
"title": "World",
"department": {
    "name": "Politics"
}
}]

How we can format the above code to
[{
"title": "Python",
"department": "Software"
},
{
"title": "World",
"department": "Politics"
}]

When I tried to format the ctx.result , it gives me an error like only getter is supported.

"message": "Cannot set property books of #ModelConstructor which has only a getter",

A: You can use Array#map to loop through the items and modify each item in the iteration:

const data = [{"title":"Python","department":{"name":"Software"}},{"title":"World","department":{"name":"Politics"}}];

const result = data.map(item => {
  item.department = item.department.name;
  return item;
});

console.log(result);


text:
Q: Audio louder than usual until volume is changed - Windows 8.1 Same issue as this:
Audio louder than usual until volume is changed
, but I am on Windows 8.1 and the answer doesn't work for me. I've found forum topics about this with solutions involving uninstalling/reinstalling the sound driver and that doesn't work as well. Unlike everyone else I've read about my laptop uses Conexant instead of Realtek, I don't even have a loudness equalization enhancement, I've disabled all enhancements anyway (Night Mode, 3D Immersion, Phantom Speaker).

A: As a workaround, consider using the generic "High Definition Audio Device" driver built into Windows.
This worked for some users in Windows 10.  It seems worth trying.
Source: Sound louder than usual when playing media after pausing - Page 3 - Windows 10 Forums

*

*Open Device Manager

*Expand "Sound, video and game controllers"

*Update generic device

*

*Right click on "High Definition Audio Device"

*Select "Update driver software..."

*Click "Browse my computer for driver software"

*Select "High Definition Audio Device" and click Next

*Click "Yes" on the "Update Driver Warning" dialog

*Click "Close"

*Update specific device

*

*Right click on "Conexant whatever"

*Select "Update driver software..."

*Click "Browse my computer for driver software"

*Select "High Definition Audio Device" and click Next

*Click "Yes" on the "Update Driver Warning" dialog

*Click "Close"

*Reboot


text:
Q: Solve for $\lambda$ I have the following system of two equations:
\begin{align}
w &= \frac{1}{k}\Omega^{-1}(\mu + \lambda \mathbf{1})\\
w^T\mathbf{1}&=1
\end{align}
where $\Omega$ is a matrix of size $n \times n$, $\mu$, $w$ and $\mathbf{1}$ are vectors of size  $n$ and $k$, $\lambda$ and $1$ are magnitudes. As you can see by the second equation is that the sum of the values of $w$ should be $1$.
I want to solve for $\lambda$ respecting both equations. So I input the first one on the second one.
My naïve attempt have been the following:
\begin{equation}
w^T\mathbf{1} = \mathbf{1}^Tw =1
\end{equation}
\begin{equation}
\mathbf{1}^T\frac{1}{k}\Omega^{-1}(\mu + \lambda \mathbf{1})=1
\end{equation}
\begin{equation}
\frac{1}{k}\mathbf{1}^T\Omega^{-1}(\mu + \lambda \mathbf{1})=1
\end{equation}
Here I got somehow stuck because I cannot send the terms $\mathbf{1}^T\Omega^{-1}$ to the right hand side of the equation. I thought of multiplying from the left by $\Omega\mathbf{1}^{T+}$ both sides of the equation where $\mathbf{1}^{T+}$ is the pseudoinverse of $\mathbf{1}^T$, that would give me something like the following $\Omega\mathbf{1}^{T+}\mathbf{1}^T\Omega^{-1}$. However the term $\mathbf{1}^{T+}\mathbf{1}^T$ would give me a $n \times n$ which is not the identity matrix.
I'm out of ideas, I though I wasn't not going to spend a lot of time to solve for $\lambda$ but I've been hours and I see that I don't have the right background or that I'm just missing something.

A: Based on Ian's comment,
$$\frac{1}{k}\mathbf{1}^T\Omega^{-1}(\mu+\lambda\mathbf{1})=1\to \mathbf{1}^T\Omega^{-1}\mu+\lambda\mathbf{1}^T\Omega^{-1}\mathbf{1}=k$$
$$\lambda\mathbf{1}^T\Omega^{-1}\mathbf{1}=k-\mathbf{1}^T\Omega^{-1}\mu$$
but see that $\mathbf{1}^T\Omega^{-1}\mathbf{1}\in \mathbb R$, which is the sum of all elements of $\Omega^{-1}$. So, if $\mathbf{1}^T\Omega^{-1}\mathbf{1}\ne 0$ then you can write,
$$\lambda=\frac{1}{\mathbf{1}^T\Omega^{-1}\mathbf{1}}(k-\mathbf{1}^T\Omega^{-1}\mu).$$
Ps.: $\mathbf{1}^T\Omega^{-1}\mathbf{1}$ may be equal to $0$. For instance, take
$$\Omega^{-1}=\begin{pmatrix}
2&-1\\
0&-1
\end{pmatrix}.$$


text:
Q: How to prove $\lim_{n\to\infty} \left(1+\frac{1}{(3n+1)}\right)^n $ = $ e^\frac{1}{3}$ I really just need to know how to prove $ \lim_{n\to\infty} \left(1+\frac{1}{(3n+1)}\right)^n $ = $ e^\frac{1}{3}$
I have tried using the squeeze theorem and tried to find a convergent subsequence.
Any help would be appreciated

A: Hint.
You know that:
$$(1+\frac 1{3n+1})^n=e^{n\log(1+1/(3n+1))}$$
and you can know use the fact:
$$\log(1+x)\underset{x\to 0}{\sim}x$$
to conclude.
More hint : because then $\log(1+1/(3n+1))\underset{n\to \infty}{\sim}1/(3n+1)$.

A: $$\lim _{ n\rightarrow \infty  }{ { \left( 1+\frac { 1 }{ 3n+1 }  \right)  }^{ n } } =\lim _{ n\rightarrow \infty  }{ { \left[ { { \left( 1+\frac { 1 }{ 3n+1 }  \right)  }^{ 3n+1 } } \right]  }^{ \frac { n }{ 3n+1 }  } } ={ e }^{ \lim _{ n\rightarrow \infty  }{ \frac { n }{ n\left( 3+\frac { 1 }{ n }  \right)  }  }  }={ e }^{ 1/3 }$$

A: Hints:
Either you know the standard limit of $\Bigl(1+\dfrac1n\Bigr)^n$, and you just have to set the substitution $m=3n+1$.
Or you determine the limit of the log.


text:
Q: Atom Script can't find the path for Python 3 on Mac When using the script addon for Atom it brings up:

Unable to run
/usr/bin/python3

Did you start Atom from the command line?
atom .

Is it in your PATH?
PATH: /usr/bin/python3:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/bin/python3:/usr/local/share/dotnet:/Library/Frameworks/Mono.framework/Versions/Current/Commands:~/.dotnet/tools

How do I get Atom to recognize Python 3?
I tried installing Python using Homebrew and it is installed to /usr/local/bin/python3 as well as using the Terminal to add all of the suggested path locations to /etc/paths.

A: You need to properly configure the script package to use a profile that points to the correct python3.

*

*Open a Terminal and navigate to the directory containing your scripts.
$ pwd
/Users/cerberus/Scripts

*Get the path to python3

*

*If you installed it via Homebrew, then it should be at:
$ python3 -V
Python 3.7.3
$ which python3
/usr/local/bin/python3

*You can also check that Homebrew already updated PATH to add /usr/local/bin, but unless you did something wrong with the Python installation, this part is unnecessary.
$ echo $PATH
.../usr/local/bin/:/...

*Now, start Atom from the command line as explained in the package docs

Make sure to launch Atom from the console/terminal. This gives atom
  all your useful environment variables. Additionally, make sure to run
  it with the project path you need.

$ cd /path/to/scripts
$ atom .

OR
$ atom /path/to/scripts

*Go to Packages > Command Palette > Toggle (or use CMD+SHIFT+P)

*Select Script: Run Options

*Input the path to your scripts and the path to the python3 command

NOTE: On my machine, just setting python3 also works. But if you are having problems with your python path, you can try to specify the full path (/usr/local/bin/python3) as shown.

*Save the profile (ex. as "Python3")

*Now, when you want to run your Python scripts, use the Script: Run with Profile command and then select the profile you just created.

*That should work now.


text:
Q: How can I make two boxes turn one color when you hover over either? Currently, when you hover over the blue box both turn yellow, but when you hover over the red box, only it turns yellow.
I need both of them to turn yellow when you hover over either the blue, or the red.
This is as far as I have gotten:
<!DOCTYPE html>

A: here is solution without js

JSFIDDLE

A: Demo
just this
.container:hover div {
    background: yellow;
}

A: Using :before to simulate a hovered div #one...
HTML stays the same
DEMO
CSS
#one {
    background-color: blue;
    width: 50px;
    height: 50px;
    float: left;
}
#two {
    background-color: red;
    width: 50px;
    height: 50px;
    float: left;
    margin-left: 100px;
}
#one:hover, #one:hover ~ #two, #two:hover {
    background-color: yellow;
}
#two:before {
    content:'';
    display:none;
    width:50px;
    height:50px;
    margin-left:-150px;
    background-color: yellow;
}
#two:hover:before {
    display:block;
}

A: If you want hover to applied only when child are hovered, then pointer-events can be a way to do this: DEMO
your CSS turns to be more like :
#one {
  background-color: blue;
  width: 50px;
  height: 50px;
  float: left;
}
#two {
  background-color: red;
  width: 50px;
  height: 50px;
  float: left;
  margin-left: 100px;
}

.parent {
  pointer-events:none;
  overflow:hidden;/* for float , for DEMO purpose to extend body or parent as there would be more content behind childs in real situation. */
}
.parent div {
  pointer-events:auto;
  cursor:pointer
}
.parent:hover div#one,
.parent:hover div#two
{
  background-color:yellow;
}

How does this works ?
pointer-events:none , kills mouse events on parent. Reset to normal to childs.
If you hover a child, then the parent is hovered and the CSS rules parent:hover can be applied.


text:
Q: Where to specify localhost port in VS Code I am building an ASP.NET Core app and am wanting to use a specific port when launching debug in VS Code. It defaults to running http:// localhost:5000. I am unable to find any setting for where I would change this. When I try to specify a port setting in the launch.json file, I am being alerted that it is not allowed. Is there a specific setting to set for specifying which port?

A: In your Program.cs
try to add    .UseUrls("http://localhost:5050")
Port number can be anything other than the specified one

A: You can configure this from the launch.json file.  You want to find the "env" property and add
"ASPNETCORE_URLS":"http://localhost:<PORT_NUMBER>"

Adjusting from the default launch.json it should look something like this:
"env": {
     "ASPNETCORE_ENVIRONMENT": "Development",
     "ASPNETCORE_URLS":"http://localhost:5001"
},

This way your port change will only affect your locally running application and you won't be adding debugging code to your production application

A: Do you have to remove this when you deploy to staging or production?
This doesnt seem good for anything but local dev.


text:
Q: manage many documents scan with a java application I am trying to make an application to scan documents from a scanner and i have found an application based on the mmscomputing free library that i found in github https://github.com/ashishkataria/browserWebScanning
It shows a panel from where you can choose a scanner from a list of available ones and scan the document.
public void getScan()
{

    try
    {
        scanner.acquire();
    }
    catch (ScannerIOException e1)
    {
        IJ.showMessage("Access denied! \nTwain dialog maybe already opened!");
        e1.printStackTrace();
    }
}

 public Image getImage()
 {
     Image image = imp.getImage();
     return image;
 }

public void update(ScannerIOMetadata.Type type, ScannerIOMetadata metadata) {

    if (type.equals(ScannerIOMetadata.ACQUIRED))
    {

if(imp!=null)
{
    jContentPane.remove(ipanel);
    jContentPane.remove(cpanel);
    jContentPane.remove(crpdpanel);
}

         imp = new ImagePlus("Scan", metadata.getImage());

         im = imp.getImage();

         imagePanel = new ImagePanel(im);
         imagePanel.updateUI();

         imagePanel.repaint();
         imagePanel.revalidate();

         ClipMover mover = new ClipMover(imagePanel);
         imagePanel.addMouseListener(mover);
         imagePanel.addMouseMotionListener(mover);

          ipanel = imagePanel.getPanel();

         ipanel.setBorder(new LineBorder(Color.blue,1));
         ipanel.setBorder(BorderFactory.createTitledBorder("Scanned Image"));
         ipanel.setBounds(0, 30,600, 600);
         ipanel.repaint();
         ipanel.revalidate();
         ipanel.updateUI();
         jContentPane.add(ipanel);
         jContentPane.getRootPane().revalidate();
         jContentPane.updateUI();

         cpanel = imagePanel.getUIPanel();
         cpanel.setBounds(700, 30,300, 150);
         cpanel.repaint();
         cpanel.setBorder(new LineBorder(Color.blue,1));
         cpanel.setBorder(BorderFactory.createTitledBorder("Cropping Image"));
         cpanel.setBackground(Color.white);
         jContentPane.add(cpanel);

         jContentPane.repaint();
         jContentPane.revalidate();

        metadata.setImage(null);
        try {
            new uk.co.mmscomputing.concurrent.Semaphore(0, true).tryAcquire(2000, null);
        } catch (InterruptedException e) {
            IJ.error(e.getMessage());

        }

    }

    else if (type.equals(ScannerIOMetadata.NEGOTIATE)) {
        ScannerDevice device = metadata.getDevice();
        try {
            device.setResolution(100);
        } catch (ScannerIOException e) {
            IJ.error(e.getMessage());
        }

          try{

          device.setShowUserInterface(true);
          device.setResolution(100); }catch(Exception e){
          e.printStackTrace(); }

    }

    else if (type.equals(ScannerIOMetadata.STATECHANGE)) {
        System.out.println("Scanner State "+metadata.getStateStr());
        System.out.println("Scanner State "+metadata.getState());

        if ((metadata.getLastState() == 3) && (metadata.getState() == 4)){}

    } else if (type.equals(ScannerIOMetadata.EXCEPTION)) {
        IJ.error(metadata.getException().toString());

    }

}

I am trying  to make it handle multiple documents and save in a pdf file, this library handles only 1 document right now.
i want to know how can i save the images in a buffer or something else and rescan until the user is done .
and is there a function that can save those images in a pdf file ?


text:
Q: Word-wrap: break-word does not work with a very long word combined with width: 100% Why is it in this fiddle https://jsfiddle.net/0h1wbju0/ my word-wrap: break word and width: 100% aren't being respected and the long word is not being broken up into multiple lines to fit inside it's parent div? Thanks!.
HTML:

        <fieldset class="fieldset_description">Description

 fdsjalllffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff

        </fieldset>

CSS:
.first_div {
  width: 200px;
}

.fieldset_description {
  max-width: 100%;
  word-wrap: break-word;
}

.description {
  max-width: 100%;
  word-wrap: break-word;
}

A: you should use =>
`word-break: break-all;`

Working code jsfiddle


text:
Q: How to set current temperature using Nest Can I programmatically set a new current temperature using the Nest API?
Say, I build my own raspberry or Arduino based temperature sensor. Can that measure the current room temperature, and then set that as the current house temperature on Nest? Then of course Nest should continue operating as normal to reach whatever target temperature was already set.
In other words, can the Nest API override the measured current room temperature?

A: No you can not programmatically set the ambient temperature fields (ambient_temperature_f and ambient_temperature_c). It is exclusively a read only attribute.

A: Are you trying to override the Nest's inbuilt thermometer? Or are you just trying to define the target temperature?
If 1, then you should set the Nest target very high, and keep measuring the ambient tmeperature until it reaches your desired temp, then set the Nest target very low - in this way you are effectively switching the heating on and off manually.
If 2, then you can just set the Nest target temperature as desired.
For either case, you will need to use the appropriate one of the following parameters (depending on your operating mode and your temperature scale of choice):
target_temperature_f
target_temperature_c
target_temperature_high_f
target_temperature_high_c
target_temperature_low_f
target_temperature_low_c


text:
Q: Input string was not in a correct format wtih cm.Parameters.AddWithValue I got this error message : input string was not in a correct format
It throws this error message at these two codes:
cm.Parameters.AddWithValue("@price", double.Parse(frmCancelDetails.Instance.txtPrice.Text));
cm.Parameters.AddWithValue("@qty", int.Parse(frmCancelDetails.Instance.txtQty.Text));

Also, when (double.Parse) and (int.Parse) are deleted, another message is thrown at the end of the code:
error converting data type varchar to numeric
Here is the full code
public void SaveCancelOrder(string user)
    {
        cn.Open();
        cm = new SqlCommand("insert into tblCancel (transno, pcode, price, qty, sdate, voidby, canelledby, reason, action)values(@transno, @pcode, @price, @qty, @sdate, @voidby, @canelledby, @reason, @action)", cn);
        cm.Parameters.AddWithValue("@transno"   , frmCancelDetails.Instance.txtTransNo.Text);
        cm.Parameters.AddWithValue("@pcode"     , frmCancelDetails.Instance.txtPcode.Text);
        cm.Parameters.AddWithValue("@price"   , double.Parse(frmCancelDetails.Instance.txtPrice.Text));
        cm.Parameters.AddWithValue("@qty"       , int.Parse(frmCancelDetails.Instance.txtQty.Text));
        cm.Parameters.AddWithValue("@sdate"     ,  DateTime.Now);
        cm.Parameters.AddWithValue("@voidby"    , user);
        cm.Parameters.AddWithValue("@canelledby", frmCancelDetails.Instance.txtCanceledBy.Text);
        cm.Parameters.AddWithValue("@reason"    , frmCancelDetails.Instance.txtReason.Text);
        cm.Parameters.AddWithValue("@action"    , frmCancelDetails.Instance.comAddToInventory.Text);
        cm.ExecuteNonQuery();
        cn.Close();
    }

A: Maybe you need to round Price to 2 decimals?


text:
Q: How can I mock a custom callback passport.authenticate(...) method in PassportJS using Jest? I'm creating a back-end for a simple project, and I've gotten PassportJS and the Local Strategy to work. I wanted to add some unit tests to my controller but I can't figure out how to mock all of the business logic within my passport.authenticate, which is using a custom callback.
I've already tried using Jest's mockImplementation to create a method or a function but it always gives me a TypeError that says passport.authenticate(...) is not a function.
Here is the "registerUser" operation in my controller that's using PassportJS with a custom callback on a Local Strategy.
const registerUser = async (req, res, next) => {
  const userDetails = req.body;
  const userValidation = bodyValidator.register(userDetails);
  if (userValidation.statusCode === undefined) {
    passport.authenticate('localRegister', (err, user, info) => {
      if (err) throw err;
      if (info !== undefined) {
        res.status(400);
        res.send({
          status: 'error',
          message: info.message,
          statusCode: 400,
          code: 400
        });
      } else {
        req.logIn(user, async err => {
          const userData = {
            firstName: userDetails.firstName,
            lastName: userDetails.lastName,
            email: userDetails.email
          };
          await User.update(userData);
          res.status(200);
          res.send({
            message: 'Register successful!'
          });
        });
      }
    })(req, res, next);
  } else {
    res.status(userValidation.statusCode);
    res.send(userValidation);
  }
};

And this is what my test case looks like right now, but I don't know how to mock the authenticate method.
edited to show more code

const userController = require('../userController');
const User = require('../../models/users');
const passport = require('passport');

jest.mock('../../models/users');
jest.mock('passport');

describe.only('Register user succeeds', () => {
  let send = jest.fn();
  let status = jest.fn();
  let next = jest.fn();

  let res = {
    send,
    status
  };

  afterEach(() => {
    send.mockRestore();
    status.mockRestore();
    next.mockRestore();
  });

  it('should send a response', async () => {
    const req = {
      body: {
        email: 'mock@email.com',
        password: 'mockPassword',
        firstName: 'mockFirstName',
        lastName: 'mockLastName'
      },
      logIn
    };
    passport.authenticate.mockImplementation(() => {
      req, res, () => (done(null, '1', undefined))
    });
    User.update.mockReturnValue({});
    await userController.registerUser(req, res, next);
    expect(res.status).toHaveBeenCalledTimes(1);
    expect(res.send).toHaveBeenCalledTimes(1);
  });
});

I get a TypeError: passport.authenticate(...) is not a function, whereas I'm hoping that I can mock the (err, user, info) callback arguments from my controller's passport.authenticate()!


text:
Q: Binary: Generating all possibilities in array I have somewhat of a unique situation where I'm running into a roadblock. I'm looking for an eloquent solution to the goal, if someone is able to help with that.
Situation: An array of numbers (between 0 and 1) is provided. If the elements in the array are close enough to either 0 or 1 (0.25 in this example) they are rounded. I then would need to generate every possible binary array given the 'unknown' elements.
Example:
data = ([0.05,0.2,0.4,0.6,0.8,1,1])
data[data < 0.25] = 0
data[data > 0.75] = 1

x=-1
for n in data:
    x+=1
    if ((n != 0) and (n!=1)):
        data[x] = 2
data = data.astype(np.int)

This leaves me with array [0 0 2 2 1 1 1]
I then would like to get it to generate
[0 0 0 0 1 1 1]
[0 0 0 1 1 1 1]
[0 0 1 1 1 1 1]

I was thinking numpy array, but when I started doing:
x=-1
y=-1
data2 = data
while (2 in data):
    data = data2
    x+=1
    for n in data:
        for m in data[x,n]:
            if (m==2):
                data[x,n] = 0

It was giving me error of not being able to do the initial pass because it was a 1d array... I don't know. I'm sure there is a better solution than my while and for loops. Does anyone have any insight on the best way to approach this?

A: You can use itertools.product:
from itertools import product

data = [0, 0, 2, 2, 1, 1, 1]

r = 2

combs = product([0, 1], repeat = r)
result = []

for c in combs:
  j = 0
  a = data[:]
  for i in range(len(data)):
    if data[i] == 2:
      a[i] = c[j]
      j += 1
  result.append(a)

print(result)

Output:
[[0, 0, 0, 0, 1, 1, 1],
 [0, 0, 0, 1, 1, 1, 1],
 [0, 0, 1, 0, 1, 1, 1],
 [0, 0, 1, 1, 1, 1, 1]]

You can get r (the number of 2's in the array) by initializing it to zero and incrementing it every time you find a 2 in the array, in the loop you already have, also, you can minimize greatly the complexity of the nested loop above (for i in range(len(data)):) by using an array that stores the indices of 2's in the array.
Modification to the first loop:
r = 0
p = []

for i, n in enumerate(data):
    if (n != 0) and (n != 1):
        data[i] = 2
        r += 1
        p.append(i)

Modification to the second loop:
for c in combs:
  a = data[:]
  for j, i in enumerate(p):
    a[i] = c[j]
  result.append(a)


text:
Q: How do i create a routine that would constantly run in the background? I am making a primitive database in Excel and need a routine to run in the background constantly. I will be able to fill in the actual actions it needs to do, but I don't know how to make something run independent of a key press or some sort of Macro. If someone can give me an example of code that runs independently which I can simply fill with contents, that would be much appreciated.

A: Try this http://www.ozgrid.com/Excel/run-macro-on-time.htm

A: I haven't worked with VBA for quite some time now, but you would have to create a thread in VBA, maybe by COM-Threading, but I am not too sure if Excel is threadsafe or if you even can use Threads of some kind in Excel. Another alternative would be a Timer. If it is not implemented in VBA and I don't remember it to be, you would have to create the Timer yourself and react to the Windows Message yourself, if you can do that in VBA.
All in all I think this uses case might be to big for an Excel VBA Macro. If I were you I would consider doing this in a different way.


text:
Q: IdentityServer AccessTokenValidation results in Token is not active I use IdentityServer with AccessTokenType.Reference and one API. The API is unable to authenticate the requested User with the following error log:
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.0 POST http://dev.applicationname.com/api/query text/plain 36
info: IdentityModel.AspNetCore.OAuth2Introspection.OAuth2IntrospectionHandler[7]
      BearerIdentityServerAuthenticationIntrospection was not authenticated. Failure message: Token is not active.
info: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[7]
      Bearer was not authenticated. Failure message: Token is not active.
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[12]
      AuthenticationScheme: Bearer was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action ApplicationName.Services.QueryHandler.Controllers.QueryController.PostAsync (ApplicationName.Services.QueryHandler) in 1.0248ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 49.0536ms 401

Service
public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvcCore()
        .AddAuthorization()
        .AddJsonFormatters();

    services
        .AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
        .AddIdentityServerAuthentication(options =>
        {
            options.Authority = "http://localhost:5000";
            options.ApiName = "my_api_name";
            options.ApiSecret = "my_api_secret";
        });
}

IdentityServer

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        {
            // ...
        })
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    // ...

    services.AddIdentityServer(options =>
        {
            options.IssuerUri = "http://localhost:5000";
            options.PublicOrigin = "http://localhost:5000";
        })
        .AddDeveloperSigningCredential()
        .AddInMemoryPersistedGrants()
        .AddInMemoryIdentityResources(Config.GetIdentityResources())
        .AddInMemoryApiResources(Config.GetApiResources())
        .AddInMemoryClients(Config.GetClients())
        .AddAspNetIdentity<ApplicationUser>();
}

Config.cs

public static IEnumerable<ApiResource> GetApiResources()
{
    yield return new ApiResource
    {
        Name = "my_api_name",
        ApiSecrets = {new Secret("my_api_secret".Sha256())},
        Scopes = {new Scope {Name = $"my_api_name.full_access"}},
        UserClaims =
        {
            JwtClaimTypes.Name,
            JwtClaimTypes.Email,
            "tenant_id"
        }
    };
}

public static IEnumerable<Client> GetClients(string baseUrl)
{
    yield return new List<Client>
    {
        new Client
        {
            ClientId = "frontend",
            ClientName = "AngularClient",
            AccessTokenType = AccessTokenType.Reference,
            AllowAccessTokensViaBrowser = true,
            AllowedGrantTypes = GrantTypes.Implicit,
            AllowOfflineAccess = true,
            AlwaysIncludeUserClaimsInIdToken = true,
            RequireConsent = false,
            RequireClientSecret = false,

            RedirectUris =
            {
                "http://localhost:4200/signin-oidc"
            },
            PostLogoutRedirectUris =
            {
                "http://localhost:4200/signout-callback-oidc"
            },
            AllowedCorsOrigins =
            {
                "http://localhost:4200"
            },
            AllowedScopes = new List<string>
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile,
                IdentityServerConstants.StandardScopes.Email,
                "tenant_id",
                "my_api_name.full_access"
            }
        }
    };
}

In IdentityServer I get the following error log:
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.IntrospectionEndpoint for /connect/introspect
[15:17:44 Information] IdentityServer4.Hosting.IdentityServerMiddleware
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.IntrospectionEndpoint for /connect/introspect

fail: IdentityServer4.Validation.TokenValidator[0]
      Invalid reference token.
      {
        "ValidateLifetime": true,
        "AccessTokenType": "Reference",
        "TokenHandle": "2a29182593d7eb69e9845e3d94b16f3056bc27da6cb6d6ae760733b3141dacdb"
      }
[15:17:44 Error] IdentityServer4.Validation.TokenValidator
Invalid reference token.
{
  "ValidateLifetime": true,
  "AccessTokenType": "Reference",
  "TokenHandle": "2a29182593d7eb69e9845e3d94b16f3056bc27da6cb6d6ae760733b3141dacdb"
}

info: IdentityServer4.Endpoints.IntrospectionEndpoint[0]
      Success token introspection. Token active: False, for API name: my_api_name
[15:17:44 Information] IdentityServer4.Endpoints.IntrospectionEndpoint
Success token introspection. Token active: False, for API name: my_api_name

I assume that there is a missconfiguration but can't see it.

A: I think you have to add your client access to the resource, otherwise IdentityServer will keep rejecting the reference token validation. The apiResource must be in client's allowed scopes, it is a bit confusing imho.
public static IEnumerable<Client> GetClients(string baseUrl)
{
    yield return new List<Client>
    {
        new Client
        {
            AllowedScopes = new List<string>
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile,
                IdentityServerConstants.StandardScopes.Email,
                "tenant_id",
                "my_api_name", // add this
                "my_api_name.full_access"
            }
        }
    };
}


text:
Q: How to attach files to input tag of type file by code Is it possible to attach a file (located in the user's PC) to an input[type=file] element by code?
I use VB6 right now to do this (or at least I try) but any language would do.
(EDIT: I use a WebBrowser control.)

A: The answer is You can't
You can only make the user click the input button and then make him choose the files.
Even if you find a workaround for doing it from code(Which is quite impossible for me),
The browsers will never allow you to bypass their security measures.
Even if it is supported today, most browsers are intelligent and learning day by day.
They sure will unsupport it in the very near future
So there's no chance of achieving what you want.


text:
Q: how to get a number from a file I have to get a number from a file, some files have letters and numbers convined. like (dsh8kuebw9) or have spaces like(8  8) how can I get those numbers? I have tried so many times. I have a method to find the occurences of a digit is in a number is the count8 method.
The parseInt converts the line of the file in a integer but because in some files there are letters I am having trouble with my method because it only accepts integers no Strings
File file_a = new File("C:\\name\\textFile8a.txt");
try
{

    FileReader in = new FileReader(file_a);
    BufferedReader readFile = new BufferedReader(in);
    String n = readFile.readLine();
    int num = Integer.parseInt(n);

    System.out.println(count8(num, 8));
}
catch(IOException e)
{
    System.out.println("file could not be founded");
    System.err.println("OIException: " + e.getMessage());
}

A: You can remove all the numbers in your string before you parse it by replacing non-numberic characters with an empty string:
String n = readFile.readLine();
n = n.replaceAll("[^0-9]", "");
int num = Integer.parseInt(n);

A: basic and simple solution
public static ArrayList<Integer> extractNumber(String s) {

        ArrayList returnList = new ArrayList<Integer>();

        Pattern regex = Pattern.compile("\\d[\\d.]*");
        Matcher matcher = regex.matcher(s);
        while (matcher.find()) {
            returnList.add(matcher.group());
        }

        return returnList;
    }

    public static void main(String[] args) {

        File file_a = new File("C:\\name\\textFile8a.txt");
        try {

            FileReader in = new FileReader(file_a);
            BufferedReader readFile = new BufferedReader(in);
            String n = readFile.readLine();
            ArrayList<Integer> numberList = extractNumber(n);
            System.out.println(numberList);

        } catch (IOException e) {
            System.out.println("file could not be founded");
            System.err.println("OIException: " + e.getMessage());
        }
    }

A: Below is a method which will extract any signed or unsigned, Whole or Floating Point, numerical values from a supplied Input String of any length and return those values within a String[] Array. Read the method JavaDoc and the comments within the method:
/**
 * This method will extract all signed or unsigned Whole or floating point
 * numbers from a supplied String. The numbers extracted are placed into a
 * String[] array in the order of occurrence and returned.

 *
 * It doesn't matter if the numbers within the supplied String have leading
 * or trailing non-numerical (alpha) characters attached to them.

 *
 * A Locale can also be optionally supplied so to use whatever decimal symbol
 * that is desired otherwise, the decimal symbol for the system's current
 * default locale is used.
 *
 * @param inputString (String) The supplied string to extract all the numbers
 * from.

 *
 * @param desiredLocale (Optional - Locale varArgs) If a locale is desired for a
 *               specific decimal symbol then that locale can be optionally
 *               supplied here. Only one Locale argument is expected and used
 *               if supplied.

 *
 * @return (String[] Array) A String[] array is returned with each element of
 *               that array containing a number extracted from the supplied
 *               Input String in the order of occurrence. If the supplied Input
 *               String was found to be null or empty then a 0 length String[]
 *               Array is returned.
 */
public static String[] getNumbersFromString(String inputString, java.util.Locale... desiredLocale) {
    if (inputString == null || inputString.isEmpty()) {
        return new String[] {}; // Return a 0 length String Array.
    }
    // Get the decimal symbol the the current system's locale.
    char decimalSeparator = new java.text.DecimalFormatSymbols().getDecimalSeparator();

    /* Is there a supplied Locale? If so, set the decimal
       separator to that for the supplied locale       */
    if (desiredLocale != null && desiredLocale.length > 0) {
        decimalSeparator = new java.text.DecimalFormatSymbols(desiredLocale[0]).getDecimalSeparator();
    }
    /* The first replaceAll() removes all dashes (-) that are preceeded
       or followed by whitespaces. The second replaceAll() removes all
       periods from the input string except those that part of a floating
       point number. The third replaceAll() removes everything else except
       the actual numbers. */
   return  inputString.replaceAll("\\s*\\-\\s{1,}","")
                      .replaceAll("\\.(?![\\d](\\.[\\d])?)", "")
                      .replaceAll("[^-?\\d+" + decimalSeparator + "\\d+]", " ")
                      .trim().split("\\s+");
}

How you might use this method:
String filePath = "C:/name/textFile8a.txt";
String[] numbersArray = {};
// Get the decimal character used in the current System.
char decimalSeparator = new java.text.DecimalFormatSymbols().getDecimalSeparator();

// 'Try With Resources' used to to auto-close the reader and free resources.
try (java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.FileReader(filePath))) {
    String line;
    int lineCounter = 0;
    while ((line = reader.readLine()) != null) {
        lineCounter++;
        System.out.println("File Line #" + lineCounter + " contains:");
        System.out.println("======================");

        line = line.trim();
        // Skip blank lines (if any).
        if (line.isEmpty()) {
            continue;
        }
        numbersArray = getNumbersFromString(line);  // ****

        /* Print the number(s) extracted from the file line
           to the Console Window...         */
        for (String strgValue : numbersArray) {
            // Do what you want with the numerical values, for example:
            // Is this particular number a floating point value?
            if (strgValue.contains(Character.toString(decimalSeparator))) {
                // Yes it is...
                double dblValue = Double.parseDouble(strgValue);
                System.out.println("Extracted: -> " + dblValue);
            }
            else {
                //Nope..so it must be a Integer.
                int intValue = Integer.parseInt(strgValue);
                System.out.println("Extracted: -> " + intValue);
            }

            // Or just print them all out...
            // System.out.println(strgValue);
        }
        System.out.println();
    }
}
catch (FileNotFoundException ex) {
    System.out.println("File could not be found!");
}
catch (IOException ex) {
    System.err.println("OIException: -> " + ex.getMessage());
}

If the text file contained:
This is the #1 line.
This is version2.45 of the 2nd line
abcd4256.4efgha67klmn-56.2opqr-12stuvw666.78.
777 535 55 88 999
-56.765
dsh8kuebw9

and you run this file through the above code, the Console Window will display:
File Line #1 contains:
======================
Extracted: -> 1

File Line #2 contains:
======================
Extracted: -> 2.45
Extracted: -> 2

File Line #3 contains:
======================
Extracted: -> 4256.4
Extracted: -> 67
Extracted: -> -56.2
Extracted: -> -12
Extracted: -> 666.78

File Line #4 contains:
======================
Extracted: -> 777
Extracted: -> 535
Extracted: -> 55
Extracted: -> 88
Extracted: -> 999

File Line #5 contains:
======================
Extracted: -> -56.765

File Line #6 contains:
======================
Extracted: -> 8
Extracted: -> 9


text:
Q: O notation and merging two already sorted arrays I've been told to merge two already sorted arrays, of different sizes, A and B into an array, C in linear time.
By linear time, I understood that the time complexity of this algorithm has to be O(n). Later on, I was also told to perform sorting while merging the arrays.
One idea I had was to create an algorithm where you have two pointers in both arrays, pointing at the smallest element. The smallest element which is pointed at would go into the new array. When one array is exhausted, the remaining elements of the other array are copied into the new array.
Since I just started programming a few months ago, I have found this difficult to implement and hence I decided to perform Merge Sort (MS) since it's the most similar to the above-mentioned algorithm. However, I'm concerned with the time complexity of MS itself - O(nlogn)
However, given that the two arrays would be already sorted, would the time complexity for MS be reduced or will it remain the same?
Thanks in advance.

A: Your task is to implement the merge phase of the mergesort algorithm. mergesort has a complexity of O(N.log(N)) to sort the dataset, but each merge phase takes linear time proportional to the length of the merged set.
Here is pseudo code for this:
merge(array a, array b into array c)
    int i = 0, j = 0, k = 0;
    while (i < len(a) and j < len(b)) {
        if (a[i] <= b[j]) {
            c[k++] = a[i++];
        } else {
            c[k++] = b[j++];
        }
    }
    while (i < len(a)) {
        c[k++] = a[i++];
    }
    while (j < len(b)) {
        c[k++] = b[j++];
    }
}

The complexity is linear as each step in each of the loops copies an element into the c array, for a total of len(a) + len(b) steps.

A:
merge two already sorted arrays, of different sizes, A and B into an
array, C in linear time.

int *mergeArrays(const int *array1, const int *array2, size_t size1, size_t size2, int asc)
{
    int *result = malloc((size1 + size2) * sizeof(*array1));
    size_t index1 = 0, index2 = 0;
    size_t i;

    for(i = 0; i < size1 + size2 && index1 < size1 && index2 < size2; i++)
    {
        if(asc)
        {
            if(array1[index1] > array2[index2]) result[i] = array2[index2++];
            else result[i] = array1[index1++];
        }
        else
        {
            if(array1[index1] > array2[index2]) result[i] = array2[index2++];
            else result[i] = array1[index1++];
        }
    }
    if(index1 == size1) memcpy(result + i, array2 + index2, sizeof(result) * (size2 - index2));
    if(index2 == size2) memcpy(result + i, array1 + index1, sizeof(result) * (size1 - index1));
    return result;
}

https://godbolt.org/z/PY8Ysv319
int cmpfunc (const void * a, const void * b) {
   return ( *(int*)a - *(int*)b );
}

void sort(int *array, size_t size)
{
    qsort(array, size, sizeof(array[1]), cmpfunc);
}

int *mergeArrays(const int *array1, const int *array2, size_t size1, size_t size2, int asc)
{
    int *result = malloc((size1 + size2) * sizeof(*array1));
    size_t index1 = 0, index2 = 0;
    size_t i;

    for(i = 0; i < size1 + size2 && index1 < size1 && index2 < size2; i++)
    {
        if(asc)
        {
            if(array1[index1] > array2[index2]) result[i] = array2[index2++];
            else result[i] = array1[index1++];
        }
        else
        {
            if(array1[index1] > array2[index2]) result[i] = array2[index2++];
            else result[i] = array1[index1++];
        }
    }
    if(index1 == size1) memcpy(result + i, array2 + index2, sizeof(result) * (size2 - index2));
    if(index2 == size2) memcpy(result + i, array1 + index1, sizeof(result) * (size1 - index1));
    return result;
}

int main(void)
{
    srand(time(NULL));
    size_t size1 = rand() % 20, size2 = rand() % 20;
    int *mergedArray;

    if(size1 < 5) size1 += 5;
    if(size2 < 5) size2 += 5;

    int array1[size1], array2[size2];

    for(size_t i = 0; i < size1; i++)
        array1[i] = rand();
    for(size_t i = 0; i < size2; i++)
        array2[i] = rand();
    sort(array1, size1);
    sort(array2, size2);

    for(size_t i = 0; i < size1; i++)
        printf("array1[%2zu] = %d\n", i, array1[i]);
    for(size_t i = 0; i < size2; i++)
        printf("array2[%2zu] = %d\n", i, array2[i]);

    mergedArray = mergeArrays(array1, array2, size1, size2, 1);
    for(size_t i = 0; i < size2 + size1; i++)
        printf("result[%2zu] = %d\n", i, mergedArray[i]);
}

You need to add memory allocation checks, NULL pointer checks etc.


text:
Q: JavaMail - setReplyTo (list) Using JavaMail I would do something like the following to send replayTo more one email.
I've tried creating an array and adding an address to the array. I can't just add the list as the setReplyTo takes a string
   message.setReplyTo( listOfAddresses)

I have the following:
            String[] mailAddressTo = new String[3];
        String abb = user.getStoreAbbreviation();
        mailAddressTo[0] = abb + "test1@test.com" + ",";
        mailAddressTo[1] = abb + "test2@test.com" + ",";
        mailAddressTo[2] = abb + "test3@test.com";
        InternetAddress[] mailAddress_TO = new InternetAddress[mailAddressTo.length];
        for (int i = 0; i < mailAddressTo.length; i++) {
            mailAddress_TO[i] = new InternetAddress(mailAddressTo[i]);
        }
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

        // this line worked fine   to use the replyTo message.setReplyTo(new InternetAddress("test@test.com"));
                         //same list worked fine for the seTo   message.setTo(mailAddressTo);

tried this,
message.setReplyTo(new InternetAddress[]
                          {new InternetAddress(mailAddressTo)});

how could I pass the list?
Any help?

A: Looks like this is a limitation of MimeMessageHelper.  Try:
message.getMimeMessage().setReplyTo(mailAddress_TO);


text:
Q: Add-ins are disabled while creating a meeting in office 365 group calendar in outlook 2016 I am following this Article to create a new meeting in Office 365 group calendar using Outlook 2016(on Windows 10), But all the add-ins are disabled in outlook 2016 native when using group calendar. The add-ins works fine in web outlook for group calendar and for regular user calendar in outlook 2016 native as well.
Our applications helps to create structured agenda for a meeting but since the add-in is disabled we cant use the app in group calendar using Outlook 2016 native. Here is the screen shot.

This used to work fine earlier, Do we need to enable some settings so that these add-ins and enabled or is it not supported any more?
Would appreciate if someone can points me to the right direction here.

A: Add-ins in shared mailboxes are not supported. The fact that you are able to see them in OWA is a bug, since they only work partially (EWS and REST API do not work).
We plan to make the experience consistent with outlook desktop and the fix is on our backlog. The fix is going to be that, for shared Mailboxes, Add-ins will not show up in OWA as well.
We track Outlook add-in feature requests on our user-voice page. Please add your request there.
Feature requests on user-voice are considered when we go through our planning process.
[Outlook Add-ins Engineering Team]


text:
Q: Datetime column to list column of parts I have a tibble with a date column:
df <- structure(list(date = structure(c(1489494191.81966, 1489494125.153,
    1489494058.48633, 1489493991.81966, 1489493925.153, 1489493858.48633,
    1489493791.81966, 1489493725.153, 1489493658.48633, 1489493591.81966
    ), class = c("POSIXct", "POSIXt"), tzone = "")), .Names = "date", class = c("tbl_df",
    "tbl", "data.frame"), row.names = c(NA, -10L))

df

# A tibble: 10 × 1
                  date
                <dttm>
1  2017-03-14 13:23:11
2  2017-03-14 13:22:05
3  2017-03-14 13:20:58
4  2017-03-14 13:19:51
5  2017-03-14 13:18:45
6  2017-03-14 13:17:38
7  2017-03-14 13:16:31
8  2017-03-14 13:15:25
9  2017-03-14 13:14:18
10 2017-03-14 13:13:11

which I would like to tranform in into a list column with lists of the parts (year, month, day, hour, minutes, seconds), something like:
# A tibble: 10 × 1
                     result
                     <list>
1  list(2017,3,14,13,23,11)
2  list(2017,3,14,13,22,5)
3  list(2017,3,14,13,20,58)
4  list(2017,3,14,13,19,51)
5  list(2017,3,14,13,18,45)
6  list(2017,3,14,13,17,38)
7  list(2017,3,14,13,16,31)
8  list(2017,3,14,13,15,25)
9  list(2017,3,14,13,14,18)
10 list(2017,3,14,13,13,11)

I've tried a bunch of string split strategies but they are very inefficient (actual df is massive). The components of the list need to be integer or numeric in the end.
Is there a clever way?
EDIT:
This is what I'm doing now but it doesn't seem to scale that well:
library(lubridate)
library(purrr)

df %>%
  transmute(y = year(date),
            m = month(date),
            d = day(date),
            hh = hour(date),
            mm = minute(date),
            ss = second(date)
         ) %>%
  by_row(c, .to = "result") %>%
  select(result)

# A tibble: 10 × 1
       result
       <list>
1  <list [6]>
2  <list [6]>
3  <list [6]>
4  <list [6]>
5  <list [6]>
6  <list [6]>
7  <list [6]>
8  <list [6]>
9  <list [6]>
10 <list [6]>

A: You can use library(lubridate):
library(lubridate)

y <- year(df$date)
m <- month(df$date)
d <- day(df$date)
h <- hour(df$date)
min <- minute(df$date)
s <- as.integer(second(df$date))

and then combine to a list.
res <- lapply(1:length(y), function(x){

  return(c(y[x], d[x], d[x], h[x], min[x], s[x]))

})

tibble::tibble(res)

A: You can do it in one line of code with data.table as:
DT[, unclass(as.POSIXlt(date))][, .(year+1900, mon, mday, hour, min, sec)]
Convert your data.frame to data.table and date to POSIXlt format.
DT <- as.data.table(df)
DT[, unclass(as.POSIXlt(date))][, ':=' (year=year+1900, mon=mon+1, sec=floor(sec)) ][, .(year, mon, mday, hour, min, sec)]

This chains the operations so the result looks like:
   year mon mday hour min sec
 1: 2017   3   14    7  23  11
 2: 2017   3   14    7  22   5
 3: 2017   3   14    7  20  58
 4: 2017   3   14    7  19  51
 5: 2017   3   14    7  18  45
 6: 2017   3   14    7  17  38
 7: 2017   3   14    7  16  31
 8: 2017   3   14    7  15  25
 9: 2017   3   14    7  14  18
10: 2017   3   14    7  13  11

This is probably the fastest way in R to process millions of records splitting the date in the way you intended.


text:
Q: Searching json for a specific value I'm attempting use Python 3 to search through json for specific variables. The results usually look something like this.
[
  {
    "string": "00002000",
    "existedPrior": true
  },
  {
    "string": "00002001",
    "existedPrior": false
  },
  {
    "string": "00002002",
    "existedPrior": true
  },
  {
    "string": "00002003",
    "existedPrior": true
  },
  {
    "string": "00002004",
    "existedPrior": false
  }
]

The goal of this script would be to search these values for where "existedPrior" is false, then take the string from that value and insert it into an array. I could then later take the values of the array and re-query them against another endpoint for more data.
From what I've gathered, this is kind of close to what I'm hoping to do, but isn't actually getting me there.
import json
import requests

q = 'https://website.com/api/var'
r = requests.get(url=q)

strings = []

data = r.json()
i = 0

for item in data:
    if item['existedPrior'] == 'false':
        i += 1
        strings.append(item['string'])
        print(item['string'])
    else:
        break

print("New additions: ", i)

It's my understanding that json and python don't share the same "definition" of boolean, and this causes trouble. I read elsewhere on stackoverflow on how to handle this, but it involved json.dumps and json.loads and all sorts of messy bits that I wasn't 100% sure were needed.
As an aside, would it be better to just convert the json into a python dictionary and search from there?

A: Consider using enumerate:
for index, value in enumerate(data):
    if value["existedPrior"] == False:
        string.append(data[index]['string'])


text:
Q: How to read MS Teams version How to read MS Teams full version with major and minor version details in a C# code? I hope this statement is self explanatory. Let me know if this does not explain the question clearly.

A: It looks like Teams.exe is in the Microsoft\Teams\Current folder in local application data.
You need to get the product version of the VersionInfo, so this should do the trick:
var appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo($@"{appData}\Microsoft\Teams\current\teams.exe");
var version = myFileVersionInfo.ProductVersion;


text:
Q: Alpine: Incomplete maildomain How do I set the maildomain for Alpine?
(I'm on CentOS 7.)
It gives me this error and beeps at me twice when starting.
[Incomplete maildomain "fsphub".]

[Return address in mail you send may be incorrect.]

hostname returns the full domain. I found this page
http://www.washington.edu/alpine/tech-notes/config.html
But it's so dense it's completely useless to search for 'domain' or 'maildomain'

quell-maildomain-warning
*
  When your configuration is set up so that your domain name contains no dots, it is usually a configuration error.
  By default, Alpine will warn you about this when you start it up.
  You will see a warning message that looks like
*
*
Incomplete maildomain "<domain>".

  If this feature is set, the warning is turned off.
  This feature is displayed as "Suppress Maildomain Warning".

That doesn't tell you how to fix it! The top makes reference to /usr/local/lib/pine.conf but that file doesn't exist.

A: In ~/.pinerc look for feature-list= and make it
    feature-list=quell-maildomain-warning

You can also use the config editor in alpine, where it is listed as "Suppress Maildomain Warning".
That's assuming you want to use a user-domain that alpine thinks is incomplete.  (E.g. for peer-to-peer email).  If you were asking how to set it in alpine, select 'Setup' / 'Config' and it is the 2nd config item.


text:
Q: How 'best' to return SQLite records by most recent date of report updates for submitted reports that are not closed I have two tables, one with 'reports' and another with 'report updates'.  I want to show the most recent update date for reports that have not been closed, and the other 'Reports' information.
I have seen similar questions but am not sure if going that route is the best way. I had tried doing it with one table and I think I got it to work but two tables seems like the proper way.
I am using SQLite with Python 3.7.
Table: [Reports]
+------------------+------------+----------------------------+--------------------------+
| ClientName       | Report_ID  | Submission_Date            | Closed_Date              |
+------------------+------------+----------------------------+--------------------------+
| JoneBob          | 10010      | 2014-12-09 11:53:40.423    |                          |
| TrumHar          | 10011      | 2014-11-09 11:53:40.423    |                          |
| JoneBob          | 10012      | 2014-10-09 11:53:40.423    | 2014-10-20 04:00:00.000  |
+------------------+------------+----------------------------+--------------------------+

Table: [Report_Updates].
+------------------+----------------------------+
| Report_ID        | Follow_Up_Date             |
+------------------+------------+---------------+
| 10010            | 2014-12-10 11:53:40.423    |
| 10011            | 2014-11-11 11:53:40.423    |
| 10012            | 2014-10-14 11:53:40.423    |
| 10010            | 2014-12-12 11:53:40.423    |
| 10011            | 2014-11-14 11:53:40.423    |
| 10012            | 2014-10-18 11:53:40.423    |
| 10010            | 2014-12-13 11:53:40.423    |
| 10011            | 2014-11-15 11:53:40.423    |
| 10012            | 2014-10-21 11:53:40.423    |
+------------------+----------------------------+

Desired results:
+------------------+------------+----------------------------+--------------------------+
| ClientName       | Report_ID  | Submission _Date           | Follow_Up_Date           |
+------------------+------------+----------------------------+--------------------------+
| JoneBob          | 10010      | 2014-12-09 11:53:40.423    | 2014-12-13 11:53:40.423  |
| TrumHar          | 10011      | 2014-11-09 11:53:40.423    | 2014-11-15 11:53:40.423  |
+------------------+------------+----------------------------+--------------------------+

A: You need the maximum aggregation of Follow_Up_Date grouped by ClientName and Report_ID :
SELECT ClientName, r.Report_ID,
       MIN(Submission_Date) AS Submission_Date,
       MAX(Follow_Up_Date) AS Follow_Up_Date
  FROM Reports r
  JOIN Report_Updates ru
    ON ru.ClientName = r.ClientName
 WHERE Closed_Date IS NULL
 GROUP BY ClientName, Report_ID


text:
Q: jQuery click event requires double click to work I actually got some problems with my script: indeed it needs 2 clicks to work in a click event. The script is this:
  $('td#td_new').live('click', function() {
    $.ajax({
    type: 'GET',
    url: 'add_hobby.php',
    data: { hobby: $('#ricerca_interests').val() },
     success: function(msg) {
        nuovo_hobby="

"+$('#ricerca_interests').val()+'

';
        $(nuovo_hobby).appendTo("#interessilista");

         $('tr#new_hobby').hide().remove();

        },
    error: function() {alert("Error. Try later.");}
});

   });

A: As of jQuery 1.7, the .live() method is deprecated. you should Use .on() to attach event handlers.
it doesn't seems that your code generate something that can cause a second click need... but try changing-
$('td#td_new').live('click', function() {
to
$(document).on('click','#td_new', function() {
then open firebug or add a console.log('something') in the success: part - and make sure that the ajax request finishes as wanted and not continuing to run.
other then that we need some more code...
have fun.
EDIT:
I tried to understand what you are trying to do according to the code you upload, but
there is noway to test it, so here are some insights for you:

*

*Include your source scripts (jquery + UI etc) in the head section.

*Remove jquery.min... source - you don't need it because you include the full script any way.

*I recommend upgrading to jquery 1.9... you are using 1.7.2

*When using same identifier over different elements you should use class not id to declare them.

*I recommend you to attach the click event to the div add_hobby as a class and not to the td.

Here is a small demo of the usage of on() and appending code to your page:
jsfiddle Demo
Now feel free to direct me to your exact problem.


text:
Q: What do excel xml cell attribute values mean? Looking at the xml of an excel spreadsheet, I see these cells under sheetData/row:
<c r="T1" s="23" t="s"><v>17</v></c>
<c r="AP1" s="98"><v>28</v></c>

By looking at the spreadsheet, I can see that the first cell is a string (which I can look up in the sharedStrings file), and I know that the second one is the value "28", from which I hypothesise that if a cell has the attribute t="s", it is a string, otherwise it is a value. Is this correct?
I am guessing that the r, s, and t stand for 'row', 'style', and 'type', but can someone clarify for me what they mean and what the possible values for them are? E.g, I see some cells with the attribute t="str", is that the same as "s" or does it mean something special?
I couldn't find any documentation or specification for the excel xml files, so if such a thing exists it would be helpful to be pointed in it's direction.

A: *

*r = Reference

*s = Style Index

*t = Cell Data Type

The documentation for the Cell class is here
The possible cell data types are:

*

*b - boolean

*d - date in ISO8601 format

*e - error

*inlineStr - string that doesn't use the shared string table

*n - number

*s - shared string

*str - formula string

These values are in section 18.18.11 of the ECMA-376 standard which can be found here (specifically they are on pages 2442-2443 of the PDF file in the ECMA-376 4th edition part 1 download)
Looking at the XML schema later in that PDF file (page 3912, line 2301), the use of the t attribute is optional and the default value is n - i.e. a number

Part 1 of the 5th edition of the ECMA-476 spec was released in 2016. The equivalent page references for the 5th edition are: page 2451 for the documentation of ST_CellType and page 3928, line 2301 for the ST_CellType entry in the XML schema

A: have a look at Open XML SDK. Its a good starting point for what your looking for


text:
Q: Output Iterator in SuiteScript Map/Reduce Summarize Function I'm working on a map/reduce script to handle some automated billing processing. I run a search for invoices in the GetInput stage, group them by customer in the Map stage, and then create the payments in the Reduce stage. However, in the Summarize stage, only one key/value pair ever exists. So, I created a dummy test script to play with the functionality and figure it out, and kept running into the same problem.
Here's what I have for the testing script:
define(['N/search'], (search) => {

const getInputData = (inputContext) => {
    let filt = [
            ["trandate","on","3/29/2022"]
        ,   "and"
        ,   ["mainline","is","T"]
    ];
    let cols = [
            search.createColumn({ name : "tranid" })
        ,   search.createColumn({ name : "entity" })
        ,   search.createColumn({ name : "total" })
    ];
    let results;
    try {
        // custom search wrapper
        results = getSearchResults("invoice", filt, cols);
    }
    catch (err) {
        log.error({ title : "Error encountered retrieving invoices" , details : err });
    }

    return results;
}

const map = (mapContext) => {
    try {
        let data = JSON.parse(mapContext.value);
        let output = { key : "" , value : data };
        let rand = randomInt(0, 1); // custom random number generator
        if (rand === 0) {
            output.key = "FAILURE";
        }
        else {
            output.key = "SUCCESS";
        }
        mapContext.write(output);
    }
    catch (err) {
        log.error({ title : "Map Stage Error" , details : err });
    }
}

const reduce = (reduceContext) => {
    reduceContext.write({
            key : reduceContext.key
        ,   value : JSON.stringify(reduceContext.values)
    });
}

const summarize = (summaryContext) => {
    summaryContext.output.iterator().each((key, value) => {
        log.audit({ title : `summary -- ${key} -- ${typeof value}` , details : value });
    });
}

return {getInputData, map, reduce, summarize}

});

By all accounts, the summary logging should have two key entries to report, but only ever has one. In the test I've tried it both by marking values as either SUCCESS or FAILURE in the Map stage and then just passing it through the Reduce stage, and also by passing the values through the Map stage to be marked as SUCCESS or FAILURE in the Reduce stage and then passed on with the invoice record ID as the key. No matter what, the output iterator in the Summarize stage only ever reports back a single key. I've had this work correctly in one particular situation, but for the life of me I can't figure out what's different/wrong.
Any insights? Otherwise the only way I can think of to be able to propagate necessary data is to utilize the 'N/cache' module, which does work pretty well but feels like it should be unnecessary.

A: My understanding is that you need to return true; from the each() callback function, or it will stop processing.
const summarize = (summaryContext) => {
    summaryContext.output.iterator().each((key, value) => {
        log.audit({ title : `summary -- ${key} -- ${typeof value}` , details : value });
        return true;
    });
}

A: I handle errors in MP script by this way
summarize: function summarize(summarizeContext) {
        function handleErrorIfAny(summary)
        {
            var mapSummary = summary.mapSummary;
            var reduceSummary = summary.reduceSummary;

            handleErrorInStage('map', mapSummary);
            handleErrorInStage('reduce', reduceSummary);
        }
        function handleErrorInStage(stage, summary)
        {
            summary.errors.iterator().each(function(key, value){
                nLog.error('Failure in key ' + key, value);
                return true;
            });
        }
        handleErrorIfAny(summarizeContext);
    }


text:
Q: React Router v4 component transition with ReactCSSTransitionGroup add-on I am trying to do a very simple component opacity transition in react. I am using the ReactCSSTransition group to perform this and I believe I have set things up correctly but it does not seem to be working. I would appreciate any help on this please see below my codepen:
let {BrowserRouter,Link,Route} = ReactRouterDOM;

let Router = BrowserRouter;

let ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;

class Artwork extends React.Component {

render() {
return (

Art

  );
 }
}

class Home extends React.Component {
render() {
return (

Home

  );
 }
}

class User extends React.Component {

render() {
return (

The User Page

User ID:

<Link to="/user/artwork">Artwork</Link>

        <Route path="/user/artwork" component={Artwork}/>

  );
 }
}

 class App extends React.Component {

 render() {
 return (

  <Router>

<Link to="/user">User</Link>

<Link to="/home">Home</Link>

                  <ReactCSSTransitionGroup
                     transitionName="example"
                     transitionAppear={true}
                     transitionAppearTimeout={1500}>
                    <Route path="/" exact component={Home}/>
                    <Route path="/home" exact component={Home}/>
                    <Route path="/user" component={User}/>
                  </ReactCSSTransitionGroup>

    </Router>

   );
  }

 }

ReactDOM.render(
<App />,
document.getElementById('root')
);

CSS
.example-appear {
  opacity: 0.01;
}

.example-appear.example-appear-active {
  opacity: 1;
  transition: opacity 1500ms ease-in;
}

React route transitions
Thank you

A: You need to wrap each of your routed components in <CSSTransitionGroup> so you can create higher order functions to return component which is wrapped in <CSSTransitionGroup>. For ex. check the below codepen, I updated it with animation.
http://codepen.io/anon/pen/ZKENXy?editors=0111
For higher order components, you can head over here.
https://facebook.github.io/react/docs/higher-order-components.html


text:
Q: Каррирование с использование apply/bind/call Помогите пожалуйста пересмотрел уже ролики по каррированию, apply/bind/call, замыканиям. Вроде все понятно но как решить задачу никак не могу додуматься.
Нужно при помощи apply/bind/call написать функцию, которая оборачивает другую функцию так, чтобы результатом была тоже функция, но еще могла принимать заданное кол-во аргументов.
Функция принимает на вход другую функцию и число аргументов которое необходимо собрать чтобы передать в функцию которая была передана первым аргументом.
function watchArgs(fn, argumentsLength) {
  // Реализовать данную функцию
}

function test1(a, b, c) {
  return a + b + c;
}
function test2(a, b, c, d) {
  return a + b + c + d;
}

let result;

const t1 = watchArgs(test1, 3);
result = t1(); // все еще функция, необходимо учитывать если аргументы не были переданы
result = t1(1, 2); // все еще функция
result = t1(3); // 6 - результат выполнения функции test1 с аргументами 1, 2 и 3

const t2 = watchArgs(test2, 4);
result = t2(1);
result = t2(1);
result = t2(1, 1); // 4
result = t2(5); // 4

A: Использован только fn.apply(контекст, массив) — Он нужен, чтобы вызвать функцию, передав ей элементы массива или другого итерируемого объекта как аргументы.

function watchArgs(fn, length) {
  let args_cache = []; // Хранилище переданных аргументов при всех вызовах.

  return function _self() {
    if (args_cache.length == length) {
      // Набрано достаточно аргументов?
      // Вызов исходной функции, и на выход.
      return fn.apply(null, args_cache);
    }

    for (let i = 0; i < arguments.length; i++) {
      args_cache.push(arguments[i]);

      if (args_cache.length == length) {
        return fn.apply(null, args_cache);
      }
    }

    return _self; // Аргументов не хватает, возвращает саму себя.
  }
}

/***/
function test1(a, b, c) {
  return a + b + c;
}

function test2(a, b, c, d) {
  return a + b + c + d;
}

let result;

const t1 = watchArgs(test1, 3);
result = t1();
result = t1(1, 2);
console.log(result = t1(3));

const t2 = watchArgs(test2, 4);
result = t2(1);
result = t2(1);
console.log(result = t2(1, 1)); // 4
console.log(result = t2(5)); // 4

arguments, а заодно и apply (т.к. контекст не сохрняется), можно заменить на ... ( spread )


text:
Q: Django save image temporarily for user process in template I figure the title is somewhat confusing but that's the best I came up with.
I have an upload image form which I want to process the image file further after the user upload it (with the user - cropping using jquery) rather than put it on the model imagefield right away.
Meaning, I need to save the image temporarily so I can present it to the user in a template with the jquery crop plugin.
My current solution is ugly, I made a model called TempImageToProcess which I save the image to and from that I re-present it to the user to further process.
So my question is: is there any elegant way to save image temporarily in Django?

A: You should check TemporaryFileUploadHandler in this section.
Look this SO question for a clean up afterwards if any unexpected error occur or validation errors.
Hope this will lead you some where.


text:
Q: Expandable, non-rectangular CSS button? After much poking around online, I've found lots of advice and examples for using CSS to style submit buttons, but they all result in rectangular buttons.  I want to make a non-rectangular button that automatically sizes itself to fit the button legend.  Specifically, I want the button to look like this (plus or minus the rounded corners):

Any suggestions?

A: Totally possible with border radius, but you will have to submit with JavaScript instead of the <button> element.
For instance:
.icon {
background-color: lightblue;
width: 100px;
padding: 4px;
margin: 10px;

border-top-left-radius: 10px;
-moz-border-radius-topleft: 10px;
border-bottom-left-radius: 10px;
-moz-border-radius-bottomleft: 10px;

border-top-right-radius: 60px 22px;
-moz-border-radius-topright: 60px 22px;
border-bottom-right-radius: 60px 22px;
-moz-border-radius-bottomright: 60px 22px;
}

Makes:

See it live:
http://jsfiddle.net/9zamA/

A: You could use the CSS border triangle trick: http://css-tricks.com/snippets/css/css-triangle/
You could use svg.


text:
Q: How should I specify a tab in a website to read with webread()? Considering this web page: http://tsetmc.com/Loader.aspx?ParTree=151311&i=778253364357513 , that I like to read the contents of the one of the tabs on above of the page (most left violet tab that is written "حقیقی- حقوقی" on it for example. How should I specify that in my webread() function to go on that tab and read it's information?
Best regards.


text:
Q: What pain point does Intelligent Children Design Pattern solve? In absence of this pattern, downcasting is needed in the derived classes. My question is does this pattern solve only the problem of downcasting? And why is downcasting bad compared to the alternative offered by Intelligent Childrean Design Pattern?

A: Intelligent children is used when there are two base classes at the root of separate but related class hierarchies. For example Widget and WidgetRenderer are the base classes and ListBoxWidget needs to be used by the draw() method of the ListBoxWidgetRenderer. So the draw() method will want to downcast the Widget pointer.
Downcasting is generally frowned on, so every fresh reader will have to be convinced that it's okay in a given situation. With this pattern the right pointer is made available at the right type.


text:
Q: Spring JUnit Test I like to test my spring code:
@ContextConfiguration(locations = { "/applicationContext.xml" })
@Transactional()
public class Test {

    @Autowired
    MyDao dao;

    @org.junit.Test
    @Rollback(false)
    public void testSomething() throws Exception {
        MyEntity e = new MyEntity();
        dao.create(e);
    }
}

Running this test with eclipse (as an JUNIT test) just gives an Nullpointer-Exception.
What have I done wrong? Thx!

A: Just add @RunWith(SpringJUnit4ClassRunner.class) to your class:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext.xml" })
@Transactional()
public class Test {

    @Autowired
    MyDao dao;

    @org.junit.Test
    @Rollback(false)
    public void testSomething() throws Exception {
        MyEntity e = new MyEntity();
        dao.create(e);
    }
}

You need spring-test for that.

A: You can add a Transactional test base class like this
@ContextConfiguration(locations = "classpath*:applicationContext.xml")
public class IntegrateTestBase extends AbstractTransactionalJUnit4SpringContextTests {
}

Then wirite your test class
public class Test extends IntegrateTestBase {

    @Autowired
    MyDao dao;

    @org.junit.Test
    @Rollback(false)
    public void testSomething() throws Exception {
        MyEntity e = new MyEntity();
        dao.create(e);
    }
}

You need not write @ContextConfiguration and @Transcational in each test class