text:
Q: Aligning y-axis label with middle of subplot? I'm working with Matplotlib and have a large number of 1D heatmaps, each with their own label. However, the labels are misaligned with the plots and I cannot figure out to get this to work automatically.
Here's an MWE
import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(10, 1000)
dogs = ["woof", "bark", "bowwow"]
fig, axs = plt.subplots(10)
for i in range(10):
    axs[i].scatter(np.linspace(0, 1, 1000), np.linspace(0,1,1000)*0, 2000,
                     c=data[i, :], marker="|", cmap='inferno')
    axs[i].set_frame_on(False)
    axs[i].set_yticklabels([])
    axs[i].set_xticklabels([])
    axs[i].set_xticks([])
    axs[i].set_yticks([])
    axs[i].set_ylabel(dogs[i%3], rotation='horizontal')
plt.show()

I experimented with
    axs[i].yaxis.set_label_coords(x, y)

for various values of x and y, and nothing seems to work. I would prefer to have it align automatically, with the bottom of the text corresponding to the bottom of the individual plot.
Attached is an image showcasing the alignment issue.
Example

A: You could create your heatmaps via seaborn, and use yticklabels=[label_name] to set the labels. Rotating the labels to 0 degrees should have them nicely aligned.  Note that the data is expected to have a shape of 1xN.
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np

labels = ['Alkaid', 'Mizar', 'Alioth', 'Megrez', 'Phecda', 'Merak', 'Dubhe']
nrows = len(labels)
fig, axs = plt.subplots(nrows=nrows, figsize=(10, 5))

for ax_i, data_i, label_i in zip(axs, np.random.randn(nrows, 1, 100).cumsum(axis=2), labels):
    sns.heatmap(data=data_i, xticklabels=[], yticklabels=[label_i], cmap='inferno', cbar=False, ax=ax_i)
    ax_i.tick_params(axis='y', rotation=0, labelsize=22, length=0) # length means length of the tick mark
plt.tight_layout()
plt.show()

A: After a bit of playing around, I found that
axs[0].set_ylabel("Pseudotime", fontsize=12, rotation='horizontal', ha='right', va='center')

is sufficient for aligning the y-labels.


text:
Q: How to select a random image from the array list? I have an array of images
 selectImages = ['https://bootdey.com/img/Content/user_1.jpg', 'https://bootdey.com/img/Content/user_2.jpg', 'https://bootdey.com/img/Content/user_3.jpg'];

I need to show a random image in my html. I have following function to select the image:
pickImage = function () {
    var myImage = this.selectImages[Math.floor(Math.random() * 3)];
    return myImage;
};

Now in html i did {{pickImage}}. But I am getting error:
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'src: https://bootdey.com/img/Content/user_3.jpg'. Current value: 'src: https://bootdey.com/img/Content/user_2.jpg'.

A: myImage : 'loadingImage.jpeg';

ngAfterViewInit()
{
    this.pickImagefun();
}

pickImagefun = function () {
    this.myImage = this.selectImages[Math.floor(Math.random() * 3)];

};

now int html you can use  {{myImage }}.
You have to call your function in ngAfterViewInit.

A: You will have to put it one of the lifecycle hooks of angular. Either
       ngAfterContentChecked() - Respond after Angular checks the content projected into
       the directive/component.
Or
       ngAfterViewChecked() - Respond after Angular checks the component's views and child
       views / the view that a directive is in.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing textBox.text from event handler Can't seem to find an answer here for the life of me..
Anyhow, how can an event handler change Form's textBox.text?
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadExisting();
            //Do what ever you want with the data
            textBox2.Text = "test"; //alas, this doesn't work
        }

The event handler is created when a button is pressed
private void button3_Click(object sender, EventArgs e)
        {
                    serialPort1.PortName = comboBox1.Text;
                    serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
                    serialPort1.RtsEnable = true;
                    serialPort1.DtrEnable = true;
                    serialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
                    serialPort1.Open();
                }
            }

Any help is greatly appreciated

A: The DataReceivedHandler method is marked static, so it cannot access the instance member textBox2. Does removing static solve the problem?

A: The DataReceived is on it's own thread, you'll need to invoke the GUI in order to update the textbox.
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    string Data = serialPort1.ReadExisting();

    this.Invoke((MethodInvoker)delegate
    {
        textBox2.AppendText(Data);
    });
}


text:
Q: semaphore array initialization in java I am trying to create a semaphore array in java and initialize all semaphores to 1. I tried the following: private static Semaphore [] sem = new Semaphore [] {1,1,1,1,1};
But i get the error Type mismatch: cannot convert from int to Semaphore. How can i do this? I do not want to first declare and then initialize, it must be initialized when declared.
Thanks in advance

A: You are putting int values into a Semaphore array, hence the type mismatch. You need
private static Semaphore [] sem = new Semaphore [] {new Semaphore(1),
     new Semaphore(1), new Semaphore(1), new Semaphore(1), new Semaphore(1)};

A: I presume you would like to use Semaphore(int permits) constructor.
The only way to do that is as follows:
private static Semaphore [] sem = new Semaphore [] {
   new Semaphore(1),
   new Semaphore(1),
   new Semaphore(1),
   new Semaphore(1),
   new Semaphore(1)
};

Or using for loop (this approach will work perfectly fine if your array of Semaphore instances is much longer).
private static Semaphore [] sem = new Semaphore [5];
static {
    for(int i = 0; i < 5; i++) {
        sem[i] = new Semaphore(1);
    }
}

Also for loop would work perfectly fine if you have long number of semaphore permits not in sequence (or you would load permits from a configuration file) e.g.
private static Semaphore [] sem;

static {
    int [] semaphorePermits = {1,2,3,1,2,2,2,2,4,5,2,1,2,3,4,5,3,2,12,1,2,23,3};
    sem = new Semaphore[semaphorePermits.length];

    for(int i = 0; i < semaphorePermits.length; i++) {
        sem[i] = new Semaphore(semaphorePermits[i]);
    }
}

A: Are all semaphores going to represent permits over the same resource? In that case, you don't need an array, just a single Semaphore object, with a permit count of 5 or whatever. If you, on the other hand, have multiple resources, you can always add the semaphores to your array using a for loop.


text:
Q: Is it possible to connect and read data from OBD Bluetooth LE adapter using Android GATT interface? I am trying to read data from a obd2 Bluetooth LE adapter. I am able to connect to the adapter (Carista). I know this because onDescriptorWrite callback is called but I never get a response after sending a command using the write characteristic obtained from adapter's GATT service. I use the following command
mWriteCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
mWriteCharacteristic.setValue(cmdStr);
mBluetoothGatt.writeCharacteristic(mWriteCharacteristic)
However onCharacteristicRead is never called.
Am I doing something wrong? I've tried different variations of characteristics but to no avail.
Thanks in advance for your input.
@Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {

            if (status == BluetoothGatt.GATT_SUCCESS) {

                List<BluetoothGattService> services = gatt.getServices();
                for (BluetoothGattService service : services) {

                    if (service.getUuid().equals(SERVICE_UUID)) {

                        sharedPref.edit().putString(getString(R.string.paired_adapter_address),gatt.getDevice().getAddress()).apply();
                        mBluetoothGatt = gatt;
                        deviceState = DEVICE_STATE.CONNECTING;
                        mWriteCharacteristic = service.getCharacteristics().get(0);
                        mReadCharacteristic = service.getCharacteristics().get(1);

                        setCharacteristicNotification(mReadCharacteristic);
                        scanning = false;

                        Intent intent = new Intent("state");
                        intent.putExtra("message", MainActivity.MESSAGE_CONNECTING);
                        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
                        return;
                    }
                }
            }
            gatt.disconnect();
        }

public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.setCharacteristicNotification(characteristic, true);

        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(DESCRIPTOR_UUID);
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
    }

A: On my CARISTA, the first characteristic is the WRITE one, the 2nd is the READ one.
In general: You must probe the characteristics' properties instead of hardcoding them. There is no guarantee that the READ characteristic is always the first one and the WRITE characteristic is always the second one. In fact, it's not always necessary that the adapter exports the serial port over two distinct characteristics – sometimes it's just one.


text:
Q: Javascript pass value to asp.net   $(document).ready(function () {
    $("#MainContent_ddlFieldName").live("change", function () {
                 var id = $(this).val();
                 var name = $(this + "option:selected").text();

                 $('#<%= lblValue.ClientID %>').text(name);
                 $('#<%= lblType.ClientID %>').text(id);
             });
         });

<asp:Label ID="lblValue" runat="server" Text="" Visible="true"></asp:Label>
 <asp:Label ID="lblType" runat="server" Text="" Visible="true"></asp:Label>

protected void btnSearch_Click(object sender, EventArgs e)
        {
             string strValue = lblValue.Text;
             string strType = lblType.Text;
        }

Im using javascript and Asp.Net to get the value of a dropdownlist and put it in a label.
It actually show the text to the label and when i click a button or event i'm getting its previous value w/c is ""
Can anyone help me with this.
Thx

A: try to use hidden field
aspx page
<asp:HiddenField ID="hType" runat="server" ViewStateMode="Enabled" Value="" />
<asp:HiddenField ID="hValue" runat="server" ViewStateMode="Enabled" Value="" />
<asp:Label ID="lblValue" runat="server" Text="" Visible="true"></asp:Label>
<asp:Label ID="lblType" runat="server" Text="" Visible="true"></asp:Label>
<asp:Button Text="text" OnClick="btnSearch_Click" runat="server" />
<script type="text/javascript">
    $(document).ready(function () {
        $("#MainContent_ddlFieldName").live("change", function () {
            var id = $(this).val();
            var name = $(this + "option:selected").text();

            $('#<%= lblValue.ClientID %>').text(name);
            $('#<%= hValue.ClientID %>').val(name);
            $('#<%= lblType.ClientID %>').text(id);
            $('#<%= hType.ClientID %>').val(id);
        });
    });
</script>

code behind
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //server side code
        string strValue = hValue.Value;
        string strType = hType.Value;

    }


text:
Q: Getting total length of an index in each() I want to get an unknown (changing) # of rows from a table, between the 1st cell and the last 3. I'm using jQuery's each and don't know why $(this).length doesn't give the total length of the index.
jQuery:
$("#parent table:first tr").each(function(i){
    var  goodlng =  $(this).parent().children("tr").length -1;   //this works
    var badlng = $(this).length -1;                        //this doesn't! (always == -1)
});

Is the goodlng good practice? it seems like a hack to have to go to parent and then back to children.
Here is a jsfiddle (have console.log()) open.
Example HTML:

            unwanted 1

            wanted!

            unwanted2

tl;dr: Why doesn't $(this).length == $(this).parent().children("tr").length inside of an each function. and is there another better way of doing this.

A: Actually, this $(this).parent().children("tr").length is the correct way of handling things. this, in the context above is a reference to the tr node itself. tr.length = the length of the tr. tr.parent().children("tr"), on the other hand is a list of the node's siblings, so  tr.parent().children("tr").length is the number of siblings.

