text:
Q: Validation in MVC 5 .net Im try to give alert if there is a error in form in my form there are some text fields validation like below

                @Resources.StandardPrice

            @Html.TextBoxFor(model => model.products.BasicPrice, new { @class = "form-control errorClass", @id = "basicPrice", @placeholder = @Resources.StandardPrice, @onblur = "addClass(this)", @maxlength = Resources.AddNewProductFieldMaxLength })
            @Html.ValidationMessageFor(model => model.products.BasicPrice, null, new { @class = "help-inline" })

if there is some error in form how can I give a alert

A: In order to display the error message and prevent the submission of your form you have to add controls on your model (or ViewModel).
For example if you want that field to be required so that the form will not be submitted only if the user give a value to that field you have to add the [Required] to your product's model attribute "BasicPrice" as follow :
public class products {
   public int ID { get; set; }

   [Required]
   public string Name { get; set; }

   [DataType(DataType.Date)]
   public DateTime ReleaseDate { get; set; }

   [Required]
   public string Genre { get; set; }

   [Range(1, 100)]
   [DataType(DataType.Currency)]
   public decimal Price { get; set; }

   [StringLength(5)]
   public string Rating { get; set; }
}

Here's a link to the Microsoft official Documentation which explain the subject and give more details :
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-aspnet-mvc4/adding-validation-to-the-model

