text:
Q: Continuous clocked concurrent SQL table inserts over a RESTful WCF service slowing down until the clients receive HTTP timeouts I'm developing a WCF webservice (HTTP, REST) to enable event logging to external clients / devices to a database table. These logs shall be stored on a database (in this case MS SQL Server). The backend uses ODBC to connect to the database, because it should be compatible to multiple DBMS.
But I'm running into concurrency issues on the datatabase inserts. Currently I simulate 4 clients, that continuously log events (one REST method call every second; started at the same time). The service writes the transmitted information to the same table on the database. But after a while, the clients sometimes won't get a HTTP-responses due to timeouts, because some inserts will be queued too long.
The service calls the following Method on each REST-Call (I removed Stopwatch lines):
private static bool AddReportToDatabase(...)
{
    Database database = new OdbcDatabase(ConfigurationHandler.GetDatabaseConfigParameters());

    var dateTime = DateTime.Now;

    try
    {
        int rowsAffected = 0;

        database.Connect();
        // Note: In fact, here is only one row => theres no performance issue due to the foreach loop
        foreach (var row in csv.Rows)
        {
            // build insert statement and execute
            var insertStatement = DatabaseHelper.BuildInsertRowSqlStatement(row, ...);

            rowsAffected += database.SqlExecute(insertStatement);
        }

        // return stuff.
        return rowsAffected > 0 || csv.Rows.Count == 0;
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        return false;
    }
    finally
    {
        database.Disconnect();

        Console.WriteLine(stopwatchString);
    }
}

