text:
Q: Um método para várias classes Estava lendo que o uso de herança é quase que "errado" (vi em uma matéria da Caellum), que o certo é usar interface. Até aí, ok, fiz uma interface, só que a interface só me deixa colocar a assinatura do método, e quero que todo mundo que use a interface na verdade utilize um método com corpo. Ex: minha interface é pessoa. Quero que todas as classe que implementam pessoa, utilizem o método formatarCPF(), porém, a interface não me deixa fazer isso, aí vou ter que fazer com que cada classe que implementa pessoa, tenha o código do formatarCpf() copiado dentro da classe.
Sou novato, mas a ideia da POO não é exatamente não copiar código?

A: Tem alguns erros aí. Herança não é quase errado, é certo quando faz sentido, geralmente quando atende o princípio de Liskov. Quando a herança não é adequada então a composição é mais interessante.
É comum, mas não obrigatório que só deveria herdar de classes abstratas ou interfaces, então a herança está certa, até porque herdar delas ainda é herança de alguma forma. O problema é só deve pensar bem se deve herdar de classe concreta, só isso. Em geral quando herda de classe concreta está misturando conceitos e tende a confundir objetos, mas há casos que são exceções, por isso é permitido.
Não é verdade que interface só tem assinatura, pelo menos desde Java 8, portanto há muito tempo isto não é verdade, então você a herda normalmente, antes você herdava o tipo mas não a implementação.
Só dá para modelar objeto de forma correta sabendo todos os requisitos (que quase sempre não são pegos de forma adequada), mas posso dizer que parece que você precisa de uma classe abstrata Pessoa e não uma interface. Parece que deveria ter uma classe concreta herdado dessa classe que poderia ser PessoaFisica já que tem um CPF. O CPF não poderia estar em Pessoa porque uma pessoa pode ser jurídica e não ter CPF.
Mesmo que optasse pela interface poderia ter o método que quisesse. Só não sei se formatação deveria fazer parte da classe que modela uma pessoa. Uma pessoa não deveria formatar CPF, deveria ter uma classe só para formatar coisas ou até o CPF se auto formatar em classe própria, seguindo o SRP.
Não estou dizendo para fazer, mas uma alternativa de modelar de forma mais fácil é esquecer OO, já que é difícil fazer assim, ao contrário do que as pessoas imaginam.
Reuso de código e não "não copiar código" é uma característica de orientação a objeto, mas não exclusivo dela. De qualquer forma parece que leu um material que está dando indicações ruins para você. Por isso eu sempre falo que indicação de material é complicado. Você pode estar lendo um material indicado por um monte de gente e ele ainda ser ruim ou errado. As pessoas aprendem errado com um material e passam indicá-lo como se fosse bom, até porque ela não tem o senso crítico necessário. É fake news por todo lado.
Você ainda está bem longe do entendimento do que é orientação a objeto e não está modelando bem, talvez porque esteja seguindo receita de bolo passada em algum material. Modelar é pensar, é entender o todo. Tem umas regrinhas, mas não para seguir, é só para orientar. Tem que entender porque elas existem para modelar certo.


text:
Q: DB2 join files from 2 libraries I have two libraries with files I need.  I have added both libraries to my ODBC library list.  I have tried using qualified names datalib/fgdetl and just fgdetl to join to tables in a library apluslib.  I am not having any success with this.
I am receiving the following error:
'42S02', '[42S02] [IBM][System i Access ODBC Driver][DB2 for i5/OS]SQL0204 - USEML in APLUSV8FAQ type *FILE not found. (-204) (SQLExecDirectW)')

I am using ODBC and DB2/SQL query to pull data.
Thanks in advance for any help!

A: The System i Access ODBC Driver for DB2 uses a "." syntax of LIBRARY.FILE so just change your references to DATALIB.FGDETL and that should work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Media query not working in iPhone 5s landscape mode I have a media query resembling:
@media screen and (max-width: 600px) {
  .blah {
    font-size: 1.25rem;
  }
}

In responsive testing mode in browser dev tools, everything works fine. I can see all the changes as I drag and scale the mock viewport.
On the iPhone 5s (actual) device, portrait mode works fine, but in landscape mode on the device, it's not respecting this same media query.
Things I've tried include:

*

*Changing the text color in the rule (yup, it's bright red alright, so I know my rule is being applied)

*Ensuring that I've included the usually recommended viewport meta tag (along with the other version that includes the device rule)

*Bumping up max-width to an even larger number, in case landscape mode was being interpreted as wider than its standard setting (568px?)

*Using pixels instead of rems, and here's where I finally noticed something that is happening.

After setting the text to a teeny 8px and again confirming that portrait mode works fine, I noticed that in landscape mode, the text size is being affected, and in fact it's scaling the text, but still not according to my specified size (again, as rendered correctly in portrait mode, and I've already established that the max-width is "registering" in landscape mode).
Does this tell me something? What do you think is happening here, something device/version specific?
The fact that font-size does seem to change in landscape mode, but not to the size I specify (and can see correctly in portrait mode--8px is very small, but in landscape mode it's only reducing slightly in size), sounds almost like the device/browser is "helping out" according to its own rules.
But as mentioned, I've included: <meta name="viewport" content="initial-scale=1.0"> and can see it in my outputted HTML. <meta name="viewport" content="width=device-width, initial-scale=1.0">, same result.
This question is similar to another, which was left unanswered: iPhone 5 landscape media queries not working. The upvoted response there ignores the context of and fails to answer the original question, and doesn't answer mine, either.
(Also note that the above poster appeared to be experiencing a similar problem, without resolution/explanation.)
ANOTHER UPDATE: I can specify a media query specifically for this case:
@media only screen
and (min-device-width : 320px)
and (max-device-width : 568px)
and (orientation : landscape) {
  .blah {
    font-size: .5rem;
  }
}

And I can adjust the font size, but the numbers don't match--I just have to eyeball it and choose smaller and smaller numbers until I get the size I want. And (yet) again, this is only in landscape mode, despite having the correct max-width in my media query (so I know it's working).
I've tried other things, with different sizes and colors each time to confirm that changes are working, adding !important (to no real effect), and can only conclude that something "weird" is happening on my iPhone 5s when rendering in Landscape mode only. It appears to not be adhering strictly to my viewport setting, which I have verified is present in the rendered HTML, and making some odd choices of its own.

A: Okay, I think it's working now. I've used a landscape-specific media query targeting my device screen size:
@media only screen
and (min-device-width : 320px)
and (max-device-width : 568px)
and (orientation : landscape) {
  html {
    -webkit-text-size-adjust: none; /* none for no scaling */
  }
}

This was recommended here and here. All my other settings are being picked up now, too (because it wasn't just one rule--I was changing multiple elements in the media query).
(Thanks to those posters for their solutions. :)


text:
Q: Vim Fireplace with nREPL on docker won't run tests I have a docker container which runs lein repl :start :host 0.0.0.0 :port 7888 (I also exposed the ports via the -p switch like docker run -p 7888:7888).
Now, when I switch to vim and connect to the REPL, everything seems to work as expected. I can evaluate code via cqp and it is evaluated on that docker machine.
However, when I want to run the tests in a test file via the cpr combination, vim shows that it executes (clojure.test/run-tests 'users.models.users-it-test) in its status bar but none of the tests is really executed nor do I get a report on what happened. I can also add any failing tests like
(deftest shouldnt-work
  (is (= 3 4))

but no exception is thrown.
Even stranger: When I execute the tests via cqp and then
(clojure.test/run-tests), the tests are actually run and
the correct/failing result is printed.
My .vimrc looks like this:
" Plugins
call vundle#begin()

Plugin 'gmarik/Vundle.vim'
Plugin 'danro/rename.vim'
Plugin 'guns/vim-clojure-static'
Plugin 'scrooloose/nerdtree'
Plugin 'ctrlpvim/ctrlp.vim'
Plugin 'tpope/vim-salve'
Plugin 'tpope/vim-classpath'
Plugin 'tpope/vim-fireplace'
Plugin 'paredit.vim'

call vundle#end()
filetype plugin indent on
" End Plugins

" Add and delete spaces in increments of 'shiftwidth' for tabsb
set smarttab
set number
set tabstop=2
set shiftwidth=2
set expandtab
set noesckeys
syntax on

A: It seems like there was a conflict in my vim files causing the whole thing not to run.
I now removed rename.vim, ctrlp.vim and vim-clojure-static (since it is already contained in Vim beginning from version 7.4). Also I reordered my plugins, so that it looks like this now:
Plugin 'gmarik/Vundle.vim'
Plugin 'altercation/vim-colors-solarized'
Plugin 'scrooloose/nerdtree'
Plugin 'paredit.vim'
Plugin 'tpope/vim-salve'
Plugin 'tpope/vim-classpath'
Plugin 'tpope/vim-fireplace'


text:
Q: Setup DHCP server in GNU/Linux without internet how its going?
I am trying to create a local network between an offline computer and my laptop.
My goal is for that computer to be on a closed network with my laptop (no internet connectivity, just sharing an ethernet cable).
I have been trying with isc-dhcp-server (https://www.youtube.com/watch?v=1csFmQeXHlg) and then with networkd (https://askubuntu.com/questions/1380719/ubuntu-server-20- 04-installing-a-dhcp-without-internet-access). In the case of isc-dhcp-server, it gave me an error that it was not configured to listen on any interface (I already configured /etc/default/isc-dhcp-server) and networkd simply after running nmap told me "failed to determine route to 192.18.x.xxx" for each IP.
Any idea what is next? Thanks in advance and have a good day.


text:
Q: Personalized listview android studio (First of all sorry my bad english)
I am doing an app about routes in my town, is like a project of my grade, and I have it done it all but I don't know what is the problem..
My problem is that the ListView that I made from a ViewHolder it doesn't show up when I start the app.
My code is this:
MainActivity:
public class RutasActivity extends AppCompatActivity {
    private static final String LOGO = "";
    ImageButton btnImgAtras;
    private ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rutas);

        lv = (ListView)findViewById(R.id.lvRutas);

        RutasParser parser = new RutasParser(this);

        if(parser.parse()) {

            Ruta[] rutas = parser.getRutas();

            RutaAdapter adapter = new RutaAdapter(this, rutas);
            lv.setAdapter(adapter);

            Toast.makeText(this, "Enseñando", Toast.LENGTH_SHORT).show();
        } else {

            Toast.makeText(this, "No se pudieron obtener los datos de los países", Toast.LENGTH_SHORT).show();
        }

        btnImgAtras = (ImageButton)findViewById(R.id.imgBtnAtras);
        btnImgAtras.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(RutasActivity.this, MainActivity.class);
                startActivity(i);
            }
        });
    }
}

