text:
Q: how to rewind to the beginning of a line while reading from a file. c other than counting how many spaces i moved. is there a simple way to get the buffer back to the beginning of a line for reading? am trying to read in strings and then go back to read a different string and numbers. its not in order so i have to go back and look for them specifically. how do i do it.
i use rewind(fp); but that goes back to the beginning of the file.
also am trying to read in integers after the strings. the problem is its hard to read in double, triple digit numbers. i was able to do. but as you see the function down there is a mess. is there an easier way to read multi-digit integers;
void get_total(FILE*fp, int* ptotal, int* pscores, int* pnum_quiz){

    char c;

    int i = 0;

    int total=0;

    int digits;
    int first, second, third;

    *pnum_quiz = 0;

    int number_of_conversions;

    number_of_conversions = fscanf(fp, "%c", &c);

    while (isdigit(c) || isspace(c) && c !='\n' && c !=NULL && number_of_conversions!=0 && number_of_conversions !=EOF){

        if (isspace(c)){
            number_of_conversions = fscanf(fp, "%c", &c);

        }

        else if (isdigit(c)){
            first = c - '0'; // convert a character integer to integer

            *(pscores + i) = first;
            i++;

            number_of_conversions = fscanf(fp, "%c", &c);

            digits = 1;

            if (isdigit(c)){

                second = c - '0';

                *(pscores + i) = second;

                i++;

                number_of_conversions = fscanf(fp, "%c", &c);

                digits = 2;

                if (isdigit(c)){

                    third = c - '0';

                    *(pscores + i) = third;
                    i++;

                    digits = 3;
                }
                else{
                    fseek(fp, -1, SEEK_CUR);
                    *(pscores + i) = -1;
                    i++;
                }

            }
            else{
                fseek(fp, -1, SEEK_CUR);
                *(pscores + i) = -1;
                i++;
                *(pscores + i) = -1;
                i++;
            }

            if (digits==3){
                total = total + (first * 100) + (second * 10) + third;
            }
            else if (digits==2){
                total = total + (first * 10) + second;
            }
            else {
                total = total + first;
            }

            number_of_conversions = fscanf(fp, "%c", &c);

        }

        number_of_conversions = fscanf(fp, "%c", &c);

        *pnum_quiz = *pnum_quiz + 1;
    }

    *ptotal = total;

}

A: You could go fseeking backwards through the file, but that's not a good option, in my opinion.
Just read in the whole line and store it in a char buffer. Your code does that with repeated calls to fscanf(fp, "%c", &c), which is needlessly clumsy. There is already a function that does this, fgets:
char line[80];

while (fgets(line, sizeof(line), fp) != NULL) {
    // Now scan line instead of fp
}

Now you can parse line depending on your iput format: sscanf(line, ..) if you have a fixed format. strtok repeatedly if you need to extract tokens, and so on. (You don't show the format of your input, but there's probably a function to deal with it better than coding it by hand.)
One potential problem with fgets is that you need to specify a maximum length, which may not be suitable if you can have arbitrarily long lines. There's also the annoyance of the new-line character that's left at the end of each line.


text:
Q: Is it a way to compile Avro schema(s) to python classes? I am curious of is it a way to deal with Avro Python in the same way as in Java or C++ implementations.
According to the official Avro Python documentation, I have to provide an Avro schema in runtime to encode/decode data. But is it a way to use code generator as it did in Java/C++?

A: Update: My coworker put together a pretty good library for doing this, avro-to-python. We have been using it in production for over a year now on some pretty complex schemas.
I had to implement something like this for php: avro-to-php

A: pyschema is a pretty good start, but the documentation is poor.  You'll need to look a the source code to see how it all works. You can use it to read avro schemas and generate python source code. It adds another layer of abstraction and as such slows things down a bit more.

A: I've asked this question a couple of times recently in the Pulsar slack channel and my belief is that no tool currently exists that can convert an Avro schema to a Python class that is compatible with the Pulsar Python client library.
The Pulsar Python client library expects the Python class to inherit from the Record class (https://github.com/apache/pulsar/blob/master/pulsar-client-cpp/python/pulsar/schema/definition.py#L57), and for every field in the Python class to inherit from the Field class (https://github.com/apache/pulsar/blob/master/pulsar-client-cpp/python/pulsar/schema/definition.py#L141), both of which are defined in the Pulsar Python client library.
So, an Avro to Python converter would have to import the Record class and Field class from the Python client library, and so if such a converter exists, someone in the Pulsar Slack community really should know about it.
Further, the Pulsar Python client library is missing support for Avro keywords like "doc", "namespace", and for null default values. So even if an Avro to Python converter exists for Pulsar, likely, the converted Python class cannot be properly consumed by the Pulsar Python client library.

A: I don't see any indication of an existing Avro schema -> Python class code generator in the docs (which explicitly mention code generation for the Java case) for arbitrary Python interpreters. If you're using Jython, you could use the Java code generator to make a class that you access in your Jython code.
Unlike Java and C++, failing to have code generation doesn't affect Python performance much (in the CPython case anyway), since class instances are implemented in terms of dicts anyway (there are exceptions to this rule in a sense, but they mostly change memory usage, not the fact that dict lookup is always involved). That makes code generation largely "nice to have" syntactic sugar, not a necessary feature for development; with some effort, you could always implement a converter than writes out a class definition and evals it in Python to get a similar effect (this is how collections.namedtuple classes are defined).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scaling moves iframes apart I got a little issue with resizing the content of iframes. there are 4 iframes on my website on a 2*2 grid.
but when i want to resize the content to fit the iframe size, the iframes get smaller and suddenly there is a big distance between the iframes.
this is the code i used to resize
.scaled-frame {
        zoom: 1.2;
        -moz-transform: scale(0.71);
        -moz-transform-origin: 0 0;
        -o-transform: scale(0.71);
        -o-transform-origin: 0 0;
        -webkit-transform: scale(0.71);
        -webkit-transform-origin: 0 0;

    }

any ideas how to solves this or what i am doing wrong?
thanks

A: This is how i've done it:
Use a percentage for the width. Use the corrent settings for zoom, and -moz-transform scale.
#frame {
    width: 47%;
    zoom: 1.00;
    -moz-transform: scale(1.00);
    -moz-transform-origin: 0 0;
}

A: here is my code:
 .scaled-frame {
        width: 1024px;
        height: 768px;
        border: 0px;
    }

    .scaled-frame {

        zoom: 1.2;
        -moz-transform: scale(0.71);
        -moz-transform-origin: 0 0;
        -o-transform: scale(0.71);
        -o-transform-origin: 0 0;
        -webkit-transform: scale(0.71);
        -webkit-transform-origin: 0 0;

    }

and this is the zoom +/- function
function Inc() {
            scale = scale + 0.05;
            $("#iframes-container > iframe").each(function () {
                //$(this).width($(this).width() + $(this).width() / 100 * 10);
                //$(this).height($(this).height() + $(this).height() / 100 * 10);
                $(this).css("zoom",parseFloat($(this).css('zoom'))+0.02);
                $(this).css("-moz-transform","scale("+scale+")");
                $(this).css("-webkit-transform","scale("+scale+")");
                $(this).css("-o-transform","scale("+scale+")");
            });
        }

        function Dec() {
            scale = scale - 0.05;
            $("#iframes-container > iframe").each(function () {
                //$(this).width($(this).width() - $(this).width() / 100 * 10);
                //$(this).height($(this).height() - $(this).height() / 100 * 10);
                $(this).css("zoom",parseFloat($(this).css('zoom'))-0.02);
                $(this).css("-moz-transform","scale("+scale+")");
                $(this).css("-webkit-transform","scale("+scale+")");
                $(this).css("-o-transform","scale("+scale+")");
            });
        }

thanks
hivegeist


text:
Q: Session Facade and Data Transfer Object Multiple fine-grained invocations of Entity Beans add the overhead of network calls, even multiple transaction. In other words, the risk is to have a solution that has a high network overhead, high coupling, poor re-usability and maintainability. We use session facade to encapsulate business-tier components and expose a coarse-grained service to remote clients.  We use Data Transfer Object reduce the number of calls, and that means that you need to transfer more data with each call.
I am wondering on my little knowledge that what makes these two patterns so different. One would be serialization in DTO, but what others?

A: Although they work well together, these patterns are completely different.
Your description about session facade is good enough:

We use session facade to encapsulate business-tier components and expose a coarse-grained service to remote clients.

However the one about DTO doesn't reflects the pattern motivation and it is probably the source of your doubt.
The DTO pattern is pretty simple. If you have exposed a coarse-grained service (following the idea expresed in the Session facade pattern) it will probably need several input parameteres and it will probably produce a output relatively complex. In order to deal with this client-service data transfering, you can create a serialized object (called in this case DTO) that represent the parameters needed for your service. The same idea applies to the service output, all this information will be encapsulated in a simple java object.
//class that represents the service
public MyCoarseGrainedServiceClass{
public MyServiceOutDTO myCoarseGrainedService(MyServiceInDTO params) {
    MyServiceOutDTO outout;
            //your code goes here
    return output;
}
}

public MyServiceInDTO {
    //a list o different parameters of any type
    private int firstParam;
    private String secondParam;
    .
    .
    .
    //getters and setters
}

public MyServiceOutDTO {
    //this object represents the service output
    private int fistrOutputValue;
    ...
    //getters ans setters
}

Notice that you could have a coarse-grained service that doesn't use any DTO but, a DTO object by itself doesn't implements a coarse-grained service.


text:
Q: Change style of TimePicker in Xamarin In Xamarin, I have added a TimePicker to a Layout. In the preview window it appears as the typical box with arrows above the hour, minute, and time period (AM/PM), but in the emulator and on my phone (Lollipop/Nougat) it appears as a circular analog clock that sets the hands of the clock according to touch input. Is there a way I can force the TimePicker to appear as it does in the preview window? The circular TimePicker is somewhat useless to me.

A: You can update the attribute of the Time Picker in the .axml file to this
<TimePicker
...
android:timePickerMode="spinner" />

The default value on Material is clock.