The SqlExecute Method of that Database wrapper:
public override int SqlExecute(string statement, bool autoCloseConnection = false)
{
    // Check parameters.
    if (statement is null) { throw new ArgumentNullException(nameof(statement)); }
    if (string.IsNullOrWhiteSpace(statement)) { throw new ArgumentException(); }

    OdbcCommand cmd = null;
    int rowCount = 0;

    try
    {
        if (_connection.State != ConnectionState.Open) { ReConnect(); }
        if (_connection.State == ConnectionState.Open)
        {
            cmd = new OdbcCommand(statement, _connection);
            rowCount = cmd.ExecuteNonQuery();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
    finally
    {
        cmd?.Dispose();
        if (autoCloseConnection) { _connection?.Close(); }
    }
    return rowCount;
}

I started writing the time durations, for some operations that are called in the AddReportToDatabase(...) method, to the console.
An excerpt from the Visual Studio (Debug mode) output shows the Problem:
Connection: 00:00:43.3932743, INSERT statement build: 00:00:00.0000389, Insertion execution: 00:00:08.2686554, Disconnection: 00:00:00.0010952
Connection: 00:00:35.2980692, INSERT statement build: 00:00:00.0000205, Insertion execution: 00:00:08.4519441, Disconnection: 00:00:00.0000165
Connection: 00:00:22.5600041, INSERT statement build: 00:00:00.0022653, Insertion execution: 00:00:09.0177640, Disconnection: 00:00:00.0000160
Connection: 00:00:40.7761234, INSERT statement build: 00:00:00.0000155, Insertion execution: 00:00:08.5453105, Disconnection: 00:00:00.0000098
Connection: 00:00:40.4190963, INSERT statement build: 00:00:00.0000142, Insertion execution: 00:00:08.5454255, Disconnection: 00:00:00.0000062
Connection: 00:00:35.6413547, INSERT statement build: 00:00:00.0000319, Insertion execution: 00:00:08.5458726, Disconnection: 00:00:00.0000061
Connection: 00:00:33.2825363, INSERT statement build: 00:00:00.0000291, Insertion execution: 00:00:09.4197485, Disconnection: 00:00:00.0000173
Connection: 00:00:14.5735937, INSERT statement build: 00:00:00.0000301, Insertion execution: 00:00:00.7464504, Disconnection: 00:00:00.0000189
Exception thrown: 'System.TimeoutException' in System.Core.dll
Connection: 00:00:00.0006277, INSERT statement build: 00:00:00.0000175, Insertion execution: 00:00:01.6230868, Disconnection: 00:00:00.0000289
Connection: 00:00:00.0009455, INSERT statement build: 00:00:00.0000238, Insertion execution: 00:00:00.3431754, Disconnection: 00:00:00.0000179
Connection: 00:00:10.7779260, INSERT statement build: 00:00:00.0000271, Insertion execution: 00:00:00.9052707, Disconnection: 00:00:00.0000163
Connection: 00:00:06.7611688, INSERT statement build: 00:00:00.0000492, Insertion execution: 00:00:00.6356935, Disconnection: 00:00:00.0000194
Exception thrown: 'System.TimeoutException' in System.Core.dll
Connection: 00:00:46.1030176, INSERT statement build: 00:00:00.0000149, Insertion execution: 00:00:12.0938001, Disconnection: 00:00:00.0000191
Connection: 00:00:09.6917265, INSERT statement build: 00:00:00.0000296, Insertion execution: 00:00:00.5381473, Disconnection: 00:00:00.0000184
Connection: 00:00:40.6265686, INSERT statement build: 00:00:00.0000238, Insertion execution: 00:00:03.8422172, Disconnection: 00:00:00.0000178
Connection: 00:00:00.0006520, INSERT statement build: 00:00:00.0000171, Insertion execution: 00:00:00.5489864, Disconnection: 00:00:00.0000117
Connection: 00:00:00.0007138, INSERT statement build: 00:00:00.0000168, Insertion execution: 00:00:00.6436385, Disconnection: 00:00:00.0000087
Connection: 00:00:00.0006049, INSERT statement build: 00:00:00.0000175, Insertion execution: 00:00:00.8492274, Disconnection: 00:00:00.0000383
Connection: 00:00:00.0005660, INSERT statement build: 00:00:00.0000188, Insertion execution: 00:00:00.9499183, Disconnection: 00:00:00.0000230
Connection: 00:00:00.0009943, INSERT statement build: 00:00:00.0000438, Insertion execution: 00:00:00.3964118, Disconnection: 00:00:00.0000197
Connection: 00:00:00.0005547, INSERT statement build: 00:00:00.0000181, Insertion execution: 00:00:01.3838526, Disconnection: 00:00:00.0000192
Connection: 00:00:00.0007199, INSERT statement build: 00:00:00.0000209, Insertion execution: 00:00:00.9477482, Disconnection: 00:00:00.0000206
Connection: 00:00:00.0006825, INSERT statement build: 00:00:00.0000206, Insertion execution: 00:00:01.1694541, Disconnection: 00:00:00.0000182
Exception thrown: 'System.TimeoutException' in System.Core.dll
Exception thrown: 'System.TimeoutException' in System.Core.dll
Connection: 00:00:00.0007774, INSERT statement build: 00:00:00.0000279, Insertion execution: 00:00:01.8400186, Disconnection: 00:00:00.0000175
Exception thrown: 'System.TimeoutException' in System.Core.dll
Exception thrown: 'System.TimeoutException' in System.Core.dll
Exception thrown: 'System.TimeoutException' in System.Core.dll
Exception thrown: 'System.TimeoutException' in System.Core.dll
Exception thrown: 'System.TimeoutException' in System.Core.dll
Connection: 00:00:00.0006994, INSERT statement build: 00:00:00.0000154, Insertion execution: 00:00:00.3693845, Disconnection: 00:00:00.0000184
Connection: 00:00:00.0008125, INSERT statement build: 00:00:00.0000274, Insertion execution: 00:00:00.8685170, Disconnection: 00:00:00.0000177
Connection: 00:00:00.0009804, INSERT statement build: 00:00:00.0000198, Insertion execution: 00:00:00.4191057, Disconnection: 00:00:00.0000090
Connection: 00:00:00.0005996, INSERT statement build: 00:00:00.0000160, Insertion execution: 00:00:00.5557408, Disconnection: 00:00:00.0000193
Connection: 00:00:00.0008110, INSERT statement build: 00:00:00.0000190, Insertion execution: 00:00:00.3741617, Disconnection: 00:00:00.0000166
Connection: 00:00:00.0006637, INSERT statement build: 00:00:00.0000165, Insertion execution: 00:00:00.3732236, Disconnection: 00:00:00.0000203
Connection: 00:00:00.0006747, INSERT statement build: 00:00:00.0000152, Insertion execution: 00:00:00.3712866, Disconnection: 00:00:00.0000118
Connection: 00:00:00.0031405, INSERT statement build: 00:00:00.0000231, Insertion execution: 00:00:00.5106569, Disconnection: 00:00:00.0000191
Connection: 00:00:00.0033558, INSERT statement build: 00:00:00.0000184, Insertion execution: 00:00:00.8863036, Disconnection: 00:00:00.0000178
Connection: 00:00:00.2706784, INSERT statement build: 00:00:00.0000267, Insertion execution: 00:00:01.4607328, Disconnection: 00:00:00.0000095
Connection: 00:00:00.0008118, INSERT statement build: 00:00:00.0000194, Insertion execution: 00:00:01.1763091, Disconnection: 00:00:00.0000080
Connection: 00:00:00.0007023, INSERT statement build: 00:00:00.0000331, Insertion execution: 00:00:01.0291836, Disconnection: 00:00:00.0000165
Connection: 00:00:00.0006962, INSERT statement build: 00:00:00.0000175, Insertion execution: 00:00:00.4053649, Disconnection: 00:00:00.0000237
Connection: 00:00:00.0006658, INSERT statement build: 00:00:00.0000174, Insertion execution: 00:00:00.8583524, Disconnection: 00:00:00.0000337
Connection: 00:00:00.0005899, INSERT statement build: 00:00:00.0000158, Insertion execution: 00:00:00.8663091, Disconnection: 00:00:00.0000185
Connection: 00:00:00.0010868, INSERT statement build: 00:00:00.0000313, Insertion execution: 00:00:00.6851859, Disconnection: 00:00:00.0000168
The thread 0x80c has exited with code 0 (0x0).
The thread 0x3138 has exited with code 0 (0x0).
The thread 0x55c has exited with code 0 (0x0).
The thread 0x3788 has exited with code 0 (0x0).
Connection: 00:00:00.0012492, INSERT statement build: 00:00:00.0000348, Insertion execution: 00:00:00.6995635, Disconnection: 00:00:00.0000164
Connection: 00:00:00.0006438, INSERT statement build: 00:00:00.0000165, Insertion execution: 00:00:01.2950788, Disconnection: 00:00:00.0000175
Connection: 00:00:00.0006178, INSERT statement build: 00:00:00.0000159, Insertion execution: 00:00:03.1707274, Disconnection: 00:00:00.0000169
Connection: 00:00:00.0007568, INSERT statement build: 00:00:00.0000176, Insertion execution: 00:00:03.2457625, Disconnection: 00:00:00.0000190
Connection: 00:00:00.0007487, INSERT statement build: 00:00:00.0000187, Insertion execution: 00:00:01.3998818, Disconnection: 00:00:00.0000144
Connection: 00:00:00.0021411, INSERT statement build: 00:00:00.0000171, Insertion execution: 00:00:00.5465371, Disconnection: 00:00:00.0000164
Connection: 00:00:00.0006600, INSERT statement build: 00:00:00.0000220, Insertion execution: 00:00:00.8264877, Disconnection: 00:00:00.0000166
Connection: 00:00:00.0006120, INSERT statement build: 00:00:00.0000178, Insertion execution: 00:00:02.1364418, Disconnection: 00:00:00.0000169
Connection: 00:00:00.0006415, INSERT statement build: 00:00:00.0000167, Insertion execution: 00:00:00.3577112, Disconnection: 00:00:00.0000182
Connection: 00:00:00.0018622, INSERT statement build: 00:00:00.0000187, Insertion execution: 00:00:00.9203211, Disconnection: 00:00:00.0000911
Connection: 00:00:00.0008004, INSERT statement build: 00:00:00.0000154, Insertion execution: 00:00:01.9627891, Disconnection: 00:00:00.0000131
Connection: 00:00:00.0007099, INSERT statement build: 00:00:00.0000172, Insertion execution: 00:00:00.4785908, Disconnection: 00:00:00.0000179
Connection: 00:00:00.0008012, INSERT statement build: 00:00:00.0000176, Insertion execution: 00:00:01.5589073, Disconnection: 00:00:00.0000189
Connection: 00:00:00.0007580, INSERT statement build: 00:00:00.0000186, Insertion execution: 00:00:01.3407059, Disconnection: 00:00:00.0000162
Connection: 00:00:00.0006188, INSERT statement build: 00:00:00.0000196, Insertion execution: 00:00:01.3752180, Disconnection: 00:00:00.0000037
Connection: 00:00:00.0007519, INSERT statement build: 00:00:00.0000169, Insertion execution: 00:00:01.4691674, Disconnection: 00:00:00.0000046
Connection: 00:00:00.0006486, INSERT statement build: 00:00:00.0000151, Insertion execution: 00:00:00.7363978, Disconnection: 00:00:00.0000312
Connection: 00:00:00.0007112, INSERT statement build: 00:00:00.0000195, Insertion execution: 00:00:00.4897923, Disconnection: 00:00:00.0000167
Connection: 00:00:00.0009538, INSERT statement build: 00:00:00.0000280, Insertion execution: 00:00:00.6982814, Disconnection: 00:00:00.0000331
Exception thrown: 'System.TimeoutException' in System.Core.dll
Connection: 00:00:00.0010226, INSERT statement build: 00:00:00.0000198, Insertion execution: 00:00:02.2475417, Disconnection: 00:00:00.0000154
Connection: 00:00:00.0007328, INSERT statement build: 00:00:00.0000192, Insertion execution: 00:00:01.4527606, Disconnection: 00:00:00.0000084
Connection: 00:00:00.0010429, INSERT statement build: 00:00:00.0000224, Insertion execution: 00:00:01.9530475, Disconnection: 00:00:00.0000264
Connection: 00:00:00.0006835, INSERT statement build: 00:00:00.0000277, Insertion execution: 00:00:01.5596577, Disconnection: 00:00:00.0000056
Connection: 00:00:00.0010008, INSERT statement build: 00:00:00.0000673, Insertion execution: 00:00:01.8743239, Disconnection: 00:00:00.0000062

As you can see, the first connections take very long to success (This problem does not exist when I simulate with only one client). In addition the insertions sometimes take more than one second. And now and then much longer (e.G. 12 seconds) to insert a row into the database. As a result, the wait time of some calls will reach the HTTP timeout and the operation will be canceled. I guess that depens (partially) on the DBMS and it's table writing management.
Another thing is, that there are multiple System.TimeoutExceptions thrown internally in the System.Core.dll and written to the output, which I cannot explain. So I can't tell if they're relevant or not.
The WCF Service is running with the default service behavior for session instancing and concurrency (https://learn.microsoft.com/de-de/dotnet/framework/wcf/feature-details/sessions-instancing-and-concurrency),
which should be equal to the usage of the following code:
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession, ConcurrencyMode=ConcurrencyMode.Single)]

So to my understanding, there is a new thread (instance context) created on each REST-Call. These should be managed by the WCF Service.
Is the problem a configuration Issue on the database (MVCC=true did not help), or on the web service?
To the implementation: I've tried a singleton database instance, but that caused other database access issues. And a global mutex to handle the database command executions, slows the whole thing down.
I even removed the PK-Constraint from the table to exclude (or at least reduce the probability) subsequent issues due to indexing.
Another version of this Service acts as this should, but with the difference that it logs on local files instead of a database. Here I used a mutex to handle the file access and that works even with quite shorter/faster logging frequencies (eg. a event log each 250ms). Mutexing the Insertion did not help here.
By the way: The WCF Service is self hosted by a Windows service.
UPDATE:
I found the cause of the problem.
The REST/WCF Method that is called is the following:
public bool Report(...)
{
    NotifyGUI(someStringParameter);
    return ReportHandler.AddReport(...); // this calls implicitly AddReportToDatabase(...) in this scenario
}

The firstly called method causes the Exceptions:
Exception thrown: 'System.TimeoutException' in System.Core.dll

and blocks the main functionality (connect, write to table and disconnect), so it causes the delays that grind my gears.
private void NotifyGUI(string s)
{
    Task.Run(() =>
    {
        using (var client = new NamedPipeClientStream(typeof(HttpService).ToString()))
        {
            client.Connect(5000);
            using (StreamWriter writer = new StreamWriter(client))
            {
                writer.WriteLine(s);
                writer.Flush();
            }
        }
    });
}


text:
Q: Efficiently Map Extension string to Icon URL I have an ASP.NET web application hosted on a CMS(sharepoint 2013) that has built in search.
When running a file query with search, the only indication of the file type is an extension string, formatted without a period "PNG" or "JPG"
I do not get a file back, I just get metadata describing the file. To be clear, I do not get any MIME types or file objects, I JUST get an extension string.
I looked around the site for a question like this, and I don't see one.
It seems like there could be some sort of method that returns a string, and takes a string input in its signature, and searches through an object collection of some type, as follows:
FINAL RESULT:
static class FileIcons
{
    static public string PDF = string.Format("{0}", SPContext.Current.Site.ServerRelativeUrl + "_layouts/15/monkeysphere/images/icons/pdf.png");
    static public string Word = string.Format("{0}", SPContext.Current.Site.ServerRelativeUrl + "_layouts/15/monkeysphere/images/icons/word.png");
    static public string Generic = string.Format("{0}", SPContext.Current.Site.ServerRelativeUrl + "_layouts/15/monkeysphere/images/icons/file.png");

    static private Dictionary<String, String> IconUrls = new Dictionary<String,String>()
                        {
                            {"JPG", Picture},{"JPEG", Picture},{"GIF", Picture},{"PNG", Picture},
                            {"PDF", PDF},{"DOC", Word},{"DOCX", Word},{"XLS", Excel},{"XLSX", Excel},{"PPT", PowerPoint},{"PPTX", PowerPoint}
                        };

    static public string GetIconUrlFromExtension(string extension)
    {
        var formattedExtension = extension.Trim().Replace(".","").ToUpper();
        if (string.IsNullOrEmpty(extension) || !IconUrls.ContainsKey(formattedExtension))
            return Generic;
        return IconUrls[formattedExtension];
    }
}

A: I think a Dictionary would be a better option. Something like this:
public static class IconUrls {
    static Dictionary<string, string> _extensions;
    static string DefaultUrl = "~/siteroot/images/icons/genericicon.png";

    static IconUrls {
        extensions = new Dictionary<string, string>() {
            { "JPG", "~/siteroot/images/icons/jpegicon.png" },
            { "JPEG", "~/siteroot/images/icons/jpegicon.png" }
        }
    }

    public static Dictionary<string, string> Extensions {
        get {
            return _extensions;
        }
    }

    public static string GetIconUrl(string extension) {
    {
        if(string.IsNullOrEmpty(extension) || !_dictionary.ContainsKey(extension.Trim().ToUpper()))
            return DefaultUrl;
        return _extensions[extension.Trim().ToUpper()];
    }
}

You could also load the mappings from a configuration file so as not to hard code them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pandas lookup by different columns (one at a time) Table 1:- this my main table with formatted one
[Table 1][1]
Table1 = pd.DataFrame({'NEWLSCasGambIN':["N  ('0','')=No/Unknown",
                                         "N ('0','')=No/Unknown",
                                         "N  ('0','')=No/Unknown",
                                         "N  ('0','')=No/Unknown",
                                         "N  ('0','')=No/Unknown"],
                        'NEWLSBibDevIN':["N  ('0','')=No/Unknown",
                                         "N  ('0','')=No/Unknown",
                                         "N  ('0','')=No/Unknown",
                                         "N             ('1','Y') = Yes",
                                         "N  ('0','')=No/Unknown"],
                        'ADVNTG_MARITAL_STAT':["Q   <'2'> = 1+Sngl",
                                               "Q   <'2'> = 1+Sngl",
                                               "Q   <'2'> = 1+Sngl",
                                               "Q   <'1'> = 1+Marrd",
                                               "Q   <'2'> = 1+Sngl"],
                        'ADVTG_TRGT_INC':["Q   <'5'> =$40-$49K",
                                          "Q   <'6'> =$50-$74K",
                                          "Q   <'2'> =$15-$19K",
                                          "Q   <'7'> =$75-$99K",
                                          "Q   <'1'> =      < $15K"]})

Table 2:-[Table 2 :-][2] my mapping table. i need to use this table mapping to produced the finalout table.
Table2 = pd.DataFrame({'FLDNAME':["N  ('0','')=No/Unknown","N             ('1','Y') = Yes","N  ('0','')=No/Unknown","N             ('1','Y') = Yes",
                                  "Q   <'3'> = Mrrd N Sngl","Q   <'2'> = 1+Sngl","Q   <'1'> = 1+Marrd","Q   <'D'> =>$250K","Q   <'C'> =$200-$249K",
                                  "Q   <'B'> =$175-$199K","Q   <'A'> =$150-$174K","Q   <'9'> =$125-$149K","Q   <'8'> =$100-$124K","Q   <'7'> =$75-$99K",
                                  "Q   <'6'> =$50-$74K","Q   <'5'> =$40-$49K","Q   <'4'> =$30-$39K","Q   <'3'> =$20-$29K","Q   <'2'> =$15-$19K",
                                  "Q   <'1'> =      < $15K"],
                        'NEWBIN':[2, 1, 2, 1, 1, 3, 2, 2, 1, 2, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4,],
                        'VARNAME':["NEWLSCasGambIN", "NEWLSCasGambIN", "NEWLSBibDevIN", "NEWLSBibDevIN", "ADVNTG_MARITAL_STAT",
                                   "ADVNTG_MARITAL_STAT", "ADVNTG_MARITAL_STAT", "ADVTG_TRGT_INC", "ADVTG_TRGT_INC", "ADVTG_TRGT_INC",
                                   "ADVTG_TRGT_INC", "ADVTG_TRGT_INC", "ADVTG_TRGT_INC", "ADVTG_TRGT_INC", "ADVTG_TRGT_INC", "ADVTG_TRGT_INC",
                                   "ADVTG_TRGT_INC", "ADVTG_TRGT_INC", "ADVTG_TRGT_INC", "ADVTG_TRGT_INC",]})
Table2

Final Output: this is my final output i will get after mapping table1 and table2. how can i achieve this final out. pasted the DataFrame code for each table.
[Final Output][3]
 finaloutput = pd.DataFrame({'NEWLSCasGambIN':[2,2,2,2,2],
                             'NEWLSBibDevIN':[2,2,2,1,2],
                             'ADVNTG_MARITAL_STAT':[3,3,3,2,3],
                             'ADVTG_TRGT_INC':[3,3,4,3,4]})

Example:-
Table 1:-
NEWLSCasGambIN
N  ('0','')=No/Unknown
N  ('0','')=No/Unknown
N  ('0','')=No/Unknown
N  ('0','')=No/Unknown
N  ('0','')=No/Unknown

    Table2 consists of element mapping of  NEWLSCasGambIN
    FLDNAME                      | NEWBIN      |      VARNAME
    N  ('0','')=No/Unknown       |   2         |      NEWLSCasGambIN
    N             ('1','Y') = Yes|   1         |      NEWLSCasGambIN

    Final output :-
    NEWLSCasGambIN
    2
    2
    2
    2
    2

Thanks in advance.
[1]: https://i.stack.imgur.com/wuycI.png
[2]: https://i.stack.imgur.com/6vbJU.png
[3]: https://i.stack.imgur.com/PVTeL.png

A: Here's a solution:
df = pd.merge(Table1.reset_index().melt(id_vars="index"),
              Table2,
              left_on = ["variable", "value"],
              right_on = ["VARNAME", "FLDNAME"])

res = pd.pivot_table(df, index = "index", columns="VARNAME", values="NEWBIN")
print(res)

The output is:
VARNAME  ADVNTG_MARITAL_STAT  ADVTG_TRGT_INC  NEWLSBibDevIN  NEWLSCasGambIN
index
0                          3               3              2               2
1                          3               3              2               2
2                          3               4              2               2
3                          2               3              1               2
4                          3               4              2               2

(Note that there's a typo in one of the values of Table1)


text:
Q: iframe or object load function not working I want to show loading icon until pdf is loaded into the webpage.I have pasted what I have tried but loading icon keeps on displaying even the pdf is loaded fully. So, I concluded $iFrame.load(function() doesn't trigger anything. Got this code from JSFiddle. But in JSFiddle it is working.

A: I need to do an additional check for caches files (who fired the event, just before added an event handler listening for it). I tried the following jquery and it worked fine.
 $iFrame.on('load', function() {
  $('h3').html('PDF loaded...');
}).each(function() {
  if(this.complete) $(this).load();
});


text:
Q: Linear mapping on a Banach space that composition is bounded Let X,Y and Z be Banach spaces. Suppose $F\subset B(X,Y)$ has the property that $Tx=0$ for all $T\in F\implies x=0$. If $S:Z\rightarrow X$ is a linear mapping such that $TS\in B(Z,Y)$ for all $T\in F$, show that $S\in B(Z,X)$.
I have worked out a way below: If a linear functional is bounded, then it is continuos at 0. Then we assume that it is not bounded, then there is a sequence $\{x_n\}$ converges to 0 that $S(x_n)$ doesn't converges to 0. But $TS(x_n)$ converges to 0 implies that $s(x_n)$ converges to 0 by the condition it provided for F. This is a contradiction. However, I didn't apply X,Y and Z are complete. So what's wrong with my proof? And how to produce a correct proof?


text:
Q: Turn a string into list elements I have a string array returned from a database that needs parsing:
x = "[SD, 1G, 2G, 3G+]"
If they were integers I could do:
json.loads(x) and return a list of elements, however due to them being characters I can't.
Is there an easy implementation for this?
desired output: ['SD', '1G', '2G', '3G+'] (type: list)

A: You can use str.split() assuming that you are sure there will never be any surrounding whitespace:
>>> x = "[SD, 1G, 2G, 3G+]"
>>> xs = x[1:-1].split(", ")
>>> xs
['SD', '1G', '2G', '3G+']

If there is a possibility for that you could call str.strip() on x beforehand:
>>> x = " [SD, 1G, 2G, 3G+]   "
>>> xs = x.strip()[1:-1].split(", ")
>>> xs
['SD', '1G', '2G', '3G+']

A: What about just use yaml:
(You need pip install pyyaml)
>>> import yaml
>>> s = "[SD, 1G, 2G, 3G+]"
>>> yaml.safe_load(s)
['SD', '1G', '2G', '3G+']


text:
Q: How to move cell in tableViewCell with animation with usage of swipe action using: objective-C
I have a tableView with rows. I want that user can move cell a little aside and additional action shown to him.
What was done:
Currently create separately table in xib file and cell in xib file.
Cell is very simple

I want to move viewWIthLabel.
In cell class file for using animation I use next code
- (void)awakeFromNib
{
    UISwipeGestureRecognizer * leftGestrudeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeft:)];
leftGestrudeRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    UISwipeGestureRecognizer * rightGestrudeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRight:)];
rightGestrudeRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
[self addGestureRecognizer:rightGestrudeRecognizer];
[self addGestureRecognizer:leftGestrudeRecognizer];
}