A: This is the context of EACH element, not all of them. Therefore, this is only ONE tr at a time. That is why the length does not have all the elements.

A: Your question says "cells", but it seems like you're trying to get the number of rows.
If you really want it inside the .each(), you could use the siblings()[docs] method and the andSelf()[docs] method.
$(this).siblings().andSelf().length

But if the rows aren't changing, why do it repetitively?
Or if they are changing, I'd just use the native rows property on the table to get the length.
var table = $("#parent table:first");

table.find('tr').each(function() {

    var len = table[0].rows.length;

});

A: The each() function is unaware of the collection of elements that it is working on. It is dealing with a single element at all times. Thats why when you go to the parent and ask for all children you get the right answer.
  $(this)

simply refers to the current tr element that you are dealing with, not a collection of them.


text:
Q: Reactjs can't return jsx within pure functional component 'ParseError: Unexpected token' I'm learning how to use Reactjs through a Net tuts series called 'Modern Web Apps with React and Redux'. Right now we're just covering the basics of react components, yet, for whatever reason, I can never return jsx from a pure function, use classes, or any other various methods of creating components I've found online.
Seeing as I've already tried many different methods of creating a component, my guess is that the error resides somewhere within how I use watchify and babelify.
Here is the error I get:
/home/michael/Documents/Web Dev/flaschard-app/src/app.js:33
return (

     ^
ParseError: Unexpected token

My index.html:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

My app.js:
const cards = (state, action) => {
    switch(action.type) {
        case 'ADD_CARD':
            let newCard = Object.assign({}, action.data, {
                score: 1,
                id: +new Date
            });

            return state.concat([newCard]);

        default:
            return state || [];
    };
};

const store = Redux.createStore(Redux.combineReducers({
    cards
}));

// store.subscribe(() => {
//  console.log(store.getState());
// });
//
// store.dispatch({
//  type: 'ADD_CARD',
//  data: {
//      front: 'front',
//      back: 'back'
//  }
// });

const App = (props) => {
    return (

Hello React!

);
};

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

and my package.json:
{
  "name": "flaschard-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.22.0",
    "babelify": "^7.3.0",
    "live-server": "^1.2.0",
    "watchify": "^3.9.0"
  },
  "devDependencies": {
    "tern-react": "^0.1.0"
  },
  "scripts": {
    "build": "watchify src/app.js -o public/bundle.js -t [babelify --presets [react es2015]]",
    "server": "cd public; live-server --port=1234 --entry-file=index.html"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Thank you!

A: Your problem is wrong watchify command syntax. You should separate square brackets in the command just like in examples to make babelify work:
watchify src/app.js -o public/bundle.js -t [ babelify --presets [ react es2015 ] ]


text:
Q: The perfect rack for a pool variant called 'Cutthroat' To give some background, the pool game 'Cutthroat' is played with three people, each person claiming the set of low balls (1-5), middle balls (6-10), or high balls (11-15). The goal of the game is to sink everyone else's balls, and to win by only having your own balls left on the table. (i.e. someone playing mid balls would sink all the low and high balls to win).
While racking up for a game, I was pondering whether or not it would be possible to have what I considered a 'perfect rack'. This would consist of there being only a single low, middle, and high ball in each 'sub-triangle' (triangle of only three balls) within the entire triangular rack. Is this possible to do?
Also, as I'm not the most mathematically educated, I feel it's worth noting that I'm not 100% sure what to classify this problem as, so I went with combinatorics. If someone would also like to share what field of mathematics this falls under I would appreciate that as well.

A: Is this the kind of configuration you are looking for ?


text:
Q: Pandas - Generate ID based on row values AND proximity of rows

id
dob
status
sex
work_code
work_cat
gross_income
dependent_cat
dependent_dob
preparer
city
new_id

1
1981
Married
MALE
1111
Government
15000
U
2001
Taxpayer
BOSTON
1

2
1981
Married
MALE
1111
Government
15000
U
2002
Taxpayer
BOSTON
1

3
1983
SINGLE
MALE
2222
Federal
20000
N
2009
Taxpayer
MIAMI
2

4
1983
SINGLE
MALE
2222
Federal
20000
N
2010
Taxpayer
MIAMI
2

5
1975
SINGLE
MALE
2222
Federal
12000
N/A
-
Taxpayer
NYC
3

6
1983
Married
MALE
2222
Federal
18000
U
2013
Taxpayer
NYC
4

7
1981
Married
MALE
1111
Government
12000
N
2005
Taxpayer
PORLAND
5

8
1981
Married
MALE
1111
Government
15000
N/A
-
Taxpayer
BOSTON
6

About the data
I've a .txt dataset with 1.6m rows that looks like this, sans the new_id column which I want to generate. Each row is a taxfiller and their dependent (unless dependent_cat is N/A). When a row is followed by an identical one (sans the two dependent_X columns), it is assumed that this is in fact the same household, but a different dependent within the household (and thus, I wish to generate new_id = 1 for both, so I can later collapse the dataset such that each row is a household, and there is a column that counts the dependents and whatnot).
What I've done
I have in fact generated household ID's in the real dataset, but I did not manage to incorporate the 'row proximity'. Turns out its quite important - got too many cases like the example of #1,2,8 being bunched up into the same household when they shouldn't be. Got too many 0 income households with a count of >10 dependents due to this.
What I propose
I've tried to think this through, and I came up with:
looping through each row,
assigning a new ID if dependent_cat is N/A,
otherwise, verify if the previous row is identical in all columns (except dependent_cat and dependent_dob)
if so, copy its new_id
otherwise, new_id = last assigned id +1
Why my proposal sucks - looking for alternatives
However I know that looping through 1.6m dataframe rows is not very pythonic. I might try it, but relying on it would be continuing my lazy approach to Python.
Is there any way that hashing could help me here? I've only found hashing which would make id #1 and id #8 end up with the same new_id - leaving me at my current status. I'd need hashing to 'reset' when it passes id #2, such that it doesn't assign id #8 their same new_id. I would also prefer, but not require, new_id to be  cardinal numbers as I've shown (such that max new_id, in the end, is the number of households in my dataset).
Related question: Pandas - Generate Unique ID based on row values

A: (i) Create a list from the column names that are relevant to identify households (basically, dropped "id", "dependent_dob" since one is unique for every entry and the other is the personal info of the dependent).
(ii) use shift to shift index by 1 and see if consecutive rows match for the columns identified in (i). The idea is, if there is any difference, then it's a different household; otherwise the same household. This will create a boolean Series.
(iii) Use cumsum on the outcome of (ii) and assign the outcome to 'new_id' column.
dep_id_cols = ['dob', 'status', 'sex', 'work_code', 'work_cat',
               'gross_income', 'dependent_cat', 'preparer', 'city']
df['new_id'] = df[dep_id_cols].ne(df[dep_id_cols].shift()).any(axis=1).cumsum()

Output:
   id   dob   status   sex  work_code    work_cat  gross_income dependent_cat  \
0   1  1981  Married  MALE       1111  Government         15000             U
1   2  1981  Married  MALE       1111  Government         15000             U
2   3  1983   SINGLE  MALE       2222     Federal         20000             N
3   4  1983   SINGLE  MALE       2222     Federal         20000             N
4   5  1975   SINGLE  MALE       2222     Federal         12000           NaN
5   6  1983  Married  MALE       2222     Federal         18000             U
6   7  1981  Married  MALE       1111  Government         12000             N
7   8  1981  Married  MALE       1111  Government         15000           NaN

  dependent_dob  preparer     city  new_id
0          2001  Taxpayer   BOSTON       1
1          2002  Taxpayer   BOSTON       1
2          2009  Taxpayer    MIAMI       2
3          2010  Taxpayer    MIAMI       2
4             -  Taxpayer      NYC       3
5          2013  Taxpayer      NYC       4
6          2005  Taxpayer  PORLAND       5
7             -  Taxpayer   BOSTON       6


text:
Q: Always returning a SMTP email address for Outlook Recipient I have seen a few posts on here where people are asking to find the recipient email address and are referred to the MAPI property : http://schemas.microsoft.com/mapi/proptag/0x39FE001E" . However, as some users have pointed our not all MAPI properties are guaranteed to be there. So I am looking to develop a function which finds the correct method to get this email address. For senders email address I am able to tell if its an exchange user and get back the SMTP email address. Is there a method on here to return this regardless of if MAPI is missing?
Here is what I have so far
Public Function RecipientSMTPEmailAddress(outRecip As Outlook.Recipient) As String

On Error GoTo MissingMAPIError
RecipientSMTPEmailAddress = outRecip.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x39FE001E")

Exit Function
MissingMAPIError:

RecipientSMTPEmailAddress = outRecip.Address

End Function

I am looking for a method similar to this used for the sender info:
 If OutMail.SenderEmailType = "EX" Then
      SenderInfo = OutMail.Sender.GetExchangeUser.PrimarySmtpAddress
 Else
      SenderInfo = OutMail.SenderEmailAddress
 End If

If there is a better way to ensure I get the SMTP email address I am all ears!
*Edited 9/23/2019 - New and Improved code to catch all recipient errors
Public Function RecipientSMTPEmailAddress(outRecip As Outlook.Recipient) As String

On Error GoTo MissingMAPIError

RecipientSMTPEmailAddress = outRecip.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x39FE001E")

Exit Function

MissingMAPIError:

RecipientSMTPEmailAddress = RecipientSMTPEmailAddressExchange(outRecip)

End Function
Public Function RecipientSMTPEmailAddressExchange(outRecip As Outlook.Recipient) As String

On Error GoTo MissingExchangeError

RecipientSMTPEmailAddressExchange = outRecip.AddressEntry.GetExchangeUser.PrimarySmtpAddress

Exit Function

MissingExchangeError:

RecipientSMTPEmailAddressExchange = ""

End Function

A: If the PR_SMTP_ADDRESS property is missing, use Recipient.AddressEntry.GetExchangeUser().PrimarySmtpAddrress (be prepared to handle nulls and exceptions).


text:
Q: Query optimisation in SQL Server The following is taking a long time to get executed. Considering each table has close to 50 million to 100 million rows, is there anything that I can do from the query side to get it optimized.It is a source table and involves huge data movements (insertion ranging in millions) every hour and is better off without indexes.I don't have the required access to get an execution plan from this server.
 DECLARE @var INT

 SELECT TOP 1 @var = s_type
 FROM s_shot
 WHERE s_type < 10000
 ORDER BY s_type DESC;

 WITH cte AS
 (
     SELECT
         sps_id,
         SUM(xin) xin,
         SUM(xout) xout
     FROM
         s_lock
     GROUP BY
         sps_id
)
SELECT
    A.[s_id], a.acc_id,
    B.[o_type],
    B.[o_id], B.[sec_id], B.[c_id],
    B.[style_type_id], [s_type],
    A.[end_date],
    B.[mv],
    b.xin + ISNULL(c.xin, 0) [xin],
    b.xout + ISNULL(c.[xout], 0) xout,
    b.accr_in + b.accr_inter [acc],
    b.accr_in, b.accr_inter,
    b.units
FROM
    s_shot a WITH (NOLOCK)
JOIN
    s_pos3 b WITH (NOLOCK) ON a.s_id = b.s_id
JOIN
    cte c ON b.sps_id = c.sps_id
WHERE
    b.is_sl = 1
    AND a.end_date > DATEADD(mm, -24, GETDATE())  -- 24 months

As you can see, I want to fetch the data of last 24 months. Is there any optimization that is possible in this query so as to bring down its execution time to manageable levels.
The create table scripts are provided below.
CREATE TABLE [dbo].[s_shot]
(
    [s_id] [int] IDENTITY(1,1) NOT NULL,
    [acc_id] [int] NULL,
    [s_type] [int] NULL,
    [end_date] [datetime] NULL,
    [recon] [tinyint] NULL,
    [is_pers] [tinyint] NOT NULL,
CONSTRAINT [PK_s_shot_1] PRIMARY KEY NONCLUSTERED
(
    [s_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[s_lock]
(
    [sps_id] [int] NOT NULL,
    [units] [decimal](18, 5) NULL,
    [accr_in] [decimal](18, 2) NULL,
    [xin] [decimal](18, 2) NULL,
    [xout] [decimal](18, 2) NULL,
    [lock_date] [date] NOT NULL,
    [accr_inter] [decimal](18, 2) NULL,
    [mv] [decimal](18, 2) NULL,
 CONSTRAINT [PK_s_lock] PRIMARY KEY CLUSTERED
(
    [sps_id] ASC,
    [lock_date] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[s_pos3]
(
    [sps_id] [int] IDENTITY(1,1) NOT NULL,
    [s_id] [int] NOT NULL,
    [o_type] [tinyint] NOT NULL,
    [o_id] [int] NOT NULL,
    [s_id] [int] NOT NULL,
    [c_id] [int] NOT NULL,
    [s_type_id] [int] NOT NULL,
    [units] [decimal](18, 5) NULL,
    [accr_income] [decimal](18, 2) NULL,
    [distr] [decimal](18, 2) NULL,
    [mv] [decimal](18, 2) NULL,
    [perf_stat] [smallint] NULL,
    [is_slv] [bit] NULL,
    [accr_inter] [decimal](18, 2) NULL,
    [perf_mtd] [decimal](18, 10) NULL,
    [xin] [decimal](18, 2) NULL,
    [xout] [decimal](18, 2) NULL,
    [a_s_type_id] [int] NULL,
 CONSTRAINT [PK_s_pos3] PRIMARY KEY NONCLUSTERED
(
    [sps_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

Any help is appreciated.
Edit: Updated indexing details


text:
Q: Is a sqlite3 online backup valid in a running transaction without the journal file I used the backup API of sqlite3 to create online backups of my sqlite3 databases as described in Example 2. Sqlite3 saves additionally to the database a journal file in case of a transaction to make the rollback possible. It seams as if this leads to problems if a backup is written, while a transaction is running.
So if a backup is created while a transaction is running, is the resulting backup still valid without a journal file? I already did some research, but could not find any information of what has to be done to ensure valid backups of an database. Has the journal file to be copied or does the backup API takes care of everything?

A: A backup uses the normal transacation mechanism to access the database, so it is not possible for the backup to be in an inconsistent state.
(When in journal rollback mode, the backup transaction would be blocked while somebody else is writing; when in WAL mode, the backup has the state before the write transaction began.)


text:
Q: Mutually recursive IO definitions I can write the following:
f :: [Int] -> [Int]
f x = 0:(map (+1) x)

g :: [Int] -> [Int]
g x = map (*2) x

a = f b
b = g a

main = print $ take 5 a

And things work perfectly fine (ideone).
However, lets say I want g to do something more complex than multiply by 2, like ask the user for a number and add that, like so:
g2 :: [Int] -> IO [Int]
g2 = mapM (\x -> getLine >>= (return . (+x) . read))

How do I then, well, tie the knot?
Clarification:
Basically I want the list of Ints from f to be the input of g2 and the list of Ints from g2 to be the input of f.

A: The effectful generalization of lists is ListT:
import Control.Monad
import Pipes

f :: ListT IO Int -> ListT IO Int
f x = return 0 `mplus` fmap (+ 1) x

g2 :: ListT IO Int -> ListT IO Int
g2 x = do
    n  <- x
    n' <- lift (fmap read getLine)
    return (n' + n)

a = f b
b = g2 a

main = runListT $ do
    n <- a
    lift (print n)
    mzero

You can also implement take like functionality with a little extra code:
import qualified Pipes.Prelude as Pipes

take' :: Monad m => Int -> ListT m a -> ListT m a
take' n l = Select (enumerate l >-> Pipes.take n)

main = runListT $ do
    n <- take' 5 a
    lift (print n)
    mzero

Example session:
>>> main
0
1<Enter>
2
2<Enter>
3<Enter>
7
4<Enter>
5<Enter>
6<Enter>
18
7<Enter>
8<Enter>
9<Enter>
10<Enter>
38

You can learn more about ListT by reading the pipes tutorial, specifically the section on ListT.


text:
Q: How to authenticate JWT via websocket? I have a REST API server written in Node js, and a websocket server that get as a parameter my HTTP server.
I want to establish a connection with the user only after authentication (using JWT).
This is my verifyToken func:
verifyToken: (req, res, next) =>
    {
        const authHeader = req.headers['authorization']
        const token = authHeader && authHeader.split(' ')[1]
        if (token == null)
        {
            return res.send("No token sent");
        }

        jwt.verify(token, publicToken, (err, payload) =>
        {
          if(err)
          {
              return res.send("Not valid token");
          }

          req.payload = payload
          next()
        })
      }

I want to use this authentication in here:
wss.on('connection', (ws) =>
{
 **verify token**
console.log('A new user connected');
}

How can I do it?


text:
Q: Why compare f(n)/f(n-1) = 1 to solve for the maxima of a discrete function? I am aware of a general strategy where you have a discrete function, e.g.,
$f = \dfrac{{10 \choose 5}{n-10 \choose 15}}{n \choose 20}$
And in order to find the maximum, you solve $\frac{f(n)}{f(n-1)} = 1$.
I may be mistaken in this method applying to discrete functions only... But the bottom line is that I am trying to understand why this method works, and then understand how broadly this strategy can be used (in what situations).
I appreciate any insight. I feel like there must be something intuitive I am missing.

A: It's the discrete equivalence of finding the point(s) for which the derivative is $0$ in the differentiable case, i.e. finding local extrema.
One definition of the derivative is
$$f'(a) = \lim_{h\to 0}\frac{f(a+h)-f(a)}{h}$$
A discrete counterpart would be to remove the limit and set $h$ to the smallest increment available, i.e. 1. Then you get
$$\frac{f(n+1)-f(n)}1$$
Setting this property to $0$ will give you
$$f(n+1)-f(n) = 0 \implies \frac{f(n)}{f(n+1)}=1$$
Is this a maximum? You can't be sure, you only know it is a local extremum. Equivalent to the continuous case, you'll have to check the sign of the second "derivative" to decide if it's a maximum or minimum.

A: The idea is that (if $f(n) \gt 0$), $\frac {f(n)}{f(n-1)} \gt 1 \implies f(n) \gt f(n-1)$, so if I can find an $n$ such that $\frac {f(n)}{f(n-1)} \gt 1 $ and $\frac {f(n)}{f(n+1)} \gt 1 $ then $n$ is a (local) maximum of $f(n)$.  Note that I have used inequalities where you have equality.  We are looking for the point where the inequality changes sense.
In your example, you should be able to convince yourself that $\frac {f(n)}{f(n-1)}=\frac {(n-10)(n-20)}{(n-25)n}$, which equals $1$ at $n=40$.  This gives us $f(39)=f(40)$, then the functions starts decreasing.


text:
Q: Support and tensor product doubts Some questions:

*

*This is proposition $3.5$ , page $39$ of Atiyah's and Macdonald's book.

Let $M$ be an $A$-module. Then $S^{-1}A \otimes_{A} M \cong S^{-1}M$ as $S^{-1}A$-modules.
So the idea is to use the universal property of the tensor product. The mapping $S^{-1}A \times M \rightarrow S^{-1}M$ given by $(a/s,m) \mapsto am/s$ is $A$-bilinear so we get an  $A$-linear map $f: S^{-1}A \otimes_{A} M \rightarrow S^{-1}M$ given by $f((a/s) \times m) = am/s$.
Then the rest of the proof shows the map is injective and surjective. My question is, can't we simply give the inverse? let $g: S^{-1}M \rightarrow S^{-1}A \otimes_{A} M$ given by $g(m/s) = 1/s \otimes m$.
Then we have:
$(g \circ f)((a/s) \otimes m)=g(f(a/s))=g(am/s)=1/s \otimes am = a/s \otimes m$.
Similarly for $f \circ g$.

*This is exercise $4$ (same book) page $44$: let $f: A \rightarrow B$ be a ring homomorphism and let $S$ be a multiplicatively closed subset of $A$. Let $T=f(S)$. Show that $S^{-1}B \cong T^{-1}B$ as $S^{-1}A$-modules.

My question here: why $S^{-1}B$ makes sense? I thought that we always needed that the multiplicatively closed set is a subset of the ring $B$, here $S \subseteq A$, why we can take the localization then?

*Let $M$ be an $A$-module let $\textrm{Supp}(M)=\{P \in \mathrm{Spec}(A) : M_{P} \neq 0\}$, the support of $M$.

I want to compute $\textrm{Supp}(\mathbb{Z} \otimes \mathbb{Z}/2\mathbb{Z})$ (viewed as a $\mathbb{Z}$-module).
I know that in general $\textrm{Supp}(M_{1} \oplus M_{2}) = \textrm{Supp}(M_{1}) \cup \textrm{Supp}(M_{2})$.
So two doubts here:
$\textrm{Supp}(\mathbb{Z}) = \{0\} \cup \{(p) : p\textrm{ is prime}\}$ right? because if we localize at such prime ideals we don't get the trivial module.
On the other hand I think $\textrm{Spec}(\mathbb{Z}/2\mathbb{Z}) = \{(0)\}$ and if we localize $\mathbb{Z}/2\mathbb{Z}$ at $(0)$ we get again $\mathbb{Z}/2\mathbb{Z}$ because $\mathbb{Z}/2\mathbb{Z}$ is a field right?
So in conclusion $\textrm{Supp}(\mathbb{Z} \otimes \mathbb{Z}/2\mathbb{Z}) = \{(0)\} \cup \{(p): p \textrm{ is prime}\}=\textrm{Spec}(\mathbb{Z})$.
Is this OK?
Thanks in advance
EDIT. Sorry, in 3. I meant $\textrm{Supp} (\mathbb{Z} \oplus \mathbb{Z}/2\mathbb{Z})$.

A: (1) You can certainly do that as well. You just have to check that your map $g$ is well-defined, and that it's a morphism of $S^{-1}A$-modules (remember that the expression $m/s$ is not unique).
(2) Here $B$ is given the canonical structure of an $A$-module, $a\cdot x = f(a)x$.
(3) Since $\mathbb{Z} \otimes_\mathbb{Z} \mathbb{Z}/2\mathbb{Z} \simeq \mathbb{Z}/2\mathbb{Z}$ as $\mathbb{Z}$-modules, you have $\text{Supp}(\mathbb{Z} \otimes \mathbb{Z}/2\mathbb{Z}) = \text{Supp}(\mathbb{Z}/2\mathbb{Z})$. For a prime $P \in \mbox{Spec }\mathbb{Z}$, the localization $(\mathbb{Z}/2\mathbb{Z})_P$ is $0$ if and only if $P\neq (2)$.

A: $\DeclareMathOperator{\supp}{supp}$For (1), I think that this is a fine way to do it, although you should be careful when defining maps out of something like $S^{-1}M$. Unfortunately, most books omit the universal property of a localised module, but it's a good exercise to figure out what it is. Less elegantly, you could define a map of sets $S \times M \to S^{-1}A \otimes M$ and check that it respects the equivalence relation used in the construction.
I think you have mixed up the direct sum and the tensor product in your attempt to solve (3). I agree with your computation of $\supp(\mathbf{Z})$, but as Bruno says that turns out to be unnecessary for this problem. Also note that you are not trying to find the support of $\mathbf{Z}/2\mathbf{Z}$ as a module over itself; if you were, then I would agree with your answer.
A fact that you might like, which would be overkill for this problem: if $M, N$ are finitely generated modules over $A$, then it is true that $\supp(M \otimes N) = \supp(M) \cap \supp(N)$. See Exercice 3.19(vi) in Atiyah–Macdonald.

A: For 3), ${\bf Z} \otimes {\bf Z}/2$ is the same thing as ${\bf Z}/2$, so it support is all of $Spec({\bf Z}/2)$, which is the 0 ideal as you say. But you also seem to be mixing up the 0 ideal in ${\bf Z}/2$ and the one in ${\bf Z}$.


text:
Q: Redshift Materialized View Not Refreshing (No Error) I have a materialized view in Redshift that refreshes fine when I run refresh materialized view command, however the AWS Glue job is failing to refresh.
I'm not seeing any kind of error in the logs and reviewing the redshift query history shows it completing successfully.  Additionally, the update time is the same so it does appear to be running correctly. However querying the view after glue updates does not show updated records, but does if I run the refresh.
I have ran the following permissions to grant the glue account access.
alter table reporting.my_view owner to glue;

alter schema reporting owner to glue;

grant all on schema reporting to glue;
grant all on all tables in schema reporting to glue;
alter default privileges in schema reporting grant all on tables to glue;

A: Try to use "commit;" before your main post actions query, for example:
"postactions": "commit; your_query"
REFRESH works for commited records only.


text:
Q: What is the smallest x86_64 Hello World ELF binary? I tried to write the smallest possible x86_64 ELF hello world program by hand, but I receive a Segmentation fault when trying to run it.
gdb says: During startup program terminated with signal SIGSEGV, Segmentation fault.
Here is the hexdump:
00000000: 7f45 4c46 0201 0100 0000 0000 0000 0000  .ELF............
00000010: 0200 3e00 0100 0000 7800 0000 0000 0000  ..>.....x.......
00000020: 4000 0000 0000 0000 0000 0000 0000 0000  @...............
00000030: 0000 0000 4000 3800 0100 0000 0000 0000  ....@.8.........
00000040: 0100 0000 0500 0000 0000 0000 0000 0000  ................
00000050: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000060: 3100 0000 0000 0000 3100 0000 0000 0000  1.......1.......
00000070: 0200 0000 0000 0000 b801 0000 00bf 0100  ................
00000080: 0000 be9a 0000 00ba 0a00 0000 0f05 b83c  ..."...........<
00000090: 0000 00bf 0000 0000 0f05 4865 6c6c 6f2c  ..........Hello,
000000a0: 2057 6f72 6c64 210a 00                    World!..

Here is the output of readelf -a:
ELF Header:
  Magic:   7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
  Class:                             ELF64
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           Advanced Micro Devices X86-64
  Version:                           0x1
  Entry point address:               0x78
  Start of program headers:          64 (bytes into file)
  Start of section headers:          0 (bytes into file)
  Flags:                             0x0
  Size of this header:               64 (bytes)
  Size of program headers:           56 (bytes)
  Number of program headers:         1
  Size of section headers:           0 (bytes)
  Number of section headers:         0
  Section header string table index: 0

There are no sections in this file.

There are no section groups in this file.

Program Headers:
  Type           Offset             VirtAddr           PhysAddr
                 FileSiz            MemSiz              Flags  Align
  LOAD           0x0000000000000000 0x0000000000000000 0x0000000000000000
                 0x0000000000000031 0x0000000000000031  R E    0x2

There is no dynamic section in this file.

There are no relocations in this file.
No processor specific unwind information to decode

Dynamic symbol information is not available for displaying symbols.

No version information found in this file.

And here is the code:
0xb8 0x01 0x00 0x00 0x00 /* mov %rax, 1 ; sys_write */
0xbf 0x01 0x00 0x00 0x00 /* mov %rdi, 1 ; STDOUT */
0xbe 0x9a 0x00 0x00 0x00 /* mov %rsi, 0x9a ; address of string */
0xba 0x0a 0x00 0x00 0x00 /* mov %rdi, 15 ; size of string */
0x0f 0x05                /* syscall */

0xb8 0x3c 0x00 0x00 0x00 /* mov %rax, 60 ; sys_exit */
0xbf 0x00 0x00 0x00 0x00 /* mov %rdi, 0 ; exit status */
0x0f 0x05                /* syscall */

The "Hello, World!\n" string follows immediately afterwards.
I have been using this MOV instruction.
Playing around with the program header offset, alignment and virtual address fields did not yield anything. The manpage is a little confusing in this section. I also tried comparing this binary to one written in assembly, but I've found nothing useful.
Now to my question: Can you tell me what the mistake is and/or how I can debug this binary?

A:
I tried to write the smallest possible x86_64 ELF hello world program by hand

You should provide a source for your program, so we can fix it.

gdb says: During startup program terminated with signal SIGSEGV

This is GDB telling you that it called fork/execve to create the target program, and expected the kernel to notify GDB that the program is now ready to be debugged. Instead, the kernel notified GDB that the program has died with SIGSEGV, without ever reaching its first instruction.
GDB didn't expect that. Why would this happen?
This happens when the kernel looks at your executable, and says "I can't create a running program out of that".
Why is that the case here? Because this LOAD segment:
Program Headers:
  Type           Offset             VirtAddr           PhysAddr
                 FileSiz            MemSiz              Flags  Align
  LOAD           0x0000000000000000 0x0000000000000000 0x0000000000000000
                 0x0000000000000031 0x0000000000000031  R E    0x2

is asking the kernel to map 0x31 bytes from offset 0 in the file to virtual address 0. But the kernel (rightfully) refuses such nonsense request, and terminates the program with SIGSEGV before returning from execve.
You could probably avoid this by making the file ET_DYN instead of ET_EXEC -- that would change the meaning of your program header from "map this segment at 0" to "map this segment anywhere".
You could definitely avoid this by keeping the ET_EXEC, but changing the .p_vaddr and .p_paddr of the segment to something like 0x10000.
TL;DR: Your program and file headers must make sense to the kernel, or you'll never get off the ground.

A: The answer that I accepted did the trick. I just want to share the new hexdump of the binary here:
00000000: 7f45 4c46 0201 0100 0000 0000 0000 0000  .ELF............
00000010: 0200 3e00 0100 0000 7800 0100 0000 0000  ..>.....x.......
00000020: 4000 0000 0000 0000 0000 0000 0000 0000  @...............
00000030: 0000 0000 4000 3800 0100 0000 0000 0000  ....@.8.........
00000040: 0100 0000 0500 0000 0000 0000 0000 0000  ................
00000050: 0000 0100 0000 0000 0000 0100 0000 0000  ................
00000060: 3100 0000 0000 0000 3100 0000 0000 0000  1.......1.......
00000070: 0200 0000 0000 0000 b801 0000 00bf 0100  ................
00000080: 0000 be9a 0001 00ba 0f00 0000 0f05 b83c  ...............<
00000090: 0000 00bf 0000 0000 0f05 4865 6c6c 6f2c  ..........Hello,
000000a0: 2057 6f72 6c64 210a 00                    World!..

readelf -a:
ELF Header:
  Magic:   7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
  Class:                             ELF64
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           Advanced Micro Devices X86-64
  Version:                           0x1
  Entry point address:               0x10078
  Start of program headers:          64 (bytes into file)
  Start of section headers:          0 (bytes into file)
  Flags:                             0x0
  Size of this header:               64 (bytes)
  Size of program headers:           56 (bytes)
  Number of program headers:         1
  Size of section headers:           0 (bytes)
  Number of section headers:         0
  Section header string table index: 0

There are no sections in this file.

There are no section groups in this file.

Program Headers:
  Type           Offset             VirtAddr           PhysAddr
                 FileSiz            MemSiz              Flags  Align
  LOAD           0x0000000000000000 0x0000000000010000 0x0000000000010000
                 0x0000000000000031 0x0000000000000031  R E    0x2

There is no dynamic section in this file.

There are no relocations in this file.
No processor specific unwind information to decode

Dynamic symbol information is not available for displaying symbols.

No version information found in this file.

The code:
0xb8, 0x01, 0x00, 0x00, 0x00, /* mov $0x1,%rax     ; sys_write */
0xbf, 0x01, 0x00, 0x00, 0x00, /* mov $0x1,%rdi     ; STDOUT */
0xbe, 0x9a, 0x00, 0x01, 0x00, /* mov $0x1009a,%rsi ; address of string */
0xba, 0x0f, 0x00, 0x00, 0x00, /* mov $0xf,%rdx     ; size of string*/
0x0f, 0x05,                   /* syscall */
0xb8, 0x3c, 0x00, 0x00, 0x00, /* mov $0x3c,%rax    ; sys_exit */
0xbf, 0x00, 0x00, 0x00, 0x00, /* mov $0x0,%edi     ; exit status */
0x0f, 0x05                    /* syscall */

As mentioned in the comments, this is not the smallest possible x86_64 ELF binary. The code could be improved and if you want to be crazy, you can put stuff in unused parts of the elf header. But in any case, I'm quite satisfied with a file size of 169 Bytes.


text:
Q: Projectile not shooting direction of my weapon So my game is sort of like a 3d top down shooter, so I want my gun to shoot wherever the mouse is and it wont go to the mouse unless im shooting down. If you've seen brackyes game called ball wars, im sort of trying to replicate one like that but the projectile is not shooting the right way.
I got my script from blackthornprods ranged combat tutorial (which is for 2d so maybe thats the issue but I dont know how to solve it) :
public float speed;
public float lifeTime;

private void Start()
{
    Invoke("DestoryProjectile", lifeTime);
}

private void Update()
{
    transform.Translate(transform.up * speed * Time.deltaTime);
}

void DestroyProjectile()
{
    Destroy(gameObject);
}

Appreciate anyone to try!
Here is my other script:
 Camera mainCam;
public GameObject projectile;

public Transform shotPoint;

private float timeBtwShots;
public float startTimeBtwShots;

void Awake()
{
    mainCam = Camera.main;
}

void Update()
{
    float objectDepthFromCamera = Vector3.Dot(
            transform.position - mainCam.transform.position,
            mainCam.transform.forward);

    Vector3 cursorWorldPosition = mainCam.ScreenToWorldPoint(Input.mousePosition
            + Vector3.forward * objectDepthFromCamera);

    Vector3 localUpNeeded = Vector3.Cross(Vector3.forward,
            cursorWorldPosition - transform.position);

    transform.rotation = Quaternion.LookRotation(Vector3.forward, localUpNeeded);

    if(timeBtwShots <= 0)
    {
        if (Input.GetMouseButtonDown(0))
        {
            Instantiate(projectile, shotPoint.position, transform.rotation);
            timeBtwShots = startTimeBtwShots;
        }
    }
    else
    {
        timeBtwShots -= Time.deltaTime;
    }
}

A: Projectile not shooting direction of my weapon. Simple solution -

*

*First instantiate or pool the instance of projectile.

*Set rotation of projection from the rotation of weapon & set location to spawn point

*Now fire, or whatever strategy you are using

Consider Global rotation, if you need help, tell me, I will edit and give a snippet of code.
This should work. If doesn't post all necessary code, I will give a better solution.
Here is sample github project I created, just for you. I opened Unity nearly after a year. Please check all the versions.
Must check :
firing in facing direction
just instantiate at spawn point
just added some rotation

I think this should give you concept.
Press X for a rantom rotation
Press Space to shoot a projectile :lol:
The white cube shows that it always shoots at a constant direction


text:
Q: IBDesignable View Rendering I had custom view like this image and it work (text font and text color i set in drawRect)
+*******************+
*text 01 IMAGE *
*text 02_______ *
+*******************+
Now i wanna set font and color from Interface Builde but i get error:

IB Designables: Failed to render instance of AvailableSeatView: Rendering the view took longer than 200 ms. Your drawing code may suffer from slow performance.

Here my code:
In AvailableSeatView.h
#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface AvailableSeatView : UIView
@property (nonatomic) IBInspectable UIImage *image;
@property (nonatomic) IBInspectable NSInteger numberSeats;
@property (nonatomic) IBInspectable UIFont *numberSeatsFont;
@property (nonatomic) IBInspectable UIColor *numberSeatsColor;
@property (nonatomic) IBInspectable NSString *title;

In AvailableSeatView.m
@implementation AvailableSeatView
- (void)drawRect:(CGRect)rect {
    //UIImage
    CGRect myFrame = self.bounds;
    CGFloat yImage = myFrame.size.height/2 - self.image.size.height < 0 ? 0 : myFrame.size.height/2 - self.image.size.height;
    CGRect imageFrame = CGRectMake(myFrame.size.width/2, yImage, self.image.size.width, self.image.size.height);
    [self.image drawInRect:imageFrame];

    //UILabel number of seats
    [self drawString:[NSString stringWithFormat:@"%li", (long)self.numberSeats]
            withFont:self.numberSeatsFont
            andColor:self.numberSeatsColor
            aligment: NSTextAlignmentRight
              inRect:CGRectMake(0, yImage, imageFrame.origin.x, self.image.size.height)];

    //UILabel Title
    UIFont *titleFont = [UIFont systemFontOfSize:20];
    UIColor *titleColor = [UIColor redColor];
    [self drawString:self.title
            withFont:titleFont
            andColor:titleColor
            aligment: NSTextAlignmentCenter
              inRect:CGRectMake(0, myFrame.size.height/2, myFrame.size.width, myFrame.size.height/2)];
}

- (void) drawString: (NSString*) s
           withFont: (UIFont*) font
           andColor: (UIColor *)color
           aligment: (NSTextAlignment) alignment
             inRect: (CGRect) contextRect {

    CGFloat fontHeight = font.pointSize;
    CGRect textRect = CGRectMake(0, contextRect.origin.y, contextRect.size.width, fontHeight);
    NSMutableParagraphStyle* p = [NSMutableParagraphStyle new];
    p.alignment = alignment;
    [s drawInRect:textRect withAttributes:@{NSFontAttributeName: font,
                                            NSForegroundColorAttributeName: color,
                                            NSParagraphStyleAttributeName: p}];
}
@end

And after search in google, i find this post: IBDesignable View Rendering times out    i try to do override initWithFrame, initWithCoder but it still not working.

A: Basically, using DrawRect( ) method for the Live Rendering purpose is a wrong concept. Apple provides a separate method for this (For Live rendering purpose)"- (void)prepareForInterfaceBuilder { }".
However you cannot set UIFont property from the IB in this case. But you can set UIcolor.
Sample Project


text:
Q: How to get list of product having a specific property id's I have a table having columns 'product_id' and 'property_id'. Some products having both property 20 & 21, some of them only have 20 or 21.
product_id   property_id
1            20
1            21
2            20
3            21
3            20
4            21

I need to get list of product having both property_id 20 and 21. In here I needed the product list of 1 & 3 like below,
product_id
1
3

A: This should gives you the correct result.
select product_id
from `xy`
where property_id in (20,21)
group by product_id
having count( distinct property_id)=2

The the sqlfiddle

A: Use IN and COUNT(distinct property_id):
SELECT product_id
FROM TableName
WHERE property_id IN (20,21)
GROUP BY product_id
HAVING COUNT(distinct property_id) = 2

Explanation:
IN checks if property_id has values either 20 or 21.
COUNT (distinct property_id) = 2 verifies having two different values of property_id. So, when product 2 has 2 same values in property_id like (20,20), it will not be selected.
Result:
product_id
----------
1
3

Sample result in SQL Fiddle.

A: Make use of IN to check multiple values.
Select product_id
from products
where property_id in(20,21)
group by product_id
having count(property_id) >=2

A: SELECT `product_id` FROM TableName
WHERE `property_id` IN (20,21)
GROUP BY `product_id`
HAVING COUNT(*) = 2


text:
Q: Whats the distinction between objects and variables? I have followed the java SE tutorial from www.patrickvideos.com and have come across a problem in the chapter about "class & object". The person making the tutorial gave the following code example:
Employee alex;
Employee linda;
Employee john;

He said explicitly that "alex, linda, john are what you call objects". However, if i'm not mistaken variables themselves can't be objects but simply hold references to objects or to an instance of a class. So are alex, linda, john objects or is it safe to assume that they are references to objects and that person is spreading misinformation?

A: Yes, reference variables
You are correct, alex, linda, and john are all reference variables.
All three are little containers that hold either nothing (null) or a reference (pointer) to an object setting in memory somewhere else. Those three variables do not hold an object, but they know how to get you to an object.
Given the syntax in Java, we tend to forget about this distinction. In our daily programming work, we usually think of alex as the object. We generally think:

alex holds a Person object representing the human known as Alex

… whereas the technical truth is:

alex may hold a reference that can lead us to the chunk of memory elsewhere holding our Person object that we want to access

In a tutorial, it can be tiring and distracting to constantly refer to alex and linda as reference variables. So perhaps we should give the author of your tutorial some poetic license to call them objects.
Example code
Some example code, using the records feature in Java 16+.
record Person( String firstName , String lastName , Color favoriteColor ) { }

Person alex = new Person( "Alex" , "Peterson" , Color.MAGENTA );
Person linda = new Person( "Linda" , "Greystone" , Color.GREEN );
Person john = new Person( "John" , "Petrov" , Color.YELLOW );

Each call to new Person instantiates an object, that is, allocates a chunk of memory somewhere in RAM to hold our three member fields (state) along with handles to the executable code we think of as named methods (behavior). (For records, the compiler implicitly creates constructor, getters, equals & hashCode, and toString methods. Plus, you can add more.)
The call to new Person returns a reference, essentially the address in memory where the new Person object/instance lives. We store that reference in the reference variable alex or linda.  We declared those variables as being references to hold objects of type Person.

A: You are right that, strictly speaking, in the above example, we are declaring variables alex, linda, john that will hold reference to an object.
But since they hold reference to an object, in a juggling of terminologies, we can call them objects.
So a variable can be considered a syntactic construct, while the object (what it refers to) is its semantic.
It's like in Math, you can say sin(x) is a function, but strictly speaking it is an expression. To be a function you also have to specify its domain, so sin(x) in this case is refering to the function x -> sin(x) where x is a real number.

A: *

*Employee  is a class

*alex is an object of the class Employee

*alex is an instance of the class Employee

*alex for the jvm is the variable of object that doesn't contains the object data.

*alex is said to be an instance of Employee and an Employee object for simplicity.

In Java, no variable can ever hold an object.
A variable can only hold a reference to an object [1].

Instead of holding an object itself, a variable holds the information necessary to find the object in memory. This information is called a reference or pointer to the object [1].

Object is not stored in the variable.The object is somewhere else; the variable points to it [1].

[1] https://math.hws.edu/javanotes/c5/s1.html


text:
Q: Using Boost library in XCode not particularly good with this kind of stuff I have managed to install the Boost C++ library and this basic program works with the g++ compiler and linking to the right .dylib files.
#include <iostream>
#include <boost/filesystem.hpp>

using namespace boost;

int main()
{
filesystem::path path1("/Users/username/Documents/testfile.txt");
filesystem::remove(path1);
std::cout << "It worked" << std::endl;
return 0;
}

Now I would like to do the same, just using Xcode to build and run the program, but it doesn't work. I have done everything in this tutorial:
http://buddypanda.com/?p=10
i.e. include header and library search paths, as well as linked the .dylib files of filesystem and system under the 'Build Phases' tab.
The Build succeeds but then the program crashed with an error of EXC_BAD_ACCESS.
I can maybe provide more specifics on what goes wrong if you tell me where to look.
Thanks!
EDIT1: I am using g++-4.9 and Boost-1.58 and Xcode 6.4


text:
Q: Chooser with camera intent and image picker intent I have created a chooser for either picking an image from file or for making a picture.
The code I use works fine on a Nexus 5, however when I try it on a Samsung S5, the chooser does not display the camera icons.
public Intent makePhotoIntent(String title, Context ctx, String uniqueImageId){

        //Build galleryIntent
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        galleryIntent.setType("image/*");

        //Create chooser
        Intent chooser = Intent.createChooser(galleryIntent,title);

        if (checkexCameraHardware()){
            Intent  cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            mTempImage = null;
            try {
                mTempImage = createImageFile(uniqueImageId);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (mTempImage != null){
                cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempImage)); //add file ure (photo is saved here)
                Intent[] extraIntents = {cameraIntent};
                chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
            }
        }
        return chooser;
    }

When I change the order in which the intents are added to the chooser the Samsung device does show the camera but only shows android-system as the file option.
public Intent makePhotoIntent(String title, Context ctx, String uniqueImageId){

        //Build galleryIntent
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        galleryIntent.setType("image/*");

        //Create chooser
        Intent chooser = Intent.createChooser(galleryIntent,title);

        if (checkexCameraHardware()){
            Intent  cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            mTempImage = null;
            try {
                mTempImage = createImageFile(uniqueImageId);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (mTempImage != null){
                cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempImage)); //add file ure (photo is saved here)

                //I have to re-create the chooser here or the Samsung will not show the 'camera' icons.
                //I have to add the cameraIntent first.
                chooser = Intent.createChooser(cameraIntent,title);
                Intent[] extraIntents = {galleryIntent};

                //Intent[] extraIntents = {cameraIntent};
                chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
            }
        }
        return chooser;
    }

Ideally I would like the Samsung device to show the same as the Nexus one when I add the gallery intent first. I can however not get this to work.

A: *

*If there are multiple intent matches for the extra intent (Intent.EXTRA_INITIAL_INTENTS) , it will show all of them combined under "Android System". When you click on "Android System", it will open another chooser with all those intent matches.

*So, in your first screenshot for samsung device, the camera is indeed showing up - its just under "Android Systeem" (clicking this will show all camera intent matches).

*If you make galleryIntent the extra instead of camera intent, it will combine all gallery related intents under "Android Systeem" (as seen in your 2nd screenshot for samsung device)
I guess the user can be confused if he does not know what this "Android Systeem" is !

*

*With below solution you can directly add each one to your chooser
In your 2nd code snippet, replace
Intent[] extraIntents = {galleryIntent};
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);

with :
List<Intent> galleryIntents = new ArrayList<Intent>();
PackageManager pm = getApplicationContext().getPackageManager();
for (ResolveInfo ri: pm.queryIntentActivities(galleryIntent, PackageManager.MATCH_DEFAULT_ONLY)) {
    Intent intent = pm.getLaunchIntentForPackage(ri.activityInfo.packageName);
    intent.setAction(Intent.ACTION_PICK);
    galleryIntents.add(intent);
}
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, galleryIntents.toArray(new Parcelable[] {}));

This will manually add each matching intent directly to your chooser

A: Try this way,hope this will help you to solve your problem
Please follow these steps and this is the best and simple way to pick image from gallery and from camera,
Step 1. declare globally variables
public static final int rcCC = 33;
boolean isCC = false;

Step 2 . Copy these methods and paste your code
void picPhoto() {
    String str[] = new String[] { "Camera", "Gallery" };
    new AlertDialog.Builder(getActivity()).setItems(str,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    performImgPicAction(which);
                }
            }).show();
}

void performImgPicAction(int which) {
    Intent in;
    if (which == 1) {
        in = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    } else {
        in = new Intent();
        in.setAction(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    }
    startActivityForResult(
            Intent.createChooser(in, "Select profile picture"), which);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

        try {
            if (rcCC == requestCode) {
                getActivity();
                if (resultCode == Activity.RESULT_OK) {
                    isCC = true;

                }
            } else {
                getActivity();
                if (resultCode == Activity.RESULT_OK) {
                    BitmapFactory.Options option = new BitmapFactory.Options();
                    option.inDither = false;
                    option.inPurgeable = true;
                    option.inInputShareable = true;
                    option.inTempStorage = new byte[32 * 1024];
                    option.inPreferredConfig = Bitmap.Config.RGB_565;
                    if (Build.VERSION.SDK_INT < 19) {
                        Uri selectedImageURI = data.getData();
                        uImage = BitmapFactory.decodeFile(Common.getPath(
                                selectedImageURI, getActivity()), option);
                    } else {

                        ParcelFileDescriptor pfd;
                        try {
                            pfd = context
                                    .getContentResolver()
                                    .openFileDescriptor(data.getData(), "r");
                            FileDescriptor fileDescriptor = pfd
                                    .getFileDescriptor();

                            uImage = BitmapFactory.decodeFileDescriptor(
                                    fileDescriptor, null, option);
                            pfd.close();

                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        ivProfile_image.setImageBitmap(uImage);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

}

Step 3. call the method, where you want to pick pic and show dialog
  picPhoto();

Step 4.
Make user permission in manifest file,
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.CAMERA" />

Thanks

A: Try in this way, i hope its works for you, i check in samsung galaxy tab 2 it show camera option
Declare your intent like this
  Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    galleryIntent.setType("image/*");

    //Create chooser
    Intent chooser = Intent.createChooser(galleryIntent,title);

        Intent  cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        fileUri = getOutputMediaFileUri(uniqueImageId);
            cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri); //add file ure (photo is saved here)
            Intent[] extraIntents = {cameraIntent};
            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);

            startActivityForResult(chooser, Constants.SEND_IMAGE_FROM_CEMERA);

and  getOutputMediaFileUri(uniqueImageId) method this return you Uri of image
getOutputMediaFileUri(String uniqueImageId){

        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "IMAGE_DIRECTORY_NAME");

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        File mediaFile;
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + uniqueImageId + ".jpg");

        return Uri.fromFile(mediaFile);
}


text:
Q: How can I persist tpm keys on disk using .NET and Tpm2Lib? Instead use the tpm limited non-volatile memory, I want to persist a generated tpm key on my hard disk. What is the best way to this?
I'm using the Tpm2Lib to .NET from Microsoft, and I'm implementing that solution at linux OS.

A: You wouldn't persist them on disk but recreate them on demand with exactly the same key template.
If you call TPM2_CreatePrimary with the same key template (and the same internal seed) you would recreate exactly the same key.


text:
Q: Is there any possibilty to choose a next song on Spotify when the app is minimalized? is there any kind of a shortcut to choose a next song while the app is minimalized? I got the SpotMenu and Karabiner app.

A: The keyboard key fast forward works for me without issue. Thats the alt F9 key.
It skips to the next song.


text:
Q: scrollIntoView vs moveToElement In Selenium WebDriver, there are two major methods to put an element into a visible area:

*

*Scrolling into view:
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);

*Using moveToElement browser action:
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();

Are these methods equivalent and which one should be preferred?

A: scrollIntoView
The DOM method scrollIntoView only scrolls the element into view. If scrollIntoView cannot scroll the element into view, it will just fail silently.I added an invisible element to the start of body and called scrollIntoView on it. Nothing scrolled but there was no error. Note that you have more control on how the element is scrolled with scrollIntoView than with moveToElement. Selenium is only interested in bringing the element into view so that the mouse can be placed on it. It does not give you any say in how it is going to do it. scrollIntoView however allows you, for instance, to specify whether you want the top or bottom of the element to be align with its scrollable ancestor. (See here for the details.)
moveToElement
The Selenium method moveToElement does two things: it scrolls the element into view and moves the mouse on top of the element. I've also tested it with elements that cannot be scrolled or moved to because they have no coordinates on screen and got no error here either.
Choosing One
I default to using moveToElement, with the following exceptions:

*

*If you do not want to affect at all where Selenium has placed the mouse but you want to scroll something into view (a bit strange... but possible), then you should use scrollIntoView.

*If you need to scroll an element with the kind of control that scrollIntoView gives you (like the alignment option I mentioned above), then you have to use it rather than moveToElement.

*There are cases where trying to simulate user behavior through Selenium's commands is not possible or is very expensive to do by sending a series of Selenium commands. (Each command is a round-trip to the network. When the testing server somewhere across the Internet, it adds up.) In such cases, I use Selenium's executeScript. In such case, it can be advantageous to use scrollIntoView in the script being executed, rather then end the script, create an Action to perform the scroll, and finish the whole operation with another executeScript.


text:
Q: Error Executing update ERR_UPDATEQUERY in Yellowfin 7.1 Installer
I am getting an error while exposing my database source to yellowfin 7.1 Installer . I have searched a lot in google .But I can't get clear. Also i am using PostGreSql . I dont know where to add all previleges to corresponding role or username in Postgresql.
So please guide me where do I add all previleges in Postgresql.


text:
Q: How to interact with a C++ program input stream from a Node.js process? I'm new to Node.js but I'm not new to C++ and Javascript. I'm gonna make a C++ tool using node but I face a problem, when C++ program call std::cin, I don't know how to send data from node process to C++ process.
See this code (main.exe):
int main() {
  int a, b, c;
  cout << "Enter 3 numbers: ";
  cin >> a >> b >> c;
  cout << "Total: " << (a + b + c) << endl;
  return 0;
}

In my javascript code, I use child_process.spawn to invoke main.exe, I know that I can use event 'data' to get the message "Enter 3 numbers: ", but how do I let node enters a, b and c automatically and finally finish main.exe?
UPDATE:
My Javascript code (I don't know which event can be use to write data so I use 'data')
var spawn = require('child_process').spawn;
var child = spawn('main.exe');
child.stdout.on('data', (data) => {
  console.log(data);
  child.stdout.end('12 34 56');
});
child.on('close', (code) => console.log('Exit code: ' + code));

A: Two things,

*

*Your child process doesn't flush after cout << "Enter 3 numbers: "; so the data event is never getting triggered. (Edit: Reading your question again, it seems the data event is getting triggered. The buffering mechanism under Windows might be different than what I'm used to on Linux. I'll leave this here just in case though :)

*You need to write to stdin and not stdout for the child process.

Try this for your javascript code instead:
var spawn = require('child_process').spawn;
var child = spawn('main.exe');

child.stdin.end('12 34 56');
child.stdout.on('data', (data) => {
  console.log(data);
});
child.on('close', (code) => console.log('Exit code: ' + code));


text:
Q: What is an alternative to insertSublayer in swiftUI I am creating a cameraApp as part of a project I am doing and I am relatively new to swiftUI. I am using AVFoundation and I need to create a previewLayer. However, I am unable to create a previewLayer because I don't know how I can display it. I have followed a few tutorials and read Apple's documentation.
This is what my code looks like
struct ContentView: View {

    var captureSession = AVCaptureSession()
    var currentCamera: AVCaptureDevice?
    var photoOutput: AVCapturePhotoOutput?
    var cameraPreviewLayer: AVCaptureVideoPreviewLayer?

    func setupCaptureSession() {
        captureSession.canSetSessionPreset(.high)
    }

    mutating func setupDevice() {
        let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera,
        for: .video, position: .unspecified)

        currentCamera = videoDevice
    }

    func setupInputOutput() {
        do {
            let captureDeviceInput = try AVCaptureDeviceInput(device: currentCamera!)
            captureSession.addInput(captureDeviceInput)
            photoOutput!.supportedPhotoCodecTypes(for: .jpg)
        } catch {
            print("err")
        }
    }

    mutating func setupPreviewLayer() {
        cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
        cameraPreviewLayer?.connection?.videoOrientation =
        AVCaptureVideoOrientation.landscapeRight
        cameraPreviewLayer?.frame = self.view.frame
        self.view.insertSublayer(cameraPreviewLayer!, at: 0)
    }

    func startRunningCaptureSession() {
        captureSession.startRunning()
    }

    var body: some View {
        Text("Hello World")
            .frame(maxWidth: .infinity, maxHeight: .infinity)

    }
}


text:
Q: How do I synchronize multiple Access Databases together? I'm conducting a study, where we will be collecting data using Access.  Since there will be multiple persons conducting these studies using the same structured Access DB we need to figure a way to update/synchronize to a central Database with the information collected from all other databases.  In other words, the data that is collected by the multiple persons needs to be collected into one central area.  How do I do this?
In essence this is exactly what I  want to do but don't know how:

Indirect synchronization
Indirect synchronization is useful when you work in a disconnected environment, such as when you are traveling with a laptop.
Indirect synchronization can only be configured by using Replication Manager. Once indirect synchronization is configured with Replication Manager, you can execute an indirect synchronization by using Microsoft Access, Replication Manager, or JRO.

site

A: The most reliable way I know of to do this is to write a program that works with the database off a fileserver.  I've had to work on a program (from scratch) to do this for a client that wanted to use MS Access, nothing else.  Unfortunately, it's too tricky to explain here.  If you can just access the Access database file from multiple places, the MS Access software should be able to make changes but I don't know if those changes would propagate through other systems, or how reliable it would be.

A: See this article : Merge Multiple MS Access Databases into a single one :

Find below a Merge() function written
  in MS Access VBA for consolidating
  multiple typically structured
  databases into a single one. I had to
  write this function for one of my
  project where I needed to consolidate
  many island databases. The structure
  of the databases were exact same.
You will receive warnings when data
  can not be inserted as they will
  create duplicate records. In such
  situation simply ignore the warning
  message and proceed.

The script itself just loops on executing commands that look like:
INSERT INTO target SELECT * FROM source

Since the original webserver seems to be broken, the entire script is retrieved from the Wayback Machine and reproduced here :
Option Compare Database
Option Explicit

'Set the below variable to TRUE
'When you are done with testing
'Basically testing mode will print
'the names of all the databases
'you are going to merge
Const bTest = False

Sub Merge()

    'Copyright © iLoveCoding, 2010
    'Web: http://www.iLoveCoding.co.uk

    'The Merege() is a function that merges
    'records from multiple MS Access databases
    'into a consolidated one provided that the
    'structure of all databases are exactly same.
    '
    'This function assumes that there are
    'no relationships defined among the tables.
    'Which is typically the scenario when an
    'MS Access database is used in an Intranet or
    'Web application.

    'However properly altering the order of the
    'dbfiles() initialization one can easily
    'address the issue of relationships and
    'data integrity among tables

    On Error GoTo errhand
    Dim appPath$
    '----------------------------------------------
    'Change the below number to number of databases
    'you are going to merge
    '----------------------------------------------
    Const ndb = 22
    Dim dbfiles$(2 To ndb)
    Dim i%
    'ANA.mdb
    '----------------------------------------------
    'Array of the database file names without path
    'Copy this code into a module of the first database
    'The first database is going to be the consolidated
    'capturing the records from all other databases.
    'The first database name is not present here
    'That is why the index starts with 2.
    '----------------------------------------------
    dbfiles(2) = "second.mdb" '<= change the file name
    dbfiles(3) = "third.mdb"
    dbfiles(4) = "fourth.mdb"
    '
    'similarly initialize other files
    '
    dbfiles(10) = "tenth.mdb"
    '----------------------------------------------
    ' The databases should be copied to the same
    ' folder of the first database
    '----------------------------------------------
    appPath = CurrentProject.Path
    For i = 2 To ndb
        Dim dbpath$, db As Database
        dbpath = appPath & "\" & dbfiles(i)
        Set db = OpenDatabase(dbpath)
        Dim tbl As TableDef, j%
        For j = 0 To db.TableDefs.Count - 1
            DoEvents
            Set tbl = db.TableDefs(j)
            If tbl.Attributes = 0 Then
                If bTest Then
                    Debug.Print tbl.Name
                Else
                    DoCmd.TransferDatabase acLink, "Microsoft Access", _
                    dbpath, acTable, tbl.Name, tbl.Name & "_Linked", False
                    Dim sql$
                    sql = "INSERT INTO [" & tbl.Name & "] SELECT * FROM [" & _
                    tbl.Name & "_Linked" & "]"
                    DoCmd.RunSQL sql
                    DoCmd.DeleteObject acTable, tbl.Name & "_Linked"
                End If
            End If
        Next j
        Debug.Print dbfiles(i)
    Next i
    Exit Sub
errhand:
    MsgBox Err.Description
End Sub

A: Something similar has been discussed on StackOverflow, maybe it can give you some pointers on how to continue.
Another option which might be above your budget, could be Altova DatabaseSpy, it can import CSV/XML data into an Access database.

A: I'm not sure what type of UI you're using for data input, but I'd suggest NOT using access and instead using SQL Express, and perhaps doing the data input as a .Net application.
You can then run SQL Server and merge the individual express databases back into the master. Take a look at http://msdn.microsoft.com/en-us/library/ms152746.aspx
You don't have details of the data you're collecting, but it sounds like there wouldn't be any overlap - i.e. each collector has a unique data set, without any possibility of merge conflicts - so it should go fairly easily.

A: If you do this syncing can be done by creating tables with random number primary keys. If 'autonumber' keys are used two users entering data will cause conflicts with duplicate record primary keys.
Syncing can then be done between instances with an append query.
I sync mine on sync.com because of HIPAA requirements.
I have had no record conflicts so far.


text:
Q: Retrieving keys from a custom system-wide keychain in Mac OS X 10.7+ I am working on an app for OSX Lion and onwards. The app has a root daemon process. I have created a system-wide keychain using "SecKeychainCreate" in /Library/Keychains which is accessible only by the daemon and wish to store generic keys in that keychain. Can anyone help me with retrieving generic keys from this keychain programmatically ? To add a key to the keychain, I used the "SecKeychainItemCreateFromContent" function as it accepts a SecKeychainRef parameter and passed kSecPublicKeyItemClass as the first parameter. Here is my code :
char *itemLabel = "Generic public key";

//Setting up the attribute vector (each attribute consists of {tag, length, pointer}):
SecKeychainAttribute attrs[] = {kSecLabelItemAttr, strlen(itemLabel), itemLabel};

SecKeychainAttributeList attributes = { sizeof(attrs)/sizeof(attrs[0]), attrs };

//pubKey is the key (NSData) that I want to store, while tempKeyChain is my keychain
status = SecKeychainItemCreateFromContent(kSecPublicKeyItemClass, &attributes,   [pubKey length],(__bridge const void *)pubKey, tempKeyChain, NULL, NULL);

if (status != noErr)
{
    NSString *error = (__bridge NSString *)SecCopyErrorMessageString(status, NULL);
    NSLog(@"Error in adding item to keychain : %@",error);
    return errSecUnimplemented;
}

Now, to retrieve the key, there are two options - "SecKeychainSearchCreateFromAttributes" which is deprecated in OS X 10.7 and so is useless, or "SecItemCopyMatching". The former accepts a SecKeychainRef parameter while the latter does not. So, I manually set my search list using "SecKeychainSetSearchList" to include tempKeyChain, and then used "SecItemCopyMatching". Here is the code for that :
OSStatus status;

SecKeychainRef defaultKeychain = nil;
SecKeychainCopyDefault(&defaultKeychain);

NSArray *searchList = [NSArray arrayWithObjects:(__bridge id)defaultKeychain,tempKeyChain, nil];

OSStatus result = SecKeychainSetSearchList((__bridge CFArrayRef)searchList);

if (result != noErr)
{
    NSString *error = (__bridge NSString *)SecCopyErrorMessageString(result, NULL);
    NSLog(@"Error : %@",error);
    return errSecUnimplemented;
}

NSMutableDictionary *query = [[NSMutableDictionary alloc] init];

[query setObject:kSecClassKey forKey:(id)kSecClass];
[query setObject:@"Generic public key" forKey:kSecAttrLabel];

CFTypeRef items;

status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &items);

return status;

This code always gives a status of "Item not found", even though my keychain is added to the search list alongwith the default search list.
I would greatly appreciate any pointers on why this might be happening, or any other better ways to store and retrieve keys from a custom keychain.
P.S - I do not want to store passwords, only keys (public and private). Could anyone guide me to some code or present a small code snippet explaining the same ? Thanks.


text:
Q: Group rows by field I have the following table structure:
+------------------------+
| id |  name  | category |
+------------------------+
|  1 | name_1 |    cat_1 |
|  2 | name_2 |    cat_2 |
|  3 | name_3 |    cat_1 |
|  . |   .    |      .   |
|  . |   .    |      .   |
|  n | name_n |    cat_k |
+------------------------+

were "n" is the total rows of table and "k" is an arbitrary number. My question is, is there any way to make an SQL query that retrieve rows grouped by category? I mean it is possible to get something like this structure?
array(
    "cat_1" => array(
                     "name_1", "1",
                     "name_3", "3",
               ),
    "cat_2" => array(
                     "name_2", "2",
                      some rows ....
               ),
    ...
    "cat_k" => array(
                     some rows....
               ),
)

If there is any way please give me some keywords, not entire solution please.

A: You can't really do this in a single query since mysql alone will not be able to yield multi-dimensional arrays, but it's almost trivial to do using PHP.  Basically here is what you would do:
$cats = array();
while ($row = $result->fetch()) {
    if (!isset($cats[$row->category])) {
        $cats[$row->category] = array();
    }
    $cats[$row->category][] = $row->name;
}

A: The query itself will not give you that structure, but it is quite easy to read the result set into that sort of two dimensional array:
$query = "SELECT category, id, name FROM table ORDER BY category ASC, id ASC";

$result = /* use you DB query mechanism of choice here */;

$array = array();

while($row = /* use your DB row fetch mechanism of choice here */) {
    $array[$row['category']][] = array($row['id'] => $row['name']);
}


text:
Q: 'Clone URL is incorrect' when importing from GitHub to Azure DevOps I am trying to import a GitHub repository to Azure DevOps and I keep getting this error:
Import request cannot be processed due to one of the following reasons:

Clone URL is incorrect.
Clone URL requires authorization.

Here is a screenshot of my input parameters:

I have double and triple checked the cloning url and the authentication parameters. No matter what I put into the fields it always displays these two errors.
How can I trouble shoot this?

A: I've tested the Import a Git repository in sevral situations: public or private Github repo, with or without access in PAT and with or without file in Github repo.
Only in two cases i can reproduce the problem:

*

*No file exists in the Github repo, if there's nothing in the Github
    repo, seems the url https://github.com/****/*****.git can not be
    recognized successfully.
In this case, you need to upload at least one any file into the repo
    and the url will be recognized then.

*Wrong PAT, we copy PAT from one place to another, there might be
unexpected characters included, such as a space.
In this case, you need to check the PAT by click the little eye icon
in the input textbox, delete or add characters to make it correct.

A: Got the very same problem when trying to make a fresh new import of a private GitHub repo managed by an Organization to my new Azure DevOps account (even though my account is the owner of both GitHub and Azure DevOps profiles I was trying to link).
Three steps actually helped me to resolve it:

*

*Link two accounts via Azure DevOps > your project > Project Settings > GitHub connections. If your GitHub repo is stored in an Organization profile, here you have to make sure that you grant access to this Organization while you're setting up the connection in Azure DevOps (there will be a small Grant button next to the identified Organization profile in Azure DevOps, you have to press it to actually grant the access). In my case I missed it and the connection did not work (Azure DevOps couldn't find any repos in the GitHub profile). To resolve this, I had to follow the link from an automatic e-mail sent to me by GitHub and grant access to Azure DevOps there. Then in Github > your organization > Organization Settings > Third-party access you will be able to see Azure DevOps in the list - if the status is Approved, you're good to go.

*Then I had to create a PAT for my personal profile in GitHub (NOT the Organization profile) and use it instead of the password when I was importing the repo in Azure DevOps (big thanks to @Yang Shen who pointed this out above). This way you first have to go to Github > your profile > Profile Settings > Developer Settings > Personal access tokens and generate a new token there.

*Then I returned to Azure DevOps > your project > Repos > Files > Import, putting in:
a) Link to my private Github repo;
b) Tick "Authentication required";
c) My GitHub username;
d) My PAT generated at Step 2 above instead of my actual password
Then it worked like a charm, my private Github repo was cloned to Azure Repos.