Activity Layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RutasActivity"
    >

    <ImageView
        android:layout_width="45dp"
        android:layout_height="44dp"
        app:srcCompat="@drawable/escudoazulsinfondo"
        android:id="@+id/imageView5"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginEnd="16dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginRight="16dp"
        android:contentDescription="" />

    <TextView
        android:text="@string/Rutas_Javea"
        android:textSize="20sp"
        android:textColor="@color/Blacky"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView4"
        android:layout_marginTop="32dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginEnd="16dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginRight="16dp"
        android:layout_marginStart="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginLeft="16dp" />

    <ImageButton
        android:layout_width="32dp"
        android:layout_height="32dp"
        app:srcCompat="@drawable/atras"
        android:id="@+id/imgBtnAtras"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="16dp"
        android:background="@android:color/transparent"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp" />

    <ListView
        android:layout_width="312dp"
        android:layout_height="358dp"
        android:id="@+id/lvRutas"
        android:layout_marginStart="24dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginLeft="24dp"
        android:layout_marginEnd="24dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginRight="24dp"
        app:layout_constraintHorizontal_bias="0.45"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="24dp"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toTopOf="parent" >
    </ListView>

    <ImageView
        android:layout_width="105dp"
        android:layout_height="36dp"
        app:srcCompat="@drawable/depturismenofondo"
        android:id="@+id/imageView6"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="16dp"
        android:layout_marginStart="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginLeft="16dp"
        tools:ignore="ContentDescription" />

</android.support.constraint.ConstraintLayout>

Then, my AdapterView:
public class RutaAdapter extends ArrayAdapter<Ruta> {

    Ruta[] rutas;

    public RutaAdapter(Context context, Ruta[]rutas) {
        super(context, R.layout.listitem_ruta, rutas);
        this.rutas = rutas;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View item = convertView;
        ViewHolder viewHolder;

        if(item == null) {

            LayoutInflater inflater = LayoutInflater.from(getContext());

            item = inflater.inflate(R.layout.listitem_ruta, null);

            viewHolder = new ViewHolder();

            viewHolder.vhKm = (TextView) item.findViewById(R.id.listKm);
            viewHolder.vhNombreRuta = (TextView) item.findViewById(R.id.listNombre);
            viewHolder.vhDesnivel = (TextView) item.findViewById(R.id.listDesnivel);
            viewHolder.vhDificultad = (TextView) item.findViewById(R.id.listDificultad);
            viewHolder.vhTiempoTotal = (TextView) item.findViewById(R.id.listTiempo);

            item.setTag(viewHolder);
        } else {

            viewHolder = (ViewHolder)item.getTag();
        }

        viewHolder.vhKm.setText(String.valueOf(rutas[position].getDistancia()));
        viewHolder.vhNombreRuta.setText(rutas[position].getNombre());
        viewHolder.vhDificultad.setText(rutas[position].getNivel_dificultad());
        viewHolder.vhTiempoTotal.setText(rutas[position].getTiempo_efectivo());
        viewHolder.vhDesnivel.setText(String.valueOf(rutas[position].getDesnivel_acumulado_ascenso()));

        return item;
    }

    static class ViewHolder {
        TextView vhNombreRuta;
        TextView vhKm;
        TextView vhDificultad;
        TextView vhTiempoTotal;
        TextView vhDesnivel;
    }
}

My parser:
public class RutasParser {

    private Ruta[] rutas;
    private InputStream rutasFile;

    public RutasParser(Context c) {
        this.rutasFile = c.getResources().openRawResource(R.raw.rutas);
    }

    public boolean parse() {
        boolean parsed = false;
        rutas = null;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document dom = builder.parse(rutasFile);
            Element root = dom.getDocumentElement();
            NodeList items = root.getElementsByTagName("country");
            rutas = new Ruta[items.getLength()];
            for (int i = 0; i < items.getLength(); i++) {
                Node item = items.item(i);

                int rutaId = Integer.parseInt(item.getAttributes().getNamedItem("code").getNodeValue());
                String rutaNombre = item.getAttributes().getNamedItem("name").getNodeValue();
                String rutaDescrip = item.getAttributes().getNamedItem("description").getNodeValue();
                double rutaDistance = Double.valueOf(item.getAttributes().getNamedItem("distance").getNodeValue());
                String rutaHora = item.getAttributes().getNamedItem("horas").getNodeValue();
                String rutaDif = item.getAttributes().getNamedItem("dificultad").getNodeValue();
                int rutaElev = Integer.valueOf(item.getAttributes().getNamedItem("elevacion").getNodeValue());

                rutas[i] = new Ruta(rutaId, rutaNombre, rutaDescrip, rutaDistance, rutaDif, rutaHora, rutaElev);
            }

            parsed = true;
        } catch (ParserConfigurationException pce) {
            Log.e("CountryParser", "ParserConfigurationException: "+pce.getLocalizedMessage());
        } catch (Exception e) {
            Log.e("CountryParser", "Unknown Exception: "+e.getLocalizedMessage());
        }
        return parsed;
    }

    public Ruta[] getRutas() {
        return this.rutas;
    }
}

And the ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00.00km"
        android:textSize="30sp"
        android:id="@+id/listKm"
        android:layout_gravity="center_horizontal|center_vertical"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:orientation="vertical"
        android:paddingLeft="3dp"
        android:paddingStart="3dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:text="nombre de ruta"
            android:id="@+id/listNombre"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/listDificultad"
                android:text="dificultad"
                android:paddingRight="10dp"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/listTiempo"
                android:text="000000"
                android:paddingRight="10dp"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/listDesnivel"
                android:text="000000"/>

            </LinearLayout>
        </LinearLayout>
</LinearLayout>

At first place I don´t see any error but it doesn´t show up in my app..
If you can help me, I would be grateful..
Thanks
Photo of what I tell you


text:
Q: Add Avatar to Material-UI AppBar I'm trying to add an Avatar to an AppBar. However, the Avatar is not getting added to the  AppBar. Could you please assist me. Please refer the attached image for my coding

A: V1+ documentation : https://material-ui.com/api/app-bar/
V0+ documentation : https://v0.material-ui.com/#/components/app-bar
The property "iconElementRight" is only available on v0+
If you migrated to the V1 you have to add the icon yourself as a child of the AppBar.


text:
Q: ASP.NET MVC download csv file through modal popup I'm trying to download a csv file through asp.net mvc controller, but since I need user to make a selection input via dropdown list, I created a bootstrap modal pop-up.
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { @class = "modal-form" }))
{

                @Html.Label("locationTypeId", new { @class = "control-label col-md-3" })

                    @Html.DropDownList("locationTypeId", Model.LocationList, new { @class = "form-control" })

        <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
        <button class="btn btn-primary" type="submit">Save</button>

}

Once user clicks Save button, it would post to the controller as such:
[HttpPost]
public ActionResult Create(DefaultViewModel model)
{
    if (ModelState.IsValid)
    {
        try
        {
            var repository = new SqlRepository(model);
            // go about creating csv file

            // returns byte[]
            var output = repository.CreateShipmentDataUpload();

            //DownloadCSV();
            return Json(new { success = true });
        }
        catch (Exception e)
        {
            ModelState.AddModelError("", e.Message);
        }
    }

    return PartialView("_Create", model);
}

I'm not sure if I can/should call DownloadCSV() there. Here's the DownloadCSV():
public FileContentResult DownloadCSV(byte[] byteArray)
{
    return File(byteArray, "text/csv", "report.csv");
}

And here's the ajax success function call:
@section Scripts {

}

How do I get to download the csv file to work properly?

A: *

*Take the form control out of the modal popup

