text:
Q: Calculating distance using geometry of x and y location in SQL I'm using SQL Server and I need to calculate the distance between the x and y of a frame and the previous x and y of a frame where the day, team, and member are all the same. Currently, I have this code that works but doesn't accomplish what I need. I'm getting every distance permutation of the x and y location where the day, team, and member are all the same.
I need help to incorporate frames into the query so that I get the N+1 Frame x and y location minus the N Frame x and y location.
CREATE TABLE TestTable (
  Day int NULL,
  Frame int NULL,
  Team int NULL,
  Member int NULL,
  x float NULL,
  y float NULL
);

Insert into a Values
  (1, 1, 1, 1, 1486.64, 2017.55),
  (1, 1, 1, 2, 1754.55, 1495.81),
  (1, 1, 2,1, 2049.15, 876.349),
  (1, 2, 1, 1, 1707.59, 1171.22),
  (1, 2, 1, 2, 1432.56, 1459.99),
  (1, 2, 2, 1, 1470.27, 1086.22),
  (1, 3, 1, 1, 3639.19, 1281.36),
  (1, 3, 1, 2, 2751.37, 976.348),
  (1, 3, 2, 1, 2496.69, 1283.29),
  (1, 4, 1, 1, 2347.26, 984.255),
  (1, 4, 1, 2, 2044.92, 711.154),
  (1, 4, 2, 1, 2473.65, 1816.23);

Select A.Day, A.Frame, A.Team, A.Member,
GEOMETRY::Point(A.[x], A.[y], 0).STDistance(GEOMETRY::Point(B.[x], B.[y], 0)) As Distance
From a A
Join a B
ON A.Day = B.Day and A.Team = B.Team and A.Member = B.Member

I also may deal with NULL x and y values so if it's possible to add this to the query too.
Where A.x IS NOT NULL and A.y IS NOT NULL

Ultimately I want to track the distance of every member throughout the day, frame by frame.Later, I'll add up each member's total distance for the day.

A: ;WITH CTE1 AS
(
    SELECT
        [day], team, member, frame, x, y,
        LAG(x) OVER (PARTITION BY [day], team, member ORDER BY frame) AS PervFrameX,
        LAG(y) OVER (PARTITION BY [day], team, member ORDER BY frame) AS PervFrameY
    FROM
        TestTable
    WHERE
        X IS NOT NULL AND Y IS NOT NULL
),
CTE2 AS
(
    SELECT
        [day], team, member, frame, x, y, PervFrameX, PervFrameY,
        IIF(PervFrameX IS NULL OR PervFrameY IS NULL, 0,
            GEOMETRY::Point(x, y, 0).STDistance(GEOMETRY::Point(PervFrameX, PervFrameY, 0))) As Distance
    FROM
        CTE1
)
SELECT
    *,
    SUM(Distance) OVER (PARTITION BY [day], team, member) AS MemberTotalDistance,
    SUM(Distance) OVER (PARTITION BY [day]) AS DailyTotalDistance
FROM
    CTE2
ORDER BY
    [day], team, member, frame

CTE1 and CTE2 are used to improve readability of the query.
Output:
    day team member frame x         y       PervFrameX PervFrameY Distance  MemberTotalDistance DailyTotalDistance
    1   1     1     1     1486.64   2017.55 NULL        NULL       0.000    4135.086           8812.698
    1   1     1     2     1707.59   1171.22 1486.64     2017.55    874.696  4135.086           8812.698
    1   1     1     3     3639.19   1281.36 1707.59     1171.22    1934.738 4135.086           8812.698
    1   1     1     4     2347.26   984.255 3639.19     1281.36    1325.652 4135.086           8812.698
    1   1     2     1     1754.55   1495.81 NULL        NULL       0.000    2483.257           8812.698
    1   1     2     2     1432.56   1459.99 1754.55     1495.81    323.976  2483.257           8812.698
    1   1     2     3     2751.37   976.348 1432.56     1459.99    1404.695 2483.257           8812.698
    1   1     2     4     2044.92   711.154 2751.37     976.348    754.586  2483.257           8812.698
    1   2     1     1     2049.15   876.349 NULL        NULL       0.000    2194.355           8812.698
    1   2     1     2     1470.27   1086.22 2049.15     876.349    615.750  2194.355           8812.698
    1   2     1     3     2496.69   1283.29 1470.27     1086.22    1045.167 2194.355           8812.698
    1   2     1     4     2473.65   1816.23 2496.69     1283.29    533.438  2194.355           8812.698


text:
Q: Como faço uma Alert message UIAlertController Boas,
Como faço um alert? do jeito que fiz parece estar tudo correcto excepto pelo erro da função.
alguma ajuda, desde ja agradeço.

A: No Swift 3, o método presentViewController(_:animated:completion:) foi substituído por present(_:animated:completion:)
self.present(myAlert, animated: true, completion: nil)

A: O erro original era que você havia chamado "presentedViewController", que é uma propriedade, em vez de "presentViewController()" que é um método. Foram duas letrinhas, é fácil confundir :-)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Organising JMeter API tests I'm pretty new to performance testing.
I've got a bunch of endpoints to test and I wonder what is the best approach to do it.
I thought about grouping tests for endpoints in separate .jmx files, for example:
Suppose that there are 2 endpoints: A with simple GET method and B that can serve GET, PUT, POST and DELETE requests. In this scenario I would create 2 .jmx files.
Any helpful links to some tutorials appreciated :)

A: Normally people use Test Fragments for organizing large JMeter scripts.
Depending on whether you want to keep the requests in a single .jmx script or separate you can use:

*

*Module Controller - for re-using requests in the same scripts (i.e. to avoid code duplication)

*Include Controller - to "pull" external .jmx script into the current one


text:
Q: .htaccess rule seemingly ignored I have a Marionette application that manages routes, but I don't want it handling them for api call requests to server.com/api/anything/at/all
My rule looks like this at the moment, but Marionette seems to be always catching it, even when it's for /api/*
# ------------------------------------------------------------------------------
# | Marionette                                                                    |
# | If it's not for /api/*, then handle it                                        |
# ------------------------------------------------------------------------------