text:
Q: Excel reader return null value with no reason c# I've got a little problem with my code use to read values in excel file.  I use a loop to read line per line and cells per cells.
The 152 first rows in excel file reads correctly but after the line 153, I get only null values for each cells.
This is my code :
public DataTable parseExcelFile(string path,bool firstLineHeader)
{
    DataTable values = new DataTable("Impayés");
    Excel.Application appExcel = new Excel.Application();
    Excel.Workbook wb = appExcel.Workbooks.Open(path, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Type.Missing, Type.Missing, Type.Missing, Type.Missing,Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    Excel.Worksheet sheet = (Excel.Worksheet)wb.Sheets["Feuil1"];
    Excel.Range excelRange = sheet.UsedRange;
    bool premiere = firstLineHeader;
    foreach (Excel.Range row in excelRange.Rows)
    {
        if (!premiere)
        {
            int rowNumber = row.Row;//Récupération du numéro de ligne
            //Récupération des valeurs des cellules de la ligne en cours
            string groupe = Convert.ToString(row.Range["A" + rowNumber.ToString()].Value);
            if (groupe == null)
                MessageBox.Show("Eh c'est vide ! (Ligne "+ rowNumber.ToString() + ")");
            string sousgroupe = Convert.ToString(row.Range["B" + rowNumber.ToString()].Value);
            string codeapporteur = Convert.ToString(row.Range["C" + rowNumber.ToString()].Value);
            string apporteur = Convert.ToString(row.Range["D" + rowNumber.ToString()].Value);
            string dossier = Convert.ToString(row.Range["E" + rowNumber.ToString()].Value);
            string siren = Convert.ToString(row.Range["F" + rowNumber.ToString()].Value);
            string client = Convert.ToString(row.Range["G" + rowNumber.ToString()].Value);
            string adresse = Convert.ToString(row.Range["H" + rowNumber.ToString()].Value);
            string localite = Convert.ToString(row.Range["I" + rowNumber.ToString()].Value);
            string cp = Convert.ToString(row.Range["J" + rowNumber.ToString()].Value);
            string ville = Convert.ToString(row.Range["K" + rowNumber.ToString()].Value);
            string telephone = string.Format("{0:00}{1:00}{2:00}{3:00}{4:00}", row.Range["L" + rowNumber.ToString()].Value, row.Range["M" + rowNumber.ToString()].Value,row.Range["N" + rowNumber.ToString()].Value,row.Range["O" + rowNumber.ToString()].Value,row.Range["P" + rowNumber.ToString()].Value);
            string etat = Convert.ToString(row.Range["Q" + rowNumber.ToString()].Value);
            string bic = Convert.ToString(row.Range["R" + rowNumber.ToString()].Value);
            string iban = Convert.ToString(row.Range["S" + rowNumber.ToString()].Value);
            RIB rib = new RIB(bic, iban);
            string domiciliationrib = Convert.ToString(row.Range["T" + rowNumber.ToString()].Value);
            string bienfinance = Convert.ToString(row.Range["U" + rowNumber.ToString()].Value);
            decimal mt_ht_fi = Convert.ToDecimal(row.Range["V" + rowNumber.ToString()].Value);
            decimal mt_ech = Convert.ToDecimal(row.Range["W" + rowNumber.ToString()].Value);
            string dateapp = Convert.ToString(row.Range["X" + rowNumber.ToString()].Value) + "/" + Convert.ToString(row.Range["Y" + rowNumber.ToString()].Value) + "/" + Convert.ToString(row.Range["Z" + rowNumber.ToString()].Value);
            string terme = Convert.ToString(row.Range["AA" + rowNumber.ToString()].Value);
            string premiereech = Convert.ToString(row.Range["AB" + rowNumber.ToString()].Value) + "/" + Convert.ToString(row.Range["AC" + rowNumber.ToString()].Value) + "/" + Convert.ToString(row.Range["AD" + rowNumber.ToString()].Value);
            string derniereech = Convert.ToString(row.Range["AE" + rowNumber.ToString()].Value) + "/" + Convert.ToString(row.Range["AF" + rowNumber.ToString()].Value) + "/" + Convert.ToString(row.Range["AG" + rowNumber.ToString()].Value);
            int nbimp = MyConverter.ToInt(Convert.ToString(row.Range["AH" + rowNumber.ToString()].Value));
            decimal mt_imp_1 = Convert.ToDecimal(row.Range["AI" + rowNumber.ToString()].Value);
            string dateimpaye1 = Convert.ToString(row.Range["AJ" + rowNumber.ToString()].Value) + "/" + Convert.ToString(row.Range["AK" + rowNumber.ToString()].Value) + "/" + Convert.ToString(row.Range["AL" + rowNumber.ToString()].Value);
            int motifimpaye1 = MyConverter.ToInt(Convert.ToString(row.Range["AM" + rowNumber.ToString()].Value));
            string dateimpaye2 = Convert.ToString(row.Range["AN" + rowNumber.ToString()].Value) + "/" + Convert.ToString(row.Range["AO" + rowNumber.ToString()].Value) + "/" + Convert.ToString(row.Range["AP" + rowNumber.ToString()].Value);
            int motifimpaye2 = MyConverter.ToInt(Convert.ToString(row.Range["AQ" + rowNumber.ToString()].Value));
            string dateimpaye3 = Convert.ToString(row.Range["AR" + rowNumber.ToString()].Value) + "/" + Convert.ToString(row.Range["AS" + rowNumber.ToString()].Value) + "/" + Convert.ToString(row.Range["AT" + rowNumber.ToString()].Value);
            int motifimpaye3 = MyConverter.ToInt(Convert.ToString(row.Range["AU" + rowNumber.ToString()].Value));
            DataRow dr = values.Rows.Add(groupe, sousgroupe, codeapporteur, apporteur, dossier, siren, client, adresse, localite, cp, ville, telephone, etat, bic, iban, domiciliationrib, bienfinance, mt_ht_fi, mt_ech, dateapp, terme, premiereech, derniereech, nbimp, mt_imp_1, dateimpaye1, motifimpaye1, dateimpaye2, motifimpaye2, dateimpaye3, motifimpaye3);
        }
        else
        {
            foreach (Excel.Range eRange in row.Range["A1:AU1"].Cells)
            {
                if (eRange.Value != "TEL2" && eRange.Value != "TEL3" && eRange.Value != "TEL4" && eRange.Value != "TEL5" && eRange.Value != "Col_21" && eRange.Value != "Col_22" && eRange.Value != "Col_25" && eRange.Value != "Col_26" && eRange.Value != "Col_28" && eRange.Value != "Col_29")
                    values.Columns.Add(eRange.Value);
            }
            premiere = false;
        }
    }
    return values;
}

And this is the example lines of my excel file :

A: Try deleting that row 152, or move it up or down in the document, and see if the error follows that row.
If you move that row to 145, and then the program stops at row 145, then we found the source of the problem: it's the data. There is probably an invalid or unreadable character in that row, and it crashes the program. It would be most likely to be a letter in one of the rows that should be a decimal or int.
Also, you are instantiating all your strings, decimals, and ints each time you run the loop. You should declare them all before the loop, then set their values inside the loop. This is a general good practice.


text:
Q: How to fix this type mismatch? Suppose I am defining zipWith like this:
def zipWith[A](f:(A, A) => A)(xs:Iterable[A], ys:Iterable[A]): Iterable[A] =
  (xs, ys).zipped map f

Now I'd like to use for zipping matrices like that:
type Matrix = Vector[Vector[Int]]

val zipMatrix: ((Int, Int) => Int) => Matrix => Matrix => Matrix = f =>
  zipWith(zipWith(f))

However I got an error:
<console>:15: error: type mismatch;
found   : (Iterable[Iterable[Int]], Iterable[Iterable[Int]]) => Iterable[Iterable[Int]]
required: Matrix => (Matrix => Matrix)
(which expands to)  scala.collection.immutable.Vector[Vector[Int]] => (scala.collection.immutable.Vector[Vector[Int]] => scala.collection.immutable.Vector[Vector[Int]])

Why doesn't Vector[Vector[Int]] match Iterable[Iterable[Int]] ? How to fix this error ?

A: Consider this:
def zipWith[A] (f:(A => A => A))(xs:Vector[A])(ys:Vector[A]): Vector[A] =
  (xs, ys).zipped.map {case (x, y) => f (x)(y)}

val zipMatrix: (Int => Int => Int) => (Matrix => Matrix => Matrix) = f =>
  zipWith(zipWith(f))


text:
Q: Is there a way to view jenkins plugin update history? Plugins were updated on our Jenkins, after which Jenkins entered the "safe-shutdown" mode, blocking all of our nightly scheduled jobs.
We don't know who (or "what") started the updates, and I cannot find any sort of log that refers to the plugin updates. All we know is the time they were updated (through "Date modified" on the actual plugin *.jpi files).
If it helps, we are using Active Directory authentication, with role-based rights management, so we actually know who (normal + service users) has rights on this, but no one seems to have done it, which makes me think it may have been triggered through script or scheduled task somewhere somehow.
Is there any way to find out who started the updates or how they were started?
Thanks.

A: The only place I found even a lit bit of information was in a Catalina log file.
catalina.2019-08-07.log:07-Aug-2019 16:37:10.695 INFO [Update center installer thread [#1]] hudson.model.UpdateCenter$DownloadJob.run Starting the installation of Credentials Binding on behalf of aakoch
I know you asked this 2 months ago, but I was having an issue also and found this question. So I'm adding what little info I have for the next person.
I'm going to add the stacktrace I had. Maybe it will show up in a search result.
Loading library jenkins-library@master
java.lang.NullPointerException
    at org.jenkinsci.plugins.workflow.libs.LibraryAdder.retrieve(LibraryAdder.java:157)
    at org.jenkinsci.plugins.workflow.libs.LibraryAdder.add(LibraryAdder.java:138)
    at org.jenkinsci.plugins.workflow.libs.LibraryDecorator$1.call(LibraryDecorator.java:125)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1065)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
    at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
    at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:142)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:127)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:561)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:522)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:320)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429)
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: Loading libraries failed

1 error

    at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
    at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
    at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:142)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:127)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:561)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:522)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:320)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE

Issue was that the information I had defined for the library got erased after doing some plugin update. I'm not sure which one. I just redefined the info and I was good to go.

A: Meanwhile we have a job running the python script below @daily in order to save the current plugin names and versions in a json file on the server:
import os, json, base64, urllib.request, ssl, datetime, time

request = urllib.request.Request("https://jenkins-server-name/pluginManager/api/json?depth=1")
#according to https://stackoverflow.com/a/28052583/4609258 the following is ugly
# ... but still ok if you basically access localhost, I think
context = ssl._create_unverified_context()
base64string = base64.b64encode(bytes('%s:%s' % ('jenkins user name', '34 characters long api key'),'ascii'))
request.add_header("Authorization", "Basic %s" % base64string.decode('utf-8'))