*Make your modal submit button call js script to close modal and fire ajax call back Download CSV method on the controller passing in the selection they made on the modal dropdown (get their selection by getting val of field by the elements ID

*Do the byte parsing logic and return file in Download CSV method
The big idea around modal pop-ups and such is not to kill your user with page reloads. You've taken care of all of the hard work already with the modal popup and an ajax call, then your firing off a page load at the end. That's like running a race then sitting down 5 feet in front of the finish line.
Example
Test class to show in dropdown:
public class Whatever
{
    public int locationTypeId { get; set; }
    public List<SelectListItem> Locations { get; set; }
}

Controller Methods:
    public ActionResult Wut()
    {
        Whatever wut = new Whatever();
        wut.Locations = new List<SelectListItem>();
        wut.Locations.Add(new SelectListItem { Text = "Uno", Value = "1" });
        wut.Locations.Add(new SelectListItem { Text = "Dos", Value = "2" });
        return View(wut);
    }
    public FileContentResult DownloadCSV(string location)
    {
        return File(new System.Text.UTF8Encoding().GetBytes("Generate, CSV, LOGIC, HERE, DEPENDING, ON, LOCATION"), "text/csv", "Example" + DateTime.Now.ToString("_MM-dd-yyyy-mm-ss-tt") + ".csv");
    }

View:
    @model DeleteMeWeb.Controllers.Whatever

Show Modal

Modal title

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                    @Html.DropDownList("locationTypeId", Model.Locations, new { @class = "form-control" })

Save changes

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

JS:
    @section scripts
    {

    }

A: You can't return a Json response and a FileContentResult with the same Ajax call. You can either:-

*

*Send the $.ajax request to carry out form validation (before creating the file for download), and if the validation is ok ($.ajax success), then send another "fire and forget" request to create and download the form using a FileContentResult action from within the original $.ajax success function. Or

*Just send the "fire and forget" and return an empty file (or no file) if the validation fails.
Both scenarios allow you to close the modal in a controlled way without reloading the page; the FileContentResult simply downloads the file without affecting the View.
One way of carrying out a "fire and forget" is:
var data = { id: "someId" };
var form = document.createElement("form");
form.setAttribute("method", "GET");
form.setAttribute("action", "url/to/DownloadCSV");
if (data != null && data.constructor === Object) {
    for (var key in data) {
        if (data.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", data[key]);
            form.appendChild(hiddenField);
        }
    }
}
document.body.appendChild(form);
form.submit();
form.remove();

This would go (or be referenced) in the if (result.success) { } part of the $.ajax request (if you intend to validate), along with $('#modalDialog').modal('hide'); (but not location.reload();)
The file download action would then be something like:
public FileContentResult DownloadCSV(string someParameterToMakeTheFileIfNeeded)
{
    // Make the file and then return the FileContentResult here
    return File(byteArray, "text/csv", "report.csv");
}

There are different ways to skin this cat, and it's worth researching what's out there, but I find this works for me.


text:
Q: c# hight memory used. for ManagementObjectSearcher private void Form1_Load(object sender, EventArgs e)
{

    t = new Thread(new ThreadStart(serialcek));
    CheckForIllegalCrossThreadCalls = false;
    t.Start();
  }

public void serialcek()
{

    ManagementObjectSearcher theSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'");
    try
    {
        foreach (ManagementObject currentObject in theSearcher.Get())
        {
            ManagementObject theSerialNumberObjectQuery = new ManagementObject("Win32_PhysicalMedia.Tag='" + currentObject["DeviceID"] + "'");
            try
            {
                serial = theSerialNumberObjectQuery["SerialNumber"].ToString();
                textBox1.Text = serial;
            }
            catch (Exception)
            {
                // MessageBox.Show("Bişiler oldu bende anlamadım");

            }

        }
        Thread.Sleep(sure);
        serialcek();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Patladım ben." + ex.Message.ToString());
    }

}

use thread. but i can't stop it. thread always run and application used memory high.
give an error a few mins later.  maybe i can't use for function  true.

A: It's because you call the thread's method recursively without any exit condition. That will eventually lead to a StackOverflowException.
Instead of this approach, you should place a while loop inside you thread's method. This is of course implemented roughly, just to give you the idea:
bool exitThread;

private void Form1_Load(object sender, EventArgs e)
{

    t = new Thread(new ThreadStart(serialcek));
    CheckForIllegalCrossThreadCalls = false;
    exitThread = false;
    t.Start();
  }

public void serialcek()
{

    ManagementObjectSearcher theSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'");
    while (! exitThread)
    {
        try
        {
            foreach (ManagementObject currentObject in theSearcher.Get())
            {
                ManagementObject theSerialNumberObjectQuery = new ManagementObject("Win32_PhysicalMedia.Tag='" + currentObject["DeviceID"] + "'");
                try
                {
                    serial = theSerialNumberObjectQuery["SerialNumber"].ToString();
                    textBox1.Text = serial;
                }
                catch (Exception)
                {
                    // MessageBox.Show("Bişiler oldu bende anlamadım");

                }

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Patladım ben." + ex.Message.ToString());
        }
        finally
        {
            // Moved Sleep into 'finally' block to make it be called even if an exception occurs
            Thread.Sleep(sure);
    }
}

And then you can exit this thread anytime you like by simply assigning true to exitThread:
private void Button1_Click(object sender, EventArgs e)
{
    exitThread = true;
}


text:
Q: too many items in toc I am using "The Legrand Orange Book" template from Mathias Legrand on http://www.LaTeXTemplates.com for a collection of "some" poems and
unfortunately I run into a problem, I can't handle myself:
I have so many sections, that the list in the toc is somehow miss-printed. Is it possible to set a max. number of items for the toc and then let a new page start with the other items?
I have provided a picture with my problem and also contacted the developer, but he answered:
... part page cannot spread over more than one page because of the use of Tikz and a \parbox. See below in structure.tex

\node[anchor=south east] at (\paperwidth-1cm,-\paperheight+1cm){\parbox[t][][t]{8.5cm}{
\printcontents{l}{0}{\setcounter{tocdepth}{1}}}};, hope you will be able to

Hope someone here can help :)
Thanks and happy x-mas by the way :)

A: Here is a solution we save the partial toc in \vbox and use \vsplit
 \global\setbox\mtpbox=\vbox{\printcontents{l}{0}{\setcounter{tocdepth}{1}}}

complete code
\documentclass[11pt,fleqn]{book}
\input{structure}

\newbox\mtpbox

\makeatletter
\def\@part[#1]#2{%
\ifnum \c@secnumdepth >-2\relax%
\refstepcounter{part}%
\addcontentsline{toc}{part}{\texorpdfstring{\protect\@mypartnumtocformat{\thepart}{#1}}{\partname~\thepart\ ---\ #1}}
\else%
\addcontentsline{toc}{part}{\texorpdfstring{\protect\@myparttocformat{#1}}{#1}}%
\fi%
\startcontents%
\markboth{}{}%
{\thispagestyle{empty}%
\global\setbox\mtpbox=\vbox{\printcontents{l}{0}{\setcounter{tocdepth}{1}}}
\begin{tikzpicture}[remember picture,overlay]%
\node at (current page.north west){\begin{tikzpicture}[remember picture,overlay]%
\fill[ocre!20](0cm,0cm) rectangle (\paperwidth,-\paperheight);
\node[anchor=north] at (4cm,-3.25cm){\color{ocre!40}\fontsize{220}{100}\sffamily\bfseries\@Roman\c@part};
\node[anchor=south east] at (\paperwidth-1cm,-\paperheight+1cm){\parbox[t][][t]{8.5cm}{
\ifdim\ht\mtpbox<\textheight\box\mtpbox\else\vsplit\mtpbox to 15\baselineskip\fi%
}};
\node[anchor=north east] at (\paperwidth-1.5cm,-3.25cm){\parbox[t][][t]{15cm}{\strut\raggedleft\color{white}\fontsize{30}{30}\sffamily\bfseries#2}};
\end{tikzpicture}};
\end{tikzpicture}}%
\@endpart}

\def\@endpart{\vfil\newpage
\ifvoid\mtpbox\else\unvbox\mtpbox\vfil\newpage\fi
\ifodd\value{page}\else
\if@twoside
\if@openright
\null
\thispagestyle{empty}%
\newpage
\fi
\fi
\if@tempswa
\twocolumn
\fi\fi}
\makeatother

\begin{document}

\part{Part One}
\foreach \x in {1,...,30} {
\chapter{A chapter with number \x}
\section{A section}
\subsection{A subsection}
}

\part{Part One}
\foreach \x in {1,...,36} {
\chapter{A chapter with number \x}
\section{A section}
\subsection{A subsection}
}
\end{document}

Update: changes commented in code
\makeatletter
\def\@part[#1]#2{%
\ifnum \c@secnumdepth >-2\relax%
\refstepcounter{part}%
\addcontentsline{toc}{part}{\texorpdfstring{\protect\@mypartnumtocformat{\thepart}{#1}}{\partname~\thepart\ ---\ #1}}
\else%
\addcontentsline{toc}{part}{\texorpdfstring{\protect\@myparttocformat{#1}}{#1}}%
\fi%
\startcontents%
\markboth{}{}%
{\pagestyle{empty}%
\global\setbox\mtpbox=\vbox{\printcontents{l}{0}{\setcounter{tocdepth}{1}}}
\loop    %  use a boocle: loop
\begin{tikzpicture}[remember picture,overlay]%
\node at (current page.north west){\begin{tikzpicture}[remember picture,overlay]%
\fill[ocre!20](0cm,0cm) rectangle (\paperwidth,-\paperheight);
\node[anchor=north] at (4cm,-3.25cm){\color{ocre!40}\fontsize{220}{100}\sffamily\bfseries\@Roman\c@part};
\node[anchor=south east] at (\paperwidth-1cm,-\paperheight+1cm){\parbox[t][][t]{8.5cm}{
\ifdim\ht\mtpbox<16\baselineskip\box\mtpbox\else\vsplit\mtpbox to 15\baselineskip\fi%
 % rather then \textheight we use 16\baselineskip for example
}};
\node[anchor=north east] at (\paperwidth-1.5cm,-3.25cm){\parbox[t][][t]{15cm}{\strut\raggedleft\color{white}\fontsize{30}{30}\sffamily\bfseries#2}};
\end{tikzpicture}};
\end{tikzpicture}%
\vfil\newpage  % go to next page
\unless\ifvoid\mtpbox\repeat} % end of boocle
\@endpart}

\def\@endpart{\vfil\newpage
%\ifvoid\mtpbox\else\unvbox\mtpbox\vfil\newpage\fi  % not used any more
\ifodd\value{page}\else
\if@twoside
\if@openright
\null
\thispagestyle{empty}%
\newpage
\fi
\fi
\if@tempswa
\twocolumn
\fi\fi}
\makeatother

A: Here's a proposition (however, not for the 'famous' Orange Book, but it works with that too, I've checked!)
\documentclass{book}
% Insert this to the file of the thesis
\newcounter{limitperpage}
\setcounter{limitperpage}{15}

\newcounter{tocentries}

\usepackage{xpatch}

\xapptocmd{\addcontentsline}{\ifstrequal{#1}{toc}{%
    \stepcounter{tocentries}%
    }{}%
    \ifnum\value{tocentries} = \value{limitperpage}
    \addtocontents{toc}{\protect\clearpage}%
    \setcounter{tocentries}{0}%
    \fi
}{}{}

%before \begin{document}

\usepackage{pgffor}

\begin{document}
\tableofcontents
\foreach \x in {1,...,100} {
\chapter{A chapter with number \x}
\section{A section}
\subsection{A subsection}
}

\end{document}


text: Q: how to solve 404 post error in bot framework emulator as using hosted url on godadday? I have created bot using echo bot template of visual studio and then hosted it on godadday, used that url to registered  on microsof bot framework, created app id and password which is given in visual studio code and on microsoft bot framework while registering it, When i going to test bot on emulator i used hosted url microsoft app id and microsoft password on bot emulator but it shows post 404 error, why does this appear? How can I solve it?


text:
Q: monitor specific action to specific table SQL SERVER I want to know current update, insert , select on specific table.
I have used sql server profiler but don't know how to filter. When filter by sqltext, It include many noisy things example the query update on others table but it select data from table which I want to monitors I don't want  this show up . Just exactly the update on table A or B.
I am using SQL 2008 R2
Thanks


text:
Q: Where are we using the monotone convergence theorem in this proof? I am looking at the proof that $\frac{\sin{x}}{x}$ is not Lebesgue integrable on $[0,\infty)$ from Carrothers.
(I know that "prove $\frac{\sin{x}}{x}$ is not Lebesgue integrable has been asked before on this site, but the proofs there were provided were different from what Carrothers does, and my question is really more about the MCT than the proof of non-existence, so hopefully this isn't a duplicate! If it is, I apologize).
Carrothers writes: "By the Monotone Convergence Theorem,
$$\int_0^\infty \frac{|\sin{x}|}{x}dx = \sum_{n=1}^\infty \int_{(n-1)\pi}^{n\pi}\frac{|\sin{x}|}{x}dx \ge \sum_{n-1}^\infty \frac{1}{n\pi}\int_0^\pi |\sin(x)|dx = \infty."$$
I'm confused as to where the MCT is used. It seems to me it must be in the first equality, however, I thought that just followed from linearity of the Lebesgue integral? By my reasoning, then, we have
$$\int_{(n-1)\pi}^{n\pi}\frac{|\sin{x}|}{x} = \int_0^\pi\frac{|\sin{x}|}{x+(n-1)\pi}\ge \int_0^\pi\frac{|\sin{x}|}{n\pi},$$
which gives us the inequality, and then the last equality is obvious. So where does the MCT come in?

A: I bet the MCT is applied in the following way: the sequence of functions given by $$f_N(x)=\frac{\left|\sin x\right|}{x}\cdot\mathbb{1}_{(0,N\pi)}(x)$$
is a sequence of $L^1(\mathbb{R}^+)$ functions that monotonically converge to $f(x)=\frac{\left|\sin x\right|}{x}$ over $\mathbb{R}^+$. Assuming that $f\in L^1(\mathbb{R}^+)$, it follows that:
$$ \int_{0}^{+\infty}f(x)\,dx = \lim_{N\to +\infty}\int_{0}^{+\infty}f_N(x)\,dx =\lim_{N\to +\infty}\sum_{k=0}^{N-1}\int_{0}^{\pi}\frac{\left|\sin x\right|}{x+k\pi}$$
but the last series is a divergent series, hence $f\not\in L^1(\mathbb{R}^+)$.

A: Indeed MCT is uesd in the first step. Linearity only applies to when dealing with finite sums.
Notice that $\left\{[(n-1)\pi,n\pi)\right\}_{n=1}^{\infty}$ is a partition of the positive half-line $[0,\infty)$. Now clearly $$\int_{[0,\infty)}\frac{|\sin(x)|}{x}\,d\lambda(x)= \int_{\bigcup_{n\geq 1}[(n-1)\pi,n\pi)}\frac{|\sin(x)|}{x}\,d\lambda(x)$$
Now we can put the characteristic function inside the integral $$\int_{[0,\infty)}\frac{|\sin(x)|}{x}\,d\lambda(x)=\int_{[0,\infty)}1_{\bigcup_{n\geq 1}[(n-1)\pi,n\pi)}\, \frac{|\sin(x)|}{x} \, d\lambda(x)=\int_{[0,\infty)}\sum_{n=1}^{\infty}1_{[(n-1)\pi,n\pi)}\frac{|\sin(x)|}{x}\, d\lambda(x)$$
Now MCT (Actually Beppo-Levi's) is used on the non-negative, non-decreasing partialsum $$S_{N}(x)=\sum_{n=1}^{N}{1_{[(n-1)\pi,n\pi)}}\frac{|\sin(x)|}{x}$$ which converges pointwise for all $x\in[0,\infty)$ to $$S(x)= \sum_{n=1}^{\infty}1_{[(n-1)\pi,n\pi)}\frac{|\sin(x)|}{x}$$
Hence $$\int_{[0,\infty)}S(x) \, d\lambda(x) = \lim_{N\rightarrow \infty}\int_{[0,\infty)}S_{N}(x) \, d\lambda(x)= \lim_{N \rightarrow \infty}\sum_{n=1}^{N}\int_{[(n-1)\pi,n\pi)}\frac{|\sin(x)|}{x} \, d\lambda(x)$$


text:
Q: "This is not a login form" is being stored when updating a password in keycloak theme At our project we got a problem with the Keycloak theme. The Keycloak theme developers placed 2 html input boxes that are hidden in the Keycloak theme:
<input type="text" readonly value="this is not a login form" style="display: none;">
 <input type="password" readonly value="this is not a login form" style="display: none;">
They did this to prevent the browser to fill the current password. But when you update your password, the password manager of the browsers tries to store "this is not a login form" as either username and password.
Anyone an idea how to prevent the password manager to store "this is not a login form" when updating an users password or is this intentional
screenshots

A: I created my own theme and added jQuery. Then i wrote this little rascal:
$(function() {
  $("input#username").on("change", function() {
    var currentVal = $("input#username").val();
    if(currentVal === "this is not a login form") {
      $("input#username").val("");
    }
  });
});


text:
Q: how to use a variable in the BEGIN block in awk? I try to run a one-line command like this
touch ./py.py; awk 'BEGIN{print FILENAME}' ./py.py

and expect to get the result ./py.py but only get a blank line. However, if I do it without a BEGIN block, it works:
touch ./py.py; awk '{print FILENAME}' ./py.py

It seems that the FILENAME variable is not available in the BEGIN block. Why is that? How can I use that variable in the BEGIN block?

A: Awk can process multiple files in one invocation (e.g. awk '{whatever}' file1 file2 file3). The BEGIN block is executed when awk starts, before it opens the first file, not at the beginning of each file (END blocks are similar). One could possibly argue that extending awk to have per-file BEGIN/END hooks might be useful, but they don't exist in any current version of awk/nawk/gawk that I've used...

A: To summarize with the benefit of hindsight:

*

*In gawk (GNU awk) 4 or higher, using BEGINFILE instead of BEGIN ensures that FILENAME is defined; note, however, that BEGINFILE, as the name suggests, is called for every input file.

*In other awk variants, where only BEGIN is offered, FILENAME is not yet defined at that point, because, by design, input-file processing has not begun yet. (By contrast, FILENAME does have a value in the END block, namely the last file processed.)
Workaround:
You can  gain access to the filename arguments passed to awk via the built-in argument ARGV, where ARGV[1] reports the 1st filename argument, ARGV[2] the 2nd, and so on.

*

*Note that options and implied stdin input do not count, so with implicit stdin input ARGV[1] will be an empty string.

*By contrast, pseudo filenames that act as variable assignments do count (e.g., VAR=10).

Thus, assuming no pseudo filenames, ARGV[1] in the BEGIN block is the equivalent of FILENAME in later blocks while the [first] file is being processed.
Caveat re implicit use of stdin: BSD awk (e.g., on OSX) reports implicit stdin input also as an empty string in FILENAME (in later blocks), whereas mawk and gawk report "-".
All 3 variants, however, support explicit stdin input by passing - as a filename argument, in which case FILENAME returns "-" in all 3 variants.

A: It is true that FILENAME isn't available in BEGIN block of awk. As a matter of fact awk doesn't start processing input file in the BEGIN block hence this internal variable is not set. Even this command:
awk 'BEGIN{print;}' ./file

will not print anything from file.

A: Whilst I have no idea what's the deeper sense of this, I could still come up with a hack. I would not call it a "solution" though. Still, it was a nice way of passing time. ;)
This is one of the original working one-liners:
touch ./py.py; awk '{print FILENAME}' ./py.py

For that, you have to know that awk physically checks whether the file exists on the media. Hence, had we attempted something like this:
awk '{print FILENAME}' ./py2.py

awk would have bailed out with:
awk: cmd. line:1: fatal: cannot open file `./py2.py' for reading (No such file or directory)

Alright. So if we're in a BEGIN block (therefore getting files ignored as arguments), we will have to simulate this behavior as if the argument behind the awk line were a file, via the sneaky approach with the awk-builtin ARGV[]array, e. g. like this:
awk 'BEGIN {$0 = ARGV[1]; if ((getline <$0) == -1) print "ERROR: File not found: " $0; else print ARGV[1]}' ./py.py

This will give the result:
./py.py

So far, so good. Now why not do deliberately with a file we don't have on the physical media:
awk 'BEGIN {$0 = ARGV[1]; if ((getline <$0) == -1) print "ERROR: File not found: " $0; else print ARGV[1]}' ./py2.py

will result in
ERROR: File not found: ./py2.py

So we're physically checking files for existence (like awk does with FILENAMEin non-BEGIN blocks) and spitting out an error if the file does not exist.
Rather pointless IMO, but---alas, if we always had to question how sensible a solution actually is, we'd need the span of a lifetime for it, especially in politics. :)


text:
Q: Repeat words inside a loop I am new to programming using JavaScript. How do I repeat a string value retrieved from an <input type="text"> element value, repeat the string by the number retrieved from a sibling <input> element, then set the .innerHTML of a
 element to the resulting repeated string using JavaScript? I have tried the below approach, which did not return expected result. What am I doing wrong at my current attempt? Is there a simpler way to achieve the expected result?

 function repeatWord(str, num) {
        num = Number(num);

        var result = '';
        while (true) {
            if (num & 1) { // (1)
                result += str;
            }
            num >>>= 1; // (2)
            if (num <= 0) break;
            str += str;
        }

        return result;
    }

</script>

<title></title>

Fun with Loops

  <form>

Enter any word

   <input type="text" id="word" class="formfield" size="20" />

Enter number of times to repeat word

   <input type="text" id="repeatnum" class="formfield" size="20" />

   <input type="button" value="Show Output" id="button" onClick="repeatWord()" />

  </form>

<title></title>

Fun with Loops

  <form>

Enter any word

   <input type="text" id="word" class="formfield" size="20" />

Enter number of times to repeat word

   <input type="text" id="repeatnum" class="formfield" size="20" />

   <input type="button" value="Show Output" id="button" onClick="repeatWord()" />

  </form>

A: The function repeatWord returns expected result.
The issue is that you do not pass any parameters to the function, the return value from the function is not further processed. The DOM  elements are not referenced within repeatWord function call. No element has .textContent or .innerHTML set using return value of repeatWord.
Note, you can use console.log() to check a value within a function call, or the return value of a function. For example, console.log(result). See also What is the scope of variables in JavaScript?.
You can substitute input type="number" forinput type="text"as#repeatnumelement, withminattribute set to0,maxattribute set to10`, or other positive number value, as a positive number would appear to be expected value of the element.
Define variables to reference elements having ids word, repeatnum, results to reference the elements within repeatWord function call.
Get the .values from #word and #repeatnum elements; set str as #word .value, set num with #repeatnum .valueAsNumber passed to Number constructor.
At completion of while loop, set #results .textContent to result.

Fun with Loops

    <form>

Enter any word

      <input type="text" id="word" class="formfield" size="20" />

Enter number of times to repeat word

      <input type="number" min="0" max="10" id="repeatnum" class="formfield" size="20" />

      <input type="button" value="Show Output" id="button" onClick="repeatWord()" />

    </form>


text:
Q: UPS settings in Magento 1.6 I am using Magento 1.6. Here I want to use UPS shipping method. But in the backend I have not seen userid, pass, access key in UPS settings.
But I have all seen these options in magento 1.9.
So please guide how to set up UPS for magento 1.6

A: UPS API has been updated since Magento 1.6 release, so UPS module shipped with Magento 1.6 is outdated. The proposed solution would be to upgrade UPS shipping module or use a third-party UPS shipping module from Magento Connect Marketplace:
http://www.magentocommerce.com/magento-connect/catalogsearch/result/?q=UPS+shipping&pl=0


text:
Q: FANN doesn't train properly I am trying to approximate the square function with FANN. The code follows:
#include "../FANN-2.2.0-Source/src/include/doublefann.h"
#include "../FANN-2.2.0-Source/src/include/fann_cpp.h"
#include <cstdlib>
#include <iostream>

using namespace std;
using namespace FANN;

//Remember: fann_type is double!
int main(int argc, char** argv) {
    //create a test network: [1,2,1] MLP
    neural_net * net = new neural_net;
    const unsigned int layers[3] = {1,3,1};
    net->create_standard_array(3,layers);

    //net->create_standard(num_layers, num_input, num_hidden, num_output);

    net->set_learning_rate(0.7f);

    net->set_activation_steepness_hidden(0.7);
    net->set_activation_steepness_output(0.7);

    net->set_activation_function_hidden(SIGMOID_SYMMETRIC_STEPWISE);
    net->set_activation_function_output(SIGMOID_SYMMETRIC_STEPWISE);
    net->set_training_algorithm(TRAIN_QUICKPROP);

    //cout<<net->get_train_error_function()
    //exit(0);
    //test the number 2
    fann_type * testinput = new fann_type;
    *testinput = 2;
    fann_type * testoutput = new fann_type;
    *testoutput = *(net->run(testinput));
    double outputasdouble = (double) *testoutput;
    cout<<"Test output: "<<outputasdouble<<endl;

    //make a training set of x->x^2
    training_data * squaredata = new training_data;
    squaredata->read_train_from_file("trainingdata.txt");

    net->train_on_data(*squaredata,1000,100,0.001);

    cout<<endl<<"Easy!";
    return 0;
}

trainingdata.txt is this:
10 1 1
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100

I feel that I have done everything right with the API. However, when I run it, I get huge error that never seems to reduce with training.
Test output: -0.0311087
Max epochs     1000. Desired error: 0.0010000000.
Epochs            1. Current error: 633.9928588867. Bit fail 10.
Epochs          100. Current error: 614.3250122070. Bit fail 9.
Epochs          200. Current error: 614.3250122070. Bit fail 9.
Epochs          300. Current error: 614.3250122070. Bit fail 9.
Epochs          400. Current error: 614.3250122070. Bit fail 9.
Epochs          500. Current error: 614.3250122070. Bit fail 9.
Epochs          600. Current error: 614.3250122070. Bit fail 9.
Epochs          700. Current error: 614.3250122070. Bit fail 9.
Epochs          800. Current error: 614.3250122070. Bit fail 9.
Epochs          900. Current error: 614.3250122070. Bit fail 9.
Epochs         1000. Current error: 614.3250122070. Bit fail 9.

Easy!

What have I done wrong?

A: If you use sigmoid function for your output layer, the output will provide the range of (0,1).
You may have two choice, (1) divide all your output by a constant, say, 1e4. When a test data comes, you also divide it by 1e4. The problem is that you may not predict the square number larger than 100 (100^2=1e4);(2) make both hidden and output layer to the linear, and the network will automatically learn the weights to give whatever output values you have.


text: Q: how to find out which class the UICollectionViewCell class is in? I'm having a little trouble here.  I'm using a UICollectionViewCell class in 2 different UIViewController classes, how can I find which of the UIViewController class in the UICollectionViewCell class in from the UICollectionViewCell class?  The UICollectionViewCell has some button properties, and I would like to change the color of the buttons depending on the UIViewController.


text:
Q: Como hago una subconsulta dentro de UPDATE Buenas tengo un problema en mysql y es el siguente, resulta que tengo que actualizar como trayecto corto todo lo que dure menos de 3 horas, hice esta consulta
UPDATE reservas
SET trayecto = 'corto'
WHERE 3 < (
        SELECT
            HOUR(TIMEDIFF(fin_alquiler, incio_alquiler)) AS 'Diferencia'
        FROM reservas
);

Pero me da un error de que no puedo especificar la tabla reservas para actualizar con FROM. Gracias de antemano


text:
Q: Communicate to LAN device via http from within a secure (https) internet website I have a device in the local-network which serve data using API over http.
and a web application that is hosted on a secure (ssl, https) internet web server.
Because the web application is accessed via https, it cannot perform ajax calls directly to the device via http.
thought about two workarounds, but interested to see if i'm missing something:
Option 1 - Flash -
Write flash component that will do the communication with the device over http. as flash is not restricted by the browser to secure communication only.
The downside in this option is that whoever using the site will have to have flash installed.
Option 2 - new window -
Open a new window using 'window.open' command, and passing it the html+script via parameter (similar to this SO).
This window is consider non-secure and can communicate with the device over http.
The downside in this option is that the user lose the context of the app, and that the new window could possibly be blocked by popup blockers.
Are there any other options i'm missing? (unfortunately opening a https server on the device is not possible)

A: Because of the mixed content it's impossible in many browsers, such requests are blocked. You have to choose:

*

*serve your internet site over HTTP

*use HTTPS on local site. If this site is part of your application, then application creates self-signed certificate, sends sign-request (google for SCEP) to your own Certificate Authority (CA) over internet. Sign the certificate with your CA, send signed certificate back to application. To avoid browser's security warning your application installs your CA's certificate as Trusted Root on local machine. Then while subscriber visiting your website can access his localhost data from the same page (on internet site) without any security warning about bad SSL certificate in browser.


text:
Q: C# CLR Excecption "BadImageFormatException: Could not load file or assembly" I am using VS 2019 Version 16.8.2

I referred a "CLR Class Library(.NET Core)" project in my "WPF App (.NET)" project and i met a exception:
BadImageFormatException: Could not load file or assembly 'LibCLR, Version=1.0.7646.21580, Culture=neutral, PublicKeyToken=null'. An attempt was made to load a program with an incorrect format.

Let me first talk about how I did it.

*

*Create a "WPF App (.NET)" project "TestCLR"

*Add a new "CLR Class Library(.NET Core)" project "LibCLR" in this solution

*The "common language runtime support" setting of "LibCLR"

*Target "TestCLR" to ".NET 5.0"

*"LibCLR.h" created automatically in project "LibCLR" and codes was inside
#pragma once

using namespace System;

namespace LibCLR {
    public ref class Class1
    {
        // TODO: Add your methods for this class here.
    };
}

*Add "new LibCLR.Class1();" in MainWindow.xaml.cs in project "TestCLR"

using System.Windows;

namespace TestCLR {
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
            new LibCLR.Class1();
        }
    }
}

*Rebuild All and debug, then i met exception

*Then i change the solution platform to x64 or x84, the exception were the same.

*It works well if i choice "WPF App (.NET Framework)" for "TestCLR" in step 1 and "CLR Class Library(.NET Framework)" for "LibCLR" in step 2
Why did not it work?
Can not i use a "CLR Class Library(.NET)" project as a project reference in a "WPF App (.NET Core)" project?
How can i solve this problem?

A: You should change Platform target to "X86" here

A: The most common answer is changing between x86 and x64 targets.  In a comment to your original question, here, you mentioned that you tried that and it didn't work for you.  So, I have a suggestion.  You are building a WPF project, and targeting dotnet 5.0. Dotnet 5.0 is OS-agnostic.  WPF is OS-specific.  It needs Windows.
Try using an OS-specific Target Framework Moniker. Open the .csproj file of both projects.  Try setting both projects to <TargetFramework>net5.0-windows</TargetFramework>
Clean solution, rebuild, and test.
We've got a solution here that is dependent on Windows.  We shouldn't have to, but let's try explicitly targeting it. Especially that C++ project.
More reading

*

*NET 5: Merging .NET Core and .NET Standard with New Target Framework Monikers (TFMs)

*New templates Targeting .NET 5.0

*Cannot compile WPF applications targeting .NET 5


text:
Q: self submit form acces variables javascript I'm making a site for some peaple of my class and I want them to be able to login. I don't want to make an extra loginpage, so I created this bit of code for my login system, but it doesn't work. I looked al over the internet to find other soloutions, but with no success... I want the person to type in their username and password and I want to store that information in a javascript function, so that I can do a function like tis:
function passCheck  () {
    if (pass="johndohpassword1234") // userbname johndoe and passsword password1234
    {
        document.getElementById('h').innerHTML= "welcome, John!";
    }

this is my code:

<?php

$id = $_POST[username] . $_POST[password];

?>

    <title>Login</title>

Login

    <form action="http://timkast.tk" method="post">
        Username:<input type="text" name="username">

        Password:<input type="password" name="password">

        <input type="submit"></input>
    </form>

everything works fine, but the code for window.alert does nothing and I dont know why, please can someone explain/fix this?

A: When you specify a src for the script tag, it ignores the contents of the script tag.
As specified in the documentation:

If a script element has a src attribute specified, it should not have a script embedded inside its tags.

A: You can't write code into a

And you need:


text:
Q: Symfony form type inheritance problems I am building an API using the FOSRestBundle and performing validation using the Types provided by Symfony.
The problem I am facing is that I am trying to find a way to flatten the form type inheritance model that was created when trying to prevent code duplication with inheritance within the form types. This was achieved using the guide on inherit data option.
e.g.
....

$builder->add('nested', new NestedType());

....

However this has an implication when trying to submit data to the API.
Currently:
{
    "type": {
        "key": "value",
        "nested": {
            "nested_key": "value"
        }
    }
}

What I am after:
{
    "type": {
        "key": "value",
        "nested_key": "value"
    }
}

Is there a way to achieve this without duplicating the code within the NestedType?

A: The solution that I ended up going with was to extend the NestedType for example:
class TypeType extends NestedType
{
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
    parent::buildForm($builder, $options);
    $builder
      ->add('key');
  }

  ....

This is less than ideal though since on validation errors the errors in the extended class are hidden only bubbling the error and not what it is associated with.


text:
Q: Difference between file size and string bytelength of text file content? I'm experimenting with coding a very small application-specific local server in Tcl and don't understand the proper method of determining Content-length.  I read that it is bytes or decimal number of octets.
In the code below, [file size "index.html"] returns the correct length such that the browser read/loads all of the content; but [string bytelength $html] is too small and the browser does not read to the end.
Why is this and is there a better method?  Thank you.
if { $op eq "GET" } {
  if { $arg eq "/" } {
    set fp [open "index.html" r]
    set html [read $fp]
    set resp "HTTP/1.1 200 OK\n"
    append resp "Connection: Keep-Alive\n"
    append resp "Content-Type: text/html; charset: utf-8\n"
    append resp "Content-length: [file size "index.html"]\n\n"
    #append resp "Content-length: [string bytelength $html]\n\n"
    append resp $html
    puts stdout $resp
    puts $so $resp
    close $fp
    unset html resp
  }
  # Remainder of if $arg
}

A: The result of file size is the number of bytes that the file takes up on disk, and is exactly the number reported by the OS. (It's also the offset you'd be at if you opened the file and seeked to the end.)
If you were to read the file in in binary mode, the string length of what you read would be the same as the file size. When the file is read in (default) text mode it's different because it depends on the encoding that the file is read with; encodings like UTF-8 can use multiple bytes to describe a character and string length reports the number of characters in a string.
The string bytelength command reports the number of bytes used by the data when it is encoded using Tcl's internal encoding (which is rather similar to UTF-8 but not exactly; there are specific denormalizations). That encoding is not normally exposed to the outside world, and is only really of interest to C extensions. Of course, those C extensions can get the length of a string for themselves easily anyway: it's produced (as an OUT parameter because the string itself is the return value) by Tcl_GetStringFromObj() so string bytelength isn't very useful. Indeed, I've only ever found one (1) legitimate use for it, and a better job of integration work with that extension would have got rid of it.
The value reported by string bytelength is not the amount of storage currently used by a value, but rather just (closely related to, by a static difference) the amount of storage used by the standard "string" interpretation. If the value has any other ("internal") representation as well, which is common (numbers, binary data, true-unicode data, lists, dictionaries, command names, channel handlers, executable code, all those may have additional representation data) then that is not counted.
In your case, you want to open the file in binary mode and use that. And also do this:
set filename "index.html"
set fp [open $filename rb];   # NB: rb — b is for BINARY; this is important
set size [file size $filename]

# HTTP spec says headers are ISO 8859-1 and CRLF-separated
fconfigure $so -encoding iso8859-1 -translation crlf
set headers ""
append headers "HTTP/1.1 200 OK\n"
append headers "Connection: Keep-Alive\n"
# Detecting the content type of a file is its own chunk of complexity
append headers "Content-Type: text/html; charset: utf-8\n"
append headers "Content-length: $size\n"
puts stdout $headers
puts $so $headers

# Ship the data in binary mode; fcopy is VERY efficient
fconfigure $so -translation binary
fcopy $fp $so -size $size
close $fp

Writing HTTP messages to the console is a bit messy because of the mixed encoding used; it's not normally a good idea to write the body of a file. But for debugging you would do:
set data [read $fp]
puts stdout $data
# Additional -nonewline to not add a line terminator
puts -nonewline $so $data

However, the fcopy command (also called chan copy in newer Tcl as part of a command systematization effort) is much more efficient when moving binary data from one place to another. The only way we could make it significantly more efficient would be to move the copy into the OS kernel.

tl;dr: You don't want to use string bytelength. What it does is subtly not useful.


text:
Q: how call method and retrive json array nested in flutter I new used flutter. I have model but i don't understand to call method and retrive data to show in ui(interface). I using packages http post.
this my code model
import 'dart:convert';

MutasiRekResponse myModelFromJson(String str) => MutasiRekResponse.fromJson(json.decode(str));
String myModelToJson(MutasiRekResponse data) => json.encode(data.toJson());

class MutasiRekResponse {
    String responseCode;
    String responseMessage;
    String date;
    String time;
    List<Content> content;

    MutasiRekResponse({
        this.responseCode,
        this.responseMessage,
        this.date,
        this.time,
        this.content,
    });

    factory MutasiRekResponse.fromJson(Map<String, dynamic> json) => MutasiRekResponse(
        responseCode: json["responseCode"],
        responseMessage: json["responseMessage"],
        date: json["date"],
        time: json["time"],
        content: List<Content>.from(json["content"].map((x) => Content.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "responseCode": responseCode,
        "responseMessage": responseMessage,
        "date": date,
        "time": time,
        "content": List<dynamic>.from(content.map((x) => x.toJson())),
    };
}

class Content {
    String postingDate;
    String valueDate;
    String inputDate;
    String inputTime;
    String desc;
    String noReff;
    String amount;
    String balance;

    Content({
        this.postingDate,
        this.valueDate,
        this.inputDate,
        this.inputTime,
        this.desc,
        this.noReff,
        this.amount,
        this.balance,
    });

    factory Content.fromJson(Map<String, dynamic> json) => Content(
        postingDate: json["postingDate"],
        valueDate: json["valueDate"],
        inputDate: json["inputDate"],
        inputTime: json["inputTime"],
        desc: json["desc"],
        noReff: json["noReff"],
        amount: json["amount"],
        balance: json["balance"],
    );

    Map<String, dynamic> toJson() => {
        "postingDate": postingDate,
        "valueDate": valueDate,
        "inputDate": inputDate,
        "inputTime": inputTime,
        "desc": desc,
        "noReff": noReff,
        "amount": amount,
        "balance": balance,
    };
}

I am using http post package, please advice code:
    static Future<MutasiRekResponse> (String accNumber, String startDate, String endDate) async {
    String apiURL = "URL";
    var credentials = base64.encode(bytes);
    var headers = {
      "Content-Type": "application/json",
      "Authorization": "Basic $credentials"
    };
    var requestBody = jsonEncode(
        {'accNumber': accNumber, 'startDate': startDate, 'endDate': endDate});
    http.Response apiResult =
        await http.post(apiURL, body: requestBody, headers: headers);
    if (apiResult.statusCode == 200) {
      apiResult.body;
    } else {
      Exception('failed to load data');
    }
    final jsonObject = json.decode(apiResult.body);
    final _postResult = MutasiRekResponse(jsonObject);
    return _postResult;
  }

how to using correct http.pos and how to call method & retrive data in ui(interface). thank you.

A: Future - Widget that builds itself based on the latest snapshot of interaction with a Future.
I've added a code snippet for showing a list of contents (desc and date) in a ListView.
Widget contentList() {
  return FutureBuilder(
    builder: (BuildContext context, AsyncSnapshot<MutasiRekResponse> dataSnapshot) {
      if (dataSnapshot.connectionState == ConnectionState.none &&
        dataSnapshot.hasData == null) {
        return Container(child: Text('Something went wrong'));
      }
      return ListView.builder(
        itemCount: dataSnapshot.data.content.length,
        itemBuilder: (context, index) {
          return Column(
            children: <Widget>[
              Text(dataSnapshot.data.content[index].desc);
              Text(dataSnapshot.data.content[index].balance);
            ],
          );
        },
      );
    },
    future: getMutasiDetails('your account number', '05/03/2020', '10/03/2020), // Your async function
  );
}

static Future<MutasiRekResponse> getMutasiDetails(String accNumber, String startDate, String endDate) async {
  String apiURL = "your api url";
  var credentials = base64.encode(bytes);
  var headers = {
    "Content-Type": "application/json",
    "Authorization": "Basic $credentials"
  };

  var params = Map<String, dynamic>();
  params['accNumber'] = accNumber;
  params['startDate'] = startDate;
  params['endDate'] = endDate;

  http.Response apiResult =
      await http.post(apiURL, body: params, headers: headers);
  if (apiResult.statusCode == 200) {
    return MutasiRekResponse.fromJson(json.decode(apiResult.body));
  } else {
    throw Exception('failed to load data');
  }
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('Content List'),
    ),
    body: contentList(),
  );
}


text:
Q: Does there exist an open source tool for simulating a CAN bus with programmable CAN nodes? I am looking for a tool to make it easier to experiment with tweaks to the Controller Area network (CAN) protocol, as well as experiment with building protocols on top of it.
In particular, I am looking for a simulation of the CAN bus with programmable nodes such that each node is able to completely control the bits that it outputs on the bus in any given packet, but the usual CAN node behavior (such as inter-frame spacing) and CAN bus features (such as arbitration) are still available.
However, if anything close to such a tool exists and is open source, I can most likely modify it to satisfy my requirements.
I have looked at CANOpen Magic, and RTaW-Sim, but they do not provide the exact functionality that I am looking for, and I cannot modify them to do so because they are not open source.
If no such library exists, please mention this in the comments.

A: For pure simulation, you could use the OpenCores CAN controller. You'll have to learn Verilog and get up to speed on running Verilog simulations - you could use Icarus Verilog or CVer to run your simulations.
You would have full access to all aspects of the CAN controller through modifications to the Verilog source.


text:
Q: rewriterule how to handle no ending slash I try to redirect anything coming into a directory to another. the rewriterule command I use is :
RewriteRule ^VirtualDirectory(.*)$ GENS/RealDirectory$1 [L,NC]

The thing is that I'd like that a query with no end slash to VirtualDirectory to be rewritten as if the query was for VirtualDirectory/
The behaviour I get is :
query to VirtualDirectory/ works great without the user noticing
query to VirtualDirectory workd great but the url shown in the brwoser is : GENS/RealDirectory/
I've tried many things but I can't get the behaviour I want.
If I add a rule
RewriteRule ^VirtualDirectory$ GENS/RealDirectory/ [L,NC]

to handle that specific case, it works great except that all resources of the page are rewrited to the folder before VirtualDirectory

A: What's happening is the internal rewrite is happening without a trailing slash, then mod_dir takes over and does a browser redirect to the same URL but with a trailing slash. You can turn off mod_dir by using DirectorySlash Off in your .htaccess file. If you want the trailing slash always, try changing the rule to this:
RewriteRule ^VirtualDirectory/?(.*)$ GENS/RealDirectory/$1 [L,NC]


text:
Q: send a variable to nginx and take it back I am sending custom variables to nginx like this:
http://myserver2.com/adm/306/89/protectedfile.zip?h=4JljxlK530mM6CPbG5wdTQ&e=1372125364&o=279

the variables "h" and "e" are for the secure_link mod, the "o" was added by me and is the one I want to take back in post_action. See my directives:
    location /adm/ {
        secure_link $arg_h,$arg_e;
        secure_link_md5 SECRETKEY$uri$arg_e$remote_addr;
        if ($secure_link = "") {
            return 403;
        }
        if ($secure_link = "0") {
            return 403;
        }
        rewrite  ^/adm/(.*)$  /download/$1  break;
        post_action /has_finished_downloading/$1;
    }

    location /has_finished_downloading/ {
        resolver 8.8.8.8;
        proxy_pass http://mymainserver.com/download_complete.php?ip=$remote_addr&body_bytes_sent=$body_bytes_sent&status=$request_completion&file_name=$1;
    }

This way, I can take back some variables successfully, including for example $_GET['file_name'] which is "/adm/306/89/protectedfile.zip".
Except the "o" variable. I tried many things to take back the $_GET['o] without success in my php script. It is not sent by nginx, and I have no ideas left how to do it the correct way.
I also tried this but it fails (adding $arg_o):
location /has_finished_downloading/ {
    resolver 8.8.8.8;
    proxy_pass http://mymainserver.com/download_complete.php?ip=$remote_addr&body_bytes_sent=$body_bytes_sent&status=$request_completion&file_name=$1&myo=$arg_o;
}

Thank you for your suggestions.

A: I more or less solved it with
$request_uri


text:
Q: Unable to resolve error in ctx.getContext() in phonegap 3.4 Here I am tring to call an activity from a phonegap 3.4 plugin and this is the error being shown in the following code.
public void startActivity() {
        Intent myIntent = new Intent(ctx.getContext(), SecActivity.class);
        ctx.startActivity(myIntent);
    }

"ctx" is showing an error.
But the same code worked with phonegap 1.6.
With what should I replace ctx?

A: ctx is a legacy member and is deprecated since the release of phonegap 2.0.
Check this link http://docs.phonegap.com/en/2.7.0/guide_plugin-development_android_index.md.html
To rectify the error try replacing ctx.getContext() with this.cordova.getActivity()


text:
Q: How can I set my own, custom keys for shortcuts in Visio 2013? For my life, I've been searching and crying, then searching again. Can't find it! According to Microsoft's own information, the default for zooming is highly cumbersome combination of alt+F6 and shift+alt+F6.
How can I set my own?!
Can I set my own to begin with...?

A: Unfortunately, as of Visio 2013, Visio does not allow you to assign custom keyboard shortcuts.
Note: After further review, the following workaround does not help, since the shortcut key only works in the Visio file that has the macro saved in it.
One workaround for this is to record a macro and assign a keyboard shortcut to the macro when recording it. So let's say we want to use CTRL+u for ungrouping shapes in addition to the default CTRL+SHIFT+u. You can record a macro ungrouping some grouped items and assign the CTRL+u keyboard shortcut to the macro when recording it. After recording the macro, edit the macro and delete all the lines except for the lines below. If the selected shapes are not grouped, running this macro would cause an error. So add "On Error Resume Next" to cause the error to be ignored.
Sub Ungroup()
   On Error Resume Next
   ActiveWindow.Selection.Ungroup
End Sub

However, when you record a macro it is saved in one specific Visio file and the keyboard shortcut will only work when that file is open. In Word, you can simply save your favorite macros in a Word file and place the file in Word's Start-up folder. Unfortunately, you cannot open a Visio file (.vsd) or Visio template (.vst) by copying it to Visio's Start-up; only EXE or DLL files work in the Start-up folder.
In order to have the Visio load the file that contains your macro and keyboard shortcut when Visio starts, do the following:

*

*Install AutoIt.

*Write an AutoIt file with one line that opens the Visio file that contains your macros. The file must be a text file with a .au3 extension.
Here is an example of the one line: Run ("C:\Program Files (x86)\Microsoft Office\Office14\VISIO.EXE C:\Visio Templates\MyMacros.vsd")  The above Run command has one parameter. This parameter contains the path to the Visio program followed by a space, followed by the path to the Visio file that you want to open.

*Close the AutoIt file.

*Right-click on the file and select Compile Script. An EXE file is created.

*Define a Start-up folder location in Visio (File>Options>Advanced>File Locations). Make sure there are no spaces in the path of the Start-up folder.

*Copy the EXE file to the Start-up folder. Note that only the EXE file must be in the Start-up folder. The Visio file that your opening can be anywhere on the computer.

Now every time you open Visio, Visio will run the EXE, which will open the Visio file containing your macros.

A: I love AutoHotkey! I add to OP's frustration... Even after years of Visio not catching up to MS Word on keyboard customization, I finally downloaded the free AutoHotkey and found it quite easy to learn. Non-profit too! Not crapware in any sense!
Even better, I am using it all over my PC. I added single-clicks like INSERT creates a new row in Excel AND Google Sheets (who ever likes overtype editing???), enable the selection pointer in Visio with F1, etc. I have been able to modify anything I set out to modify with a pretty low learning curve. The community support is great! There are great instructions and examples. When I once got stuck, I posted
It knows which app window is in context and just magically enables your shortcuts for that app. Any key sequence that naively exists can be automated. It intercepts your keystrokes and maps them to the sequence needed to do what you want.


text:
Q: Django order by query in foreign key cases I do have two tables such that,
class A(BaseModel):
      name = models.CharField(...)

class B(BaseModel):
      a = models.ForeignKey(A, on_delete=models.CASCADE)
      val = models.IntegerField(blank=True, null=True)

a = A.objects.all().oreder_by("b__val")

Whenever I use order by query, getting repeated instances with different val. But i wanna get only one row from the B model.
Optimized query??
NOTE: Using MySQL.


text:
Q: Annotation for binding a json field to a field in POJO with a different name Java class (used as a Data Transfer Object):
class Resource also has a field named id with a different type along with its getter and setter, hence the syntax error.
class A extends Resource
{
   private int id;

   public int getId() { return id; }   // syntax error as getId() function already exists in Resource
   public void setId(int id) { this.id = id; }
}

Since the above class is a DTO, a JSON response (with field id) will be mapped to it, and getId() cannot be used, I want to change the field to _id_ and change getter and setter correspondingly, and mark it with an annotation saying bind this to id field.
Note: I'm using spring boot. I tried using @JsonProperty annotation but that didn't work. Is there an annotation for doing this in spring?

A: Googled and found this question: Jackson serialization: how to ignore superclass properties. Adapted it for your problem.
public class A extends B {
    private int id;

    public A(int id) {
        super.setId("id" + id);
        this.id = id;
    }

    @Override
    @JsonProperty("_id_")
    public String getId() {
        return super.getId();
    }

    @Override
    @JsonProperty("_id_")
    public void setId(String id) {
        super.setId(id);
    }

    @JsonProperty("id")
    public int getIntId() {
        return id;
    }

    @JsonProperty("id")
    public void setIntId(int id) {
        this.id = id;
    }
}

public class B {
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

Tested it with this:
@RestController
public class TestController {
    @GetMapping("/test")
    public A test() {
        return new A(1);
    }
}

And the output was:
{
  "_id_": "id1",
  "id": 1
}

A: public A extends Resource {
    private int id;

    @JsonProperty("_id")
    public int getId() {
      return id;
    }

    @JsonProperty("id")
    public void setId(int id) {
      this.id = id;
    }
}

the method names should be different, so jackson parses it as different fields, not as one field.


text:
Q: ArcMap: ETRS89 LAEA to GRS80 TM I have two layers and they just won't line up. I am a novice and tried a variety of things but I can't get it right.
My layers are in:
GRS_1980_Transverse_Mercator
ETRS_1989_LAEA
These are CORINE and Copernicus EUDEM layers, or layers derieved from them.
What should I do, and more importantly - how?


text:
Q: TimerService#createTimer Ignores Delay I want to use the Java EE timer service to create a periodic task. Tutorials like this one suggest this is the way to go:
@Startup
@Singleton
public class AutomaticBean {

    @Resource
    TimerService timerService;

    @PostConstruct
    public void initialize() {
        this.timerService.createTimer(0, 5000, null);
        System.out.println("AutomaticBean.initialize()");
    }

    @Timeout
    public void programmaticTimout(Timer timer) {
        System.out.println("AutomaticBean.programmaticTimout()");
    }
}

What I'm expecting to see is a message every 5 seconds. However it's send every one second.
11:20:13,341 INFO  [stdout] (EJB default - 6) AutomaticResendBean.programmaticTimout()
11:20:13,392 INFO  [stdout] (EJB default - 5) AutomaticResendBean.programmaticTimout()
11:20:14,340 INFO  [stdout] (EJB default - 3) AutomaticResendBean.programmaticTimout()

I have no idea why that won't work. I tried other methods of the timer service as well. createSingleActionTimer did not work either, and it created a periodic timer as well (instead of one that is executed a single time).
What is the problem? The container is Wildfly 16.

A: The answer to this problem had nothing to do with the actual setup, but someone else might have the same problem so here it goes:
On default JMS timers are created with a TimerConfig that is persistent. Which means once you create a timer that runs every second, this timer gets run even if you restart the server (or remove the creation of it).
So that's what happend. I had created a timer every second. Which ran every second. Then I created a second timer with a delay. Since the same code was run for both, I couldn't see that I had actually two timers.


text:
Q: Windows 10 File Explorer crashing regularly I upgraded to Windows 10 a week ago, and then installed a fresh copy of it on a SSD. Everything worked fine, until File Explorer suddently started to behave weird: When I double-click on a folder, it opens in a new window (despite having "Browse Folders" set to "Open in same window"), and when I copy a file, it freezes for ~10 seconds, after which it crashes and restarts (however, the file is copied just fine). The crash also happens randomly when I browse Control Panel.
Things I tried already:

*

*Reset Windows. The problem was fixed temporarily, but came back after a couple of days.

*Uninstalled last update.

*Booted in Safe Mode.

*Removed all shell extensions using shexview.

Nothing worked.
The crash event log:
Log Name:      Application
Source:        Application Error
Date:          8/30/2015 6:30:18 PM
Event ID:      1000
Task Category: (100)
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      D180-M1
Description:
Faulting application name: Explorer.EXE, version: 10.0.10240.16431, time stamp: 0x55c9bd76
Faulting module name: windows.storage.dll, version: 10.0.10240.16405, time stamp: 0x55b46055
Exception code: 0xc000041d
Fault offset: 0x0000000000120dec
Faulting process id: 0xc48
Faulting application start time: 0x01d0e3408ef60455
Faulting application path: C:\WINDOWS\Explorer.EXE
Faulting module path: C:\WINDOWS\system32\windows.storage.dll
Report Id: 3f9927d9-ad92-45c6-a325-dace805f2099
Faulting package full name:
Faulting package-relative application ID:

A: I had a similar issue. It seems that what caused it for me was trying to customize explorer using command line. I ended up with the copy/move crash, and open-in-new-window issue.
This is the command that broke things for me:
%SystemRoot%\explorer.exe /e,/root,::{450d8fba-ad25-11d0-98a8-0800361b1103}

I chanced upon this case, and it seems that resetting folder options in the registry might keep you from having to do a system restore, or recreating the user. Here's the related KB.
I ended up only having to delete and recreate BagMRU, and Bags (I compared my registry before and after corruption for differences, I also compared to the MS case).
[HKEY_CURRENT_USER\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\Shell\BagMRU]

[HKEY_CURRENT_USER\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags]

There were more differences, but this was the first I tried and it solved at least the open-in-new-window issue. I wasn't experiencing the crashing anymore because I had done a system restore.


text:
Q: reading decimal number from textfile using fscaf c proramming Hi I am new to c programming and I am having trouble getting the decimal number in the text file using the fscanf. It always give me 2 numbers instead of one
Example: in the text file there is: 2.5
but in the result it game me 1 char type(2.) and 1 integer type(5);
how can I get the decimal number as int?
while((val = fscanf(stdin,"%d%c",&num ,&c)))

A: 2.5 is not an int value.  You must scan and store it as a floating-point type, preferably double:
int n;
double d;
FILE *infile;
...
n = fscanf(infile, "%lf", &d);
if (n!=1)
{
    ... handle bad input ...
}

You can then cast to int, or whatever.  The reason for double is that float can't represent all 32-bit int values exactly.
Edit: To test for a double value being integral, just compare d == (int)d.  That will be true if and only if d is exactly equal to an integer.
PS: I missed the use of stdin in the example line.  It's usual to use scanf() to scan from stdin.  Now it looks more like maybe there's keyboard input with a chance of typing errors.  For that, I tend to use fgets() to get a string and sscanf() to convert and validate:
char input[82];
...
while (fgets(input, sizeof(input), stdin) != NULL)
{
    int value;
    char ignore;
    int n = sscanf(input, "%d %c", &value, &ignore);
    if (n != 1)
    { ... invalid input: print message & continue; }
    ... do something with value
}

A: The reason why you are getting
num == 2 and c == 5 is because you are trying to read integer first and then a char,
now your input buffer contains 2, ., 5
Reading an integer stops when a '.' is encountered and '.' is flushed from the input buffer, next you are trying to read a character and hence '5' goes into c.
You can do something like this
float tmp;
int num;
char c;
scanf("%f%c", &tmp, &c);
num = tmp; //this will truncate the decimal part

Note: Be careful that if you hit enter after reading a character and immediately you try to read a character again, the newline character still resides in the input buffer and will be read as next character, you will have to explicitly flush it

A: For char is better to use fgetc() than fscanf(fin,"%c);
Use it like that :
c=fgetc(fi); or fputc(c,fout);


text:
Q: Timer job move to different farm I have created timer job as per the article How to Create Timer Job in SharePoint 2013.
It is running fine in site collection in dev environment.

*

*What are the steps to move it from dev to different environment?
I was going to save site collection as a template and restore it in target farm,

*what about the timer job? What are the steps to move it to diferent environment?

*In Event receiver, there is a Guid. This is the Site or list Guid?

Edit:
I have list in the site collection with custom form. Timer job is created to daily check the list and send reminders etc.
Need to move both to the different environment.
So for site collection it will be: save as a template etc.
What are steps to move timer job definition?

A: Timer Jobs resides inside an assembly and it gets executed by SharePoint Timer Windows service.
To move timer job you need to create a WSP solution in Visual Studio. In that solution add a Feature and use the Feature Activated event to install the timer job.


text:
Q: Property 'id' does not exist on type 'T' I have a React component which is a table and it can take any kind of data.
The definition looks like this:
type SimpleTableProps<T> = {
  data: Array<T>;
  ...
};

const SimpleTable = <T,>(props: SimpleTableProps<T>): JSX.Element => {...}

When looping over the data to create the table rows, I need to use a unique key -- I can't use the index as the order of the rows can change.
I have this at the moment:
{data.map((el, index) => (
  <tr key={el.id || index}>
   ....
  </tr>
)}

The issue is that typescript complains that id does not exist on type T, which makes sense.
I applied the answer from this post but now I get other errors from the usage of the SimpleTable where an id is not needed (i.e. when the data passed does not contain an id key):
Type '{ whatever: string }' has no properties in common with type '{ id?: number | undefined; }'.

I tried things like using in, Object.has..., el.hasOwn, and things like this, without success:
key={Object.keys(el).includes('id') ? el.id : index}

Any idea how to make it work?

Edit: simple reproduction here: https://codesandbox.io/s/typescript-error-uqwmju

A: Here's how I fixed it
type SimpleTableProps<T> = {
  data: Array<T & { id?: number }>;
  ...
};

const SimpleTable = <T,>(props: SimpleTableProps<T>): JSX.Element => {...}


text:
Q: DB2 subquery not working using IN statement SQLCODE 115 I'm trying to execute a query in DB2. But it throws following error:
Error: DB2 SQL Error: SQLCODE=-115, SQLSTATE=42601, SQLERRMC=IN, DRIVER=4.8.86
SQLState:  42601
ErrorCode: -115
Error: DB2 SQL Error: SQLCODE=-514, SQLSTATE=26501, SQLERRMC=SQL_CURSH200C1; STMT0001, DRIVER=4.8.86
SQLState:  26501
ErrorCode: -514

Which does'nt make sense as my query looks correct:
SELECT ROW_NUMBER() OVER() AS ID,
CONCAT(TRIM(TB1.ROW1),CONCAT('_',TRIM(TB1.ROW2))) AS CODE_DESCRIPTION,
CASE
    WHEN TRIM(TB1.ROW1) IN (SELECT T1.ROW1 FROM DB1.TABLE1 T1  WHERE T1.ROW3 = 'TEST')
    THEN 'Valid'
    ELSE 'Invalid'
END,
TB1.* FROM DB1.TABLE1 TB1
WHERE TB1.ROW3 = 'CLASS1';

SQLCode 115 means Comparison is invalid. Which is not ?
Update:
What I'm trying to accomplish here is. I have a Table Table1(Name changed for simplicity). Following is the part of the content.
**Row3**    **Row1**                                **Row2**
KSASPREM    SRQ                         0   0   Auto Carry                                                                                SRQ
KSASPREM    SCG                         0   0   BRT Buses                                                                                SCG
KSASPREM    SCE                         0   0   Buses                                                                                SCE
KSASPREM    SRR                         0   0   Buses                                                                                SRR
KSASPREM    SDC                         0   0   Domestic All Risks                                                                                SDC
KSASPREM    SDA                         0   0   Domestic Buildings                                                                                SDA

Task to accomplish:

*

*Retrieve all the values from Table1 where Row3 is KSASPREM

*The result should contain one extra column 'Valid' value Yes/No if value of Row1 is not in the Values retrieved from Table1 where Row3 is 'TEST'

Hope I made myself clear and not more confusing ?
Any Help ?
Thanks
Ps. Updated the Query

A: As with so many things, a JOIN (here, LEFT JOIN) is the answer.  Specifically, we need to put the (slightly modified) subquery as the table reference:
LEFT JOIN (SELECT DISTINCT row1, 'Valid' as valid
           FROM Table1
           WHERE row3 = 'TEST') AS Test
       ON Test.row1 = TB1.row1

*

*LEFT JOIN tells the query engine that "rows in this other table aren't required".

*DISTINCT says, "for all value combinations in these columns, give me just one row"

*Using a constant value - 'Valid' - returns that constant value.

... so this gets us a (virtual, temp) table containing unique row1 entries where row3 = 'test'.
Here's the full query:
SELECT ROW_NUMBER() OVER(ORDER BY TB1.row1) AS ID,
       TRIM(TB1.ROW1) || '_' || TRIM(TB1.ROW2) AS CODE_DESCRIPTION,
       COALESCE(Test.valid, 'Invalid') AS valid,
       TB1.row3, TB1.row1, TB1.row2
FROM Table1 TB1
LEFT JOIN (SELECT DISTINCT row1, 'Valid' as valid
           FROM Table1
           WHERE row3 = 'TEST') Test
       ON Test.row1 = TB1 .row1
WHERE TB1.ROW3 = 'KSASPREM'

SQL Fiddle Example
COALESCE(...) returns the first non-null value encountered in the value list.  Since, if there is no Test row, Test.valid will be null, this outputs 'Invalid' for TB1 rows without a corresponding Test row.  (Internally it's calling CASE, I believe, this just makes it prettier)
Note that:

*

*I've put an ORDER BY into the OVER clause, to return (mostly) consistent results.  If you only ever plan on running this once it doesn't matter, but if you need to run it multiple times and get consistent IDs, you'll need to use something that won't be shuffled.

*DB2 (and apparently PostgreSQL) support || as a concat operator.  It makes reading statements so much easier to understand.

*Never use SELECT *, it isn't safe for several reasons.  Always specify which columns you want.


text:
Q: AVG(COLUMN_SCORE) Not Generating Average In my App. I have a series of for tables.

*

*League

*Bowler

*Series

*Game

By the time a bowler enters in his/her scores the id's might look something like this;

*

*League id = 2

*Bowler id = 1

*Series id = 1

*Game id's = 1,2,3

In my Games table I am recording the scores for each game played (i.e. 1,2,3).  I want to be able to generate an Average Score for a series (i.e. 1).
I know that this can be done with
CREATE VIEW AVERAGE_SCORE AS SELECT AVG(COLUMN_SCORE) FROMFROM " + Game.TABLE_NAME + " WHERE " + Game.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " AND " + Game.COLUMN_BOWLER_ID + " = '" + bowlerId + "'" + " AND " + Game.COLUMN_SERIES_ID + " = '" + seriesId + "'" + " ORDER BY " +
        Game.COLUMN_TIMESTAMP + " DESC";

I have managed to get a value to appear in logcat using the following code:
public int getSeriesAverage(String leagueId, String bowlerId, String seriesId)
    {
        int total = 0;
        SQLiteDatabase database = getReadableDatabase();
        Cursor cursor = database.rawQuery("CREATE VIEW IF NOT EXISTS AVERAGE_SCORE AS SELECT AVG(COLUMN_SCORE) FROM " + Game.TABLE_NAME + " WHERE " + Game.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " AND " + Game.COLUMN_BOWLER_ID + " = '" + bowlerId + "'" + " AND " + Game.COLUMN_SERIES_ID + " = '" + seriesId + "'" + " ORDER BY " +
                Game.COLUMN_TIMESTAMP + " DESC", null);
        if (cursor.moveToFirst()) {
            do {
            total = cursor.getInt(0);
        }while (cursor.moveToNext());
        }
        cursor.close();
        //Close Database Connection
        database.close();
        Log.d("GET AVERAGE FROM SQL","Average = >>>>" + total + "<<<<");
        return total;
    }

However it does not appear to be generating an average value.  In my database I have three scores Game 1 = 222, Game 2 = 300, Game 3 = 200.  The average should be 240.  But Log.d shows it as 0.
07-24 19:58:53.385 7287-7287/ca.rvogl.tpbcui D/GET AVERAGE FROM SQL: Average = >>>>0<<<<

What am I doing wrong, any assistance would be greatly appreciated

Changed Code:
public int getSeriesAverage(String leagueId, String bowlerId, String seriesId)
    {
        int total = 0;
        SQLiteDatabase database = getReadableDatabase();
        Cursor cursor = database.rawQuery("SELECT AVG(COLUMN_SCORE) FROM " + Game.TABLE_NAME + " WHERE " + Game.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " AND " + Game.COLUMN_BOWLER_ID + " = '" + bowlerId + "'" + " AND " + Game.COLUMN_SERIES_ID + " = '" + seriesId + "'", null);
        if (cursor.moveToFirst()) {
            do {
            total = cursor.getInt(0);
        }while (cursor.moveToNext());
        }
        cursor.close();
        //Close Database Connection
        database.close();
        Log.d("GET AVERAGE FROM SQL","Average = >>>>" + total + "<<<<");
        return total;
    }

Series Class:
public class Series {

    public static final String TABLE_NAME = "Series";

    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_LEAGUE_ID = "league_id";
    public static final String COLUMN_BOWLER_ID = "bowler_id";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_SERIES_AVERAGE = "average";
    public static final String COLUMN_TIMESTAMP = "timestamp";

    private int id;
    private String league_id;
    private String bowler_id;
    private String name;
    private String average;
    private String timestamp;

    // Create table SQL query
    public static final String CREATE_TABLE =
            "CREATE TABLE " + TABLE_NAME + "("
                    + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + COLUMN_LEAGUE_ID + " TEXT,"
                    + COLUMN_BOWLER_ID + " TEXT,"
                    + COLUMN_NAME + " TEXT,"
                    + COLUMN_SERIES_AVERAGE + " TEXT,"
                    + COLUMN_TIMESTAMP + " DATETIME DEFAULT CURRENT_TIMESTAMP"
                    + ")";

    public Series() {
    }

    public Series(int id, String league_id, String bowler_id, String name, String average, String timestamp) {
        this.id = id;
        this.league_id = league_id;
        this.bowler_id = bowler_id;
        this.name = name;
        this.average = average;
        this.timestamp = timestamp;
    }

    public int getId() {
        return id;
    }

    public String getLeagueId() {return league_id;}

    public String getBowlerId() {return bowler_id;}

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAverage() {
        return average;
    }

    public void setAverage(String average) {
        this.average = average;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setLeagueId(String league_id) {
        this.league_id = league_id;
    }

    public void setBowlerId(String bowler_id) {
        this.bowler_id = bowler_id;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }
}

Updated Method:
 public int getSeriesAverage(String leagueId, String bowlerId, String seriesId)
    {
        int total = 0;
        SQLiteDatabase database = getReadableDatabase();
        Cursor cursor = database.rawQuery("SELECT AVG(" + Game.COLUMN_SCORE + ") FROM " + Game.TABLE_NAME + " WHERE " + Game.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " AND " + Game.COLUMN_BOWLER_ID + " = '" + bowlerId + "'" + " AND " + Game.COLUMN_SERIES_ID + " = '" + seriesId + "'", null);
        if (cursor.moveToFirst()) {
            do {
            total = cursor.getInt(0);
        }while (cursor.moveToNext());
        }
        cursor.close();
        //Close Database Connection
        database.close();
        Log.d("GET AVERAGE FROM SQL","Average = >>>>" + total + "<<<<");
        ContentValues values = new ContentValues();
        values.put(Series.COLUMN_SERIES_AVERAGE,Series.getAverage());
        Log.d("GET AVERAGE FROM SQL","Average = >>>>" + Series.COLUMN_SERIES_AVERAGE + "<<<<");
        return total;
    }

A: Your sql statement is a CREATE statement and not a query to fetch rows. So change it:
"SELECT AVG(" + Game.COLUMN_SCORE + ") FROM " + Game.TABLE_NAME + " WHERE " + Game.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " AND " + Game.COLUMN_BOWLER_ID + " = '" + bowlerId + "'" + " AND " + Game.COLUMN_SERIES_ID + " = '" + seriesId + "'"

You might also need to change: total = cursor.getInt(0);
I'm not sure if the average value which will be produced will be rounded to int.   Better use getDouble or getString and then parse to int


text:
Q: Get form coordinates of a custom control In Winforms, I have implemented a custom object with a draw method, which is called by Form_Paint. I now want to be able to get the coordinates of this object after being drawn to the form, for the sake of a Move procedure in the works. I have tried using object.Location, object.Left, and object.Top, but these just give 0,0. I then tried object.Size to test, and it gave me the size of the form.
How can I get the location of my runtime object on the form? Thanks

A: Try using
Point objLocation= cusObject.FindForm().PointToClient(
cusObject.Parent.PointToScreen(cusObject.Location));