A: For me, it was because the GitHub repo I wanted to copy was Private.
Make it Public* and try again.

*

*Go to the GitHub repo you want to import, on the Settings's page change the visibility to Public.

*Copy the .git (HTTPS) URL of the repo.

*On Azure, paste the link and click on Import.

*

*WARNING: Please be aware of the implications of making your repo public.

My GitHub repo Settings' page

A: This should be the answer:
you must provide your User Name. The aeterisk * is missing though

A: I just recognized
"Generate Git Credentials" does the trick!
In your source repos, you must "Generate Git Credentials"

In your dest repos where you click import use the "Clone Url" from source and enter the generate Git credentials!

A: I found the solution!

*

*In your GitHub account, go to your icon in the top right corner and then click on Settings

*In the left sidebar, click on Developer settings

*Then in the left sidebar again, click on Personal access tokens

*Click the button Generate new token

*Give the token a name, e.g. 'Move to Azure'

*Set the Expiration to however long you need it to be for your move

*Under Select scopes, tick repo

*Click on the green button labeled: Generate token

*Copy your token (save it in a password safe if you have multiple repos)

*In Azure, paste it into the field Password / PAT

*After you've moved all repositories, don't forget to delete your Personal Access Token from GitHub

A: I get this message even if I want to copy a Repos from the same Account from another project. No chance! I am wondering why the Clone URL refers to a "*.git" file? If I take the "Clone Repos URL" from the source repos, there is no ".git" at the end.