and actions:
- (IBAction)swipeLeft:(id)sender{
NSLog(@"swipeL");
[UIView animateWithDuration:0.5 animations:^{
    self.viewWIthLabel.frame = CGRectMake(-100, 0, self.viewWIthLabel.frame.size.width, self.viewWIthLabel.frame.size.height);
} ];
}

 - (IBAction)swipeRight:(id)sender{
NSLog(@"swipeR");
[UIView animateWithDuration:.5 animations:^{
    self.viewWIthLabel.frame = CGRectMake(0, 0, self.viewWIthLabel.frame.size.width, self.viewWIthLabel.frame.size.height);
}];
}

So idea to swipe the cell and move it with animation for some distance to show a hidden button.
Result of this code - almoust like I want:

But if you start to scroll the tableView you can get duplicates of "swiped cells" in random (depending on scrolling speed) positions:

Any idea why it happened?

A: You might have to clear/reset the swiped state of the cell in – tableView:cellForRowAtIndexPath:. Since the cells get re-used (I am assuming you are doing that as would be required for good performance of the tableview). Probably something like this -
 self.viewWIthLabel.frame = CGRectMake(0, 0, self.viewWIthLabel.frame.size.width, self.viewWIthLabel.frame.size.height);


text:
Q: How to count the number of times in a pandas df that the sum of consecutive values crosses a threshold? I have a data frame that consists of a time-series of integers.  I'm trying to group the data frame by year and then for each year count the number of times that the sum of the absolute value of consecutive entries with the same sign is greater than or equal to 5.
>>> import pandas as pd
>>> l  = [1, -1, -4, 2, 2, 4, 5, 1, -3, -4]
>>> idx1 = pd.date_range('2019-01-01',periods=5)
>>> idx2 = pd.date_range('2020-01-01',periods=5)
>>> idx = idx1.union(idx2)
>>> df = pd.DataFrame(l, index=idx, columns=['a'])
>>> df
            a
2019-01-01  1
2019-01-02 -1
2019-01-03 -4 \\ 2019 count = 1: abs(-1) + abs(-4) >= 5
2019-01-04  2
2019-01-05  2
2020-01-01  4
2020-01-02  5 \\ 2020 count = 1: abs(4) + abs(5) + abs(1) = 10 >=5
2020-01-03  1
2020-01-04 -3
2020-01-05 -4 \\ 2020 count = 2: abs(-3) + abs(-4) = 7 >= 5

The desired output is:
2019 1
2020 2

My approach to solve this problem is to chain groupby and apply.  Below are the implementations of the functions I created to pass to groupby and apply respectively.
>>> def get_year(x):
        return x.year

>>> def count(group, t=5):
        c = 0 # counter
        s = 0 # sum of consec vals w same sign
        for i in range(1,len(group)):
            if np.sign(group['a'].iloc[i-1]) == np.sign(group['a'].iloc[i]):
                if s == 0:
                    s = group['a'].iloc[i-1] + group['a'].iloc[i]
                else:
                    s += group['a'].iloc[i]
                if i == (len(group) -1):
                   return c + 1
            elif (np.sign(group['a'].iloc[i-1]) != np.sign(group['a'].iloc[i])) and (abs(s) >= t):
    #if consec streak of vals w same sign is broken and abs(s) >= t then inc c and reset s
                c += 1
                s = 0
            elif (np.sign(group['a'].iloc[i-1]) != np.sign(group['a'].iloc[i])) and (abs(s) < t):
    #if consec streak of vals w same sign is broken and abs(s) < t then reset s
                s = 0
     return c

>>> by_year = df.groupby(get_year)
>>> by_year.apply(count)
2019 1
2020 2

My question is:
Is there a more "pythonic" implementation of the above count function that produces the desired result but doesn't rely on for loops?


text:
Q: Separating Names In Excel I have a list of 60K names. I need to separate them into different worksheets based on their length.
I have been doing it using normal way using len() formula, filter them and copy paste them to separate sheet.
Is there any VBA code which I can use to do it ?
Example list
Name     Length
EMMALINE    8
EMMIE       5
EMMER       5
AMMIE       5
EMMY        4
AMMA        4
EMMELINE    8
EMMALEE     7
EMMALOU     7

A: This is just a sample approach.  First name the destination sheets as follows:

Then run this macro:
Sub croupier()
    Dim N As Long, i As Long, s As String, M As Long

    Sheets("Sheet1").Select
    N = Cells(Rows.Count, 1).End(xlUp).Row
    For i = 2 To N
        v = Cells(i, 1).Value
        s = "s" & Len(v)
        With Sheets(s)
            M = .Cells(Rows.Count, 1).End(xlUp).Row + 1
            .Cells(M, 1) = v
        End With
    Next i
End Sub


text:
Q: Can I define conditionals in a unit and use them in other units? I am working on a large unit, the unit got so large that I decided to split it into 3 units. Let's say these unit names are Main, Common, and Objects. The Main unit uses both the other two units, and the Objects unit also uses the Common unit. There is code in all 3 units which needs to refer to these conditionals.
The problem is, no matter which of the 3 units I define these conditionals in, the other 2 units don't see them. I certainly don't want to copy them in all 3 units. I also don't want to define them in the project, because these units will be used by multiple projects, in which case all projects using this shouldn't care about the conditionals.
Can I define these conditionals in a way that all 3 units will see them, without defining them in the project?

A: Your only option, for conditional defines, is to put them in a .inc file which you then include in all three units.
However, conditional defines, and $IFDEF are not the only way to achieve conditional compilation. You might consider using a boolean constant instead of a conditional. So long as it is visible in all three units, you can use $IF rather than $IFDEF.
{$IF MyConstant}
  ....
{$IFEND}

Or, starting in XE3, you can terminate the {$IF} with {$ENDIF}.
Personally I tend to favour this latter approach when trying to compile conditionally and don't want the condition to have global scope.


text:
Q: Excel VBA End User Selecting a Chart Object I would like to generate some code that allows an end user to select one of many charts from a sheet, after which I will do a bunch of manipulation based on that selection.
I am looking for something similar to the Application.Inputbox Type:=8 that allows for an object selection instead of a range selection.
Am I asking to much of humble old VBA??

A: It's a lot easier to select the chart first, then run code on the selected chart(s), than it is to pause the code and try to select the chart(s) from within the code.
But it can be done.
You need a userform, called F_ChartChooser with two buttons, btnCancel and btnContinue.
The code in the F_ChartChooser module:
Option Explicit

Private Sub btnCancel_Click()
  CancelProcedure
End Sub

Private Sub btnContinue_Click()
  ContinueProcedure
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
  ' so clicking red X doesn't crash
  If CloseMode = 0 Then
    Cancel = True
    CancelProcedure
  End If
End Sub

The code in the regular module consists of a main procedure which must get the chart(s) from the user. It has to call the userform modelessly so the user can select charts in the worksheet. This means the code continues running while the form is displayed, so the thing to do is end the sub when the userform is called.
Based on what happens with the userform, the code either continues with CancelProcedure or with ContinueProcedure. Here's the code:
Option Explicit

Dim mfrmChartChooser As F_ChartChooser

Sub Main()
  ' code here

  ' need to select chart(s) here
  Application.Goto ActiveCell
  Set mfrmChartChooser = New F_ChartChooser
  mfrmChartChooser.Show vbModeless
End Sub

Sub CancelProcedure()
  Unload mfrmChartChooser
  Set mfrmChartChooser = Nothing
  MsgBox "User canceled.", vbExclamation
End Sub

