text:
Q: Terminating a Form while COM DataReceived Event keeps fireing. C# I'm currently having a problem, which seems to be related to closing a Form, while a scale, which is connected through a Serial Connection keeps sending data (about 3 packages per sek).
I handle new data over the DataReceived-Event (handling itself might be uninteresting for this issue, since I'm just matching data) Keep an eye on the COM_InUse variable and the allowFireDataReceived check.):
    private void COMScale_DataReceived(object sender, EventArgs e)
    {
        if (allowFireDataReceived)
        {
            //set atomar state
            COM_InUse = true;

            //new scale:
            if (Properties.Settings.Default.ScaleId == 1)
            {
                strLine = COMScale.ReadTo(((char)0x2).ToString());
                //new scale:
                Regex reg = new Regex(Constants.regexScale2);
                Match m = reg.Match(strLine);
                if (m.Success)
                {
                    strGewicht = m.Groups[1].Value + m.Groups[2];
                    double dblComWeight;
                    double.TryParse(strGewicht, out dblComWeight);
                    dblScaleActiveWeight = dblComWeight / 10000;
                    //add comma separator and remove zeros
                    strGewicht = strGewicht.Substring(0, 1) + strGewicht.Substring(1, 2).TrimStart('0') + strGewicht.Substring(3);
                    strGewicht = strGewicht.Insert(strGewicht.Length - 4, ",");

                    //write to textbox
                    ThreadSafeSetActiveScaleText(strGewicht);

                    COMScale.DiscardInBuffer();
                    //MessageBox.Show(dblScaleActiveWeight.ToString(), "dblScaleActiveWeight");
                }

            }
            //free atomar state
            COM_InUse = false;
        }
    }

The COM_InUse variable is a global bool and "tells" if there is a current process of handling data.
The allowFireDataReceived is also a global bool and if set to false will lead to no extra handling of the data which has been sended.
My problem now is the following:
It seems that Eventhandling is a separate Thread, which leads to a deadlock on klicking the Cancel-Button since the COM_InUse will never turn to false, even if the Event was handled (see end of COMScale_DataReceived, where COM_InUse is set to false).
While setting allowFireDataReceived = false works perfectly (no handling any more), as I said: the while loop will not terminate.
    private void bScaleCancel_Click(object sender, EventArgs e)
    {
        allowFireDataReceived = false;
        while (COM_InUse)
        {
            ;
        }
        if (!COM_InUse)
        {
            ret = 1;
            SaveClose();
        }
    }

When I comment out the while-block I have to click twice on the button, but it works without a crash. Since this very user unfriendly, I'm searching for an alternative way to safely close the window.
Info:
Simply closing (without checking if the COM-Data was processed) lead to a fatal crash.
So, maybe someone can explain to me what exactly causes this problem or can provide a solution to this. (Maybe one would be to trigger the Cancel-Clicking Event again, but that is very ugly)
Greetings!
I count on you :)
//edit:
Here is the current code of
    private void ThreadSafeSetActiveScaleText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.lScaleActive.InvokeRequired)
        {
            SafeActiveScaleTextCallback d = new SafeActiveScaleTextCallback(ThreadSafeSetActiveScaleText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.lScaleActive.Text = text;
        }
    }

A:    ThreadSafeSetActiveScaleText(strGewicht);

Yes, the DataReceived event runs on a threadpool thread.  You already knew that, you wouldn't have called it "ThreadSafe" otherwise.  What we can't see is what is inside this method.  But given the outcome, it is highly likely that you are using Control.Invoke().
Which is going to cause deadlock when you loop on COM_InUse in code that runs on the UI thread.  The Control.Invoke() method can only complete when the UI thread has executed the delegate target method.  But the UI thread can only do that when it is idle, pumping the message loop and waiting for Windows messages.  And invoke requests.  It cannot do this while it looping inside the Click event handler.  So Invoke() cannot complete.  Which leaves the COM_InUse variable for ever set to true.  Which leaves the Click event handler forever looping.  Deadlock city.
The exact same problem occurs when you call the SerialPort.Close() method, the port can only be closed when all events have been processed.
You will need to fix this by using Control.BeginInvoke() instead.  Make sure the data is still valid by the time the delegate target starts executing.  Pass it as an argument for example, copying if necessary.
Closing the form while the scale is unrelentingly sending data is in general a problem.  You'll get an exception when you invoke on a disposed form.  To fix this, you'll need to implement the FormClosing event handler and set e.Cancel to true.  And unsubscribe the DataReceived event and start a timer.  Make the Interval a couple of seconds.  When the timer Ticks, you can close the form again, now being sure that all data was drained and no more invokes can occur.
Also note that calling DiscardInBuffer() is only good to randomly lose data.


text: Q: Find $\max\{t_k: t_k \leq t\}$, where $t_{k+1}-t_{k}=g(t_k)$, with $g(t_k)\to\infty$, and $t\in\mathbb{N}_{+}$. Suppose we define a sequence $t_k$ generated by the difference relation $t_{k+1}-t_{k}=g(t_k)$, where $t_1$ is a positive integer, and $g(\cdot):\mathbb{N}_{+}\rightarrow\mathbb{N}_{+}$ is a monotonically increasing function of its argument. Given any $t\in\mathbb{N}_{+}$, I want an analytical expression for $f(t)=max\{t_k: t_k \leq t\}$. Is there a general technique that one can employ to solve this? For specific functional forms of $g(\cdot)$, (such as $g(t_k)=k$, or $g(t_k)=a^k$), this is fairly easy. But is there a unified way to find an analytical expression for the largest term in a sequence to the left of a given number, for a general growing function $g(\cdot)$?

redpajama_set_name: RedPajamaStackExchange


text:
Q: What happens on ARM when double to int64_t conversion overflows? With x86 you get the magic value 1 << 63 (MSB set, rest clear, i.e. the most-negative number, which Intel calls the "integer indefinite" value) when you convert a double to an int64_t with the x87 FPU, SSE or AVX, when the result of rounding to an integer isn't in range.  In addition to that, the invalid operation FP exception is raised.
Is there a similar behaviour with ARM? That would be nice because I need portability only to x86 and ARM.


text:
Q: Pandas won't recognize date while reading csv I'm working on a script which reads in a .csv file with pandas and fills in a specific form.
One column in the .csv file is a birthday-column.
While reading the .csv I parse it with 'parse_dates' to get a datetime object so i can format it for my needs:
df = pd.read_csv('readfile1.csv',sep=';', parse_dates=['birthday'])

While it works perfectly with readfile1.csv, it won't work with readfile2.csv. But these files look exactly the same.
The error i get makes me think that the automatic parsing to datetime through pandas is not working:
print(df.at[i,'birthday'].strftime("%d%m%Y"))
AttributeError: 'str' object has no attribute 'strftime'

In both cases the format of the birthday looks like:
'1965-05-16T12:00:00.000Z' #from readfile1.csv
'1934-04-06T11:00:00.000Z' #from readfile2.csv

I can't figure out what's wrong. I checked the encoding of the files and both are 'UTF-8'. Any ideas?
Thank you!
Greetings

A:
if you do not set keyword parse_dates, and convert the column after
reading the csv, with pd.to_datetime and keyword errors='coerce', what
result do you get? does the column have NaT values? – MrFuppes 32 mins
ago

MrFuppes comment on calling pd.to_datetime led to success. One faulty date in the column was the cause of the error. Also Lumber Jacks's hint was helpful to determine the datatypes!


text:
Q: What is a format for static documents like PDF but not divided into pages? PDF is for static documents, so a document is shown the same in different applications, even if it has an unusual layout. But PDF documents are divided into pages because the format is designed for documents to be printed.
I would like to have a document with static content but with no page breaks. Which document format can do that? I guess that it could be achieved with PDF with a single page as long as it needs to be, but I don't know that any software could do that, and it seems like abuse of PDF.
I create PDF documents in LATEX, and they almost never are printed, and the page layout is in the way when they are read on a screen. So I'm looking for how I could have documents where the layout is fixed because of hyphenation, mathematics and graphics, but more suitable for reading on screens.


text:
Q: Hadoop1.0.4 Example not running I recently installed Hadoop 1.0.4 with cygwin on windows 7 (64bit).
I have configured *-site.xml according to this site. I am able to do everything perfectly but my program hangs at this particular point:
$ bin/hadoop jar hadoop-examples-*.jar grep input output 'dfs[a-z.]+'
13/02/12 15:15:17 WARN util.NativeCodeLoader: Unable to load native-hadoop library for
your platform... using builtin-java classes where applicable
13/02/12 15:15:17 WARN snappy.LoadSnappy: Snappy native library not loaded
13/02/12 15:15:17 INFO mapred.FileInputFormat: Total input paths to process : 16
13/02/12 15:15:17 INFO mapred.JobClient: Running job: job_201302121513_0002
13/02/12 15:15:18 INFO mapred.JobClient:  map 0% reduce 0%

I have checked jobtracker and tasktracker also. One node is live and total submission is 1 but there is no active jobs!
There is nothing running there.. no mapping/no reducing!
I am so much confused right now, I am not able to do anything else. Please help wat to do next.
P.S: I am trying pseudo-single node setup only on one machine.
please guide me what to do?
even jps command is also not working?
I have set the path to C:\jdk_1.6.0_15.

A: For JPS to work give the path as  C:\jdk_1.6.0_15/bin
And about the Job not running, check the Job-tracker logs.
It might be that some configuration error is resulting in the aborting of the job.
You can also specifically try to set the maximum Number of mappers and reducers in the configuration. It might be set to zero
Hope it helps

A: 1)Check your hadoop condition using jps/ps, Are all components are working fine ?
2) check java version.it must be either be sun/oracle jdk > = 6, check java configuration(mainly JAVA_HOME) in hadoop-env.sh
3) check /hadoop-1.*/lib/native folder for native libraries, Does these supports for your platform?
If they are not there,then compile using this instruction link, because (native library are only tested with *nix platform i.e. Unix/Linux systems,  & then load libraries into your filesystem as mentioned
useful other links
even if this is not working,then try with hadoop-0.20,because thats working with windows-64 bit
for example you can try
hadoop-0.20.2/bin/hadoop jar /home/trendwise/apache/hadoop-0.20.2/hadoop-0.20.2-examples.jar pi 16 1000


text:
Q: field appears null or empty sting but I can not select it select *
from ss.mailer_data
where
id = 249122
and address_3 like'%%'

will not hit on address_3.  I've tried changing the last line to
and address_3 is null

and address_3 = ''
and address_3 = ' '
I tried using char_length, ascii functions and they return nothing for that filed value.  Anyone have any ideas?

A: could also be that id = 249122 is not true for that combination. What happens when you do
select *
from ss.mailer_data
where address_3 is null

or
select *
from ss.mailer_data
where address_3 = ''

A: NULL is a special case - It's undefined but if that were your problem, Is Null should've found it
Can I ask you what data IS actually stored in Address3?
If you just want all records where address3 is empty/null,
select *
from ss.mailer_data
where
RTRIM(COALESCE(address_3, '')) =''

NB: LIKE is computationally expensive so use it carefully. Also, like '%%' is identical to Like '%'
Are you sure you had the right Id?


text:
Q: C#, Ajax Redirection to another page through static method I have and ajax and C# method ...
I need to redirect to another page in the static web method..
But I am unable to do so.
methods for redirection to another page are follwoing
 if (tempUser == "0")
                {

                    HttpContext.Current.Response.Redirect("login.aspx");
                }
                else
                {
                    HttpContext.Current.Response.Redirect("list.aspx");
                }

AJAX
$('#Button1').click(function () {
                    var HTML = document.getElementById("data").innerHTML;
                //  alert(HTML);
                var Fname = document.getElementById("MyText").value;
                Senddata = { "HTML": HTML, "Fname": Fname };
                $.ajax({
                    type: "Post",
                    url: "/wwwroot/Default.aspx/save",
                    data: JSON.stringify(Senddata),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {

                    }
                });
            }
        });

