text:
Q: Add labels to BigQuery tables using Airflow BigqueryOperator I have to add labels to the bigquery tables. I am aware of doing it through BigQuery UI but how can it be done through airflow operators.
Use case : For billing and searching purpose. As multiple teams work under same project and dataset, we need to club together all the tables created by respective teams. As each team will have different labels for the tables, hence labels are necessary for us.
bq_query = BigQueryOperator(bql=sql,
                            destination_dataset_table='my_dataset.my_table'),
                            task_id='bq_query',
                            bigquery_conn_id='my_bq_connection',
                            use_legacy_sql=False,
                            write_disposition='WRITE_TRUNCATE',
                            create_disposition='CREATE_IF_NEEDED',
                            query_params={})

Here I want to add label to this destination table destination_dataset_table='my_dataset.my_table'
I did give a try as mentioned in this link : https://airflow.apache.org/docs/apache-airflow/1.10.12/_api/airflow/contrib/operators/bigquery_operator/index.html#airflow.contrib.operators.bigquery_operator.BigQueryOperator.template_fields
from airflow import models, DAG
from airflow.contrib.operators import bigquery_operator, bigquery_to_gcs, bigquery_table_delete_operator
from airflow.operators.python_operator import PythonOperator

# Define Airflow DAG
with dag:

    bq_query = BigQueryOperator(sql='<some query>',
                                destination_dataset_table='my_dataset.my_table'),
                                task_id='bq_query',
                                use_legacy_sql=False,
                                write_disposition='WRITE_TRUNCATE',
                                create_disposition='CREATE_IF_NEEDED',
                                labels={'project_id': 'project_name', 'dag_id': 'dag_name', 'task_id': 'task_name'}
                                query_params={})

EDIT
Note : The definition of labels  is different for BigqueryOperator and BigqueryCreateExternalTableOperator as per the documentation.
Definition of labels for BigqueryOperator is a dictionary containing labels for the job/query, passed to BigQuery which is happening fine. But I wanted to add a label to the table when it gets created.
We are widely using BigqueryOperator and cannot use BigqueryCreateExternalTableOperator
Is it possible using BigqueryOperator? or a workaround

A: With the class airflow.contrib.operators.bigquery_operator.BigQueryOperator you are using, you can use the parameter label. You can see the parameters that supports.
labels  – a dictionary containing labels for the job/query, passed to BigQuery
classairflow.contrib.operators.bigquery_operator.BigQueryOperator(bql=None, sql=None, destination_dataset_table=None, write_disposition='WRITE_EMPTY', allow_large_results=False, flatten_results=None, bigquery_conn_id='bigquery_default', delegate_to=None, udf_config=None, use_legacy_sql=True, maximum_billing_tier=None, maximum_bytes_billed=None, create_disposition='CREATE_IF_NEEDED', schema_update_options=, query_params=None, labels=None, priority='INTERACTIVE', time_partitioning=None, api_resource_configs=None, cluster_fields=None, location=None, encryption_configuration=None, *args, **kwargs)

You can use this class airflow.contrib.operators.bigquery_operator.BigQueryCreateExternalTableOperator to create the table with tags
labels  – a dictionary containing labels for the table, passed to BigQuery
classairflow.contrib.operators.bigquery_operator.BigQueryOperator(bql=None, sql=None, destination_dataset_table=None, write_disposition='WRITE_EMPTY', allow_large_results=False, flatten_results=None, bigquery_conn_id='bigquery_default', delegate_to=None, udf_config=None, use_legacy_sql=True, maximum_billing_tier=None, maximum_bytes_billed=None, create_disposition='CREATE_IF_NEEDED', schema_update_options=, query_params=None, labels=None, priority='INTERACTIVE', time_partitioning=None, api_resource_configs=None, cluster_fields=None, location=None, encryption_configuration=None, *args, **kwargs)
template_fields= ['bql', 'sql', 'destination_dataset_table', 'labels']

You can see more information about these two classes.
EDIT
You can see this example.
   bq_query = BigQueryOperator(bql=sql,
                                destination_dataset_table='my_dataset.my_table'),
                                task_id='bq_query',
                                bigquery_conn_id='my_bq_connection',
                                use_legacy_sql=False,
                                write_disposition='WRITE_TRUNCATE',
                                create_disposition='CREATE_IF_NEEDED',
                                template_fields= ['dataset_id', 'table_id', 'project_id', 'gcs_schema_object', 'labels']
                                query_params={})

You can see this example on how to use it.


text:
Q: How to enable VSTO for all users in MSI? I have an MSI (in VS 2010) that is creating a VSTO (4.0) (targeting .NET 4.0; for Office 2007) in the x86 Program Files folder, and everything seems to be fine.  The registry correctly shows the VSTO, the VSTO's files are installed in the correct location, and after I load the Office application, I can see the plugin in the add-ins.
When I try to enable it in Office, I get the following error:
"This add-in is installed for all users on this computer, and can only be connected or disconnected by an administrator."
It will be installed by an administrator for all users -- is there a custom action or something I can do in the MSI to ensure that it gets registered/connected for all users?
I've double-checked the registry -- the LoadBehavior for the VSTO is still 3 and without problems...
Any thoughts?

A: As a lesson learned, I discovered that because we were signing the package, the reason it didn't work was because the certificate was NOT installed on the machine.  As such, I had to manually install the certificate for signing and then I could easily make it install "For Everyone" or "Just Me" without a hitch.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change window text? case WM_PAINT:
  {
    PAINTSTRUCT pt;
    HDC hdc;
    hdc=BeginPaint(hWnd,&pt);
    SetTextColor(hdc,RGB(255,0,0));
    SetBkColor(hdc,RGB(0,255,0));
    SetBkMode(hdc,TRANSPARENT);
    //为什么矩形绘制成功,但是字体没有绘制呢?
    TextOut(hdc,0,0,TEXT("WM_PAINT"),strlen("WM_PAINT"));
    EndPaint(hWnd,&pt);
  }

We use above code to write text in a Window.  What should i do if want output "int i" to window, i increace every second? i means ouput 0, 1, 2, 3, 4, 5.... in to window.

A: Store your i variable somewhere that your WM_PAINT handler can access it. Then, whenever you change the value of i, such as in a timer, then you can call InvalidateRect() to trigger a repaint. Your WM_PAINT handler should draw the current value of i whenever the window needs to be painted.
int i = 0;

...

case WM_TIMER: {
    ++i;
    InvalidateRect(hWnd, NULL, TRUE);
    break;
}

case WM_PAINT: {
    PAINTSTRUCT pt;
    HDC hdc = BeginPaint(hWnd, &pt);
    SetTextColor(hdc, RGB(255,0,0));
    SetBkColor(hdc, RGB(0,255,0));
    SetBkMode(hdc, TRANSPARENT);
    TCHAR str[16];
    int len = wsprintf(str, TEXT("%d"), i);
    TextOut(hdc, 0, 0, str, len);
    EndPaint(hWnd, &pt);
    break;
}


text:
Q: How does one get the code as a string of an object? I was attempting to do a little metaprogramming and I was wondering how to get the code for an object (or ActiveRecord relation) passed to a method. Ideally, it would return the string of the ruby code. For example:
class Bike
end

# Ideal response
get_code_for(Bike.new)
#=> 'Bike.new'

get_code_for(User.where(id: 123))
#=> 'User.where(id: 123)'

get_code_for(Article.published)
#=> 'Article.published'

This works for numerics and strings, however, for classes and relations, the arguments are evaluated and return something along the lines of #<Bike:0x000056338e33fca8>.

A: If you want a pointer to a method, you can get that with Class#method. This gets you a Method instance which has methods such as #receiver and #name.
m = Bike.method(:new)
m.receiver # => Bike
m.name # => :new
m.call # => #<Bike:0x000000017a7078>
format("%s.%s", m.receiver, m.name) # => "Bike.new"


text:
Q: How to implement a pandas dataframe row as an object (and have its own methods)? I am using a pandas dataframe to hold financial data (time series of candlesticks).
Columns are: (index: datetime, financial_instrument, granularity, open, high, low, close, volume).
I have built a class that stores this dataframe to implement specific methods for this kind of object (time series of candlesticks), such as:
def getCandle(self, i):
    try:
        return self._list_of_candles.iloc[i:]
    except:
        return None

def getLastCandle(self):
    return self.getCandle(-1)

def getPreviousCandle(self):
    return self.getCandle(-2)

It makes a lot of sense for me to think as each row on the dataframe as an object (candlestick), and to have specific methods for this object, such as:
def getCandleSize(self):
    return self.getHighValue() - self.getLowValue()

I am open to completely different lines of thought on how to deal with this problem and how to architecture its solution.
I honestly have no clue on how to solve it. The solution I can see now is by implementing some specific methods on top of the pandas series object. But how to implement it is not clear to me.
Once the row (candle) is selected from the dataframe, it can be manipulated quite a lot, so in previous applications I had built, it was really useful to have a 'Candle' class for these kinds of operations.
I need a performant solution. I really appreciate if you can point me in the direction of a solution for this problem. Thank you.
UPDATE: I am thinking about converting the selected row to a Candle object, as it seems much easier to build code if it is structured that way, as I don't need to be making fecthing data from the dataframe for each atributte or calculation to be made.


text:
Q: Adding a new statisitical distribution What would I need to define to add a new statistical distribution to Mathematica?
Ideally, it would support as many of Mathematica's statistical functions as possible.
In practice, this might most easily be done using ProbabilityDistribution or TransformedDistribution but are there alternatives?
For example, I can give definitions for unknowndistribution  (PDF unknown, but specified mean and variance).  For example
Mean[unknowndistribution[μ_, σ_]] ^:= μ
Variance[unknowndistribution[μ_, σ_]] ^:= σ^2

I then can write
d = unknowndistribution[μ, σ];
Mean[d]
(* μ *)

but if I try
TransformedDistribution[x + y, {x \[Distributed] d, y \[Distributed] d}]

it returns effectively unevaluated.
Motivation
Some comments have questioned the motivation for doing this.  I'm interested because I want to understand the capabilities of Mathematica.
Clearly, internal distributions are not defined in terms of ProbabilityDistribution e.g.
ProbabilityDistribution[PDF[NormalDistribution[], x], {x, -∞, ∞}]