with urllib.request.urlopen(request, context=context) as url:
    parsed = json.loads(url.read().decode())
    f = open(datetime.datetime.now().strftime("%Y-%m-%d_%H-%M") + "_plugins.json", "w")
    f.write(json.dumps(parsed, indent=4, sort_keys=True))
    f.close()

If there is a problem, one can compare these daily files with each other, to see what was changed when.


text:
Q: how do I close a redis connection using the sinatra streaming api? I have the following sinatra app:
require 'sinatra'
require 'redis'
require 'json'

class FeedStream < Sinatra::Application

  helpers do
    include SessionsHelper

    def redis
      @redis ||= Redis.connect
    end
  end

  get '/feed', provides: 'text/event-stream' do

    stream do |out|

      redis.subscribe "feed" do |on|

        on.message do |channel, message|
          event_data = JSON.parse message
          logger.info "received event = #{event_data}"
          out << "event: #{event_data['event']}\n"
          out << "data: #{{:data => event_data['data'],
                           :by => current_user}}.to_json\n\n"
        end
      end
    end

  end

end

basically, it receives events published by other users to a feed using redis pubsub, and then it sends those events with the sinatra streaming api.
The problem is that, when the browser reconnects to the feed, the redis client keeps connected, and it keeps receiving events, so the redis server gets full of useless connections.
how can i close all this connections once the broser closes the connection to the web server?

A: I know it's been a while.
Were you looking for quit?

A: After much research and experimentation, here's the code I'm using with sinatra + sinatra sse gem (which should be easily adapted to Rails 4):
class EventServer < Sinatra::Base
 include Sinatra::SSE
 set :connections, []
 .
 .
 .
 get '/channel/:channel' do
 .
 .
 .
  sse_stream do |out|
    settings.connections << out
    out.callback {
      puts 'Client disconnected from sse';
      settings.connections.delete(out);
    }
  redis.subscribe(channel) do |on|
      on.subscribe do |channel, subscriptions|
        puts "Subscribed to redis ##{channel}\n"
      end
      on.message do |channel, message|
        puts "Message from redis ##{channel}: #{message}\n"
        message = JSON.parse(message)
        .
        .
        .
        if settings.connections.include?(out)
          out.push(message)
        else
          puts 'closing orphaned redis connection'
          redis.unsubscribe
        end
      end
    end
  end
end

The redis connection blocks on.message and only accepts (p)subscribe/(p)unsubscribe commands. Once you unsubscribe, the redis connection is no longer blocked and can be released by the web server object which was instantiated by the initial sse request.  It automatically clears when you receive a message on redis and sse connection to the browser no longer exists in the collection array.


text:
Q: How to run custom Javascript code in wordpress May be this question is not new, but stuck here.
I have designed a beautiful looking website using WordPress.
My Question is I Want to run some custom javascript code that I have written to manipulate elements of worpress page.
Second I have created an API,
I Have Designed a Questionire Page. Whenever someone click on the sumit button I Want Wordpress to send all the filled details in post request to my Web API that accept POST request. Then wait for the response and Create the Wordpress page as per the response using JavaScript.

A: add_action( 'wp_head','custom_js_code' );
function custom_js_code(){
 echo '<script>PUT YOUR JAVASCRIPT CODES HERE...</script>';
}


text:
Q: Cannot fetch data from external api with nextJs (ERR_ABORTED 400) I am trying to fetch some data from an external API with NextJS. I have tested the API url with postman and it works fine - result is fetched properly. But when I try to fetch API data with fetch() method in NextJS it gives me net::ERR_ABORTED 400 error in the browser console.
Here is piece of code:
React component:
import {fetchApiProduct} from "../../../lib/content-api";

export default function ProductPage(params) {
  const product = fetchApiProduct();

  return (
    <>

product.name

    </>
  );
}

fetachApiProduct() method:
export async function fetchApiProduct() {
  const sku = await useRouter().query.sku;
  const url = `https://sometesturl/api/product/${sku}`;
  console.log(url);

  const res = await fetch(url, {
    method: 'GET',
    mode: 'no-cors',
    headers: {
      'Accept': 'application/json'
    }
  })

  console.log(res);
  return res;
}

Edit:
If I use only:
await fetch(url);

Then this is what I get in console:

*

*Access to fetch at '...' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

*net::ERR_FAILED

*Uncaught (in promise) TypeError: Failed to fetch


text:
Q: script.js:2 Uncaught ReferenceError: angular is not defined I have checked all the available solution but didn't help me to resolve the problem.
I have simple code but it fails to run with the mentioned error.
Here is my code
index.html

<!DOCTYPE html>

    <link data-require="bootstrap-css@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
    <link rel="stylesheet" href="style.css" />

 Dash Board

 {{item.name}}
                {{item.value}}

        <button data-ng-="" click="getControllPanel()" class="btn btn-primary">Control Panel</button>

Here is the script.js

'use strict';
var app = angular.module('piApp',[]);

app.controller("piController", ["$scope",
  function($scope) {
    $scope.data =

    [{
      name: "Temperature",
      value: 25
    },
    {
      name: "Humidity",
      value: 75
    },
    {
      name: "Humidity2",
      value: 75
    }];
}]);

Not able to understand what is causing the mentioned error?
Do I need to have the angular.min.js locally?
Am I missing something trivial?

A: You have added dependency of angular2, and you have written code of angularjs
Also, you cannot use "data-ng-app" before loading the script. So remove it from html tag, and add it in body.
Add following line in head:

and remove the first two lines which has dependency of systemjs and angular2


text:
Q: Shifting a table by deleting rows and columns I have a table populated by random numbers and I would like to delete x number of columns from the left of the table, x number of rows from the bottom of the table and move the remaining values to the bottom left corner.
Public Sub shiftrandom()
Dim Difference As integer
Difference = 5
Dim i As Integer
For i = 1 To Difference
    Range("B2:B20").Delete Shift:=xlToLeft
    Range("B20:N20").Delete Shift:=xlDown
Next i

End Sub

Here B2:B20 is first column and B20:N20 is the last row. This is a 13x19 table.
the Range("B2:B20").Delete Shift:=xlToLeft works fine by its own, it shifts all the remaining values to the left by the correct number of columns, but the shift down line returns an

out of bounds error.

Thanks.

A: Excel does not shift Down or Right when deleting.
Only Left or Up are possible:
XlShift - Used only with Range objects. Specifies how to shift cells to replace deleted cells. Can be one of the following XlDeleteShiftDirection constants: xlShiftToLeft or xlShiftUp . If this argument is omitted, Microsoft Excel decides based on the shape of the range.
MSDN - Delete Range

A: Don't loop
Public Sub shiftrandom()
    Dim Difference As Long
    Difference = 5
    With Range("B2:N20")
        .Resize(,Difference).Delete
        .Rows(.Rows.Count - Difference + 1).Resize(Difference).Delete
    End With
End Sub


text:
Q: Is card-scan plus SMS-pin cosnidered as two-factor authentication? Here is the scenario:
For a person to become a member of a club, the person needs to register and upon registration the member:

*

*must provide a mobile number

*is given a unique card associated with
his or her person

In order for the member to make use of the club computers and services, the person must:

*

*Step 1: get the physical card scanned in front of a machine (RFID) stationed in a specific shop/branch/office

*Step 2: enter a one-time-use random 4-digit code received by SMS on the mobile number originally registered.  (The code expires after 5 minutes.)

I consider the membership card as something-that-you-own and the random one-time-use code as something-that-you-know.  The card and the 4-digit code are therefore the two factors.  If the card is lost or stolen, the 4-digit-code is still unknown to the thief.  And if the mobile phone (SIM Card) is lost or stolen, the card is still required to proceed in making use of the club services.  . Hence the two are independent from each other.
Is this correct?
Thanks

A: It was concluded that the above scenario is a grey area, leaning however mostly to the conclusion that it is not a 2-factor-authentication scenario.
Rationale:
When someone presents a bank credit or debit card at an ATM, the person has two tools: the card and the pin.
The card is the something-that-you-own; and
The pin is the something-that-you-know.
Therefore the PIN is definitely a knowledge factor...
The above scenario also has exactly the same two tools, a card and a pin.
However
The bank card pin is theoretically stored in your mind while in the above scenario, the PIN is received by SMS.
A mind cannot be stolen.  A mobile phone can be stolen.  For these reasons, the SMS PIN seems to become an invalid knowledge factor in this case.
The argument that follows is:  What is the SMS PIN then? Why send it in the first place?
The SMS Pin seems to be a method to verify that the phone is still in your possession.  But it cannot be considered as a knowledge factor per se.


text:
Q: Postgres Datediff I want to have datediff and use that in where condition in Postgres.
I have created this query
select emp_id
      ,"last_date::date" - "first_date::date" as days
  from emp
  where "last_date::date" - "first_date::date" > 10
;

Is there any better solution?


text:
Q: Distinguish a code comment from a text comment Is there an optimal way to see if a single line or block comment is merely code that was commented out, or if it is an actual comment.
e.g.
// console.log('foo');

Should validate true of being a code comment.

// This does stuff

Should validate false of being a code comment.

Current Solution:
Parse the comment contents through to an AST and see if it's code or not, kind of like a validator.
Assumptions:

*

*I have access to the original code parsed into an AST already and have access to a comment node.

*Is going to be a node script.

A: You need to collect the comment text, and run it through a language substring recognizer.  You might have:
 /*  X=2.7*Y^3+9.3^Y2+2.7*  */