A: If you already did what @Mohamed Kamel Bouzekria suggested and still not working.
it's possible that you missing something in your controller which could this
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult YOurMethod( Model model)
        {

            if (ModelState.IsValid)//if there is no errors and valid values
            {
               //do something

                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View();//else return the same view that should display the errors
        }

if it still not working then you missing something else in your view.if so post the full code of the view


text:
Q: how to pass multiple PHP arguments to bash setip.php :
<?php
$IP_Addr = $_GET['ip'];
$NetMask = $_GET['ip2'];
$NetWork = $_GET['ip3'];
$Broad = $_GET['ip4'];
$DNS = $_GET['dns1'];

$cmd="sh /var/www/cgi-bin/ipset.sh ".escapeshellarg($IP_Addr)."".escapeshellarg($NetMask)."".escapeshellarg($NetWork)."".escapeshellarg($Broad)."".escapeshellarg($DNS);
 exec("$cmd");

example input : ip=10, ip2=20, ip3=30, ip4=40, dns1=10
ipset.sh :
#!/bin/bash -x
echo "IPADDR=$1"       >>/etc/sysconfig/network-scripts/ifcfg-eth0
echo "NETMASK=$2"     >>/etc/sysconfig/network-scripts/ifcfg-eth0
echo "NETWORK=$3"     >>/etc/sysconfig/network-scripts/ifcfg-eth0
echo "Broadcast=$4"   >>/etc/sysconfig/network-scripts/ifcfg-eth0
echo "DNS=$5"        >>/etc/sysconfig/network-scripts/ifcfg-eth0

result in ifcfg-eth0 :
IPADDR=1020304010
NETMASK=
NETWORK=
BROADCAST=
DNS=

any sugestion how to pass argument correctly ?

A: Solved, add space between argument.
  <?php
    $IP_Addr = $_GET['ip'];
    $NetMask = $_GET['ip2'];
    $NetWork = $_GET['ip3'];
    $Broad = $_GET['ip4'];
    $DNS = $_GET['dns1'];

    $cmd="sh /var/www/cgi-bin/ipset.sh ".escapeshellarg($IP_Addr)." ".escapeshellarg($NetMask)." ".escapeshellarg($NetWork)." ".escapeshellarg($Broad)." ".escapeshellarg($DNS);
     exec("$cmd");

redpajama_set_name: RedPajamaStackExchange


text:
Q: como buscar entre fechas con consultas sql 23 Muestra los datos de los alumnos cuya fecha de nacimiento comprenda los
años 1993 y 1994. Ordena el resultado por nombre.
NO FUNCIONA EN PHP MY ADMIN, HAY ALGUNA FORMA DE QUE ESTO FUNCIONE? Y ALGUNO CONOCE DONDE BUSCAR ESTAS COSAS DE PHPMYADMIN?
SELECT * FROM fecha_nacimiento BETWEEN '1993-01-12' AND '1994-12-31' ORDER BY nombre;

A: Esa es tu sentencia?
SELECT * FROM fecha_nacimiento BETWEEN '1993-01-12' AND '1994-12-31' ORDER BY nombre;

Porque no veo ningun tipo de WHERE, PHPMyAdmin usa MySQL como gestor de BD, lo correcto seria
SELECT * FROM TuTabla WHERE TuFecha BETWEEN '1993-01-01' AND '1994-12-31'

O tambien puede usar un >= y <=


text:
Q: AMDGPU install error: "not available" & "no release candidate" I am running ubuntustudio and cannot install amdgpu driver 22.20. When running amdgpu-install from the terminal I get the following message:

"Package linux-modules-extra-5.15.0-56-lowlatency is not available, but is referred t
o by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package 'linux-modules-extra-5.15.0-56-lowlatency' has no installation candidate"

I initially checked my system and the package is necessary and part of the Linux lowlatency metapackage. The error does not appear or hinder any other install as I have installed 20 programs from 8 different repositories with no errors. I also created a fresh install of ubuntustudio 22.04.1 and got the same results.
The instructions on the AMD site for drivers does not address any issues or the necessary packages needed in case the install script fails. How can I bypass/solve this and simply install the necessary packages to get my two GPUs to be seen by Blender 3.3 for rendering?
-Specs-
Processor        : Intel(R) Xeon(R) CPU E5-1650 v4 @ 3.60GHz
Memory        : 131806MB (9690MB used)
Machine Type        : Desktop
-Display-
Resolution        : 5760x1080 pixels
OpenGL Renderer        : AMD Radeon RX 5600 XT
X11 Vendor        : The X.Org Foundation
AMD Radeon RX 6600 (second GPU for rendering in blender)
-Version-
Kernel        : Linux 5.15.0-56-lowlatency (x86_64)
Version        : #62-Ubuntu SMP PREEMPT
C Library        : GNU C Library / (Ubuntu GLIBC 2.35-0ubuntu3.1) 2.35
Distribution        : Ubuntu 22.04.1 LTS


text:
Q: how to create a template based table and use it in multiple DITA xml and populate the data through it I am new to DITA. I would like to create the DITA xml for my PDF publishing
WHAT I WANT TO DO IS :
first i want to have the template based table which can be used in number of DITA xmls
and in hat table template I can populate the data according to my need.
In this way I can use same table schema multiple times and populate different data into that table present in different DITA xmls.
can it be possible through python?
Is it possible to do so?

A: It sounds like you could use the DITA conref capability. For the template table, you can have that in a DITA XML file that you store separately. Then in each DITA file that you want to use that table in, you use a conref to pull in your template table.
You could use Python for this, but it would be simpler to just use the free DITA Open Toolkit, which supports the conref feature by default.


text:
Q: OutOfMemory error with FixedThreadPool and ExecutorCompletionService I working on app what should get list of users from db and update thie details from directory (ldap or AD). I what do this procedure on multicore machine so I created this app (code below). I'm using CompletionService and getting the results in Future object.
After some time, I'm getting out of memory error with 'unable to create new native thread' message. In task manager I see that app created enormous amount of threads but I asked create fixed thread pool with size equals amount of my processors.
What is wrong with my code?
class CheckGroupMembership {
public static void main(String[] args) throws Exception {

    final ExecutorService executor = Executors.newFixedThreadPool(**Runtime.getRuntime().availableProcessors()**);

    CompletionService<LdapPerson> completionService =
        new ExecutorCompletionService(executor)<LdapPerson>(executor);

    final int limit = 2000;

    DocumentService service1 = new DocumentService();
    List<String> userNamesList = service1.getUsersListFromDB(limit);

    List<LdapPerson> ldapPersonList = new ArrayList() <LdapPerson> (userNamesList.size());
    LdapPerson person;

    for (String userName : userNamesList) {
        completionService.submit(new GetUsersDLTask(userName));
    }

    try {
        for (int i = 0, n = userNamesList.size(); i < n; i++) {
            Future<LdapPerson> f = completionService.take();
            person = f.get();
            ldapPersonList.add(person);
        }
    } catch (InterruptedException e) {

        System.out.println("InterruptedException error:" + e.getMessage());
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    System.exit(0);
}
}

ERROR CheckGroupMembership:85 - java.lang.OutOfMemoryError: unable to create new native thread
  java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: unable to create new native thread
      at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
      at java.util.concurrent.FutureTask.get(FutureTask.java:83

GetuserDLs task
public class GetUsersDLTask implements Callable<LdapPerson> {
private String userName;

public GetUsersDLTask(String u) {
    this.userName = u;
}

@Override
public LdapPerson call() throws Exception {
    LdapService service = new LdapService();
    return service.getUsersDLs(userName);
}

}

A: I am having a hard time believing you are not creating a Thread in GetUsersDLTask (or at least it's service Object). If you look at your stacktrace, the Exception is being thrown from the Future's get() method.  The only way this exception get's set is after the Executor invokes Callabale.call().  Any throwable that occurs in the call() method will be set in the Future's internal exception field
For example:
Thread Pool:
    Thread-1
      invoke call()
        call()
          Create Thread
            throw OutOfMemoryError
         propogate error to Thread pool
      set exception

Otherwise, this exception would be occurring when you submit the ask to thread pool, not when you get from the future.

A: Executors.newFixedThreadPool will accept the submission of many tasks, but will only execute the number of threads that you allow.  So if you have a fixed pool of 2 threads, but you submit 50 tasks, the 48 other tasks are queued internally on the executor and are run as the executing threads finish tasks. Seems like you need to limit the number of threads you are spawning within your code.
Edit: check out http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)

A: Did you verify the number of threads created in the fixed pool.  Maybe the # of available processors is coming out as too big.


text:
Q: Pinyin to character I'm trying to make a document with both English words, pinyin translation and chinese characters.
Is it possible to write the code in pinyin (or something similar) and get the corresponding characters when you compile?
Ex:
In code: jǔ -> In document: 举
or
In code: ju3 -> In document: 举
//Pinyin describes the English way of pronouncing a Chinese character. The character 举 sounds like "ju".
If this is the wrong forum please tell

A: This would not really be feasible, because there can be many characters with the same pronunciation (pinyin). So e.g. ma3 (or mǎ) may be 马 or 码 or 玛 ……
But perhaps you can do it the other way round: Type the Chinese characters, and the xpinyin package can annotate it with the pinyin. Here's an example from the documentation:
\documentclass{article}
\usepackage{xeCJK}
\usepackage{xpinyin}
\begin{document}
\xpinyin*{汉语拼音示例}
\end{document}

Sooner or later you'll come across characters that can have more than one pronunciation. In that case you can specify the pinyin explicitly:
\xpinyin*{小树\xpinyin{长}{zhang3}大了, 枝梢变\xpinyin{长}{chang2}了}


text:
Q: Calculate data based on text box values with javascript/html I am trying to get the values from 3 html text fields and add them together to get the total value when the use clicks on the button. I am new to javascript and after researching online, I found an example code and implemented to my code, but it is not showing any values. Here is my code:
 <form name="selectVehicleForm" action="SelectVehicle">
            Car Make: <input type="text" name="make" id="make" value="${Vehicles.make}" disabled>

            Car Model: <input type="text" name="model" id="model" value="${Vehicles.model}" disabled>

            Car Year: <input type="text" name="year" id="year" value="${Vehicles.year}" disabled>

            Car Transmission: <input type="text" name="transmission" id="transmission" value="${Vehicles.transimssion}" disabled>

            Car Rate Per Mile: <input type="text" name="rpm" id="rpm" value="${Vehicles.ratePerMile}" disabled>

            Car Rate: <input type="text" name="rpd" id="rpd" value="${Vehicles.ratePerDay}" disabled>

            <%
                int id = (Integer) request.getAttribute("id");
            %>
            <input type="hidden" name="id" value="<%=id%>">

            Pick Up Date: <input type="date" name="pickUpDate">

            Return Date: <input type="date" name="returnDate">

            Total Miles: <input type="text" name="totalMile" id="totalMile" placeholder="approximate">

Total Amount Due: <input type="text" name="totalDue" id="totalDue">

        </form>

            <button id="showPaymentForm" onclick="totalDue()">Billing/Payment Info</button>

A: You need to set the value of the field instead of innerHTML in your case. Please refer to the fiddle here : https://jsfiddle.net/jhf18hsr/1/
I have put the parsing to integer values, which you can change to float as per your need, when reading the values from input controls.
function totalDue(){
  var rpm = parseInt(document.getElementById("rpm").value) || 0;
  var rpd = parseInt(document.getElementById("rpd").value) || 0;
  var totalMiles = parseInt(document.getElementById("totalMile").value) || 0;

  var totalDue = (rpm * totalMiles) + rpd;
  document.getElementById("totalDue").value = totalDue;
}

A: First we put some values in both rpm and rpd, like 3 and 40. For now let us do this:
Car Rate Per Mile: <input type="text" name="rpm" id="rpm" value="3">

Or you can simply remove the default values if desired:
Car Rate Per Mile: <input type="text" name="rpm" id="rpm">

Same for rpd. In the future you may want to load this values from a database or something, it would be awesome since you stated you are new to JS and maybe you will try php later but not the case today; in the meantime remove the "disabled" part and input your desired values each time.
Second, add a parseFloat in your math so js treat your rpm and rpd values as numbers not as text; parseFloat will allow you to use and display some decimals, in contrast to parseInt.
var totalDue = (parseFloat(rpm) * parseFloat(totalMiles)) + parseFloat(rpd);

Third, change document.getElementById("totalDue").innerHTML = totalDue; for document.getElementById("totalDue").value=totalDue;. This way you will populate your output textbox onClick.
However this does not integrate dates into equation, you must ellaborate your JS function a little bit more to achieve this.
In your output textbox line I would add disabled since I don't want to write in this box, only show the result:

Total Amount Due: <input type="text" name="totalDue" id="totalDue" disabled>

Hope this helps.


text:
Q: Position fixed is not working on ipad I am trying to fix the background of my website and i have place a div "bgDiv" on my website having position fixed. It is working good on desktop. but on ipad position fixed is not working it scrolls with my whole website. and background image is repeating. is there any way to avoid scrolling the bgDiv.
 .bgDiv{
    background: url("test.jpg") repeat scroll 0 0 transparent;
    background-size: 100% 100%;
    bottom: 0;
    left: 0;
    position: fixed;
    right: 0;
    top: 0;
    z-index: -2;
    height: inherit;
    }

          content

A: Update your css with this,
.bgDiv{
    background: url("test.jpg") repeat scroll 0 0 transparent;
    background-size: 100% 100%;
    left: 0;
    position: fixed;
    top: 0;
    z-index: -2;
    height: auto;
    width:100%;
 }

If not added, add this to your code above,
 <meta name="viewport" content="width=device-width, user-scalable=no" />

You can refer to this documentation:-
http://www.quirksmode.org/blog/archives/2010/12/the_fifth_posit.html


text:
Q: Encountered a StorageException while trying to fetch the diagnostic events Out of nowhere started seeing this error when opened function apps, Application is working though.
Unable to retrieve diagnostics and error information for your function app.
Encountered a StorageException while trying to fetch the diagnostic events.
Please make sure the connection string in the app setting "AzureWebJobsStorage" has the permissions to access Azure Table Storage

Storage account network access is set to "Enabled from selected virtual networks and IP addresses". Even with this settings there was no error before.
but now the above error message is gone only when changed to "Enabled from all networks".
Recently updated functionapp to dotnet 6.0 and v4 runtime even after, there was no error. Not sure if this has anything to do with this.
How do I fix for this?

A: This was caused by a platform level alert raised by a diagnostic component, and although it had no impact on the production workloads, the verbiage wasn't clear and the level misleading. The event has been disabled and you should no longer see this come up.
To expand, this error was reported by the control plane for the diagnostic component, which is meant to surface diagnostic events raised by production components to the portal, but not involved in any production workload flow and had no impact on the App's functionality.

A: We noticed the same issue in several of our functionapps. We also have configured the functionapp to be able to access the storage account via a subnet in a vnet, which worked fine until a few days ago. The functionapp itself is still working as intended, but it started showing  this message a few days ago. As a test we did 'Enable from all networks' on the storage account, which resolved the warning message. I suspect there is some other service besides the functionapp which needs access to the storage account to read the functionapp diagnostic information. If I would know which service we could grant it access to the storage account without needing to 'Enable from all networks'

A: I raised a support ticket with Microsoft regarding this issue and was told that there seems to be a platform issue for App Services in West Europe region and they are currently investigating.


text:
Q: What is recommended lifetime of Database object in a web application? I consider using PetaPoco in a conventional web app. Saying conventional I mean

*

*handling requests in separate threads from a pool

*requests are quick: no long polling, streaming, etc

*but not necessarily ASP.NET, it may be for example Nancy

What should be the lifetime of the Database object, and that of the underlying DbConnection?

*

*globally static (I guess no, due to this answer)

*per-thread static, [ThreadStatic]

*per-request

*unit of work style: create and dispose as soon as the task is finished

I especially appreciate answers from those who run production apps with PetaPoco.

A: Per request is the way to go

*

*globally static: you guess right. Will bring problems accessing the same recordset and others. Definitely no.

*per-thread static. You should avoid [ThreadStatic] in Asp.net

*per-request: works great

*unit of work style: It works great also (not my preference)

A: You need one object per thread, but you shouldn't associate the object with the thread itself, because handling a request can start in one thread and finish in another thread.
Using one object per request would normally be the best, at least for quick request handling. However that is not always simple. If you risk leaving objects without disposing them (for example if there is an exception), it's better to use one object for a limited task where you can make sure that it is disposed properly.

A: Database is a cheap object to create, so I just create it as needed. I use PetaPoco (or more specifically AsyncPoco so I'm not tying up threads during I/O bound work) in a busy web app and this works great for me. Others do prefer per-request though, and that should also work well.


text:
Q: Relative size of symbols This is perhaps a typography question rather than a LaTeX one.  I'm using playing card symbols from Book Antiqua and the heart symbol feels too big to me (subjective, I know).  So I rescale it and that looks OK in the first text line of the MWE.
But then I use the symbols again when they are very close together and the sizes look wrong to my eye.  What I think is happening is that the relatively large numbers and brackets change the size perception.
I could make the brackets smaller but I wonder how other people would address this issue.  Or if they even see it as an issue :-)
MWE:
\documentclass[a4paper, 11pt, oneside]{memoir}

\usepackage{fontspec}
\usepackage[HTML, hyperref, x11names]{xcolor}

\usepackage{relsize}

\defaultfontfeatures{Scale=MatchUppercase}
\newfontface{\BCards}{Book Antiqua}

\NewDocumentCommand{\BCs}{}{{\BCards\char"2663}}
\NewDocumentCommand{\BDs}{}{{\color{red}\BCards\char"2666}}
\NewDocumentCommand{\BHs}{}{{\relscale{0.9}\color{red}\BCards\char"2665}}
\NewDocumentCommand{\BSs}{}{{\BCards\char"2660}}

\begin{document}

In sequence 1\BCs{}--1\BDs{}--1\BHs{}--1\BSs{}

\begin{tabular}{@{} *{3}{l}}
2NT     &                       &\\
        &Pass                   &0--4 HL ;\\
        &3\BCs{}                &4+ HL, Stayman Puppet ;\\
        &3\BDs{}(\BHs{})        &4+ HL, Texas M ;\\
        &3\BSs{}(4\BCs{})       &4+ HL, Texas m ;\\
        &4\BHs{}(\BSs{})        &9+ HL, two suiter ;\\
\end{tabular}

\end{document}


text:
Q: How to change InnoDB AUTO_INCREMENT Lock Modes on Debian? I create a table with auto_increment, and insert into it a lot of data.
My database skip number while I am using auto-increment, i found that i have to change the auto_incremet_lock_mode = 0, but i didn't find, where i have to do this change on Debian system?
I tried to find the my.cnf file in /etc/mysql/ but it contains only 2 rows, so i don't know how i can change it. I read the mysql site too but there isn't any information about it.

A: It was hard, but i found the answer!

*

*
*

*edit the /etc/my.cnf file with
[mysqld]
innodb_autoinc_lock_mode=0
//You have to use autoinc_lock_mode inside this [mysqld] part!

*

*restart/reload configs with sudo /etc/init.d/mysql restart


text:
Q: You cannot call a method on a null-valued expression. clicking button in webpage via powershell I am trying to click a button within a synology nas webpage environment.
Sadly the $link=$ie.Document.getElementByID('ext-gen258') $linck.click()
doesn't work as the element id constantly changes when you reload the page.
The element im trying to open:

Beveiliging

I also tried the following code:
$button = $ie.Document.getElementsByTagName("div") |
          Where-Object {$_.value -eq "controlpanel:leaf_security"}

$button.click()

But then the code wont resume and get stuck.
What am I doing wrong?

A: $doc = $ie.document

# commit the button
$commit = $doc.getElementById("controlpanel:leaf_security")
if ($commit) { $commit.click() }

this code works... dont know why tho would love to have a explanation.


text:
Q: What is the meaning of 'drive up'? He was marching up and down in front of the camp when four officers drove up in a car. What is the meaning of 'drove up'?

A: In this particular context it's to approach or arrive at a location.

up
  adverb
1.So as to approach; near:
  came up and kissed me.
American Heritage Dictionary
3To the place where someone is.
  'Dot didn't hear Mrs Parvis come creeping up behind her'
Oxford Living Dictionary
6.to or at a source, origin, center, or the like.
Collins Dictionary
8a : so as to arrive or approach
Merriam-Webster Dictionary

This is a question that's not answered so easily because we use "up" after many verbs. In some cases it changes the meaning entirely, in other cases it doesn't, and removing it would result in much the same meaning.

*

*I went to the man and asked him for directions.

*I went up to the man and asked him for directions.

*I drove to Arlington.

*I drove up to Arlington.
In certain cases there may a semantic difference, but it's only generally known from context. In other cases it may be for emphasis of some sort. For example in "driving to" vs "driving up to" the extra word may possibly emphasize effort or distance (leaving aside the cardinal directions (north/south) or uphill/downhill, or not. It's to be understood in the overall context.
The emphasis can also be on appearing without expectation or quickly, as in this example from Oxford Living Dictionaries:

'He was talking with his client outside the courtroom when a witness rushed up and attacked his client.'

*

*it came up behind me
is more likely to mean something moved behind you suddenly or without notice more than would be the case from just saying:

*

*it came behind me
It's uses are many and subtle. I doubt I could give a very good explanation of its use and its meaning. However, in the example case you've shown, the meaning is as I explained at the beginning of my answer.


text:
Q: How do I get my application Version in Android Can anyone tell me how to get the application version in Android?

A: I am using Android Studio, I realized I could use one line code to get this.
/*version name*/
BuildConfig.VERSION_NAME

/*version code*/
BuildConfig.VERSION_CODE

Edited:
If you are using other android libraries, make sure you import BuildConfig from your application package. This is similar to the automatically generated R class for identifying resources.

A: If you are using eclipse try this:
PackageInfo packageInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
int versionCode = packageInfo.versionCode;
String version = packageInfo.versionName;

In Android Studio :
int versionCode = BuildConfig.VERSION_CODE;
String versionName = BuildConfig.VERSION_NAME;

make sure you have mansion version code in your module-level build.gradle file

A: In your (Module: app) gradle define the version name and version code
defaultConfig {
        applicationId "com.sing.smart"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.1.0"
    }

versionCode
The versionCode is an integer value used to easily differentiate between app versions.
App developers must increment this value when they release updates to their apps in Android Market, so it can determine if users are using an old version of the app, and offer them to update it.
versionName
The versionName is a string containing a regular "release version" as seen in other desktop applications, such as "1.4.5" or "3.7".
The versionName is just a "human readable" version code.
PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
int versionNumber = pinfo.versionCode;
String versionName = pinfo.versionName;

A: This page has a tips on how to do it from java:
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(
    context.getPackageName(), 0);
String version = info.versionName;

Also, this link has official information on how to properly set up your application versioning.

A: public int getVersion(Context context) {
        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            return pInfo.versionCode;
        } catch (NameNotFoundException e) {
            return 0;
        }
    }
}

More info on this link

A: To get application information:
PackageManager manager = this.getPackageManager();
try {
   PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
   String packageName = info.packageName;
   int versionCode = info.versionCode;
   String versionName = info.versionName;
   } catch (NameNotFoundException e) {
   // TODO Auto-generated catch block
   }

A: The easiest and best answer I found is to just import your BuildConfig
import your.package.BuildConfig;

then just
String verName = BuildConfig.VERSION_NAME;
int verCode = BuildConfig.VERSION_CODE;

A: If you need it for scripting purposes (not for programming) you can use this command:
 adb shell "pm dump com.example.your.package.name | grep \"versionCode\"" | awk '{print $1}' | awk -F '=' '{print $2}'

A: int versionCode = BuildConfig.VERSION_CODE;
String versionName = BuildConfig.VERSION_NAME;

A: Java
String versionCode = String.valueOf(BuildConfig.VERSION_CODE);
String versionName = String.valueOf(BuildConfig.VERSION_NAME);

Kotlin
val versionCode = BuildConfig.VERSION_CODE
val versionName = BuildConfig.VERSION_NAME

A: On Nativescript (with Typescript) one can do like this:
import {Observable} from 'data/observable';
import * as applicationModule from 'application'

export class AboutViewModel extends Observable {
    public version: string;

    constructor() {
        super();
        let manager = applicationModule.android.context.getPackageManager();
        let info = manager.getPackageInfo(applicationModule.android.context.getPackageName(), 0);
        this.version = info.versionName;
    }
}

A: In kotlin :
fun getAppVersionName(context: Context): String {
        var appVersionName = ""
        try {
            appVersionName =
                context.packageManager.getPackageInfo(context.packageName, 0).versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return appVersionName
    }

fun getAppVersionCode(context: Context): Long {
        var appVersionCode = 0L
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                appVersionCode =
                    context.packageManager.getPackageInfo(context.packageName, 0).longVersionCode
            }
            else{
                appVersionCode =
                    context.packageManager.getPackageInfo(context.packageName, 0).versionCode.toLong()
            }
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return appVersionCode
    }


text:
Q: Move a default text as you type in a textbox along with text typed default text is "Move"
-------------------------------------
|Move                                |
|                                    |
|                                    |
-------------------------------------

-------------------------------------
|W Move                              |
|                                    |
|                                    |
-------------------------------------

-------------------------------------
|Wo Move                             |
|                                    |
|                                    |
-------------------------------------

-------------------------------------
|Wow Move                            |
|                                    |
|                                    |
-------------------------------------

As I start typing letters "w" "o" "w" default text "Move" move to right as a new letter append to the text box.
I searched for sometime but din't get any right pointer to achieve this. Hope to get someone would be able to point me towards the right direction.
Here is a jsfiddle page I have so far, http://jsfiddle.net/jsnewbie/xmtFM/2/
Thanks for your help.

A: Not sure why you'd need JavaScript to accomplish this? If some one were to just click in the box before the word Move, the default functionality for a textbox would accomplish exactly what you desire.

A: EDIT
Backspace and a bit responsive as @KevinB suggested
var store = $('textarea').val();
console.log(store);
var newVal = [];
$("textarea").focus(function () {
    console.log(store);
}).keydown(function (e) {
    var self = this;
    setTimeout(function () {
        if (e.keyCode !== 8) {
            var curr = String.fromCharCode(e.keyCode);
            newVal.push(curr);
            console.log(newVal + store);
        } else { // Backspace
            e.preventDefault();
            if (newVal.length > 0) newVal.pop();
        }
        $(self).val(newVal.join('') + " " + store);
    }, 20);
});

Check Fiddle


text:
Q: Building backward compatible binaries with newer CPU instructions support What is the best way to implement multiple versions of the same function that uses a specific CPU instructions if available (tested at run time), or falls back to a slower implementation if not?
For example, x86 BMI2 provides a very useful PDEP instruction. How would I write a C code such that it tests BMI2 availability of the executing CPU on startup, and uses one of the two implementations -- one that uses _pdep_u64 call (available with -mbmi2), and another that does bit manipulation "by hand" using C code. Are there any built-in support for such cases?  How would I make GCC compile for older arch while providing access to the newer intrinsic?  I suspect execution is faster if the function is invoked via a global function pointer, rather than an if/else every time?

A: You can declare a function pointer and point it to the correct version at program startup by calling cpuid to determine the current architecture
But it's better to utilize support from many modern compilers. Intel's ICC has automatic function dispatching to select the optimized version for each architecture long ago. I don't know the details but looks like it only applies to Intel's libraries. Besides it only dispatches to the efficient version on Intel CPUs, hence would be unfair to other manufacturers. There are many patches and workarounds for that in Agner`s CPU blog
Later a feature called Function Multiversioning was introduced in GCC 4.8. It adds the target attribute that you'll declare on each version of your function
__attribute__ ((target ("sse4.2")))
int foo() { return 1; }

__attribute__ ((target ("arch=atom")))
int foo() { return 2; }

int main() {
    int (*p)() = &foo;
    return foo() + p();
}

That duplicates a lot of code and is cumbersome so GCC 6 added target_clones that tells GCC to compile a function to multiple clones. For example __attribute__((target_clones("avx2","arch=atom","default"))) void foo() {} will create 3 different foo versions. More information about them can be found in GCC's documentation about function attribute
The syntax was then adopted by Clang and ICC. Performance can even be better than a global function pointer because the function symbols can be resolved at process loading time instead of runtime. It's one of the reasons Intel's Clear Linux runs so fast. ICC may also create multiple versions of a single loop during auto-vectorization

*

*Function multi-versioning in GCC 6

*Function Multi-Versioning

*The - surprisingly limited - usefulness of function multiversioning in GCC

*Generate code for multiple SIMD architectures
Here's an example from The one with multi-versioning (Part II) along with its demo which is about popcnt but you get the idea
__attribute__((target_clones("popcnt","default")))
int runPopcount64_builtin_multiarch_loop(const uint8_t* bitfield, int64_t size, int repeat) {
    int res = 0;
    const uint64_t* data = (const uint64_t*)bitfield;

    for (int r=0; r<repeat; r++)
    for (int i=0; i<size/8; i++) {
        res += popcount64_builtin_multiarch_loop(data[i]);
    }

    return res;
}

Note that PDEP and PEXT are very slow on current AMD CPUs so they should only be enabled on Intel


text:
Q: AIX (no GNU sed/awk) join line if it does NOT have control M or \r character at the end I am looking for way to join line if the file does not control M character. AIX has its standard awk and sed utility but not GNU
The issue: we get file from 3rd party , from windows. And the file has ^M (i.e. \r) character at end of each line, expect for some lines , in which the data in some field itself has \n character. Hence there is need to join the lines which has this extra \n character.
Data example :
col1|col2|col3|col4|col5|^M
a1|a2|a3|a4|a5|^M
b1|b2|b3|b
4|b5|^M
c1|c2|c3|c4|c5|^M

expected output.
col1|col2|col3|col4|col5|^M
a1|a2|a3|a4|a5|^M
b1|b2|b3|b4|b5|^M
c1|c2|c3|c4|c5|^M

Thank you in advance for any help.

A: Just for the record, perl is handling really good transformations of \n, \r , etc, without the restrictions of non gnu sed - actually perl -pe can replace sed directly.
So this operation worked fine in BSD :
$ echo -ne "abc\r\ndef\nijk\r\nlmn\r\n" |cat -vte
abc^M$
def$
ijk^M$
lmn^M$

$ echo -ne "abc\r\ndef\nijk\r\nlmn\r\n" |perl -pe "s/\r\n/\0/g;s/\n//g;s/\0/\r\n/g" |cat -vte
abc^M$
defijk^M$
lmn^M$

A: A literal carriage-return can be used by typing ^V (Ctrl-V) followed by the "Return" key.
The following sed(1) script loops over lines that do not end in a carriage-return, removing the undesired line-feeds:
sed '
:label
/^M$/! {
    N
    s/\n//
    blabel
}'

As one line:
sed -e ':l' -e '/^M$/!{N;s/\n//;bl' -e '}'


text:
Q: What does my QQ Plot tell me if I have 4 variables? I have a model:
Model <- lm(Offensive.Score ~ FirstDown+ThirdDownPct+RushYds+PassYds, data = NFL.Team)

I have done crazy research on QQ Plots and understand that they are standardized points.
I still have no idea how that translates to my data though.
Above, I have a model that tries to predict the final score of the offensive team
with variables:
# x1:Num of offensive team's first downs.
# x2:Percent of offensive team's plays that get to the third down.
# x3:Yards gained during rushes.
# x4:Yards gained during passes.

My qqPlot shows right-skewness.
What does this mean?
I thought finding if something was skewed only applied to ONE variable but I have 4?
Thank you!


text:
Q: HTML element with variable In jQuery I can create a HTML element with data:
$('<button onclick="btn()"></button>').data("field", { i: i, j: j }).appendTo("body");

and use it so:
function btn(){
    var field = $(this).data("field")
    alert(field.i)
}

HTML
<button onclick="btn()" data-field= "{ i: thevalueofi, j: tthevalueofj }"></button>

function btn(){
    var field = $(this).data("field")
    alert(field.i)
} // it doesn't work

How can I use data in JavaScript?

A: If you want the html of a button which will have the same data available as the button you created, you'll have to use the html5 data attributes. i.e.
<button data-field='{ "i": "thevalueofi", "j": "tthevalueofj" }'></button>

and read it
 function btn(){
        var field = $('button').data("field");
        alert(field.i)}
 }

with plain js
 function btn(){
        var field = JSON.parse(document.querySelector('button').getAttribute("data-field"));
        alert(field.i)}
 }

A: With .dataset:
document.querySelector('button').dataset.field

This isn't supported in all browsers, so you may need to find a polyfill (or use jQuery).

A: I want to expand on Derek's comment, and on some of the other answers here to address the burning question.

ok, but how can i use it?

The data-* series of attributes are designed for storing a set of data as attributes on an HTML element, and it's designed in such a way so that you don't have to explicitly deal with data to JSON conversions yourself or store all the data in a single attribute.
Instead of storing all your data in a single data-* attribute, store the data in individual attributes, like so:

     ...

Then, when you need to retrieve your data, you can retrieve it all at once with a simple JavaScript command:
var userObj = document.getElementById("wrapper").dataset;

console.info("user id = " + userObj.id); // prints "12345"
console.info("name = " + userObj.name);  // prints "James"
console.info("role = " + userObj.role);  // prints "developer"

As you can see, non-data-* attributes, like the id and class, are not included in dataset, which makes it easy to extract only the data itself.
Moreover, the userObj is similar to a pure JavaScript object, which I can confirm by stringifying it:
console.info("Stringified JSON object = " + JSON.stringify(userObj));
    // prints '{"id":12345,"name":"James","role":"developer"}'

However, truth be told, the object isn't a true JavaScript object but is in fact a DOMStringMap, which has limitations when it comes to nesting data, which we'll see below:

void setDataAttr(
  in DOMString prop,
  in DOMString value
);
Parameters
prop
The property whose value is to be set.
value
The property's new value.

Note that the above value is a DOMString, not an object.
In your case, you're storing all of your data as a single, stringified JSON object on a single data-* field called data-field. This isn't incorrect, but it's slightly different, and may lead to more work for you. It may have different advantages and disadvantages in regards to readability, for instance, as well as the extra work converting the string to an object.
In your case, to extract the data, you'd need to do this:

var userString = document.getElementById("user").dataset.field;

Except, here's where we begin to see holes in this methodology. The dataset.field value is not an object like it would be in the first example; instead, it's a string, and we must convert it to an object ourselves:
var userObj = JSON.parse(userString);

Now we can access the properties of the data represented by data-field:
console.info("name = " + userObj.name);  // prints the name "James"

Unlike a regular JSON object, which can contain nested JSON objects, the DOMStringMap is an object containing key/value pairs where the values are all strings.  In short, any nested objects inside a value are represented as strings, not as an object, which means they must be converted to objects individually.
Again, this isn't a bad thing, but it suggests that storing objects in a single element might be better reserved for more complex data structures where the object representation is more than just one level deep. In that case, we must convert from string to JSON, but we'd have a good reason to do so in that case, since the engine won't do those conversions for us beyond just one level of nesting.
Try manipulating the data yourself from the Chrome JavaScript console, or the Firebug console, if you prefer Firefox. The console allows us to play around with different techniques in real-time and get a stronger feel for how a certain feature is supposed to work.  Hope this helps!

A: Use this javascript.
<button type="button" id="mybutton" onclick="btn()" data-field= "{ i: thevalueofi, j: tthevalueofj }"></button>

OR
Use jQuery like this.
<button type="button" id="mybutton" onclick="btn()" data-field= "{ i: thevalueofi, j: tthevalueofj }"></button>


text:
Q: How to get started with testing on an existing python script? I'm fairly experienced with python as a tool for datascience, no CS background (but eager to learn).
I've inherited a 3K line python script (simulates thermal effects on a part of a machine). It was built organically by physics people used to matlab. I've cleaned it up and modularized it (put it into a class and functions). Now I want an easy way to be certain it's working correctly after someone updates it. There have been some frustrating debugging sessions lately. I figure testing of some form can help there.
My question is how do I even get started in this case of a large existing script? I see pytest and unittest but is that where I should start? The code is roughly structured like this:
class Simulator:
    parameters = input_file
    def __init__(self):
        self.fn1
        self.fn2
        self.fn3

    def fn1():
        # with nested functions
    def fn2
    def fn3
    ...
    def fn(n)

Each function either generates or acts on some data. Would a way to test to have some standardized input/output run and check against that? Is there a way to do this within the standard convention of testing?
Appreciate any advice or tips,
cheers!

A: Broadly speaking, you test a function by calling it with arguments and checking if the return value is what you expect it to be. This means you should know beforehand how you expect your function to behave.
Here's a test for a simple add function:
def add(a, b):
    return a + b

def test_add_function():
    a = 1
    b = 2
    assert add(a, b) == 3  # we KNOW that adding 1 + 2 must equal 3

If you call test_add_function and no AssertionError is raised, congrats! Your test passed.
Of course, testing gets messier if you don't have "pure" functions, but rather objects that operate on shared data, like classes. Still, the logic is basically the same: call the function and check whether the expected result actually happens:
class MyClass:
    def __init__(self, a):
        self.a = a

    def add_one_to_a(self):
        self.a += 1

def test_method_add_one_to_a():
    initial_a = 1
    instance = MyClass(a=1)
    assert instance.a == initial_a  # we expect this to be 1
    instance.add_one_to_a()  # instance.a is now 2
    assert instance.a == initial_a + 1  # we expect this to be 2

I suggest reading/watching some tutorials on Python's unittest module to get your feet wet, especially getting used to the unittest.TestCase class, which helps a lot to common test operations, like set up/tear down routines (which allows you to e.g. "refresh" your Simulator instance between tests), testing if an error is raised when a function is called with wrong arguments, etc.
There are of course other strategies when things are more complicated than this (as they often are), like mocking objects which basically allows you to inspect any object/function called or modified by another object/function, check if it was called, what arguments were used, and so on.
If testing your functions is still too complex, this probably means that your code isn't modularized enough, or that your functions try to perform too many things at once.

A: Hope everything is alright with you!
pytest is good for simple cases like yours (1 file script).
It's really simple to get started. Just install it using pip:
pip install -U pytest

Then create a test file (pytest will run all files of the form test_*.py or *_test.py in the current directory and its subdirectories)
# content of test_fn1.py

from your_script import example_function

def test_1():
    assert example_function(1, 2, 3) == 'expected output'

You can add as many tests in this file as you want, and as many test files as you desire. To run, go to the folder in a terminal and just execute pytest. For organization sake, create a folder named test with all test files inside. If you do this, pay attention to how you import your script since they won't be in the same folder anymore.
Check pytest docs for more information.
Hope this helps! Stay safe!

A: If you are savvy enough with Python, but struggle to adopt unittesting meaningfully to a set of scripts which take data in and transform it, I would take a different approach, at least if the output is deterministic

*

*store sample data somewhere and keep it under source control

*run individual functions against that test data.

*

*record the output.  this is assumed to be "known good"/baseline.

*

*one challenge is that you may have to "scrub" out continuously-varying data like timestamps or GUIDs.

*sort, sort, sort.  plenty of data comes out unsorted, and is good as long as all the records are correct.  you cannot compare anything meaningfully under those circumstances, so you'll need to sort in a deterministic fashion.

*file diffing typically works on a line-by-line basis.  so it's best to "explode" multiple fields in 1 row into 1 field per row, possibly with a label <row1key>.f1 : <value1>\n<row1key>.f2: : <value2>

*at this point, you don't need to validate anything via this mechanism.  (traditional unittesting approaches can still be used elsewhere)

*whenever you modify/refactor the code, run the sample data against the relevant functions.

*

*compare your new output against your previous baseline.  if it doesn't match you have 2 possibilities:

*

*the new code produces better output, i.e. it fixes something.  the new output becomes the baseline.  store it in the baseline.

*the old output is better.  fix the new code till you have the same output

*if you store in text/json/yaml form, you can leverage diff-type utilities such as Winmerge, Beyond Compare (never used), diff, opendiff, etc to assist you in finding points of divergence.  In fact, in the start it's often easier to ask Python to just write the output files without checking for equality and then using file diff tools to compare multiple last-run vs current-run files.
This sounds rather naive.  After all, your "tests" don't really know what is going on.  But it is a surprisingly powerful method to achieve stability and refactorability against an existing codebase that takes in lots of data and outputs lots of already acceptable results.  This is especially true when you don't know the codebase well yet.  It is less useful against a new codebase.
Note that you can always use regular pytest/unittest techniques feed your functions with more limited carefully crafted test data that exercises some particular aspect.
I've done this a number of times and it has always served me well.  As you get more comfortable with the technique it takes less and less time to adapt to new circumstances and becomes more and more powerful.  It is good for batch and data-transformation pipelines, not so much for GUI testing.
I have an html-oriented toolkit on github, lazy regression tests, based on this approach.  Probably unsuited for a data pipeline, but you can really write your own.

A: No matter how hard you test a program, it is always fairly reasonable to assume that there will always still be bugs left unfound, in other words, it is impossible to check for everything. To start, I recommend that you thoroughly understand how the program works; thus, you will know what the expected and important values that should be returned are, and what exceptions should be thrown when an error occurs. You will have to write the tests yourself, which may be a hassle, and it sounds as if you don't want to do it, but rigorous testing involves perseverance and determination. As you may know, debugging and fixing code can take a lot longer than the coding portion itself.
Here is the pytest documentation, I suggest you map out what you want to test first before reading the documentation. You don't need to know how pytest works before you understand how that script of yours works first. Take a pen and paper if necessary and plan out what functions do what and what exceptions should be thrown. Good luck!

A: Summary: One method is to create a stand alone doctests file from tests run on your existing code through the command line interpreter.
Ideally you want a set of tests in place before you refactor the existing code. If you have inherited a big ball of mud (bbom), it can be tricky to create a set of comprehensive unit tests for each function prior to refactoring. Creating doctests can be a faster way to go.
You can quickly extend your doctests file as your understanding of the code develops and you encounter edge cases you need to include in your tests.
Please find an example for a nonesense 'little ball of mud' class (lbom) below.
import random

class Lbom():
  def __init__(self, **kwargs):
    for key, value in kwargs.items():
      if key == 'color':
        self.print_color(value)
      if key == 'combo':
        self.combo(value)

  def combo(self, combination):
    print(combination * random.randint(0,100))

  def print_color(self, color):
    print('color: {}'.format(color))

enter the Python REPL by typing 'python' at the command line:
>>> from lbom import *
>>> random.seed(1234)
>>> test = Lbom(color='blue', combo = 3.4)
color: blue
336.59999999999997
>>> test.print_color('red')
color: red
>>> random.seed(1010)
>>> test.combo(-1)
-85
>>>

Cut and paste the tests into a file. I wrap these commands into a python module as shown below and saved it as test_lbom.py in a subdirectory called tests. The advantage of saving as a .py file and not just using doctest with a .txt file is that you can place the file in a folder separate from the file under test.
test_lbom.py:
def test_lbom():
    '''
    >>> from lbom import *
    >>> random.seed(1234)
    >>> test = Lbom(color='blue', combo = 3.4)
    color: blue
    336.59999999999997
    >>> test.print_color('red')
    color: red
    >>> random.seed(1010)
    >>> test.combo(-1)
    -85
    >>>
    '''

if __name__ == '__main__':
  import doctest
  doctest.testmod(name='test_lbom', verbose=True)

Run this using:
python -m tests.lbom_test

You will get a verbose output showing all tests are passing.


text:
Q: Code Runner in VSCode not removing the file path on integrated Console I added These lines to my Settings.JSON file, however, I still get the file path when I run my code. Am I missing some lines in order to make this work?
"code-runner.clearPreviousOutput": true,
"code-runner.showExecutionMessage": false,

VSCode Settings.JSON code


text:
Q: Execute a WHERE clause before another one I have the following statement
SELECT * FROM foo
WHERE LEN(bar) = 4 AND CONVERT(Int,bar) >= 5000

The values in bar with a length of exactly 4 characters are integers. The other values are not integers and therefore it throws an conversion exception, when trying to convert one of them to an integer.
I thought it's enough to put the LEN(bar) before the CONVERT(Int,bar) >= 5000. But it's not.
How can I kind of prioritize a specific where clause? In my example I obviously want to select all values with a length of 4, before converting and comparing them.

A: 6 answers and 5 of them don't work (for SQL Server)...
SELECT *
  FROM foo
 WHERE CASE WHEN LEN(bar) = 4 THEN
       CASE WHEN CONVERT(Int,bar) >= 5000 THEN 1 ELSE 0 END
       END = 1;

The WHERE/INNER JOIN conditions can be executed in any order that the query optimizer determines is best. There is no short-circuit boolean evaluation.
Specifically for your question, since you KNOW that the data with 4-characters is a number, then you can do a direct lexicographical (text) comparison (yes it works):
SELECT *
  FROM foo
 WHERE LEN(bar) = 4 AND bar > '5000';

A: try this
SELECT bar FROM
(
SELECT  CASE
       WHEN LEN(bar) = 4 THEN   CAST( bar as int)
       ELSE  CAST(-1 as int) END bar
FROM Foo
) Foo
WHERE bar>5000


text: Q: How is the Tumbleweed badge awarded? I have been searching through meta trying to find out what the exact number of views is that constitutes "low views."  Is there an algorithm that determines when the Tumbleweed badge is programmatically awarded?  Or does someone go through questions and manually award the badges to questions they think meet the criteria?


text:
Q: WebRTC ICE-Stun message-integrity attribute What do I use for the HMAC-SHA1 key when verifying the MESSAGE-INTEGRITY attribute of STUN Binding Requests from Chrome? (chrome is in the ICE-CONTROLLING role as the SDP offer is from an ICE-LITE peer)
RFC-5245 states:

To compute the message integrity for the check, the agent uses the
remote username fragment and password learned from the SDP from its
peer.  The local username fragment is known directly by the agent for
its own candidate.

But it does not state how these are concatenated by the agent to form the HMAC SHA1 key
I have tried different combinations of ice-username:ice-password to form the key, but none seem to be able to generate the same hash as the message integrity attribute in the Binding request from chrome.
Does anyone know how the HMAC key is formed?

A: Requests for you will be signed with your local ice-pwd and the responses must be signed with it (as described ħere).
See RFC 5389 on how to compute the hash.


text:
Q: ¿Cómo usar un "comodin" en el nombre de una variable? Quiero asignar un número a una variable dentro de una función a modo de comodin de manera similar a como se usa al recorrer un listado accediendo a su indice.
Este es el código que tengo actualmente, y me gustaría reemplazar la variable color1 por color* (o donde haya un 1) dentro de la función.
color0 = 'red'
color1 = 'green'
color2 = 'blue'

def _func(ev):
    itm['C1'].BackgroundColor = color1
    # color1
    # color1
    # y otras tantas referencias a color1
    #...
dlg.On.C1.Clicked = _func

Mi intento ha sido este:
color0 = 'red'
color1 = 'green'
color2 = 'blue'

def selColor(n):
    itm['C' + n].BackgroundColor = color[n]
    # color[n]
    # color[n]
    # ...

def _func(ev):
    n = 1
    selColor(n)
dlg.On.C1.Clicked = _func

A: Usar una lista con las variables color1, color2, color3,... me sirve, excepto para seleccionar un item que funciona por ID, y cuyas variables son string.
He probado con esto, intentando seleccionar por index, pero me peta la aplicación cuando se ejecuta la función _func, en la condición store == 1
color = [color0, color1, color2, color3, color4, color5]
ids = ['c0', 'c1', 'c2', 'c3', 'c4', 'c5']

def selColor(n,i):
  toollist = comp.GetToolList(True).values()
  tool = []
  if store == 0:
    for tool in toollist:
      tool.TileColor = color[n]
  elif store == 1:
    color[n] = color
    itm[ids[i]].BackgroundColor = color[n]

def _func(ev):
  n = 0
  i = n
  selColor(n,i)
dlg.On.c0.Clicked = _func


text:
Q: Make one time only activation code to python code, and make updates available? I'm coding a program to do some action with webdriver and Autoit in python, I want to do two things before I start selling my code:

*

*Add onetime activation code to my software on one PC, like to make the program works only on one pc.

*Make my program able to receive updates from the internet once I add to the code some more features or correct some others.
is it possible only with Python? or what is the method statement to do it?

A: On client side you need use hard-disk serial or/and uuid of partition or Operational System timestamp + something to generate serial code .
On server side , you need a API to store hard disk serial to validate if this is a computer valid . And you client on load check if activaction is valid .
The second question i can't answer .

A: Regarding the second part of your question:
Create a text file with the latest version of your application and put it on your webserver e.g. http://download.example.com/example-app-version.txt to get and read its value later.
On your python code download and read the text (for Python 3+ use 'import urllib.request' and urllib.request.urlretrieve) when your app  runs and compare it against the installed version (if statement).
E.g.
if latestVer > installedVer:
    #update
else:
    #application continues


text:
Q: Compare 2 users lists python I need to compare 2 lists [new_user] and [current_user] and verify if new user is already in current user (no case sensitive)
current_users = ['john', 'anne', 'matthew', 'yennefer', 'tony']
new_users = ['paul', 'frank', 'carl', 'nana', 'JOHN']
current_users.extend(new_users[0:2])
lower_user = []

for new_user in new_users:
    lower_user.append(new_user.lower())
    if lower_user in current_users:
        print("Name unavaible, " + str(new_user))
    else:
        print("Name available, " + str(new_user))

Actually, that's the output:
Name available, paul
Name available, frank
Name available, carl
Name available, nana
Name available, JOHN

JOHN is available, so isn't working.
How can i do it?

A: In your code, your if statement is basically saying if the list lower_user is in the list current_users, then do something. Instead, you want to see if the previously appended result in lower_user is in current_users. Do this by adding the index [-1] to the lower_user list.
current_users = ['john', 'anne', 'matthew', 'yennefer', 'tony']
new_users = ['paul', 'frank', 'carl', 'nana', 'JOHN']
current_users.extend(new_users[0:2])
lower_user = []

for new_user in new_users:
    lower_user.append(new_user.lower())
    if lower_user[-1] in current_users:
        print("Name unavailable, " + str(new_user))
    else:
        print("Name available, " + str(new_user))

This provides the output:
Name unavailable, paul
Name unavailable, frank
Name available, carl
Name available, nana
Name unavailable, JOHN

If this is the intended output, great. If not, please provide what the expected output is.
You could also simplify this a lot and eliminate appending to the lower_user list by just comparing it directly.
current_users = ['john', 'anne', 'matthew', 'yennefer', 'tony']
new_users = ['paul', 'frank', 'carl', 'nana', 'JOHN']
current_users.extend(new_users[0:2])

for new_user in new_users:
    if new_user.lower() in current_users:
        print("Name unavailable, " + str(new_user))
    else:
        print("Name available, " + str(new_user))

I do find it interesting that you extend the current_users list to include the first two values in new_users with the line current_users.extend(new_users[0:2]), but I digress.


text:
Q: VNC via socks SSH proxy tunnel I can connect to my private work network using Putty with the following settings:

*

*Hostname: login.example.com

*Port: 502

*SSH Forwarded Ports: D8888

This opens an SSH socks proxy which allows me to access internal servers.
I again use Putty to connect to the internal Ubuntu server using the socks proxy above.
Now I want to get the server GUI using VNC, but I am unable to connect with the socks proxy. I tried forwarding the ports, but since I am newbie to this, I may have done it incorrectly. So how can I run VNC from my Windows machine to access the remote VNC server?
This article did not help me to connect using vncserver. RDP isn't working, either. The VNC session is on a different server accessible only from login.example.com as a socks proxy.
Note: I am able to SSH to the internal servers using the configuration above with the login.example.com as socks proxy in Putty.

A: If you're using the RealVNC viewer, as shown in the article you cited, then you should be able to do the following:

*

*Use PuTTY to connect to login.abc.com and set the D8888 forwarding (which you said you've already been doing).

*Start RealVNC viewer and click the Options... button.

*Select the Connection tab.

*Click the Use these proxy settings radio button.

*Set Proxy type to SOCKS 5.

*Set Proxy address and port to localhost:8888.

*Now try connecting to the actual VNC server, e.g. vnc-server.abc.com:1. Don't use localhost:1, as you should be going through the SOCKS proxy.

A: Most VNC clients don't support SOCKS proxies so can't use the dynamic port forwarding (the D in D8888). You can forward a local port to a specific machine+port instead but it will mean one such local port mapping per remote system you want to VNC to. (This is in the article you linked to - it shows such a mapping to the localhost at the other end of the SSH tunnel). You then VNC connect to the forward port on your local machine and SSH tunnels it for you to the specific remote address:port.
Forwarded Ports: L8889 x.x.x.x:5900  (x.x.x.x address of machine you want to VNC to)
Some VNC clients do support SOCKS proxies but it tends to the paid / pro version.


text:
Q: storing form data from landing page to csv file for later use in mail client I have been looking all afternoon, and no results I have found worked for me, maybe I am not integrating the code correctly. I have a script for a landing page for wifi, and the php for the auth page, forwarding to the net. I want to use php somewhere in the middle to store the form data from the landing page to a csv file on the server to use later in an email client. Each time a user enters a new set of details, the csv is updated with a new row.
The form:
    <?php
    session_start();
 $_SESSION['id'] = $_GET['id'];          //user's mac address
 $_SESSION['ap'] = $_GET['ap'];          //AP mac
 $_SESSION['ssid'] = $_GET['ssid'];      //ssid the user is on (POST
 2.3.2)
 $_SESSION['time'] = $_GET['t'];         //time the user attempted a
 request of the portal
 $_SESSION['refURL'] = $_GET['url'];     //url the user attempted to
 reach
 $_SESSION['loggingin'] = "unique key";  //key to use to check if the
 user used this form or not
                // -- prevents them from simply going to
 /authorized.php on their own

 ?>
 <!DOCTYPE html>

 <meta charset="utf-8">
 <title>Portal Page Example</title>

<form name="login" action="authorized.php" method="post">
<input id="Name" type="text" name="name" value="Name" />
<input id="Email" type="text" name="email" value="Email" />
<input id="submit" type="submit" name="submit" value="Connect" />
</form>

The auth page:
   <?php

session_start();

function sendAuthorization($id, $minutes)
{
$unifiServer = "https://unifi-IP:8443";
$unifiUser = "UniFi Username";
$unifiPass = "UniFi Password";

// Start Curl for login
$ch = curl_init();
// We are posting data
curl_setopt($ch, CURLOPT_POST, TRUE);
// Set up cookies
$cookie_file = "/tmp/unifi_cookie";
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
// Allow Self Signed Certs
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
// Force SSL3 only
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
// Login to the UniFi controller
curl_setopt($ch, CURLOPT_URL, "$unifiServer/login");
curl_setopt($ch, CURLOPT_POSTFIELDS,
    "login=login&username=$unifiUser&password=$unifiPass");
// send login command
curl_exec ($ch);

// Send user to authorize and the time allowed
$data = json_encode(array(
    'cmd'=>'authorize-guest',
    'mac'=>$id,
    'minutes'=>$minutes));

// Send the command to the API
curl_setopt($ch, CURLOPT_URL, $unifiServer.'/api/cmd/stamgr');
curl_setopt($ch, CURLOPT_POSTFIELDS, 'json='.$data);
curl_exec ($ch);

// Logout of the UniFi Controller
curl_setopt($ch, CURLOPT_URL, $unifiServer.'/logout');
curl_exec ($ch);
curl_close ($ch);
unset($ch);
}

if ($_SESSION['loggingin'] == "unique key") // Check to see if the form
has been posted to
{
ob_start();
    sendAuthorization($_SESSION['id'], (12*60)); //authorizing user for
12 hours
ob_end_clean();
unset($_SESSION['loggingin']);
}

?>

Connecting to the network...

This is nearly the exact solution: https://daveismyname.blog/form-to-csv-with-php but it downloads the csv instead of storing it with the web page, and I need it to append a row of data every time someone else fills out the form.
Thanks in advance

A: Sorted it, just for anyone else trying to do this, here is the answer. Put this code in at the top of your processing php file, and edit to your own needs:
    <?php
$Name = Trim(stripslashes($_POST['Name']));
$Email = Trim(stripslashes($_POST['Email']));

if (!empty($Name) || !empty($Email)) {
$csvData = $Name . "," . $Email;
$fp = fopen("formdata.csv","a");
if (fp)
{
fwrite($fp,$csvData."\n");
fclose($fp);
}

}


text:
Q: Join normalized table with active record There is a customer table with columns id, name and email as well as a address table with columns id, street, code, customer_id.
In SQL I join both by using:
SELECT c.id, c.name, c.email, a.street, a.code FROM customer AS c, address AS a WHERE a.customer_id = c.id;

In Rails I modelled:
class Address < ActiveRecord::Base
    self.table_name = 'address'
end
class Customer < ActiveRecord::Base
    self.table_name = 'customer'

    has_one :address
end

In the controller I tried:

*

*Customer.joins(:address) => SELECT customer.* FROM customer INNER JOIN address ON address.customer_id = customer.id

*Customer.includes(:address) => SELECT customer.* FROM customer; SELECT address.* FROM address  WHERE address.customer_id IN (1, 2)
However both do not return the expected result.
How do I get the same results as defined in the first SQL Query or what is the right way to do this?

A: It's not quite the way, but I understand where you're coming from, having learned Rails after doing a lot of DB work. Run console to test these ideas. First, the Address correctly "belongs_to" the Customer. The Customer "has_one" Address. these are defined in the Model. Think of the model as a database table. The foreign keys are defined by these relationships you've specified. The join is interpreted by the relationship.
So, in console, create an address.
> Address.create(:street => "123 Main")

The output will show the new address's ID. Create a customer record, and in the address_id column, put the id of the address.
Customer.create(:address_id=> [ new address id ] )

Query the customer:
> customer =  Customer.find([id number])

Then, type
> customer.address

It should show you the address. No joins necessary (but they are happening on the server).
And, you don't need to specify the table names in the model.


text:
Q: Vim mappings/command not working I am working with split windows in vim, but I am having trouble navigating and resizing split windows.
I have added these mappings to my .vimrc text file:
nmap <silent> <A-Up> :wincmd k<CR>
nmap <silent> <A-Down> :wincmd j<CR>
nmap <silent> <A-Left> :wincmd h<CR>
nmap <silent> <A-Right> :wincmd l<CR>

But still, when pressing <A-Left> it does not move window. Also I am using <C-w> +, but the windows do not resize! I also tried <C-w> <, but it resizes like 1 pixel at a time! Is there any faster way to resize split windows?

A: 10 Ctrl-W+ increases the window size by 10 lines. To resize all Windows to the same size, you can use CTRL-W = and to increase a window to its maximum size, use Ctrl-W _.
To resize in different steps, you can create maps that will adjust the window size differently. For example to increase the window size by a factor of 1.5 and decrease the window size by 0.67, you can map this:
 nnoremap <silent> <Leader>+ :exe "resize " . (winheight(0) * 3/2)<CR>
 nnoremap <silent> <Leader>- :exe "resize " . (winheight(0) * 2/3)<CR>

Alternatively you can use the :resize command to change the height of the window, to change the window width, use the :vertical modifier. So to resize by 10 lines, use:
:res +10
:res -10

as for navigation try
 nnoremap <C-h> <C-w>h
 nnoremap <C-j> <C-w>j
 nnoremap <C-k> <C-w>k
 nnoremap <C-l> <C-w>l

A: The <C-W> commands resize by individual lines / columns (pixels wouldn't even be possible in console Vim), but you are supposed to prepend a number before them to change larger amounts at once. (A lot of Vim commands take such a [count], as it's called in the help.)

For the <A-Up> mappings, do they work in graphical GVIM, but not in the console?! The mapping definitions look fine (but you should use :nnoremap).
Due to the way that the keyboard input is handled internally, some key combinations, like Ctrl + non-alphabetic cannot be mapped, and Ctrl + letter vs. Ctrl + Shift + letter cannot be distinguished. (Unless your terminal sends a distinct termcap code for it, which most don't.) In insert or command-line mode, try typing the key combination. If nothing happens / is inserted, you cannot use that key combination. This is a known pain point, and the subject of various discussions on vim_dev and the #vim IRC channel.
Some people (foremost Paul LeoNerd Evans) want to fix that (even for console Vim in terminals that support this), and have floated various proposals, cp. http://groups.google.com/group/vim_dev/browse_thread/thread/626e83fa4588b32a/bfbcb22f37a8a1f8
But as of today, no patches or volunteers have yet come forward, though many have expressed a desire to have this in a future Vim 8 major release.


text:
Q: Property name enclosed in double quotes How do I put this in double quotes? I've tried json.dumps(), json() and json.loads() and they don't work.
{'object': 'transaction', 'status': 'waiting_payment', 'refuse_reason': None, 'status_reason': 'acquirer', 'acquirer_response_code': None, 'acquirer_response_message': None, 'acquirer_name': 'development', 'acquirer_id': '560e8122ee1e15677388a1f0', 'authorization_code': None, 'soft_descriptor': None, 'tid': None, 'nsu': None, 'date_created': '2022-06-03T19:14:15.381Z', 'date_updated': '2022-06-03T19:14:15.597Z', 'amount': 4250, 'authorized_amount': 4250, 'paid_amount': 0, 'refunded_amount': 0, 'installments': 1, 'id': 17226066, 'cost': 0, 'card_holder_name': None, 'card_last_digits': None, 'card_first_digits': None, 'card_brand': None, 'card_pin_mode': None, 'card_magstripe_fallback': False, 'cvm_pin': False, 'postback_url': None, 'payment_method': 'boleto', 'capture_method': 'ecommerce', 'antifraud_score': None, 'boleto_url': 'https://pagar.me', 'boleto_barcode': '1234 5678', 'boleto_expiration_date': '2022-06-06T03:00:00.000Z', 'boleto': {'paid_interest_and_fine': 0}, 'referer': 'api_key', 'ip': 'xxxx', 'subscription_id': 885133, 'metadata': {'nome_projeto': 'xxx'}, 'antifraud_metadata': {}, 'reference_key': None, 'device': None, 'local_transaction_id': None, 'local_time': None, 'fraud_covered': False, 'fraud_reimbursed': None, 'order_id': None, 'risk_level': 'unknown', 'receipt_url': None, 'payment': None, 'addition': None, 'discount': None, 'private_label': None, 'pix_data': None, 'pix_qr_code': None, 'pix_expiration_date': None}

A: If your input is a string then first evaluate it:
p = "{'object': 'transaction', 'status': 'waiting_payment', 'refuse_reason': None, 'status_reason': 'acquirer', 'acquirer_response_code': None, 'acquirer_response_message': None, 'acquirer_name': 'development', 'acquirer_id': '560e8122ee1e15677388a1f0', 'authorization_code': None, 'soft_descriptor': None, 'tid': None, 'nsu': None, 'date_created': '2022-06-03T19:14:15.381Z', 'date_updated': '2022-06-03T19:14:15.597Z', 'amount': 4250, 'authorized_amount': 4250, 'paid_amount': 0, 'refunded_amount': 0, 'installments': 1, 'id': 17226066, 'cost': 0, 'card_holder_name': None, 'card_last_digits': None, 'card_first_digits': None, 'card_brand': None, 'card_pin_mode': None, 'card_magstripe_fallback': False, 'cvm_pin': False, 'postback_url': None, 'payment_method': 'boleto', 'capture_method': 'ecommerce', 'antifraud_score': None, 'boleto_url': 'https://pagar.me', 'boleto_barcode': '1234 5678', 'boleto_expiration_date': '2022-06-06T03:00:00.000Z', 'boleto': {'paid_interest_and_fine': 0}, 'referer': 'api_key', 'ip': 'xxxx', 'subscription_id': 885133, 'metadata': {'nome_projeto': 'xxx'}, 'antifraud_metadata': {}, 'reference_key': None, 'device': None, 'local_transaction_id': None, 'local_time': None, 'fraud_covered': False, 'fraud_reimbursed': None, 'order_id': None, 'risk_level': 'unknown', 'receipt_url': None, 'payment': None, 'addition': None, 'discount': None, 'private_label': None, 'pix_data': None, 'pix_qr_code': None, 'pix_expiration_date': None}"
import ast
d = ast.literal_eval(p)

Now you have a dict. If your input already was a dict literal (not a string), the above step is not needed.
Then continue with that dict to transform it into JSON:
import json
result = json.dumps(d)

result will now be a string that looks like this:
{"object": "transaction", "status": "waiting_payment", "refuse_reason": null, "status_reason": "acquirer", "acquirer_response_code": null, "acquirer_response_message": null, "acquirer_name": "development", "acquirer_id": "560e8122ee1e15677388a1f0", "authorization_code": null, "soft_descriptor": null, "tid": null, "nsu": null, "date_created": "2022-06-03T19:14:15.381Z", "date_updated": "2022-06-03T19:14:15.597Z", "amount": 4250, "authorized_amount": 4250, "paid_amount": 0, "refunded_amount": 0, "installments": 1, "id": 17226066, "cost": 0, "card_holder_name": null, "card_last_digits": null, "card_first_digits": null, "card_brand": null, "card_pin_mode": null, "card_magstripe_fallback": false, "cvm_pin": false, "postback_url": null, "payment_method": "boleto", "capture_method": "ecommerce", "antifraud_score": null, "boleto_url": "https://pagar.me", "boleto_barcode": "1234 5678", "boleto_expiration_date": "2022-06-06T03:00:00.000Z", "boleto": {"paid_interest_and_fine": 0}, "referer": "api_key", "ip": "xxxx", "subscription_id": 885133, "metadata": {"nome_projeto": "xxx"}, "antifraud_metadata": {}, "reference_key": null, "device": null, "local_transaction_id": null, "local_time": null, "fraud_covered": false, "fraud_reimbursed": null, "order_id": null, "risk_level": "unknown", "receipt_url": null, "payment": null, "addition": null, "discount": null, "private_label": null, "pix_data": null, "pix_qr_code": null, "pix_expiration_date": null}


text:
Q: is it possible to set default open folder for File Explorer of Windows 10 version 1903 opened from Taskbar? Windows 10: version 1903
I tried rename "Libraries folder" into "File Explorer" and replace the "%APPDATA%\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\File Explorer.lnk", but the Taskbar show two folder, one is the "File Explorer" that open my computer as default another is the "Libraries folder".
At windows 7, I can change the target from a .lnk property, but in windows 10, it seem we cannot edit the target field.
is it possible to set File Explorer's default open "Libraries folder" when opened from Taskbar? (in ideal, there is one file explorer pinned to the taskbar, you click it a "Libraries folder" opened, after all only one file explorer show in taskbar)

A: You can open Libraries directly by creating a shortcut that will call
explorer.exe shell:Libraries.
Many more shell: commands exist. They are all listed in the article
Shell Commands to Access the Special Folders in Windows 10/8/7/Vista/XP.

A: •  Search for Folder Options
•  In the top dropdown menu, select which location you need to open by default


text:
Q: Why iptables is not working as expected? I have put these four filters with iptables:
iptables -I FORWARD -p udp -i eth0 -j DROP
iptables -I FORWARD -p udp -o eth0 -j DROP
iptables -I INPUT -p udp -i eth0 -j DROP
iptables -I OUTPUT -p udp -o eth0 -j DROP

hoping to drop any udp packet on eth0, but when I do:
tcpdum udp -vv -i eth0

I still see UDP packages come and go.
Can anyone explain this? And tell me how to really drop UDP packages on a specific interface? (eth0 for example)

A: tcpdump captures the packets by tapping into the packet stream.  It gets all packets even those that will be dropped by the firewall rules.
If you want to verify the traffic is being blocked, you should check on the network for outgoing traffic.  You can test incoming traffic by setting up a listener and trying to send it traffic from the network.  If your rules work, you should get different results with or without the rules in place.  However, if you have a DROP policy, the results will be the same.
In iptables you could add logging or accept rules after the drop rules.  Checking the the packet counts for the rules will tell you if anything is getting by the drop rules.
Are you sure you want to drop all UDP traffic?  DNS tries UDP first and falls back to TCP only if necessary.


text:
Q: How to set default value for ASP.NET MVC DropDownList from model i am new in mvc. so i populate dropdown this way
public ActionResult New()
{
    var countryQuery = (from c in db.Customers
                        orderby c.Country ascending
                        select c.Country).Distinct();
    List<SelectListItem> countryList = new List<SelectListItem>();
    string defaultCountry = "USA";
    foreach(var item in countryQuery)
    {
        countryList.Add(new SelectListItem() {
                        Text = item,
                        Value = item,
                        Selected=(item == defaultCountry ? true : false) });
    }
    ViewBag.Country = countryList;
    ViewBag.Country = "UK";
    return View();
}

@Html.DropDownList("Country", ViewBag.Countries as List<SelectListItem>)

i like to know how can i populate dropdown from model and also set default value. any sample code will be great help. thanks

A: Well this is not a great way to do this.
Create a ViewModel that will hold everything you want to be rendered at the view.
public class MyViewModel{

  public List<SelectListItem> CountryList {get; set}
  public string Country {get; set}

  public MyViewModel(){
      CountryList = new List<SelectListItem>();
      Country = "USA"; //default values go here
}

Fill it with the data you need.
public ActionResult New()
{
    var countryQuery = (from c in db.Customers
                        orderby c.Country ascending
                        select c.Country).Distinct();
    MyViewModel myViewModel = new MyViewModel ();

    foreach(var item in countryQuery)
    {
        myViewModel.CountryList.Add(new SelectListItem() {
                        Text = item,
                        Value = item
                        });
    }
    myViewModel.Country = "UK";

    //Pass it to the view using the `ActionResult`
    return ActionResult( myViewModel);
}

At the view, declare that this view is expecting a Model with type MyViewModel using the following line at the top of the file
@model namespace.MyViewModel

And at anytime you may use the Model as you please
@Html.DropDownList("Country", Model.CountryList, Model.Country)

A: You can't set the default value using Html.DropDownList, if you want to have a default value, the property itself should have a default value.
private string country;
public string Country
{
    get { return country ?? "UK"; }
    set { country = value; }
}

Then, when the drop down list renders, as long as "UK" is actually a value for one of the options, it will be automatically set to that.

A: If the DropDownList is filled in the controller and sent to the view via ViewBag, you can do:
ViewBag.MyName = new SelectList(DbContextname.Tablename, "Field_ID", "Description",idtobepresented);


text:
Q: Does WebClient.DownloadDataTaskAsync do a post or a get I have seen WebClient.DownloadDataTaskAsync doing a GET, can I do a POST by using this method, for HTTP request?

A: You use the UploadString method to POST with the WebClient:
See http://msdn.microsoft.com/en-us/library/0645045y(v=vs.110).aspx for more information.

A: Method documentation says that "This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used."
link to MSDN

A: GET.
From MSDN

This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.

There is an UploadDataTaskAsync that lets you control the verb; else it defaults to POST:

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.


text:
Q: How to move axes to the middle of QCustomPlot By default QCPAxisRect has four axes which arrange in a rectangle. I want a plus type axis at the the center of QCustomPlot. How can I do that?

A: Here is a small hack to which can be used as a workaround:
http://www.qcustomplot.com/index.php/support/forum/86


text:
Q: Why is pointer/reference to array allowed to not specify the array size? This may be a bad question as I'm really new to the concept of statically-typed language and arrays in C++ and may have misunderstood these concepts...
I know that C++ is a statically-typed language, in my understanding, this implies that all types must be known at compile-time.
Also, I know that the number of elements in an array is part of the array's type, and thus the dimension must be known at compile time.
int a = 10;
int arr[a];    // error

However, I noticed that we could have:
int (*p)[];
void fun(int(&r)[]) {  }

Why can p and r not specify the size of the array?
My humble guess is that, for the above cases, the type of p is just int(*)[] and the type of r is just int(&)[], that is, for pointer/reference to array, it is allowed to have type which does not include the size of the array. (At first I was tending to think of p and r being in some kind of state where their types are to be "completed" later, but then I realized that if so, C++ would not be statically-typed)
My I ask if my guess is correct?
It seems really quirky to me, since we can do (in C++20):
int a[10];
int b[100];

p = &a;
p = &b;
fun(a);
fun(b);

Why would C++ allow such types (and conversion from the types with array size to them)? When are these "incomplete" type useful?

A: Everything you said is correct.
In addition to the regular array types T[N] there are "arrays of unknown bound" T[].
Those types are "incomplete", meaning objects of those types can't be created, sizeof() can't be applied to them, etc. Attempting to create an array of unknown bound requires you to provide an initializer, and transforms the type into a regular array, based on the number of elements in the initializer.
References and pointers to arrays of unknown bound are allowed to point to regular arrays (and that's the only thing they could point to). This is a C++20 change.
Those are indeed quirky. It's not immediately clear to me why they would be useful. They allow you to have a function that accepts a reference/pointer to any "array of T" without adding the array size as a template parameter, and without also accepting "pointers to T".

A: Yes these are legal types explicitly allowed by the C++ standard. Such types are useful in about the same circumstances where bare pointers that point to array elements are useful. In both cases, there is an array, but the type of the pointer/reference does not reflect the size of the array. Here are two silly examples:
// use a pointer to an array element
int sum(int* array, int size) {
    int ret = 0;
    for (int i = 0; i < size; ++i) {
        ret += array[i];
    }
    return ret;
}

// use a reference to an array
int sum(int (&array)[], int size) {
    int ret = 0;
    for (int i = 0; i < size; ++i) {
        ret += array[i];
    }
    return ret;
}


text:
Q: Can't insert data into Postgres database with PHP I am creating a simple php api to manage students. The DBMS used is Postgres. While creating the query to insert data into the psql dataabase, i get an error. I'm using Postman to send requests.
Instead of using SET i tried using VALUES but that still gave me an error saying that the column name and course exist, but i can't run it in that part of the query.
The line of code:
$query = 'INSERT INTO ' . $this->table . ' SET name = :name, course = :course';

The error i get:

Fatal error: Uncaught PDOException: SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "SET" LINE 1: INSERT INTO students SET name = $1, course = $2 ^

A: Insert  should use the syntax:
'INSERT INTO ' . $this->table . ' ( name, course)  VALUES ( :name,  :course);';


text:
Q: Avoid Duplication or Error When Updating Form in Laravel I have 2 tables beneficiaries and addresses joined with relation beneficiary_id as foreign key while each beneficiary record should have 1 address only.
The records are duplicated or fails to insert request() in the second table.
When I use the below code the records are duplicated
public function update(UpdateBeneficiaryRequest $request, Beneficiary $beneficiary, Address $address)
{
    abort_unless(\Gate::allows('beneficiary_edit'), 403);

    $beneficiary->update($request->all());

    // $address->update($request->all());

    $address->fill([
        'beneficiary_id'    => $beneficiary->id,
        'country'           => request('country'),
        'state'             => request('state'),
        'district'          => request('district'),
        'town'              => request('town'),
        'street'            => request('street'),
        'building'          => request('building'),
        'nearby'            => request('nearby')
    ]);

    //->where('id',$id);
    //$address->save();

    $beneficiary->addresses()->save($address);

    return redirect()->route('admin.beneficiaries.index');
}

However when I change the code to get all requests I get an error
public function update(UpdateBeneficiaryRequest $request, Beneficiary $beneficiary, Address $address)
{
    abort_unless(\Gate::allows('beneficiary_edit'), 403);

    $beneficiary->update($request->all());

    $address->update($request->all());

    //->where('id',$id);
    //$address->save();

    $beneficiary->addresses()->save($address);

    return redirect()->route('admin.beneficiaries.index');
}

Error Message:

SQLSTATE[HY000]: General error: 1364 Field 'country' doesn't have a
  default value (SQL: insert into addresses (beneficiary_id,
  updated_at, created_at) values (1, 2019-12-02 02:07:27, 2019-12-02
  02:07:27))

In the second option the request aren't sent according to table structure
beneficiaries table structure

addresses table structure

How to avoid records duplication while updating form and get all request to be inserted in the right tables.
I've also used update() and updateOrCreate() functions however both ended in the same result
Please note I'm currently using 2 tables while the target to use 5 tables for 1 form.
EDIT: Fields are mandatory can't be NULL
Added the UpdateBeneficiaryRequest class
namespace App\Http\Requests;

use App\Beneficiary;
use Illuminate\Foundation\Http\FormRequest;

class UpdateBeneficiaryRequest extends FormRequest
{
    public function authorize()
    {
        return \Gate::allows('beneficiary_edit');
    }

    public function rules()
    {
        return [
            'name'      => [ 'required',],
            'lname'     => [ 'required',],
            'father'    => [ 'required',],
            'mother'    => [ 'required',],
            'dob'       => [ 'required',],
            'phone'     => [ 'required',],
            'record_no' => [ 'required',],
            'country'   => [ 'required',],
            'state'     => [ 'required',],
            'district'  => [ 'required',],
            'town'      => [ 'required',],
            'street'    => [ 'required',],
            'building'  => [ 'required',],
            'nearby'    => [ 'required',],

        ];
    }
}

A: Your country column is set to not null.
insert into addresses (beneficiary_id, updated_at, created_at) values (1, 2019-12-02 02:07:27, 2019-12-02 02:07:27)
the above query is failing because of that. It will fail with updateOrCreate() as it will try to add in case it does not exist.
You have to make all the column null if they are not mandatory.

A: You have to validate your form before saving the data to the database. And it looks like you are using a custom validation class called UpdateBeneficiaryRequest. In these class you have to set a validation on the field that you want to be unique on the data base. See example below. We want to make sure that the beneficiary_id is unique inside the  address table.
public function rules()
{
  return [
      'beneficiary_id' => 'required|unique:address,beneficiary_id,'.$this->address->id,
  ];
}

A: After Struggling I had to go to the main process...
public function update(UpdateBeneficiaryRequest $request, Beneficiary $beneficiary, Address $address)
{
    abort_unless(\Gate::allows('beneficiary_edit'), 403);

    $beneficiary->update($request->all());

    $address = Address::find($beneficiary->id);
    $address = Address::where('beneficiary_id', '=', $beneficiary->id)->first();
    $address->country   = $request->country;
    $address->state     = $request->state;
    $address->district  = $request->district;
    $address->town      = $request->town;
    $address->street    = $request->street;
    $address->building  = $request->building;
    $address->nearby    = $request->nearby;
    $address->save();

    return redirect()->route('admin.beneficiaries.index');
}

Now it's working

A: The Simple solution for this simple problem..
your migration file.
public function up(){
  Schema::create('users', function (Blueprint $table) {
       $table->string('address')->unique();
}

by adding unique(), it will allow only unique values in the table, try to re-migrate your table with this function.


text:
Q: WPF: Inner content wont scroll I have a Window with a Grid inside:
<Grid KeyboardNavigation.TabNavigation="Local">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" MinHeight="70" />
        <RowDefinition Height="*" />
        <RowDefinition Height="25" />
    </Grid.RowDefinitions>

    <ContentControl Grid.Row="0" Content="{Binding ChildViewModel.View}" />

    <DockPanel Grid.Row="1" Visibility="{Binding SearchResultViewVisibility}">
        <GridSplitter DockPanel.Dock="Top" Background="LightGray" Height="5" HorizontalAlignment="Stretch" VerticalAlignment="Top" IsTabStop="False"/>
        <Views:SearchResultView DataContext="{Binding SearchResultViewModel}" />
    </DockPanel>

    <UserControls:GradientBackgroundControl Grid.Row="2" Height="25">
        <Validators:FocusSummaryControl x:Name="FocusSummary" ValidateOnlyFocusedElement="False" />
    </UserControls:GradientBackgroundControl>
</Grid>

The ContentControl gets a UserControl with this Grid set:
<Grid KeyboardNavigation.TabNavigation="Local">
<Grid.RowDefinitions>
    <RowDefinition />
    <RowDefinition Height="35" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="80" />
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="80" />
    <ColumnDefinition Width="80" />
</Grid.ColumnDefinitions>

<ScrollViewer Grid.Row="0" Grid.ColumnSpan="4">
    <StackPanel>
        ...
    </StackPanel>
</ScrollViewer>

The problem now is, that the ScrollViewer in the UserControl doesn't scroll. The content of the UserControl set to the ContentControl is heigher and the overflow ist just hidden.

A: If I am not wrong, StackPanel requires a Height to be set for scroll functionality to work because StackPanel, by design, grows in one direction (based on Orientation).
To confirm whether this is the cause of your problem, please test by setting the height of StackPanel to a fixed height. Alternately, you may want to replace the StackPanel with say DockPanel and see the behaviour. Also there is a ScrollViewer.CanContentScroll property that you may want to fiddle with.
Let us know the result of this test.

A: I think you need to rearrange things a little bit.  My suggestions (I'm sure there are infinite variations that would work):
First, add a new row to your grid (Height="Auto") and set the height of your top row (with your ContentControl in it) to "*"
<Grid.RowDefinitions>
  <RowDefinition Height="*" MinHeight="70" />
  <RowDefinition Height="Auto" />
  <RowDefinition Height="*" />
  <RowDefinition Height="25" />
</Grid.RowDefinitions>

Second, move your GridSplitter out of the DockPanel.  Put the splitter in row 1 and the dockpanel in row 2.
<ContentControl Grid.Row="0" Content="{Binding ChildViewModel.View}" />

<GridSplitter Grid.Row="1" Background="LightGray" Height="5" HorizontalAlignment="Stretch" VerticalAlignment="Top" IsTabStop="False" ResizeBehavior="PreviousAndNext"/>

<DockPanel Grid.Row="2" Visibility="{Binding SearchResultViewVisibility}">
    <Views:SearchResultView DataContext="{Binding SearchResultViewModel}" />
</DockPanel>

Note that you'll probably also have to set the ResizeBehavior for your GridSplitter as shown above.  I hope this will get you close to what you want.


text:
Q: iOS: How do paint/draw apps eliminate the initial delay in response to touches? When I've used painting/drawing apps, I never notice a delay between pressing my finger and being able to see something drawn on the display. However with my app, the initial touches are received very slowly. The second and third and fourth gestures are received a 60 per second, but the first gesture is maybe 2-3 touch events per second. Furthermore if I let the app sit idle for a 10 seconds, the same delay happens again. It's as though iOS forgets that the app needs attention, or the device (iPad 3, iOS 5.1.1) goes into a kind of sleep where the display is on but touch response slows.
UPDATE: If I put the iPad 3 to sleep/lock by closing the display and leave it for 10 seconds, then open the display, the initial sluggish touches response happens every time.
UPDATE: This problem is not occurring on my iPad 1 running iOS 5.1.1. Even when I bring the iPad 1 back from sleep/unlock, there is no delay.

A: I haven't really worked with this kind of thing before, but I recall reading somewhere about using a UIBezierPath to create a drawing app. You could try to use that. According to this question, it's faster:
Why is UIBezierPath faster than Core Graphics path?
A tutorial is here: http://soulwithmobiletechnology.blogspot.com/2011/05/uibezierpath-tutorial-for-iphone-sdk-40.html


text:
Q: How to send FCM message with only data payload via PyFCM? I'm trying to send data-only FCM message to topic subscribers. But it not works nether when app in background or closed.
My android app have following code:
FirebaseMessaging.getInstance().subscribeToTopic("topicname");

My FCM-sender code
from pyfcm import FCMNotification

API_KEY = "AAAA....akZKg"

push_service = FCMNotification(api_key=API_KEY)

data = {
        "title":"mytitle",
        "body":"mybody",
        "url":"myurl"
        }

print(push_service.notify_topic_subscribers(topic_name="topicname", data_message=data))

outputs
{'canonical_ids': 0, 'results': [], 'failure': 0, 'success': 1, 'multicast_id': None}

But notification not appear. Need to show message to all topic subscribers that are not have running-right-now-app (have background or closed state)

A: Hi Please upgrade to the latest version of pyfcm.After going through the source code i find that pyfcm always added a 'notification' dict in payload,but now they introduce a option "remove_notification" option in its source code which prevent the addition to payload. So as pyfcm does not provide any method for data only "notify_topic_subscribers" we have to override the fcm.py or fork the project and change. In fcm.py method  add "remove_notification" to "notify_topic_subscribers" method and make it true in "parse_payload" call  in that function.Thats it.