C# STATIC WEB METHOD
[WebMethod(EnableSession = true)]
    public static void save(string HTML, string Fname)
    {

        HttpContext.Current.Session["GUID"] = Convert.ToString(Guid.NewGuid());

        try
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["MS"].ConnectionString;
            SqlCommand cmd = new SqlCommand();
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }

            string tempUser = Convert.ToString(HttpContext.Current.Session["UserID"]);

            if (string.IsNullOrEmpty(tempUser))
            {
                tempUser = "0";
            }

            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            cmd.CommandText = "insert into Forms(Name,HTML,UserID,GUID)values(@Name,@HTML,@UserID,@GUID)";
            cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 1024).Value = Fname;
            cmd.Parameters.Add("@HTML", SqlDbType.VarChar, 8000).Value = HTML.Trim();
            cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = tempUser;
            cmd.Parameters.Add("@GUID", SqlDbType.NVarChar, 50).Value = HttpContext.Current.Session["GUID"];

            cmd.ExecuteNonQuery();
            cmd.Dispose();
            con.Close();
            if (tempUser == "0")
            {

                HttpContext.Current.Response.Redirect("login.aspx");
            }
            else
            {
                HttpContext.Current.Response.Redirect("list.aspx");
            }

        }
        catch (Exception ex)
        {

            CommonBLL.WriteExceptionLog(ex, "Form Save Default.aspx");
            throw ex;
        }

    }
}

error thrown in catch block is
[System.Threading.ThreadAbortException] = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}

A: You have to redirect in the SUCCESS function of the ajax call:
$('#Button1').click(function () {
    var HTML = document.getElementById("data").innerHTML;
    //  alert(HTML);
    var Fname = document.getElementById("MyText").value;
    Senddata = { "HTML": HTML, "Fname": Fname };
    $.ajax({
        type: "Post",
            url: "/wwwroot/Default.aspx/save",
            data: JSON.stringify(Senddata),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
                window.location.href = "http://stackoverflow.com";
            }
        });
    }
});

HOPE this helpsenter code here

A: I think you cannot redirect from server side code during or after an ajax call.
At least you could return a url (Eg. Response.write("YourURlBuildOnC#")) to use for redirect on the success function


text:
Q: How to send an array struct into a function using pointers How to send an array of structs into a function as a parameter?
The employee variable is a struct.
My function:
void arraySort(struct Employee *employee[])
{
    bool flag = false;
    for (int i = 0; i < 5000; i++)
    {
        int empID1 = employee[i]->empID;
        int empID2 = employee[i + 1]->empID;
        flag = Employee().compareEmpID(empID1, empID2);
        if (flag == true)
        {
            Employee swap;
            swap = *employee[i + 1];
            *employee[i] = *employee[i + 1];
            *employee[i + 1] = swap;
        }
    }
}

Which calls this function:
bool Employee::compareEmpID(int empID1, int empID2)
{
    if (empID1 >= empID2)
        return true;
    return false;
}

I am trying to invoke a call to the arraySorts function from main by using the employee array struct as a pointer:
arraySort(*employee);

A: The function compareEmpID have to be a static method in struct employee and invoked by calling as Employee::compareEmpID.
There are some issues in for your arraySort method.

*

*You hard code the number 5000, that means your array need to have 5000 elements or more, otherwise you will get error about illegal memory access.

*The variable swap should be a pointer and declared outside of the for loop.

*Your swap logic is wrong.

I rewrite the program base on your code and tested it.
#include<iostream>

using namespace std;

struct Employee {
    int empID;
    static bool compareEmpID(int empID1, int empID2) {
        return empID1 > empID2;
    }
};

void arraySort(Employee *employees[], int size) {
    bool flag = false;
    Employee *swap;

    for(int i=0; i<size-1; i++) {
        int empID1 = employees[i]->empID;
        int empID2 = employees[i+1]->empID;
        flag = Employee::compareEmpID(empID1,empID2);
        if(flag) {
            swap = employees[i+1];
            employees[i+1] = employees[i];
            employees[i] = swap;
        }
    }
}

int main(int argc, char* args[]) {
    Employee** employee;
    employee = new Employee*[2];
    employee[0] = new Employee;
    employee[0]->empID = 5;
    employee[1] = new Employee;
    employee[1]->empID = 1;
    arraySort(employee, 2);
    cout << "emp[0]: " << employee[0]->empID << endl;
    cout << "emp[1]: " << employee[1]->empID << endl;
    delete employee[0];
    delete employee[1];
    delete[] employee;
    return 0;
}

Hope this helps you boots your learning progress.


text:
Q: Migrating 200GB of Postgres data from 9.0 to 9.6 We have a simple database with just 5 tables. But 1 table is huge, around 100GB of data by itself, and the indices together are nearly double that size. The server is an old CentOS 5 server with PG 9.0. I'm moving to a more modern setup with SSD hard disks, CentOS 7, and PG 9.6.
Question: what's the best way to migrate data in a simple way. pg_dump it on the old server, move it via rsync or something to the new server and pg_restore? I could do the pg_dump with -Fc option, so that we can pg_restore it easily (otherwise it's a text format and we have to use psql -f instead). But a trial run suggested that while the pg_dump is OK, the pg_restore on the destination server, which is much faster, goes on and on. We did a pg_restore --verbose, but there was no verbosity at all. Perhaps the server was stuck doing IO?
Our pg.conf settings for the pg_restore are as follows:
maintenance_work_mem = 1500MB
fsync = off
synchronous_commit = off
wal_level = minimal
full_page_writes = off
wal_buffers = 64MB
max_wal_senders = 0
wal_keep_segments = 0
archive_mode = off
autovacuum = off

What should we do to ensure that the pg_restore works? Right now both servers are offline, so I can do pretty much anything needed -- any settings can be changed.
Some more background info--
Old server: CentOS 5, SCSI RAID 1 disks,  4GB RAM (not much), PG 9.0
New server: CentOS 7 (latest), SSD disk,  16GB RAM,  PG 9.6
Thank you for any pointers on moving large tables in the best way possible. The usual PG documentation doesn't seem to be helping. We've tried both the text dump way and the -Fc way.

A: I strongly suggest you pg_upgrade:

*

*Install 9.0.23 on the new server. From source if necessary.

*Set up a streaming replica on the new server using pg_basebackup and a suitable recovery.conf. Enable WAL archiving and restore_command too, in case it becomes desynchronised for any reason.

*Also install 9.6 on the new server

*Do an upgrade test by stopping the replica and attempting a pg_upgrade to 9.6. Restart the replica, fix any issues and repeat until you succeed.

*When you're confident pg_upgrade will succeed, plan a cut-over time. Stop the 9.0 master and stop the replica. pg_upgrade the replica. Start the new 9.6 server.

See the pg_upgrade documentation for more info.
Remember: KEEP BACKUPS.

If you want simple, just pg_dumpall and then pipe to psql. But that'll be slow and it'll cause problems if your restore fails partway through then you try to resume, etc.
Better:
If you don't want to use replication, then use parallel-mode pg_dump and pg_restore with directory format input/output if you want to get things done quickly.

*

*Configure your 9.0 database to accept connections from the 9.6 host and make sure there's a high-performance network connection (gigabit or better).

*Using the 9.6 host, running the 9.6 versions of pg_dump and pg_dumpall:

*

*Dump your global objects with pg_dumpall --globals-only -f globals.sql

*Dump your database(s) with pg_dump -Fd -j4 -d dbname -f dbname.dumpdir or similar. -j is the number of parallel jobs. You'll need to dump each database separately if there are multiple ones.

*Cleanly initdb a new PostgreSQL 9.6 install, removing whatever attempts you have previously made (since I don't know what is/isn't there). Alternately, DROP any created roles, databases, etc, returning it to a clean state.

*Use psql to run the globals script: psql -v ON_ERROR_STOP=1 --single-transaction -f globals.sql -d postgres

*Use pg_restore to load the database dumps: pg_restore --create -d template1 -j4 template1 dbname.dump, repeating for each dumped DB. You can restore multiple DBs concurrently.

Yes, I know the handling of global objects sucks. And yes, it'd be nice if all this were wrapped up in a simple command. But it isn't. Designs and well thought out patches are welcome if you want to try to improve this. So far nobody's wanted to enough to do the work.


text:
Q: Encrypt file with .asc extension from Nautilus Is it possible to encrypt file with .asc extension directly from Nautilus?
I tried with Seahorse add on but its always encrypting with gpg extension.

A: You can use Nautilus-Actions Configuration Tool and create an action to do this.
Find the application in Software Centre
From Gnome Terminal type:
sudo apt-get install nautilus-actions
nautilus -q
nautilus-actions-config-tool

Then add you action like this:

path = /usr/bin/pgp
parameter = --recipient "" --armor --encrypt %f
Now when you right click on file, you'll see this

Actual Result (even if not GUI, because I don't have nautilus-actions-config-tool installed) :

A: You can create a file .asc with GPG on older versions. Now, you'll have to rename the extension. So, create file.pgp, and mv file.pgp file.asc to rename it.
That should be it.
In here, it's also said that you can do that :
1) First make sure you don't have a key already:
gpg --list-keys

2) If you didn't and need to create a key then run:
gpg --gen-key

It might hang for awhile while generating enough random entropy. Run ls -R / to speed things up.
3) And upload it to a public key server:
gpg --keyserver hkp://pgp.mit.edu --send-keys <keyid>

4) Now list the keys again to get the keyid:
gpg --list-keys

The keyid is the half after the / in:

pub   XXXX/XXXXXXXX 2011-12-05

5) Then generate your key:
gpg -ab <filename>


text:
Q: Network Diagramming software options? I've used The Dude to map my network, but I can only export the network map as a graphics file. I've also used Dia and Vision to manually diagram portions of my network.
Does anyone out there have a solution where I can do automatic network mapping using a tool like  "The Dude", then pull that file over to a manually editable format for cleaning up and/or enhancing in Visio or Dia?

A: There seems to be a load of suggestions here:
What tools can create a map of my network?

A: nmap can map networks. You can get the output in various ways, xml for example: http://nmap.org/book/man-output.html

A: Spiceworks is a pretty complete tool
http://www.spiceworks.com/


text:
Q: How can I list all the trips from one stop to another using GTFS? I am using the below table:
1   0051ML66220600132482    06:00:00        06:00:00        1538    100 0   1
2   0051ML66220600132482    06:00:00        06:00:00        1540    200 0   0
3   0051ML66220600132482    06:00:00        06:00:00        1541    300 0   0
4   0051ML66220600132482    06:01:00        06:01:00        1542    400 0   0
5   0051ML66220600132482    06:01:00        06:01:00        1543    500 0   0
6   0051ML66220600132482    06:02:00        06:02:00        1544    600 0   0
7   0051ML66220600132482    06:03:00        06:03:00        1546    700 0   0

Table structure us like below:
> ------------------------------------------------------------------
> --  TABLE stop_times
> ------------------------------------------------------------------
>
> CREATE TABLE stop_times ( id int(12),
>                           trip_id varchar(100),
>                           arrival_time varchar(8),
>                           arrival_time_seconds int(100),
>                           departure_time varchar(8),
>                           departure_time_seconds int(100),
>                           stop_id varchar(100),
>                           stop_sequence varchar(100),
>                           pickup_type varchar(2),
>                           drop_off_type varchar(2) );

I am attempting to get DISTINCT trip_id is it matches both the destination and arrival stop_id
I have tried the below SQL with no luck:
select DISTINCT trip_id from stop_times where stop_id=1538 AND stop_id =1540;

Where is should produce: 0051ML66220600132482
I have also tried a INNER JOIN SQL like below:
SELECT
       t.trip_id,
       start_s.stop_name as departure_stop,
       end_s.stop_name as arrival_stop