A: I had the same issue when trying to import a private repository.
I had missed a step when setting a Personal Access Token (Github > Settings > Developer Settings > Fine-grained tokens).
I had selected "All repositories" in the Repository Access section, but didn't realise I also needed to set "Repository permissions" in the Permissions section. I now have this:

where "Contents" is set to Read-only access:

(Metadata is also set to Read-only when the above is set)
Without setting Permissions, the PAT reverts to "Public Repositories (read-only)". It's also possible to edit existing PATs, so easy to check if permissions are correctly set.

A: i ran into same issue it worked when i enter my exact Github username and PAT. While creating PAT, make sure to select github scopes: repo and projects.


text:
Q: Simplify the sum of vectorspaces Consider the two subspaces $U_1,U_2\subset\mathbb{R}⁴$ given as $$U_1=\mathbb{R}(0,1,2,0)+\mathbb{R} (0,0,1,1),\quad U_2=\mathbb{R}(1,0,1,1)+\mathbb{R}(-3,1,1,-1).$$
How can I find vectors $w_1,w_2,w_3\in\mathbb{R}⁴$ such that $U_1+U_2=\mathbb{R}w_1+\mathbb{R}w_2+\mathbb{R}w_3$? I already found an vector $v$ such that $U_1\cap U_2=\mathbb{R}v$, namely $v=(0,1,4,2)$. Maybe this helps.