Sub ContinueProcedure()
  Unload mfrmChartChooser
  Set mfrmChartChooser = Nothing
  If Not ActiveChart Is Nothing Then
    ' do something with active chart

    ' this demo is announcing that it was selected
    MsgBox """" & ActiveChart.ChartTitle.Text & """ was selected.", vbExclamation
    ' end of demo code
  ElseIf TypeName(Selection) = "DrawingObjects" Then
    Dim sh As Shape
    Dim vCharts As Variant
    Dim nChart As Long
    ReDim vCharts(0 To nChart)
    For Each sh In Selection.ShapeRange
      If sh.HasChart Then
        ' do something here with each chart

        ' this demo is building a list of selected charts
        nChart = nChart + 1
        ReDim Preserve vCharts(0 To nChart)
        vCharts(nChart) = sh.Chart.ChartTitle.Text
        ' end of demo code
      End If
    Next

    ' this demo now is showing the list of selected charts
    If nChart = 0 Then
      MsgBox "No chart selected.", vbExclamation
    Else
      If nChart = 1 Then
        MsgBox """" & vCharts(nChart) & """ was selected.", vbExclamation
      Else
        Dim sPrompt As String
        sPrompt = nChart & " charts selected:" & vbNewLine & vbNewLine
        Dim iChart As Long
        For iChart = 1 To nChart
          sPrompt = sPrompt & """" & vCharts(iChart) & """" & IIf(iChart < nChart, vbNewLine, "")
        Next
        MsgBox sPrompt, vbExclamation
      End If
    End If
    ' end of demo code
  Else
    ' do nothing because no chart was selected

    ' this demo is announcing that nothing was selected
    MsgBox "No chart selected.", vbExclamation
    ' end of demo code
  End If
End Sub

The CancelProcedure and ContinueProcedure routines above have excess code in them just to help with the demo. In real code I would streamline them like this, probably not even bother to notify the user when nothing was selected (they know they canceled, right?), and just process the selected chart(s):
Sub CancelProcedure()
  Unload mfrmChartChooser
  Set mfrmChartChooser = Nothing
End Sub

Sub ContinueProcedure()
  Unload mfrmChartChooser
  Set mfrmChartChooser = Nothing
  If Not ActiveChart Is Nothing Then
    ' do something with active chart
    ProcessChart ActiveChart
  ElseIf TypeName(Selection) = "DrawingObjects" Then
    Dim sh As Shape
    Dim vCharts As Variant
    Dim nChart As Long
    ReDim vCharts(0 To nChart)
    For Each sh In Selection.ShapeRange
      If sh.HasChart Then
        ' do something here with each chart
        ProcessChart sh.Chart
    Next
End Sub


text:
Q: Reversing a Dictionary I've tried reading everywhere, and can't seem to find the answer that works...
The exercise is to create a function that takes a number (0-6) and returns the corresponding day of the week, with Sunday numbered as 0.  I did that using a dictionary.  Now it wants the other way around, but everything I've tried doesn't seem to work except typing it in.  Here's my current code started for reverse:
dayDict = {0: 'Sunday', 1:'Monday', 2:'Tuesday', 3:'Wednesday',
           4:'Thursday', 5:'Friday', 6:'Saturday'}

def day_num(dayName):
    if dayName == "Sunday":
        return dayDict[dayName]

print(day_num("Sunday"))

It would continue with an elif for each day.

A: A reverse dictionary is a simple line of code ... once you know how.
day_num = {value: key for key, value in dayDict.iteritems()}

A: dayNumDict = {v:k for k,v in dayDict.iteritems()}
def day_num(dayName):
    return dayNumDict[dayName]

If you are using Python 3.x:
dayNumDict = {v:k for k,v in dayDict.items()}
def day_num(dayName):
    return dayNumDict[dayName]

A: you can also built your dict with both the day and the number in it, like this
>>> days=['Sunday','Monday','Tuesday', 'Wednesday','Thursday','Friday', 'Saturday']
>>> dayDict=dict()
>>> for n,day in enumerate(days):
        dayDict[n]=day
        dayDict[day]=n

>>> dayDict
{0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday',
'Tuesday': 2, 'Thursday': 4, 'Friday': 5, 'Wednesday': 3, 'Saturday': 6, 'Sunday': 0, 'Monday': 1}
>>>
>>> dayDict[0]
'Sunday'
>>> dayDict["Friday"]
5
>>>

A: So from what it sounds like, you want a new function that takes in Sunday-Saturday and returns the corresponding numerical value.
The only method I can think of to do this is to use a loop and test all of the dictionary options like so:
def getDayNumber(day):
   for i in range(len(<dictionary>)):
       if <dictionary>[i] == day.captialize():
           return i

A: Since you've already got a bunch of dictionary answers.... In your specific case it seems like this would be easier-solved with an Enum.
from enum import IntEnum

DOW = IntEnum("DOW", "Sunday Monday Tuesday Wednesday Thursday Friday Saturday")

DOW.Sunday == 1  # True
DOW(1)  # <DOW.Sunday: 1>


text:
Q: How can I open a file that is stored in a virtual machine from host? I'm running Red Hat Linux on VMWare installed on Windows 7 and I want to be able to open a text file that is stored on the VM from Windows. How can I achieve this?
Thanks

A: I got it to work by doing this:
On the host:
- On VMPlayer go to VM Settings
- Go to the Options tab then Shared Folders
- Pick Always Enabled
- Add a new Folder
Inside the VM:
- Go to /mnt/hgfs/
The files inside the folder will be shared!
Also I think you need root access on VM to copy to the folder.
You might also need to change the Network Adapter to NAT in VM Settings under Hardward tab.
Hope this helps someone!


text:
Q: Selection disappears when action button is clicked in adaptive cards I am using Input Choice List but when I click on submit button,the selected value from the choicelist disappears in the card.
Adaptive Card version: 1.0
I am trying to post this card to Microsoft Teams.

A: As mentioned in my answer to the other question, this is expected behavior in Microsoft Teams. You can use the workaround I provided there, or you can ask Teams to change this behavior in their builtin feedback system:


text:
Q: TransferState some part of resolved data is not present on client side, though it's present on the server app.routing.module:
{
  path: '',
  component: IndexComponent,
  resolve: { videos: GetVideosResolver },
},

GetVideosResolver:
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const VIDEOS_KEY = makeStateKey('videos');

if (this.transferState.hasKey(VIDEOS_KEY)) {
  const videos = this.transferState.get(VIDEOS_KEY, null);
  this.transferState.remove(VIDEOS_KEY);
  return of(videos);
} else {
  return this.http.get(`${environment.api_url}/video/list`).pipe(
    tap((videos: any) => {
      if (isPlatformServer(this.platformId)) {
        this.transferState.set(VIDEOS_KEY, videos);
      }
    }),
    catchError((err) => of())
  );
}

}
console.log(this.route.shapshot.data.videos) prints correct resolved data in my IDE console, though in browser console some crucial object is missing. It seems angular has some kind of restriction on how large of an object you can resolve in one time. How do I bypass that?

A: Got it working.
this.transferState.set(VIDEOS_KEY, { ...videos });


text:
Q: How to remove the last digit after the some symbols in SQL? For input

A.B.1.23

I want output

A.B.1

A: In SQL Server, you can use:
select left(col, len(col) - charindex('.', reverse(col)))

This is dynamic and simply assumes that there is at least on '.' in the column.

A: See if this helps..
DECLARE @ AS VARCHAR(100) = 'A.B.1.23'
SELECT REVERSE(SUBSTRING(REVERSE(@),CHARINDEX('.',REVERSE(@),0)+1,LEN(REVERSE(@))))

A: You can use this also :
DECLARE @ AS VARCHAR(100) = 'A.B.1.23'
select substring(@, 1, len(@) - charindex('.', reverse(@)))


text:
Q: Using Dagger for dependency injection on constructors So, I'm currently redesigning an Android app of mine to use Dagger.  My app is large and complicated, and I recently came across the following scenario:
Object A requires a special DebugLogger instance which is a perfect candidate for injection.  Instead of passing around the logger I can just inject it through A's constructor.  This looks something like this:
class A
{
    private DebugLogger logger;

    @Inject
    public A(DebugLogger logger)
    {
        this.logger = logger;
    }

    // Additional methods of A follow, etc.
}

So far this makes sense.  However, A needs to be constructed by another class B.  Multiple instances of A must be constructed, so following Dagger's way of doing things, I simple inject a Provider<A> into B:
class B
{
    private Provider<A> aFactory;

    @Inject
    public B(Provider<A> aFactory)
    {
        this.aFactory = aFactory;
    }
}

Ok, good so far.  But wait, suddenly A needs additional inputs, such as an integer called "amount" that is vital to its construction.  Now, my constructor for A needs to look like this:
@Inject
public A(DebugLogger logger, int amount)
{
...
}

Suddenly this new parameter interferes with injection.  Moreover, even if this did work, there would be no way for me to pass in "amount" when retrieving a new instance from the provider, unless I am mistaken.  There's several things I could do here, and my question is which one is the best?
I could refactor A by adding a setAmount() method that is expected to be called after the constructor.  This is ugly, however, because it forces me to delay construction of A until "amount" has been filled in.  If I had two such parameters, "amount" and "frequency", then I would have two setters, which would mean either complicated checking to ensure that construction of A resumes after both setters are called, or I would have to add yet a third method into the mix, like so:
(Somewhere in B):

A inst = aFactory.get();
inst.setAmount(5);
inst.setFrequency(7);
inst.doConstructionThatRequiresAmountAndFrequency();

The other alternative is that I don't use constructor-based injection and go with field-based injection.  But now, I have to make my fields public.  This doesn't sit well with me, because now I am obligated to reveal internal data of my classes to other classes.
So far, the only somewhat elegant solution I can think of is to use field-based injection for providers, like so:
class A
{
    @Inject
    public Provider<DebugLogger> loggerProvider;
    private DebugLogger logger;

    public A(int amount, int frequency)
    {
        logger = loggerProvider.get();
        // Do fancy things with amount and frequency here
        ...
    }
}

Even still, I'm unsure about the timing, since I'm not sure if Dagger will inject the provider before my constructor is called.
Is there a better way?  Am I just missing something about how Dagger works?

A: What you are talking about is known as assisted injection and is not currently supported by Dagger in any automatic fashion.
You can work around this with the factory pattern:
class AFactory {
  @Inject DebugLogger debuggLogger;

  public A create(int amount, int frequency) {
    return new A(debuggLogger, amount);
  }
}

Now you can inject this factory and use it to create instances of A:
class B {
  @Inject AFactory aFactory;

  //...
}

and when you need to create an A with your 'amount' and 'frequency' you use the factory.
A a = aFactory.create(amount, frequency);

This allows for A to have final instances of the logger, amount, and frequency fields while still using injection to provide the logger instance.
Guice has an assisted injection plugin which essentially automates the creation of these factories for you. There have been discussion on the Dagger mailing list about the appropriate way for them to be added but nothing has been decided upon as of this writing.

A: What Jake's post says is perfectly true.  That said, we (some of the Google folk who work with Guice and Dagger) are working on an alternative version of "assisted injection" or automatic-factory generation which should be usable by Guice or Dagger or stand-alone - that is, it will generate factory class source code for you.  These factory classes will (if appropriate) be injectable as any standard JSR-330 class would.  But it is not yet released.
Pending a solution like this, Jake Wharton's approach is advisable.

A: You're having a problem because you are mixing injectables and non injectables in your constructor. The general rules for injection that will save you tons of heartache and keep your code clean are:

*

*Injectables can ask for other injectables in their constructor, but not for newables.