FROM
trips t
        INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id
        INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id
        INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id
        INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id
WHERE
   start_s.stop_id = 1538
  AND end_s.stop_id = 1540;

But it is sooo slow, and takes about 8-15 seconds for this simple query.
Explain Added:

What is the fastest/Best way to make this query?

A: So in other words, you are looking for a query that will identify all the trips that pass through a pair of stops, the origin (starting point) and destination (ending point).
Try this query:
SELECT destination.trip_id
    FROM stop_times AS origin
    INNER JOIN stop_times AS destination
        ON destination.trip_id = origin.trip_id
        AND destination.stop_id = 1540
    WHERE origin.stop_id = 1538
        AND origin.stop_sequence < destination.stop_sequence;

Or, for a prettier view (and to match the second query in your question):
SELECT destination.trip_id, origin_stop.name, destination_stop.name
    FROM stop_times AS origin
    INNER JOIN stop_times AS destination
        ON destination.trip_id = origin.trip_id
        AND destination.stop_id = 1540
    INNER JOIN stops AS origin_stop
        ON origin_stop.id = origin.stop_id
    INNER JOIN stops AS destination_stop
        ON destination_stop.id = destination.stop_id
    WHERE origin.stop_id = 1538
        AND origin.stop_sequence < destination.stop_sequence;

For good performance, create an index first on stop_id and trip_id:
CREATE INDEX stop_times_stop_id_trip_id_index ON stop_times(stop_id, trip_id);

(Note that EternalHour's query identifies all the trips that pass through either stop, not only trips that pass through one first and then the other.)

A: Seems like this is the query you need. I took out DISTINCT and replaced it with GROUP BY and also replaced the WHERE with IN. Your query indicates that stop_id should be of type INT, not varchar since you had not added quotes to it, the fiddle reflects that.
The IN basically does an OR instead of an AND. Nothing will be returned with AND since both stop_id's don't exist on the same row.
SELECT trip_id
FROM stop_times
WHERE stop_id IN(1538,1540)
GROUP BY trip_id

Here is a SQLFiddle


text:
Q: 'module' object has no attribute 'now' will trying to create a CSV Hello I'm having problems importing to csv, I get that error, the problem is that I have the same code running in other machine and it runs perfectly.
What am I missing do I need to install an other library for this?.
def exportar_a_csv_grl(request):
    #Fecha actual
    hoy = datetime.now().date()
    #Creado el:
    creado_hoy = hoy.strftime("%m/%d/%Y")
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment;filename="Reporte de Miembros ' +      creado_hoy + '.csv"'
response['Content-Type'] = 'text/csv; charset=utf-8'
response.write("\xEF\xBB\xBF")

writer = csv.writer(response)
miembros = Miembro.objects.all().extra(select={'miem_monto': "aplicacionmediexcel_miembro_monto.monto"},
                                       tables=["aplicacionmediexcel_miembro_monto"], where=[
        """aplicacionmediexcel_miembro.id=aplicacionmediexcel_miembro_monto.miembro_id"""])
#.extra(select = {'precio':'''select aplicacionmediexcel_miembro_monto.monto from aplicacionmediexcel_miembro_monto, aplicacionmediexcel_miembro where  aplicacionmediexcel_miembro.id = aplicacionmediexcel_miembro_monto.miembro_id'''})
miembros_colec = Miembro_colec.objects.all().extra(
    select={'miem_monto': "aplicacionmediexcel_colectivo_miembro_monto.monto"},
    tables=["aplicacionmediexcel_colectivo_miembro_monto"],
    where=["""aplicacionmediexcel_miembro_colec.id=aplicacionmediexcel_colectivo_miembro_monto.miembro_colec_id"""])
dependientes = Dependiente.objects.all()
dependientes_colec = Dependiente_colec.objects.all()
writer.writerow(['Creado el:             ' + creado_hoy + ' '])
writer.writerow([''])
#csv_data = (
#   ('ID Miembro', 'Apellido Paterno', 'Nombre', 'MI', 'Numero de Seguro Social', 'Tipo de contratacion','Tier', 'Tipo de dependiente', 'Fecha de nacimiento', 'Edad', 'Sexo', 'Estado Civil', 'Correo Electronico', 'Domicilio', 'Ciudad','Estado', 'Codigo Postal', 'Telefono', 'Idioma', 'Region de servicio', 'Medico', 'Fecha Efectiva', 'Tipo Plan', 'Grupo', 'Monto'),
#)
writer.writerow(
    ['ID Miembro', 'Apellido Paterno', 'Nombre', 'MI', 'Número de Seguro Social', 'Tipo de contratación',
     'Tier', 'Tipo de dependiente', 'Fecha de nacimiento', 'Edad', 'Sexo', 'Estado Civil', 'Correo Electrónico',
     'Domicilio', 'Ciudad',
     'Estado', 'Código Postal', 'Teléfono', 'Idioma', 'Región de servicio', 'Médico', 'Actividad', 'Fecha Efectiva',
     'Fecha Renovación', 'Tipo Plan', 'Grupo', 'Monto'])

#t = loader.get_template('my_template_name.txt')
#c = Context({
#   'miembros': miembros,
#})
#response.write(t.render(c))

A: i had the same problem when i used
from datetime import datetime,date,timedelta
import pytz
utc=pytz.UTC
today = datetime.now().replace(tzinfo=utc)

Solution for this which i will suggest is to import all the dependencies
from datetime import *
import pytz
utc=pytz.UTC
today = datetime.now().replace(tzinfo=utc)

A: When you do
import datetime

you have to use
>>> datetime.datetime.now()
datetime.datetime(2016, 12, 14, 1, 15, 58, 606802)

otherwise if you import like
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2016, 12, 14, 1, 17, 31, 772406)

But on some machine you could refer to wrong datetime module because of sys.path , instead of doing from datetime import datetime or import datetime make a habbit of using
from datetime import datetime as dt

A: You probably have
import datetime

change that to
from datetime import datetime

Demo:
>>> import datetime
>>> datetime.now()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'now'
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2013, 10, 7, 13, 57, 18, 456504)
>>>

Also, you will run into issues due to indentation. Please fix those.


text:
Q: Which resampling methods are suitable in the presence of dummy variables? I want to build a machine learning model using the caret package in R. Some of the features in my dataset are dummies taking the value 0 or 1. I would like to know which resampling methods can be used in the presence of dummy variables.
k-fold cross-validation does not seem to be an option as explained in this post. I could potentially use leave-one-out cross-validation; however, this seems to be too expensive when N is large (my dataset has 100000+ observations).
Are there any suitable resampling methods in the presence of dummies and large N?


text:
Q: Best way to deploy react app with gitlab-ci? I'm just getting started figuring out gitlab CI/CD.  I have my own gitlab instance, and a couple runners, 1 shared, 1 project specific, both using docker engine.
Currently my staging server is its own VM that it hosts with docker-compose.  I usually deploy to this server with a bare git repo, and just keep the build files in git.
But I wanted to switch to a CI/CD model, so I tried this as my .gitlab-ci.yml:
image: node

stages:
- build
- stage

build_frontend:
  stage: build
  script:
  - cd ./src/frontend
  - npm install && npm audit fix
  # CI=false set to ignore warnings as errors
  - CI=false npm run build
  artifacts:
    paths:
    - ./src/frontend/build
  tags:
  - projectname

But I'm sort of lost on how to actually deploy the build.  What would the best way be to get the files onto the staging server, which is just a VM.

A: You can take some clues from how GitLab itself uses its own CI, as described in "How to use GitLab CI for Vue.js":
They have a dedicated deploy step:
build site:
  image: node:6
  stage: build
  script:
    - npm install --progress=false
    - npm run build
  artifacts:
    expire_in: 1 week
    paths:
      - dist

unit test:
  image: node:6
  stage: test
  script:
    - npm install --progress=false
    - npm run unit

deploy:
  image: alpine
  stage: deploy
  script:
    - apk add --no-cache rsync openssh
    - mkdir -p ~/.ssh
    - echo "$SSH_PRIVATE_KEY" >> ~/.ssh/id_dsa
    - chmod 600 ~/.ssh/id_dsa
    - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
    - rsync -rav --delete dist/ user@server.com:/your/project/path/

So if you can package and scp your app, you can deploy it to your VM.


text:
Q: Angular Firebase retrieving collected data from anonymous users I have a survey system using Angular and Firebase which stores the results of users answers inside of an object specific to each user. This works well for storing data, but I've realized that it may be difficult to pull the data back out due to each object having a unique name.
I'd like to loop over each object and pull the all of the values together. So for all 50 entries find the total of comprehension.icons.damage[1]
How can I construct a loop that goes over objects with unique names like the objects below?
Here is my json structure
  "usersanonymous:-JgTyGt6An3WWyLvnnuu" : {
"comprehension" : {
  "-JgTzC0r_H58n7y8Al_-" : {
    "date" : 1422154060632,
    "icons" : [ {
      "damage" : [ null, "0", "3", "3" ],
      "ocular" : [ null, "2", "3", "1" ],
      "physical therapy" : [ null, "0", "4", "4" ],
      "skin" : [ null, "4", "0", "1" ]
    } ]
  }
}

 },
  "usersanonymous:-JgU-ryIpI-HR7D4VDkp" : {
    "comprehension" : {
      "-JgU0MwBwisNbjvRFGOT" : {
        "date" : 1422154629142,
        "icons" : [ {
          "damage" : [ null, "0", "3", "4" ],
          "ocular" : [ null, "1", "4", "3" ],
          "physical therapy" : [ null, "2", "4", "3" ],
          "skin" : [ null, "4", "1", "3" ]
        } ]
      }
    }
  }

A: Given your input data, I would create a function to extract just the data you're interested in.  I've written this in raw javascript - if you're using jQuery you may have fun using $.map rather than for (x in y).

var data = {
    "usersanonymous:-JgTyGt6An3WWyLvnnuu": {
        "comprehension": {
            "-JgTzC0r_H58n7y8Al_-": {
                "date": 1422154060632,
                "icons": [{
                    "damage": [null, "0", "3", "3"],
                    "ocular": [null, "2", "3", "1"],
                    "physical therapy": [null, "0", "4", "4"],
                    "skin": [null, "4", "0", "1"]
                }]
            }
        }
    },
    "usersanonymous:-JgU-ryIpI-HR7D4VDkp": {
        "comprehension": {
            "-JgU0MwBwisNbjvRFGOT": {
                "date": 1422154629142,
                "icons": [{
                    "damage": [null, "0", "3", "4"],
                    "ocular": [null, "1", "4", "3"],
                    "physical therapy": [null, "2", "4", "3"],
                    "skin": [null, "4", "1", "3"]
                }]
            }
        }
    }
};

function extractComprehension(rawData) {
    var result = [];

    for (var usersanonymous in rawData) {
        usersanonymous = rawData[usersanonymous];
        if (usersanonymous.comprehension) {
            for (var token in usersanonymous.comprehension) {
                token = usersanonymous.comprehension[token];
                if (token.icons) {
                    result.push(token.icons[0]);
                }
            }
        }
    }

    return result;
}

function sumOf(objectList, property, index) {
    var result = 0;

    for (var o in objectList) {
        var numbers = (objectList[o][property] || []);

        if (numbers.length >= index) {
            result += parseInt(numbers[index], 10);
        }
    }

    return result;
}

Using this mini api you can get the sum of the properties you're interested in:

// Get the data array.
var comprehension = extractComprehension(data);

// Sum some property.
console.log(sumOf(comprehension, 'damage', 3));


text:
Q: Передача json с jsp в controller с помощью ajax Добрый вечер. Пытаюсь передать json с вью в контроллер, но все время получаю 400 ошибку при методе  GET и 405 при методе POST. Подскажите пожалуйста как решить данную проблему.
скрипт

                <button id="but" type="button" onclick="searchText()"/>GO