A: Of course it helps (if it is correct; I did not check it)! Call $w_3$ to your vector $v$. Find a vector $w_1\in U_1\setminus\mathbb{R}w_3$ and a vector $w_2\in U_2\setminus\mathbb{R}w_3$ and you're done.

A: Let call $v_1=(0,1,2,0),\ v_2=(0,0,1,1),\ v_3=(1,0,1,1),\ v_4=(-3,1,1,-1)$
You have $\DeclareMathOperator{\Span}{Span} U_1=\Span(v_1,v_2)$ and $U_2=\Span(v_3,v_4)$.
Since $a.v_1+b.v_2=0\iff\begin{cases}0=0\\a=0\\a+2b=0\\b=0\end{cases}\iff a=b=0\quad$ then $\dim U_1=2$.
Similarly $a.v_3+b.v_4=0\iff\begin{cases}a-3b=0\\b=0\\a+b=0\\a-b=0\end{cases}\iff a=b=0\quad$ then $\dim U_2=2$.
Now $U_1+U_2=\Span(v_1,v_2,v_3,v_4)$ but what is its dimension ?
$\sum a_iv_i=0\iff\begin{cases}c-3d=0\\a+d=0\\2a+b+c+d=0\\b+c-d=0\end{cases}\iff\begin{cases}c=3d\\a=-d\\0=0\\b=-2d\end{cases}$
This system is of dimension $1$ meaning that $U_1+U_2$ is only of dimension $3$.
This is because the $4$ vectors are not linearly independent : indeed $v_4=v_1+2v_2-3v_3$.
So finally a basis for $U_1+U_2$ is $\Span(v_1,v_2,v_3)$ but you can also select any $3$ among the $4$ vectors.