*Newables can ask for other newables in their constructor but not for injectables.
Injectables are service type objects, ie objects that do work such as a CreditCardProcessor, MusicPlayer, etc.
Newables are value type objects such as CreditCard, Song, etc.

A: Jake's post is great, but there is more simple way. Google created AutoFactory library for creating factory automatically at compile time.
First, create class A with @AutoFactory annotation and @Provided annotation for injecting arguments:
@AutoFactory
public class A {

    private DebugLogger logger;

    public A(@Provided DebugLogger logger, int amount, int frequency) {
        this.logger = logger;
    }
}

Then library creates AFactory class at compile time. So you need just inject the factory to a constructor of B class.
public class B {

    private final AFactory aFactory;

    @Inject
    public B(AFactory aFactory) {
        this.aFactory = aFactory;
    }

    public A createA(int amount, int frequency) {
        return aFactory.create(amount, frequency);
    }
}

A:
I just want to add that years passed after this question has been posted and now there is a library called
  AssistedInject which has been created by Jake and friends at Square,
  to solve the exact same problem and is fully compatible with Dagger 2.

You can find it here: https://github.com/square/AssistedInject

A: Dagger 2 now has support for assisted injection which should help solve your usecase.
https://dagger.dev/dev-guide/assisted-injection
You can wrap your class like this:
@AssistedInject
public A(DebugLogger logger, @Assisted int amount)
{
...
}

Create a factory for this class.
@AssistedFactory
public interface MyDataFactory {
  A create(int amount);
}

and in your client, you can use:
@Inject MyDataFactory dataFactory;

  void setupA(int amount) {
    A a = dataFactory.create(config);
    // ...

  }


text:
Q: Why can't I select "update after install" in clickonce WPF app? I have published my .net 5.0 WPF application to a UNC network directory. From there I ran "setup.exe" to install the appliation on my computer. Then when I ran the application it showed the "verifying application requirements" dialog which then disappeared without launching the application.
Running the application directly from the exe from the UNC path works fine. I have investigated this and it looks like it might be a case of this issue here:
ClickOnce Application Won't Open
Which points to a solution of selecting thee "after the application starts" option in the "Application Updates" window. The problem is I can't select this. Clicking the radio button "After the application starts" shown in the image below does nothing:

Why can't I select this?

A: It turns out that the "After the application starts" option is no longer supported in after .NET Core 3.0:
https://learn.microsoft.com/en-us/visualstudio/deployment/choosing-a-clickonce-update-strategy?view=vs-2019

For .NET 3.1 and newer applications, checking updates before the application starts is the only update option supported.

This doesn't help me resolve the issue of why my clickonce application won't start but at least I know why this option is unavailable.


text:
Q: How to create .htpasswd file for nginx using chef I am new to chef and I am trying to generate a .htpasswd file to store user hash, I went through some links
but this is not helping.
I need ngnix to secure Kibana and I want to generate a password for users using openssl. I have created a template file as .htpasswd_temp.erb
it looks like this:
<% @kibana_user.each do |user| %>
<%= user %>:

<% end %>

and my recipe is:
kibana_configs = node['kibana']['kibana_auth']
template 'path/to/.htpasswd' do
source '.htpasswd_temp.erb '
variables(
  kibana_user: kibana_configs['kiba_user']
)
end

I have created one role file where I have defined all default attributes(including kiba_user).
Above code adds users to .htpasswd file but I have no idea how to generate password using openssl. Openssl command works fine using execute resource but execute resource does not work inside template resource, thus does not get reflected in .htpasswd file.I am really confused. Thank so much for your help ^^

A: the following recipe snippet might by handy for you...
it assumes that you are familiar with encrypted data bag and that you have stored your credentials in a data bag named creds, with encrypted item named nginx that holds username and password keys.
htpassed_file = '/root/.htpasswd'

chef_gem 'htauth'

ruby_block 'create .htpasswd' do
  block do
    require 'htauth'
    creds = data_bag_item('creds', 'nginx')
    HTAuth::PasswdFile.open(htpassed_file, HTAuth::File::CREATE) do |pf|
      pf.add(creds['username'], creds['password'])
    end
    FileUtils.chmod 0o600, htpassed_file
  end
end

A: You can use recipe for that as well https://github.com/redguide/htpasswd with combination of data bags to encrypt your password (as well as username).
htpasswd "/etc/nginx/htpassword" do
  user "foo"
  password "bar"
end


text:
Q: Swift Line Command : xcrun swiftc I'm using the swift line command to comiple my code Client.Swift . when i compile i'm getting the object Client.o
Now, i would to link the Client .o with my static library libjjeromqi386.a in order to generate the excutable app. To do this i enter this line command :
$ xcrun swiftc -sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.3.sdk -o app Client.o -target i386-apple-ios8.3 -import-objc-header /Users/systems/pMaster/ProjetXcode/SimpleSwift/Bridging-Header.h -L/Users/systems/pMaster/ProjetXcode/Librairies -Xcc -I/Users/systems/pMaster/ProjetXcode/j2objc-0.9.6/include -Xcc -I/Users/systems/pMaster/ProjetXcode/jjeromqObjC/src/main -Xcc -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
i get the error :
Undefined symbols for architecture i386:
  "_OBJC_CLASS_$_OrgZeromqZMQ", referenced from:
      __TMaCSo12OrgZeromqZMQ in Client.o
  "_OBJC_CLASS_$_OrgZeromqZMQ_Context", referenced from:
      __TMaCSo20OrgZeromqZMQ_Context in Client.o
  "_OBJC_CLASS_$_OrgZeromqZMQ_Socket", referenced from:
      __TMaCSo19OrgZeromqZMQ_Socket in Client.o
  "_OrgZeromqZMQ_contextWithInt_", referenced from:
      __TFC6Client4main6ClientfS0_FT_T_ in Client.o
ld: symbol(s) not found for architecture i386
Any help please ?
You should know that the library libjjeromqi386 is i386 architecture, as the client.o too
Thanks in advance


text:
Q: Setear de forma dinamica un element REf angular Dentro de un for, tengo un input a los cuales los quiero poner una referencia elementRef para usarlos mas tarde en TS, como puedo poner dinámicamente el # en vez del [id] con los valores que me genera el for?
Actual:
    <div *ngFor="let item of items" >
      <input type="radio"  [id]="superId+ '_' + item.value" />
    </div>

Deseado:
<div *ngFor="let item of items" >
   <input type="radio"  #'_' + item.value />
</div>

Coponente TS:
 @ViewChild('_myValor') myElementoDeReferencia: ElementRef;

A: ¿Por qué no con el ID?
Lo que yo haría es agregar a cada input un id, puede ser un label que tenga el item.
Digamos que se llama title. Entonces:
<div *ngFor="let item of items" >
 <input type="radio" [id]="item.title" #input/>
</div>

Luego en el ts
@ViewChildren('input') inputsArray: QueryList<ElementRef>

Y para obtener el input que necesitas, ya depende del momento en que lo vas a seleccionar.
Si es con un evento, por ejemplo. focus, entonces:
<div *ngFor="let item of items" >
 <input type="radio" [id]="item.title" #input (focus)="getElementRef(item)"/>
</div>

Y en el ts,
getElementRef(item){
 let toArray = this.inputsArray.toArray()
 let ref: ElementRef<HTMLInputElement> = toArray.find(el => el.nativeElement.id == item.title)
}

Y así obtendrías la referencia.
Espero te sirva.
Te dejo enlace para que veas cómo funciona.
https://stackblitz.com/edit/angular-ivy-wzpunr?embed=1&file=src/app/app.component.ts


text:
Q: Return integer in function String How return integer in function String
It's my code
public class Utils {
    public static String type(String s){
        if(UraniumProtectMain.materialname){
            return s;
        } else {
            return Integer.parseInt(s); //<--- It's
        }
    }
}

A: Either return Object or return integer as String.

A: As you want to return both Integer and String, you can use return type as Object class,  because Object is super class of all classes and we can hold any type of value in Object variable.
public static Object type(String s){
    // code here
}

Now you can get the type of value return by type with the help of instanceOf method
if(Utils.type() instaceOf String)
{
    // code here
} else if(Utils.type() instanceOf Integer) {
    // code here
}

A: As User has suggested that you can return change method return type to object. But, apart from that you can also use either of

*

*String.valueOf(number) (my preference)

*Integer.toString(number)

to return integer as string and perform type check at method calling point


text:
Q: Webserver stop working after script with selenium I created a script in Python, which opens some website using Selenium, makes some actions and closes the site. If I launch by myself it works, but if I try to launch it using a php file then it works but after completion, the script webserver doesn't ask. I just can fix it by restarting Apache. Does anyone knows where is the problem?
php file
<?php
    $result = shell_exec('C:\\xampp\\htdocs\\project\\find.py');

    echo "
";
    echo $result;
    echo "
";
?>

python script
import sys
import selenium
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import unittest
import time

driver = webdriver.Chrome()

driver.get("http://smolensklib.ru/scripts_cut/zgate.exe?Init+souball.xml,simple.xsl+rus")

author = driver.find_element_by_name("TERM_1")
author.send_keys("Пушкин")

author = driver.find_element_by_name("TERM_2")
author.send_keys("Капитанская дочка")

button = driver.find_element_by_name("SEARCH")
button.click()

books = driver.find_elements(By.XPATH, '//a[text()="Детальная информация"]')

for book in books:
    print(book.get_attribute("href"))

driver.close()

A: Problem was solved after exchanging Chrome webdriver on Firefox webdriver


text:
Q: Where is the OpenSuSE server ISO for download? Which download is the "server" version for OpenSuSE?
Index of download.opensuse.org/distribution/openSUSE-current/iso/
[ICO]   Name    Last modified   Size    Metadata
[DIR]   Parent Directory        -
[ ] openSUSE-Leap-42.3-DVD-x86_64.iso   24-Jul-2017 17:08   4.3G    Details
[ ] openSUSE-Leap-42.3-DVD-x86_64.iso.sha256    24-Jul-2017 17:08   630     Details
[ ] openSUSE-Leap-42.3-DVD-x86_64.iso.torrent   25-Jul-2017 14:39   44K     Details
[ ] openSUSE-Leap-42.3-DVD.iso.torrent  25-Jul-2017 14:39   44K     Details
[ ] openSUSE-Leap-42.3-NET-x86_64.iso   24-Jul-2017 17:08   108M    Details
[ ] openSUSE-Leap-42.3-NET-x86_64.iso.sha256    24-Jul-2017 17:08   630     Details

I also went to the main SuSE site, but it everything was trial software.

A: Choose the openSUSE-Leap-42.3-DVD-x86_64.iso
When you will start the installation  process, it will ask you for Desktop Selection, there you can choose Minimal Server Selection (Text Mode)

Edit
There is also SUSE enterprise Linux Server, it can be used to install the OS headlessly but it isn't offered freely. They give a 30-day. You can try it on kvm.


text:
Q: Javascript: why do callback functions with global execution context have access to scoped variables? In the following code:
function test() {
    var x = 5 // scoped to test function
    console.log(this); // global object
    logCb(function(){
        console.log(this); // global object
        console.log(x);
    })
}

function logCb (cb) {
    console.log(this); // global object
    cb() // This still seems to execute within the test function scope? why...
}

test()

x is scoped to test, and this is where the callback function is defined. I would have expected line cb() to throw an error, as the logCb() function does not have access to the x variable.
However this is not the case. Why? It seems like references within the callback are created during assignment, and NOT during execution - which I guess makes sense if you consider hoisting - i.e. during compilation, is the callback function is hoisted to the top of 'test' and then assignment happens within test's scope?
I have read that execution is not the same as scope. In this article: http://ryanmorr.com/understanding-scope-and-context-in-javascript/, this sentence scope pertains to the variable access of a function when it is invoked and is unique to each invocation seems to imply that the callback is invoked from within the test function.
Because it seems to me that no matter where the callback function is invoked it would still be scoped to test.
I think my question is:
How is the callback function handled in terms of definition and then invocation when thinking about scope and execution context?