Контроллер:
@RequestMapping(value="/admin/get",method=RequestMethod.POST)
public  @ResponseBody String  getSearchUserProfiles(@RequestBody Search search, HttpServletRequest request) {
    String pName = search.getlName();
    String lName = search.getlName();

    System.out.println(pName+lName);
    // your logic next
    return "Success";
}

Класс Search:
public class Search {
private String pName;
private String lName;

public void setpName(String pName) {
    this.pName = pName;
}

public void setlName(String lName) {
    this.lName = lName;
}

public String getpName() {
    return pName;
}

public String getlName() {
    return lName;
}

}

A:
            <button id="but" type="button" onclick="searchText()"/>GO

В итоге решил проблему


text:
Q: Maven, Spring-boot - The import javax.validation can not be resolved I have the same issue as in here (sorry am not yet able to comment) but the  suggested dependency in the accepted answer did not help me (i have it already).
What caused the problem for me :
I had the project working fine on a computer then i decided to move to another computer which is more convenient for coding. In the new computer, i installed the exact same environnement (Jdk1.8, Eclipse for JEE latest version) then i imported the project as existing maven project but i can not build it due to the mentionned error.
What can i do to import it ?
I tried many solutions like running maven clean, maven update, deleting old target folder...etc.

A: For those who may wonder : Clearing Maven'c cache solved the problem (deleting .m2\repository in current user directory for Windows) as @Andy Wilkinson said in comment.


text:
Q: getView() returning textview but textview is not updating I have a fragment A that extends B. Inside of B I init my views in the onCreateView like this
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    mView = super.onCreateView(inflater, container, savedInstanceState);
    mText1 = (TextView) mView.findViewById(R.id.textView1)
    mText2 = (TextView) mView.findViewById(R.id.textView2)
    retrun mView
}

but in my text update method if I try to get the mText1 like this (I know can you use the mText1 field from before but that is not the point)
public void updateView()
{
  mText1 = (TextView) getView().findViewById(R.id.textView1);
  mText1.setText("test");
  mText2.setText("test");
}

Notice that I use getView() to get mText1. On the screen strangely only the mText2 is set and mText1 is totally blank!!??
Edit: Additionally if I switch to another fragment then come back both mText1 and mText2 will not get updated

A: If you have more than one Fragment active that defines a textview as R.id.textView1, then you are probably finding a textview somewhere else in the view hierarchy.  You're not getting a NullPointerException when you call setText(), so findViewById() is returning something.
Since getView() returns the root view for the Activity, findViewById will find the first view with that id.
Try using mView.findViewById(...) to restrict the search to just the views within your fragment.