There was no need to go for $v\in U_1\cap U_2$ because you already have the vectors you want.
This would matter if you were asked for a basis of $V=U_1\cap U_2$ in order to find $E=V\oplus W$ where $V=\mathbb Rv=\Span(w_3)$ and $W=\Span(w_1,w_2)$.
But here you are NOT asked for a direct sum, just $U_1+U_2$, this is a simpler question, and the resulting basis is just a subset of the set of vectors forming the basis for $U_1$ and $U_2$.


text:
Q: How to persist a connection pool for asyncpg and utilise it in Databases wrapper? As per FastApi documentation, I'm using the Databases wrapper and Sqlalchemy Core to do async operations on the postgres database.
I have come across an issue where the connection gets closed in the middle of operation. As it turns out it is an issue with asyncpg and can be resolved by using a pool.
However I'm not using asyncpg directly, but use the Database wrapper as it was recommended by FastAPI. How can I create a pool like this:
await asyncpg.create_pool(database="dbname",
    user="username",
    password="dbpw",
    max_inactive_connection_lifetime=3)

and utilise it within the databases wrapper?
import databases
from sqlalchemy import MetaData

db = databases.Database(settings.SQLALCHEMY_DATABASE_URI)
metadata = MetaData(schema='main')

A: Under hood database.connect uses asyncpg.create_pool, your SQLALCHEMY_DATABASE_URI already has connection vars, you could also add additional connection options:
db = databases.Database(settings.SQLALCHEMY_DATABASE_URI, max_inactive_connection_lifetime=3)