A:
How is the callback function handled in terms of definition and then
  invocation when thinking about scope and execution context?

A function scope is based on where it is physically present in the lexical environment
Explanation: The callback is lexically present in the function test(), so it will always try to find the value of this either within itself(if present) otherwise it will see its value in the outer environment (which is function test in this case)
The test function and LogCb function will follow the same practice. In this case the outer environment will be global

how does the engine keep track of scope separately to execution
  context?

Lexical Environment: Where something sits physically in the code you write.
Execution Context: A wrapper to help manage the code that is running.
Now in your code there are lot of lexical environments. Which one is currently running is managed via execution contexts. It can contain things beyond what you have written in your code.
Whenever execution context is created we have three things that are available to us:

*

*Global object (window) :Any variable or function in the global scope is linked to window object

*'this'

*Outer environment

So depending on which execution context is currently running, these things will vary as per where it is physically or lexically present in code. For example the outer environment for cb is the function test()

A: Scope is determined by where a function is created, not by where it is called.
The function you pass to logCb is created inside test, so it has access to test's scope.

A: When a function is called in  javascript , a context is passed to it.
The context can be one of the following ways

*

*using new , a temp object is created and it is passed as context to the function

*calling function via object a.getValue() . getValue gets the context a

*if none of the above 2 pass the global object ie window

A: Because of the closure.
Closure is the function with lexical environment.
Lexical environment means the collection of local variables and the references to its parents variables.
In your code you defined callback function inside the test function, the callback function will create a closure with lexical environment which contains reference to it's parent's variables.
By using this closure the function still can access the variable x.


text:
Q: Functional equation $\big(\frac{1}{x}-1\big)f(x)+\big(\frac{1}{x^{\phi-1}}-1\big)f(x^\phi)=1$
Consider the functional equation
  $$\Big(\frac{1}{x}-1\Big)f(x)+\Big(\frac{1}{x^{\phi-1}}-1\Big)f(x^\phi)=1$$
  where $\phi$ is the golden ratio. I'm looking for a continuous function $f:[0,1)\to \mathbb R^+$ with $f(0)=0$ satisfying this equation. I've shown that this function is unique, so if I can find a single elementary function satisfying it, then I've found the only solution meeting these requirements.
QUESTION: Can anyone find the function $f$ in closed form? I'm not interested in integral or series representations.

How I know there's a unique solution: To see why there is a unique continuous solution with $f(0)=0$, we can do a series of repeated substitutions into the original functional equation:
$$\Big(\frac{1}{x^\phi}-1\Big)f(x^{\phi})+\Big(\frac{1}{x^{(\phi-1)\phi}}-1\Big)f(x^{\phi^2})=1$$
$$\Big(\frac{1}{x^{\phi^2}}-1\Big)f(x^{\phi^2})+\Big(\frac{1}{x^{(\phi-1)\phi^2}}-1\Big)f(x^{\phi^3})=1$$
$$...$$
If we keep making the substitution $x\mapsto x^\phi$, we can treat this like a long system of equations in the variables $f(x),f(x^\phi),f(x^{\phi^2}),$ and so on. Through repeated substitution, we can solve for $f(x)$ in terms of $f(x^{\phi^n})$, which approaches $0$ as $n\to\infty$. The algebra is messy, but this leaves us with a different series representation for $f(x)$, showing that it is uniquely determined when we assume continuity and $f(0)=0$.
MOTIVATION: It turns out that the unique solution $f$ has the following series representation:
$$f(x)=\sum_{n=1}^\infty x^{n+(\phi-1)\lfloor n (\phi-1)\rfloor}$$
and I'm trying to find a closed-form of this series (if not in terms of $x$, at least at some special values of $x$).
It's a bit tricky to explain how I know $f$ satisfies this functional equation, but it can be proven from the following generalized identity:
$$\frac{1-x}{x}\sum_{n\ge 1}x^n y^{\lfloor n\alpha\rfloor}+\frac{1-y}{y}\sum_{n\ge 1}y^n x^{\lfloor n/\alpha\rfloor}=1$$
which holds for all $x,y\in (0,1)$ and positive irrational $\alpha$. The functional equation for $f$ follows by setting $y=x^{\phi-1}$ and $\alpha=\phi-1$.

A: $\left(\dfrac{1}{x}-1\right)f(x)+\left(\dfrac{1}{x^{\phi-1}}-1\right)f(x^\phi)=1$
$\left(\dfrac{1}{(e^x)^{\phi-1}}-1\right)f((e^x)^\phi)=\left(1-\dfrac{1}{e^x}\right)f(e^x)+1$
$(e^{-\phi x}-e^{-x})f(e^{\phi x})=(e^{-x}-e^{-2x})f(e^x)+e^{-x}$
$(e^{-\phi\phi^x}-e^{-\phi^x})f(e^{\phi\phi^x})=(e^{-\phi^x}-e^{-2\phi^x})f(e^{\phi^x})+e^{-\phi^x}$
$(e^{-\phi^{x+1}}-e^{-\phi^x})f(e^{\phi^{x+1}})=(e^{-\phi^x}-e^{-2\phi^x})f(e^{\phi^x})+e^{-\phi^x}$
$f(e^{\phi^{x+1}})=\dfrac{e^{-\phi^x}-e^{-2\phi^x}}{e^{-\phi^{x+1}}-e^{-\phi^x}}f(e^{\phi^x})+\dfrac{e^{-\phi^x}}{e^{-\phi^{x+1}}-e^{-\phi^x}}$


text:
Q: How to use Jackson to deserialize to list or value based upon JSON? I have a json in following format, where in key represents the attribute type and value represents the value of that attribute.
{ "attributes":
[
  {
    "key":"name",
    "value":"Archit"
  },
  {
    "key":"website",
    "value":"stackoverflow"
  },
  {
    "key":"languages",
    "value":[
              "python",
              "java",
              "c++"
            ]
  }
]
}

I am trying to map it to an following java object using jackson :
public class Attributes {
  List<Attribute> attributes;
}

public abstract class Attribute {
  String key;
}

public class SingleValuedAttribute extends Attribute{
  String value;
}

public class MultiValuedAttribute extends Attribute{
  List<String> value;
}

  ObjectMapper mapper = new ObjectMapper();
  Attributes attributes = mapper.readValue(new File(jsonFilePath), Attributes.class);

I tried having a look at polymorphic deserialization but that required type info in the json object, which doesn't exist in my json ?
Any tips on how to do this ?
PS:
I can't change the json format.
The list of keys is not bounded/limited.

A: I do not see the difference between SingleValuedAttribute and MultiValuedAttribute classes. SingleValuedAttribute class represents one element array. You could simplify your POJO classes hierarchy by deleting it.
Please, see below example how it could looks like:
import java.io.File;
import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonProgram {

    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

        File json = new File("/x/test.json");
        System.out.println(objectMapper.readValue(json, Attributes.class));
    }
}

class Attributes {

    private List<Attribute> attributes;

    //getters, setters
}

class Attribute {

    private String key;
    private List<String> value;

    //getters, setters
}

Above program prints:
[Attribute [key=name, value=[Archit]], Attribute [key=website, value=[stackoverflow]], Attribute [key=languages, value=[python, java, c++]]]


text:
Q: Is this a binary operation? For the following set, determine if the given operation is a
binary operation or not.
The set of all 2 × 2 matrices with real entries whose 2, 2 entry is
zero:
$$X=\left\{\begin{bmatrix}a & b \\c & 0\end{bmatrix} | a,b,c \in \mathbb{R}\right\}$$
With matrix multiplication.
Normally id say yes right away but the part thats confusing me is that after its multiplied by anther matrix its very likely that the 0 entry will no longer be a 0 entry does that disqualify it?

A:
after its multiplied by anther matrix its very likely that the 0 entry will no longer be a 0 entry does that disqualify it?

Yes.  A binary operation on a set $X$ is a function $X \times X \rightarrow X$.  So the output of multiplying any two such matrices must also be a matrix with a zero in the $2,2$ slot.  You can investigate this by multiplying together two general matrices in this set:
$$
\left[
 \begin{matrix}
  a & b  \\
  c & 0
 \end{matrix}
\right] \cdot \left[
 \begin{matrix}
  d & e  \\
  f & 0
 \end{matrix}
\right] = \left[
 \begin{matrix}
  ad + bf & ae  \\
  cd & ce
 \end{matrix}
\right]$$
Given that $c$ and $e$ are arbitrary...


text:
Q: mobile virtual keyboard make html body height 100% wired I'm making mobile page and all the layout is designed with percentage.
all the components in layout depends on body width, height.
When virtual keyboard is not present, there is no any problem.
But when virtual keyboard shows up, here is the problem.
I think a picture is worth a thousand words.