That looks like code to me, even if it is incomplete.
So in general you want to detect substrings of the language as opposed to arbitrarily chosen language structures.  (Even if you choose expansion of langauge just nonterminals as defined by a grammar, do you include all 1000 of the nonterminals in your complex grammar? Just "statement" or "expression"?
Your first problem will be deciding where the "comment" begins or ends. Is
 //  X=X+1;
 /*  foo(bar);
     bar(baz);
 */

one code block or two (or three)?  What if the apparant code is split across comments?
//  X=X+
/*  1;  */

I'd guess your biggest problem is finding a langauge substring parser.  Just because you have a parser for the full language doesn't mean you an easily build a subtring recognizer with it.  (We have done that by bending GLR parsers for our tools, see my bio if you want to know more).
Your hardest problem is intention:  did the programmer really comment out actual code, or was she just sketching a computation in a comment? You can't know unless you can read long-gone minds.


text:
Q:  tag seems to always assign the last value on visualforce page, regardless of which event was clicked I have a VF page with 3 tabs. I can't figure out why the value assigned to the activeTab String always gets set to the last  value in the
. I thought the events were separate for each <apex:actionSupport/> tag... could someone kindly tell me what I am doing wrong here?
Example: when the page first loads, the controller correctly sets the value to 'regularUSR'. However when any
 is clicked, only the last value ('multiLicenseDeactivate') will get assigned.
UPDATE: I noticed that the onclick event apparently is firing for any click on the visualforce page, not just on the anchor tags / list items on the page.
VF page:

        <apex:actionSupport event="onclick" action="{!tabWasChanged}" reRender="ResultPanel1,ResultPanel2">
          <apex:param value="regularUSR" assignTo="{!activeTab}"></apex:param>
        </apex:actionSupport>
      Standard USR

        <apex:actionSupport event="onclick" action="{!tabWasChanged}" reRender="ResultPanel1,ResultPanel2">
          <apex:param value="multiLicenseActivate" assignTo="{!activeTab}"></apex:param>
        </apex:actionSupport>
      License Request

        <apex:actionSupport event="onclick" action="{!tabWasChanged}" reRender="ResultPanel1,ResultPanel2">
          <apex:param value="multiLicenseDeactivate" assignTo="{!activeTab}"></apex:param>
        </apex:actionSupport>
      License Deactivation

Extension:
public Boolean regularUSR {get;set;}
public Boolean multiLicenseActivate {get;set;}
public Boolean multiLicenseDeactivate {get;set;}
public String activeTab {get;set;}

public USRlicenseExtension(ApexPages.StandardController stdController) {
    u = (User_Support__c)stdController.getRecord();
    if(activeTab == null){activeTab = 'regularUSR';}
    tabWasChanged();
}

public PageReference tabWasChanged(){

    System.Debug('activeTab= '+activeTab);

    if(activeTab == 'regularUSR'){
        regularUSR = true;
        multiLicenseActivate = false;
        multiLicenseDeactivate = false;
    }

    else if(activeTab == 'multiLicenseActivate'){
        regularUSR = false;
        multiLicenseActivate = true;
        multiLicenseDeactivate = false;
    }

    else if(activeTab == 'multiLicenseDeactivate'){
        regularUSR = false;
        multiLicenseActivate = false;
        multiLicenseDeactivate = true;
    }

    return null;
}

A: The docs state "adds AJAX support to another component"

  <apex:outPutPanel layout="inline">

    <apex:actionSupport event="onclick" action="{!tabWasChanged}" reRender="ResultPanel1,ResultPanel2">
      <apex:param value="regularUSR" assignTo="{!activeTab}"></apex:param>
    </apex:actionSupport>
  Standard USR
   </apex:outPutPanel>


text:
Q: Visual Studio 2013 and .NET 4.6 I'm trying to set the 4.6 .NET framework for my project and in the settings, as it wasn't listed, I chose the last option - to install more frameworks. That directed me to a page where I selected VS2013, clicked on .NET 4.6 and downloaded the software but despite the installation being successful and restart of the computer, I still don't get to see the 4.6 .NET in the list of available options.
I've googled around for it and found mentioned that 4.6 is available on Win 8.1 (which is my system). However it doesn't say explicitly that it's available for VS 2013 (it doesn't say that it isn't, neither, though).
It's being said that .NET 4.6 is included in VS 2015 but I'm not clear if it's available for VS 2013. Is it? And how to get it to work?
Edit
After having installed the TP (a.k.a. Targeting Pack), I still get nothing new in the options, as the image depicts. Suggestions?

A: By putting together various pieces from the previous answers I was finally able to get a matching .Net Framework 4.6 and the Targeting Pack for it, and once both were installed the v4.6 Framework shows up as an available target framework Visual Studio 2012.
I downloaded the standalone installer for Framework 4.6 (NDP46-KB3045557-x86-x64-AllOS-ENU.exe) from http://www.microsoft.com/en-us/download/details.aspx?id=48130, and installed it first.
Then I downloaded and mounted the ISO for Visual Studio 2015 Professional ISO from https://www.visualstudio.com/downloads/download-visual-studio-vs, browsed to the netfx_46mtpack subdirectory, and installed netfx_46mtpack.msi.

A: I am experiencing the very same issue with Visual Studio 2012 and .NET 4.6. I have installed both, the runtime and targetting pack from http://getdotnet.azurewebsites.net/target-dotnet-platforms.html
I made a mistake in installing first the targetting pack and then runtime. I reinstalled the targetting pack after installing the runtime and voilá, it's alive! The solution mentioned by Brandon is correct.

A: You need to install the .NET Framework 4.6 Targeting Pack.

The .NET Framework 4.6 Targeting Pack is a package that enables developers to build applications targeting the .NET Framework 4.6 using either Visual Studio 2013, Visual Studio 2012 or third party IDEs. You need to download and install the .NET Framework 4.6 prior to installing the targeting pack.

A: The easiest solution is to install Visual Studio 2015 Community Edition. Not elegant, but it resolves all the dependencies automatically.
After it's installed you can use Visual Studio 2013 with .NET 4.6

A: You're looking for the .NET Targeting Pack, which you can find here.

A: I followed the steps presented here, but Visual Studio didn't display the .NET Framework 4.6.2 on the project property target framework list.
I had to download NDP462-DevPack-KB3151934-ENU in order to be added on the list. You can download it from Microsoft Download Center.
Hope it helps!

A: Referring to this support article by Microsoft:
Microsoft .NET Framework 4.6 Targeting Pack and Language Packs for Windows
In short you need three components:

*

*The .Net 4.6 Framework itself of course

*The .NET Framework 4.6 Targeting Pack

*

*language neutral reference assemblies to compile against

*download file name like "NDP46-TargetingPack-KB3045566.exe"

*optional: The .NET Framework 4.6 Targeting Pack Language Packs

*

*translated IntelliSense help files

*download file name like "NDP46-TargetingPack-KB3045566-ENU.exe"
(suffix -ENU for english, -DEU for german etc.)

A: Just download SDK for .net framework developer pack, that you need (it worked for me):
https://www.microsoft.com/net/targeting
(In my sytuation it was .NET Framework 4.6.2 Developer Pack )

A: for the sake of completeness to what answered by @jerhewet, download the lasted Visual Studio Installer: vs_community (2017). while in the normal installation process you need to select all the needed workloads,  here uncheck all but the
.NET Framework 4.6 Targeting Pack. Wait for the installation process to complete and just close the installer.

In this way, you don't even need to install a standalone .NET 4.6.


text:
Q: Libreoffice has different behaviour in Debian Jessie and Ubuntu I'm using docker in order to set up the environment needed in order to run a converter (any format to pdf) through LibreOffice. I have a certain file; when I run it in the Jessie environment (base image is Debian Jessie) the conversion is not good (blacked out lines). When the base image is Ubuntu 16.04 the conversion is great.
My question is, what package(s) is Jessie missing (compared to Ubuntu) that would affect the conversion?
RUN apt-get update
RUN apt-get -y -q install \
    build-essential openjdk-8-jdk maven wget unzip curl \
    fonts-crosextra-carlito fonts-crosextra-caladea \
    fonts-opensymbol hyphen-fr hyphen-de hyphen-en-us hyphen-it hyphen-ru \
    fonts-dejavu fonts-dejavu-core fonts-dejavu-extra \
    fonts-dustin fonts-f500 fonts-fanwood fonts-freefont-ttf fonts-liberation \
    fonts-lmodern fonts-lyx fonts-sil-gentium fonts-texgyre fonts-tlwg-purisa

A: Debian Jessie, or Debian 8 is known as old-stable. You are comparing it to a much newer Ubuntu 16.04 LTS. A more appropriate comparison might be Ubuntu 14.04 LTS.
The current Debian 'stable' release is Stretch (Debian 9) so it'd make a closer match to Ubuntu 16.04 LTS.
Note however Debian & Ubuntu are unlikely to perfectly match as they are on different release cycles; Ubuntu's releases are date fixed, Debian isn't and on a longer cycle even if its releases occur roughly two years like LTS releases of Ubuntu.
Ubuntu is built largely from debian-testing (currently Debian 10 or Buster), but also contains Debian Sid ....
I'm suggesting comparing Debian 8 with Ubuntu 14.04LTS, or if you want Ubuntu 16.04LTS try Debian 9.   (from comments.. with thanks to @N0rbert who helped too)


text:
Q: Is someone trying to hack into our system? I have a CentOS 6 server that has misbehaved over the last couple of weeks. I have tried to trace network, adjust settings, and asked a lot of clever people about it (see more in this question: Something is closing connections in my CentOS VMs - how to best troubleshoot?)
The issue has not been there the last 3-4 days so I was getting closer to perhaps believing that some of the adjustments had made a difference. But now it just happened twice within an hour. I started looking in logs. And I stumbled over this in the /var/log/nginx/access.log:
:
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
34.78.120.99 - - [13/Aug/2021:15:18:34 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
:

... and many more of them!
This occurred around both of the times that I saw the issue. Does anyone know if this is Ok - or if not, what is the best way forward to block it?
Thanks!
/John
Edit
I reported it as suggested - and then blocked that IP address in my Nginx.
So today I checked again - and now I have a bunch of similar requests - just from another IP.
104.155.101.3 - - [18/Aug/2021:13:54:36 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:02:45 +0200] "GET / HTTP/1.1" 200 26314 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:02:45 +0200] "GET / HTTP/1.1" 200 26313 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:02:46 +0200] "GET / HTTP/1.1" 200 26348 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:02:46 +0200] "GET / HTTP/1.1" 200 26325 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:02:46 +0200] "GET / HTTP/1.1" 200 26280 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:02:48 +0200] "GET / HTTP/1.1" 200 26325 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:02:49 +0200] "GET / HTTP/1.1" 200 26280 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:02:49 +0200] "GET / HTTP/1.1" 200 26299 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:06:25 +0200] "GET / HTTP/1.1" 200 26298 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:06:25 +0200] "GET / HTTP/1.1" 200 26349 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:06:27 +0200] "GET / HTTP/1.1" 200 2379 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:06:27 +0200] "GET / HTTP/1.1" 200 26279 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:06:28 +0200] "GET / HTTP/1.1" 200 26349 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:06:29 +0200] "GET / HTTP/1.1" 200 26318 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:06:30 +0200] "GET / HTTP/1.1" 200 26348 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:06:30 +0200] "GET / HTTP/1.1" 200 26319 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:06:32 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:06:32 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:06:32 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"
104.155.101.3 - - [18/Aug/2021:16:06:32 +0200] "GET / HTTP/1.1" 499 0 "-" "python-requests/2.26.0" "-"