<ifModule mod_rewrite.c>
    DirectorySlash Off
    RewriteEngine On
    RewriteCond %{THE_REQUEST} ^.*/index.php
    RewriteCond %{REQUEST_URI} !^/api/ [NC]
    RewriteRule ^(.*)index.php $1 [R,L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/index\.php
    RewriteRule (.*) index.php
</ifModule>
# ------------------------------------------------------------------------------
# | Phalcon                                                                    |
# | If it fell through, handle with Phalcon                                    |
# ------------------------------------------------------------------------------

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>

Can anyone tell me what I've done wrong here please? Thanks.
Edit: If it gives any clarity, the above .htaccess is in my /public folder. In the root folder I have:
# ------------------------------------------------------------------------------
# | Phalcon                                                                    |
# ------------------------------------------------------------------------------

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule  ^$ public/    [L]
    RewriteRule  (.*) public/$1 [L]
</IfModule>

That public rewrite works fine. I just thought I'd share it in case there's something about it affecting the one in public that I'm not thinking of. Thanks!

A: You Marionette rule should be like this:
<ifModule mod_rewrite.c>
    DirectorySlash Off
    RewriteEngine On
    RewriteCond %{THE_REQUEST} ^.*/index.php
    RewriteCond %{REQUEST_URI} !^/api/ [NC]
    RewriteRule ^(.*)index.php $1 [R,L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{THE_REQUEST} !\s/+(index\.php|api/) [NC]
    RewriteRule ^ index.php [L]
</ifModule>


text:
Q: Creating MBean in Java I am trying to make a class implement an MBean Interface so I can interrogate the properties at runtime. The class I am trying to interrogate is as follows
public class ProfileCache implements ProfileCacheInterfaceMBean{

    private Logger logger = Logger.getLogger(ProfileCache.class);
    private ConcurrentMap<String, Profile> cache;

    public ProfileCache(ConcurrentMap<String, Profile> cache){
        this.cache = cache;
    }

    /**
     * Update the cache entry for a given user id
     * @param userid the user id to update for
     * @param profile the new profile to store
     * @return true if the cache update
     */
    public boolean updateCache(String userid, Profile profile) {
        if (cache == null || cache.size() == 0) {
            throw new RuntimeException("Unable to update the cache");
        }
        if (cache.containsKey(userid)) {
            if (profile != null) {
                cache.put(userid, profile);
                logger.info("Updated the cache for user: "
                            + userid + "  profile: " + profile);
                return true;
            }
        }
        return false;
    }

    @Override
    public ConcurrentMap<String, Profile> getCache() {
        if(cache == null){
            cache = new ConcurrentHashMap<String, Profile>();
        }
        return cache;
    }

}

The interface looks like this
import com.vimba.profile.Profile;

public interface ProfileCacheInterfaceMBean {

    ConcurrentMap<String, Profile> getCache();

}

And i start the MBean like this
        cacheImpl = new ProfileCache(factory.createCacheFromDB());
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName profileCache = new ObjectName("org.javalobby.tnt.jmx:type=ProfileCacheInterfaceMBean");
        mbs.registerMBean(cacheImpl, profileCache);

However i keep getting the below exception and I am not sure what I need to change
javax.management.NotCompliantMBeanException: MBean class com.vimba.cache.ProfileCache does not implement DynamicMBean, and neither follows the Standard MBean conventions (javax.management.NotCompliantMBeanException: Class com.vimba.cache.ProfileCache is not a JMX compliant Standard MBean) nor the MXBean conventions (javax.management.NotCompliantMBeanException: com.vimba.cache.ProfileCache: Class com.vimba.cache.ProfileCache is not a JMX compliant MXBean)

I think potentially it's because it returns a Map?

A: The implementing mbean class can declare as many methods as it likes that are not defined in mbeans interface... There is no requirement that the implementing class can/must only implement the interface methods.
In many of the cases this problem is caused because the mbean interface and implementation class are not in the same package!

A: Having just encountered this exception and looked at the current answers as well as https://blogs.oracle.com/jmxetc/entry/javax_management_standardmbean_when_and I thought it might help to emphasize and clarify the following already elucidated to:

*

*The NotCompliantMBeanException is caused, among other things, by failing to follow this convention 'ConcreteClassName' implements 'ConcreteClassNameMBean'

*I resolved this by updating the original name of my mbean interface from 'OrignalNameMBean' to 'OriginalNameMXBean' allowing the mbean to be registered without following the convention

*Another solution would be to follow the convention.

A: You can change interface name from SomethingMBean to SomethingMXBean,such as HelloMBean to HelloMXBean,from jdk's source code i saw this:
public static boolean isMXBeanInterface(Class<?> interfaceClass) {
    if (!interfaceClass.isInterface())
        return false;
    if (!Modifier.isPublic(interfaceClass.getModifiers()) &&
        !Introspector.ALLOW_NONPUBLIC_MBEAN) {
        return false;
    }
    MXBean a = interfaceClass.getAnnotation(MXBean.class);
    if (a != null)
        return a.value();
    return interfaceClass.getName().endsWith("MXBean");
}

if not endsWith "MXBean",it will return false,then cause throw IllegalArgumentException
jdk version:1.8.0_25
class is "JMX",line 376

A: Just change interface suffix from 'MBean' to 'MXBean'.
This works for me.

A: I had the same issue ("does not implement DynamicMBean, and neither follows the Standard MBean conventions") and this article helped me to resolve the problem (see Using StandardMBean section: https://blogs.oracle.com/jmxetc/entry/javax_management_standardmbean_when_and).
I have to explicitly construct a

StandardMBean mbean = new StandardMBean(mBeanImpl, MBeanInterface.class);

then register the mbean:
mbServer.registerMBean(mbean, mBeanName);

It works.
When I register the mBeanImpl with the mbServer, I got the above exception.

A: Just change your implementation class name from ProfileCache  to ProfileCacheInterface. It should work now. Moreover your implementation class can have any number of its own methods and those methods needs not to be mentioned in the MBean interface.
JMX's standard mbean naming convention is like this
    public interface SomeBeanNameMBean{
    ...
    }

    public class SomeBeanName implements SomeBeanNameMBean{
    ...
    //implements all the methods of SomeBeanNameMBean
    ...
    //implement other class's own methods if needed
    }

A: I faced the same problem like 'Exception in thread "main" javax.management.NotCompliantMBeanException', in my case I kept MBean interface and implementation classes in differnet package. To resolve the issue, I moved both MBean interface and the implementation class to same package.

A: In the all the examples I've seen for MBean implementations, I've never seen a class define a method that was not defined in the interface. E.g., ProfileCache has method updateCache, but ProfileCacheInterfaceMBean does not. Try removing the updateCache method from ProfileCache and see if it will work.


text:
Q: referencing an ID field of a form in Views.py I am trying to send the url of a model entry to via e-mail when my form is submitted
However when I reference my form.id like so
 + `'(http://localhost:8000/zipherJobCards/viewJobCard/'+form.cleaned_data['id']+')',`

I get the following error
KeyError: 'id'

Is there any right way to reference the id of an entry like this ?
Please see the full send_mail function here
def jobCard(request ):
    form = jobCardForm()

    if request.method == 'POST':
        form = jobCardForm(request.POST)
        if form.is_valid():
            form.save()

            send_mail(
                'ZTS JOB CARD' + form.cleaned_data['jobNumber'],
                'A new job card has been loaded for ' + form.cleaned_data['customerName'] + ' with a Total Cost of ' + form.cleaned_data['totalCostOfJob'] + '(http://localhost:8000/zipherJobCards/viewJobCard/'+form.cleaned_data['id']+')',
                'it.zipher@gmail.com',
                ['it@zipher.co.za'],
                fail_silently=False,
            )

            return redirect('home')
        else:
            print(form.errors)

    content = {'form':form}
    return render(request, 'main/jobCard.html', content)

A: id (or pk) is not part of the form, it is the primary key that is set when the object is saved. You need to do obj = form.save(), then you can reference the saved object, like obj.id.


text:
Q: Azure Devops - Nested Variables At Runtime I have a set of databases that I am trying to work with in Azure Devops.
I have a variable group that has various pieces of information for each database.
The variables follow a convention of .
CoreUserName, CoreIPAddress
TestUserName, TestIPAddress
FooUserName, FooIPAddress
The databases come into the template via parameterized array of strings that I am doing a foreach over. What I need is a way to resolve the value of the variables for the current item in the array.
Say the array is passed in like this:
dbPackages: ['Core','Test']
I need a way to take Core and append UserName (to CoreUserName) and then resolve the value of the CoreUserName variable.
I know that nested parameters "are not supported" but I am wondering if something like this can be accomplished with setting variables in a bash or powershell script? I just haven't figured out the proper syntax.
Ideas?

A: Here's two possible syntaxes. I'm assuming you're defining dbStages as a parameter and doing foreach loop in the pipeline....
As Environment Variables
All pipeline variables are available at runtime as environment variables, so it's possible to access them in several different ways programmatically. Here I'm passing Core/Test/Foo as an env value and then accessing it as an environment variable.
parameters:
- name: dbStages
  type: object
  default:
  - Core
  - Test
  - Foo

variables:
- group: myVariableGroup

steps:
- ${{ each dbPrefix in parameters.dbStages }}:
  - task:PowerShell@2
    inputs:
      targetType: inline
      script: |

        $prefix = $env:prefix
        $varUserName  = $prefix + "UserName"

        # access through $env
        $UserName = $env:$varUserName

        # access through Env: provider
        $UserName = Get-Item Env:$varUserName

        # access through .NET
        $UserName = [System.Environment]::GetEnvironmentVariable($varUserName)

      env:
        prefix: ${{ dbPrefix }}

You could go one step further, and de-reference CoreUserName to UserName by using the available Logging Commands. Subsequent tasks would be able to use the $(UserName) variable...

$UserName = $env:$( $prefix + "UserName" )
Write-Host "##vso[task.setvariable variable=UserName]$UserName"

Through Macro Syntax
The second option is to access the variables through the $() macro syntax. It's important to realize that parameters are resolved when the pipeline is compiled and variables are evaluated at runtime.
We can leverage compile time parameters to construct the macro syntax with the variable name you want to evaluate at runtime:
- ${{ each dbPrefix in parameters.dbStages }}:
  - task: PowerShell@2
    inputs:
      targetType: inline
      script: |

         # resolves into "$(CoreUserName)" at compile time
         # by is evaluated as "<value-of-CoreUserName>" at runtime
         $userName = "$(${{ dbPrefix }}UserName)"


text:
Q: Displaying vectors on Screen I have been doing some reading about how to create a set number of arrays and populate those arrays using for loops in C++. Everywhere says that I need to use vectors. I have created the arrays and populated them using vectors (I think). When I compile and run with displaying the arrays, everything is ok. When I try to display the contents of the arrays, The program compiles ok but crashes when I run it.
I am trying to create 100 arrays with their size increasing by 500 elements each time. (This is for an assignment where we need to test the efficacy of an algorithm.)
unsigned int numArrays = 100;
unsigned int arraySize = 0;
//Create holder variable:
unsigned int randomInt = 0;
//Create the arrays:
std:vector<std::vector<int> > arrays(numArrays);

for(std::size_t i=0; i< numArrays; i++){

    arraySize = i * 500;
    vector<int> temp;
    temp.reserve(arraySize);

    for(int j=0; j< arraySize; j++){

        //Generate Random number:
        randomInt = rand();
        //Add the number to the array:
        temp.push_back(randomInt);

    }
    arrays.push_back(temp);
}

for(int i=0; i<arrays.size(); i++){

    cout << "{";
    for(int j=0; j<arrays.at(i).size() - 1; j++){

        cout << arrays.at(i).at(j) << ",";

    }
    cout << arrays.at(i).back() << "}" << endl;
}

I assume the error is somewhere in the final nested loops but I am not sure. Thanks in advance.

A: std:vector<std::vector<int> > arrays(numArrays);

Here you initialize your vector with numArrays empty vector<int>s.
But then you append your new vectors. Meaning you have at the end 2*numArrays vectors.
The crash comes from the first half of the vectors:

*

*the minus 1 in j<arrays.at(i).size() - 1: size() returns an unsigned 0, minus 1 is the maximum value.

*arrays.at(i).back() trying to get a non existing last element.

To fix the problem, replace this line
std::vector<std::vector<int> > arrays(numArrays);

by
std::vector<std::vector<int> > arrays;
arrays.reserve(numArrays);

And add a test for non-empty()ness before computing size() - 1.


text:
Q: Call forwarding loop instead of redirect I have a code in django view (django==2.1), where I want to redirect from sub domain to main domain.
def signup(request):
    current_site = Site.objects.get_current()
    if request.META['HTTP_HOST'] != current_site.domain:
        full = urljoin(current_site.domain, reverse('accounts:signup'))
        return HttpResponseRedirect(full)

Instead of redirecting, there's a redirecting loop. And instead of the full address, there is the ending: /accounts/signup/.
It should be http://localhost:8000/accounts/signup/


text:
Q: How can I avoid heap out of memory? I wrote this code to get ended my homework as a practice.
This code controls browser with nightmare.js.It just iterates clicking button and waiting for a sec.
But this code issued an error of heap out of memory. I just tried out "--max-old-space-size=4096". but it didn't work...
ANYONE HELP ME??
I checked other than iterations can work. Then putting iterations..., it cannot work due to heap out of memory.
To be honest, I am not good at coding and English. If there are any miswriting, ask me please!
const Nightmare = require('nightmare');
const nightmare = Nightmare({show: true});

const LinguaURL = "";
const NumberOfMine = "";
const PwdOfMine = "";

var i,j = -1;
var selection, progress;
var radioSelect = -1;

function main() {
  nightmare
    .goto(LinguaURL)
    .wait(1000)
    .type("input[type='text']", NumberOfMine)
    .type("input[type='password']", PwdOfMine)
    .click("input[type='submit']")
    .wait(5000)
    .click('a[href="javascript:document.Study.submit()"]')
    .wait(3000)
    .click("input[type='button']")
    .wait(3000);

    for(i = 3;i<43;i++){
      nightmare
        .click('a[onclick="unit_view_page(\''+i.toString()+'\');"]');
        while(true){
          j++;

          if(j % 4 == 0){
          nightmare
            .click('input[onclick="select_unit(\'drill\', \''+(1833+j).toString()+'\', \'\');"]')
            .wait(1000);

          while(true){
            radioSelect++;

            nightmare
              .click('input[id="answer_0_' + radioSelect.toString() +'"]')
              .wait(1000)
              .click('input[id="ans_submit"]')
              .wait(1000)
              .evaluate(function (){
                 return selection = document.querySelector('.btn btn-answer-view form-font-size');
              })
              .evaluate(function (){
                return progress = document.querySelector('btn btn-next-problem form-font-size');
              });

              if(selection == null && progress == null)break;

              if(selection != null){
                continue;
              }else{
                nightmare
                  .click('input[class="btn btn-next-problem form-font-size"]');
                continue;
              }
          }
          if((j + 1) % 10 == 0)break;
          }
        }
      }
      nightmare
        .wait(100)
        .end()
        .then(console.log);
}

main();

A: If I'm not mistaken, I think this is the reason.
function main() {
    for(i = 3;i<43;i++){
        while(true){
            j++;
            if(j % 4 == 0){
                while(true){
                    /**** break for the second while. ****/
                    if(selection == null && progress == null) break;
                    if(selection != null){
                        continue;
                    }else{
                        continue;
                    }
                }
                /**** break for the first while. ****/
                // But this code will be run if 'j % 4 == 0',
                // and I can't see any assigned the value to 'j' variable inside of 'if'.
                // There's no way the result will be true.
                if((j + 1) % 10 == 0) { break; }
            }
        }
    }
}

var j = -1;
var limit = 2000 * 4;
while(true){
    j++;
    if(j != 0 && j % 1000 == 0) console.log("loop: " + j);
    // here we go.
    if(j % 4 == 0){
        while(true){
            break;
        }
        // But this code will be run if 'j % 4 == 0',
        // and I can't see any assigned the value to 'j' variable inside of 'if'.
        // There's no way the result will be true.
        if((j + 1) % 10 == 0) { console.log("your if statement"); break; }
        // limit
        if (j == limit) { console.log("break using limit"); break; }
    }
    // Maybe (do you just want to run ten times?)
    // if((j + 1) % 10 == 0) { console.log("[maybe] your if statement"); break; }
}
console.log("process end");


text:
Q: Spark UDF not giving rolling counts properly I have a Spark UDF to calculate rolling counts of a column, precisely wrt time. If I need to calculate a rolling count for 24 hours, for example for entry with time 2020-10-02 09:04:00, I need to look back until 2020-10-01 09:04:00 (very precise).
The Rolling count UDF works fine and gives correct counts, if I run locally, but when I run on a cluster, its giving incorrect results. Here is the sample input and output
Input
+---------+-----------------------+
|OrderName|Time                   |
+---------+-----------------------+
|a        |2020-07-11 23:58:45.538|
|a        |2020-07-12 00:00:07.307|
|a        |2020-07-12 00:01:08.817|
|a        |2020-07-12 00:02:15.675|
|a        |2020-07-12 00:05:48.277|
+---------+-----------------------+

Expected Output
+---------+-----------------------+-----+
|OrderName|Time                   |Count|
+---------+-----------------------+-----+
|a        |2020-07-11 23:58:45.538|1    |
|a        |2020-07-12 00:00:07.307|2    |
|a        |2020-07-12 00:01:08.817|3    |
|a        |2020-07-12 00:02:15.675|1    |
|a        |2020-07-12 00:05:48.277|1    |
+---------+-----------------------+-----+

Last two entry values are 4 and 5 locally, but on cluster they are incorrect. My best guess is data is being distributed across executors and udf is also being called in parallel on each executor. As one of the parameter to UDF is column (Partition key - OrderName in this example), how could I control/correct the behavior for cluster if thats the case. So that it calculates proper counts for each partition in a right way. Any suggestion please

A: As per your comment , you want to count the total no of records of every record for the last 24 hours
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.types.LongType

//A sample data (Guessing from your question)
val df = Seq(("a","2020-07-10 23:58:45.438","1"),("a","2020-07-11 23:58:45.538","1"),("a","2020-07-11 23:58:45.638","1")).toDF("OrderName","Time","Count")

// Extract the UNIX TIMESTAMP for your time column
val df2 = df.withColumn("unix_time",concat(unix_timestamp($"Time"),split($"Time","\\.")(1)).cast(LongType))

val noOfMilisecondsDay : Long = 24*60*60*1000

//Create a window per `OrderName` and select rows from `current time - 24 hours` to `current time`
val winSpec = Window.partitionBy("OrderName").orderBy("unix_time").rangeBetween(Window.currentRow - noOfMilisecondsDay, Window.currentRow)

// Final you perform your COUNT or SUM(COUNT) as per your need
val finalDf = df2.withColumn("tot_count", count("OrderName").over(winSpec))

//or val finalDf = df2.withColumn("tot_count", sum("Count").over(winSpec))


text:
Q: Geonames API add new name I started to integrate Geonames in my RDF. I use the web services to search informations about places, but the browsers gui to add new names. There is a way to send the lat,lng coordinates and create a new name automatically?
EDIT:
I have some kml files. I want to use the coordinates value to create new elements in geonames (http://www.geonames.org). I have to do this "manually", going on the map and giving a "insert new name here" command.
To read information from geonames there are some web services (http://www.geonames.org/export/web-services.html), but I didn't found nothing for insert new elements.


text:
Q: discord.py tenor api am i doing this wrong? @client.command()
async def oppai1(ctx):
 async with aiohttp.ClientSession() as session:
  embed = discord.Embed (
        title = 'OPPAI',
        description = "Here's Ya OPPAI!",
        colour = discord.Colour.blue())

  response = await session.get('https://api.tenor.com/v1/search?q=oppai&key=85LY8DY0JV3Q&limit=30&media_filter=basic')
  data = json.loads(await response.text())
  gif_choice = random.randint(0,29)
  embed.set_image(url=data['weburl'][gif_choice]['gif']['url'])

  await session.close()
  await ctx.send(embed=embed)

I'm new so I kinda don't know anymore need halp, I'm trying it to only send 'oppai' GIF : ) also pls don't say I'm bad I'm just a dum-dum and new. ( Giphy worked fine for me but its search relevance is really bad it's supposed to be an oppai search it would send a different gif, whilst tenor is very relevant to its search)
Someone pls halp ;-;

A: First of all, be more careful with your API key. It's like your password to the tenor API, so try not to write it on StackExchange.
As for the solution, I believe you just need replace ['weburl'] with ['results'] in url=data['weburl'][gif_choice]['gif']['url'].


text:
Q: Django - how to define a MySQL CHAR data type in models? I use MySQL as the db backend in django, I want to define a MySQL CHAR data type. When i use CharField, it will be a VARCHAR data type.
c0 = models.CharField(max_length=1)

How to define a MySQL CHAR data type in django models.

A: You'll have to Manually Create It.
from django.db import models

class MytypeField(models.Field):
    def db_type(self, connection):
        return 'CHAR'

class your_model(models.Model):
    name = models.CharField(max_length=80)
    your_field_you_want_to_create_custom_type = MytypeField()

Try it and comment if it works.


text:
Q: Why is my op-amp giving same output for low voltages? So I am trying to make analog output 0-10vdc with my esp32 microcontroller.
I have read that esp can give true analog voltage cause it has DAC so my plan is to connect one of esp32 DAC pins to non inverting op-amp circuit to get a gain of 3 so I have 0-10VDC analog output from the op-amp. I have connected everything according to online schematics for non inverting op-amp (using lm741cn), My R1 is 1k fixed resistor and R2 is trimmer 2k that I put on the value of 2k so it gives me 3 gain in theory. In the esp32 code I change dac value from 0-255 and it actually gives 0-3.15vdc on the output of esp32 pin. Problem is that for low values of dac (0-127 tested) I get same output on op-amp of 6.68Vdc instead of proper linear voltage that I should get (0-5VDC in theory). Can someone tell me what could be the problem here? I tested connections and everything should work fine.

A: An LM741 is not the best choice here. You're outside the input range of the op-amp and the output cannot swing to even a bit near the negative rail.
You can either give the op-amp a negative supply (-10V to -12V, for example), as well as a positive supply of 12V or so,  or replace it with something like an LM358 dual, with a supply of +12 and GND.


text:
Q: Cython: Efficiently loop over list with multiple types I have a Python function that loops over a list and I want to convert it to Cython for performance gain.
The lists it accepts contain a mix of strings, integers, and floats, so I'm not sure how to statically type the variables involved (I don't know C).
What would be the most efficient way to implement something like this in Cython?

A: You seem to be hoping for a C type that has all the flexibility of the Python object, but is somehow magically faster.
There is basically a good option and a bad option here:

*

*The good option is to accept that such a type doesn't really exist.
Therefore, you should leave your data extracted from the list untyped so that it remains a regular Python object. Not everything in Cython needs to be typed - the vast majority of Python code should run unchanged.
It might be worth typing your list as list, since Cython can generate slightly more efficient loops when it knows the iterable is a list.

*The bad option is to use a feature of C called a union which represents a variable that is one of a limited number of dissimilar types. I am not recommending this (especially for someone that doesn't know C already) because there is no "easy" Cython wrapping (you'll have to dive directly into the C details). You will find handling strings in a union particularly challenging.
Pursue this option at your own peril.


text:
Q: Android Intent - Extras not found on first load from url I'm trying to load my application from a webpage via deep linking.
I'm using window.location to call the intent url when a webpage is hit.
The app opens fine using:
window.location("intent://open/#Intent;scheme=testapp;package=gb.testapp.testapp;S.id=3026;end"); however, the id that I'm trying to pass in only seems to appear if the URL is loaded for a second time...
My Intent in AndoridManifest.xml is:
<intent-filter>
    <action android:name="android.intent.action.VIEW"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <category android:name="android.intent.category.BROWSABLE"/>
    <data android:scheme="testapp"  android:host="open" android:path="/" />
 </intent-filter>

I'm calling the following code in my MainActivity.java
public void onNewIntent(Intent intent) {

        super.onNewIntent(intent);

         Bundle extras = getIntent().getExtras();
         System.out.println("URLLOAD -  " + intent.getDataString());
         if (extras != null){
             String sid = extras.getString("id");

             if (sid!=null)
             {
                 System.out.println("URLLOAD - FOUND PARAMS");
             }

         }else{
             System.out.println("URLLOAD -  NO PARAMS");
         }
}

This results in:
First time opening url after app install:
System.out﹕ URLLOAD -  testApp://open/
System.out﹕ URLLOAD -  NO PARAMS

Opening the URL again
I/System.out﹕ URLLOAD -  testApp://open/?id=3026
I/System.out﹕ URLLOAD - FOUND PARAMS

Has anyone come across a similar issue or can see an issue with my code?
Thanks,
Simon

A: My guess would be that the first time you launch your acitivty (app) the onCreate() method is being called instead of onNewIntent(). For all subsequent calls your activity is "updated" via the onNewIntent method.


text:
Q: How to Skip, Take and Orderby using Azure.Data.Tables? Microsoft suggests azure.data.tables nuget and namespace instead of older microsoft.azure.cosmos.table namespace but it is not well documented and I cannot find more information beside their Github page. Here they described basic querying but my question is; is it possible to get sorted and filtered entities from the server, not on the client side?
For example with the other library it is possible to use TableQuery and do take, orderby operations like described here
What i am trying to achieve it basically
var result= query.OrderByDescending(l => l.Timestamp).Skip((pagenumber- 1) * count.Value).Take(count.Value);

Is it possible to achieve this query on the server side using  Azure.Data.Tables namespace?

A: Only thing you can use from these operators is "Take" because other two operators are not supported by Azure Table Storage.
For the list of supported LINQ operators with Azure Table Storage, please see this link: https://learn.microsoft.com/en-us/rest/api/storageservices/query-operators-supported-for-the-table-service.

A: I am in a similar situation and I came across these articles:

*

*https://scotthelme.co.uk/hacking-table-storage-to-do-order-by-on-timestamp/

*https://scotthelme.co.uk/hacking-table-storage-like-queries/
The methods he describes is a hack and will take some thought as to how to apply to your situation. Thought I'd put it up here in case anyone ends up on this page.


text:
Q: What to do if favorite open source library does not have a Nuget package If my favorite open source library is not available as a Nuget package on Nuget.org, which of these is preferred?

*

*Create a Nuget package and use a private Nuget server to host it.

*Create a Nuget package and publish it on Nuget.org - even if I'm not the author.

*Plead with the library authors and ask them to publish it.

Or something else?

A: I had the same problem as you have. I solved it by asking whether it would be OK to package the library as a NuGet package and publish it to the official NuGet feed. The authors agreed and I packaged the library. The package has >400 downloads in two months, so there's other people out there using it :-)
So, basically a combination of the second and third option. Most people will agree if you offer to do the work...

A: Since we have some commercial assemblies that we also want to package up and serve using nuget, I opted to create our own private feed.  It is working for us.
I see the value in contacting the library authors and work with them to create a package for the main nuget feed, so maybe when I get more comfortable with creating packages and 'doing it right' I can start doing that for open source libraries.


text:
Q: Counting paths from the origin to a given point Consider the following "walk" from the origin (0,0) in the plane to the point E=(5,5). A walk consists of starting at the origin and on each move, moving either one unit distance up or one unit distance to the right. Each walk that starts at the origin and ends up at E=(5,5) traces out a continuous path consisting of horizontal and vertical line segments which starts at (0,0) and ends at (5,5). How many different such paths are there?
(Hint: Note that to reach E=(5,5) from the origin, you have to make 10 moves total of which 5 have to be upward and 5 rightward.)
I have absolutely no idea what this is asking. I asked my professor to clarify... has not responded yet...

A: As the hint suggested, to reach $(5,5)$ from $(0,0)$, we will take $10$ consecutive "steps," of which $5$ will be up and $5$ to the right. We can choose any $5$ of these $10$ steps to be the "up" steps.
So there are $\binom{10}{5}$ possible paths.

A: To visualize the problem draw the quarter xy plane, that is, the positive x and y axises, on a graphing sheet. Now mark all the points with integer coordinates on and inside the square whose vertices are (0,0),(0,5),(5,0), and (5,5). You can draw small dots to make these marks. So, for example, you would have a dot on your graphing paper at the point (1,1). When you are done, you should have a total of 25 points. Now, the question asks, how many ways are there, starting from the origin (0,0), to move to the corner point (5,5), with the constraint that you can only move up or right and you can only step on the drawn points? A sample path would be (0,1)(0,2)(1,2)(2,2)(3,2)(3,3)(3,4)(4,4)(5,4)(5,5). Notice that you can't move diagonally to a point. Only up and right. Obviously you can count all the distinct paths by actually drawing them out or you can use combinatorics and counting methods to compute the number of paths.


text:
Q: Fix button alignment when content pushes it down I've created a few products using HTML & CSS only.
An issue I'm facing is that when the content in the  exceeds a certain amount, it pushes everything down, making the alignment uneven (see 3rd product in image). How can I go about making so everything is in alignment?
My thoughts are to have the h2 tag have enough space to cover 2 or 3 lines worth (I don't have products longer than 2 lines). So the read more, grams and button will remain fixed and inline.
Any ideas how I can achieve that or any recommendations? I've pasted the codepen, code & image for reference
Codepen

@import url(https://fonts.googleapis.com/css?family=Work+Sans:200,300,400,500);
* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  outline: none;
  font-family: "Work Sans", sans-serif;
}

body {
  font-style: normal;
  margin: 0 0 0.5em;
  line-height: 1.4;
}

h2 {
  color: #303457;
  margin: 2rem 0 .5rem;
  font-size: 1.25rem;
  font-weight: 400;
  text-transform: uppercase;
  font-weight: bold;
}

a {
  color: inherit;
}

img {
  display: block;
  border: 0;
  width: 100%;
  height: 200px;
}

.container {
  margin: auto;
  width: 80%;
  padding: 10px;
}

/*** Cards ***/

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  grid-auto-rows: minmax(200px, auto);
  grid-gap: 2rem;
  min-height: 400px;
}

.card {
  /*height: 200px;*/
  /*background: red;*/
  padding: .5rem;
  display: flex;
  /* -webkit-box-orient: vertical; */
  /* -webkit-box-direction: normal; */
  -ms-flex-direction: column;
  flex-direction: column;
  position: relative;
  color: #5d5e5e;
}

.thumbnail img {
  fill: #c7c4c4;
  padding: 1rem;
}

.card-content {
  font-size: 0.9rem;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  text-align: center;
}

.card-content p {
  font-size: 1rem;
  margin: 10px 0px;
}

a.read_more {
  font-size: 16px;
  font-weight: 400;
  text-decoration: none;
}

p.product_grams {
  font-size: 14px;
  font-weight: bold;
}

.btn {
  background-color: #303457;
  border: none;
  color: white;
  padding: 12px 0px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  -webkit-transition: all 1s ease-out;
  -moz-transition: all 0.2s ease-out;
  -o-transition: all 0.2s ease-out;
  -ms-transition: all 0.2s ease-out;
  transition: all 0.2s ease-out;
}

.btn:hover {
  background-color: #3F457E;
  cursor: pointer;
  -webkit-transition: background-color 0.3s;
  -ms-transition: background-color 0.3s;
  transition: background-color 0.3s;
}

.btn:active {
  outline: none;
}

        <picture class="thumbnail">

        </picture>

American Hard Gums

          Read More

80g

          <button type="submit" class="btn">Add</button>

        <picture class="thumbnail">

        </picture>

Dracula Teeth

          Read More

80 grams

          <button type="submit" class="btn">Add</button>

        <picture class="thumbnail">

        </picture>

Fizzy Blue Jelly Babies

          Read More

80 grams

          <button type="submit" class="btn">Add</button>

        <picture class="thumbnail">

        </picture>

Fizzy Cola Bottles

          Read More

80 grams

          <button type="submit" class="btn">Add</button>

        <picture class="thumbnail">

        </picture>

Fizzy Strawberries

          Read More

80 grams

          <button type="submit" class="btn">Add</button>

        <picture class="thumbnail">

        </picture>

Peach Rings

          Read More

80 grams

          <button type="submit" class="btn">Add</button>

A: Try this.
Hope it solved your problem.

@import url(https://fonts.googleapis.com/css?family=Work+Sans:200,300,400,500);

* {
  -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    outline: none;
    font-family: "Work Sans", sans-serif;
}

body {
    font-style: normal;
    margin: 0 0 0.5em;
    line-height: 1.4;
}

h2 {
    color: #303457;
    margin: 2rem 0 .5rem;
    font-size: 1.25rem;
    font-weight: 400;
    text-transform: uppercase;
    font-weight: bold;
}

a {
    color: inherit;
}

img {
    display: block;
    border: 0;
    width: 100%;
    height: 200px;
}

.container {
    margin: auto;
    width: 80%;
    padding: 10px;
}

.cards {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    grid-auto-rows: minmax(200px, auto);
    grid-gap: 2rem;
    min-height: 400px;
}

.card {
    padding: .5rem;
    display: flex;
    -ms-flex-direction: column;
    flex-direction: column;
    position: relative;
    color: #5d5e5e;
}

.thumbnail img {
    fill: #c7c4c4;
    padding: 1rem;
}

.card-content {
    font-size: 0.9rem;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
    -webkit-box-flex: 1;
    -ms-flex: 1;
    flex: 1;
    text-align: center;
}

.card-content p {
    font-size: 1rem;
    margin: 10px 0px;
}

.card-content h2{
  flex-grow: 1;
}

a.read_more {
    font-size: 16px;
    font-weight: 400;
    text-decoration: none;
}

p.product_grams {
    font-size: 14px;
    font-weight: bold;
}

.btn {
    background-color: #303457;
    border: none;
    color: white;
    padding: 12px 0px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    -webkit-transition: all 1s ease-out;
    -moz-transition: all 0.2s ease-out;
    -o-transition: all 0.2s ease-out;
    -ms-transition: all 0.2s ease-out;
    transition: all 0.2s ease-out;
}

.btn:hover {
    background-color: #3F457E;
    cursor: pointer;
    -webkit-transition: background-color 0.3s;
    -ms-transition: background-color 0.3s;
    transition: background-color 0.3s;
}

.btn:active {
    outline:none;
}

                    <picture class="thumbnail">

                    </picture>

American Hard Gums

                        Read More

80 grams

                        <button type="submit" class="btn">Add</button>

                    <picture class="thumbnail">

                    </picture>

Dracula Teeth

                        Read More

80 grams

                        <button type="submit" class="btn">Add</button>

                    <picture class="thumbnail">

                    </picture>

Fizzy Blue Jelly Babies

                        Read More

80 grams

                        <button type="submit" class="btn">Add</button>

                <picture class="thumbnail">

                </picture>

Fizzy Cola Bottles

                    Read More

80 grams

                    <button type="submit" class="btn">Add</button>

A: You could set the height of the H2 a half of the line height (if you say there will not be more than 2 lines).
In your case these values should work:
h2 {
    line-height: 30px;
    height: 70px;
}


text:
Q: How do I implement the following type of search : I have to come up with the design  for a search . The searched data is not of document type . The data entity to be searched are medical procedures  basically consists of one/two/three words each . The words are pre defined by the admin . Ex: Angioplasty Surgery , Rhinoplasty , Adrenal Surgery , ACTH simulation test etc .
The end user selects the procedure name from a selection and the user's selection is stored in db . End user refers to a user who is creating his profile .
I index the keywords in a separate table with the user id's . So for Rhinoplasty if three user's have added it , I will have three entries in the indexed table . Similarly for other procedures .

Procedure Name |  User ID|
-------------------------
Rhinoplasty       1
Rhinoplasty       2
Rhinoplasty       3
Adrenal Surgery   2
Adrenal Surgery   3
Angioplasty       1

And so on .

The problem arises when some  user tries to search for procedures(which leads him to the profiles)  .He may write 'adrenal surgery' as 'surgery adrenal' or 'angioplasty' as 'angioplasty surgery' or 'ACTH simulation test ' as 'Simulation test for ACTH' . Some times procedures can have synonmys/acronyms as well .
I understand the concept of stop words . I can define common words such as 'surgery' and 'test' under them . Strip my indexed tables of these stop words and strip the search query as well .
How can I implement synonyms ? ALso is there a better way to implement search like this ? I don't think I can look at lucene or solr as they are full text search engines  .

A: Sounds like that you need some kind of full text search solution, take a look at solr or a little less heavyweight sphinx.
For fuzzy match alone, you can try using your database system's built in fulltext indexes too, both mysql and progresql features one. Postgres supports dictionaries for synonyms too.

A: Try using using like clause in your query
 SELECT * from TABLENAME WHERE Procedure Name like "%Surgery Adrenal%";


text:
Q: How to specify query MediaStore.Audio.Media in Android SDK? I have a ListView of a music albums that are on my SD. I want to make another list that displays the songs that are on the album, when i click it. How to I query MediaStore only for that certain album?
Thanks!

A: Hi this may help you.....
Specify where clause with MediaStore.Audio.Media.ALBUM =
cur = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                            proj, whereclause, null, null);


text:
Q: Finding size of RAM on a remote computer I am attempting to find the size of the RAM on a remote computer on the domain. Here is the relevant part of the powershell script I have:
Invoke-Command -ComputerName $ComputerName {Get-PSDrive -PSProvider FileSystem} |
    where {$_.Free -gt 0} |
    select pscomputername,Root,@{name="RAM (GB)";expression={"{0:N3}"
        -f (($_.TotalPhysicalMemory)/1gb)}}

The script executes without any errors, however, shows "0.00" as the output for the installed RAM. This is of course incorrect and I have tried running this on several remote computers.
Any tips would be appreciated as I am a beginner in PS.

A: You can try
Invoke-Command -ComputerName $ComputerName {Get-WmiObject win32_computersystem} | select @{name="RAM (GB)";e={[math]::Round($_.totalphysicalmemory/1GB,0)}}

and as what i know filesystem provider refers to the Disk Drive.


text:
Q: SharePoint Online list items 5000 +, rest query I have few lists and libraries which may reach the threshold value of 5000 soon? I have several dashboards which I've used Rest queries to fetch data according to the status of the items. My question is if list exceeds 5000 items, will there be any effect on the dashboards I have, will the rest query function normally or breaks. Can anyone answer please
Thanks,
Suzeeth

A: If you have used filters on status and/or on other columns which will always return less than 5000 items from list then it will not cause any problems.
Another way to avoid the issues due to threshold is add indexes on the columns you are using in filters(Check below link for more details).
So, either you should add filters to your REST query so that it will always return less than 5000 list items or you can use $top as given below:
siteUrl/_api/web/lists/getbytitle('List Display Name')/items?$top=1000

Also, there are some ways to manage such large lists in SharePoint using indexes and folders which you can find in below article:
Manage large lists and libraries in SharePoint.
Also you can use recursive call to get 5000 items like given below:
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ListName')/items?$select=Title&$top=1000&$skiptoken=Paged=TRUE";
    var response = response || [];  // this variable is used for storing list items
    function GetListItems(){
        return $.ajax({
            url: url,
            method: "GET",
            headers: {
                "Accept": "application/json; odata=verbose"
            },
            success: function(data){
                response = response.concat(data.d.results);
                if (data.d.__next) {
                    url = data.d.__next;
                    GetListItems();
                } else {
                    return response;
                }

            },
            error: function(error){
            }
        });
    }

A: Make sure your status column is indexed. At any point of time, if your list has items more than 5000 which has same status column value(like Completed or Pending). It will not return data.
You can still break your API calls to get 4999 items using paging techniques,
To implement paging, We have to add ?$skiptoken=Paged=TRUE&$top=4999 to the end of the URI.
In your response, The URI for the next page will be included under JSON.d.__next.
At the end of data(or last page) is reached __next will not be present.
So you have to handle this in your code logic to make recursive call until all data for a particular filter is returned.
Please note that if have to use any other filter in your queries, all such columns should be indexed before list threshold is reached.


text:
Q: System.FormatException: 'Failed to convert parameter value from a String to a Int32.' I keep getting the error in the title when i am trying to pass data to my database using a c# windows form.
For reference, I am trying to use the Scope_Identity to get the current PK from one table and then pass it to another table as a FK. But i am having trouble making this work. I have no doubt I am missing something or doing something wrong, but I honestly cannot find a solution to what I need. Here is the code I am using.
SqlConnection con = new SqlConnection(@"");
        con.Open();
        {
            using (SqlCommand cmd = new SqlCommand("INSERT dbo.Booking(CustomerID,VehicleID,DateofBooking," +
                "DurationBooked, ExpectedReturnDate) VALUES( @CustID, @VehicleID, @DOBooking, @DurationBooked,@ExpectedReturn); INSERT dbo.Payments (BookingID,PaymentMethod,Discount,PaymentAmount," +
                "PaymentDate,PaymentReceived) VALUES( SCOPE_IDENTITY(),@PayMeth,@PayAmount,@PayDate, @PayReceived, @Discount)"))

            {
                cmd.Connection = con;
                cmd.Parameters.Add("@CustID", SqlDbType.Int).Value = comboBox1.ValueMember;
                cmd.Parameters.Add("@VehicleID", SqlDbType.Int).Value = comboBox2.ValueMember;
                cmd.Parameters.Add("@DOBooking", SqlDbType.Date).Value = datefrom.Text;
                cmd.Parameters.Add("@ExpectedReturn", SqlDbType.Date).Value = dateTo.Text;
                cmd.Parameters.Add("@DurationBooked", SqlDbType.Float, 3).Value = Duration.Text;
                cmd.Parameters.Add("@PayMeth", SqlDbType.VarChar, 15).Value = listBox1.Text;
                cmd.Parameters.Add("@PayAmount", SqlDbType.Money).Value = PayAmount.Text;
                cmd.Parameters.Add("@PayDate", SqlDbType.Date).Value = DatePay.Text;
                cmd.Parameters.Add("@PayReceived", SqlDbType.VarChar, 3).Value = PayReceived.Text;
                cmd.Parameters.Add("@Discount", SqlDbType.SmallMoney).Value = Discount.Text;

            }

I am having a ridiculous amount of hassle trying to Pass this PK to another Table as a FK For reference, it is the BookingID from the Booking table that i am trying to pass to the Payments table in the BookingID column which is a FK relationship
Error Image

A: I think you're trying to fight with a different problem.
you have conversion issue, but not PK or FK key consistency.
please check if all the params they you send have the same type as described in your instruction.
It can be also that even your scope_identity() has type different from value.
I don't know if you covered this with Keys constraints
by the way. out of scope. There is also a way to get last id is to use @@IDENTITY.
The @@identity function returns the last identity created in the same session. The scope_identity() function returns the last identity created in the same session and the same scope.

A: FIXED. Thank you to all those who helped. The issue was indeed with my Parameters, specifically with dates. I needed to change the DataType in SQL server to DateTime, as well as ensuring the query would run in SQL Server first helped.
 using (SqlCommand cmd = new SqlCommand("INSERT dbo.Booking(CustomerID,VehicleID,DateofBooking, DurationBooked, ExpectedReturnDate) " +
                "VALUES( @CustID, @VehicleID, @DOBooking, @DurationBooked,@ExpectedReturn) SELECT SCOPE_IDENTITY(); " +
                "INSERT dbo.Payments (BookingID,PaymentMethod,Discount,PaymentAmount, PaymentDate,PaymentReceived)" +
                "VALUES( SCOPE_IDENTITY(),@PayMeth,@Discount,@PayAmount, @PayDate, @PayReceived)"))

            {
                cmd.Connection = con;
                cmd.Parameters.Add("@CustID", SqlDbType.Int).Value = Convert.ToInt32(CustID.SelectedValue);
                cmd.Parameters.Add("@VehicleID", SqlDbType.Int).Value = Convert.ToInt32(VehicleID.SelectedValue);
                cmd.Parameters.Add("@DOBooking", SqlDbType.DateTime).Value = DateofBooking.Value.Date;
                cmd.Parameters.Add("@ExpectedReturn", SqlDbType.DateTime).Value = ExpectedReturnDate.Value.Date;
                cmd.Parameters.Add("@DurationBooked", SqlDbType.Float, 3).Value = Duration.Text;
                cmd.Parameters.Add("@PayMeth", SqlDbType.VarChar, 15).Value = PaymentMethod.Text;
                cmd.Parameters.Add("@PayAmount", SqlDbType.Money).Value = PayAmount.Text;
                cmd.Parameters.Add("@PayDate", SqlDbType.DateTime).Value = PayDate.Value.Date;
                cmd.Parameters.Add("@PayReceived", SqlDbType.VarChar, 3).Value = Received.Text;
                cmd.Parameters.Add("@Discount", SqlDbType.VarChar, 3).Value = Discount.Text;
                if (cmd.ExecuteNonQuery() > 0)
                {
                    MessageBox.Show("Record inserted");
                }
                else
                {
                    MessageBox.Show("Customer failed");
                }

For Ref, Scope_Identity worked perfectly.
Thanks for all your support, I know this may seem basic for some of you, but i am new to all this and trying to self teach, so as you can imagine.. it was a relief even this little issue is solved. Thanks guys


text:
Q: MySQL Theory: Single DB for multiple companies I have design question for MySQL. As a side project, I am attempting to create a cloud based safety management system. In the most basic terms, a company will subscribe to the service, which will manage company document record as blobs, corrective, employee information, audit results.
My initial design concept was to have a seperate DB for each company.
However, the question I have is if user access control is secure, would it be ok to have all the companies under one DB? What are the pitfalls of this? Are there any performance issues to consider? For identifying records, would it be a compound key of the company and referenceID number unique for each company? If so when generating a reference number for a record of a company, would it slow down as the record set increases?
In terms of constraints, I would expect up to 2000 companies and initially a maximum of 1000 records per company growing at 5% per year. I expect a maximum of 2 gig of blob storage per company growing at 10% per year. The system is to run one cloud server whether multiple db or one big one.
Any thoughts on this would be appreciated.

A: If there is not much inter-company interaction and overall frequent statistics and you don't plan to make application updates every week or so which would impact the DB structure, I'd go with separate DB (and DB user) for each company. It's more scalable, less prone to user access bugs and easier to make some operations such as remove a company.
On the other hand, 2 mil entries is not such a big deal and if you plan to develop the application further, keeping it in one DB could be better approach.

A: You have two question : performance and security.
If you use the same mysql user, security will not be different from one option to the other.
If you need performance, you can have the same results, running one or multiple databases (see for instance mysql partioning).
But there are others things that you should consider: like how it will be easy to have one database for your website... or like how it would be easy to have one database per user.
In fact, I give you an answer : considering the size of your data, don't make a choice on performance matters that are quite significantly equals for your needs, but on the choice that will make your life easy.


text:
Q: How to detect when a device has been connected/disconnected? I have tried the following:
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    Const WM_DEVICECHANGE As Integer = &H219
    Const DBT_DEVICEARRIVAL As Integer = &H8000

    If m.Msg = WM_DEVICECHANGE Then
      If m.LParam.ToInt32=DBT_DEVICEARRIVAL
        MessageBox.Show("Device arrival")
      End IF
    End If

    MyBase.WndProc(m)
End Sub

But m.LParam constantly returns a value of 7 and hence I am unable to detect when a device is added. I am looking to allow my program to detect when a piece of hardware has been added and if it's a particular device then perform some action (I am not interested in USB mass storage devices so please don't send me any examples regarding this).


text:
Q: Objective C - underscore needed without @synthesize? I get an error from this method, i have an imageView property linked to the header file from my storyboard, but it works only when i use the _imageView instead of imageView. The original code uses the imageView version without underscore, but it has a @synthesize imageView line under the @implementation. Do i need the underscore because of the lack of @synthesize?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *filteredDictionary = [filterNames objectAtIndex:indexPath.row];
imageView.image = [filteredDictionary objectForKey:@"filteredImage"];

A: Yes, Apple flip flopped on this.
If you add the default @synthesize::
@synthesize propertyName;

Then the instance variable will be called propertyName. If you omit the @synthesize and allow it to be inferred implicitly, the instance variable will be called _propertyName.
I guess one internal school of thought ended up winning over another.

A: In the current version of Xcode it does the @synthesize for you behind the scenes.   But in doing so forces you to use the underscore. It is similar to you using @synthesize imageView = _imageView. So if you don't synthesize use the underscore.

A: There are two possible variants to access instance variable:

*

*By using property. In this case you should use self.imageView

*By direct access to the variable. Code for access depends on using @synthesize or not.
If you don't use @synthesize then compiler automatically creates instance variable for you with underscore: _imageView.
If you use @synthesize imageView or @synthesize imageView = imageView then you should access instance variable by calling: imageView without underscore.


text:
Q: Hstore Query to find records matching with any array element using ruby on rails I've a hstore field in a database table. I want to write a Query to find records matching with any array element in any hash of hstore field using ruby on rails.
 Users Table
 --------------------------------------------------------------------------------
        ID    Name    sectors(hstore)

        1     Piotr   {"aviation"=>"0", "oil_and_gas" => "50", "transport" => "50"}
        2     reza    {"oil_and_gas" => "70", "energy" => "30"}
        3     pat     {"transport" => "40", "energy" => "60"}
        4     Kim     {"infrastructure" => "20", "healthcare" => "20", "industrial" => "60"}

considering above test data, I want to write a query on hstore field to get all records having any key like ['oil_and_gas', 'energy', 'transport']
I can match and find single sector records as its mentioned in https://nandovieira.com/using-postgresql-and-hstore-with-rails, but my requirement is to find any record where hstore hash is having any one key matching with any one element of array.
I'm using Rails 5.1.6.2, ruby 2.5.3

A: May be you are looking for the following operator:
hstore ? key # does hstore contain key?

Query may looks like so:
User.where("sectors ? 'oil_and_gas'")
    .or("sectors ? 'energy'")
    .or("sectors ? 'transport'")

According to postgresql docs

Check for a specific key in hstore column You can check for a specific
  key in an hstore column using the ? operator in the WHERE clause. For
  example, the following statement returns all rows with attr contains
  key publisher.

SELECT
  title,
  attr->'publisher' as publisher,
  attr
FROM
  books
WHERE
  attr ? 'publisher';


text:
Q: SmartPointer Template I'm trying to implement a SmartPointer template Class. Basically shared_ptr, when i'm right.
#include <iostream>

using namespace std;

template <typename T>
class SmartPointer
{
    T *_object;
    int *_counter;

    void removeOne() {
            *_counter -= 1;

        if (*_counter == 0) {
            delete _object;

        }
    }

public:
    SmartPointer(T *obj) {
        cout << "Konstruktor SmartPointer \n";
        _object = obj;
        *_counter++;
    }

    SmartPointer(SmartPointer& sp) {
        cout << "Kopier-Konstruktor SmartPointer \n";
        _object = sp._object;
        sp._counter += 1;
        _counter = sp._counter;
    }

    ~SmartPointer() {
        cout << "Destruktor SmartPointer \n";
        removeOne();
    }

    SmartPointer& operator=(SmartPointer& sp) {
        cout << "Zuweisungsoperator SmartPointer \n";

        if (this == &sp) {
            return *this;
        }
        if (*_counter > 0) {
            removeOne();
            sp._object = _object;
            sp._counter += 1;

            return *this;
        }
    }

    int getCounter() {
        return *_counter;
     }

    T* operator*() {
        return _object;
    }
};

template <typename T>
int fkt(SmartPointer<T> x) {
    cout << "fkt:value = " << *x << endl;
    cout << "fkt:count = " << x.getCounter() << endl;
    return x.getCounter();
}

int main() {

    SmartPointer<double> sp(new double(7.5));
    fkt(sp);

    return 0;
}

My Problem is that get an read access error for the getCounter function and that the * operator just returns the address.
How can i make it work?
I tried to use the & operator, but got i wrong.
Glad for every help!

A: Well this sticks out:
SmartPointer(T *obj) {
    cout << "Konstruktor SmartPointer \n";
    _object = obj;
    *_counter++;      // I don't see _counter being initialized.
                      // So here you are incrementing the content of some
                      // random memory location.
}

This looks wrong:
SmartPointer& operator=(SmartPointer& sp) {
    ....
    if (*_counter > 0) {
        removeOne();
        sp._object = _object;
        sp._counter += 1;

        // Hold on you have not updated this object.
        //
        // You have made the other smart pointer point at your object
        // (which oucld have been deleted) but keep the reference
        // count for the old object and incremented it!!!!
        return *this;
    }
}

I wrote something about smart pointer. I think you definately need to read.
Smart-Pointer - Unique Pointer
Smart-Pointer - Shared Pointer
Smart-Pointer - Constructors


text:
Q: How to paint fully transparent pixels/points in P2D mode? According to the Processing Reference, stroke(gray, alpha) allows to set the color and opacity of the stroke. With the default color mode, an alpha value of 255 denotes full opacity, while a value of 0 should correspond to complete transparency. While this works with the (default) JAVA2D renderer, I can't seem to paint fully transparent points in P2D mode.
This code clearly renders a pixel at the center of the canvas, even though the alpha value is set to 0 (fully transparent):
public class Transparency extends PApplet {

    @Override
    public void setup() {
        size(200, 200, P2D);
    }

    @Override
    public void draw() {
        stroke(0, 0);
        point(width / 2, height / 2);
    }

    public static void main(String[] args) {
        PApplet.main(new String[] { Transparency.class.getSimpleName() });
    }

}
What's wrong here?

A: This is a processing bug.
For now the only thing you can do is check the transparency yourself, and don't draw if it's zero


text:
Q: How can I test a OPC-UA server running on Raspberry Pi from a Windows computer? As a part of a job assignment where I am to implement and test an OPC server on a Raspberry Pi, I found and implemented a node.js server found at this Github repository (sample_server.js).
Now, being new to OPC in general, I tried downloading the MatrikonOPC Explorer to connect to the server, but it refused to find the server. At first I thought I was just not putting in the right things (endpoint URL goes somewhere?) into the connect prompt, but having read some more, (I think) I now understand that the explorer uses the regular OPC specification while my server is a OPC-UA server. Please correct me if I'm wrong here.
Anyway, I would like to see if this server actually works and can be accessed. What is a good way of testing this? If possible, I would like to test it over the network, from my Windows PC (they are both on the same network, and I have ensured they are pingable from eachother).

A: It turns out my suspicion was right - the problem was solved by adding a UA proxy that translated the OPC-UA to OPC Classic, allowing the explorer to detect and access the server.


text:
Q: Add content of form to 2 different tables cakephp I am building a form with Cakephp 2.x and I want to submit some of the data that is received when submitting it to table A and the other data to table B. Does anyone know how to achieve this in cakephp?

A: I believe you need to look at Cakephp's model documentation.  Looking at it now it seems that saveMany could help you with that. http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array

A: Yes. You should do what you want follow below way:
1. Create method receiveData() in FooController.
2. Create view file receive_data.ctp in folder foo.
$this->Foo->create();
$this->Foo->input('....', array(....));
// other input.
$this->Foo->end();

3. In FooController\receiveData(), When submit, you have data array $myDataArray like this: http://book.cakephp.org/2.0/en/tutorials-and-examples/blog/part-two.html#adding-posts
(Notice: It is Foo controller).
4. Before you save data from submitted data, you maybe need manipulation with submitted data array.
5.
You must call Model Bar inside FooController by:
$uses = array('Bar');

You will save to other table by:
$this->Bar->save($myDataArray);

(Notice: It is Bar Model).

A: Do Table A and Table B represent two different Models?
if yes saveAssociated might help you.
http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-hasone-hasmany-belongsto
If you want to save the same kind of model n times then saveMany is what you want to do.


text:
Q: Collating all the http response inside a common function using $q in Angularjs I am trying to use the $q service inside my controller. I have multiple environment which I need to hit and collect the data and consolidate the data and then put inside the scope. I have the below code.
     var results=[];
     for(var environment in  $rootScope.envs){
       $http.get(callService.getDomainUrl()+'/'+$rootScope.envs[environment]+ '/hosts.json').success(function(data){
              results.push(data)
          })
      }

      $q.all(results).then(function(){
          console.log(results);
      })

However, I am not sure if this is the right approach and also I need to map the result into an object of the below type:
results:{
  env1: { // result data for env1},
  env2: { // result data for env2},
  env3: { // result data for env3},
}

How to resolve the promise and consolidate the data in the above format.

A: You should check this example(look at log). I simulate $http.get request by means of setTimeout function.

A: As an addition to @SlavaUtesinov answer.
You should not to create new promises with $q.defer, just use $http.get return.
You'll get something like this:
  $q.all(Object.keys($rootScope.envs).map(request)).then(function(res){
    var results = {};
    for (var env in res) {
      results[env] = res[env].data;
    }
    console.log(results);
  }, function(err){
    console.error(err);
  });

  function request(env) {
    return $http.get(callService.getDomainUrl()+'/'+$rootScope.envs[env]+ '/hosts.json');
  }

Anyway, $q.all combine array/hash of promises into a single promise.
So, you should collect promises before call it.


text:
Q: I need to uninstall ubuntu I installed Ubuntu from a Ubuntu LiveCD image to dual boot. I did this on my GFs Windows 7 system and now she wants me to remove it so she can have her Win 7 back, she got tired of the boot options screen. Well, last night I booted to Win 7 and through Disk Management I deleted the contents of the Ubuntu partition and now when i boot the system the screen says GRUB recovery....not sure how to resolve this issue.

A: *

*reinstall ubuntu

*change the grub order so that if you do nothing Windos will start as first.
You can use an easy-to-use the GUI application called Grub Customizer to make your life a little bit easier. As the name suggests, you can do much more than just reordering GRUB menu entries with it.

You can install it by typing the following in the Terminal:
sudo add-apt-repository ppa:danielrichter2007/grub-customizer
sudo apt-get update
sudo apt-get install grub-customizer

see How do I change the GRUB boot order?. (note change the time out from 10 to 5, so Windows wille start after 5 sec. if you do nothing).

A: GRUB is the bootloader that Ubuntu installed on your hard disk, replacing the Windows 7 bootloader. It can't run without certain files from your Ubuntu partition, which you deleted. You'll need to reinstall the Windows 7 bootloader. To do this, you'll Windows 7 install media. Instructions are here: "How to Manually Repair Windows 7 Boot Loader Problems".


text:
Q: Scraping and non-API interaction I'm considering building an application to check stock levels of various stores. Some of the stores do not have an API that exposes this information.
I'm considering building a scraper for each website.
Do you think this will work? Can I build just one script to check all sites? For example, this is the markup from one site:
<div class = "stock status6">
  <b> In stock </b>
</div>

So my script would need to parse this to extract the stock information.
From what I understand, the problem with this technique is that if a site changes markup then my scraper could stop working.
How can I get the benefits of working with an API when one isn't available? Can Javascript help here?

A:
I'm considering building a scraper for each website.

This is your only option when you don't have access to an API.

Do you think this will work? Can I build just one script to check all sites?

Scraping is a very common approach to such problems. How you structure the script is a detail here, however each site will likely need to be parsed in a different way.

From what I understand, the problem with this technique is that if a site changes markup then my scraper could stop working.

Yes, you need to be ready to update your script when the page changes or get the data from another source if it's made unavailable.

How can I get the benefits of working with an API when one isn't available? Can Javascript help here?

Scraping can be a hard to maintain and is rarely as reliable as an API.
Client-side Javascript can't be used to scrape data because of the Same-origin policy. Javascript can be used to build a scraper if ran from the server.


text:
Q: How to decompress lzma2 (.xz) and zstd (.zst) files into a folder using Python 3? I have been working for a long time with .bz2 files. To unpack/decompress .bz2 files into a specific folder I have been using the following function:
destination_folder = 'unpacked/'
def decompress_bz2_to_folder(input_file):
    unpackedfile = bz2.BZ2File(input_file)
    data = unpackedfile.read()
    open(destination_folder, 'wb').write(data)

Recently I obtained a list of files with the .xz (not .tar.xz) and .zst extensions. My poor research skills told me that the former is lzma2 compression and the latter is Zstandard.
However, I couldn't find of an easy way to unpack the contents of these archives into a folder (like I do with the .bz2 files).
How can I:

*

*Unpack the contents of an .xz (lzma2) file into a folder using
Python 3?

*Unpack the contents of a .zst (Zstandard) file into a folder using Python 3?

Important Note: I'm unpacking very large files, so it would be great if the solution takes into consideration any potential Memory Errors.

A: The LZMA data can be decompressed using the lzma module, simply open the file with that module, then use shutil.copyfileobj() to efficiently copy the decompressed data to an output file without running into memory issues:
import lzma
import pathlib
import shutil

def decompress_lzma_to_folder(input_file):
    input_file = pathlib.Path(input_file)
    with lzma.open(input_file) as compressed:
        output_path = pathlib.Path(destination_dir) / input_file.stem
        with open(output_path, 'wb') as destination:
            shutil.copyfileobj(compressed, destination)

The Python standard library doesn't have any support for Zstandard compression yet, you can use either the zstandard (by IndyGreg from Mozilla and the Mercurial project) or zstd; the latter is perhaps too basic for your needs, while zstandard offers a streaming API specifically suited for reading files.
I'm using the zstandard library here to benefit from the copying API it implements, which lets you decompress and copy at the same time, similar to how shutil.copyfileobj() works:
import zstandard
import pathlib

def decompress_zstandard_to_folder(input_file):
    input_file = pathlib.Path(input_file)
    with open(input_file, 'rb') as compressed:
        decomp = zstandard.ZstdDecompressor()
        output_path = pathlib.Path(destination_dir) / input_file.stem
        with open(output_path, 'wb') as destination:
            decomp.copy_stream(compressed, destination)


text:
Q: How to restrict the date selected How to disable dates greater than today in a DateEdit control in an AX form?
Is possible with a date extended data type?

A: It is not possible to restrict date ranges on the extended data type level.
You will have to validate the entered date.
The method where to validate (preferred method first):

*

*validateField on table

*validateWrite on table (if comparing two entered dates)

*validate on form field

*validate on form control

Also see method sequence.


text:
Q: Error with using "dynamic" keyword in Silverlight app I get the following error:
"One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll"
I do have System.Core.dll, do have I to find Microsoft.CSharp somewhere? It wasn't part of the project and it isn't in the references list.

A: Should be at: C:\Program Files\Microsoft SDKs\Silverlight\v4.0\Libraries\Client\

A: You might want to check out this blog post.  There are some versioning conflicts with Silverlight 4 and VS 2010 RC 1 that might be causing this problem.


text:
Q: How can I get the similar attribute with xpath?
Demo

I am tried this xpath("./div/a/@src"),but it will give me all of that, but I don't want the @data-src, how should  I do???
the raw page is here:
the raw page

A: first of all I would recommend you to change the @src-data in data-src!
it will avoid you many problems when parsing XML files.
Then you can use directly the following XPATH to get your src attribute:
/div/a/@src

if you make it start with . it will only access the relative path from the current node.


text:
Q: How to iterate through this html table and get data from rows whose last col is not empty? I've been trying to get this data, but the array comes out empty:
function saveData() {
  var tableData = [];
  var table = document.getElementById("dtable");
  console.log(table)

  for (var i = 0; i < table.length; i++) {
    let tableCells = table.rows.item(i).cells;
    let cellLength = tableCells.length;

    for (let j = 0; j < cellLength; j++) {
      let cellVal = tableCells.item(j).innerHTML;
      tableData.push(cellVal)
    }
  }
  console.log(tableData)
  rows = JSON.stringify(tableData);
  google.script.run.formToSheets(rows);
}

Thanks for any help!

A: In your script, as one of several possible modifications, how about the following modification?
From:
var tableData = [];
var table = document.getElementById("dtable");
console.log(table)

for (var i = 0; i < table.length; i++) {
  let tableCells = table.rows.item(i).cells;
  let cellLength = tableCells.length;

  for (let j = 0; j < cellLength; j++) {
    let cellVal = tableCells.item(j).innerHTML;
    tableData.push(cellVal)
  }
}
console.log(tableData)

To:
var table = document.getElementById("dtable");
console.log(table)

var [, ...tr] = table.querySelectorAll("tr");
var tableData = [...tr].map(r => {
  var td = r.querySelectorAll("td");
  return [...td].map((c, j) => j != 3 ? c.innerHTML : c.querySelectorAll("select")[0].value);
});
console.log(tableData)

*

*In this modification, from a table, the table rows are retrieved. And, the table cells are retrieved from the table rows. In teh case of the dropdown list, the value is retrieved from the dropdown list.

Note:

*

*When this modification was not the direct solution to your issue, I think that when you provide your whole script, it will help to correctly understand your question.


text:
Q: Viewable area in an HTML email Potentially a topic for debate (or not) and I've searched and searched but not found anything. I code quite a lot of HTML emails (for my sins) and am surprised that this debate has only just come up but is there any way of determining where the "fold" would be in an HTML email?
I've thought about this quite a bit and of course it depends on lots of things such as:

*

*How the user has setup their viewing panes (if using Outlook)

*Screen resolution

*What email client they are using

So I may have really answered my own question but I hope this is open for debate. Is there any "best practice" guidelines? I.e. maximum width (I try and keep emails below 600 and below) and of course the things I listed above. I've looked at the usual sites, MailChimp, Campaign Monitor etc to no avail!
I would be interested to hear your thoughts/comments/suggestions.
Thanks
Kiz

A: For HTML documents, you'd need to look into JavaScript code to check window dimensions. Alas, most e-mail clients disallow JS in incoming mail, so this will be extremely unreliable.
Aside from this, I don't think there's a way to do this: I've seen so many configurations that I think any size is possible.


text:
Q: how do i sum duplicate array elements the program works fine, except that the "change" array has many duplicates, summing the duplicates is supposed to be easy, except it gives wrong sums!
ex: summing 3 twenties should give 60, instead it gives 80!
i noticed that the error only happens with the odd duplicates!
another thing that i cant figure out is why the "change" array is changing when i sum the duplicates? i copied the change array to a different array so if anything happens to the 2nd array it shouldnt affect "change" array!
the program works well until i get to the part where i need to sum the duplicates (sumDuplicates() function works fine on its own, but not with my code)

function checkCashRegister(price, cash, cid) {
  var change = [];
  let difference = cash - price;
  let level = 0;
  let currency = [
    ["PENNY", 0.01],
    ["NICKEL", 0.05],
    ["DIME", 0.1],
    ["QUARTER", 0.25],
    ["ONE", 1],
    ["FIVE", 5],
    ["TEN", 10],
    ["TWENTY", 20],
    ["ONE HUNDRED", 100]
  ]
  //sum all money in register
  let totalFunds = cid.reduce((r, [key, value]) => {
    return r + value
  }, 0)

  //function to match the difference to appropriate currency
  function findLevel(dif) {
    for (let i = currency.length - 1; i >= 0; i--) {
      //our change must be the highest availabe currency
      if (dif >= currency[i][1] && cid[i][1] != 0) {
        //console.log(currency[i])
        return i
      }
    }
  }
  //function to subtract
  function subtractor(dif, lvl) {
    if (cid[lvl][1] != 0) {
      dif = dif.toFixed(2)
      dif = dif - currency[lvl][1]
      cid[lvl][1] -= currency[lvl][1]
      change.push(currency[lvl])
      return dif
    }
  }
  //if no change needed
  if (difference == 0) {
    return {
      status: "CLOSED",
      change: []
    }
  }
  //if we dont have enough money to pay back
  if (totalFunds < difference) {
    return {
      status: "INSUFFICIENT_FUNDS",
      change: []
    }
  }
  //if we need to pay change AND we have enough money
  if (difference > 0 && totalFunds >= difference) {
    while (difference >= 0.01) {
      level = findLevel(difference)
      difference = subtractor(difference, level)
      //console.log(difference)
    }
  }

  //to sum duplicate elements in the "change" array, this is the problem!!!
  function sumDuplicates(arr1) {
    let arr = [...arr1]
    let sums = arr.reduce((sums, item) => {
      let found = sums.find(([key]) => key === item[0]);
      //console.log(found)
      if (found)
        found[1] += item[1];
      else
        sums.push(item);
      // console.log(item)
      return sums;
    }, []);
    return sums;
  }
  let sums = sumDuplicates(change)
  console.log(sums);
  return {
    status: "OPEN",
    change: sums
  };
}

checkCashRegister(3.26, 100, [
  ["PENNY", 1.01],
  ["NICKEL", 2.05],
  ["DIME", 3.1],
  ["QUARTER", 4.25],
  ["ONE", 90],
  ["FIVE", 55],
  ["TEN", 20],
  ["TWENTY", 60],
  ["ONE HUNDRED", 100]
]);

I expect [[twenties,60]] instead I get [[twenties,80]]

A: You need to be careful with pushing references into arrays, because they don't make copies. You do it in an couple places and in your sum function you end up modifying the original array which changes the values in your lookup table.
if (found)
     found[1] += item[1]; // <-- now modifying your original currency lookup!
else
     sums.push(item);     // <-- your pushing a ref to your original currency lookup!

A quick fix is to push a copy instead in your sum function:
 sums.push([...item])

A (probably better alternative) is to push a copy into the change array:
function subtractor(dif, lvl) {
  if (cid[lvl][1] != 0) {
      dif = dif.toFixed(2)
      dif = dif - currency[lvl][1]
      cid[lvl][1] -= currency[lvl][1]
      change.push([...currency[lvl]]) // < push a copy not the original ref
      return dif
   }
 }

function checkCashRegister(price, cash, cid) {
  var change = [];
  let difference = cash - price;
  let level = 0;
  let currency = [
    ["PENNY", 0.01],
    ["NICKEL", 0.05],
    ["DIME", 0.1],
    ["QUARTER", 0.25],
    ["ONE", 1],
    ["FIVE", 5],
    ["TEN", 10],
    ["TWENTY", 20],
    ["ONE HUNDRED", 100]
  ]
  //sum all money in register
  let totalFunds = cid.reduce((r, [key, value]) => {
    return r + value
  }, 0)

  //function to match the difference to appropriate currency
  function findLevel(dif) {
    for (let i = currency.length - 1; i >= 0; i--) {
      //our change must be the highest availabe currency
      if (dif >= currency[i][1] && cid[i][1] != 0) {
        //console.log(currency[i])
        return i
      }
    }
  }
  //function to subtract
  function subtractor(dif, lvl) {
    if (cid[lvl][1] != 0) {
      dif = dif.toFixed(2)
      dif = dif - currency[lvl][1]
      cid[lvl][1] -= currency[lvl][1]
      change.push([...currency[lvl]])  //< -- PUSH A COPY!
      return dif
    }
  }
  //if no change needed
  if (difference == 0) {
    return {
      status: "CLOSED",
      change: []
    }
  }
  //if we dont have enough money to pay back
  if (totalFunds < difference) {
    return {
      status: "INSUFFICIENT_FUNDS",
      change: []
    }
  }
  //if we need to pay change AND we have enough money
  if (difference > 0 && totalFunds >= difference) {
    while (difference >= 0.01) {
      level = findLevel(difference)
      difference = subtractor(difference, level)
      //console.log(difference)
    }
  }

  //to sum duplicate elements in the "change" array, this is the problem!!!
  function sumDuplicates(arr1) {
    let arr = [...arr1]
    let sums = arr.reduce((sums, item) => {
      let found = sums.find(([key]) => key === item[0]);
      //console.log(found)
      if (found)
        found[1] += item[1];
      else
        sums.push(item);
      // console.log(item)
      return sums;
    }, []);
    return sums;
  }
  let sums = sumDuplicates(change)
  console.log(sums);
  return {
    status: "OPEN",
    change: sums
  };
}

console.log(checkCashRegister(3.26, 100, [
  ["PENNY", 1.01],
  ["NICKEL", 2.05],
  ["DIME", 3.1],
  ["QUARTER", 4.25],
  ["ONE", 90],
  ["FIVE", 55],
  ["TEN", 20],
  ["TWENTY", 60],
  ["ONE HUNDRED", 100]
]));


text:
Q: How to show that $|A/R|=|A|/n$. Suppose $A$ is a finite set and $R$ is an equivalence relation on $A$. Suppose also there is some positive integer $n$ such that for every $x\in A |[x_R]|=n$. Prove that $A/R$ is finite and $|A/R|=|A|/n$.
Proof:
Suppose $X\subseteq A$,
since for all $x\in A$ we can always choose an $x\in A$ such that $X=[x_R]$ then $X\subseteq A/R$ and since $A$ is finite then $A/R$ is finite.
So i'm stuck on how to show $|A/R|=|A|/n$.

A: Your proof doesn't make any sense. There are more subsets of $A$ than equivalence classes in $R$.
HINT:

*

*Find a surjection from $A$ onto $A/R$. Recall that the image of a finite set is finite.

*Choose a system of representatives $x_1,\ldots,x_k$ from $A/R$, then $A=[x_1]_R\cup\ldots\cup[x_k]_R$. That is a disjoint union. Now use the assumption.

A: Hint $\ $ Recall that an equivalence relation on $A$ induces a partition of $A$ (into equivalence classes). By hypothesis, each class in the partition has the same size $n$. Hence $\,|A|\, =\, n\, |A/R|$.


text:
Q: MEF - notify when plugins are loaded / unloaded I have a simple asp mvc app which uses MEF, and there is a route which can be accessed by admins to refresh the directory catalog and compose parts, however one thing I am trying to find out how to do is notify some code when a plugin is loaded / unloaded.
The scenario is that when plugins are loaded they register the routes they need, however when they are unloaded I need them to unload their routes, as subsequent refreshes try to re-register the routes and it bombs.
Are there any events which I can hook into from the MEF objects?
The plugin container is something like:
[ImportMany(typeof(ISomePluginInterface))]
IEnumerable<ISomePluginInterface> Plugins {get; private set;}

Each ISomePluginInterface has something like:
public interface ISomePluginInterface
{
   public void PluginLoaded();
   public void PluginUnloaded();
}

A: This is similar in theory to this Stackoverflow question and this was my answer. In your case, you have a similar need, you want to fire an event when the plugin is started, and clean up when it is no longer needed.
Using the same concept, you can use the InterceptingCatalog to register routes, but I wouldn't make it an explicit part of the interface definition to do so, instead, you need to look at how your components fit together as a whole, e.g., if the operations for registering routes won't be used for all plugins, what is the purpose of them existing in the interface definition.  You could break out the route registration into a separate interface, the IRouteRegistrar, and use intercepting strategies to automatically call the appropriate registration method when the plugin is used for the first time, e.g., I could break out the interface into:
public interface IPlugin
{
  void SomeOperation();
}

public interface IRouteRegistrar : IDisposable
{
  void RegisterRoutes();
}

The latter interface does the work of registering routes, and we use the Dispose pattern to ensure that it is cleaned up after it is finished with. Therefore, A sample plugin could resemble:
[Export(typeof(IPlugin))]
public class MyPlugin : IPlugin, IRouteRegistrar
{
  public void SomeOperation() { }

  public void RegisterRoutes()
  {
    // Register routes here...
  }

  protected virtual Dispose(bool disposing)
  {
    if (disposing)
    {
      // Unregister routes here...
    }
  }

  void IDisposable.Dispose()
  {
    Dispose(true);
  }
}

I only export as an IPlugin, but I ensure my plugin also implements the IRouteRegistrar. The way we use that, is with a strategy:
public class RouteRegistrarStrategy : IExportedValueInteceptor
{
  public object Intercept(object value)
  {
    var registrar = value as IRouteRegistrar;
    if (registrar != null)
      registrar.RegisterRoutes();

    return value;
  }
}

Now, only if the plugin supports that interface will it register routes. This also enables you to apply the route registration interface to other plugins which could be used in a different way. You gain a bit more flexibility.  To use that strategy in code, you need to add the MefContrib project to your app, and do a little more wire up:
var catalog = new DirectoryCatalog(".\bin");
var config = new InterceptionConfiguration().AddInterceptor(new RouteRegistrarStrategy());

var interceptingCatalog = new InterceptingCatalog(catalog, configuration);
var container = new CompositionContainer(interceptingCatalog);


text:
Q: Grub gives messages about the boot sector being used by other software. What should I do? This only happens with one of my computers. It is an elderly laptop that has had a long and varied history with several operating systems, but in its retirement it is acting as a server for my home network using Ubuntu 12.04. It is a single-boot system, there are no other systems installed.
Every so often, whenever there is a grub upgrade, I notice a message like this:
Setting up grub-common (1.99-21ubuntu3.4) ...
Installing new version of config file /etc/grub.d/00_header ...
Setting up grub2-common (1.99-21ubuntu3.4) ...
Setting up grub-pc-bin (1.99-21ubuntu3.4) ...
Setting up grub-pc (1.99-21ubuntu3.4) ...
/usr/sbin/grub-setup: warn: Sector 32 is already in use by FlexNet; avoiding it.  This software may cause boot or other problems in future.  Please ask its authors not to store data in the boot track.
Installation finished. No error reported.

Should I be worried about this? What (if anything) should I do about it?

A: It's not a big deal since there is no error reported so just warning.
But, if you wish to get rid of this, you need to wipe sector 32. To do this you have many choices:
a. Wiping the whole hard disk;
b. writing zeros to Whole sectors in your MBR and reinstall your grub;
c. Writing zeros to sector 32 in your MBR (that's what we'll do here).
To do that follow the following steps:

*

*Backup your MBR:
sudo dd if=/dev/sda of=~/first_63_sectors bs=512 count=63

*zero your sector number 32:
sudo dd if=/dev/zero of=/dev/sda bs=512 count=1 seek=32

*chroot and reinstall grub:
Here "/media" should be whatever your chosen mount point is. Some step-by-step instructions use "/mnt" rather than "/media".
sudo mount /dev/sda* /media/sda*

sudo mount --bind /dev /media/sda*/dev

sudo mount --bind /proc /media/sda*/proc

sudo mount --bind /sys /media/sda*/sys

sudo chroot /media/sda*

PS: replace * by the appropriate number of your hdd
Now update your grub:
sudo update-grub

Note: You are not obliged to these steps, since its not an error that may affect your system.

A: I found a couple of useful links that explain what the message is about, and how to clean out the boot sectors on the disk.
This thread gives a very good explanation of the problem.
This thread gives a nice easy cookbook recipe for cleaning things up.
The cookbook worked for me, although I made a mess of the chrooting bit... (see below)
I am lucky in that my computer is single-boot and I have no plans EVER to re-install Windows. But it seems that if you have a dual-boot Windows system with software that uses FlexNet or similar software, you can expect to have regular problems. Also I think some Windows viruses may use this part of the disk. The first thread discussion offers a solution for Ubuntu users, to install an app called boot-repair on your live-CD USB booter.
I also found the boot-repair program referred to above invaluable when things go wrong. IMHO this is so useful it should be on the Live CD by default. See this link.

A: Less CLI typing with live DVD/USB
Here is a way of doing the same with less command line typing, using a live DVD or a live USB.

*

*Boot into a live session (= select trying out (X)Ubuntu).

*Use the lsblk command to show all drive partitions.
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0 298.1G  0 disk
├─sda1   8:1    0   512M  0 part /boot
├─sda2   8:2    0   4.5G  0 part [SWAP]
├─sda3   8:3    0    44G  0 part /
└─sda4   8:4    0 249.1G  0 part /home
sr0     11:0    1  1024M  0 rom

Make sure you target the affected drive (here sda).

*Remove FlexNet from the affected drive (here /dev/sda), using the sector number reported by GRUB (here sector 32):
$ sudo dd if=/dev/zero of=/dev/sda bs=512 count=1 seek=32

There is no need to backup this usually empty part of the extended boot record (EBR).

*Now, mount the partition of the affected drive which is normally used for booting (here /dev/sda1).
$ sudo mount /dev/sda1 /mnt

*Finally, reinstall GRUB on the affected drive:
$ sudo grub-install --boot-directory=/mnt /dev/sda

GRUB should now install without any warnings.

*You are now safe to reboot from the disinfected hard drive.


text:
Q: SubSonic How to Execute a SQL Statement? My site is using Subsonic 2.2 on my site.
I have 1 weird situation where I need to run some ad-hoc SQL statements.
public IList<string> GetDistincList(string TableName, string FieldName)
{
    string sqlToRun = string.Format("SELECT DISTINCT {0} FROM {1} ORDER BY {0}", FieldName, TableName);

    Query query = new Query(TableName);
    query.PleaseRunThis(sqlToRun);
    query.ExecuteReader();

}

Can anyone help me here? As it appears, I just want to return a generic list of strings.
Thanks!

A: Subsonic has a great method called ExecuteTypedList() so you can do somethink like this.
List<int> result = DB.Select(Table.Columns.Id)
  .Distinct()
  .From<Table>()
  .OrderBy(Table.Columns.Id)
  .ExecuteTypedList<int>();

or even with pocos:
public class UserResult
{
    public int Id {get;set;}
    public string Name {get;set;}
}

List<UserResult> users = DB.Select(
       User.Columns.UserId + " as Id",     // the as ... is only needed if your
       User.Columns.UserName + " as Name"  // column name differs from the
   ).From<User>()                          // property name of your class
    .ExecuteTypedList<UserResult>();

Unfortunately this method doesn't work for string since it requires
a) a valuetype
b) a class with a parameterless constructor since the method uses reflection to map the columns from the result to the properties of the class
However I wrote an extension method a while ago that works for string:
Use the Subsonic.Select() ExecuteTypedList Method with String
Look at my own answer in the link.
If you add the extensionmethod to your code you can do:
 List<String> result = DB.Select(User.Columns.UserName)
                         .From<User>()
                         .ExecuteTypedList();

A: Use the CodingHorror class.
Here's the SubSonic 3 way of doing it: http://www.subsonicproject.com/docs/CodingHorror
The SubSonic 2 way is similar:
Dim ch As SubSonic.CodingHorror
ch.Execute("delete from @tablename", table)