This shouldn't happen!
Can anyone knows the way to ignore virtual keyboard area?
Or suggest alternative way?
This is the code for fitting height 100%.
The reason why I used this code instead of css or viewport device-height is
that css height:100% and viewport device-height is never working whatever I tried.
$( window ).resize(function() {
    var bodyWidth = $('html').width();
    var bodyHeight = $('html').height();
    $('body').css("height", bodyHeight);
}


text:
Q: Second argument when emitting messages with process.send main.js
let child = require('child_process').fork('./child.js');

child.on('message', function () {
    console.log('message', arguments)
});

child.js
process.send({ ... });

It appears that the handler is called with two arguments:

{ '0': { ... }, '1': undefined }

I'm counting on arguments length in message listener, so the exact number of arguments is important.
What is the second argument (undefined)? Is it there unconditionally in all Node.js versions?

A: The fine manual states:

Event: 'message'
• message <Object> a parsed JSON object or primitive value.
• sendHandle <Handle> a net.Socket or net.Server object, or undefined.

If you search for sendHandle on the same page, you end up here, specifically:

The optional sendHandle argument that may be passed to child.send() is for passing a TCP server or socket object to the child process. The child will receive the object as the second argument passed to the callback function registered on the process.on('message') event.

However, in your situation you're sending the message in the other direction, from child to server, in which case sending a handle doesn't make sense. Hence, my guess would be that the second argument will always be undefined in that case (but will still be present).


text:
Q: Sorting a list by last element in Python 3 I need to sort a list of IP addresses in descending order by their packet size. This is the last number in the list. For example, in the first list the packet size is 34. I'm not sure how to do this. This is what I have so far:
ip_list = [['192.0.80.1','208.0.0.1',34], ['192.0.80.1','200.0.255.255',224],
          ['192.24.8.1','108.0.8.8',304], ['192.0.25.1','228.0.38.1',128]]

option = input("If you would like to sort the list enter -s, anything esle will quit")

if option == "-s" :

    ip_list.sort (reverse = True)
    print (ip_list)
else :
    print ("Okay the list will not be sorted. Gooodbye!!")

A: from operator import itemgetter

ip_list = [['192.0.80.1','208.0.0.1', 34], ['192.0.80.1','200.0.255.255', 224], ['192.24.8.1', '108.0.8.8', 304], ['192.0.25.1', '228.0.38.1', 128]]

ip_sorted = sorted(ip_list, key=itemgetter(2), reverse=True)

print(ip_sorted)

OUTPUT
[['192.24.8.1', '108.0.8.8', 304], ['192.0.80.1', '200.0.255.255', 224], ['192.0.25.1', '228.0.38.1', 128], ['192.0.80.1', '208.0.0.1', 34]]


text:
Q: How do I repeat this JQuery Function/ Animation? I have this code which I got from Github and at the moment what it does is that it calls the function once and then stops but I want it to repeat itself 3 times and within those 3 times want it to have a delay of like 10 seconds.
I tried using setInterval but it didn't work. When I try to insert setInterval into the code, the second time it tries to do the animation it doesn't work properly. So could you please help me out?
Here is the link to jsfiddle
HTML code:

  London

 New York

  Dublin

A: With onComplete event you can:
    var ratio = 0.3;
    $('.resized-splitflap').splitFlap({
        charWidth:  25 * ratio,
        charHeight: 50 * ratio,
        imageSize:  (1250 * ratio) + 'px ' + (50 * ratio) + 'px',
        onComplete: function() {

           $('.resized-newyork').splitFlap({
              charWidth:  25 * ratio,
              charHeight: 50 * ratio,
              imageSize:  (1250 * ratio) + 'px ' + (50 * ratio) + 'px',
              onComplete:function() {

                $('.resized-dublin').splitFlap({
                     charWidth:  25 * ratio,
                     charHeight: 50 * ratio,
                     imageSize:  (1250 * ratio) + 'px ' + (50 * ratio) + 'px'
                });
               }
           });
        }
   });

It's a weird nested function code, but it works.
Edit
As I tell you , it works. See this fiddle:
http://jsfiddle.net/pr2amqsp/1/


text:
Q: How can just apply forward propagation for single-layer-feed-forward or multi-layer-feed-forward models by Keras? I was wondering if it is possible to implement single-layer-feed-forward and multi-layer-feed-forward models on time-series data just by using forward-propagation in Keras  to predict some features? Since Keras performs backpropagation implicitly with no need for a special command. As you know single-layer-feed-forward and multi-layer-feed-forward models are considered as feed-forward approach and as far as I know using optimizer in  back-propagation just by model.compile(optimizer='adam') they will allow us to bring the error functions to a minimum with low computational resources.
Moreover Is there any relationship between fully-connected models and backpropagation?
I would really welcome some Python code to explain so, if there is any for helping me to understand from implementation point of view in this simple concept from prediction-based usage of ANN by Keras.
I've shared datasets here for train & test.
Thanks for your attention and ask a naive question in this area!

A: Following the comment, if you are looking to model time series with feed-forward networks and iteratively feed the inputs, that is just the SimpleRNN which is "Fully-connected RNN where the output is to be fed back to input."
At each time step a feed-forward network is used and the recurrent aspect is just an unrolled version of chained feed-forward networks that share the same weights. It computes tanh(Wx + b + Uh) where h is the previous output, you can consider that a feed-forward network with 2 inputs, the current timestep input and the previous output.


text:
Q: aws code deploy: No such file or directory - appspec.yml When trying to deploy my rails app through code deploy I get the following error message:
No such file or directory - /opt/codedeploy-agent/deployment-root/b3ff73b4-aa93-4e49-99e4-c26cdcf7a6f0/d-06LE313R9/deployment-archive/appspec.yml

on a "BeforeInstall" error.
I have appspec.yml in my rails app root directory (e.g it is myapp/appspec.yml), and have no idea how to put the appspec file into the deployment-archive directory.

A: The appspec.yml file should be at the root of the archive you upload to S3 or the GitHub repo you are deploying with. Try moving your appspec up one directory.
\
|-- appspec.yml
`-- myapp
    `--- (the rest of your rails app source tree)

Note that the appspec mostly uses paths relative to the archive root, so you might have to adjust them if you move your appspec.
Alternatively, you can create your bundle from inside your myapp directory so that the appspec.yml is still in the root directory of your archive.


text:
Q: startx / xorg boot issues on linux ubuntu 18.04 virtualbox client I migrated an ubuntu 18.04 virtualbox client over to another machine with an AMD Ryzen CPU and have been having a lot of issues getting xorg to boot cleanly.
After trying any/all versions of virtual display drivers, driver display options, different kernels, a newer xorg module, I still have an issue starting X.
Current behavior upon invoking startx: the terminal hangs until a timeout is listed on the .Xauthority file, then more hang until eventually X boots into a blank/lifeless display.
Strange workaround:  If I press Ctrl-C 4 times a few seconds after I invoke startx, then X will boot as normal, though I suspect it may be hampered somewhat as, and perhaps this is unrelated, but 1) glxinfo lists 1MB of video memory, though 128MB registers with dmesg on boot, and 2) unclutter-xfixes which is a program that hides the cursor after inactivity has ceased to hide the cursor.
Any ideas how to troubleshoot this?  I did start another ubuntu virtual machine from scratch (this time 18.10) and it has no issues starting X.

A: I was getting the same "X won't start after logging in" issue, and was able to login only by the mentioned workaround (pressing Ctrl+C about 4 times).
I was eventually able to fix it by deleting a local X log file:
rm ~/.local/share/xorg/Xorg.1.log

After that, X server would start fine.


text:
Q: Is there a way to cancel mongoose find execution and return data from redis instead? I'm trying to implement Redis cache along with mongoose in nest.js and I'm looking for a way
to check redis cache first before executing find or findOne and return the data from redis
otherwise execute query, save result in redis and return the result.
The reason I'm not implementing caching as recomended by nest.js
is that I'm also using Apollo Server for GraphQL.
@Injectable()
export class MyService {
    async getItem(where): Promise<ItemModel> {
        const fromCache = await this.cacheService.getValue('itemId');
        if(!!fromCache){
            return JSON.parse(fromCache);
        } else {
            const response = await this.ItemModel.find(where);
            this.cacheService.setValue('itemId', JSON.stringify(response));
            return response
        }
    }
}

I'd like to move this piece of code to a single place so that I don't have to
repeat this code for each query in my code since I have multiple services.
I know mongoose middleware has a way to run pre and post functions on queries
but I'm just not sure how to accomplish this using.
These are the versions I'm using:

*

*nestjs v7

*mongoose v5.10.0

A: You could create a method decorator where you move the logic to:
export const UseCache = (cacheKey:string) => (_target: any, _field: string, descriptor: TypedPropertyDescriptor<any>) => {
    const originalMethod = descriptor.value;
    // note: important to use non-arrow function here to preserve this-context
    descriptor.value     = async function(...args: any[]) {
        const fromCache = await this.cacheService.getValue(cacheKey);
        if(!!fromCache){
            return JSON.parse(fromCache);
        }
        const result = await originalMethod.apply(this, args);
        await this.cacheService.setValue(cacheKey, JSON.stringify(result));
        return result;
    };
}

Then use it with:
@Injectable()
export class MyService {

    constructor(private readonly cacheService:CacheService) { .. }

    @UseCache('itemId')
    async getItem(where): Promise<ItemModel> {
        return this.ItemModel.find(where);
    }

    @UseCache('anotherCacheKey')
    async anotherMethodWithCache(): Promise<any> {
         // ...
    }
}


text:
Q: What is cppcheck rule-file  syntax? I've poked around for a while, and can't find this anywhere.  I have found a nice example of a cppcheck rule-file that shows a simple pattern;
<?xml version="1.0"?>
<rule version="1">
  <pattern>if \( p \) { free \( p \) ; }</pattern>
  <message>
    <id>redundantCondition</id>
    <severity>style</severity>
    Redundant condition. It is valid to free a NULL pointer.
  </message>
</rule>

Which works nicely, as long as all the pointers are named 'p' and the call is 'free'.  How do I change 'p' to match any identifier? How do I check for "'free' or 'delete'"?  Is the pattern a grep/awk/sed pattern?

A: I am a Cppcheck developer.
Cppcheck uses PCRE. So use a regular expression that follows the Perl rules.
I'm not really good at Perl regular expressions so I can't answer how/if you can match any identifier (since it should be matched twice).
.. hope that helps a little at least.

A: From my regex experience, I'd try this
<?xml version="1.0"?>
<rule version="1">
  <pattern>if \( (\w+) \) { free \( \1 \) ; }</pattern>
  <message>
    <id>redundantCondition</id>
    <severity>style</severity>
    Redundant condition. It is valid to free a NULL pointer.
  </message>
</rule>

Where these PCRE features replace the p of your original example:

*

*(\w) is a word pattern (of alphanumeric chars and '_'), caught in group #1

*\1 is the back-reference to the text which matched the pattern

An elaborated description can be found at Martin Moene's Blog: Find code patterns with CppCheck

A: change the p into dot(.) so that it means any character


text:
Q: Paste Special - values only I am trying to create an audit trail DB, and have the managed to formulate some code to take each line to sheet 2, however I have fallen at the last and cannot work out how to paste values only?
here is my code thus far; any help greatly appreciated
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim nxtRow As Integer, b As Boolean
    'Determine if change was to Column I (9)
   If Target.Column = 9 Then
        'If Yes, Determine if cell >= 1
       If IsError(Target.Value) Then
        b = True
    Else
        If Target.Value >= 1 Then
            b = True
        Else
            b = False
        End If
        End If
        If b Then
        'If Yes, find next empty row in Sheet 2
       nxtRow = Sheets(2).Range("A" & Rows.Count).End(xlUp).Row + 1
        'Copy changed row and paste into Sheet 2
       Target.EntireRow.Copy _
        Destination:=Sheets(2).Range("A" & nxtRow)
            End If
    End If
End Sub

Thanks
Matt

A: To paste values, you can copy to the clipboard then use the PasteSpecial method, for example:
 Target.EntireRow.Copy
 Sheets(2).Range("A" & nxtRow).PasteSpecial Paste:=xlPasteValues

A: This might not solve the problem but it will improve your code.
you open some If-statements but you don't close some which will make your code do something else than you want.
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim nxtRow As Integer, b As Boolean
    'Determine if change was to Column I (9)
   If Target.Column = 9 Then
        'If Yes, Determine if cell >= 1
       If IsError(Target.Value) Then ' You open this If but you don't close it
        b = True
       'if you don't close it here the next line (else) will be the else of this if
       End If
   Else
        If Target.Value >= 1 Then
            b = True
        Else
            b = False
        End If
      'this line had an else if as well. which would just stop your main if statement
        If b = True Then
        'you say 'if b then' on the line above, which basically does nothing
        'If you want to check if b = True for example, do what I did above

        'If Yes, find next empty row in Sheet 2
             nxtRow = Sheets(2).Range("A" & Rows.Count).End(xlUp).Row + 1
            'Copy changed row and paste into Sheet 2
            Target.EntireRow.Copy _
            Destination:=Sheets(2).Range("A" & nxtRow)
        End If
    End If
End Sub


text:
Q: Force Embedded Jetty to disconnect at once I'm creating a small utility which receives a lot of HTTP requests. It is written in java and uses embedded-jetty to handle requests via https.
I have a load-testing tool for it, but when it is being run for some time it starts to throw exceptions:
java.net.BindException: Address already in use: connect