Should I be concerned about some of the new ones (with code 200)???


text:
Q: Como puedo hacer un mensaje emergente dentro de mvc 5? lo que quiero hacer es que el mensaje emergente me aparezca en la vista de create antes de  que  me redireccione al index y que cuando le de click a aceptar del mensaje me redireccione a index y pues no comprendo el porque no puedo hacer con algunos ejemplos lo intentado pero no me sale

Este es mi get del controlador (create)

    // GET: Reflectores/Create
    public ActionResult Create()
    {
        ViewBag.IdTipo = new SelectList(db.TiposdeReflectores, "IdTipo", "TipodeReflector");
        ViewBag.IdTurno = new SelectList(db.TurnodelOperadors, "IdTurno", "Turno");
        return View();
    }

el controlador del mismo(create)

  [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "IdReflector,Fecha,Operador,IdTurno,NumTO,NumParte,IdTipo,NumSerie,ClaseRMS,RMSValor,ValidaciondeRMS,EmpacadoMPS,Comentario,contador,contadorLT")] Reflector reflector)
    {
        reflector.Fecha = Convert.ToDateTime(DateTime.Now.Date.ToShortDateString());
        //  reflector.Fecha = DateTime.Now.Date.ToShortDateString();
        if (ModelState.IsValid)
        {
            db.Reflectors.Add(reflector);
            db.SaveChanges();

aquie es donde me redirecciona al index pero quiero que primero me salga el mensaje

            return RedirectToAction("Index");
        }

        ViewBag.IdTipo = new SelectList(db.TiposdeReflectores, "IdTipo", "TipodeReflector", reflector.IdTipo);
        ViewBag.IdTurno = new SelectList(db.TurnodelOperadors, "IdTurno", "Turno", reflector.IdTurno);

aqui use el mensaje de viewbag pero no es lo que necesito

        //ViewBag.Crotolamo = "No puede ser el mismo inspecto IPQC y OBA";

        return View(reflector);
    }

vista create

  @model Docuemto_de_reporte_de_excel.Models.Reflector

@{
    /**/

    ViewBag.Title = "Create";
}

Registro de Reflector

@using (Html.BeginForm())