A: I had a static reference from a 3rd party library that was keeping the old fragment alive :(


text:
Q: NoMethodError: undefined method `send_data' for CloneDatabase:Class Rails não encontra método send_data
clone_database.rb

require 'zip'

class CloneDatabase < ApplicationController
  def self.make_clone
    zip_data = 'a'.to_json
    send_data zip_data, type: 'application/zip', filename: 'Topic.zip'
  end
end

test.rake
  namespace :my_namespace do
      desc 'Clone database'
        task clone_database: :environment do
          CloneDatabase.make_clone
        end
    end

A: Olá @Ruan,
Creio que não está encontrando porque o send_data é um método de instância não? e você está querendo usar ele dentro de um método de classe.
Tente remover o self de seu método make_clone e em sua task tente algo como:
clone_database = CloneDatabase.new
clone_database.response = ActionDispatch::Response.new
clone_database.make_clone


text:
Q: Computer won't boot up: "hal.dll is missing or corrupt" I'm hoping that someone will be able to help me out. I'm in desperate need to recover my data, and I really do not know where to begin.
This is my old PC (HP Pavilion M7480N media center, Windows XP).
I was restoring my computer to an earlier point, and in middle of the process I accidentally unplugged the computer. When I tried to turn it back on this is what it reads:
Windows could not start because the following file is missing or corrupt:
<Windows root>\system32\hal.dll.
Please re-install a copy of the above file.

Here's also a quick video which I uploaded to youtube.
What, if anything, can I do? What is my next step? I don't have a Windows XP CD. This computer didn't come with it.

A: That's basically the file that tells Windows how to load your hardware. If that's gone, you're gonna have to borrow someone else's XP CD.
Just so you know, I've seen that problem about 10 times, and only once was it JUST the one file that needs replacing. I would recommend an upgrade to a more modern OS, or else a re-installation of XP. Make sure you get the same version as before though

A: 80% of the time this is file system corruption, or possibly a bad sector on the hard drive.
Run a chkdsk from recovery console.
Boot from a XP install CD, choose R to load the recovery console.
At the command prompt type

chkdsk /r

Hit enter and let it run to completion, when it is done see if it will boot, if it does, defragment the hard drive.
Borrow a XP CD from a friend, relative or co-worker.
Or make your own bootable XP recovery console CD, download this package to an empty folder of choice, unzip the contents then read the "readme.htm" file, it will tell you to go to a page and download this package for XP Pro,   or this one for XP Home to the same folder and then rename the file, follow the rest of the instructions to make your own XP Recovery console boot CD.
Source of information
If you get it booting again, install the recovery console to the hard drive, then you won't have to look for the disc when trouble rears its ugly head. This will require the real XP install CD to get it done.

A: If you just want to recover your data, and have:

*

*A spare (blank) CD

*A spare removable storage medium (Flash drive, external HDD, heck even a floppy if you want to take it in lots of small steps)

*A computer capable of burning to that CD

*The ability to download approx. 700mb

I'd recommend you grab a Linux live CD image and use that. That will allow you to run a whole OS off the CD and copy your files. For data recovery, any newer distro (Linux variant) would work, but I've personally used Knoppix. It doesn't really matter, as long as the distro you choose has NTFS read support.
Alternatively, if you still want to use the computer and don't want to reinstall Windows, don't have an XP CD and do have the above requirements, and the other suggestions on this page don't work for you... if you have another XP installation of the same service pack installed on another computer, you can boot the computer using the Linux CD and transfer those missing/corrupt files via the removable media.
I'd recommend not trying to use your network, Linux and Windows don't tend to play nice.
No, I don't use Linux myself, but it is nice for recovery. There are also bootable Windows based solutions, such as Bart PE, but they can be more difficult to set up.

A: I know it's an old thread but I just found the answer.
On my system (Dell) there are several disks, one of them has remnants of the old Windows installation and another one has current working Win installation. I thought as long as my active Win HD is on the 0 SATA connector I'm good, however it's not the case.
In BIOS there is settings for boot order where you can set to boot from CD or HD or whatever,
but also, kind of hidden, there is setting for HD boot priority. That is from which HD it starts to boot. Those settings were messed up. as soon as I set my active WIN HD to be first- machine started booting up.
Hope this will help someone.


text:
Q: What's a good box to serve files on my local network, cross platform? I've installed CAT5e cable and gigabit switches in my house with the goal of having an "always-on" file server in the loft, accessible to both my macbook and my partner's Windows box. I'd like to find a solution which:

*

*uses minimal power.

*allows me to access as much disk bandwidth as possible.

*provides glitch-free file access to both MacOS and Windows.

*is as cheap as possible, while remaining reliable.

Optional, but desirable extras: software or hardware RAID; open source
solutions.
A SheevaPlug with eSATA seems one possibility, but I'm sure there are any number of other good options.

A: Take a look at Drobo
It supports -

*

*Gigabit Ethernet network

*Windows, Mac, or UNIX/Linux computer

*dual-drive redundancy

*Simple install and setup

A: For software, you can try: http://sourceforge.net/projects/freenas/
More info: http://en.wikipedia.org/wiki/FreeNAS
Do you already have the hardware, or are you looking for hardware as well?

A: I'm happy with my ReadyNAS
Drobo's another good solution.
If you want reliability, I recommend a RAID-based solution with swappable drives like these.

A: We just got the HP StorageWorks X510, there is a consumer edition of this too called hp media smart. It supports both Mac and PC and even Time Machine.
And we actually use it as VM Ware Server too, so it's not just a dump NAS.
LaCie has something similar, but sexier in terms of look, but just with an Atom. So running a VM Ware server is not an option on that one (LaCie 5big Storage Server).
It's also more expensive :-)


text:
Q: MS Access SQL Reorder Dates for Trailing 12 Months I'm trying to format a query correctly to make Access 365 charting work properly (I know, I know) for a trailing 12 month graph. I.E. if I run this query in June, I want June to be the last data point (Month 12) and proceed backwards in order to the previous July (Month 1). I'm getting stuck on how to build this logic into the query as the order is constant but the relative number changes. I have:
FROM (
SELECT "Jan" as Mo,Month(DateAdd("m",1,Date())) AS MoN, SUM(IIF(MonthNumOpen = 1,1,0)) AS             SalesOpened,SUM(IIF(MonthNumClose = 1,1,0)) AS Sales, Month(Date()) as Today1, Sales - SalesOpened as SalesDelta FROM Trailing12MonthData_Trial1
UNION SELECT "Feb", Month(DateAdd("m",2,Date())), SUM(IIF(MonthNumOpen = 2,1,0)) AS SalesOpened,SUM(IIF(MonthNumClose = 2,1,0)) AS Sales, Month(Date()) as Today1, Sales - SalesOpened  as SalesDelta FROM Trailing12MonthData_Trial1
UNION SELECT "Mar", Month(DateAdd("m",3,Date())), SUM(IIF(MonthNumOpen = 3,1,0)) AS SalesOpened,SUM(IIF(MonthNumClose = 3,1,0)) AS Sales, Month(Date()) as Today1, Sales - SalesOpened  as SalesDelta FROM Trailing12MonthData_Trial1
UNION SELECT "Apr", Month(DateAdd("m",4,Date())), SUM(IIF(MonthNumOpen = 4,1,0)) AS SalesOpened,SUM(IIF(MonthNumClose = 4,1,0)) AS Sales, Month(Date()) as Today1, Sales - SalesOpened  as SalesDelta FROM Trailing12MonthData_Trial1
UNION SELECT "May", Month(DateAdd("m",5,Date())), SUM(IIF(MonthNumOpen = 5,1,0)) AS SalesOpened,SUM(IIF(MonthNumClose = 5,1,0)) AS Sales, Month(Date()) as Today1, Sales - SalesOpened  as SalesDelta FROM Trailing12MonthData_Trial1
UNION SELECT "Jun", Month(DateAdd("m",6,Date())), SUM(IIF(MonthNumOpen = 6,1,0)) AS SalesOpened,SUM(IIF(MonthNumClose = 6,1,0)) AS Sales, Month(Date()) as Today1, Sales - SalesOpened  as SalesDelta FROM Trailing12MonthData_Trial1
UNION SELECT "Jul", Month(DateAdd("m",7,Date())), SUM(IIF(MonthNumOpen = 7,1,0)) AS SalesOpened,SUM(IIF(MonthNumClose = 7,1,0)) AS Sales, Month(Date()) as Today1, Sales - SalesOpened  as SalesDelta FROM Trailing12MonthData_Trial1
UNION SELECT "Aug", Month(DateAdd("m",8,Date())), SUM(IIF(MonthNumOpen = 8,1,0)) AS SalesOpened,SUM(IIF(MonthNumClose = 8,1,0)) AS Sales, Month(Date()) as Today1, Sales - SalesOpened  as SalesDelta FROM Trailing12MonthData_Trial1
UNION SELECT "Sep", Month(DateAdd("m",9,Date())), SUM(IIF(MonthNumOpen = 9,1,0)) AS SalesOpened,SUM(IIF(MonthNumClose = 9,1,0)) AS Sales, Month(Date()) as Today1, Sales - SalesOpened  as SalesDelta FROM Trailing12MonthData_Trial1
UNION SELECT "Oct", Month(DateAdd("m",10,Date())), SUM(IIF(MonthNumOpen = 10,1,0)) AS SalesOpened,SUM(IIF(MonthNumClose = 10,1,0)) AS Sales, Month(Date()) as Today1, Sales - SalesOpened  as SalesDelta FROM Trailing12MonthData_Trial1
UNION SELECT "Nov", Month(DateAdd("m",11,Date())), SUM(IIF(MonthNumOpen = 11,1,0)) AS SalesOpened,SUM(IIF(MonthNumClose = 11,1,0)) AS Sales, Month(Date()) as Today1, Sales - SalesOpened  as SalesDelta FROM Trailing12MonthData_Trial1
UNION SELECT "Dec", Month(DateAdd("m",12,Date())), SUM(IIF(MonthNumOpen = 12,1,0)) AS SalesOpened,SUM(IIF(MonthNumClose = 12,1,0)) AS Sales, Month(Date()) as Today1, Sales - SalesOpened  as SalesDelta FROM Trailing12MonthData_Trial1
ORDER BY MoN
)  AS subquery
ORDER BY IIF(Month(Date()) = 11, Mo ="Jan", IIF(Month(Date()) = 10, Mo="Feb",IIF(Month(Date()) = 9, Mo="Mar",IIF(Month(Date()) = 8, Mo="Apr",IIF(Month(Date()) = 7, Mo="May",IIF(Month(Date()) = 6, Mo="Jun",IIF(Month(Date()) = 5, Mo="Jul",IIF(Month(Date()) = 4, Mo="Aug",IIF(Month(Date()) = 3, Mo="Sep",IIF(Month(Date()) = 2, Mo="Oct",IIF(Month(Date()) = 1, Mo="Nov", Mo="Dec"))))))))))), MoN;

Help is much appreciated.

A: Use modulus to calculate the period for each month. Here June is the current month:
For M = 1 to 12 : ? "Period: " & M, "Month: " & (Month(Date) - 1 + M) Mod 12 + 1 : Next
Period: 1     Month: 7
Period: 2     Month: 8
Period: 3     Month: 9
Period: 4     Month: 10
Period: 5     Month: 11
Period: 6     Month: 12
Period: 7     Month: 1
Period: 8     Month: 2
Period: 9     Month: 3
Period: 10    Month: 4
Period: 11    Month: 5
Period: 12    Month: 6

Then you probably can reduce this query dramatically.


text:
Q: Сумма двух float-чисел вычисляется не верно Объясните, пожалуйста, что со мной не так, или почему результат вычислений столь странный? Здесь же даже нечего отрубать(округлять), если бы мы допустим хотели показать (1/3).
На сколько понимаю: 11.4+5.7 = 11.0+5.0 + 1.1 = 17.1
Так в школе ещё объясняли...
public class Test{
    public static void main(String[] args) {
        System.out.println(11.4f+5.7f);
    }
}

Output:
17.099998

A:
Подобные ошибки связанны с внутренним двоичным (binary) представлением
  чисел. Подобно тому, как в десятичной системе нельзя точно представить
  результат деления 1/3, так и в двоичной системе невозможно точно
  представить 1/10.

Подробнее здесь
В двух словах, числа с плавающей точкой не подходят для арифметических вычислений. Если вы хотите иметь возможность выполнять арифметические действия над дробными числами, используйте класс BigDecimal


text:
Q: Hibernate unidirectional ManyToMany delete only from association table I am fairly new to java and hibernate (with annotation) and not sure if the below is correct.  I have a unidirectional many to many relationship between two tables as in the example below:
class Group {
@ManyToMany(cascade = {CascadeType.ALL})
            @JoinTable(
                    name = "Group_Students",
                    joinColumns = @JoinColumn(name = "group_id", referencedColumnName="group_id),
                    inverseJoinColumns = @JoinColumn(name = "student_id", referencedColumnName="student_id)
            )
         private Set<Student> students;
}

The following works ok:
-   insert in table Student if I save an instance of Group -> this works ok
-   update in table Student if a student instance of the Group is modified -> this works ok
I want to delete the record from the Group and association table but keep the ones in the Student table. Currently before deleting the Group record, I set the instance's student set to null (students = null). This seems to work perfectly, but I am not sure if this is the correct way to do it or if it is a bad practice – it seems that this solution is only a workaround and might cause issues in future. Do you have any other suggestions on how to do this?

A: It is a bad practice. You should almost never cascade ALL or REMOVE in a many-to-many association, because after deleting a Group, you probably don't want the deletion to be cascaded to all the students belonging to that group.
The correct approach is to specify only the desired cascade types (without the two mentioned above). Then, since the association is unidirectional, you can simply remove the Group (without any changes to the students collection).


text:
Q: How can I programatically add shipping address to checkout form I'm making a custom shipping module. When a user selects the shipping method, I want it to populate the shipping address fields with some custom address data.
I have overridden the select shipping method handler like so:
var config = {
    map: {
        '*': {
            'Magento_Checkout/js/action/select-shipping-method':
'Vendor_Module/js/action/select-shipping-method'
        }
    }
};

I want to programatically set the form field values on the checkout page. Something like:
define([
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/action/select-shipping-address'
], function (quote, shipping) {
    'use strict';

    return function (shippingMethod) {
        shipping.street("99 Road Street");
        shipping.city("New York");
    };
});

Is there a way to do this without just dumping in the values using jquery?

A: Add parameters into object in this file
"new-customer-address.js" is setting up the shipping address. find file in Magento_Checkout/js/model/ code library.
just add the values into these parameters

email: shipping_address.email,
            countryId: countryId,
            regionId: regionId || shipping_address.regionId,
            regionCode: shipping_address.region ? shipping_address.region['region_code'] : null,
            region: shipping_address.region ? shipping_address.region.region : null,
            customerId: shipping_address['customer_id'] || shipping_address.customerId,
            street: shipping_address.street ? _.compact(shipping_address.street) : shipping_address.street,
            company: shipping_address.company,
            telephone: shipping_address.telephone,
            fax: shipping_address.fax,
            postcode: shipping_address.postcode ? shipping_address.postcode : DefaultPostCodeResolver.resolve(),
            city: shipping_address.city,
            firstname: shipping_address.firstname,
            lastname: shipping_address.lastname,
            middlename: shipping_address.middlename,
            prefix: shipping_address.prefix,
            suffix: shipping_address.suffix,
            vatId: shipping_address['vat_id'],
            saveInAddressBook: shipping_address['save_in_address_book'],
            customAttributes: shipping_address['custom_attributes']


text:
Q: Can the closest jquery function find child tags inside other tags I have this HTML code

 My Txt

link1  link2

Now i want that if someone click on a.linkclass then i alert the text inside p tag
I tried this but it didn't work
$(this).closest('p').text();

A: Try this
$(this).closest('div').prev('div').find('p').text();

Here p is not the ancestor of the anchor tag.. Is is nested inside a div.. So you cannot use the .closest() on the p tag directly..
The closest selector only traverses thru the ancestors of the element...
EDIT
You can also use the closest on the td directly.
$(this).closest('td').find('p').text();


text:
Q: http 1.0 keep-alive server and curl I'm busy with my own http server implementation on an embedded platform. Technically the server is HTTP 1.0 compliant, and therefore it expects the the client to send the header "Connection: Keep-Alive" to keep the connection open.
The implementation looks like this. I removed the code that parses the HTTP header and performs the request, to keep the post as short as possible:
int Service_Request(int conn) {

    struct ReqInfo reqinfo;
    volatile int resource = 0;
    int retval = 0;
    Req_Result req_result = GOT_REQ;

    InitReqInfo(&reqinfo);

    /* while we still have HTTP requests to process */
    while (req_result == GOT_REQ)
    {

        /*  Get HTTP request, there are 3 different return values:
         * GOT_REQ: we got a valid HTTP request
         * TIMEOUT_REQ we timed out waiting for a request
         * ERROR_REQ there was some error receiving from the socket
         * usually because the connection was closed by the peer*/
        req_result = Get_Request(conn, &reqinfo);
        if ( req_result == TIMEOUT_REQ)
        {
            /* timed out waiting for the client, exit */
            retval = 0;
            break;
        }
        else if (req_result == ERROR_REQ)
        {
            /* some error, exit */
            retval = -1;
            break;
        }
        /* Process the request GET, PUT and POST is supported*/
        if (reqinfo.method == GET)
        {
            /* code to handle GET*/
        }
        /* PUT and POST are handled in the same way */
        else if ((reqinfo.method == PUT) || (reqinfo.method == POST) )
        {
            /* Code to handle PUT and POST*/
        }
        else
        {
            /* not supported, code should never get here */
            reqinfo.status = 501;
            Return_Error_Msg(conn, &reqinfo);
        }
        /*Diag_Msg("Client Request: \r\n");
        Diag_Msg(reqinfo.clientRequest);*/

        /*
         * the reqinfo.keep_alive flag will be set to 1 if the
         * "Connection: Keep-Alive" header was sent by the client
         */
        if(reqinfo.keep_alive == 0)
        {
            break;
        }

        reqinfo.keep_alive_max--;
        if(reqinfo.keep_alive_max <= 0 )
        {
            /*
             * the connection has been reused for the maxmum amount of times, stop
             */
            break;
        }
        /*
         * If we get here, we will clear the memory used for the client request
         * and go to the beginning of the while loop to receive another request
         */
        Writeline(conn,"\r\n",2);
        FreeReqInfo(&reqinfo);

    }
    FreeReqInfo(&reqinfo);
    return (retval);
}

The Get_Request function looks like this:
Req_Result Get_Request(int conn, struct ReqInfo * reqinfo) {

    char   buffer[MAX_REQ_LINE] = {0};
    int    rval;
    fd_set fds;
    struct timeval tv;

    /*  Set timeout to 5 seconds if this is the first request since the client connected, wait 5 seconds
     * Otherwise, wait 5ms */
    if(reqinfo->first_request == 1)
    {
        tv.tv_sec  = 5;
        tv.tv_usec = 0;
        reqinfo->first_request = 0;
    }
    else
    {
        tv.tv_sec  = reqinfo->keep_alive_timeout;
        tv.tv_usec = 0;
    }

    /*  Loop through request headers. If we have a simple request,
    then we will loop only once. Otherwise, we will loop until
    we receive a blank line which signifies the end of the headers,
    or until select() times out, whichever is sooner.                */
    do {

    /*  Reset file descriptor set  */

    FD_ZERO(&fds);
    FD_SET (conn, &fds);

    /*  Wait until the timeout to see if input is ready  */

    rval = select(conn + 1, &fds, NULL, NULL, &tv);

    /*  Take appropriate action based on return from select()  */

    if ( rval < 0 )
    {
        Diag_Msg("Error calling select() in get_request()");
        return (ERROR_REQ);
    }
    else if ( rval == 0 ) {

        /*  input not ready after timeout  */

        return (TIMEOUT_REQ);

    }
    else {

        /*  We have an input line waiting, so retrieve it  */
        memset(buffer,0,MAX_REQ_LINE - 1);
        if(Readline(conn, buffer, MAX_REQ_LINE - 1) == -1)
        {
            return (ERROR_REQ);
        }
        if(reqinfo->clientRequest == NULL)
        {
            reqinfo->clientRequest = calloc(MAX_REQ_LINE - 1, sizeof(char));
            strncpy(reqinfo->clientRequest,buffer,MAX_REQ_LINE - 1);
        }
        else
        {
            strncat(reqinfo->clientRequest,buffer,MAX_REQ_LINE - 1);
        }
        Trim(buffer);

        if ( buffer[0] == '\0' )
        break;

        if ( Parse_HTTP_Header(buffer, reqinfo) )
        break;
    }
    } while ( reqinfo->type != SIMPLE );

    return (GOT_REQ);
}

To describe the workings of this server in English: The server receives the first request. It parses the headers, if it finds the "Connection: Keep-Alive" header, it sets a flag. The server proceeds to process this request. WHen it is done it checks the keep-alive flag. If it is cleared, the server closes the connection. If set the server performs a clean-up operation and the proceeds to wait for another request over the same connection. And so on.
I tested this with curl:
C:\curl>curl -v -H "Connection: Keep-Alive" --data-binary @vid1.bin 10.84.67.129/s1p0:1/vid[1-2].bin

[1/2]: 10.84.67.129/s1p0:1/vid1.bin --> <stdout>
--_curl_--10.84.67.129/s1p0:1/vid1.bin
* About to connect() to 10.84.67.129 port 80 (#0)
*   Trying 10.84.67.129...
* connected
* Connected to 10.84.67.129 (10.84.67.129) port 80 (#0)
> POST /s1p0:1/vid1.bin HTTP/1.1
> User-Agent: curl/7.28.1
> Host: 10.84.67.129
> Accept: */*
> Connection: Keep-Alive
> Content-Length: 51200
> Content-Type: application/x-www-form-urlencoded
> Expect: 100-continue
>
* HTTP 1.0, assume close after body
< HTTP/1.0 100 Continue
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Server: DTSVU v0.1
< Content-Type: text/html
* HTTP/1.0 connection set to keep alive!
< Connection: Keep-Alive
< Keep-Alive: timeout=5, max=10
<
* Connection #0 to host 10.84.67.129 left intact

[2/2]: 10.84.67.129/s1p0:1/vid2.bin --> <stdout>
--_curl_--10.84.67.129/s1p0:1/vid2.bin
* Connection #0 seems to be dead!
* Closing connection #0
* About to connect() to 10.84.67.129 port 80 (#0)
*   Trying 10.84.67.129...
* connected
* Connected to 10.84.67.129 (10.84.67.129) port 80 (#0)
> POST /s1p0:1/vid2.bin HTTP/1.1
> User-Agent: curl/7.28.1
> Host: 10.84.67.129
> Accept: */*
> Connection: Keep-Alive
> Content-Length: 51200
> Content-Type: application/x-www-form-urlencoded
> Expect: 100-continue
>
* HTTP 1.0, assume close after body
< HTTP/1.0 100 Continue
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Server: DTSVU v0.1
< Content-Type: text/html
* HTTP/1.0 connection set to keep alive!
< Connection: Keep-Alive
< Keep-Alive: timeout=5, max=10
<
* Connection #0 to host 10.84.67.129 left intact
* Closing connection #0

As you can see, curl says: Connection #0 seems to be dead! afterthefirstrequest is completed. It then proceeds to close the connection and opens a new one. I'm sure I implemented the HTTP 1.0 keep-alive functionality correctly. SO my question is: what does curl expect over the connection after the first request is completed? Why does it decide the connection is dead?
PS the above code was adapted from http://www.paulgriffiths.net/program/c/webserv.php

A: I solved it. If the server replies with HTTP/1.1 and "Content-Length: 0", curl reuses the connection. My server reply lookes like this
< HTTP/1.1 100 Continue
< HTTP/1.1 200 OK
< Server: DTSVU v0.1
< Content-Type: text/html
< Connection: Keep-Alive
< Keep-Alive: timeout=1, max=95
< Content-Length: 0

after the 5th reuse of the connection.


text:
Q: Is their any way to identify user updating app and user installing app for the first time in iOS? I'm giving an update for my existing iOS App and in this update I'm locking few existing functionalities and on In App purchase these functionalities will be unlocked.
But for existing users even if they update it should not lock the functionalities only for new users it has to happen. How can I handle this?

A: You can do what is called "Receipt Validation."  There is a programming guide here
Basically, you can get the purchase data of the app, and it will include the original version that was purchased.  That way, if it is below the version that you introduced the new model into then you can disable in app purchasing and just give the full functionality.


text:
Q: What is the best way to store usage reports over time? I currently have a few server reports that return usage statistics whenever run. The data is collected from several different sources (mostly log files), so they're not in a database to begin with.
The returned data are simple lists, for example, detailing how much disk space a user is using (user => space) average percent memory they've used for the month (user => memory), avg CPU time, etc.
Some of the information is a running total (like disk usage) and others are averages of snapshots taken throughout the month.
Running these reports and looking at the results works perfect, but I'd like to start storing these results to look at long-term trends.
What would be the best way to do this?

A: CACTI is very useful and highly configurable.  Utilizes RRD Tool.
RRD Tool is great, b/c it stores data in a circular format and summarizes it.  When RRD creates a data file, it creates it with every data point that it will ever store, so it never gets larger.  You don't have to worry about log files getting too large.  The key is to configure it to summarize in time periods, e.g., daily, monthly, yearly.  The downside is that next year, you might not be able to know the CPU usage for the five minute period from January 1 of this year.  But who really needs that?

A: RRDtool seems the obvious solution for this.
Or for that matter, one of the out-of-the box monitoring tools, some of which happen to use rrdtool for storing their data. E.g. Munin.


text:
Q: multi drop down wordpress not fitting, scroll not working Referring to this site: http://premierdisab.staging.wpengine.com/
On the header nav menu when you hover over "Medical Conditions" found under "Social Security Disability" on the top nav bar it does display all conditions but not all fit. I tried adding to the class "sub-menu" the attribute "Overlay-y: scroll" but it didn't work. It applied to the first dropdown but then hid the second drop down which could only be accessed by an x-axis scroll that was now showing.
Is there a way in WordPress to give a unique drop down a specific class? I have a feeling that would do it but I can't figure out how after looking at the menu settings on the WP Dashboard.

A: You can add this to your stylesheet:
.nav-menu .sub-menu .sub-menu {
  overflow: auto;
}


text:
Q: Module including in rails project I have written constant.rb in lib/ folder for my rails app.To use that in ActiveRecord, I have written ActiveRecord::Base.extends Constant in constant.rb and it is working. But I don't know how to use the same in ActionController, I tried ActionController::Base.extends Constant But It is not worked. Pls help.

A: A simple mistake.
You want ActionController::Base.extend(Constant).
Note: extend not extend*s*

A: it's typo... you wrote the plural but actually it's singular extend.
A few tips:

*

*Constant may not be a good name for your Module maybe call more specific like AppConstant.

*You shouldn't put this into your lib/constant.rb, it's cleaner to create a new initializer like
config/initializers/constants.rb
require 'app_constant'
ActiveRecord::Base.extend AppConstant
ActiveController::Base.extend AppConstant

maybe there's an even better way: put the extend AppConstant into your app/controllers/application_controller.rb


text:
Q: Pyspark: add incremental counter to rows, for each different value I need to add a "row number" to a dataframe, but this "row number" must restart for each new value in a column.
Let me show you an example:
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('test').getOrCreate()

df = spark.createDataFrame([
    ('2018-01-01', 'John', 0),
    ('2018-01-01', 'Paul', 1),
    ('2018-01-08', 'Paul', 3),
    ('2018-01-08', 'Pete', 4),
    ('2018-01-08', 'John', 3),
    ('2018-01-15', 'Mary', 6),
    ('2018-01-15', 'Pete', 6),
    ('2018-01-15', 'John', 6),
    ('2018-01-15', 'Paul', 6),
], ['str_date', 'name', 'value'])

# Convert str_date to date:
df = df.withColumn('date', to_date(df['str_date'])) \
    .select(['date', 'name', 'value'])

# Sort by name and date
df.orderBy(['name', 'date']).show()

## +----------+----+-----+
## |      date|name|value|
## +----------+----+-----+
## |2018-01-01|John|    0|
## |2018-01-08|John|    3|
## |2018-01-15|John|    6|
## |2018-01-15|Mary|    6|
## |2018-01-01|Paul|    1|
## |2018-01-08|Paul|    3|
## |2018-01-15|Paul|    6|
## |2018-01-08|Pete|    4|
## |2018-01-15|Pete|    6|
## +----------+----+-----+

So, what I need is to add a new column with the number of the row for each name:
# Expected result
## +----------+----+-----+------+
## |      date|name|value|rowNum|
## +----------+----+-----+------+
## |2018-01-01|John|    0|     1| <- First row for 'John'
## |2018-01-08|John|    3|     2|
## |2018-01-15|John|    6|     3|
## |2018-01-15|Mary|    6|     1| <- First row for 'Mary'
## |2018-01-01|Paul|    1|     1| <- First row for 'Paul'
## |2018-01-08|Paul|    3|     2|
## |2018-01-15|Paul|    6|     3|
## |2018-01-08|Pete|    4|     1| <- First row for 'Pete'
## |2018-01-15|Pete|    6|     2|
## +----------+----+-----+------+

I've been trying with the Window function, but I'm stuck. Can you please help me?
Notes:

*

*It is guaranteed that the rows will be sorted (and, if they are not sorted, they will be sorted as part of the work pipeline)

*I'm using Spark 2.4.0

A: Use a ranking function like row_number to do this. If there can be ties for a name on a given date, use dense_rank instead.
from pyspark.sql import Window
from pyspark.sql import functions as f
#Window definition
w = Window.partitionBy(df.name).orderBy(df.date)
res = df.withColumn('rnum',f.row_number().over(w))
res.show()

A: Vamsi's answer is correct. missed a () for row_number so ...
    w = Window.partitionBy(df.name).orderBy(df.date)
    res = df.withColumn('rnum',f.row_number().over(w))  # change after row_number
    res.show()


text:
Q: How to read extract data between parantheses and print it to another file I am looking a method to extract a particular text from multiple parentheses and wanted to store in a file. The content looks like this.
{& Vendor CGIO} 1100 650} {{& IP_OWNER cjohn} 1100 550} {{& Product pk_sgmii_serdes_sx_ico_idac_sw_by2} 1100 450} {{& DATE_TIME Aug 29 03:27:36 2016} 1100 750} {{& Version 1.1} 1100 350} {{& PDK_RELEASE_VERSION V1} 1100 850}

I wanted to extract following and print into a file.
& Vendor CGIO
& IP_OWNER cjohn
& Product pk_sgmii_serdes_sx_ico_idac_sw_by2
& Version 1.1

I tried using cut command but its not so useful to extract all variables.
cat Tags_file | cut -d '{' -f2 | cut -d '}' -f1

A: Using grep -oP with lookaround based regex:
grep -oP '(?<={)[^{}]+(?=})' file

& Vendor CGIO
& IP_OWNER cjohn
& Product pk_sgmii_serdes_sx_ico_idac_sw_by2
& DATE_TIME Aug 29 03:27:36 2016
& Version 1.1
& PDK_RELEASE_VERSION V1

A: Perhaps while loop will also print the outputs:
my $str = '{& Vendor CGIO} 1100 650} {{& IP_OWNER cjohn} 1100 550} {{& Product pk_sgmii_serdes_sx_ico_idac_sw_by2} 1100 450} {{& DATE_TIME Aug 29 03:27:36 2016} 1100 750} {{& Version 1.1} 1100 350} {{& PDK_RELEASE_VERSION V1} 1100 850}';

print "$1\n" while($str=~m/\{([^\{\}]*)\}/g);

A: Try
grep -Poh '(?<={)& (?!DATE|PDK)[^}]+' Tags_file

What I got:
& Vendor CGIO
& IP_OWNER cjohn
& Product pk_sgmii_serdes_sx_ico_idac_sw_by2
& Version 1.1

Just what you needed. (excluded DATE_TIME and PDK as in your example)
Regex101 demo

A: First, change all {& to newlines, then get rid of the remaining noise (note that I removed the initial & also):
$ echo "{& Vendor CGIO} 1100 650} {{& IP_OWNER cjohn} 1100 550} {{& Product pk_sgmii_serdes_sx_ico_idac_sw_by2} 1100 450} {{& DATE_TIME Aug 29 03:27:36 2016} 1100 750} {{& Version 1.1} 1100 350} {{& PDK_RELEASE_VERSION V1} 1100 850}"
| sed 's/{&/\n/g' | awk -F\} '{ print $1 }'

 Vendor CGIO
 IP_OWNER cjohn
 Product pk_sgmii_serdes_sx_ico_idac_sw_by2
 DATE_TIME Aug 29 03:27:36 2016
 Version 1.1
 PDK_RELEASE_VERSION V1


text:
Q: Esper: Reset std:firstevent() Currently i am using following piece of code. It looks for the first event of ValueTrigger and saves it and ignore all the next ValueTriggered Events. Then it compares currentData.last
value with first ValueTriggered event.
select
*
from
Tick as currentData unidirectional,
ValueTriggered.std:firstevent() as triggerPoint
where
currentData.last < triggerPoint.highValue;

What i want to achieve is to rest the value of triggerPoint when ever the condition is matched. I want to change std:firstevent() with some function which reset value when ever "where" condition matches(by reset i mean next ValueTriggerd Value).

A: Sounds like "every ValueTriggered -> Tick(...)"
A "reset" can also be done using explicit delete from a named window.


text:
Q: IS NOT NULL AS ... - Convert Query from MySQL to MS-SQL I have an application that is working fine using a MySQL/MariaDB-Database.
I did make it more flexible and now I am basically able to use a Microsoft SQL-Server database.
I found out, that some SQL-queries do NOT work anymore.
I don't have experience with MS-SQL and I am looking for support to convert the following query to make it work with MS-SQL. It would be great, if the query could be converted to work in both MS-SQL and MySQL ...
I have created an SQL-Fiddle with some example-data.
Link: http://sqlfiddle.com/#!18/5fb718/2
The Query itself looks like this:
SELECT computermapping.PrinterGUID, computerdefaultprinter.PrinterGUID IS NOT NULL AS isDefaultPrinter
FROM computermapping
LEFT JOIN computerdefaultprinter ON computerdefaultprinter.ComputerGUID = computermapping.ComputerGUID
AND computerdefaultprinter.PrinterGUID = computermapping.PrinterGUID
WHERE computermapping.ComputerGUID = "5bec3779-b002-46ba-97c4-19158c13001f"

When I run this on SQL-Fiddle I get the following error:

Incorrect syntax near the keyword 'IS'.

When I run this Query in Microsoft SQL Server Management Studio I get the same Error. I have an German-Installation ...

Meldung 156, Ebene 15, Status 1, Zeile 1
Falsche Syntax in der Nähe des IS-Schlüsselworts.

I was looking on the Internet to find information on how to use the IS NOT NULL AS in MS-SQL. Maybe I was using the wrong keywords, but I was not able to find a solution myself.
If it does matter, I am using "SQL-Server 2014 SP3" at the moment.
Thank you

A: Convert
computerdefaultprinter.PrinterGUID IS NOT NULL AS isDefaultPrinter

to
CASE
   WHEN computerdefaultprinter.PrinterGUID IS NOT NULL THEN 1
   ELSE 0
END AS isDefaultPrinter

Demo here
Also bear in mind that there is no BOOLEAN type in SQL Server. BIT type is used instead.
Finally
WHERE computermapping.ComputerGUID = "5bec3779-b002-46ba-97c4-19158c13001f"

should be converted to
WHERE computermapping.ComputerGUID = '5bec3779-b002-46ba-97c4-19158c13001f'

since the single quote character is used to delimit strings in SQL Server

A: MySql evaluates boolean expressions like:
computerdefaultprinter.PrinterGUID IS NOT NULL

as 1 for TRUE or 0 for FALSE.
SQL Server does not do such an evaluation, so you need a CASE expression:
CASE WHEN computerdefaultprinter.PrinterGUID IS NOT NULL THEN 1 ELSE 0 END

A: The exact question was already answered, but you should really, really try using the SQL Server Migration Assistant for MySQL. No database supports the SQL standard beyond a basic compatibility level and MySQL is one of the quirkiest databases when it comes to SQL compatibility.
The SQL standard process is sloooow so all vendors implement features long before they're standardized. Different databases have different priorities too, and MySQL's priority for the first decade at least wasn't enterprise applications, so SQL compatibility wasn't a high priority.
Some common features were added only in MySQL 8. Some hacks allowed (but discouraged) in MySQL, like non-aggregate columns in a grouping query, or quirky updates to calculate row numbers, don't work in any other databases because logically, they lead to unpredictable results.
Even in MySQL, non-aggregate columns can cause serious performance degradation when upgrading from one 5.x version to the next. There's at least one SO question about this.
The Migration assistant will convert tables and types where possible and flag any stored procedure or view queries that can't be translated. It can also copy data from an existing MySQL database to a SQL Server database


text:
Q: androidx legacy library suddenly in the project I have an android studio project where I recently changed the minSDK from 21 to 26. Now I saw that the project has a new dependecy
'androidx.legacy:legacy-support-v4:1.0.0' and I really don't know how it came here.
I never added that dependency to my project and now I don't know if I can safely delete it.
Is there a possibility that android studio added that dependency because of that minSDK change?
if not is there a way to see if the project needs that dependency.


text:
Q: msvc2010: ошибка: C2440: инициализация: невозможно преобразовать Использую std::multiset
Он определен в подключаемых заголовках vs2010
Компилятор (msvc2010) ругается на то, что я неверно инициализирую экземпляр std::multiset::const_iterator, а также неверно использую оператор сравнения.
Возможно, конечно это из-за неполной поддержки компилятором стандарта C++11.
Но все же я решил спросить.
Можно ли это как-то обойти?
Ошибка возникает и для неконстантных итераторов.
typedef std::multiset<
    const RuleInfo*, // пользовательская стрктура
    RuleInfoCmpRulePtrParMore // оператор сравнения
> RuleInfoConstPtrMSet;
...
void CriteriaDialog::addButtonClicked() {
    RuleInfoConstPtrMSet::const_iterator it = allowable_rules_.begin(); // 1-я ошибка

    if ( ui->combo_box_param_->currentIndex() )
        std::advance( it, ui->combo_box_param_->currentIndex() );

    if ( it == allowable_rules_.cend() ) return; // 2 ошибка
    // ...
}

Первая ошибка:
C:\Files\qt\universal_tsw_client\src\tsw-client\ui\criteria_dialog.cpp:328: ошибка: C2440: инициализация: невозможно преобразовать "std::_Tree_const_iterator<_Mytree>" в "std::_Tree_const_iterator<_Mytree>"
with
[
    _Mytree=std::_Tree_val<std::_Tset_traits<const RuleInfo *,RuleInfoCmpRulePtrParMore,std::allocator<const RuleInfo *>,false>>
]
and
[
    _Mytree=std::_Tree_val<std::_Tset_traits<const RuleInfo *,RuleInfoCmpRulePtrParMore,std::allocator<const RuleInfo *>,true>>
]
Ни один конструктор не смог принять исходный тип, либо разрешение перегрузки конструктора неоднозначно

Вторая ошибка:
C:\Files\qt\universal_tsw_client\src\tsw-client\ui\criteria_dialog.cpp:333: ошибка: C2678: бинарный "==": не найден оператор, принимающий левый операнд типа "std::_Tree_const_iterator<_Mytree>" (или приемлемое преобразование отсутствует)
with
[
    _Mytree=std::_Tree_val<std::_Tset_traits<const RuleInfo *,RuleInfoCmpRulePtrParMore,std::allocator<const RuleInfo *>,true>>
]
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE\exception(470): может быть "bool std::operator ==(const std::_Exception_ptr &,const std::_Exception_ptr &)" [найдено при поиске с зависимостью от аргументов]
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE\exception(475): или       "bool std::operator ==(std::_Null_type,const std::_Exception_ptr &)" [найдено при поиске с зависимостью от аргументов]
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE\exception(481): или       "bool std::operator ==(const std::_Exception_ptr &,std::_Null_type)" [найдено при поиске с зависимостью от аргументов]
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE\system_error(408): или       "bool std::operator ==(const std::error_code &,const std::error_condition &)" [найдено при поиске с зависимостью от аргументов]
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE\system_error(416): или       "bool std::operator ==(const std::error_condition &,const std::error_code &)" [найдено при поиске с зависимостью от аргументов]
c:\qt\4.8.5\include\qtcore\../../src/corelib/global/qglobal.h(2015): или       "bool operator ==(QBool,bool)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/global/qglobal.h(2016): или       "bool operator ==(bool,QBool)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/global/qglobal.h(2017): или       "bool operator ==(QBool,QBool)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qchar.h(392): или       "bool operator ==(QChar,QChar)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qbytearray.h(527): или       "bool operator ==(const QByteArray &,const QByteArray &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qbytearray.h(529): или       "bool operator ==(const QByteArray &,const char *)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qbytearray.h(531): или       "bool operator ==(const char *,const QByteArray &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qstring.h(908): или       "bool operator ==(QString::Null,QString::Null)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qstring.h(909): или       "bool operator ==(QString::Null,const QString &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qstring.h(910): или       "bool operator ==(const QString &,QString::Null)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qstring.h(936): или       "bool operator ==(const char *,const QString &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qstring.h(949): или       "bool operator ==(const char *,const QLatin1String &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qstring.h(962): или       "bool operator ==(const QLatin1String &,const QLatin1String &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qstring.h(1202): или       "bool operator ==(const QStringRef &,const QStringRef &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qstring.h(1205): или       "bool operator ==(const QString &,const QStringRef &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qstring.h(1208): или       "bool operator ==(const QStringRef &,const QString &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qstring.h(1212): или       "bool operator ==(const QLatin1String &,const QStringRef &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qstring.h(1215): или       "bool operator ==(const QStringRef &,const QLatin1String &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qstring.h(1236): или       "bool operator ==(const char *,const QStringRef &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qstring.h(1238): или       "bool operator ==(const QStringRef &,const char *)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qsize.h(83): или       "bool operator ==(const QSize &,const QSize &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qsize.h(233): или       "bool operator ==(const QSizeF &,const QSizeF &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qpoint.h(80): или       "bool operator ==(const QPoint &,const QPoint &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qpoint.h(238): или       "bool operator ==(const QPointF &,const QPointF &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qrect.h(162): или       "bool operator ==(const QRect &,const QRect &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qrect.h(599): или       "bool operator ==(const QRectF &,const QRectF &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qmargins.h(77): или       "bool operator ==(const QMargins &,const QMargins &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/tools/qhash.h(198): или       "bool operator ==(const QHashDummyValue &,const QHashDummyValue &)"
c:\qt\4.8.5\include\qtcore\../../src/corelib/kernel/qvariant.h(413): или       "bool operator ==(const QVariant &,const QVariantComparisonHelper &)"
c:\qt\4.8.5\include\qtnetwork\../../src/network/kernel/qhostaddress.h(137): или       "bool operator ==(QHostAddress::SpecialAddress,const QHostAddress &)"
c:\files\qt\universal_tsw_client\src\tsw-client\ui\../criteria_typedefs.h(83): или       "bool operator ==(const RuleInfo &,const RuleInfo &)"
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE\xtree(315): или       "bool std::_Tree_const_iterator<_Mytree>::operator ==(const std::_Tree_const_iterator<_Mytree> &) const"
with
[
    _Mytree=std::_Tree_val<std::_Tset_traits<const RuleInfo *,RuleInfoCmpRulePtrParMore,std::allocator<const RuleInfo *>,true>>
]
при попытке сопоставить список аргументов "(std::_Tree_const_iterator<_Mytree>, std::_Tree_const_iterator<_Mytree>)"
with
[
    _Mytree=std::_Tree_val<std::_Tset_traits<const RuleInfo *,RuleInfoCmpRulePtrParMore,std::allocator<const RuleInfo *>,true>>
]
and
[
    _Mytree=std::_Tree_val<std::_Tset_traits<const RuleInfo *,RuleInfoCmpRulePtrParMore,std::allocator<const RuleInfo *>,false>>
]

UPD: Пользователь @AnT заметил, что в листингах не было объявления объекта allowable_rules_, он объявлен как объект типа typedef std::<const RuleInfo*, RuleInfoCmpRulePtrParMore> видимо,  msvc не кастит итераторы multiset к set,или такого преобразовния не было в реализации STL от Microsoft, т.к. в gcc такой код собирался.


text:
Q: How to associate data to a ListView item? In Windows API, I can use the lParam memeber of the LVITEM structure to associate data to a ListView item. Can I do a similar thing in C#?
Note: Of course I can just add an extra column to my ListView to do that, but I don't want to display this data to the user.

A: You're looking for the Tag property, which can store an arbitrary object.


text:
Q: git commiting changes on openshift server I'm running Statamic a flat file system (database-less) CMS on Openshift.
The issue i'm having is that when i update the content on the server (i.e. using the CMS) the changes that are made to the flat files (i.e. the content) isn't committed to the git repo. So, when I push up new changes to the website from my local repo, I wind up writing over it each time there's a git push. If I do a git pull, I get nada because the remote server doesn't know about the changes (they haven't been committed yet)
What I need to be able to do is make a git commit to any changes that happen on the server. Sadly, his doesn't work. I tried SSH in and it has no idea that there's a git repo. Something to do with the build process that they use.
Ideally, I'd like to find a way to automatically commit the changes on the server so i can pull them down without SSH in to commit. But anything that gets the job done is a huge win at this point.

A: You need to store your flat-file databases in the ~/app-root/data directory instead of your repo directory.  The repo directory gets removed on each git push.  My recommendation would be to find out what the names and locations of the flat files are, and then symlink the directory that stores them to your $OPENSHIFT_DATA_DIR so they will not be affected on a git push.  You can do this using an action hook like the WordPress cartridge does here: https://github.com/openshift/wordpress-example/blob/master/.openshift/action_hooks/deploy


text:
Q: ics file sended to outlook are not reconized as event I need to develop an application to send events to Gmail / Outlook calendars. Java mail 1.5.5 is used. I did some tests with version 1.6.2, without more success
The chosen solution is to generate ics files, and send them by email to the target calendars adresses.
On Gmail, the email is well recognized as an event email (the email contains the description of the event, the possibility to change the answer, and the event is automatically added to the calendar)
On Outlook, the attachment is not recognized as an event (the email just contains the ics file as an attachment, no description or response request, and the event is not automatically added to the calendar) . You must then click on the attachment, then on "Add to calendar" so that the event is created in the calendar
I found many similar topics on the net, but nothing that helped me solve the problem
The problem could come from the ics file or the headers of the mail. The ics file looks good to me: If on gmail, I create a new message, I add my ics as an attachment, and I send it to my Outlook address, the email is well recognized as an event
Here is the content of the ics file
BEGIN:VCALENDAR
PRODID:<MYPRODID>
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:REQUEST
BEGIN:VEVENT
DTSTAMP:20220629T121224Z
SUMMARY:Test Event
DTSTART:20220630T110000Z
DTEND:20220630T130000Z
UID:<MYUID>
SEQUENCE:1656460800
DESCRIPTION:Event body
ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=FALSE;CN=<MYCN>:mailto:<MYEMAIL>
ORGANIZER;CN=<MYORGNAME>:mailto:<MYORGEMAIL>
END:VEVENT
END:VCALENDAR

I have some doubt on the headers / mail structure. I find a lot of different things on the internet, but everything I try leads to the same result (the need to open my email in Outlook, to manually import the attachment)
Here is my java code during the last tests:
Properties prop = new Properties();

prop.put("mail.mime.charset", "UTF-8");
prop.put("mail.smtp.host", "<MYHOST>");
prop.put("mail.smtp.port", "<MYPORT>");
prop.put("mail.smtp.auth", Boolean.TRUE.toString());
prop.put("mail.smtp.user", "<MYUSER>");
prop.put("password", "<MYPASS>");

String from = "<MYORGEMAIL>";
String to = "<MYEMAIL>";

Session session = Session.getInstance(prop, new SMTPAuthenticator(prop));
// Define message
MimeMessage message = new MimeMessage(session);
message.addHeader("method", "REQUEST");
message.addHeader("charset", "UTF-8");
message.addHeader("component", "VEVENT");

message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Outlook Meeting Request Using JavaMail");

File invitation = new File("<MYFILEPATH>\\vCalendar_5067936453064913847.ics");

MimeMultipart mixed = new MimeMultipart("mixed");

// Create the message part
MimeMultipart alternative = new MimeMultipart("alternative");
MimeBodyPart alternativePart = new MimeBodyPart();
alternativePart.setContent(alternative);
mixed.addBodyPart(alternativePart);
MimeBodyPart plain = new MimeBodyPart();
plain.setText("body", "UTF-8", "plain");
MimeBodyPart html = new MimeBodyPart();
html.setText("
body
", "UTF-8", "html");
alternative.addBodyPart(plain);
alternative.addBodyPart(html);

// Create the attachment part
BodyPart icsBodyPart = new MimeBodyPart();
icsBodyPart.addHeader("method", "REQUEST");
icsBodyPart.addHeader("Content-Class", "urn:content-classes:calendarmessage");
icsBodyPart.addHeader("Content-ID", "calendar_message");
icsBodyPart.addHeader("component", "VEVENT");
FileInputStream inputStream = new FileInputStream(invitation.getAbsolutePath());
final DataSource source =
    new ByteArrayDataSource(inputStream,
        "text/calendar; charset=\"UTF-8\"; name=\"vCalendar_5067936453064913847.ics\"");
icsBodyPart.setDataHandler(new DataHandler(source));
icsBodyPart.setFileName(invitation.getName());
mixed.addBodyPart(icsBodyPart);

// Put parts in message
message.setContent(mixed);

// send message
Transport.send(message);

To know how to structure my mime parts, I look to my message structure in my gmail sendbox (the one that is reconized by Outlook) :
MIME-Version: 1.0
Date: Tue, 12 Jul 2022 14:44:10 +0200
Message-ID: <XXXXXXXXXXX@mail.gmail.com>
Subject: Mail title test
From: XXXXXXXXXXX <XXXXXXXXXXX@gmail.com>
To: XXXXXXXXXXX <XXXXXXXXXXX@XXXXXXXXXXX.com>
Content-Type: multipart/mixed; boundary="00000000000072927505e39b0616"

--00000000000072927505e39b0616
Content-Type: multipart/alternative; boundary="00000000000072927005e39b0614"

--00000000000072927005e39b0614
Content-Type: text/plain; charset="UTF-8"

Mail content test

--00000000000072927005e39b0614
Content-Type: text/html; charset="UTF-8"

Mail content test

--00000000000072927005e39b0614--
--00000000000072927505e39b0616
Content-Type: text/calendar; charset="UTF-8"; name="vCalendar_5067936453064913847.ics"
Content-Disposition: attachment; filename="vCalendar_5067936453064913847.ics"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_l4i5zybk0
Content-ID: <f_l4i5zybk0>

QkVHSU46VkNBTEVOREFSClBST0RJRDpTeWxvYiBudWxsClZFUlNJT046Mi4wCkNBTFNDQUxFOkdS
RUdPUklBTgpXXXXXXXXXXXVRVUVTVApCRUdJTjpWRVZFTlQKRFRTVEFNUDoyMDIyMDYyOVQxMjEy
MjRaClNVTU1BUlk6NSAtIMOJdsOpbmVtZW50IGR1IDI4MDYgw6AgU3lsb2IgZGUgZMOpbW8gCkRU
U1RBUlQ6MjAyMjA2MzBUMTEwMDAwWgpEVEVORDoyMDIyMDYzMFQxMzAwMDBaClVJRDp0ZXN0VWlk
MTY1OTc1QHN5bG9iLmNvbQpTRVFVRU5DRToxNjU2NDYwODAwCkRFU0NSSVBUSU9OOlRlc3QgZGUg
Y29ycCBkZSB0ZXh0ZVxuc3VyIHBsdXNpZXVycyBsaWduZXNcLCBhY2NlbnRzIMOgIHRlc3RlcgpB
VFRFTkRFRTtST0xFPVJFUSXXXXXXXXXXXXXOVDtQQVJUU1RBVD1BQ0NFUFRFRDtSU1ZQPUZBTFNF
O0NOPUFsZXhhbmRyZSBORURORUQ6bWFpbHRvOmFsZXgubmVkamFyaUBnbWFpbC5jb20KT1JHQU5J
WkVSO0NOPSJPcmfDom5pc2F0ZXVyIjptYWlsdG86ZGF0YUBzeWxvYi5jb20KRU5EOlZFVkVOVApF
TkQ6VkNBTEVOREFSCgo=
--00000000000072927505e39b0616--

If I knew how to see the same informations on outlook, I could compare the mail received from gmail and the one received from java, but I'm not sure it's possible (I found the "display / message details" option, but this option only show informations about the top level mime part, not the complete mime structure)
Does anyone have an idea how to fix this problem?
Thanks,

A: I had a similar problem and found a solution in rewriting a Content-Type header. I've added method=REQUEST to this header and after that outlook started recognize my emails as events.
Content-Type: text/calendar; charset="utf-8"; method=REQUEST

Example of code on python:
msg = MIMEMultipart()
msg['Subject'] = 'Your event'
msg['From'] = 'test@test.com'
msg['To'] = 'test@test.com'

with open('example.ics') as f:
    event = MIMEText(f.read(), _subtype='calendar', _charset='utf-8')
    event.replace_header('Content-Type', 'text/calendar; charset="utf-8"; method=REQUEST')
    msg.attach(event)

s.send_message(msg)
s.quit()


text:
Q: Evaluating the Gauss Circle Problem $N(n)$ in $O(n^{\frac{1}{3}+\epsilon})$ I'm interested in the technique of counting the number of positive integer pairs $x$ and $y$ satisfying $x^2+y^2 \leq n$ in $O(n^{\frac{1}{3}+\epsilon})$. The basic idea is that we can only focus on the convex hull of the integer lattice points falling in the circle $x^2+y^2 \leq n$ and the number of vertices of such convex hull is $O(n^\frac{1}{3})$. By trying to find the lattice points on the convex hull quickly (in roughly amortized constant time), we are able to yield the answer in $O(n^{\frac{1}{3}+\epsilon})$. Though there is a program implementing such an idea together with the stern-brocot tree, it is still quite hard to follow. Any detail/thought/explanation on the solution is welcome.
A related problem is here, which uses essentially the same technique to find out the convex hull of the integer lattice points under the hyperbola.
Meanwhile, a proof of the number of integer lattice points of the convex hull is $O(n^\frac{1}{3})$ is also appreciated.


text:
Q: working with sqlite3 in mac os x 10.9 I know that Mac OSx has pre-installed sqlite3.But when I am entering this command, when in
/usr/bin directory, sqlite3 test.db i get this displayed on terminal..
Adityas-MacBook-Air:bin adityabahuguna$ sqlite3 test.db
SQLite version 3.7.13 2012-07-17 17:46:21
Enter ".help" for instructions
Enter SQL statements terminated with a ";"

Its fine till now. But when i try to create a table by
sqlite> create table t(name text);

I always get this error:
Error: unable to open database "test.db": unable to open database file

This however does not occur when i directly use create table command without creating a new database. I want to figure out the way to create a new database (say test.db as above).

A: You're trying to create the database in /usr/bin where normal users don't have write access.
You can write to /usr/bin with root/sudo as suggested by Atul but that's not really something you should do.
Instead, specify a database path that is writable by your normal user, for example
sqlite3 ~/test.db

so the test.db gets created in your home directory.

A: you need to be logged in as root user to have create database privilege. you can become root user by following these steps: How to Become root user.