(note, this is on sender's side, not in my project)
As I understand this means no more free sockets were found in system when another connect was called. Throughput is about 1000 requests per second, and failures start to appear somewhere after 20000 to 50000 requests.
However when I use the same load testing tool with another program (a kind of simple consumer, written in scala using netty by some colleague - it simply receives all requests and returns empty ok response) - there is no so problem with sockets (though typical speed is 1.5-2 times slower).
I wonder if this could be fixed by telling Jetty somehow to close connections immediately after response was sent. Anyway each new request is sent via new connection. I tried to play with Connector#setIdleTimeout - it seems to be 30000 by default but have not succeeded.
What can I do to fix this - or at least to research the matter deeper to find its cause (if I am wrong in my suggestions)?
UPD Thanks for suggestions, I think I am not allowed to post the source, but I get the idea that I should study client's code (this will make me busy for some time since it is written in scala).

A: I found that really there was a problem with client - it sends requests with Connection: Keep-Alive in header, though creates new HttpURLConnection for each request and calls disconnect() method after it.
To solve this trouble on the server-side it was sufficient to send Connection: close in response header, since I have no allowance to change testing utility.


text:
Q: AOP: A combination of two @annotation clauses is not working I'm trying to write a pointcut, which shall hit for every method marked with certain annotation except the ones marked with another annotation.
But the following is not working:
<aop:aspect ref="...">
        <aop:before method="execute" pointcut="@annotation(MyAnnotation1)
                  and not @annotation(MyAnnotation2)"/>
</aop:aspect>

Will you please advise what i'm doing wrong?..

A: The Spring AOP documentation states

When combining pointcut sub-expressions, && is awkward within an XML
  document, and so the keywords and, or and not can be used in place of
  &&, || and ! respectively.

However, you're not allowed to bind parameters with negation. If you're saying it doesn't exist, what value would be passed as an argument?
Change it to
<aop:before method="execute" pointcut="@annotation(MyAnnotation1)
                  and not @annotation(com.example.MyAnnotationName)"/>

So MyAnnotation1 can refer to a parameter, but the other can't. As such, you need to specify the fully qualified name of the annotation type. A corresponding pointcut would look like
//@Pointcut(value = "@annotation(MyAnnotation1) && !@annotation(com.example.MyAnnotationName)")
public void yesNotNo(MyAnnotation1 MyAnnotation1) {
}


text:
Q: pyqt and table widget clear contents I am new to PYQT and I am trying to get a feel for it. I am trying to populate a table widget with 5 different push buttons. I need to clear out the table between each button push, but would like to leave the headers I have. I have tried a tablewidget clearcontents. but that clears everything and I am unsure of where to place it properly so it will clear the contents before each button push, that brings in the new info.
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Form(object):

    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(761, 637)
        self.pushButton = QtGui.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(0, 550, 201, 31))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.pushButton.clicked.connect(self.get_output1_statement)

        self.pushButton_2 = QtGui.QPushButton(Form)
        self.pushButton_2.setGeometry(QtCore.QRect(0, 580, 201, 31))
        self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
        self.pushButton.clicked.connect(self.get_output2_statement)

        self.pushButton_3 = QtGui.QPushButton(Form)
        self.pushButton_3.setGeometry(QtCore.QRect(0, 610, 201, 31))
        self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
        self.pushButton_3.clicked.connect(self.get_output3_statement)

        self.pushButton_4 = QtGui.QPushButton(Form)
        self.pushButton_4.setGeometry(QtCore.QRect(250, 580, 201, 31))
        self.pushButton_4.setObjectName(_fromUtf8("pushButton_4"))
        self.pushButton.clicked.connect(self.get_output4_statement)

        self.pushButton_5 = QtGui.QPushButton(Form)
        self.pushButton_5.setGeometry(QtCore.QRect(510, 580, 201, 31))
        self.pushButton_5.setObjectName(_fromUtf8("pushButton_5"))
        self.pushButton.clicked.connect(self.get_output5_statement)

        self.tableWidget = QtGui.QTableWidget(Form)
        self.tableWidget.setGeometry(QtCore.QRect(0, 0, 741, 551))
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(5)
        sizePolicy.setVerticalStretch(5)
        sizePolicy.setHeightForWidth(self.tableWidget.sizePolicy().hasHeightForWidth())
        self.tableWidget.setSizePolicy(sizePolicy)
        self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
        self.tableWidget.setColumnCount(5)
        self.tableWidget.setRowCount(50)
        self.tableWidget.setItem(0,0,QtGui.QTableWidgetItem("name"))
        self.tableWidget.setItem(0,1,QtGui.QTableWidgetItem("column_1"))
        self.tableWidget.setItem(0,2,QtGui.QTableWidgetItem("column_2"))
        self.tableWidget.setItem(0,3,QtGui.QTableWidgetItem("column_3"))
        self.tableWidget.setItem(0,4,QtGui.QTableWidgetItem("column_4"))

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Form", None))
        self.pushButton.setText(_translate("Form", "button1", None))
        self.pushButton_2.setText(_translate("Form", "button2", None))
        self.pushButton_3.setText(_translate("Form", "button3", None))
        self.pushButton_4.setText(_translate("Form", "button4", None))
        self.pushButton_5.setText(_translate("Form", "button5", None))

A: You can use the clearContents() method when you set the table headers in an appropriate way.
change:
self.tableWidget.setItem(0,0,QtGui.QTableWidgetItem("name"))
self.tableWidget.setItem(0,1,QtGui.QTableWidgetItem("column_1"))
self.tableWidget.setItem(0,2,QtGui.QTableWidgetItem("column_2"))
self.tableWidget.setItem(0,3,QtGui.QTableWidgetItem("column_3"))
self.tableWidget.setItem(0,4,QtGui.QTableWidgetItem("column_4"))

to:
self.tableWidget.setHorizontalHeaderItem(0, QtGui.QTableWidgetItem("name"))
self.tableWidget.setHorizontalHeaderItem(1, QtGui.QTableWidgetItem("column_1"))
self.tableWidget.setHorizontalHeaderItem(2, QtGui.QTableWidgetItem("column_2"))
self.tableWidget.setHorizontalHeaderItem(3, QtGui.QTableWidgetItem("column_3"))
self.tableWidget.setHorizontalHeaderItem(4, QtGui.QTableWidgetItem("column_4"))

EDIT Extra code after comments
Maybe this helps you? I tried keeping as much of your code.
class Ui_Form(QtGui.QDialog):

    def __init__(self, parent=None):
        super(Ui_Form, self).__init__(parent)
        self.setObjectName(_fromUtf8("Form"))
        self.resize(761, 637)
        self.pushButton = QtGui.QPushButton()
        self.pushButton.setGeometry(QtCore.QRect(0, 550, 201, 31))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.connect(self.pushButton, QtCore.SIGNAL("released()"), self.get_output1_statement)

        self.tableWidget = QtGui.QTableWidget()
        self.tableWidget.setGeometry(QtCore.QRect(0, 0, 741, 551))
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,     QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(5)
        sizePolicy.setVerticalStretch(5)
        sizePolicy.setHeightForWidth(self.tableWidget.sizePolicy().hasHeightForWidth())
        self.tableWidget.setSizePolicy(sizePolicy)
        self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
        self.tableWidget.setColumnCount(5)
        self.tableWidget.setRowCount(50)
        self.tableWidget.setHorizontalHeaderItem(0, QtGui.QTableWidgetItem("name"))
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.tableWidget)
        layout.addWidget(self.pushButton)
        self.setLayout(layout)
        for i in range(1, 5):
            self.tableWidget.setHorizontalHeaderItem(i,     QtGui.QTableWidgetItem("column_{0}".format(i)))
        self.retranslateUi()

    def retranslateUi(self):
        self.setWindowTitle(_translate("Form", "Form", None))
        self.pushButton.setText(_translate("Form", "button1", None))

    def get_output1_statement(self):
        self.tableWidget.clearContents()
        self.tableWidget.setItem(0,0,QtGui.QTableWidgetItem("add some data"))

app = QtGui.QApplication(sys.argv)
form = Ui_Form()
form.show()
app.exec_()


text:
Q: Setting different permission classes for POST and GET while using djangorestframework's default router I was just watching some online tutorial on how to use Django Rest Framework to create a basic REST API using their default router. Link to Docs
but then because he used a model viewset he had to add permission_classes to them which means all different types of requests whether its post or get or others it'll all take the same permission.
I was wondering if there's a way to give them different permission_classes depending on the type of request.

A: Yes, you can write your own permissions.
Just create some python file. I named it permissions.py:
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import BasePermission
from company.models import Company

class IsGetOrIsAuthenticated(BasePermission):
    def has_permission(self, request, view):
        if request.method == 'GET':
            return True
        return request.user and request.user.is_authenticated

class IsGetOrIsCompanyOwner(BasePermission):
    def has_permission(self, request, view):
        if request.method == 'GET' or 'OPTIONS':
            return True
        elif request.method == 'DELETE':
            company = get_object_or_404(Company, id=view.kwargs['pk'])
            return request.user.user_type == 'moder' or company.owner == request.user
        else:
            company = get_object_or_404(Company, id=view.kwargs['pk'])
            return company.owner == request.user or request.user.user_type == 'moder'

class IsModer(BasePermission):
    def has_permission(self, request, view):
        return request.user.user_type == 'moder'

After that you can use them in views.py
from company.permissions import IsGetOrIsAuthenticated, IsGetOrIsCompanyOwner, IsModer

class ActiveCompanyShortView(ModelViewSet):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsGetOrIsAuthenticated,)

you can read more there

A: To achieve what you need, one possible solution is to override the get_permissions() of ViewSet.
def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        if self.action == 'list':
            return [objects of permissions_u_need_in_list_view]

        elif self.action == 'create':
            return [objects of permissions_u_need_in_create_view]

This is what DRF provides the definition of get_permissions().
def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        return [permission() for permission in self.permission_classes]


text:
Q: Bug in Camel 2.13.2 Release-Bud Id 7544 The XSD allows to specify customId="true" id="foo" in the route elements. But when reading the route using Spring you get a parse error in Spring. I can't able to understand this bug. Can you please clarify me?

A: You should not use customId but only id.
The customId is for internal usage when updating routes from XML that the id is auto assigned or assigned by the end user.


text:
Q: where/when should env.sample (.env) be pulled in? Is this a bug? I was sourcing .env through my shell, which, I suspect, is a non-standard behavior, because this struck me as a bug:
DJANGO_SECRET_KEY=string

along with all the other variables are not quoted with single-apostrophe ticks ' ... which means that if there are characters that can be shell-evaluated, they will be.  This also affects urls because of the & that may be possible in their strings, as well as other shell characters.
Shouldn't it be
DJANGO_SECRET_KEY='string'

?
Or am I doing it wrong .env never gets sourced by a shell?

A: The .env file is read by the package django-environ and bears no relationship to either the python or shell formatting, it literally wants <key>=<value>.

A: Yes, the .env file is meant to be consumed by the django-environ package.
For detailed usage, check out the GitHub repo.


text:
Q: Using Apache UIMA Ruta from my own annotator I have a series of UIMA Ruta rules that I wish to run from within my own UIMA annotator. This is described here, but I can't get it to work: http://uima.apache.org/d/ruta-current/tools.ruta.book.html#ugr.tools.ruta.integration
When I try to run the annotator (from within a JUnit test, which I have used with other UIMA annotators successfully in the past), I get an error telling me that one of the Ruta basic annotation types (org.apache.uima.ruta.type.TokenSeed) is used in the Java code but isn't defined in the XML.
I've added the absolute path to the Ruta type system (BasicTypeSystem.xml and InternalTypeSystem.xml) to the descriptorPaths parameter (as detailed here: http://uima.apache.org/d/ruta-current/tools.ruta.book.html#ugr.tools.ruta.ae.basic.parameter.descriptorPaths), but that doesn't seem to make a difference.
I've had a look through the Ruta source code and couldn't figure out where I was going wrong.
Has anyone successfully got a Ruta script to run from within a UIMA annotator? How did you manage to get it working?

A: The problem is caused by the fact that the type system used by your analysis engine does not contain the types UIMA Ruta needs. The error mentions the seeding types because the initial annotations are added at the beginning. Even without seeding, more errors will occur because of the missing types like RutaBasic.
Adding the BasicTypeSystem to the type system used in your analysis engine should solve the problem.