{

   @Html.AntiForgeryToken()

Reflector

    @if (TempData["Success"] != null)
    {

@TempData["Success"]

    }

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Operador, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Operador, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Operador, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.IdTurno, "IdTurno", htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownList("IdTurno", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.IdTurno, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.NumTO, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.NumTO, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.NumTO, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.NumParte, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.NumParte, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.NumParte, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.contadorLT, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.contadorLT, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.contadorLT, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.IdTipo, "IdTipo", htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownList("IdTipo", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.IdTipo, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.NumSerie, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.NumSerie, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.NumSerie, "", new { @class = "text-danger" })

                Selector de Numero de Clase:

        @*<select id="selecionaNUM" class="form-control" onchange="select();" name="selectclase">
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>

                </select>

*@

            @Html.LabelFor(model => model.ClaseRMS, htmlAttributes: new { @class = "control-label col-md-2" })

                    A
                    @Html.RadioButtonFor(model => model.ClaseRMS, "A", new { htmlAttributes = new { @class = "form-control", @id = "clasea" } })

                    B
                    @Html.RadioButtonFor(model => model.ClaseRMS, "B", new { htmlAttributes = new { @class = "form-control" } })

                    C
                    @Html.RadioButtonFor(model => model.ClaseRMS, "C", new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.ClaseRMS, "", new { @class = "text-danger" })

                No Aplica En el RMS Valor:    <input id="ValidacionDeRMS" type="checkbox" onchange="habilitar();" />

            @Html.LabelFor(model => model.RMSValor, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.RMSValor, new { htmlAttributes = new { @class = "form-control", @id = "validacion" } })
                @Html.ValidationMessageFor(model => model.RMSValor, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.ValidaciondeRMS, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.ValidaciondeRMS, new { htmlAttributes = new { @class = "form-control", @id = "mega" } })
                @Html.ValidationMessageFor(model => model.ValidaciondeRMS, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.EmpacadoMPS, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.EmpacadoMPS, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EmpacadoMPS, "", new { @class = "text-danger" })

                No Aplica Comentario:    <input id="ValidacionDeCM" type="checkbox" onchange="habilitar2();" />

            @Html.LabelFor(model => model.Comentario, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Comentario, new { htmlAttributes = new { @class = "form-control", @id = "validacion2" } })
                @Html.ValidationMessageFor(model => model.Comentario, "", new { @class = "text-danger" })

aqui este el buton que me redirecciona al create  que esl input value ="Terminar"

                    <input type="submit" name="response" value="Terminar" class="btn btn-success" />

                @*<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
                        Launch demo modal
                    </button>*@
                @Html.ActionLink(" Regresar A la lista", "Index", null, new { @class = "btn btn-warning glyphicon glyphicon-arrow-left" })

                @*<button class="btn-danger eliminar" data-id="@Model.IdReflector">Eliminar</button>*@

}

A: Una vez que mandas llamar el Index, no es posible detenerlo.
Puedes hacerlo por un ajax, regresar un resultado y mandar el mensaje, luego mandar pintar tu mensaje emergente y al final redireccionar.
O usando MVC puedes guardar tu mensaje en un TempData
TempData["Mensaje"] = "Registro guardado correctamente.";
Y mostrar ese tempdata en tu index (Ejemplo usando boostrap)
@{
    string classAlerta = string.Empty;
}

@if (TempData["Mensaje"] != null)
{

    if (esError)
    {
        classAlerta = "alert alert-danger";
    }
    else
    {
        classAlerta = "alert alert-success";
    }

                <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                @TempData["Mensaje"].ToString()

}


text:
Q: Rename localhost 127.0.0.1, in LAMP stack I am using a LAMP stack. Will there be problems if I update the /etc/host file to reflect 127.0.0.1 as somename from localhost?
Thanks!
Edit:
I sometimes work in remote sites with no network. I have the same setup on different machines and I need the server name to know dynamically where to do changes, etc.
I edited /etc/hosts to show
127.0.0.1 localhost somename
Now, with my Wifi off I am trying http://somename and it is not connecting. If I turn my wifi on, it works. But I need it to work with no connection. How can I resolve this?

A: No. Just add somename after localhost separated by space in /etc/hosts. You can add as many aliases as you like, as long as you don't delete localhost.


text:
Q: Etiquette of presenting a problem you have managed to solve yourself
Possible Duplicate:
Can I answer my own questions, even those where I knew the answer before asking?

I'm new round these parts.  I spent today struggling mightily with an MS-Access/SQL problem, and had just finished typing out my question when I thought of one more thing I could try before posting to the board.  This last idea led me to find my answer, so I don't need help anymore.  Win!
But!  But I searched for information about my solution on the Web and didn't find anything within the first page of Google hits.  It's either an undocumented "feature" of MS-Access 2007, or I'm just pretty bad at searching.  Anyway, this made me wonder -- what is the etiquette of asking a question I have already answered?  I don't want to look like some schmuck who wants to be able to upvote myself, but I doubt I'm the only person who will run into this Access problem, and it seems like it might be a public service to document it somewhere.


text:
Q: Overly complicated proof of the surjectivity of the Artin map Let $K/k$ be an abelian extension of number fields and $\frak c$ a cycle of $k$ divisible by all primes ramifying in $K$. Then we have the following theorem from algebraic number theory (see Lang's ANT chapter X, Theorem 1):

The Artin map $A : I({\frak c})\to \operatorname{Gal}(K/k),{\frak a}\mapsto ({\frak a},K/k)$ is surjective.

The proof in Lang's book goes like this:
Consider the fixed field $F$ of the image of $A$. Then every prime in $I(c)$ splits completely in $K$. If $A$ is not surjective, i.e. $F\ne k$ there is an intermediate field $F_0$ of $F/k$ which is cyclic and of degree $>1$ over $k$. He now refers to the global cyclic norm index equality and one of its corollaries (from chapter IX) to deduce that in such an extension infinitely many primes do not split completely which is a contradiction because $I(\frak c)$ contains all but finitely many primes from $k$.
The global cyclic norm index equality was a very non-trivial theorem the proof of which was basically the whole chapter IX.
It seems like we only need the following:

If $L/k$ is finite and Galois then the set of primes of $k$ splitting completely in $L$ has density $\frac{1}{[L:k]}$. Thus (in the setting above) we have $[F:k]=1$.

This can be deduced very easily from the more elementary fact that the Dedekind zeta function of $L$ has a simple pole at $1$ (see below). And this holds for arbitrary (finite), not necessarily abelian or even cyclic, Galois extensions.
This also shows that in general, i.e. if $K/k$ might not be abelian, but still finite and Galois, the set of Frobenius elements of primes in $I(\frak c)$ generates the whole group $\operatorname{Gal}(K/k)$ (of course this can be improved by replacing 'generates' by 'equals' using e.g. Chebotarev's density theorem which is again more involved)
Why did Lang use the more complicated/involved proof?
I know that he already used some class field theoretical facts in earlier results on prime densities (e.g. in the theorem on primes in generalized arithmetic progressions or the Chebotarev density theorem) but this is not the case here, so no circular reasoning.
Are there maybe other situations (e.g. other global fields, i.e. function fields over $\Bbb F_q$) where Lang's argument is advantageous?

Proof of the claim above:
We have \begin{align*}
\log(s-1)^{-1}&\sim\log\zeta_L(s)\\
&\sim\sum_{{\frak P}\subset L}N{\frak P}^{-s}\\
&\sim\sum_{\substack{{\frak P}\subset L\\f({\frak P}\mid{\frak P}\cap k)=1}\\e({\frak P}\mid{\frak P}\cap k)=1}N{\frak P}^{-s}\\
&=\sum_{\substack{{\frak P}\subset L\\{\frak P}\cap k\text{ splits completely in $L$}}}N{\frak P}^{-s}\\
&=[L:k]\sum_{\substack{{\frak p}\subset k\\{\frak p}\text{ splits completely in $L$}}}N{\frak P}^{-s}\\
\end{align*}
It follows that $\{{\frak p}\subset k\mid {\frak p}\text{ splits completely in }L\}$ has (Dirichlet-)density $\frac{1}{[L:k]}$.
(Here $\sim$ denotes that the difference of the two sides is bounded as $s\to 1^+$.)


text:
Q: Training inputs in keras I have word-vectors(Glove vectors) pre trained over general twitter dataset. I have a set of tweets and I want to retrain the word-vectors parallelly with the task in hand. This requires updating the inputs in the MLP. How do I retrain input in sequential MLP in keras?
Edit :
Glove pre-trained(on twitter) vector are already provided on their website . I have some users and their tweets and I have a classification task . So I am trying to convert words of the tweets into wordvectors and taking their average to get word vector representation of tweet. But as adopted in standard literature , I want to retrain the wordvectors on the new network(Word vectors are inputs now). How can I implement this in keras


text:
Q: spring aop with mybatis dao annotation I have used MapperScannerConfigurer to create mybatis dao,
but I can't use Annotation with the mybatis dao.
Is the order of the wrong?
Spring in the bean and mybatis dao is not in a resource library?
Normal injection is possible, but can not get class annotations
Here are some configuration
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="annotationClass" value="org.springframework.stereotype.Repository"/>
    <property name="basePackage" value="com.wecash"/>
    <property name="sqlSessionFactoryBeanName" value="masterSqlSessionFactory"/>
</bean>

@Aspect
@Component
public class DataSourceAspect {

    public DataSourceAspect(){
        System.out.println("init  DataSourceAspect ");
    }

    private final static LoggerWithMDC LOGGER = LoggerWithMDC.getLogger(DataSourceAspect.class,"dataSource");

    @Around("@annotation(dataSource)")
    public Object processed(ProceedingJoinPoint point, DataSource dataSource) throws Throwable {
        System.out.println("-----------------------");
        return   point.proceed();
    }
}


text:
Q: Run query right after docker-compose with Mysql I have the following docker-compose
version: '3.7'

services:
  mysql:
    image: mysql
    command: --default-authentication-plugin=mysql_native_password
    hostname: 'mysql'
    restart: always
    container_name: mysqlserver
    networks:
      - internal-network
    ports:
      - 3306:3306
    environment:
      MYSQL_DATABASE: my_database
      MYSQL_ROOT_PASSWORD: my_secret_password
    volumes:
      - mysql-data:/var/lib/mysql

This works fine but after that I have to run the following query in order to connect to my database:
ALTER USER 'root' IDENTIFIED WITH mysql_native_password BY 'root';
FLUSH PRIVILEGES;

I was wondering: is there any way to automate the process and run this query automatically right after the docker-compose up? Is there any way to specify it inside the docker-compose.yaml or other file?


text:
Q: Bitters error ("Undefined variable: $font-stack-system") My folder structure:
- app
-- sass
--- style.scss
--- base
--- bourbon

In my style.scss I import bourbon and base (and neat):
@import "bourbon/bourbon";
@import "base/base"; // bitters
@import "neat/neat"; // bourbon grid

When I run "$gulp" (gulp is installed globally) I get the error:
[Error: app\sass\base\_variables.scss
Error: Undefined variable: "$font-stack-system".
    on line 6 of app/sass/base/_variables.scss
>> $base-font-family: $font-stack-system;
   -------------------^
]
  formatted: 'Error: Undefined variable: "$font-stack-system".\n        on line 6 of app/sass/base/_variables.scss\n>> $base-font-family: $font-stack-system;\n   -------------------^\n',

(+ some more "Undefined variable" errors from "base" (bitters)) When I delete the line:
@import "base/base"; // bitters

It works. So I think there is a file missing but I don't know which.
EDIT: I found the error - the console always installs an old bourbon install (v. 4.x) and i need v. 5.x.


text:
Q: How to generate Maya 3D animation model to .h file for augmented reality vuforia? Currently, I am working on augmented reality and I am unsure about how to get the .h file from Maya for my 3D model to implement into my xcode project.
Any help would be greatly appreciated.


text:
Q: How do I stitch multiple images in a panaroma? I am using opencv and want to stick with it.
I have 5 images with some common areas in a pairwise manner. I want to merge them together in a single image. I have been successful joining two images together, as they were of the same resolution(a little tweak brought them to the same resolution without distorting the contents significantly). But now this first stage of merging gives me a highly inflated image, the resolution has gone significantly up(kind of an addition of two images).
To merge the two images I had brought their resolutions to the same value and it didn't cause much distortion. But now there's this image with double the length. If I change its resolution to the level of the image next in line for stitching, it is going to highly distort the content of the first stage and hence the result from here on.
How do I fix this issue given that I need to go through 5-6 iterations of stitching where the resolution is going to keep increasing?
Also, if there is any text which goes into details of image processing with examples, like above.
Stitcher.py
# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
# import the necessary packages
import numpy as np
import imutils
import cv2

class Stitcher:
      def __init__(self):
        # determine if we are using OpenCV v3.X
        self.isv3 = imutils.is_cv3()

      def stitch(self, images, ratio=0.75, reprojThresh=4.0,
        showMatches=False):
        # unpack the images, then detect keypoints and extract
        # local invariant descriptors from them
        (imageB, imageA) = images

        #(b, g, r) = cv2.split(imageA)
        #imageA = cv2.merge([r,g,b])
        #(b, g, r) = cv2.split(imageB)
        #imageB = cv2.merge([r,g,b])

        (kpsA, featuresA) = self.detectAndDescribe(imageA)
        (kpsB, featuresB) = self.detectAndDescribe(imageB)

        # match features between the two images
        M = self.matchKeypoints(kpsA, kpsB,
            featuresA, featuresB, ratio, reprojThresh)

        # if the match is None, then there aren't enough matched
        # keypoints to create a panorama
        if M is None:
            return None
           # otherwise, apply a perspective warp to stitch the images
        # together
        (matches, H, status) = M
        result = cv2.warpPerspective(imageA, H,
            (imageA.size[1] + imageB.size[1], imageA.size[0]))

        result[0:imageB.size[0], 0:imageB.size[1]] = imageB

        # check to see if the keypoint matches should be visualized
        if showMatches:
            vis = self.drawMatches(imageA, imageB, kpsA, kpsB, matches,
                status)

            # return a tuple of the stitched image and the
            # visualization
            return (result, vis)

        # return the stitched image
        return result
      def detectAndDescribe(self, image):
        # convert the image to grayscale
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # check to see if we are using OpenCV 3.X
        if self.isv3:
            # detect and extract features from the image
            descriptor = cv2.xfeatures2d.SIFT_create()
            (kps, features) = descriptor.detectAndCompute(image, None)

        # otherwise, we are using OpenCV 2.4.X
        else:
            # detect keypoints in the image
            detector = cv2.FeatureDetector_create("SIFT")
            kps = detector.detect(gray)

            # extract features from the image
            extractor = cv2.DescriptorExtractor_create("SIFT")
            (kps, features) = extractor.compute(gray, kps)

        # convert the keypoints from KeyPoint objects to NumPy
        # arrays
        kps = np.float32([kp.pt for kp in kps])

        # return a tuple of keypoints and features
        return (kps, features)
      def matchKeypoints(self, kpsA, kpsB, featuresA, featuresB,
        ratio, reprojThresh):
        # compute the raw matches and initialize the list of actual
        # matches
        matcher = cv2.DescriptorMatcher_create("BruteForce")
        rawMatches = matcher.knnMatch(featuresA, featuresB, 2)
        matches = []

        # loop over the raw matches
        for m in rawMatches:
            # ensure the distance is within a certain ratio of each
            # other (i.e. Lowe's ratio test)
            if len(m) == 2 and m[0].distance < m[1].distance * ratio:
                matches.append((m[0].trainIdx, m[0].queryIdx))
        # computing a homography requires at least 4 matches
        if len(matches) > 4:
            # construct the two sets of points
            ptsA = np.float32([kpsA[i] for (_, i) in matches])
            ptsB = np.float32([kpsB[i] for (i, _) in matches])

            # compute the homography between the two sets of points
            (H, status) = cv2.findHomography(ptsA, ptsB, cv2.RANSAC,
                reprojThresh)

            # return the matches along with the homograpy matrix
            # and status of each matched point
            return (matches, H, status)

        # otherwise, no homograpy could be computed
        return None
      def drawMatches(self, imageA, imageB, kpsA, kpsB, matches, status):
        # initialize the output visualization image
        (hA, wA) = imageA.shape[:2]
        (hB, wB) = imageB.shape[:2]
        vis = np.zeros((max(hA, hB), wA + wB, 3), dtype="uint8")
        vis[0:hA, 0:wA] = imageA
        vis[0:hB, wA:] = imageB

        # loop over the matches
        for ((trainIdx, queryIdx), s) in zip(matches, status):
            # only process the match if the keypoint was successfully
            # matched
            if s == 1:
                # draw the match
                ptA = (int(kpsA[queryIdx][0]), int(kpsA[queryIdx][1]))
                ptB = (int(kpsB[trainIdx][0]) + wA, int(kpsB[trainIdx][1]))
                cv2.line(vis, ptA, ptB, (0, 255, 0), 1)

        # return the visualization
        return vis

run.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 11:13:23 2017

@author: user
"""
# import the necessary packages
import os
os.chdir('/home/user/Desktop/stitcher')

from str import  Stitcher
import argparse
import imutils
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-f", "--first", required=True,
    help="path to the first image")
ap.add_argument("-s", "--second", required=True,
    help="path to the second image")
args = vars(ap.parse_args())
# load the two images and resize them to have a width of 400 pixels
# (for faster processing)

#from PIL import Image
#imageA = Image.open(args['first']).convert('RGB')
#imageB = Image.open(args['second']).convert('RGB')

imageA = cv2.imread(args["first"])
imageB = cv2.imread(args["second"])

#imageA = imutils.resize(imageA, width=400)
#imageB = imutils.resize(imageB, width=400)

imageA = cv2.resize(imageA,(2464,832)) #hardcoded values
imageB = cv2.resize(imageB,(2464,832)) #hardcoded values

# stitch the images together to create a panorama
stitcher = Stitcher()
(result, vis) = stitcher.stitch([imageA, imageB], showMatches=True)
cv2.imwrite('stage1.png',result)

# show the images
cv2.imshow("Image A", imageA)
cv2.imshow("Image B", imageB)
cv2.imshow("Keypoint Matches", vis)
cv2.imshow("Result", result)
cv2.waitKey(0)

As you can see, I have resized the images so that they have the same height and width with hardcoded values. I could have just got the minimum of two and put that as their length and breadth.
When I bring in the third image, I can't inflate it to match the resolution of stage1 or neither can I decrease the stage1's resolution to match the third image.
P.S. : imgutils didn't give me a way to choose both length and breadth.


text:
Q: Suspected error in proof about partitioned matrices in Matrix analysis by Roger Horn I'm quite confused when reading Horn and Johnson's Matrix analysis (second edition) p.20 , 0.7.6 Rank in a partitioned matrix and rank-principal matrices .
Denote $M_{m,n}(F)$ as the set of all $m\times n $ matrices over field $F$ (arbitrary) , for square matrices  use abbreviation .  Partition $A \in M_n(F)$ as
$$
A = \left(\begin{array}{rr}
A_{11} & A_{12} \\
A_{21} & A_{22}
\end{array}\right)
,\quad A_{11} \in M_r(F) , A_{22} \in M_{n-r}(F)
$$
The book attempts to prove (actually it's $\iff$ but I don't think it's relevant here)

$rk(A)=rk[A_{11}\;A_{12} ] = rk\begin{bmatrix}A_{11}\\ A_{21}\end{bmatrix} \implies A_{11}$ is nonsingular .

as follow

Suppose $A_{11}$ is singular , then $rk(A_{11})=k<r $ . There are nonsingular $S,T\in M_r(F)$ such that
$$
SA_{11}T = \left(\begin{array}{rr}
I_{k} & 0 \\
0 & 0_{r-k}
\end{array}\right)
$$
Therefore,
$$
\hat{A} =
\left(\begin{array}{rr}
S & 0 \\
0 & I_{n-r}
\end{array}\right) A
\left(\begin{array}{rr}
T & 0 \\
0 & I_{n-r}
\end{array}\right)
 =
 \left(\begin{array}{rr}
SA_{11}T & SA_{12} \\
A_{21}T & A_{22}
\end{array}\right)
$$
has rank $r$ , as do its block row and column . Because the $r^{th}$ row of the first block column of $\hat{A} $ is zero , there must be some column in $SA_{12}$ whose $r^{th}$ entry is not zero, which means that $\hat{A} $ has at least $r + 1$ independent columns. This contradicts $rank \hat{A} = rank A = r$ ,so $A_{11}$ must be nonsingular.
$\square$

Question : Why $rank \hat{A} = rank A = r ? $  I only know $rank \hat{A} = rank A$ since multiplication with nonsingular matrices won't change rank . I don't recall making any assumption on $A_{12}\in M_{r,n-r}(F),A_{21}\in M_{n-r,r}(F)$ and $A_{22}$ , so let all of them be $0$ , then $rk(\hat{A}) = k < r $ .
Nonetheless , if assume $rank \hat{A} = rank A = r $ , then the rest of the proof follows . I couldn't find such assumption .  Am I missing something ?


text:
Q: jQuery get class value from parent div I am trying to get the value in the class from 'quickCost' while I click on the 'icon-remove-sign'. I can get all of the html using the jQuery below but I don't know how to get to the class 'quickCost' from there to abstract the value.
In this case I am looking to get the $33.33 dollar amount.  My jQuery code outputs only the html. I am sure I am close. Thanks for any tips.

    1 CD
$33.33

jQuery
$( '.icon-remove-sign' ).click(function() {
    var theCost = $( $(this).parent() ).html();
    console.log(theCost); // Outputs all html in parent div
});

A: Use .next():

$('.icon-remove-sign').click(function() {
  var theCost = $(this).next('div.quickCost').text();
  console.log(theCost); // Outputs $33.33
});

  x1 CD

$33.33

A: You could also use .parent()
$('.icon-remove-sign').click(function() {
  var theCost = $(this).parent().find('.quickCost').text();
  console.log(theCost); // Outputs the text in .quickCost
});

https://jsfiddle.net/qLjuos62/


text:
Q: Deserialize a file with only methods I need to serialize/deserialize a Java file containing only methods calls into a JSON file.
I don't know if it's possible. I looked for it and I found mentions of the Reflection API.
This is the first time I've looked into JSON and would like to know if it's possible and if I'm on the right path.

A: There's two items here. Reading a JSON file, which you can do with a File Stream, and StreamReader. FileReader is an implementation of StreamReader, so that's a decent example below.
https://crunchify.com/how-to-read-json-object-from-file-in-java/
The second point is dynamically calling methods, and yes you are correct, you'd want to use reflection for this. For the below, scroll to the 'Get Class Object' section. Reflection carries with it it's own set of caveats, but it is useful for runtime-scripting. There are other options here though, depending on the complexity of your use case.
The last time I used it in Java was for the interface between a javascript interpreter and my application code, for a game project where I wanted my teammates to be able to script in-game events without requiring a new build for any changes.
https://www.journaldev.com/1789/java-reflection-example-tutorial
EDIT: Answering user's question:


text:
Q: Add thick borders to the corner edges of a view in android studio How can I add a thick lines across the corners of a view in android studio, something similar to what looks a photo frame. Something like the image given below.

A: In this case it would be significantly easier if you would just use a vector graphic as a backgound for this view, which then contains your content.
Then you would get the same effect but with a way lower programming effort.
EDIT:
If you want to get this effect using VectorGraphics you can just create that Gaphic with one of the free Vector Graphic tools like Inkscape, Gimp, or if you prefer an Online Version vectr.com. If you created this you can basically just copy it to your project folder and create a resource from it.
You can do this by right-clicking your drawable folder in AndroidStudio and choosing New>ImageResource. AndroidStudio should guide you through the process.
If you have done that, you go to the LayoutFile and switch to XML. Then you can just navigate to your view and add the line:
android:background="@drawable/yourNamehere"

This will make your Vector file, the BackgroudResource of the View.

A: You can make a custom view and draw thick lines on all corners like shown in the image.
You can then set the view as parent view of your imageview or any view & it will draw the frame around your view.
You can find more about drawing custom views here:
https://blog.mindorks.com/create-your-own-custom-view
You can draw lines (in this case, it's the only option), circles, rectangles & anything you want with custom views. Just give it a try & it will be fun. ;)


text:
Q: MVC4 Bundling: where the URL for bundle is held When the bundle is registered in MVC4, what is responsible for "intercepting" incoming http requests for /bundles/someBundle?v=1hDzBpmYJm4Iu-OjRN1YqS1WeNThVl0kStLJGP8WCr41?
also since hash for each bundle is calculated only once (at a first request), where is that actually held,  - and is it possible to return 404 if an incoming hash does not match

A:
what is responsible for "intercepting" incoming http requests for ~/bundles/someBundle

There are no incoming requests to ~/bundles/someBundle. It's the server side helper that you are using (Scripts.Render) that on the server (within the same HTTP requests) interprets this value and spits the correct url in the resulting HTML.

also since hash for each bundle is calculated only once (at a first request), where is that actually held,

The actual bundle contents is stored in the server side cache : HttpContext.Cache. The actual hash represents a SHA256 hash on this content that is calculated every time you use the Scripts.Render helper.

UPDATE:
It's the System.Web.Optimization.BundleModule that is auto-registered when you reference the System.Web.Optimization assembly that is responsible for intercepting requests to urls like /bundles/someBundle?v=1hDzBpmYJm4Iu-OjRN1YqS1WeNThVl0kStLJGP8WCr41 and returning the actual contents.

A: You should have a file called BundleConfig.cs in a folder App_Start in your web project.
That section basically links a url "/bundles/something" to some script(s). When in accessing the site in Release mode (not debug activated), it will automatically merge the script into one in-memory file, minimize the script, add caching headers to the request and generate a hash of the file content.
If you are in debug, all the scripts should be separated to make debugging easier.
You either redefine the bundles you see in that file or declare some of your own.
Enjoy.

A: The reason to append a query string with a parameter based on contents of actual files that you are serving is solving the caching problem. Sou you can inform browsers to cache this requests for a long period of time and speed up subsequent pages load times.
So for developers of this bundling mechanism there is no difference what that parameter is. Only thing that is important is that if you change contents of your scripts or css - hash would change and it will force clients browser to request new files from the server.
As for what is responsible for intersepting this requests - there is source code of MVC available on codeplex, but i guess it plugs right into routing.


text:
Q: How to rename dynamically file name I want to have the file names like this: Nr[first number in file]-[last number in file].txt.
this I have:
   static void Main(string[] args)
        {

            const int linesPerFile = 10;
            string path = @"G:\Folder";
            const string destinationFileName = @"G:\Folder\File-Part-{0}.txt";
            var bans = BankAcoutNumbers.BANS;
            string tempFile;
            //string fileName = "File";
            var maxNumberOfFiles = 10;
            Stopwatch timer = new Stopwatch();

                var fileCounter = 0;

                if (!Directory.Exists(path))
                {
                   DirectoryInfo di = Directory.CreateDirectory(path);
                }

                var destiNationFile = new StreamWriter(string.Format(destinationFileName, fileCounter + 1));
                try
                {

                    // foreach (var bank in BankAcoutNumbers.BANS.Take(100))
                    //{
                    var lineCounter = 0;
                    string line;

                    while (fileCounter <= maxNumberOfFiles)
                    {
                        timer.Start();
                        foreach (var bank in BankAcoutNumbers.BANS.Take(100))
                        {
                            if (lineCounter % linesPerFile == 0)
                            {
                                //lineCounter = 0;
                                destiNationFile.Flush();
                                destiNationFile.Dispose();
                                destiNationFile = new StreamWriter(string.Format(destinationFileName, fileCounter + 1));
                                fileCounter++;
                            }

                            destiNationFile.WriteLine(bank);
                            lineCounter++;

                        }

                        fileCounter++;

                        //}

                    }

                    timer.Stop();
                    // Console.WriteLine(BankAcoutNumbers.BANS.Count());
                    Console.WriteLine(timer.Elapsed.Seconds);
                }
                catch (Exception)
                {

                    throw;
                }

            // Keep the console window open in debug mode.

            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }

So the first file contains the numbers:
100000002
100000010
100000029
100000037
100000045
100000053
100000061
100000088
100000096
100000118
so the file name has to be then: Nr[100000002]-[100000118].txt
Thank you
and second file contains the numbers:
100000126
100000134
100000142
100000150
100000169
100000177
100000185
100000193
100000207
100000215

A: Unless your files are very long, you can simply read their full content into the memory, split up their content and rename them.
            // Get files
            DirectoryInfo di = new DirectoryInfo (@"c:\my\path");
            var files = di.GetFiles();

            // Loop through files
            foreach (var file in files)
            {
                // Read file
                string content = File.ReadAllText (file.FullName);

                // Split text (add as many separators as you want, I'm using
                // whitespace just like in your example)
                string[] numbers = content.Split (' ');

                // First number is numbers[0]
                // Last number is numbers[numbers.Length - 1]

                // Rename file
                File.Move(file.FullName, string.Format("Nr{0}-{1}.txt", numbers[0], numbers[numbers.Length - 1]));
            }


text:
Q: *args in recursion: TypeError: unsupported operand type(s) for +: 'int' and 'tuple' I am learning python. trying to use take *args as parameter in a recursion function (for addition of 'n' numbers), but getting error: Below is my code and error:

def add(*n):
  if len(n) == 1:
    return n[0]
  else:
    sum =  n[len(n)-1] + add(n[:-1])
  return sum

a = add(2,4,6)
print(a)

Error:
Traceback (most recent call last):
  File "/tmp/sessions/9d1de49c52e0e9b9/main.py", line 22, in <module>
    a = add(2,4,6)
  File "/tmp/sessions/9d1de49c52e0e9b9/main.py", line 18, in add
    sum =  n[len(n)-1] + add(n[:-1])
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

please explain what i am doing wrong

A: n[:-1] is returning a tuple, to get the last value into add use add(n[-1])
Edit:
working solution:

def add(*n):
    if len(n) == 1:
        return n[0]
    else:
        return n[-1] + add(*n[:-1])

A: I would propose a simpler setup:
def add(*n):
    if len(n) == 1:
        return n[0]
    return n[0] + add(*n[1:])    # n[1:] gives the "rest" of a list, i.e. all elements after the first.

*

*In a function definition (def add(*n):), the star collects multiple separate arguments into a list.
e.g. when you call add(2, 4, 6), then n will be a list [2, 4, 6]

*In a function call (add(*n)) the star spreads a list into multiple separate arguments.
e.g. when you have n = [2, 4, 6], then calling add(*n) will be as if you had called add(2, 4, 6)
In order to a list that to a function that collects its arguments, you need to spread it out first.
Your code did the first thing, but not the second. That's why it doesn't work:
def add(*n):                            # <-- collecting multiple arguments into a list
  if len(n) == 1:
    return n[0]
  else:
    sum =  n[len(n)-1] + add(n[:-1])    # <-- not spreading list into multiple arguments
  return sum

FWIW, an even shorter implementation would go like this
def add(*n):
    return 0 if not n else n[0] + add(*n[1:])


text:
Q: How do I repeat an ajax request until a condition is met with RxJS Observable? I'm attempting to repeat a request until the response has data using RxJS, at which point I'd like to call a success (or failure) handler, but I'm having trouble w/RxJS. Here's my current approach:
// ... redux-observable action observable
.mergeMap(() =>
    fetchData()
    .repeatWhen(response =>
        response.takeWhile(({ data }) => !data.length)
        .of(response)
    )
)
.map(successFunction)
.catch(failureFunction);

Disclaimer: I'm quite new to RxJS....

A: It's simpler to repeat the request on an interval, filter on its result and take one emission.
Observable.timer(0, 500)
  .flatMap(() => fetchData())
  .filter(r => r.data && r.data.length)
  .take(1)
  .timeout(10000)

http://jsbin.com/cafericore/1/edit?js,console

A: It sounds like you want to suppress ajax results and retry until you get the response you want.  I'd do it like so:
// observable that will re-fetch each time it is subscribed
const request = Observable.defer(() => fetchData());

// each time request produces its value, check the value
// and if it is not what you want, return the request
// observable, else return an observable with the response
// use switchMap() to then subscribe to the returned
// observable.
const requestWithRetry = request.switchMap(r =>
    r.data.length ? Observable.of(r) : requestWithRetry);

A: Empty data is not an error so first we check if the data is empty and throw an error if it is.
then retryWhen can be used to test for this error and retry as long as it's occurring.
.mergeMap(() =>
   fetchData()
   .map(data => {
       if (!data.length) {
          throw 'no data';
       }
       return data;
    })
   .retryWhen(errors => errors.takeWhile(error => error === 'no data'))
)
.map(successFunction)
.catch(failureFunction);


text:
Q: Можно ли в Wordpress изменить header для одной конкретной страницы для вывода на ней изображения из базы данных? Сохраняю изображения в базе данных MySQL в пользовательской таблице Wordpress в формате Blob.
Затем вывожу их в самописном плагине, который через шорткод подключается в определенной странице. Но для вывода из базы данных изображения в таком виде, нужно, чтобы выли установлены header("content-type:image/jpeg"); А так вместо изображения выводятся квакозябры.
Можно ли для этой страницы установить header?


text:
Q: Kafka Flink logging issue I am working on Kafka Flink integration actually I am done with that integration , I have written a simple word count program in Java using Flink API, when I ran it by java -jar myjarname it worked fine but when I tried to ran it with ./bin/flink run myjarname command it was giving me following error,
NoSuchMethodError:org.apache.flink.streaming.api.operators.isCheckpointingEnabled
The respected jar is there but still it is giving me above error.


text:
Q: Java setText not updating after button click I am making a count up timer using buttons to start and stop.
I need help solving this... when I press the "Start" Button it works (tested using System.out.print) but the setText doesn't update for me.
However If put the t.start(); after frame.setVisible(true); instead of after start = 1; the setText does update... but it's without me pressing the "Start" Button. How do I make setText to update after "Start" Button is pressed?
public class Cook implements ActionListener{

    private enum Actions {
        Start, Stop, Setting, Exit
      }

    JLabel minsleft;
    int start = 0, counter, stop = 0, close = 0, whileloop = 0;

     JFrame frame = new JFrame("SMART STOVE");
    public void Cook() {

        Cook instance = new Cook();
        // TODO Auto-generated method stub
         JLabel minsleft = new JLabel();
         minsleft.setFont(new Font("Serif", Font.BOLD, 17));
         minsleft.setBounds(100,300,250,40);

         try {
            frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("src\\cook.png")))));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            JButton Start = new JButton("Start");
            Start.setFont(new Font("monospaced", Font.BOLD, 30));
            Start.setActionCommand(Actions.Start.name());
            Start.addActionListener(instance);
            Start.setBounds(150, 180, 200, 100);
            frame.add(Start);

            JButton Stop = new JButton("Stop");
            Stop.setFont(new Font("monospaced", Font.BOLD, 30));
            Stop.setActionCommand(Actions.Stop.name());
            Stop.addActionListener(instance);
            Stop.setBounds(360, 180, 200, 100);

            frame.add(Stop);
            countdownLabel.setBounds(360, 250, 200, 100);
            frame.add(countdownLabel);

            frame.setLayout(null);
            frame.setSize(700, 500);
            frame.setVisible(true);

    }
    @Override
    public void actionPerformed(ActionEvent evt) {
        // TODO Auto-generated method stub
        if (evt.getActionCommand() == Actions.Start.name()) {
            start = 1;
            t.start();
          }

        if (evt.getActionCommand() == Actions.Stop.name()) {
            close = 1;
          }
        System.out.println("Done");
    }

    final JLabel countdownLabel = new JLabel("Waiting. . . ");
    public Timer t = new Timer(1000, new ActionListener() {
        int time = 0;
        @Override
        public void actionPerformed(ActionEvent e) {
            time++;
            countdownLabel.setText(format(time / 60) + ":" + format(time % 60));
            System.out.println(format(time / 60) + ":" + format(time % 60));
            if (close == 1) {
                final Timer timer = (Timer) e.getSource();
                timer.stop();
                System.out.println("Stopped");
            }
        }
    });

    private static String format(int i) {
        String result = String.valueOf(i);
        if (result.length() == 1) {
            result = "0" + result;
        }
        return result;
    }

}

A: I was wondering how you are running the code, while there is no main. So I added one
public static void main(String[] args) {
    new Cook().Cook();
}

Then I was wondering why are you creating new Cook instance in Cook method (very bad naming for Java).
Cook instance = new Cook();

So I removed it and changed Start.addActionListener(instance); to Start.addActionListener(this); and it is working now...
I'd also add default close operation otherwise it is not closed really...
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Full Code:
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

public class Cook implements ActionListener{

    private enum Actions {
        Start, Stop, Setting, Exit
      }

    JLabel minsleft;
    int start = 0, counter, stop = 0, close = 0, whileloop = 0;

     JFrame frame = new JFrame("SMART STOVE");
    public void Cook() {

//        Cook instance = new Cook();
        // TODO Auto-generated method stub
         JLabel minsleft = new JLabel();
         minsleft.setFont(new Font("Serif", Font.BOLD, 17));
         minsleft.setBounds(100,300,250,40);

         try {
            frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("src\\cook.png")))));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            JButton Start = new JButton("Start");
            Start.setFont(new Font("monospaced", Font.BOLD, 30));
            Start.setActionCommand(Actions.Start.name());
            Start.addActionListener(this);
            Start.setBounds(150, 180, 200, 100);
            frame.add(Start);

            JButton Stop = new JButton("Stop");
            Stop.setFont(new Font("monospaced", Font.BOLD, 30));
            Stop.setActionCommand(Actions.Stop.name());
            Stop.addActionListener(this);
            Stop.setBounds(360, 180, 200, 100);

            frame.add(Stop);
            countdownLabel.setBounds(360, 250, 200, 100);
            frame.add(countdownLabel);

            frame.setLayout(null);
            frame.setSize(700, 500);
            frame.setVisible(true);

    }
    @Override
    public void actionPerformed(ActionEvent evt) {
        // TODO Auto-generated method stub
        if (evt.getActionCommand() == Actions.Start.name()) {
            start = 1;
            t.start();
          }

        if (evt.getActionCommand() == Actions.Stop.name()) {
            close = 1;
          }
        System.out.println("Done");
    }

    final JLabel countdownLabel = new JLabel("Waiting. . . ");
    public Timer t = new Timer(1000, new ActionListener() {
        int time = 0;
        @Override
        public void actionPerformed(ActionEvent e) {
            time++;
            countdownLabel.setText(format(time / 60) + ":" + format(time % 60));
            System.out.println(format(time / 60) + ":" + format(time % 60));
            if (close == 1) {
                final Timer timer = (Timer) e.getSource();
                timer.stop();
                System.out.println("Stopped");
            }
        }
    });

    private static String format(int i) {
        String result = String.valueOf(i);
        if (result.length() == 1) {
            result = "0" + result;
        }
        return result;
    }

    public static void main(String[] args) {
        new Cook().Cook();
    }

}