They will be passed to asyncpg.create_pool on connection.


text:
Q: Difference between on touch down, up and move As I am a little confused to know the meaning and difference between on_touch_down(),
on_touch_move(),
on_touch_up(). Can anyone explain me how these functions works?
Note: I have already read the documentation, still couldn't understand.

A: To explain correctly I will use the following example:
from kivy.app import App
from kivy.uix.widget import Widget

class MyWidget(Widget):
    def on_touch_down(self, touch):
        print("on_touch_down")
        return super(MyWidget, self).on_touch_down(touch)

    def on_touch_move(self, touch):
        print("on_touch_move")
        return super(MyWidget, self).on_touch_move(touch)

    def on_touch_up(self, touch):
        print("on_touch_up")
        return super(MyWidget, self).on_touch_up(touch)

class MyApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()

If we press with the mouse, then move it and then release it we get the following:
on_touch_down
on_touch_move
on_touch_move
on_touch_move
...
on_touch_move
on_touch_move
on_touch_move
on_touch_up

And this is precisely what is managed in these 3 events:
on_touch_down: It is called when the mouse is pressed for the first time.
on_touch_move: It is called while you move the mouse while holding down
on_touch_up: It is called when you release the mouse.


text:
Q: Keys whose values extend V For example:
interface Foo {
  a: string
  b: string
  c: number
}