does not transform automatically to NormalDistribution[0,1].  Internally defined distributions are better supported that those defined via ProbabilityDistribution.  It would be interesting to know if it was possible to get some of these additional benefits (without having to add too many definitions).
Doing so is probably hard, but you only establish if a problem is impracticably hard by thinking about and asking other people who probably know far more.


text:
Q: I am trying to update a previously entered date in the past to the current date, if a condition is met I have a worksheet that I use to help forecast cash flow.
Column V is a date that is initially the anticipated invoice date, and upon issuance of an invoice, becomes the actual invoice date.  Upon issuing a Purchase Order("D:D") or Invoice("F:F"), I manually enter the associated number and the current date is entered in the appropriate cells of that row, Purchase Order(With rCell.Offset(0, 11)){Column O} Invoice(With rCell.Offset(0, 16)){Column V}, to be referenced in other worksheets.
I've discovered the need to automatically make sure that the date in Column V is never in the past, which does occasionally occur.  I am having difficulty with this.  I need to only update Column V dates in the past, to the current date, IF Column F is empty.
Any assistance would be greatly appreciated!
Chris
This is what I have.  The first two routines run as desired.  The third is the current date issue, and does not function as expected.
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    Dim rCell As Range
    Dim rChange As Range

    On Error GoTo ErrHandler
    Set rChange = Intersect(Target, Range("D:D"))
    If Not rChange Is Nothing Then
        Application.EnableEvents = False
        For Each rCell In rChange
            If rCell > "" Then
                With rCell.Offset(0, 11)
                    .Value = Now
                    .NumberFormat = "mm/dd/yy"
                End With
            End If
        Next
    End If

    On Error GoTo ErrHandler
    Set rChange = Intersect(Target, Range("F:F"))
    If Not rChange Is Nothing Then
        Application.EnableEvents = False
        For Each rCell In rChange
            If rCell > "" Then
                With rCell.Offset(0, 16)
                    .Value = Now
                    .NumberFormat = "mm/dd/yy"
                End With
            End If
        Next
    End If

    On Error GoTo ErrHandler
        Set rChange = Intersect(Target, Range("F:F"))
        If Not rChange Is Nothing Then
            Application.EnableEvents = False
            For Each rCell In rChange
                If rCell = "" Then
                    With rCell.Offset(0, 16)
                        If .Value < Now - 1 Then
                            .Value = Now
                            .NumberFormat = "mm/dd/yy"
                        End If
                    End With
                End If
            Next
        End If

ExitHandler:
    Set rCell = Nothing
    Set rChange = Nothing
    Application.EnableEvents = True
    Exit Sub
ErrHandler:
    MsgBox Err.Description
    Resume ExitHandler

End Sub

A: This seems to work for me:
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    Dim rCell As Range
    Dim rChange As Range

    On Error GoTo ErrHandler
    Set rChange = Intersect(Target, Range("D:D"))
    If Not rChange Is Nothing Then
        Application.EnableEvents = False
        For Each rCell In rChange
            If rCell > "" Then
                With rCell.Offset(0, 11)
                    .Value = Now
                    .NumberFormat = "mm/dd/yy"
                End With
            End If
        Next
    End If

    '## combining your two loops into a single block ##
    Set rChange = Intersect(Target, Range("F:F"))
    If Not rChange Is Nothing Then
        Application.EnableEvents = False
        For Each rCell In rChange
            With rCell.Offset(0, 16)
                .NumberFormat = "mm/dd/yy"
                If Len(rCell) > 0 Then
                    .Value = Now
                Else
                    If .Value < Now - 1 Then .Value = Now
                End If
            End With
        Next
    End If

ExitHandler:
    Set rCell = Nothing
    Set rChange = Nothing
    Application.EnableEvents = True
    Exit Sub
ErrHandler:
    MsgBox Err.Description
    Resume ExitHandler

End Sub


text:
Q: Access local front-end connected to Azure SQL Server back-end very slow I've been using Access to rapid-prototype a DB. Now I'd like to do a small group online test so I split the DB and placed the back-end on Azure SQL Server, then re-linked. It's incredibly slow and I've been researching solutions for days without positive results. My local environment is Win10, Office2016 64bit and internet connection is fast and stable.
I have tried different ODBC drivers, including the SQL Native Client v11.
I've disabled auto-tuning level on the NIC.
I've recreated all queries from access on the server.
I've made sure that Tracing in ODBC is off.
But I enabled tracing temporarily to see what was happening. If I opened the front-end, logged in (Small user table), and did something on the first form (Add 1 record with 3 sub-records...and really...nothing fancy or heavy at all and this only takes 1 minute) then closed the DB, I see that the Tracing log file is 1.5MB.
So I created an empty Access file and an ODBC link to only the User table (12 columns, 20 records), and then monitored the tracing log file again. Opening access doesn't add anything to the log file, but opening this one, linked table made the log file grow to 255kb. Opening this table in access took 5 seconds.
Access sent about 800 requests to the server for opening just this one small table. If I paste all the User table data into a text file, it's only 2kb. SO why is it so slow?
Any ideas on this, and specifically other suggestions to get this working faster?
Kind regards,

A: Well, the reason why using Azure is slower than running Access connected to a local instance of SQL server is because, well slow is slow!
I mean, if you going to travel 30 miles, you have a choice to walk, or to take a car.
So here is the question you need to know:
Why is walking slower than driving a car?
Answer: Because you are travelling at a slower speed!
So why is using Azure slower the using an instance of SQL server running on your local computer or local network?
Answer:
Because the connection speed to Azure is about 100 times slower!
The idea here that you not going to take into account the DIFFERENCE in connection speed is the issue here. It is a disservice to the reading public that may conclude that such a setup (Access front end on a pc to Azure instance of SQL server) is not a viable setup.
So the first issue here is to make a note of your connection speed to the back end database.
A typical office local area network has a speed of 100mbits, or today most are 1gig – even the el-cheapo routers you purchase at Best Buy are now rated at 1gig (1000 mbits).
However, your typical high speed internet is rated at about 5, or 10 mbits. So that is 100 times slower. (Actually 1000/5 = 200 times slower!!!).
That means if something NOW takes 3 seconds on your office network with Access and SQL server? Well then a WAN (over the internet), then you need to multiple the time by the change in your connection speed (this is so simple – yet it seems to escape all!). So, if you lucky, you might have a 5 mbits speed rating for your internet. That means you go
1000 / 5 = 200
You now take the 200 and multiple the existing delay you have of say 3 seconds and you get 600 seconds (that is 10 minutes if you are wondering!). So you going from 3 seconds to 10 minutes!
This kind of comparison in speed would be like walking into a sports shop to purchase a rubber boat to cross the Atlantic. So not taking into account the change in internet speed and wondering why things are slow is the issue here.
You can most certainly use Access to Azure, but you have to realize two simple concepts.

*

*a connection and test with a connection that is 50-200 times slower than your LAN is a test that going to run 50 to 200 times slower! The failure to mention and take into considering the MASSIVE DIFFERENCE in your speed connection of your LAN compared to a WAN is the simple issue here.

*opening a form bound to a large table of data is going to case performance issues.

I was sitting at the bus stop talking to a 90 year old granny lady. I asked her the following:
Have you ever used an instant teller?
She said, why yes, I use them all the time.
I then asked here don't you think it would be bad to have the teller machine download all the peoples accounts while you wait and THEN ask you for your account number?
The old lady stated, of course, that would be silly. I type in my account pin and the machine ONLY downloads my account information – this is practical and obvious.
In other words that old lady realised that downloading a bunch of data BEFORE you the user even types in or does anything is a waste of bandwidth.
So you never want to launch a form bound to a table and THEN ask the user what record to work on. Why have Access download large numbers of records into a form and THEN ask the user or allow the user to navigate to the required record?
Even when using Google, it does not download the whole internet into your web browser page and you then go ctrl+f to search the contents of that web page.
The same concepts should be applied to Access applications. A design that asks for what to work on and then launches a form bound to a table with a "where" clause will thus fix this issue.
So if you have a form (and even a sub form) that displays a customer invoice, you would FIRST ASK FOR the invoice number, and then simply launch that form using a where clause that restricts the form to the ONE invoice!
Keep in mind that you can STILL use that invoice form bound to a table of 1 million rows and ONLY THE ONE record will be pulled down the network connection *if one used the where clause.
So a typical internet connection has adequate speed to run a browser, and also has MORE than adequate bandwidth speed to pull down a few records. Access often gets a bad rap for poor performance, but that is ONLY DUE to Access developers IGNORING the obvious advice that downloading tons of things that you don't yet need into a form will run slow.
So web based applications, or even desktop applications written in vb.net perform well with SQL Azure running in the cloud over that MUCH slower internet connection because those applications don't launch forms bound to large datasets WITHOUT FIRST simply allowing the user to request what they need to see and view.
As for Access and using SharePoint? That setup can be VERY fast, and in fact MUCH faster than SQL Azure, MySQL or any traditional database system because when you using SharePoint tables and Access, then Access automatic syncs a copy of the data local. This setup means your application will continue to run WITHOUT ANY internet connection. The instant the connection is restored, then the data sync can resume.
This means that if you have a table with 15,000 rows and run a report on that data the report can run and launch in an instant with SharePoint back end since a local copy of the data exists in the front end at ALL TIMES! So this setup is VERY well suited an off line mode or in cases that you have a poor and slow internet connections since you as noted always have local copy of the data – only when a record is changed does a sync occur, and that sync can occur independent of Access. So you change one record – and it starts syncing with SharePoint.
However for larger data sets that have to be updated, then SQL server is far better since you can execute a sql update on 10,000 rows and ZERO network traffic and transfer of data need occur to update those 10,000 rows when using SQL server (a pass through query) and when using SharePoint, the 10,000 rows WILL transfer over the network since the local copy requires the rows to be updated. So that massive advantage of using SharePoint for the database backend does not exist for applications that have to update lots of rows or do lots of row update types of data processing.
So the key concepts and take away here:
The high speed internet connection you have is often 10-200 times slower than your typical cheap office (local) network. So that means a 2 second operation will now take 10-200 times longer.
The Access application needs to be optimized to avoid things like loading too many records into a form. So building search forms etc. That FIRST ASK the user what they need to work on is a basic and simple requirement for all good developers and that includes Access developers.
Access and SharePoint can be the BEST option, and such a setup allows the application to run EVEN WHEN there is no internet connection at all. If table sizes are below say 10,000 rows, then this setup can often be ideal. However for applications that have to update lots of rows and for data processing heavy applications this setup is poor since updates to any rows will case data syncing to occur over the network. This setup is also the cheapest, since a single office 365 account with SharePoint support for Access can be had for $6 per month, and that $6 account allows up to 500 free users and those 500 users can even use their Gmail or non-Microsoft account for this setup. And such access applications that do fit within the bounds of SharePoint tables tend to need far less changes and optimizing then using SQL server over the internet.
With SQL server, use of views, pass-tough query and in some cases writing store procedures allows updates and code to run WITHOUT using ANY bandwidth. So one can send a single update query to the server that updates 10,000 rows of data – the only network cost will be the "tiny" amount of bandwidth to send that sql statement.
So while bound forms can be used with SQL Azure running in the cloud, one needs to build software like those do for the web, or vb.net in which they FIRST ask the user what account or customer to work on and THEN launch the UI to display that given data.
So in access, you build a search form say like this:

So at the end of the day, it is important to ignore posts here that suggests Access to SQL in the cloud is not viable. Access with proper designs will work rather well over typical internet connections to SQL server running on Azure.
In fact I seen people use Access to SQL over a 56k modem!
One has to adopt sensible designs in which the data pulled for a given task is restricted – this is a hall mark of all developers – the only issue is Access does NOT enforce this approach while most other developer tools don't let you hang yourself with things like bound forms to large tables! It not that Access is slow, but Access is slow when you make poor design decisions.
Access to SharePoint can be a real winner – especially for poor bandwidth, spotty bandwidth and even when the connection is lost, the application will continue to run and run faster than 99% of the cases if you were running the same application with a SQL back end. There is a BIG caveat here since only certain types of applications will work well with SharePoint tables. For me to explain the why, how, and when such applications are better is beyond a simple post here, but one simply needs to be aware that SharePoint can be incredible solution, but not for all applications and SQL server can and will be better choice. This SharePoint "better" choice can only be determined on a case by case evaluation of the given type of application in question.

A: The problem is simply that Azure SQL Database is not very fast running with small DTUs (Database Transaction Units) compared to, say, an in-house instance of SQL Server hosted on even a moderate modern server.
I've checked it out too, and it requires extremely careful design of queries and filtering - far from what you normally can get away with - to obtain acceptable overall speed. On the other hand, this is a giving experience that will bring focus to potential bottlenecks you otherwise wouldn't encounter before it might be too late.

A: OK, so after almost a week of trying to get this to work (Access front-end to SQL Server back-end on Azure), I've come to the conclusion that it's not a viable solution.
I've tried SQL Server, and setup a Sharepoint 2016 server on Azure, which also failed.
What has worked is using a product from Bullzipp called MS Access to MySQL to convert the access tables, then adding a MySQL DB on the server and importing the file generated by Bullzip. The only thing to note here is that Bullzip doesn't like the newer access formats (it wants an MDB file) so go to Access, create a new, empty file, but make sure you set its file type to MDB. then import your tables across and run Bullzip.
It's now working a hell of a lot faster than the SQL Server, but I am getting some write conflicts in Access, so I just need to go through the code and do whatever I need to so I can avoid those messages.

A: Using Access as a front to Azure SQL tables is the worst solution.  But, sometimes you have to do it.  I have a client who is adamant that she wants to keep her Access database.  When she hired her very first employee, it became clear she needed to SQL tables behind the screens.
This was a bit of a nightmare.  However, after redesigning some terrible table structures, creating views and many procs, I've been able to do it.  I use local tables in some cases, and refill by pulling from a stored proc and inserting into the local table.  I use linked tables for basic data edits, and do explicit save records almost constantly.
I also have a first-load module that opens all forms, goes to the last record, back to the first record, and then hides the form until needed.  The load limps along for about 3
My only remaining issue is now that Azure will close connections after idle time of (I think) 30 or more minutes -- or maybe it's when the laptop sleeps?  That kills the app and it has to be closed and re-opened.


text:
Q: XHTML:  tag to multiple destinations in multiple target frames? I'm working on a table of links within a site using iframes. I'm wondering if there's any way to code a link to go to two simultaneous destinations within two different target frames? I've been reading all afternoon and can't find anything close to what I want to do. Basically I want one link to present a photo in one iframe and some data in another iframe. Any ideas?

A: Short answer: No.
Longer answer: With what you describe, using strictly X/HTML, this isn't possible. You could add in javascript to change the iframe src, however. Something like:
function click_link(id) {
    document.getElementById('iframe1').src = "page.ext?id=" + id;
    document.getElementById('iframe2').src = "other_page.ext?id=" + id;
}

But of course, you probably shouldn't be using iframes anyways...

A: The easy way is javascript, but that method has been answered already. The only way to do this (without relying on javascript) is serverside.
Make your <a target > link back to the top frameset that contains all the frames you want to change and on the serverside change the src attributes of the frames.

A: Don't use frames. They're bad for usability, bad for SEO, and cause problems like this.
This may seem unhelpful advice, but really in the long run you'll avoid a lot of headaches.
If you merge files on the server side, they'll work without problems in every browser, search engine, etc. Reloading of a simple page doesn't have to be slower than loading of 2 iframes.
Or, in case of showing photos with descriptions, a simple DHTML could do the job:
img.onclick = function(){
   $('bigphoto').src = this.src.replace(/_small/,'_big');
   $('description').innerHTML = this.title;
}


text:
Q: Using tc to delay packets to several ports After reading several pages like this this and without having a really deep knowledge about the kernel Linux, I am able to filter up to 3 ports using just the three first leaves of the tree.
tc qdisc del dev enp0s3 root //clear any previous configuration
tc qdisc add dev enp0s3 root handle 1: prio //start new queue disc but no classes yet

tc filter add dev enp0s3 parent 1: protocol ip prio 1 u32 match ip dport 6332 0xffff flowid 1:1
tc filter add dev enp0s3 parent 1: protocol ip prio 1 u32 match ip dport 6333 0xffff flowid 1:2
tc filter add dev enp0s3 parent 1: protocol ip prio 1 u32 match ip dport 6334 0xffff flowid 1:3

tc qdisc add dev enp0s3 parent 1:1 handle 30: netem delay 146ms
tc qdisc add dev enp0s3 parent 1:2 handle 20: netem delay 275ms
tc qdisc add dev enp0s3 parent 1:3 handle 10: netem delay 258ms

My problem is that I would like to have more port filters in order to simulate a big scenario with up to 16 possible ports destination. If I try to add a new filter using 10:1 what I get is that the delay is not correct because it starts adding two or more rules and I reach to have more than 1 second delay which is what I don't want to have.


text:
Q: APK Expansion Files for different screen resolutions My application requires 50MB+ of images for it to run properly. I was planing to provide different resolutions of images for different screen. The version of images are 1080p, 720p and 480p images in order to support more screens.
Is it possible to use the APK Expansion Files to host and download the files based on the screen resolution?


text:
Q: Retrieve data from realtime database into listview This is my file song.dart
class Song {
  final String title;
  final String singer;
  final String cover;
  final String url;

  Song(this.title, this.singer, this.cover, this.url);

  Song.fromJson(Map<String, dynamic> json)
      : title = json['title'],
        singer = json['singer'],
        cover = json['cover'],
        url = json['url'];

  Map<String, dynamic> toJson() => {
    'title': title,
    'singer': singer,
    'cover': cover,
    'url' : url,
  };
}

On the main.dart, this is the code that I was trying to get data from realtime database:
  List musicList = <Song>[];
  _MusicAppState() {
    FirebaseDatabase.instance.reference().child("${getCurrentUID()}").once().then((DataSnapshot snapshot){
      print("Sucessfully loaded the data");
      snapshot.value.forEach((k,v){
        musicList.add(v);
      });
      setState(() {
      });
    }).catchError((error) {
      print("Failed to loaded the data");
    });
  }

Also on the main.dart, this is the part of code that I was trying to show data into listview:
Expanded(
  child: ListView.builder(
    itemCount: musicList.length,
    itemBuilder: (context, index) => customListTitle(
      onTap: () {
        playMusic(musicList[index]['url']);
        setState(() {
          _currentTitle = musicList[index]['title'];
          _currentSinger = musicList[index]['singer'];
          _currentCover = musicList[index]['cover'];
        });
      },
      title: musicList[index]['title'],
      singer: musicList[index]['singer'],
      cover: musicList[index]['cover'],
    ),
  ),
),

I don't know why the data didn't load into listview. But the data will be loaded into listview if I remove the <Song> in the line of  List musicList = <Song>[];. How can I load the data into listview with the <Song>? Because I need the class Song in order to build the search function, or any other way that I can build search function without class Song?

A: Your musicList waiting type Song named class but once the method returns DataSnapshot class. You should firstly convert from DataSnapshot to Song class, if you don't idea how can you convert I'm explaining.
You can try the below line code;
final musicList = <Song>[];
FirebaseDatabase.instance.reference().child("${getCurrentUID()}").once().then((DataSnapshot snapshot){
print("Sucessfully loaded the data");
for(final snapshot in snapshot.value){
    final songModel = Song.fromJson(snapshot as Map);
    musicList.add(songModel);
}
setState(() {});
});


text:
Q: Sagemath available in jupyter in vscode? I am playing around with the jupyter extension inside of vscode.  And although I can use sagemath in jupyter lab on my machine it is not presented as an option of cell type within vscode.  Suggestions?
Thanks,
R Haynes


text:
Q: How to write a plugin loader for a module written in typescript I'm working on a module that as part of its startup will load in dynamically other modules based on a configuration file, which provided the name of packages or files to import. I had something written up in vanilla JS that worked well, but I'm struggling to translating it to Typescript.
In Javascript, I was doing:
./src/main.js (assume config.plugins = ['./plugin']):
class ModuleName {
  constructor(config) {
    for (let plugin of config.plugins) {
      let register = require(plugin);
      register(this);
    }
  }
}