How can I define KeysOf<T, V> such that KeysOf<Foo, string> gives "a" | "b" and KeysOf<Foo, number> gives "c"?
I tried type KeysOf<T, V> = T[infer K] extends V ? K : never, but TypeScript does not allow infer on the left operand of extends.

A: You can do this with a mapped type and a conditional type:
interface Foo {
   a: string
   b: string
   c: number
}

type KeyOf<T, V> = {
    [P in keyof T]: T[P] extends V ? P : never
}[keyof T]

type S = KeyOf<Foo, string> //"a" | "b"
type N = KeyOf<Foo, number> //"c"


text:
Q: Can I map resources to a different controller? I have my resources already defined, but a client wants to change the names of the URLs to match their brand (e.g. something like "catalog" when the resource is currently "products").  Can I specify a different controller name with a resource so I can get all the built-in resources functionality without having to actually rename the controller and model names?

A: For the record: map.resources :products, :controller => "catalog" is how you do this.

A: The rails guide specifies how to use specific controllers for certain routes.
You can do something like this:
Rails.application.routes.draw do
  resources :products, controller: "catalog"
  # but rails conventions suggests you should pluralise your controller name
  # so use "catalogs" (plural) instead of the singular "catalog"
end

A: Okay it looks like it's as simple as adding the controller name, and it seems to be working.  Nevermind!