./src/plugin.js:
class Plugin() {
}

module.exports = (main_module) => {
  main_module.plugin = new Plugin();
}

Attempting to translate this to Typescript got me to (with the main perceived difference being that the plugins are loaded now asynchronously, which is a problem, but that at least compiles, so not my focus here):
./src/main.ts:
interface Config {
  plugins: string[];
}

interface Plugin {
  register(main_module: ModuleName): void;
}

export class ModuleName {
  public config: Config;
  public constructor(config: Config) {
    this.config = config;
  }

  public async init(): Promise<string[]> {
    return this.loadPlugins(this.config.plugins);
  }

  // You don't need to return anything from here because `async` functions
  // always return a `Promise`.
  private async loadPlugins(plugins: string[]): Promise<string[]> {
    for (let plugin of plugins) {
      // Here using `async`/`await` is a lot less complicated than using
      // `then()` because of the `for...of` loop
      let loaded: Plugin = await import(plugin);
      loaded.register(this);
    }
    return plugins;
  }
}

./src/plugin.ts:
import { ModuleName } from './index';

declare module './index' {
  export interface ModuleName {
    plugin: Plugin;
  }
}

export class Plugin {
  public foo(): void {
    console.log('Plugin::foo');
  }
}

export function register(main_module: ModuleName): void {
  main_module.plugin = new Plugin();
}

now, in the main.ts it allows me to reference this.plugin freely. However, when I attempt to import this into a project, I don't can't reference the plugin.
For example, compiling the above to the ./dist folder, and having the following (at the root of my project):
./test.ts
import { ModuleName } from './dist';

let a = new ModuleName({plugins: ['./plugin']});
a.init().then(a.plugin.foo()).catch(console.error);

errors with tsc saying Property 'plugin' does not exist on type 'ModuleName'.

A: It looks like you're loading it asynchronously and probably attempting to access it too quickly. It's definitely not a good idea to use setTimeout to ensure asynchronous processes are completed when you need them (what if the process takes 50 ms on a fast computer, but 500 on a slow one?); instead, you want to access the Promise directly so you can use Promise.then(). The problem is you never want to return anything but the object itself from a constructor, so you never want to have asynchronous constructors. A better pattern would be to have a separate initialization function that performs the asynchronous process.
Furthermore, import(plugin) returns a Promise, not the plugin itself. Therefore, you must also handle this accordingly and wait to resolve the Promise returned by loadPlugins until after all of the imports resolve. That's probably not a very easy statement to read, so here's some code which can explain it far better than I can:
export class ModuleName {
  private config: Config;

  public constructor(config: Config) {
    this.config = config;
  }

  public async init(): Promise<void> {
    return this.loadPlugins(this.config.plugins);
  }

  // You don't need to return anything from here because `async` functions
  // always return a `Promise`.
  private async loadPlugins(plugins: string[]): Promise<void> {
    for (let plugin of plugins) {
      // Here using `async`/`await` is a lot less complicated than using
      // `then()` because of the `for...of` loop
      let loaded: Plugin = await import(plugin);
      loaded.register(this);
    }
  }
}

Now, when initializing, you need to properly handle the asynchronous initialization:
let a = new ModuleName(config);
a.init().then(() => {
  a.plugin.foo();
}).catch(err => console.error(err));

or even just this will work:
let a = new ModuleName(config);
a.init().then(a.plugin.foo).catch(console.error)


text:
Q: Creating a loop on a [1..10] array in Jade Wasn't there a way to write down an array as 1..10 ?
I'm trying to write an each loop, but it seems not to be working, I have to write each value manually. I was pretty sure we could do this :
- each val in [1..10] // or 1..100 or whatever
    li(class="list#{val}")

Any idea? Thanks a lot

A: Numerical loops can be written like this in Jade:
- for (var val = 0; val < 10; val++)
    li(class="list#{val}")


text:
Q: Redis for API calls Redis is single threaded yet it is fast. Can we use Redis database for API calls as APIs call is concurrent in nature? Is Redis capable of handling multiple API call requests?

A: Yes, you can use Redis at the database for a system that needs to support multiple concurrent API calls.
When you implement your API calls using whatever framework and language you are interested in using, if your API implementation needs to make a request to Redis, that call will wait on the accept queue for the socket until your request gets processed.
Many large websites use Redis as a database to implement APIs in the manner you suggest.

A: Yes, you can use.
Redis is very very fast. You might want to take a look at their benchmark. Moreover, we can scale Redis horizontally via clustering and partitioning.

Partitioning allows scaling the computational power to multiple cores and multiple computers, and the network bandwidth to multiple computers and network adapters.

https://redis.io/topics/partitioning
https://redis.io/topics/cluster-tutorial


text:
Q: Rails: no such file to load -- action_dispatch I cannot start my server, it really doesn't make sense.  Traced the paths, found the gems, install, uninstalled, re-installed, and nothing seems to work. Installed on OS X via RVM.  So here's the stats:
    $ which ruby
    /Users/Ross/.rvm/rubies/ruby-1.9.2-p180/bin/ruby
$ which rails
/Users/Ross/.rvm/gems/ruby-1.9.2-p180/bin/rails

$ which gem
/Users/Ross/.rvm/rubies/ruby-1.9.2-p180/bin/gem

$ gem list

*** LOCAL GEMS ***

actionmailer (3.1.3)
actionpack (3.1.3)
activemodel (3.1.3)
activerecord (3.1.3)
activeresource (3.1.3)
activesupport (3.1.3)
arel (2.2.1)
builder (3.0.0)
bundler (1.0.21)
erubis (2.7.0)
hike (1.2.1)
i18n (0.6.0)
json (1.6.4)
mail (2.3.0)
mime-types (1.17.2)
multi_json (1.0.4)
polyglot (0.3.3)
rack (1.3.6)
rack-cache (1.1)
rack-mount (0.8.3)
rack-ssl (1.3.2)
rack-test (0.6.1)
rails (3.1.3)
railties (3.1.3)
rake (0.9.2.2 ruby, 0.8.7)
rdoc (3.12)
rubygems-update (1.8.15)
sprockets (2.0.3)
thor (0.14.6)
tilt (1.3.3)
treetop (1.4.10)
tzinfo (0.3.31)

$ gem env
RubyGems Environment:
  - RUBYGEMS VERSION: 1.8.15
  - RUBY VERSION: 1.9.2 (2011-02-18 patchlevel 180) [x86_64-darwin11.2.0]
  - INSTALLATION DIRECTORY: /Users/Ross/.rvm/gems/ruby-1.9.2-p180
  - RUBY EXECUTABLE: /Users/Ross/.rvm/rubies/ruby-1.9.2-p180/bin/ruby
  - EXECUTABLE DIRECTORY: /Users/Ross/.rvm/gems/ruby-1.9.2-p180/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-darwin-11
  - GEM PATHS:
     - /Users/Ross/.rvm/gems/ruby-1.9.2-p180
     - /Users/Ross/.rvm/gems/ruby-1.9.2-p180@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - http://rubygems.org/

Update 12/16/12-=>
Gemfile:
source 'http://rubygems.org'
require 'rubygems'

gem 'rails'
gem 'actionpack'
gem 'jquery-rails'
gem 'haml'
gem "devise", :git => "https://github.com/plataformatec/devise.git"
# gem 'oa-core'
gem 'omniauth'
gem 'omniauth-openid'
gem 'omniauth-twitter'
gem 'omniauth-facebook'
gem 'omniauth-github'
gem "settingslogic"
gem 'composite_primary_keys'
gem 'addressable'
gem 'faraday'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

gem 'pg'
gem 'squeel'
gem 'sqlite3'
gem 'mysql2', '~> 0.2.6'
gem "bcrypt-ruby", :require => "bcrypt"

group :development, :test do
  gem 'rspec-rails'
  gem 'ruby-debug19', :require => 'ruby-debug'
  gem 'hpricot', :require => false #html2haml
  gem 'ruby_parser', :require => false # html2haml
  gem 'pickle'
  gem 'awesome_print', :require => 'ap'
  gem 'factory_girl_rails'
end

group :development do
  gem 'heroku', :require => false
  gem 'sass'
end

group :test do
  gem 'shoulda'
  gem 'cucumber-rails'
  gem 'spork', '~> 0.9.0.rc3'
  gem 'guard-spork'
  gem 'database_cleaner'
end

A: was a security conflict; I had to chown all the file in the gems directory.  The owner was root and unless I wanted to sudo the server, I just need my user to have rights to all the files


text:
Q: does celery docker container have to copy the same files from django container build? Here is tha raw question:
i was wondering if i can run the command from celery container using another container data like django container as these containers are in the same network of containers on the server or i have to duplicate the data from django project to every container or is there another way?
here is the question with explanation:
i am new to this and i tried to make a docker composer file for a Django-rest project with celery and Rabitmq and PostgreSQL,
i followed bunch of tutorials and i manage to make it work as the celery container use a shared volume from Django to start the worker(also the beat celery container) see the picture for related code from docker compose:(edited part from one of suggestions i put the code instead of pic)
version: '3.8'
services:
  api:
    build:
      context: ./youdeal_djangopart
      dockerfile: Dockerfile.prod
    container_name: 'prod-djbackend'
    image: youdeal_djangopart-prod:0.63
    restart: unless-stopped
    expose:
      - '8000'
    env_file: .env
    volumes:
      - static-data:/static
      - media-data:/youdeal_djangopart/media
      - api_vol:/youdeal_djangopart
    environment:
      - "CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672//"
    depends_on:
      - db
      - rabbitmq
  celeryworker:
    container_name: celeryworker
    image: celeryworker:0.51
    build:
      context: ./youdeal_djangopart
      dockerfile: Dockerfile.celery.prod
    env_file: .env
    volumes:
      - ./:/api_vol/
    links:
      - db
      - rabbitmq
      - api
    depends_on:
      - rabbitmq
    environment:
      - "CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672//"
volumes:
  api_vol:

now here is the problem when i want to deploy the project the server i am using (https://www.arvancloud.com/en) doesn't really allow shared volume  between containers and dont answer well in this regard, i was wondering if i can run the command from celery container using another container data like django container as these containers are in the same network of containers or i have to duplicate the data from django project to every container or is there another way?
i find this  and some other related topics but i couldn't make it work


text:
Q: Integrating trigonometric function How do you integrate:
$$\int_{0}^{1}\frac{\sin(x)}{\sin(1-x)+\sin(x)}dx$$
The answer that you must get is $\frac{1}{2}.$

A: Let $I=\int_0^1\frac{\sin x}{\sin x+\sin (1-x)}\,dx~~~~~~~~~~~~~~~~(1)$
Take $x=1-z$. Then $I=\int_0^1\frac{\sin (1-z)}{\sin (1-z)+\sin (z)}\,dz$. Or we can write it as
$$I=\int_0^1\frac{\sin (1-x)}{\sin x+\sin (1-x)}\,dx~~~~~~~~~(2)$$
Add $(1)$ and $(2)$, we have
$$2I=\int_0^1 1\,dx \implies I=\frac{1}{2}.$$


text:
Q: How to pass a struct as a pointer? [C++] I have a struct that I'm passing through CreateThread
packetargs *args;
args->s=s;
args->buf=buf;
args->len=len;
args->flags=flags;
args->to=to;
args->tolen=tolen;
CreateThread(NULL,0,mThread,args,0,NULL);

But when I receive it in my Thread function, it crashes the application(Because the information is wrong):
DWORD WINAPI mThread(LPVOID args)
{
    packetargs *pargs = (packetargs *)args;

How am I supposed to pass the struct as a pointer and then create it again in the thread function?

A: You forgot to allocate any memory for your struct:
packetargs *args = new packetargs;

(Of course, you'll need to delete it at some point.)


text:
Q: Description of the Kameda-Weiner algorithm? I'm looking for an explanation of the Kameda-Weiner algorithm.
I found the paper "On the State Minimization of Nondeterministic Finite Automata" which, I assume, contains this, though it's unfortunately behind a paywall, and I'm just a hobbyist.
Can someone explain the algorithm, or point me to another source?

A: Although I have absolutely no idea what you are talking about, I think these two pdf files contain some sort of explanation.
Link1
Link2
I just tried to answer it, because I know how frustrating it can be, when you something you really want is behind a paywall! Hope it helps.
Cheers!

A: It's implemented here: https://github.com/coder0xff/parlex_legacy/blob/132e4a23a599140d22b18ead832626f0c607340f/Automata/NFA.cs#L641
(updated to fix dead link)


text:
Q: How to display PGM image using OpenCV I'm trying to load and display a .PGM image using OpenCV(2.4.0) for C++.
void open(char* location, int flag, int windowFlag)
{
    Mat image = imread(location, flag);
    namedWindow("Image window", windowFlag);
    imshow("Image window", image);
    waitKey(0);
}

I'm calling open like this:
open("./img_00245_c1.pgm", IMREAD_UNCHANGED, CV_WINDOW_AUTOSIZE);

The problem is that the image shown when the window is opened is darker than if I'm opening the file with IrfanView.
Also if I'm trying to write this image to another file like this:
Mat imgWrite;
imgWrite = image;
imwrite("newImage.pgm", imgWrite)

I will get a different file content than the original one and IrfanView will display this as my function displays with imshow.
Is there a different flag in imread for .PGM files such that I can get the original file to be displayed and saved ?
EDIT: Image pgm file
EDIT 2 : Remarked that: IrfanView normalizes the image to a maximum pixel value of 255 .
In order to see the image clearly using OpenCV I should normalize the image also when loading in Mat. Is this possible directly with OpenCV functions without iterating through pixels and modifying their values ?

A: The problem is not in the way data are loaded, but in the way they are displayed.
Your image is a CV_16UC1, and both imshow and imwrite normalize the values from original range [0, 65535] to the range [0, 255] to fit the range of the type CV_8U.
Since your PGM image has max_value of 4096:
P2
1176 640  // width height
4096      // max_value

it should be normalized from range [0, 4096] instead of [0, 65535].
You can do this with:
Mat img = imread("path_to_image", IMREAD_UNCHANGED);
img.convertTo(img, CV_8U, 255.0 / 4096.0);

imshow("Image", img);
waitKey();

Please note that the values range in your image doesn't correspond to [0, 4096], but:
double minv, maxv;
minMaxLoc(img, &minv, &maxv);

// minv = 198
// maxv = 2414

So the straightforward normalization in [0,255] like:
normalize(img, img, 0, 255, NORM_MINMAX);
img.convertTo(img, CV_8U);

won't work, as it will produce an image brighter than it should be.

This means that to properly show your image you need to know the max_value (here 4096). If it changes every time, you can retrieve it parsing the .pgm file.
Again, it's just a problem with visualization. Data are correct.


text:
Q: How do I use std::copy_if by both coping elements and removing those elements from the original container Say I have a std::vector<int> with a simple operation to copy those elements which are even:
#include <vector>

int main()
{
    std::vector<int> v = {1, 2, 3, 4, 5, 6};
    std::vector<int> even;
    std::copy_if(std::make_move_iterator(v.begin()), std::make_move_iterator(v.end()), std::back_inserter(even), [](int i){return i%2 == 0;});

    return 0;
}

My question how can I combine the above with any other method to remove the elements from vector v which was copied to vector even

A: I wouldn't recommend trying to use std::copy_if here. Instead use std::stable_partition to move even elements to the end of v, copy this part to even using the vector constructor and then erase the copied elements from v:
int main()
{
    std::vector<int> v = { 1, 2, 3, 4, 5, 6 };

    // actual logic
    auto pivot = std::stable_partition(v.begin(), v.end(), [](int x) { return (x % 2) != 0;  });
    std::vector<int> even(pivot, v.end());
    v.erase(pivot, v.end());

    // display results
    std::cout << "v:\n";
    for (auto x : v)
    {
        std::cout << x << '\n';
    }

    std::cout << "even:\n";
    for (auto x : even)
    {
        std::cout << x << '\n';
    }

    return 0;
}

For objects that are expensive to copy, you may want to use std::move_iterator when creating even as suggested in @MooningDucks answer:
std::vector<int> even(std::move_iterator(pivot), std::move_iterator(v.end()));

A: I would switch to using std::remove_if instead and have the function you pass to remove_if do the adding to the other vector.  That gives you
std::vector<int> v = {1, 2, 3, 4, 5, 6};
std::vector<int> even;
v.erase(std::remove_if(v.begin(), v.end(),
                       [&](auto val){ bool cond = (val % 2 == 0);
                       if (cond) even.push_back(val); return cond; }), v.end());


text:
Q: "Assigned To" field not available when creating a "Update a Record" Quick Action on task i have created a new Action  Edit with Action Type as "Update a Record" on Task Object.
I want to add "Assigned To" field which is a lookup to User,Calendar in my layout of Edit.
But i don't see this field available in the palette , so that i can drag and drop to the Layout.
Please suggest

A: "Assigned To" is actually the OwnerId field. Unless a User either owns the Task record or is in the hierarchy above the existing Owner of the record, depending on your sharing model and a user's profile permissions, they're not going to be able to change ownership of a Task.


text:
Q: Page refreshes after setTimeout function and removes body attribute The code below sets a timeout of 2s to call document.write function.
As soon as the document.write() is called, it automatically refreshes (as I thought) the page. Not only that, it removes bgcolor and color property of the body too!
// JS
let name = prompt('Enter username: ', 'Captain Anonymous');

function sayHello() {
    document.write('Hello ' + name + '!');
}
setTimeout(sayHello, 2000);

// HTML

<title>Page Title</title>

I want that this code just simply writes the message in the document. How can I achieve this?

A: document.write only inserts text into your document while it's loading. Once the page is loaded, it will overwrite your page. When your setTimeout is called, the page is already loaded.
What you probably want to do is put a place in your page for your message.
Try this. Add a div tag inside the body of your page.

Then change your sayHello function to this
function sayHello() {
    document.getElementById("mytext").innerText = 'Hello ' + name + '!';
}


text:
Q: Ubuntu 13.10 Upgrade Failed I had Ubuntu 13.04 dual booted with Windows 7. I tried to upgrade to 13.10 using the software manager. However after the downloading stage i.e. Fetching new Packages my system shutdown somehow and the process was  not complete. After having restarted it I am not able to access my hard drive through Ubuntu and neither am I able to open any applications. When I check the About this Computer it says that I have Ubuntu 13.10. I try opening the applications using Alt-F2 but every application I open crashes after some time.
So is there any way to complete the upgrade process?
I'm new to ubuntu so have very little idea.

A: I used the method suggested by @braiam above. As I have already mentioned, after I restarted my system I was not able to access any applications. So I used the Alt+F2 command and then entered update-manager in the text box and checked the Run in Terminal option. The manager didn't run but I was able to open a new terminal window this way. Then I did what was suggested above and everything was fine.


text:
Q: How do I return a list of strings from a list of lists? The homework question is the following...
(10 pts) Write a function explode that, given a list of tuples, (n x), creates a new list by inserting
x into the list n times in place of (n x) (in other words, the inserted items should come in the same
order as the original tuples when you create the new list). You can assume that n will always be at
least 0.

(explode '((2 "Hello"))) produces ->("Hello" "Hello")
(explode '((2 "Hello") (3 "world"))) produces ->("Hello" "Hello"
  "world" "world" "world")

A possible solution I have thought of so far was to have a loop that would keep track of what tuple the algorithm is currently working on and then inside of that loop have a function definition that would be called recursively to add the string to the return list. But I am not sure this will work because it seems like it would require the use of 'set!' which the professor said we are not allowed to use.
I am not looking for a complete answer as this is a homework problem. I would just like to be pointed in the right direction on how to approach this problem, maybe with some sudo code.
Thanks all!

A: *

*what does explode of an empty list produce?

*what does explode of '((2 "Hello") (3 "world"))) produce?

*what does explode of '((3 "world")) produce?

*How can you go from #3 to #2?

How can you "combine" the result of #3 (recursive call on cdr) with '(2 "Hello") (car of the list) to produce the result of #2?
You can assume that you have the result of the recursive call when constructing the "combine" function (the combine function may be recursive too).

A: Divide this into two problems:
First, write a function expand that works like this:
(expand 3 "world") => ("world" "world" "world"))

Second, implement explode so that it calls expand on each of its arguments, and appends the results together into a single list.
(explode '(x y z ...)) =>
    (append (expand (first x) (second x))
            (expand (first y) (second y))
            (expand (first z) (second z))
            ...)

Both functions can be recursive. The base case for expand is when the first element of the list is 0. The base case for explode is when the list is empty. You need to figure out how to combine the current result with the recusive call to produce the correct result for each problem.

A: Try not to think about loops when using functional languages.
In general, most of the problems imperatively solved with loops, can be solved with map and reduce (foldr/foldr in Racket) functions. In special cases, when these functions are not enough, you can think about recursion.
Your particular task can be solved just utilizing map function:
#lang racket
(define(explode tuples)
  (flatten
   (map
    (lambda (tuple)
      (let*
          ([repeat-n-times (range  (first tuple))]
           [value (second tuple)])
        (map (λ _ value) repeat-n-times)))
    tuples)))


text:
Q: How can I access the url in cypress and change the value of one of the parameters, or just change the value of the url? I have a certain url, and by entering values with parameters I get from in inputs, how can I change the value using cypress in url
http://localhost:28080/app/form/54fd3434f? -initial url

http://localhost:28080/app/form/54fd3434f?text_field=Text&text_field2=Text2  -expected url
after type

A: You can do something like this -
cy.url().then(url => {
    cy.visit(url + 'text_field=Text&text_field2=Text2')
});

cy.url() will yield the current URL as a string. Now add the parameters that you want to add and using cy.visit() you can access the new url.


text:
Q: Hdmi video output blank on Tablet My Android app plays videos within the app using a videoView. When connecting the tablet to a TV using HDMI, I am able to see my tablets screen on the TV.
Everything seems to be working fine, however in my app, my videoView is ONLY displayed on the TV. The tablet is just blank. Is there a way to force the videoView to play the video on both the TV and the tablet? I want both screens to be identical.

A: HDMI out is not part of the Android SDK, and in many cases is not even really a part of the standard Android OS. Device manufacturers can do what they want in terms of what is shown on the tablet and what is shown on the TV. There is nothing on VideoView or MediaPlayer to control this behavior.
If you are targeting some specific piece of hardware, you can try contacting the manufacturer to see if they have some beyond-the-SDK way of controlling this.


text:
Q: Is it possible to get current experiment name in kubeflow pipeline? When in pipeline code I can use macros like
{{workflow.annotations.pipelines.kubeflow.org/run_name}} or  {{workflow.name}} to get those values, and potentially use them in some context, eg. passing to some component.
What I'd like to do is get current experiment name, that the run is assigned to. I'd like to pass it on to components for logging purposes.
Is this property exposed?


text:
Q: Element-wise matrix vector multiplication I have a tensor m which stores n 3 x 3 matrices with dim n x 3 x 3 and a tensor v with n 3x1 vectors and dim n x 3. How can I apply element-wise matrix-vector multiplication, i.e. multiply the i-th matrix with the i-th vector, to get an output tensor with dim n x 3?
Thanks for your help.

A: You want to perform a matrix multiplication operation (__matmul__) in a batch-wise manner. Intuitively you can use the batch-matmul operator torch.bmm. Keep in mind you first need to unsqueeze one dimension on v such that it becomes a 3D tensor. In this case indexing the last dimension with None as v[..., None] will provide a shape of (n, 3, 1).
With torch.bmm:
>>> torch.bmm(m, v[..., None])

As it turns out, torch.matmul handles this case out-of-the-box:
>>> torch.matmul(m, v[..., None]) # same as m@v[..., None]

If you want explicit control over the operation, you can go with torch.einsum:
>>> torch.einsum('bij,bj->bi', m, v)


text:
Q: How to set busy cursor for slow WPF controls There appears to be a lot of resources on showing the busy cursor.
But all the solutions I've managed to find relies on setting the cursor via the view model. (i.e, IsBusy property, disposable WaitCursor).
These methods work well when I know when my data binding/view models will be long-running.
But I don't know how to do this automatically for cases where the bottleneck is the actual WPF user control itself?
For example:
Loading a control is initially lag-free. But once a 3rd party control is used, the control exhibits a 500-ms lag every time it loads.
The binding itself is fast, hence, adding a waitcursor/IsBusy in the view model is useless because it wouldn't know when the control (or any of its logical/visual children) has finished rendering. Nor should it know, as the view model should not be affected by the view's implementation.
Is it possible for the application to automatically set the cursor to busy when one or more WPF controls is busy/slow?

A: You may need something like this,
            var busytimer = new DispatcherTimer(
            TimeSpan.FromSeconds(1),
            DispatcherPriority.Normal,
            delegate
            {
                Process application = null;
                foreach (var process in Process.GetProcesses())
                {
                    if (process.ProcessName == "Your process name")
                    {
                        application = process;
                        break;
                    }
                }

                if (!application.Responding)
                {
                    this.Cursor = Cursors.Wait;
                }
                else
                {
                    this.Cursor = Cursors.Arrow;
                }
            },
            Application.Current.Dispatcher);

A:
Is it possible for the application to automatically set the cursor to busy when one or more WPF controls is busy/slow?

Not really.  If your UI thread is blocking, you won't be able to update the cursor until it becomes unblocked anyway, which defeats the purpose.

The binding itself is fast, hence, adding a waitcursor/IsBusy in the view model is useless because it wouldn't know when the control (or any of its logical/visual children) has finished rendering. Nor should it know, as the view model should not be affected by the view's implementation.

If you go with the IDisposable wait cursor solution, you could try scheduling the Dispose() call to occur after the next layout pass:
Dispatcher.CurrentDispatcher.BeginInvoke(
    DispatcherPriority.Loaded,
    new Action(() => waitCursor.Dispose()));


text:
Q: Batch file - Write list of files to variable I'd like to get a list of all files (including their absolute path) into a variable, separated by spaces.  My Google-fu seems to be weak in this regard, because I keep running into issues.
I have a base directory stored in %baseDir%, and would like to parse it for files (not recursing or including sub-directories).  Like I mentioned, this needs to go into a list.  I'd imagine there's a nice little shortcut I could use, but a for loop and concatenation would do the trick as well.
Ideally, I'd have something like this:
echo fileList

C:\file1.c C:\file2.c C:\file3.c

A: Pretty simple:
setlocal enabledelayedexpansion enableextensions
set LIST=
for %%x in (%baseDir%\*) do set LIST=!LIST! %%x
set LIST=%LIST:~1%

In fact, you find this very example also in the help for the set command, accessible via help set, complete with an explanation why the naïve approach won't work.
To use a different set of files (rather than all), you can easily change the wildcard:
for %%x in (%baseDir%\*.c) do set LIST=!LIST! %%x


text:
Q: Springer Nature American Physical Society (APS) Reference Style Kindly suggest which .bst file should match for the style Springer Nature American Physical Society (APS) Reference Style... Please advise
For more details https://typeset.io/formats/springer-nature/springer-nature-american-physical-society-aps-reference-style/d5b6e8aee1ee4160a6f368aedf1ea79c

A: *

*If you are supposed to use the American Physical Society (APS) bib style along with the "Springer Journal" document class, give
\documentclass[sn-aps]{sn-jnl}

a try.

*If you wish to use the APS bib style without employing the "Springer Journal" document class, give
\documentclass[<some-options>]{<some-class>}
% ... (other preamble stuff)
\bibliographystyle{sn-aps}

a try. If you pursue this route, you'll probably also have to provide a dummy definition for the macro \bibcommenthead that's used by the Springer Journal bib styles. E.g., something such as \def\bibcommenthead{}.
Springer actually provides an email address for answering authors' LaTeX- and BibTeX-related questions. It is LaTeXSupport@spi-global.com.


text:
Q: Is a coupling defined on the Cartesian product of two sample spaces or a single sample space? A book I'm reading presents two definitions of a coupling which seem to me to be contradictory. First it says

A coupling of two probability distributions $μ$ and $ν$ is a pair of random variables $(X, Y)$ defined on a single probability space such that the marginal distribution of $X$ is μ and the marginal distribution of $Y$ is ν.

Later it says

In summary, a coupling can be specified either by a pair of random variables $(X, Y)$ defined on a common probability space or by a distribution $q$ on $\chi \times \chi$.

What I'm confused about is the fact that the author says it can be defined as a "distribution $q$ on $\chi \times \chi$" where $\chi$ is the sample space.
My understanding is that for you to be able to form a coupling of $Y$ and $X$, both $Y$ and $X$ must be defined on the same sample space $\chi$. I understand that the set of values the vector $(X, Y)$ can take on is the Cartesian product of the image of $X$ with the image of $Y$. But it doesn't make sense to me to define a distribution $q$ on $\chi \times \chi$. Rather, it seems that you would define the coupling $q$ on $\chi$, the same probability space that $X$ and $Y$ are defined on. It is just that $q$ might have a larger image than the marginal distributions of the two random variables. (The picture I have in my head is of a joint probability table.)
In conclusion, I'm confused about the fact that the coupling is defined on the "same probability space," but we also for some reason bring up the Cartesian product of the sample space.
Edit: Here are my understandings of some key definitions:
A sample space is a pair $(\chi, \mathcal{B}(\chi))$ where $\chi$ is a set of outcomes of some experiment and $\mathcal{B}(\chi)$ is a $\sigma$-algebra of $\chi$.
A probability space is a triple $(\Omega ,{\mathcal {F}},P)$ where $\Omega$ is a set of outcomes, $\mathcal{F}$, the set of events, is a $\sigma$-algebra of $\Omega$, and $P: \mathcal{F} \rightarrow [0, 1]$ is the probability measure. Thus, $(\Omega, \mathcal{F})$ is itself a sample space.
A probability distribution is a function assigning probabilities to measurable subsets of some set. Thus, $P$ in the definition of a probability space above is an example of a probability distribution.
A random variable is a function on a probability space. I.e., a function $X: \Omega \rightarrow \chi$. In this case $\chi$ is usually $\mathbb{R}$ but doesn't necessarily have to be.
Note: I only know the very, very basics of measure theory.

A: These definitions are not contradictory at all. Consider the definition:

A coupling of two probability distributions $\mu$ and $\nu$ is a pair of random variables $(X,Y)$ defined on a single probability space such that the marginal distribution of $X$ is $\mu$ and the marginal distribution of $Y$ is $\nu$.

First, let's suppose that $\mu$ and $\nu$ are both measures on some sample space $(\mathcal{X},\mathcal{B}(\mathcal{X}))$. Then this passage gives one definition of a coupling. That is, it is a probability space $(\Omega,\mathcal{F},\mathbb{P})$ and a random vector $Z := (X,Y): \Omega \rightarrow \mathcal{X}\times\mathcal{X}$ such that,
$$\mathbb{P}(X(\omega) \in \cdot) = \mu(\cdot)\text{ and } \mathbb{P}(Y(\omega) \in \cdot) = \nu(\cdot).$$
Thus, we have a single probability space, and a random vector defined on a product sample space. Now let's look at the second passage:

In summary, a coupling can be specified either by a pair of random variables $(X,Y)$ defined on a common probability space or by a distribution $q$ on $\mathcal{X}\times\mathcal{X}$.

So this gives us an equivalent definition of a coupling. Basically, the important part here isn't the random variables $X$ and $Y$, but rather the dependence between them that is generated by the specific coupling. Therefore, we don't actually need to create a new probability space. We can instead let $q$ be the distribution of $Z$. That is, define
$$q(\cdot) = \mathbb{P}(Z \in \cdot).$$
Then $q$ is a measure on the sample space $(\mathcal{X}\times\mathcal{X},\mathcal(B)(\mathcal{X}\times\mathcal{X}))$. Of course, this is extremely abstract, so let's do some examples.
Example 1: A metric on probability measures
Couplings are great if we want to compare probability measures that are defined on different probability spaces. We can actually treat the space of probability measures as a metric space (technically, we restrict to probability measures of random variables with a second moment). The main idea is very simple. To measure the distance between $\mu$ and $\nu$, we ask "what would happen if we compared two random variables generated by $\mu$ and $\nu$?" But to do this, we need a coupling (otherwise we can't compare random variables on different probability spaces). The metric is,
$$d(\mu,\nu) = \inf_{q\text{ couples }\mu,\nu} \left(\mathbb{E}^q[(X-Y)^2]\right)^{1/2} = \inf_{q\text{ couples }\mu,\nu}\left(\int_{\mathcal{X}\times\mathcal{X}} (x - y)^2\,q(dx,dy)\right)^{1/2}.$$
Under this metric, $\mu_n$ converges to $\mu$ if and only if $\mu_n$ converges weakly to $\mu$ and the second moments of $\mu_n$ converge to the second moment of $\mu$.
For example, let $\mu \sim \mathcal{N}(0,\sigma)$ and $\nu\sim \mathcal{N}(0,\sigma')$. Then we can show that under the minimal coupling $q$, $X = \sqrt{\frac{\sigma}{\sigma'}}Y$. Then,
$$d(\mu,\nu) = \sqrt{\mathbb{E}^q[(X - Y)^2]} = \left|\sqrt{\frac{\sigma}{\sigma'}}-1\right|\sqrt{\mathbb{E}^q[Y^2]} = \left|\sqrt{\sigma} - \sqrt{\sigma'}\right|.$$
Compare this to the independent coupling $\mu\times \nu$ where $X$ and $Y$ are independent:
$$\sqrt{\mathbb{E}^{\mu\times\nu}[(X - Y)^2]} = \sqrt{\mathbb{E}^\mu[X^2] + \mathbb{E}^\nu[Y^2] - 2\mathbb{E}^\mu[X]\mathbb{E}^\nu[Y]} = \sqrt{\sigma + \sigma'}> \left|\sqrt{\sigma} - \sqrt{\sigma'}\right|.$$
So, if $\mu_n \sim \mathcal{N}(0,\sigma_n)$, where $\sigma_n \rightarrow \sigma$, then
$$\lim_{n\rightarrow \infty} d(\mu_n,\mu) = \lim_{n\rightarrow \infty}\left|\sqrt{\sigma_n} - \sqrt{\sigma}\right| = 0,$$
so $\mu_n$ converges to $\mu$.
Example 2: A Toy Example of Couplings on Different Sample Spaces
Let $\mu$ be the distribution of a fair coin toss, and $\nu \sim \mathcal{N}(0,1)$. Then $\mu$ is defined on the sample space $\{\text{heads,tails}\}$ while $\nu$ is defined on the sample space $\mathbb{R}$. We could embed the sample space of $\mu$ into the sample space of $\nu$, but that's actually completely unnecessary. Let's look at three different couplings $(X_i,Y_i)$:

*

*Under $q_1$, $X_1$ and $Y_1$ are independent.

*Under $q_2$, $X_2 = \text{heads}$ iff $Y_2 \geq 0$.

*Move to a larger probability space including $X_1,X_2,Y_1,Y_2$ and another coin toss that we will call $Z$. Suppose $(X_3,Y_3) = (X_1,Y_1)$ if $Z$ is heads, and $(X_3,Y_3) = (X_2,Y_2)$. That is, $q_3 = \frac{q_1 + q_2}{2}$.

As you can see, there are countless ways to create a coupling between two probability measures. In all cases, the interesting part is the dependence between $X$ and $Y$ that is characterized by the measure $q$. This is why we need to work on the product sample space. If we defined $X$ and $Y$ separately on $\mathcal{X}$, then we would lose the dependence structure imposed by the coupling.
I hope this makes sense. I tried to be as clear as possible, but I think it just came out as wordy. Let me know if you have any questions.


text:
Q: is it possible to `fsck` for badblocks a single LVM logical volume SEGMENT? why? to resume fsck -fcck while looking for badblocks as it takes humongous time (1TB SATA HD) and I have no no-break on my desktop, so, I could split the logical volume in several segments of 10GB and fsck each one per day :)
kvpm only gives a popup fsck command for the whole logical volume, not the specified segment.
can such check be forced even if in some more complex way?
may be temporarily referencing the segment by separating it from the logical volume it is currently part of, like it being part of another LV just for that check?
Of course that a direct way to force resume fsck from a specified block would suffice if possible at all.
PS.: I cant suspend the desktop machine, it never works. If if it could work, it would still prevent me from using the main/root volume for a huge long time :(

A: In the comments you wrote,

The disk I want to check currently has 51 bad/pending sectors from smart data at gnome-disks. Do you mean that specifically looking for bad blocks is not really necessary anymore after SMART feature, as they apparently seem to be safely auto-fixed on demand?

Pending sectors are sectors that can't be read. When you next try to write to them, the disk firmware will automatically remap the new data to spare sectors. You don't need badblocks for this.
However, 51 sectors are a lot of sectors that have failed. You may find the disk can't remap all of them. With this many sectors it would be well worth checking the health of the drive and seriously considering replacing it.


text:
Q: Best way to handle old *.asp links with Asp.Net 4.0 on IIS 7.5? We still have a lot of incoming urls pointing to our old .asp pages. The new .aspx pages are called the same as the old .asp pages, and accept mostly the same values, so they are pretty much interchangeable. Unfortunately we still get both POST and GET requests to the old .asp pages.
We handled these .asp requests in our Asp.Net 2.0 app by adding this in our web.config (system.webserver section):
    <handlers>
        <add name="ASPClassicForRedirectToASPX"
             path="*.asp"
             verb="*"
             modules="IsapiModule"
                scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll"
             resourceType="Unspecified"
             preCondition="classicMode,runtimeVersionv4.0,bitness32" />
    </handlers>

and then checking in BeginRequest if the url ends with .asp, and if it does, do a RewritePath to .aspx
Now we have migrated to asp.net 4.0 and I started to wonder if there is a better way to handle this, and still keep backwards compatibility with the old .asp urls?

A: what i would do if not allready the case is something like that in the BeginRequest instead of url rewrite (when possible) :
Response.Clear();
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","New-url");
Response.End();

using a 301 permanent redirect you will make sure that all crawlers and stuff will change their link to the right one that should reduse the calls u get to your .asp pages by a lot. other than that you are stuck with the old direct links to your asp pages at some point im guessing you will have to let them go. Cant support old stuff forever even tho that would be awesome :)


text:
Q: Why doesn't this sql script execute? Hi I have the following python:
c = conn.cursor()

#get the account id for the specific user

actidSQL = "select id from accounts where user_id = (select id from auth_user where username = '%s');" % user
c.execute(actidSQL)
actid = c.fetchone()[0]
print actid

#fill the latencies table - currently not firing, not sure why?
latencies_sql = "insert into latencies(account, replier, sender, replyemail, origemail, replydate, origdate) select m1.account, c1.id as replier, c2.id as sender, m1.id as replyemail, m2.id as origemail, m1.date as replydate, m2.date as origdate from contacts c1, contacts c2, emails m1, emails m2 where m1.id > m2.id and m1.reply = m2.mid and m1.reply is not null and c1.id = m1.fr and c2.id = m2.fr and m1.account = %s and m1.account = m2.account;" % (actid)
print latencies_sql
c.execute(latencies_sql)

The first sql executes but the second doesn't. Is there a reason why?

A: What do you mean with "The first sql executes but the second doesn't."? You get an error? Or is there no data in the DB? I assume that there is no data in the database and you are using MySQL. This is because you don't commit your changes. A conn.commit() at the end of your script should help.

A: It looks like an invalid query problem. You're trying to run either 2 queries, or 1.5 queries in the same c.execute
You either want an insert
insert into latencies(account, replier, sender, replyemail, origemail, replydate, origdate)

Or a select
select m1.account, c1.id as replier, c2.id as sender, m1.id as replyemail, m2.id as origemail, m1.date as replydate, m2.date as origdate from contacts c1, contacts c2, emails m1, emails m2 where m1.id > m2.id and m1.reply = m2.mid and m1.reply is not null and c1.id = m1.fr and c2.id = m2.fr and m1.account = %s and m1.account = m2.account;"


text:
Q: Should I use `random.seed` or `numpy.random.seed` to control random number generation in `scikit-learn`? I'm using scikit-learn and numpy and I want to set the global seed so that my work is reproducible.
Should I use numpy.random.seed or random.seed?
From the link in the comments, I understand that they are different, and that the numpy version is not thread-safe. I want to know specifically which one to use to create IPython notebooks for data analysis. Some of the algorithms from scikit-learn involve generating random numbers, and I want to be sure that the notebook shows the same results on every run.

A:
Should I use np.random.seed or random.seed?

That depends on whether in your code you are using numpy's random number generator or the one in random.
The random number generators in numpy.random and random have totally separate internal states, so numpy.random.seed() will not affect the random sequences produced by random.random(), and likewise random.seed() will not affect numpy.random.randn() etc. If you are using both random and numpy.random in your code then you will need to separately set the seeds for both.
Update
Your question seems to be specifically about scikit-learn's random number generators. As far as I can tell, scikit-learn uses numpy.random throughout, so you should use np.random.seed() rather than random.seed().
One important caveat is that np.random is not threadsafe - if you set a global seed, then launch several subprocesses and generate random numbers within them using np.random, each subprocess will inherit the RNG state from its parent, meaning that you will get identical random variates in each subprocess. The usual way around this problem is to pass a different seed (or numpy.random.Random instance) to each subprocess, such that each one has a separate local RNG state.
Since some parts of scikit-learn can run in parallel using joblib, you will see that some classes and functions have an option to pass either a seed or an np.random.RandomState instance (e.g. the random_state= parameter to sklearn.decomposition.MiniBatchSparsePCA). I tend to use a single global seed for a script, then generate new random seeds based on the global seed for any parallel functions.


text:
Q: Syntax Error while passing numeric column name in my update query of sql server in c# I am recently work on project in which I can add column dynamically with the DateTime now and this code works fine; but when I want to update this doesn't  work fine and throw syntax error and when ever I write character column name it works fine. Below is my code
cmd = new System.Data.SqlClient.SqlCommand(
 "update attendance set '25.04.2017' =  '" +
  abcd +
 "'   where std_id = " + Convert.ToInt32(b) + "  ", con);

cmd.ExecuteNonQuery();
con.Close();

where abcd is my column values which is true or false the issue with this '25.04.2017'

A: Probably, you should swap field name (abcd) and its value (25.04.2017):
// Keep query
//   1. Readable:     @
//   2. Paramterized: @prm_date, @prm_id
//   3. Formattable:  {abcd} (string interpolation)
string sql =
  $@"update attendance
        set {abcd} = @prm_date -- field = value
      where std_id = @prm_id";

//DONE: wrap IDisposable into using
using (var cmd = System.Data.SqlClient.SqlCommand(sql, con)) {
  // Parametrize query
  //TODO: AddWithValue is not the best choice, turn into Add + Actual db type
  cmd.Parameters.AddWithValue("@prm_date", new DateTime(2017, 4, 25));
  cmd.Parameters.AddWithValue("@prm_id", b);

  cmd.ExecuteNonQuery();
}

Edit: In (for me very improbable) case that '25.04.2017' is a field name and abcd is its value:
string sql =
  $@"update attendance
        set [25.04.2017] = @prm_abcd -- eerie field with '25.04.2017' name
      where std_id = @prm_id";

//DONE: wrap IDisposable into using
using (var cmd = System.Data.SqlClient.SqlCommand(sql, con)) {
  // Parametrize query
  //TODO: AddWithValue is not the best choice, turn into Add + Actual db type
  cmd.Parameters.AddWithValue("@prm_abcd", abcd);
  cmd.Parameters.AddWithValue("@prm_id", b);

  cmd.ExecuteNonQuery();
}

A: If you really have such a column named 25.04.2017 (I'd personally not recommend to do it) - you have to wrap such a name into square brackets:
"update attendance set [25.04.2017] =  '"

A: If 25.04.2017 is a column name then you want to surround it with []
update attendance set [25.04.2017] =  ....

Your code is vulnerable to sql injection when you append your parameter values as part of the sql string. Use Parameters instead for your values that you are passing.
Also your schema is not well designed any time you start using (what should be) values for columns. Instead I recommend a table with a column AttendedOn of type DateTime2 and capture the value in there. It is very rare that you should ever have to dynamically create columns based on values and if that is the path you are on you should reconsider your design.


text:
Q: TCP socket hangs when reading response from custom HTTP request - C I have the following code that I have written which is suppose to send a simple http request over a TCP socket, I get a response but as soon as I try to read in the loop it hangs, in the 2nd read operation (tried it manually)
if anyone has an idea of why this might fail I will appreciate it a lot
attached below is the entire code
I am running the program like this: ./http_client yahoo.com
I get this response text at first:
HTTP/1.1 301 Moved Permanently
Date: Sat, 06 Aug 2022 08:07:11 GMT
Connection: keep-alive
Server: ATS
Cache-Control: no-store, no-cache
Content-Type: text/html
Content-Language: en
X-Frame-Options: SAMEORIGIN
Location: https://www.yahoo.com/
Content-Length: 8

redirect

and then it hangs and closes the socket, it shouldn't hang at all, it should run and exit without a delay or anything

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

int main(int argc, char *argv[]) {

    int sockfd;
    struct sockaddr_in cli_name;
    struct sockaddr_in *saddr;
    char *hostname;
    struct addrinfo *res;
    int port = 80;

    if (argc != 2) {
        perror("Usage: establish tcp connection to: <hostname>\n");
        exit(1);
    }

    hostname = argv[1];
    printf("Client is alive and establishing socket connection %s.\n", hostname);

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("Error opening channel");
        close(sockfd);
        exit(1);
    }

    if (0 != getaddrinfo(hostname, NULL, NULL, &res)) {
        fprintf(stderr, "Error in resolving hostname %s\n", hostname);
        exit(1);
    }

    bzero(&cli_name, sizeof(cli_name));
    cli_name.sin_family = AF_INET;
    saddr = (struct sockaddr_in *) res->ai_addr;
    cli_name.sin_addr.s_addr = inet_addr(inet_ntoa(saddr->sin_addr));
    cli_name.sin_port = htons(port);

    fflush(stdout);
    if (connect(sockfd, (struct sockaddr *) &cli_name, sizeof(cli_name)) < 0) {
        perror("Error establishing communications");
        close(sockfd);
        exit(1);
    }

    char header[100];
    int cx;
    char buf[2056];
    size_t byte_count = 0;
    size_t sent_byte_count = 0;
    cx = snprintf(header, 100, "GET / HTTP/1.1\r\nHost: %s:%d\r\n\r\n", hostname, port);

    size_t total = strlen(header);
    size_t sent = 0;
    do {
        sent_byte_count = write(sockfd, header + sent, total - sent);
        if (sent_byte_count < 0)
            printf("ERROR writing message to socket");
        if (sent_byte_count == 0)
            break;
        sent += sent_byte_count;
    } while (sent < total);

    memset(buf,0,sizeof(buf));
    while ((byte_count = read(sockfd, buf, 2054)) > 0) {
        buf[byte_count] = '\0';
        printf("%s", buf); // <-- give printf() the actual data size
        fflush(stdout);
    }

    printf("Exiting now.\n");
    close(sockfd);
    exit(0);

}


text:
Q: Understanding the Jank happening AlertDialog with TextField and DropdownButton I have AlertDilaog with TextField and DropDownButton.
Problem:
As soon as, I launch the dialog and clicks on textfield, the alertdialog shifts up and label animation in textfield happens. But while happening this I see jank.
And I did profiling and I am still trying to understand the why it is happening.
Here is the screenshot
And here is the profiling file: https://filebin.net/7wulbm9j88m6jjt3
Can anyone help me in understanding what is this VsyncProcessCallback and whatever happening in selected section(brackets)?
I am just trying to find the root cause of the Jank and remove it.
Thank you in advance.
Code of TextField:
Widget _addProtocolTextField(BuildContext context) {
    return Container(
      height: 7.h,
      width: 70.w,
      child: TextField(
        controller: _protocolNameController,
        style: TextStyle(
          color: Theme.of(context).textColor,
          fontSize: 13.sp,
        ),
        textAlign: TextAlign.left,
        maxLines: 1,
        decoration: InputDecoration(
          labelText: Strings.protocol_name_lable,
          labelStyle: TextStyle(color: ColorConstants.primaryColor),
          enabledBorder: _getBorder(),
          disabledBorder: _getBorder(),
          focusedBorder: _getBorder(),
          border: _getBorder(),
        ),
      ),
    );
  }

  OutlineInputBorder _getBorder() {
    return OutlineInputBorder(
      borderSide: BorderSide(color: ColorConstants.primaryColor),
    );
  }

A: Since this much code is not enough to provide the real solution, you can refer to the following tips:

*

*Don't make Widget with Function, Prefer to make a separate stateless or stateful widget as per your requirement

*You can try this on release build to see if it helps: https://flutter.dev/docs/perf/rendering/shader


text:
Q: How to reference the imageid from a docker build using docker/build-push-action@v2? I want to reference the imageid from the docker build using docker/build-push-action@v2
action in my next github action step when deploying to kubernetes using a Helm chart.  For now I just want to echo it out in the next part of my github action step.
This is the github documentation link for build-push-action
The following is a snippet of my github action worfklow:
      - name: Build and push Docker images
        uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}

      - name: Print my docker imageid in a separate step
        run: echo "imageid"

The following is the output from the docker build-push-action:
#15 pushing layer 54b5e2b53cf2 4.9s done
#15 DONE 4.9s
ImageID
  sha256:043e18541***e07db034bd94c5423cbd8f6ea8f045c5c8ccdd97b9254c4b5f11
Digest
  sha256:043e18541***e07db034bd94c5423cbd8f6ea8f045c5c8ccdd97b9254c4b5f11
Metadata
  {
    "containerimage.digest": "sha256:043e18541***e07db034bd94c5423cbd8f6ea8f045c5c8ccdd97b9254c4b5f11"
  }

A: You can reference the imageId as described in the output section of the doc. Just add an id at your current job just for reference, as example:
  - name: Build and push Docker images
    id: docker_build
    uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc
    with:
      context: .
      push: true
      tags: ${{ steps.meta.outputs.tags }}
      labels: ${{ steps.meta.outputs.labels }}

  - name: Print my docker imageid in a separate step
    run: echo "imageid ${{ steps.docker_build.outputs.imageid }}"