Q: navigate ListViewItem through arrow Up and Down Keys in C# I made a simple application where i have some TextBoxes and One ListItemView. When i enter a data into Textbox it shows result in ListItemView from database. And when i press Arrow keys Down it focus on ListItemView and then i Navigate ListItemView Through arrow key Up and Down. And when i pressed Enter in selected item of ItemListView it shows content from ItemListView to TextBox. That's All my Purpose But the problem is how can i do it?

A: I use this code
if(e.KeyCode==Keys.F1){
 this.ActiveControl=listView1;}


Q: What is difference between PORTABLE and Machine Independent? This might be silly question but I am confused between portable and machine independent.
What is Java, c#.net : portable or machine independent?

A: Machine Independence
Machine independence refers to the idea of software that can be executed irrespective of the machine on which it executes. A piece of Machine dependent software might be something written to use, say assembly instructions that are specific to a certain architecture. For example, if you write a C++ application with inline assembly that relies on special processor instructions such as for example, SIMD instructions, then that peice of software is machine dependent because it has specific machine requirements - it can only work on a machine that supports that specific required SIMD instruction set.
In contrast, C# and Java compile to bytecode that is executed by a virtual machine which takes that bytecode and executes it as native code directly on the processor. In this case the virtual machine is machine dependent because it will execute against the specific hardware it is written for - for example, only a 32 bit Intel processor, or an ARM Smartphone. The Java and C# applications that run on the virtual machine however are machine independent because they care not what the underlying platform is, as long as there is a virtual machine to translate to the underlying paltform for them. That abstraction layer, the virtual machine, helps separate the application from the underlying hardware and that is the reason why those applications can be machine independent.
Portability
Portability is a separate but related concept, it is a broad term that covers a number of possibilities. A piece of software is portable simply if it can be built and executed or simply executed on more than one platform. This means that machine independent software is inherently portable as it has to be by nature.
There are broadly two facets to portability - hardware portability, and software portability. Ignoring for the moment .NET implementations such as Mono and focussing purely on Microsoft's .NET implementation it is fair to say that .NET is hardware portable because it can be executed on any hardware that supports the .NET runtime, however because Microsoft's implementation is only available on Windows and Windows descended operating systems it is fair to say that it is not particularly software portable - without Mono it cannot be executed on Mac OS X or Linux. In contrast, Java could be said to be both hardware portable and software portable because it can run on multiple operating systems like Windows, OS X, Linux hence it is software portable, and hardware portable because it can run on different hardware architectures such as ARM, x86 and x64.
Finally, there is also the question of language portability. Many would argue that although a C++ application compiled for Windows will not natively execute on Linux, it is possible to write C++ code in such a way that the same set of source code can be compiled on both Linux and Windows with no changes - this means that you can port the same application to different operating systems simply by just compiling it as is. In this respect we can say that whilst a compiled C++ application is not portable, the source code for a C++ application can be portable. This applies to a number of other languages including C.
Disclaimer
This is a somewhat simplified explanation and there are many edge cases that break these rules which make it such a complex and subjective subject - for example it is possible to write a Java application that is machine dependent if for example you use the Java native interfaces.

A: Portable means that you can run this programm without any installation.
Machine independent means that the same code can be executed on different OS.
This question could be helpfull, too.

A: From Wikipedia:

Software is portable when the cost of porting it to a new platform is
  less than the cost of writing it from scratch. The lower the cost of
  porting software, relative to its implementation cost, the more
  portable it is said to be.

Machine-independent software, on the other hand, does not need any work to be ran on another machine (ex. from Windows to Mac OS). It is by this definition also highly portable.

A:
What is difference between PORTABLE and Machine Independent?

There is no real answer to this.  It depends on whose definitions of "portable" and "machine independent" you chose to accept.  (I could pick a pair of definitions that I agree with and compare those.  But I don't think that's objective.)

What is Java, c#.net : portable or machine independent?

You could argue that Java and C# are neither portable or machine independent.

*

*A Java or C# program only runs on a platform with a JVM or CLR implementation, and a "compliant" implementation of the respective standard libraries.  Ergo, the languages are not machine independent (in the literal sense).

*There are many examples of Java (and I'm sure C#) programs that behave differently on different implementations of Java / C#.  Sometimes it is due to differences in runtime libraries and/or the host operating system.  Sometimes it is due to invalid assumptions on the part of the programmer.  But the point is that Java / C# software often requires porting work.  Ergo, they are not portable (in the literal sense.)


Q: AWS S3 Folder deleted History Is there ways to get deleted history of AWS s3 bucket?
Problem Statement :
Some of s3 folders got deleted . Is there way to figure out when it got deleted

A: There are at least two ways to accomplish what you want to do, but both are disabled by default.
The first one is to enable server access logging on your bucket(s), and the second one is to use AWS CloudTrail.
You might be out of luck if this already happened and you had no auditing set up, though.


Q: Matlab ocv.dll error The Specified Module Could Not Be Loaded I am trying to use face detector of Matlab Vision Toolbox Example
I am getting this error when I run the script:

MATLAB:dispatcher:loadLibrary Can't load 'C:\Program
  Files\MATLAB\R2015a\bin\win64\ocv.dll': The specified module could not
  be found. Caught MathWorks::System::FatalException

My system is Win-64 and I don't have OpenCv installed on my system.What is the reason of getting this error ?
UPDATE: ocv.dll is existing in the specified location

A: The OpenCV DLL comes with the Computer Vision System Toolbox for MATLAB. It sounds like the Computer Vision System Toolbox is not correctly installed on your computer.


Q: Insert to file from Hard Disk I'm trying to make a small app (dictionary) that translates from English to Arabic and vice versa.
I have 2 files in the debug folder English.txt and Arabic.txt.
I am trying in my form to make it possible for the user to insert new words to the files but I don't know if StreamWriters are working while StreamReaders are.
I think that my Seek statements don't work the right way either.
Here is my code that I tried:
    FileStream englishFile = new FileStream("English.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
    StreamReader engSR = new StreamReader(englishFile);
    StreamWriter engSW = new StreamWriter(englishFile);
    FileStream arabicFile = new FileStream("Arabic.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
    StreamWriter arabSW = new StreamWriter(arabicFile);
    StreamReader arabSR = new StreamReader(arabicFile);

    string line = engSR.ReadLine();
    string[] arr = line.Split('|');
    int numberOfLines = int.Parse(arr[1]) + 1;

    englishFile.Seek(0, SeekOrigin.Begin);
    engSW.WriteLine("*|{0}", numberOfLines);
    arabSW.WriteLine("*|{0}", numberOfLines);

    englishFile.Seek(0, SeekOrigin.End);
    line = engSR.ReadLine();
    engSW.WriteLine("{0}|{1}", numberOfLines, englishin.Text);

    arabicFile.Seek(0, SeekOrigin.End);
    line = arabSR.ReadLine();
    arabSW.WriteLine("{0}|{1}", numberOfLines, arabicin.Text);

    arabicFile.Close();
    englishFile.Close();

Where englishin and arabicin are the two text-boxes.
Sadly there is no change that occurs in the file.
I have also tried :
string line = engSR.ReadLine();
        string[] arr = line.Split('|');
        int numberOfLines = int.Parse(arr[1]) + 1;

        englishFile.Seek(0, SeekOrigin.Begin);
        engSW.WriteLine("*|{0}", numberOfLines);
        arabSW.WriteLine("*|{0}", numberOfLines);

        //englishFile.Seek(0, SeekOrigin.End);

        line = engSR.ReadLine();
        while (line != null)
            line = engSR.ReadLine();
        engSW.WriteLine("{0}|{1}", numberOfLines, englishin.Text);

        //arabicFile.Seek(0, SeekOrigin.End);

        line = arabSR.ReadLine();
        while (line != null)
            line = arabSR.ReadLine();
        arabSW.WriteLine("{0}|{1}", numberOfLines, arabicin.Text);

I don't really know what's the problem with the writer.

A: you need to close your StreamReader and StreamWriter, in onder to save your written text, you need to close StreamWriter
Extra
https://msdn.microsoft.com/en-us/library/system.io.streamwriter%28v=vs.110%29.aspx
System.IO is IDisposable, you should dispose it after read and write.
 private static void Main()
    {
        FileStream englishFile = new FileStream("English.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
        StreamReader engSR = new StreamReader(englishFile);
        StreamWriter engSW = new StreamWriter(englishFile);
        FileStream arabicFile = new FileStream("Arabic.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
        StreamWriter arabSW = new StreamWriter(arabicFile);
        StreamReader arabSR = new StreamReader(arabicFile);

        char delimiter = '|';
        try
        {
            englishFile.Seek(0, SeekOrigin.Begin);

            while(!engSR.EndOfStream){
                string line = engSR.ReadLine();
                string[] arr = line.Split(delimiter);

                for (int j = 0; j < arr.Count();j++ )
                {
                    if (j > 0)
                    {
                         arabSW.Write(delimiter);
                    }
                    String outStr = ConvertStr(arr[j]);
                    arabSW.Write(outStr);
                }

                arabSW.Write(arabSW.NewLine);
            }
        }
        catch
        {

        }
        finally
        {
            arabSW.Close();
            //arabSR.Close();
            engSR.Close();
            //engSW.Close();
            arabicFile.Close();
            englishFile.Close();
        }
    }

i tried this, it work well

A: The problem is that i have to make flush whenever i finished writing so after seeking to the begin and writing i should flush and at the end of the method i should close the StreamWriter as they said.
            string line = engSR.ReadLine();
            string[] arr = line.Split('|');
            int numberOfLines = int.Parse(arr[1]) + 1;

            englishFile.Seek(0, SeekOrigin.Begin);
            engSW.WriteLine("*|{0}", numberOfLines);
            arabicFile.Seek(0, SeekOrigin.Begin);
            arabSW.WriteLine("*|{0}", numberOfLines);
            engSW.Flush();
            arabSW.Flush();

            englishFile.Seek(0, SeekOrigin.End);
            line = engSR.ReadLine();
            engSW.WriteLine("{0}|{1}", numberOfLines, englishin.Text);

            arabicFile.Seek(0, SeekOrigin.End);
            line = arabSR.ReadLine();
            arabSW.WriteLine("{0}|{1}", numberOfLines, arabicin.Text);
        }
        catch
        {

        }
        finally
        {
            engSW.Close();
            arabSW.Close();
            arabSR.Close();
            engSR.Close();
            arabicFile.Close();
            englishFile.Close();
        }


Q: Не импортируется jsonb файл в mongo
При импортировании файла, выдает вот такую вот ошибку, как ее исправить, пофиксить?
Может подсказку, в какую сторону копать. Названия и пути(как видно на скрине, указываю относительный) правильные.


Q: How can i align my components vertically and 3 in a row? On my react project i want align my components to vertical. But when i use div and make it flex , my component width is changing and looking bad. what should i do ? I using tailwindcss but if you dont know it you can tell normal css too. I can use normal css too. My component :

            <FontAwesomeIcon icon={faEtsy} className="text-2xl  text-red-600" />

              {prop.PharmacyName}

            {prop.PharmacyNumber}

        <Divider />

            {prop.PharmacyAdress}

How i calling my component :
data.map((x, index) => {
            return (

                <PharmacyCard className="relative" key={index} props={x} />

 )})

How its looks like : https://prnt.sc/1covi9m
How i want : https://prnt.sc/1cow1sq
I using that component like 30-40 times with mapping. So i want to see like 3 component in a row. Thanks for all replies!

A: You just need to put the .flex in upper level like the below:

{data.map((x, index)=>{<PharmacyCard className="relative" key={index} props={x} />})}

hope this link will assist you to get the flexbox better
https://codepen.io/enxaneta/full/adLPwv

A:
So i want to see like 3 component in a row.

Since you have clear idea about the layout, I suggest to wrap you components in another div with grid and three columns; something like this:

    {data.map((x, index)=>{<PharmacyCard className="relative" key={index} props={x} />})}

Depending on your design, you may add gap class as well.
Also consider removing w-3/12 class from components so they fill grid's width.


Q: validating a user's value length (javascript) I am practicing my javascript beginners knowledge on a simple form. I want the user to enter a 10 digits phone number (in case it's less than 10 or more than 10 I have created the invalid style class so the user will only be allowed to enter 10 digits for his phone number). Also, once they entered the phone number of 10 digits, the user should be able to click "+" and get a second box for a second phone number (the second box will appear when you click + only if the user entered 10 digits for his first phone number).
I used an if() for validating the phone number, but it doesn't seem to work. Below is my code, any ideas maybe?
<!DOCTYPE html>

    <title>Numere de telefon</title>

    <form>
    <fieldset>
        <legend>Cont nou</legend>
        <input type="text" placeholder="nume">
        <input type="text" placeholder="prenume">
        <input type="text" placeholder="nr telefon" name="numarTelefon" oninput="" onchange="minL(this,event,10);">
        <input type="button" value="+" onclick="addInput(this,event);">

        <input type="button" value="Submit">
    </fieldset>
    </form>

Thanks in advance,
Ioana

A: There are two main issues.

*

*The call to minL in the addInput function doesn't have the right number of parameters.

*minL doesn't return a boolean value when addInput expects it to.
function minL(elem,event,nr){
    var v = elem.value;
    if(v.length < nr ){
        elem.classList.add("invalid");
    } else if (v.length > nr) {
        elem.classList.add("invalid");
    } else {
        elem.classList.remove("invalid");
        return true;
    }
}

 function addInput(elem,event){
    event.preventDefault();
    var container = document.querySelector("#containerNrTel");
    if(minL(document.querySelector("[name=numarTelefon]"), event, 10)){
        container.innerHTML += '<input type="text" placeholder="nr telefon" />';
    }

}


Q: HTML options not showing I am adding some options through JavaScript to my HTML page but the options don't seem to be appearing. I do see them when I inspect them with F12 but they are not showing.
Important Note: Using bootstrap!
 <select class="browser-default" id='userSelect' name="userSelect">
     <option default>-</option>
 </select>

JavaScript:
var sel = document.getElementById("userSelect");
for (var key in result) {
    if (result.hasOwnProperty(key)) {
        var opt = document.createElement('option');
        opt.innerHTML = result[key].contactName;
        opt.value = result[key].id;
        sel.appendChild(opt);
    }
}

I did check if result has any value so that is not the problem (otherwise the options wouldn't appear). I think bootstrap is the problem here, because I read some things about it that it can be a problem in this case. Does anyone know how to solve this?
HTML Chrome Inspector:

A: It looks like you use bootstrap-select plugin.
After every DOM manipulation to select you need to use refresh method of selectpicker.
for (var key in result) {
    if (result.hasOwnProperty(key)) {
        var opt = document.createElement('option');
        opt.innerHTML = result[key].contactName;
        opt.value = result[key].id;
        sel.appendChild(opt);
    }
}
$('#userSelect').selectpicker('refresh');


Q: Counting ordered pairs $(X,Y)$ Consider two disjoint sets $A$ and $B$ with $|A|=|B|=8$. Find two ways to count the number of ordered pairs $(X,Y)$ with $X \subseteq A$ and $Y \subseteq (B \cup X)$ with $|Y|=8$.
Is my guess correct?

*

*We have $|B \cup X| = |B| + |X| - |B \cap X| = 8+|X|$ (since $A$ and $B$ are disjoint, $X \subseteq A$).
We know that $1 \le^* |X| \le |A| = 8$ and $|Y| = 8 \le 8 + |X|$.

(*We'll leave out $|X| = 0$, since it does not contribute to the number of ordered pairs $(X,Y)$).

*

*This results in $ 16 \ge |B \cup X| \ge 9 $. So for all possible elements for $Y$ we do the following: $\sum_{i=9}^{16} \binom{i}{8}$. There are from $1$ through $8$ possible elements for $X$ (chosen from $A$): $\sum_{k=1}^8 \binom{8}{k}$.

*The number of ordered pairs is $\sum_{k=1}^8 \binom{8}{k} \cdot  \sum_{i=9}^{16} \binom{i}{8}$.
I'm struggling to find another way.

A: Formula: #(A×B) = #A × #B
For each a in A there are #B ways to make a into an ordered pair.
Thus add #B, #A times.
The other way.
For each b in B, there are #A ways to make b ...


Q: How to make global variables in android? After google i found three ways:
1. static variables
2. extending Application and using getApplicationContext
3. SharedPreferences

A: EDIT: read comments pls, i don't want to delete it, because it may help other who fell into the same trap...
Be careful with static variables!! I wrote an app which uses them, but on some devices it works, on some it doesn't. the problem is, if one activity edits that variable, finishes and the focus returns to another activity, the changes are not recognized. i haven't found a solution for this and somehow  i don't get it working with getApplicationContext either...
Usually i would say that i made a mistake, but in both cases, it is working on an SGSII with Android 4.0.4 but it isn't on SGSIII with 4.1... :(
So as a consequence i assume that they've changed the use of global variables, maybe out of security reasons, so that every activity gets an own instance of that variable or so, i have no idea


Q: Issue running java program from batch file, runs fine in IDE I'm doing some basic java homework for a class on my new laptop - issue is, I can't seem to get the program to compile and run from my batch file using the directions the instructor gave me.
I've set the Path variable to my JDK inside the Environment Variables settings.
My program is a simple shipping program to keep track of shipment information - I have the program working flawlessly in NetBeans (which our instructor advised us to use for developing the code), but he's going to be testing them using batch files, so we're also advised to test them on our systems with one we create prior to turning them in - pretty straightforward.
Issue is, I cannot seem to get this to work. I've never done it before, but I've used .bat files to compile and run C++ programs, as well as using makefiles on a unix system, so I feel like I'm absolutely stupid for not figuring this out on my own, but none of my searches have returned any fruitful solutions that help at all.
My program consists of 3 .java files:
Shipment.java - an interface that contains abstracted methods that are implemented in the ShipmentHW1 class
ShipmentHW1.java - a class that implements the abstracted methods from Shipment and has constructors, etc to  create a usable object
TestShipment.java - the main class of this program, which utilizes and creates ShipmentHW1 objects based on preset parameters. This is super duper basic stuff here, and again, it runs perfectly fine inside the NetBeans IDE.
The instructions given to us state to have the batch file inside the package directory (which in this case I've set aside a seperate folder on my desktop titled "shipping", which is the package name - shouldn't be any issues there), where the 3 .java files are located as well.
They say if you don't need to explicitly list the path to the JDK, then you can simply have
    javac TestShipment.java
java TestShipment.java
pause

Afterwards I get errors talking about how it "cannot find symbol Shipment s = new ShipmentHW1();"
I've tried adding imports, but since they're in the same package it shouldn't even be an issue.
Directory path is
C:\Users\X\Desktop\shipping

All 7 files are contained within:
TestShipment.java
TestShipment.class
Shipment.java
Shipment.class
ShipmentHW1.java
ShipmentHW1.class
doHW1.bat

Does anyone have any idea? I can provide more information if I've been too vague
Also, I'm on Windows 8 if that makes any difference

A: Solved
Batch file now reads
javac TestShipment.java Shipment.java ShipmentHW1.java
cd ..
java shipment.TestShipment
pause

and it works like a charm. Anyone have any ideas why I had to call the package.class instead of just compiling it regularly?

A: Try doing
javac TestShipment.java
java TestShipment
pause

A: Without seeing the contents of TestShipment.java, I'll assume you have some dependency on the Shipment and ShipmentHW1 classes. As such, when you execute a program that uses the TestShipment class, you need to have the .class files for each of the three (and any other dependencies).
So you will have to compile Shipment.java and ShipmentHW1.java as well before running your java command. If they are in the same package, you're good, if not, you will have to specify an appropriate value for the -cp option.
When running java with a class name, you need to specify the fully qualified class name.

A: If your .java files are declared to be in the 'shipping' package, then you probably need to be running java from the parent directory of 'shipping', e.g.
cd <path>/shipping
javac TestShipment.java
cd ..
java shipping/TestShipment


Q: How to make a webpage display dynamic data in real time using Python? I am working on making a GUI front end for a Python program using HTML and CSS (sort of similar to how a router is configured using a web browser). The program assigns values given by the user to variables and performs calculations with those variables, outputting the results. I have a few snags to work out:

*

*How do I design the application so that the data is constantly updated, in real-time? I.e. the user does not need to hit a "calculate" button nor refresh the page to get the results. If the user changes the value in a field, all other are fields simultaneously updated, et cetera.

*How can a value for a variable be fetched from an arbitrary location on the internet, and also constantly updated if/when it is updated at the source? A few of the variables in the program are based on current market conditions (e.g. the current price of gold). I would like to make those values be automatically entered after retrieving them from certain sources that, let us assume, do not have APIs.

*How do I build the application to display via HTML and CSS? Considering Python cannot be implemented like PHP, I am seeking a way to "bridge the gap" between HTML and Python, without such a "heavy" framework like Django, so that I can run Python code on the server-side for the webpage.
I have been looking into this for a quite some time now, and have found a wide range of what seem to be solutions, or that are nearly solutions but not quite. I am having trouble picking what I need specifically for my application. These are my best findings:
Werkzeug - I believe Werkzeug is the best lead I have found for putting the application together with HTML and Python. I would just like to be reassured that I am understanding what it is correctly and that is, in fact, a solution for what I am trying to do.
WebSockets - For displaying the live data from an arbitrary website, I believe I could use this protocol. But I am not sure how I would implement this in practice. I.e. I do not understand how to target the value, and then continuously send it to my application. I believe this to be called scraping?

A: Question 1.
 For that you would need javascript, javascript is used for adding behaviour to websites. I would recommend using a javascript framework called Jquery for that.
You would do this by adding an html "id" or "class" to the  inputs that have the value you want to recieve from the users and an "id" to the field where you would display the results of those calculations.
You would create an javascript event that basically tracks whenever any html object that has the class you used for the inputs above was changed, when that happens you do your calculations, and post the results on the result field you decided, using it's "id" identifier.
Take a look at this link for more info
Question 2.
 For that you would have to do what is called "Web scraping": First you read the html source code of the page you want to get the information from and look at the ID of the HTML object you want to get the information from (If it doesn't have an ID, you would then have to look at the Hierarchy of it (What is also known as the Document Object Model DOM), looking at with Objects it's inside of) then you create a script that reads the HTML and looks for that ID or follows the Hierarchy you discovered and reads the text in that HTML object. Remember that HTML is just text.
I'm more used to the Ruby programming language, in ruby there is a module you download for that, but I'm sure that there is one called "Mechanize" for Python.
Question 3. You could use Flask which is a light and simple micro-framework for python Python, from the needs you describe, it sounds like perfect fit.

A: To achieve your goal, you need good knowledge of javascript, the language for dynamic web pages. You should be familiar with dynamic web techniques, AJAX, DOM, JSON. So the main part is on the browser side. Practically any python web server fits. To "bridge the gap" the keyword is templates. There are quite a few for python, so you can choose, which one suites you best. Some frameworks like django bring their own templating engine.
And for your second question: when a web site doesn't offer an API, perhaps the owner of the site does not want, that his data is abused by others.


Q: Missing Mail.app in Finder, but exists in /Applications folder I've not ever wanted to use the Mail app on my Mavericks machine, but recently I decided I'd give it a shot. However when I went to Applications in Finder, I couldn't see it. Nor was it in ~/Applications (which is completely empty anyway).

When I did a search from Terminal (find . -iname Mail.app), I discover that it is in the /Applications folder after all.
I checked the permissions, but have never seen the "@" before:
drwxr-xr-x@  3 XXXX   admin    102 21 Feb  2014 MacX Free AVI Video Converter.app/
drwxr-xr-x@  3 root   wheel    102 16 Jul  2014 Mail.app/
drwxr-xr-x   3 root   wheel    102 16 Jul  2014 Maps.app/

The only way I could seem to open it was via Terminal (open /Applications/Mail.app).
Does anyone have any idea on why it might not be visible in Finder?
Note: The app itself is running fine after opening from Terminal...
& I've since marked it as "Keep in Dock".
Many thanks,
Craig.

A: Thanks to the hint from @Zero, there is a way to Hide and Show individual files, including applications from Finder by using Terminal.
To Show individual files:
sudo chflags nohidden Mail.app/

To Hide individual files:
sudo chflags hidden Mail.app/

Depending upon the file, you may not need to use sudo, but it won't hurt in any case (other than needing to type in a password).
Disclaimer: I found the key to my answer mentioned in a comment here: https://apple.stackexchange.com/a/65175/84492


Q: mysqli_real_escape_string - No se que graba en la bbdd Como buena estudiante, tengo una duda con respecto a la función
    mysqli_real_escape_string
Mi código:
$connn=mysqli_connect("localhost","root","", "test");
1// Obtenemos los datos del formulario, asegurándonos que son válidos.
        $usuario=mysqli_real_escape_string($connn, $_POST['usuario']);
        //$usuario=mysqli_real_escape_string($db, $usuario);
        echo "usuario: $usuario </br>";

Bien no está completo pero es que es largo. Mi pregunta son dos.

*

*He tenido que generar de nuevo una variable "$connn" para poder poner el parmetro "$link". No se por que cuando me archivo ya tiene un include con "conexion.php". Donde se declara pero no la pilla.

*¿Qué dato graba en el BD? Por ejemplo si pongo "user2525" supongo que me grabará en la bd ""user2525" ya que no tiene ningún caracter que escapar. Pero si por ejemplo pongo "user/25", debería grabarme "user25" es decir sin los caracteres, ya que solo escapa string? La verdad que si debe ser así no me funciona: :(
Gracias amigos.

A: Segun la documentacion de PHP en Español acerca de mysqli_real_escape_string:

Los caracteres codificados son NUL (ASCII 0), \n, \r, \, ', ", y Control-Z.

La diagonal / no es codificada.
http://php.net/manual/es/mysqli.real-escape-string.php


Q: Keep getting "None" at every input statement I was just making a Rock , Paper and scissor game in python(Version 3.9+)  but whenever I try to run , there is NONE written at every input statement...
My whole program works fine but  I am really annoyed with "NONE" is there anything I am doing something wrong in my code.
I will really appreciate your help!
Here is my code:
    import random

num__round = int(input("Enter the number of rounds you want to play for: "))
rounds = 1
while rounds <= num__round:

    comp_choices = ["Rock" , "Paper" , "Scissor"]

    print("Round number", rounds)

    user_action = str(input(print("Enter your choice from ===> Rock , Paper or Scissor"))).lower()
    comp_actions = str(random.choice(comp_choices)).lower()

    if user_action == comp_actions:

        print("You Chose==>" , user_action , "Computer Chose ==>" , comp_actions , "\nRound draw\n")

    elif user_action == 'rock':

        if comp_actions == 'paper':

            print("You Chose==>" , user_action , "\nComputer Chose ==>" , comp_actions)
            print("Paper defeats rock!\n<===You lost this round===>,Computer won this round!\n")

        else:
            print("You Chose==>" , user_action , "\nComputer Chose ==>" , comp_actions)
            print("Rock breaks scissor!\n<===You won this round!===>\n")

    elif user_action == 'paper':

        if comp_actions == 'rock':
            print("You Chose==>" , user_action , "\nComputer Chose ==>" , comp_actions , "\n")
            print("Paper defeats rock!\n<===You won this round===>,Computer lost!" , "\n")

        else:
            print("You Chose==>" , user_action , "\nComputer Chose ==>" , comp_actions)
            print("Scissor torn the paper into pieces!\n<===You lost this round===>,Computer won!\n")

    else:

        if comp_actions == 'rock':
            print("You Chose==>" , user_action , "\nComputer Chose ==>" , comp_actions )
            print("Rock brutally breaks the scissor!\n<===You lost this round===>,Computer won\n")

        else:
            print("You Chose==>" , user_action , "\nComputer Chose ==>" , comp_actions)
            print("Scissor torn down the paper!\n<===You won this round===>,Computer lost this
            round!\n")

    rounds  = rounds + 1

And here is the "None"  written in every input statement:
 Enter your choice from ===> Rock , Paper or Scissor None rock

A: input is willing to prompt your
"Enter your choice from ===> Rock , Paper or Scissor"

on its own but you also put a print there. So first print prints what you give it, and then its return value (print returns None) is passed to input and input then prompts this None (if you notice, it's on a newline actually because your print gave a newline).
So you dont need print there:
user_action = str(input("Enter your choice from ===> Rock , Paper or Scissor")).lower()

More, you don't need to cast str the input's result because it's always a string (if succeeds), so
user_action = input("Enter your choice from ===> Rock, Paper or Scissors: ").lower()

A: I copied this myself and got the NONE to go away by moving the input().lower() out of the print statement
print("Enter your choice from ===> Rock , Paper or Scissor")

user_action = str(input()).lower()
comp_actions = str(random.choice(comp_choices)).lower()

A: Simply remove the print() from your input:
str(input("Enter your choice from ===> Rock , Paper or Scissor\n")).lower()

A: whenever you see none its because your using print twice
change this:
user_action = str(input(print("Enter your choice from ===> Rock , Paper or Scissor"))).lower()

to this:
user_action = str(input("Enter your choice from ===> Rock , Paper or Scissor")).lower()

you are saying to print the function and then print the string that will take and input, which is in your function so your saying print twice, when you only need to say print the function and since the string that will take and input is in your function it will print it out.


Q: Scala IDE failing to be installed I have checked here but I cannot find anybody with the same kind of issue.
I am trying to install the 4.7.0 version of the Scala IDE based on Eclipse available at http://scala-ide.org/download/current.html for Windows 10. While the download seems to be working fine, once I unzip the file I get a pop-up message that says "Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit."

The configuration file eclipse.ini (still within the downloaded scala IDE) is:
*-startup
plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.500.v20170531-1133
-vmargs
-Xmx2G
-Xms200m
-XX:MaxPermSize=384m*

I have tried to increase the heap memory size to 512 and 1024 MB or using winzip instead of winrar for installing the program (apparently, there was some issue with WinRAR according to some people) but to no avail. Do you have any idea of what could be wrong?


Q: PowerPoint VBA - Click on shape then press another shape to change the colour I am new to VBA (since this morning so please treat me like an idiot and you will be about right!) and am stuck on something that seems as though it should be very simple.
I am working in PowerPoint and have a set of circles and below them a red and a green coloured square.
I would like to be able to select a relevant circle and then click on the appropriate square to change that circle only to red or green, as below
 Select your option:   O         O          O              O             O

 Change colour:              [Red]                  [Green]

At the moment I am using animations and triggers but I have LOTS of circles and I only want to change them one at a time.

A: +1 to Siddharth for that answer.  There's another bit that won't be apparent if you're just getting started out.  You can have PPT pass a reference to the clicked shape when the shape triggers a macro (caution:  Mac PPT is buggy/incomplete.  This won't work there).
Using Siddharth's suggestion as a jumping off point, you can do something like this:
Option Explicit
Sub SelectMe(oSh As Shape)
' assign this macro to each of the shapes you want to color
' saves time to assign it to one shape, then copy the shape as many
' times as needed.
    ActivePresentation.Tags.Add "LastSelected", oSh.Name
End Sub
Sub ColorMeRed(oSh As Shape)
' assign this macro to the "color it red" shape

' when this runs because you clicked a shape assigned to run the macro,
' oSh will contain a reference to the shape you clicked

' oSh.Parent returns a reference to the slide that contains the shape
' oSh.Parent.Shapes(ActivePresentation.Tags("LastSelected")) returns a reference
' to the shape whose name is contained in the "LastSelected" tag,
' which was applied in the SelectMe macro above.
' Whew!

    If Len(ActivePresentation.Tags("LastSelected")) > 0 Then
        With oSh.Parent.Shapes(ActivePresentation.Tags("LastSelected"))
            .Fill.ForeColor.RGB = RGB(255, 0, 0)
        End With
    End If

End Sub
Sub ColorMeBlue(oSh As Shape)
' assign this macro to the "color it blue" shape
    If Len(ActivePresentation.Tags("LastSelected")) > 0 Then
        With oSh.Parent.Shapes(ActivePresentation.Tags("LastSelected"))
            .Fill.ForeColor.RGB = RGB(0, 0, 255)
        End With
    End If
End Sub


Q: How to show week number using Angular material v12 I am using Angular material datepicker.
https://material.angular.io/components/datepicker/
Is there is way to show week numbers of this datepicker?

A: Unfortunately, no.
It's been requested from the Angular Material team but they responded with this:
https://github.com/angular/material/issues/10003#issuecomment-364730323

We have no plans to add an option to visually display the week number on the calendar as this is not part of the Material Design Spec.

Week numbers would be great feature to add, but won't happen until Google decides to add it to the Material Design Spec.


Q: Parsing JSON response in Blackberry I am getting a below JSON Response from the server please let me know how to parse this.
I only need
---------------------------7da7d113c0dea
Content-Type: application/json
Content-Length: 338
Request-Id: 714a31e1-1b2c-4e10-8ce1-7b7c4204ff66
response-type: rfc_json
status-code: 200
processing-time: 74993

{"EXPORTING":{"OUT_CATEGORY_CODE_DESC":[{"CONTENT":"1","LIST_ID":"","DESCRIPTION":
"Business Area","DISABLED":""},{"CONTENT":"2","LIST_ID":"",
 "DESCRIPTION":"Industry","DISABLED":""},{"CONTENT":"5","LIST_ID":"",
  "DESCRIPTION":"Vendor","DISABLED":""}],
  "OUT_MESSAGE":"","OUT_SOLUTION_DETAILS":[],
   "OUT_SUBCATEGORY_SEARCH":[]},"IMPORTING": null}

    ---------------------------7da7d113c0dea--

i would like to retrive values OUT_CATEGORY_CODE_DESC[],OUT_SOLUTION_DETAILS":[] and OUT_SUBCATEGORY_SEARCH":[] . Do you have any sample code here?

A: There is a package over on JSON.org called org.json.me which is a port of org.json to Java ME.


Q: validates_presence_of and with templates ruby on rails I'm trying to validate some ratio buttons making sure the user as selected one of them. I do this by using:
validates_presence_of

In addition, I have specific template that I use for the page's layout.  Normally, without the template layout, The anything that is missing is highlighted automatcially by the validates_pressense_of helper in red.  However, with with the template, I only see the displayed words which is probably a result of the template.
Is there some way fix this and have the missing fields highlighted in red with the template?
Here is the snippet of the .css file i'm using for the template:
body{

background:#F4DDB1;

margin:0;
font: 10pt/14pt 'Lucida Grande', Verdana, Helvetica, sans-serif;
}

A:link{ color:#275A78; text-decoration:none; }
A:hover{ color:#333333; text-decoration:underline; }
A:active{ color:#275A78; text-decoration:none; }
A:active:hover{ color:#333333; text-decoration:underline; }
A:visited{ color:#275A78; text-decoration:none; }
A:visited:hover{ color:#333333; text-decoration:underline; }

#header{
background:url(../images/headerbg.gif) no-repeat #F4DDB1 top left;
width:282px;
height:439px;
margin-right:auto;
/*
 *margin-left:0;
 */
margin-bottom:0;
text-align:right;
float:left;
}

#wrap{
width:782px;
margin-right:auto;
margin-left:auto;

}

#container{
background:#F8EBD2;
width:500px;
/*margin-left:282px;
margin-top:-452px; */
float:right;
}

#navcontainer{

/*
 *
 */position:absolute;
   width:282px;

   margin-right:auto;
   margin-top:435px;
   margin-left:60px;

}

#navlist li{
    margin-left:15px;
   list-style-type: none;
   text-align:right;
   padding-right: 20px;
   font-family: 'Lucida Grande', Verdana, Helvetica, sans-serif;
   font-size:12px;
   color:#666666;
}

#navlist li a:link { color: #666666; text-decoration:none; }
#navlist li a:visited { color: #999999; text-decoration:none; }
#navlist li a:hover {color: #7394A0; text-decoration:none; }

h3{
font-size:21px;
font-weight:bold;
color:#8C7364;
}

.content{
padding:10px;
width: 100%
text-align:justify;
font: 9pt/14pt 'Lucida Grande', Verdana, Helvetica, sans-serif;
}

#footer{

  background:transparent;

   height:66px;
   text-align:center;
   font: 8pt/14pt 'Lucida Grande', Verdana, Helvetica, sans-serif;
   color:#333333;
}

#title{
position:absolute;
top:440px;
left:9px;
padding-left:9px;
font: 14pt/12pt 'Lucida Grande', Verdana, Helvetica, sans-serif;
color:#275A78;
}

The code will be in this portion:

                <%= yield :layout %>

http://www.otoplusvn.com/TherapistSurvey/counselor_questionaries/new
If you don't click on any radio buttons, and press submit you only see the error messages, but the fields aren't highlighted.
Any Advise appreciated,
Thanks,
Derek

A: The highlights from Rails comes from CSS that targets :
.field and .field_with_errors
These classes are generated with the following HAML in Rails :
.field
  = f.label :type
  = f.check_box :type

In HTML :
<% form_for(@plant) do |f| %>
 <%= f.error_messages %>
 Plant Name

 <%= f.label :name %>

 <%= f.text_field :name %>
..

What does your HAML look like for say, one of your fields?

A:

        <% for rating_option in [0,1,2,3,4,5,6]  -%>

               <%= radio_button("counselor_effectiveness", category, @temp[rating_option])%>

        <% end -%>

I'm still really new to css and ruby on rails.  The above code is used to generate the radio buttons.  Are you saying that in the css i can control the color of the background of the radio buttons (being highlighted) through the css?  If so , how is that done?
Thanks,
D


Q: Global menu bar is empty in Unity on Ubuntu 16.04? I'm running the new Ubuntu LTS (16.04) with Unity 7.4.0 (The default for 16.04).
I've taken three screenshots. The first is the behavior I expect in Chromium. As you can see in this screenshot, I was attempting to look up how to get the screenshot to capture the cursor as well, but decided it would be less work to just explain that in all three of these scenarios, I'm putting the cursor in the very top left corner of the display.
Here's a full-screen Chromium doing what I expect...

Here is a windowed Nautilus not providing any menu items (File, View, etc.)...

And here is a full-screen Eclipse not providing any menu items either, but displaying just the exit, minimize, and windowed-mode buttons...

Am I missing something here? When I last used Ubuntu 14.04 both of these applications were behaving like Chromium. I also could have sworn that Nautilus used to have those menus there where I first installed Ubuntu 16.04, all though I might be mistaken. This is either a rather annoying bug, or a rather annoying "feature." If it is a bug, how do I fix it? If not, how do I make these windows behave like Chromium is behaving?


Q: 'pointerenter' event not working on touch device I have the following html template of a table. My intention is that a user is able to highlight each table cell when they drag their pointer across each table cell. The following code works on mouse device however function that is supposed to fire on pointerenter event does not work when it is being used on touch device.

    <template v-for="patch in item.patches">

    </template>

These are the functions startDrag, handleDrag and finishDrag that are tied to pointerdown, pointerenter and pointerup respectively.

startDrag(patch, e) {
  this.mouseDown = true
  console.log("mouse down event...")
  this.handleDrag(patch)
  e.target.setPointerCapture(e.pointerId);
},
handleDrag(patch) {
  if (this.mouseDown) {
    this.highlightPatch(patch)
  }
},
finishDrag(e) {
  console.log('mouse up event...');
  this.mouseDown = false;
  e.target.releasePointerCapture(e.pointerId);
},

The above functions work fine when using mouse device but not so when using touch device. I've tried enabling and disabling style="touch-action:none;" however both options does not seem to work.


Q: Android WebView fails at loading URL stating net::ERR_INSUFFICIENT_RESOURCE I am using a WebView in my application and upon the click of a button the user is supposed to go from 'URL A' to 'URL B' , but it looks like the WebView makes an effort- I see URL B in the background of the loader but within a fraction of seconds it loops back to 'URL A'. When I checked the android studio log I found an error stating net::ERR_INSUFFICIENT_RESOURCES .
No where else in my application have I noticed such a glitch and there are so many urls the user can go to and fro with no backfire.
The URL B a grid showing a maximum of 10 photos. Hence I don't feel its heavy on resources. URL A has a list of more photos and data in it. What could be the possible cause for such an error?

A: This happens when chrome tries to load a large number of images/resources in a short period of time.Have a look at this.
Try disabling the chrome plugin adblock plus and try.Still it may take long time to load


Q: SwiftUI: Call a function of a programmatically created view I am trying to make a SwiftUI ScrollView scroll to a certain point in an abstracted view when a button is pressed in a view which is calling the abstracted view programmatically. Here is my code:
struct AbstractedView: View {
    @Namespace var view2ID

    var body: some View {
        ScrollView {
            VStack {
                View1()
                View2()
                .id(view2ID)
                View3()
            }
        }
    }
    func scrollToView2(_ proxy: ScrollViewProxy) {
        proxy.scrollTo(view2ID, anchor: .topTrailing)
    }
}

As you can see, when scrollToView2() is called (in a ScrollViewReader), the AbstractedView scrolls to view2ID. I am creating a number of AbstractedView's programmatically in a different View:
struct HigherView: View {
    var numAbstractedViewsToMake: Int

    var body: some View {
        VStack {
            HStack {
                ForEach (0..<numAbstractedViewsToMake, id: \.self) { _ in
                    AbstractedView()
                }
            }
            Text("button")
            .onTapGesture {
                /* call each AbstractedView.scrollToView2()
            }
        }
    }
}

If I stored these views in an array in a struct inside my HigherView with a ScrollViewReader for each AbstractedView would that work? I feel as though there has to be a nicer way to achieve this, I just have no clue how to do it. I am new to Swift so thank you for any help.
P.S. I have heard about UIKit but I don't know anything about it, is this the right time to be using that?

A: Using the comments from @Asperi and @jnpdx, I was able to come up with a more powerful solution than I needed:
class ScrollToModel: ObservableObject {
    enum Action {
        case end
        case top
    }
    @Published var direction: Action? = nil
}

struct HigherView: View {
    @StateObject var vm = ScrollToModel()
    var numAbstractedViewsToMake: Int

    var body: some View {
        VStack {
            HStack {
                Button(action: { vm.direction = .top }) { // < here
                    Image(systemName: "arrow.up.to.line")
                      .padding(.horizontal)
                }
                Button(action: { vm.direction = .end }) { // << here
                    Image(systemName: "arrow.down.to.line")
                      .padding(.horizontal)
                }
            }
            Divider()
            HStack {
                ForEach(0..<numAbstractedViewsToMake, id: \.self) { _ in
                    ScrollToModelView(vm: vm)
                }
            }
        }
    }
}

struct AbstractedView: View {
    @ObservedObject var vm: ScrollToModel

    let items = (0..<200).map { $0 } // this is his demo
    var body: some View {
        VStack {

            ScrollViewReader { sp in
                ScrollView {

                    LazyVStack { // this bit can be changed accordingly
                        ForEach(items, id: \.self) { item in
                            VStack(alignment: .leading) {
                                Text("Item \(item)").id(item)
                                Divider()
                            }.frame(maxWidth: .infinity).padding(.horizontal)
                        }
                    }.onReceive(vm.$direction) { action in
                        guard !items.isEmpty else { return }
                        withAnimation {
                            switch action {
                                case .top:
                                    sp.scrollTo(items.first!, anchor: .top)
                                case .end:
                                    sp.scrollTo(items.last!, anchor: .bottom)
                                default:
                                    return
                            }
                        }
                    }
                }
            }
        }
    }
}

Thank you both!


Q: Where is the configuration file for application in Tibco administrator (version 5.3) I want to find the configuration file for application configurations in Tibco administrator. Then I can know all runtime configurations of my application.

I tried to findout in the path /opt/sw/tibco/tra/domain/SOADEV/datafiles/[my app]_root but this configuration is out of date, and is not latest configuration.
Here is example:
The configuration file contains "ExchangeRate" item

Tibco Admin doesn't display ExchangeRate item (in path Global/Vn)

A: tibco/tra/domain/[ENV_NAME]/datafiles/[my app]_root is actually right place where all Global variables values and package code are stored after package deployment.
I am guessing you are looking to the wrong package or something wrong with the deployment.
All global variables should be stored in
[my app]_root\defaultVars\defaultVars.substvar

or subfolders
[my app]_root\defaultVars\[folder_name]\defaultVars.substvar

the variable can be deployment settable and service settable. Please see more details here https://community.tibco.com/questions/difference-between-global-variables-earservice-and-service-instance-levels
Also there are several ways global variables can be overridden. Please see https://support.tibco.com/s/article/Tibco-KnowledgeArticle-Article-47854

1). In Designer -> Global Variables panel, click the pencil icon (Open
Advanced Editor) at top right, select the global variable and right
click ->  “Override Variable”.
2). Use the Project -> “Save as” option to save as a new project.
Global variables will then be editable.
3). Go to Tester -> "Advanced" test settings with the "-p
PATH/properties.cfg" argument, with PATH being the absolute path and
properties the file that override global variables.
4).Change the variable in TIBCO administrator GUI during deployment.
5). Manually edit the bwengine.tra.


Q: php for each sorting by category joomla k2 Hi I have this code from joomla k2 template

<?php $thearray = $this->primary ;?>
<?php foreach($thearray as $key=>$item): ?>

    <?php
    $this->item=$item;
    echo $this->loadTemplate('item');
    ?>

<?php endforeach; ?>

Now it is taking items from main category and sub categories and displaying items like this.
item,
item,
item,
item,

I need it to take items from main and subcategories and display them like this:
category1
item
item

category2
item
item

category3
item
item

and etc.
How can I do this?
uptade:
The array is constructed like that  or at least few lines of it
Array ( [0] => stdClass Object ( [id] => 41 [title] => test2 [alias] => test2 [catid] => 8 [published] => 1 [introtext] =>
test2

[fulltext] => [video] => [gallery] => [extra_fields] => [] [extra_fields_search] => [created] => 2012-08-27 16:37:51 [created_by] => 62 [created_by_alias] => [checked_out] => 0 [checked_out_time] => 0000-00-00 00:00:00 [modified] => 0000-00-00 00:00:00 [modified_by] => 0 [publish_up] => 2012-08-27 16:37:51 [publish_down] => 0000-00-00 00:00:00 [trash] => 0 [access]

and somethere in the bottom is the category name in it.

A: There is only one method. You have to reorder your array
foreach($thearray as $key=>$item) {
    $items[$item->catid][] = $item;
}

foreach($items AS $catid => $cat_items) {
    echo '
'.$catid.'
';
    foreach($cat_items AS $item)
        echo $item->name.'
';
}

Something like this.


Q: How can I make the mock location provider to work I have a need to create a test application which can mock the location. On clicking button, the latitude and longitude values provided in text box need to be set as the mock location. I am trying to build this using simple way using fused location provider APIs
Location mockLocation = new Location("flp");
mockLocation.setLatitude(12);
mockLocation.setLongitude(82);
mockLocation.setAccuracy(1.0f);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
}
mockLocation.setTime(new Date().getTime());

Criteria criteria = new Criteria();
criteria.setAccuracy( Criteria.ACCURACY_FINE );
String provider = locationManager.getBestProvider( criteria, true );

if ( provider == null ) {
   Log.e( "", "No location provider found!" );
   return;
}

// provider and LocationManager.GPS_PROVIDER are same - "gps"

locationManager.setTestProviderLocation(LocationManager.GPS_PROVIDER, mockLocation); // --> I am getting exception here

I gave all possible permissions in manifest file:
ACCESS_COARSE_LOCATION
ACCESS_FINE_LOCATION
ALLOW_MOCK_LOCATIONS
ACCESS_MOCK_LOCATION

Also manually enabled developer options, application permissions, and mock location provider app in settings.
I am getting except on setTestProviderLocation:

java.lang.IllegalStateException: Could not execute method for
  android:onClick at
  androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
  at android.view.View.performClick(View.java:6266) at
  android.view.View$PerformClick.run(View.java:24730) at
  android.os.Handler.handleCallback(Handler.java:793) at
  android.os.Handler.dispatchMessage(Handler.java:98) at
  android.os.Looper.loop(Looper.java:173) at
  android.app.ActivityThread.main(ActivityThread.java:6698) at
  java.lang.reflect.Method.invoke(Native Method) at
  com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:782) Caused
  by: java.lang.reflect.InvocationTargetException at
  java.lang.reflect.Method.invoke(Native Method) at
  androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
  ... 9 more Caused by: java.lang.IllegalArgumentException: Provider
  "gps" unknown at android.os.Parcel.readException(Parcel.java:1955) at
  android.os.Parcel.readException(Parcel.java:1897) at
  android.location.ILocationManager$Stub$Proxy.setTestProviderLocation(ILocationManager.java:1340)
  at
  android.location.LocationManager.setTestProviderLocation(LocationManager.java:1305)

Any way to fix this?
Thanks,
raj

A: Since Android 10 my fake location app has the same issue and the app is crashing with:
java.lang.IllegalArgumentException: Provider "gps" unknown

But on older Android versions same code is working. I tested it on 6,7,8 and 9. My temporary solution for it is to catch the exception (until I find a better way). The mock should still work.
try {
   mLocationManager.removeTestProvider(getBestProvider());
} catch (IllegalArgumentException e) {
   // handle the error e.getMessage()
}

Druing debugging I can see the provider gps inside the locationManager list like
mLocationManager.getProvider(getBestProvider())


Q: Content on HTML/CSS page moves when the 'Tab' key is pressed I've created a custom login page for my Salesforce Community which consists of some HTML and CSS (all within the Visualforce page), but when I use the tab key some content on the page shifts.
From my research it seems to be from the content being larger than the container it is within, but what would be a fix for this? Having some of the content be slightly cut off is part of the style (look and feel) of the page so I'd rather not simply expose the content all the way if possible.

/* **CSS within my Visualforce page** */

/* CSS Reset */

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6,
p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del,
dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub,
sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td, button, form,
fieldset, input, textarea {
  margin: 0;
  padding: 0;
  outline: 0;
  border: 0;
  background: transparent;
  vertical-align: baseline;
  font-size: 100%;
}

body {
  line-height: 1;
}

h1, h2, h3, h4, h5, h6 {
  font-weight: normal;
}

ol, ul {
  list-style: none;
}

blockquote, q {
  quotes: none;
}

blockquote:before, blockquote:after, q:before, q:after {
  content: '';
  content: none;
}

/* remember to define focus styles! */
 :focus {
  outline: 0;
}

/* remember to highlight inserts somehow! */
ins {
  text-decoration: none;
}

del {
  text-decoration: line-through;
}

/* tables still need 'cellspacing="0"' in the markup */
table {
  border-spacing: 0;
  border-collapse: collapse;
}

address, caption, cite, code, dfn, em, strong, var {
  font-weight: normal;
  font-style: normal;
}

caption, th {
  text-align: left;
  font-weight: normal;
  font-style: normal;
}

html {
  background-color: #3a3a3a;
}

body {
  min-height: 100%;
  height: 100%;
  background: url(http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/navy_blue.png) repeat;
  font-weight: lighter;
  font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
  -webkit-font-smoothing: subpixel-antialiased;
}

a {
  color: #b1c;
  text-decoration: none;
}

p {
  display: block;
  width: 300px;
  margin-left: -180px;
  margin-top: -5px;
}

p a {
  color: #a4a4a4;
  font-size: 10px;
  text-decoration: none;
}

p a:hover {
  color: #1d83cc;
  border-bottom: 1px solid gray
}

#warp {
  position: relative;
  margin: 100px auto 0;
  width: 400px;
  text-align: center;
  color: white;
}

form {
  display: block;
  width: 100%;
  height: 300px;
}

h1 {
  color: #b6b6b6;
  font-weight: bolder;
  font-size: 60px;
}

.admin {
  height: 250px;
  float: left;
  width: 200px;
  border-right: 1px solid #333333;
  text-align: left;
  left: 0;
  top: 0;
  transition: all 200ms ease-in 100ms;
}

.cms {
  height: 250px;
  top: 70px;
  left: -62px;
  float: right;
  width: 150px;
  text-align: right;
  transition: all 200ms ease-in 100ms;
}

.admin,
.cms {
  position: relative;
  display: block;
  overflow: hidden;
  transform: rotate(30deg);
}

.cms h1 {
  margin-left: -10px;
  color: #838385;
}

.roti,
.rota {
  position: relative;
  display: block;
  transform: rotate(-30deg);
}

.admin:hover h1,
.cms:hover h1 {
  color: #1d83cc;
}

.rota {
  margin-top: 80px;
  margin-left: 35px;
}

.roti {
  margin-top: 80px;
  margin-right: 55px;
}

input,
button {
  margin: 4px;
  padding: 8px 6px;
  width: 350px;
  background: white;
  color: black;
  font-size: 10px;
  transition: all 1s ease-out;
}

.button {
  margin-left: -230px;
  background: #303030;
  color: white;
  text-align: right;
  cursor: pointer;
  transition: all 1s ease-out;
}

button:hover {
  background: #1d83cc;
  transition: all 0.3s ease-in;
}

input:hover {
  box-shadow: inset 0 0 5px rgba(29, 131, 204, 1)
}

input:focus {
  background: gray;
  color: white
}

.up {
  top: 100px;
  left: -60px;
}

.down {
  top: -100px;
  left: 60px;
}

  <form action="" id="formu">

PORTAL

        <apex:inputtext styleClass="input" value="{!username}" html-placeholder="Username" />
        <apex:inputsecret styleClass="input" value="{!password}" html-placeholder="Password" />

BW

        <apex:commandbutton styleClass="button" value="Login" action="{!doLogin}" />

          <apex:commandLink value="Forgot password?" action="{!forgotPassword}" />

  </form>


Q: How to show the value stored in an array in Objective-C I have stored data in an array from XML Parsing. In the array I have stored latitude and longitude of the start and end point. Now I want to show the value of lat and long in the table view's cell.text. How can I access this? What syntax do I use so that I show the value of the element stored in the array? When I print to console it shows that the array has 12 objects. The values stored in the array are:

araystp= (
      Step: 0x563f160,
      Step: 0x563f860,
      Step: 0x56400d0,
      Step: 0x56408e0,
      Step: 0x56410f0,
      Step: 0x5641990,
      Step: 0x5642290,
      Step: 0x5642ae0,
      Step: 0x56434a0,
      Step: 0x5643e80,
      Step: 0x56446f0,
      Sleg: 0x5623850
  )

A: Following is the code to get stored value from your xml calss.
    for (int i = 0 ; i <[array count];i++)
    {
         XmlClass *class1 = (XmlClass*) [array objectAtIndex:i];
         NSString *strLat = class1.latitude;
         NSString *strLong = class1.longitude;
    }

A: suppose u have use array in XML file is listofPoint in which u have add your class's object.Now u synthesize a NSMutableArray in app delegate file. And where you are doing parsing event there after completion of parsing make copy of array listofPoint to appdelegate array. and in next class define object of class which you have add in listofPoint array. And use this syntax.

yourclass *Object=[[yourclass alloc]init];
      Object=[appDelegate.Array objectAtIndex:0];
      NSLog(@"%f",Object.var);

it will work.

A:  for (int i = 0 ; i <[array count];i++)
 {
YourXmlClass *x = [array objectAtIndex:i]
NSString *s = x.latitude;
NSString *s1 = x.longitude;
  }


Q: How Can Structure Notify Other Threads Correctly About An Event? I'm trying to write a threadsafe structure to keep key - value pairs and to automatically remove them after certain time delay. The problem is, that the container should notify other threads about deletion.
I've also tried to use notifyAll() in a synchronized block, but the problem persists.
import java.util.Objects;
import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class Container <K extends Comparable<K>, V> {
    private ConcurrentHashMap <K, V> a;
    private final int delay = 2;
    private final Lock lock = new ReentrantLock();
    private final Condition removed = lock.newCondition();

    public Container() {
        a = new ConcurrentHashMap<>();
    }
    public synchronized void put(K k, V o) {
            lock.lock();
            a.put(k, o);
            new Thread(() -> {
                try {
                    TimeUnit.SECONDS.sleep(delay);

                    a.remove(k, o);
                    removed.signalAll();
                    lock.unlock();
                } catch (InterruptedException e){
                    e.printStackTrace();
                }

            }).start();

    }

    public  V get(int k)  {

        return a.get(k);
    }

    @Override
    public String toString() {
        return Stream.of(a)
        .filter(Objects::nonNull)
                .map(Object::toString)
                .collect(Collectors.joining(", ", "{", "}"));

    }
}

public class Main {

    public static void main(String [] args) throws InterruptedException {
        Container<Integer, Integer> c = new Container<>();
        c.put(0, 10);
        System.out.println(c);
        c.put(1, 11);
        c.put(2, 12);

        TimeUnit.SECONDS.sleep(3);
        System.out.println(c);

    }
}

Program finishes with code 0 and prints expected values: first element and the empty structure. But in either way I got the IllegalMonitorStateException.
Any thoughts, thanks.

A: public synchronized void put(K k, V o) {
    a.put(k, o);
    new Thread(() -> {
        try {
            TimeUnit.SECONDS.sleep(delay);
            lock.lock();
            a.remove(k, o);
            removed.signalAll();
            lock.unlock();
        } catch (InterruptedException e){
            e.printStackTrace();
        }

    }).start();

}

Try this maybe. You re locking the lock and unlocking the lock in different threads. The thread that call theput method is the one using lock.lock() so it is the only one that can unlock it. The code inside the new Thread(....) belong to another thread so calling lock.unlock() there will not work. Also in the current code I don't see any use of the lock and condition, you can just remove all this (unless you plan on using it somewhere else we don't see), you can put and remove from a concurrent map with worrying about managing the access yourself.

A: In order to wait or notify (await and signal if using Condition) the thread, which performs an action, must own the lock it's trying to wait or notify on.
From your example: you put a lock in the main thread (lock.put()), then start a new thread. The new thread does not own the lock (it's still held by the main thread), but despite that you try to invoke signalAll() and get  IllegalMonitorStateException.
In order to fix the problem you should:
1. Release the lock the main thread holds when it's ready (you never release it at the moment).
2. Lock in the new thread first and only then call signalAll()
3. Release the lock in the new thread when you're ready. Do it in the finally clause of the try-catch block to guarantee that the lock gets released in case of an exception.
Also a few moments:
- in order to be notified a thread must be waiting for notification.
- synchronization on the put() method is redundant, since you're already using a ReentrantLock inside.

A: We have a few things to look at here:

*

*lock

*removed which is a condition created using lock
Your main thread acquires a lock on lock in the put method.
However it never releases the lock; instead it creates a new Thread that calls removed.signalAll(). However this new thread does not hold a lock lock which would be required to do this.
I think what you need to do is to make sure that every thread that locks lock also unlocks it and that every thread calling signalAll also has a lock.
  public synchronized void put(K k, V o) {

    a.put(k, o);

    new Thread(() -> {
      try {
        TimeUnit.SECONDS.sleep(delay);

        lock.lock(); // get control over lock here
        a.remove(k, o);
        removed.signalAll();
        lock.unlock();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

    }).start();

  }


Q: Passing ModelBuilder parameter to update cursor gives ERROR 999999? I have two point layers.  I trust the geometry (read: x and y coordinates) from one of them, but not the attributes data.  I trust the attribute data but not the geometry from the other one (the attribute tables have different schema).  The basic process (shown in a model builder screenshot below) is to spatially join the point layers, join the result to the points with good data/bad geometry and update their shape field with a script. The script produces one of those damnable "999999: Error executing function" errors.
If I manually step through every stop of the process and feed the update cursor a ready-made feature class it works fine, the points move as intended.  It's just when it's set up to run in a model that the script throws the error.  I have a feeling that I may be passing the parameter incorrectly, but I can't say for sure.
I've tried moving the "fc = GetParameterAsText()" line around (including in the update cursor parameters) to no avail.
I will also point that I shamelessly took the python from a post on Geonet, located here.
The Model:

The Script:
import arcpy
from arcpy import env

env.workspace = r"C:\Temp\TempGDB.gdb"

#Get the feature layer from the previous step in the model
fc = arcpy.GetParameterAsText(0)

pnt = arcpy.Point()

#Update the shape field with the new coordinates
rows = arcpy.UpdateCursor(fc)
for row in rows:
    pnt.X = row.X_Coord
    pnt.Y = row.Y_Coord
    row.shape = pnt
    rows.updateRow(row)

del row, rows

The Script Tool Properties

A: It lools like the problem is that pnt has no spatial reference and arc is having a spit, It's that or your field isn't being retrieved correctly, it's best to use row.getValue(field_name) rather than row.field_name as getValue is more flexible. Please ensure the fields X_Coord and Y_Coord exist in your layer (and aren't turned off) in the layer dialog.
Try this:
import arcpy
from arcpy import env

env.workspace = r"C:\Temp\TempGDB.gdb"

#Get the feature layer from the previous step in the model
fc = arcpy.GetParameterAsText(0)
desc = arcpy.Describe(fc)
SR = desc.spatialReference # get the spatial reference from the feature class

pnt = arcpy.Point()

#Update the shape field with the new coordinates
rows = arcpy.UpdateCursor(fc)
for row in rows:
    pnt.X = row.getValue("X_Coord")
    pnt.Y = row.getValue("Y_Coord")
    pGeom = arcpy.PointGeometry(pnt)
    pGeom.spatialReference = SR # apply it to the shape
    row.shape = pGeom
    rows.updateRow(row)

del row, rows

This would definitely work better as an arcpy.da cursor (ArcGIS 10.1+):
import arcpy
from arcpy import env

env.workspace = r"C:\Temp\TempGDB.gdb"

#Get the feature layer from the previous step in the model
fc = arcpy.GetParameterAsText(0)

#Update the shape field with the new coordinates
with (arcpy.da.UpdateCursor(fc,["SHAPE@X","SHAPE@Y","X_Coord","Y_Coord"])) as rows:
    for row in rows:
        row[0]=row[2] # X = X_coord
        row[1]=row[3] # Y = Y_coord
        rows.updateRow(row)


Q: How can I set didEndOnExit in code rather than Interface Builder?
Possible Duplicate:
Assign a method for didEndOnExit event of UITextField

How can I add didEndOnExit to a UITextField in pure code rather than IB?
Thanks!

A: Assuming your talking about textFieldDidEndEditing: or textFieldShouldReturn:.  You would implement the method in your view controller, and set the text fields delegate to self like so:
- (void)viewDidLoad {
    [super viewDidLoad];
    // ....
    myTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 50, 25)];
    myTextField.delegate = self;
    [self.view addSubview:myTextField];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField == myTextField) {
        // Do stuff...
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == myTextField) {
        return YES;
    }
    return NO;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ((myTextField.text.length + string.length) < 5) {
        return YES;
    }
    return NO;
}

Then, in your header file in the @interface you can specify that you are a UITextFieldDelegate like this:
@interface MyViewController : UIViewController <UITextFieldDelegate> {
    // ....
    UITextField *myTextField;
    // ....
}

// Optionally, to make myTextField a property:
@property (nonatomic, retain) UITextField *myTextField;

@end

UITextField Reference
UITextFieldDelegate Reference

Edit (as per your comment, this should work):
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ((myTextField.text.length + string.length) < 5) {
        return YES;
    }
    return NO;
}


Q: Pipe output of cat to cURL to download a list of files I have a list URLs in a file called urls.txt.  Each line contains 1 URL.  I want to download all of the files at once using cURL.  I can't seem to get the right one-liner down.
I tried:
$ cat urls.txt | xargs -0 curl -O

But that only gives me the last file in the list.

A: xargs -P 10 | curl
GNU xargs -P can run multiple curl processes in parallel. E.g. to run  10 processes:
xargs -P 10 -n 1 curl -O < urls.txt

This will speed up download 10x if your maximum download speed if not reached and if the server does not throttle IPs, which is the most common scenario.
Just don't set -P too high or your RAM may be overwhelmed.
GNU parallel can achieve similar results.
The downside of those methods is that they don't use a single connection for all files, which what curl does if you pass multiple URLs to it at once as in:
curl -O out1.txt http://exmple.com/1 -O out2.txt http://exmple.com/2

as mentioned at https://serverfault.com/questions/199434/how-do-i-make-curl-use-keepalive-from-the-command-line
Maybe combining both methods would give the best results? But I imagine that parallelization is more important than keeping the connection alive.
See also: Parallel download using Curl command line utility

A: Here is how I do it on a Mac (OSX), but it should work equally well on other systems:
What you need is a text file that contains your links for curl
like so:
    http://www.site1.com/subdirectory/file1-[01-15].jpg
    http://www.site1.com/subdirectory/file2-[01-15].jpg
    .
    .
    http://www.site1.com/subdirectory/file3287-[01-15].jpg

In this hypothetical case, the text file has 3287 lines and each line is coding for 15 pictures.
Let's say we save these links in a text file called testcurl.txt on the top level (/) of our hard drive.
Now we have to go into the terminal and enter the following command in the bash shell:
    for i in "`cat /testcurl.txt`" ; do curl -O "$i" ; done

Make sure you are using back ticks (`)
Also make sure the flag (-O) is a capital O and NOT a zero
with the -O flag, the original filename will be taken
Happy downloading!

A: As others have rightly mentioned:
-cat urls.txt | xargs -0 curl -O
+cat urls.txt | xargs -n1 curl -O

However, this paradigm is a very bad idea, especially if all of your URLs come from the same server -- you're not only going to be spawning another curl instance, but will also be establishing a new TCP connection for each request, which is highly inefficient, and even more so with the now ubiquitous https.
Please use this instead:
-cat urls.txt | xargs -n1 curl -O
+cat urls.txt | wget -i/dev/fd/0

Or, even simpler:
-cat urls.txt | wget -i/dev/fd/0
+wget -i/dev/fd/0 < urls.txt

Simplest yet:
-wget -i/dev/fd/0 < urls.txt
+wget -iurls.txt

A: A very simple solution would be the following:
If you have a file 'file.txt' like
url="http://www.google.de"
url="http://www.yahoo.de"
url="http://www.bing.de"

Then you can use curl and simply do
curl -K file.txt

And curl will call all Urls contained in your file.txt!
So if you have control over your input-file-format, maybe this is the simplest solution for you!

A: Or you could just do this:
cat urls.txt | xargs curl -O

You only need to use the -I parameter when you want to insert the cat output in the middle of a command.

A: This works for me:
$ xargs -n 1 curl -O < urls.txt

I'm in FreeBSD.  Your xargs may work differently.
Note that this runs sequential curls, which you may view as unnecessarily heavy. If you'd like to save some of that overhead, the following may work in bash:
$ mapfile -t urls < urls.txt
$ curl ${urls[@]/#/-O }

This saves your URL list to an array, then expands the array with options to curl to cause targets to be downloaded. The curl command can take multiple URLs and fetch all of them, recycling the existing connection (HTTP/1.1), but it needs the -O option before each one in order to download and save each target. Note that characters within some URLs ] may need to be escaped to avoid interacting with your shell.
Or if you are using a POSIX shell rather than bash:
$ curl $(printf ' -O %s' $(cat urls.txt))

This relies on printf's behaviour of repeating the format pattern to exhaust the list of data arguments; not all stand-alone printfs will do this.
Note that this non-xargs method also may bump up against system limits for very large lists of URLs. Research ARG_MAX and MAX_ARG_STRLEN if this is a concern.


Q: How to make make this code clearer? I am sorry if it is a simple problem for you.But i am really struggling with this problem
In our application we have plenty of ajax calls in each and every page. We are using jQuery ajax. Presently what we are doing is
When we get the result from like myresults, we are passing to a function populate where we are building the result.
function populate(myresults)
{
    var str='
';
    for(var i in myresults){
        str+='
';
        str+=myresults[i].name;
        str+='
';
    }
    str+='
';

    $('#divId').html(str);
}

Not exactly we are building tables in all places. The code is working perfectly, but I think writing of code like this is not the right approach. How can I can beautify my code.  I can use jQuery or javascript.

A: You should try to look for TemplateEngine - it could allow to decrease code count and make it more clear.
What Javascript Template Engines you recommend?

A: You should run your code through a linting engine like JSLint or JSHint and you should familiarize yourself with good practice.
Here's one way (of more than one possible solution) to optimize your code:
function populate(myresults) {
    var table = $(document.createElement('table'));

    $(myresults).each(function (i) {
        var row = $(document.createElement('tr')),
            cell = $(document.createElement('td')).text(myresults[i].name);
        row.append(cell);
        table.append(row);
    });

    $('#divId').append(table);
}

A: Maybe, creating a new DOM element more correct ?
Like this:
function populate(myresults)
  {
   var str= $('
)';
      for(var i in myresults){
        str.append($('').text(myresults[i].name).appendTo($('
')));
      }
    $('#divId').empty().append(str);
  }

A: You could do it this way:
function populate(myResults)
{
    var tab = $('
');
    for(var i in myResults){
      if (myResults.hasOwnProperty(i)) {
          var tr = $('
');
          tr.append($(', {text: i.name}));
          tab.append(tr);
      }
    }
    $('#divId').append(tab);
}

Using a template engine as suggested by the others would be preferable as it's a better, more maintainable approach.


Q: How to invalidate redis cache with mysql? I want to use redis as cache for mysql, and the main idea is:
Query

*

*read from redis

*if not exist, read from mysql, and add to redis cache
Add

*

*write to mysql directly

Update&Delete

*

*write to mysql

*invalidate the cache of redis

My question is: how to invalidate the cache?
I know I can delete it, or set a expire time, is it a usual way, or are there any standard methods to invalidate the cache?
Thanks!

A: You would need a trigger to tell redis that mysql data has been updated.

*

*This can be a part of your code, whenever you save data to mysql, you invalidate the redis cache as well.

*You can use streams like http://debezium.io/ to capture changes in the database, and take neccessary actions like invalidating cache.


Q: Why is the $_SESSION array not being changed? I am having trouble assigning a variable to an array within the $_SESSION array.
It looks like it is assigning, but when I do a print_r at the end of the program the $_SESSION variable appears unchanged.
Here is the code.
<?php
session_start();

print_r($_SESSION[cart_array]);

$NewGroupName="NewGroupName";

foreach($_SESSION[cart_array] as $row) {

   if ($row['groupId'] == "26141"){
     echo "The initial GroupName is" . $row['GroupName'] . "
";

     echo   "The GroupName should be " . $NewGroupName."
";

     $row['GroupName']   = $NewGroupName;
     echo   "The actual GroupName is " . $row['GroupName']."
";

   }
}
print_r($_SESSION[cart_array]);
?>

The first print_r:
Array ( [0] => Array ( [groupId] => 26141 [GroupName] => 'Crystal Farm - Ten Yard Case Pack' [StylePatternColor] => A-CF-10 [Price] => 5.65 [StandardPutUp] => 320 [Discount] => 0 [DiscountText] => [StkUnit] => YDS [ListPrice] => 5.65 [Quantity] => 1 [PromiseDate] => 10/01/2017 [DoNotShipBefore] => 02-01-2017 [ColorName] => 32 Ten Yard Bolts [PatternName] => [SKUDescription] => [KitPerYardDiscount] => False [KitPerYardDiscountText] => False [Kit] => False ) [] => Array ( [DoNotShipBefore] => ) )

The assingment seems to work:
The initial GroupName is'Crystal Farm - Ten Yard Case Pack'
The GroupName should be NewGroupName
The actual GroupName is NewGroupName

But, the final print_r shows we have not changed the value of GroupName.
 Array ( [0] => Array ( [groupId] => 26141 [GroupName]
=> 'Crystal Farm - Ten Yard Case Pack' [StylePatternColor]
=> A-CF-10 [Price]
=> 5.65 [StandardPutUp]
=> 320 [Discount]
=> 0 [DiscountText]
=> [StkUnit]
=> YDS [ListPrice]
=> 5.65 [Quantity]
=> 1 [PromiseDate]
=> 10/01/2017 [DoNotShipBefore] => 02-01-2017 [ColorName]
=> 32 Ten Yard Bolts [PatternName] => [SKUDescription] => [KitPerYardDiscount] => False [KitPerYardDiscountText] => False [Kit] => False ) []
=> Array ( [DoNotShipBefore] => ) )

Any help would be appreciated.

A: You don't change $_SESSION anywhere in your code. The foreach just exposes a copy of each element. You could change it by using a reference &:
foreach($_SESSION['cart_array'] as &$row) {

Also, notice that quotes are required for string indexes $_SESSION['cart_array'].  If you had error reporting on you would see a Notice for Undefined constant: cart_array.

A: From php.net:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>


Q: MySQL on udp port I have searched around on the internet but could not find any satisfying answer. Can someone please guide, here are my confusions/questions.

*

*Can we run mysql on udp port instead of default tcp port?

*If running mysql on udp is possible, what are pros and cons?

A: It's not possible to run MySQL on UDP port, or using ICMP informational messages. Just because of it's design - it's a TCP application. To run it on UDP port it has to be rewritten in it's network part from scratch, to use UDP instead of TCP, which it's using now. Since it's opensource, it's pretty doable, but nobody so far have tried it. Mostly because nobody needs to run it on UDP.


Q: Kotlin delegate's ReadOnlyProperty with generic type value dose not cast correctly in getValue I am expecting to see the output
black
white

with below code
package delegate

import kotlinx.coroutines.runBlocking
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty

open class Color(private val name: String) {
    override fun toString(): String {
        return name
    }
}

class Black : Color("black")
class White : Color("white")

class ColorCollection {
    private val black = Black()
    private val white = White()
    val list = listOf(black, white)
}

class Palette {
    val black: Black by ColorDelegate()
    val white: White by ColorDelegate()
    val colorCollection = ColorCollection()
}

class ColorDelegate<T> : ReadOnlyProperty<Palette, T> {
    override fun getValue(thisRef: Palette, property: KProperty<*>): T {
        return thisRef.colorCollection.list.mapNotNull { it as? T }.first()
    }
}

fun main() = runBlocking {
    val palette = Palette()
    println(palette.black)
    println(palette.white)
}

However, I only get black output and then Exception in thread "main" java.lang.ClassCastException: delegate.Black cannot be cast to delegate.White.
I found that with this line thisRef.colorCollection.list.mapNotNull { it as? T }, I am expecting it only returns the value in the list that can be safely cast to the generic type, otherwise return null. For example, when accessing black delegated property in Palette, I should only see 1 black element returned by thisRef.colorCollection.list.mapNotNull { it as? T },It actually returns two (black and white). it as? T somehow always works regardless of what T is. I also tried putting a breakpoint at that line, tried "abcdef" as T?, it also works, which I expect to see cast exception that String cannot be cast to Black...

Is this a bug...?

A: Remember that Type Erasure is a thing in Kotlin, so the runtime does not know what the T in it as? T, and hence cannot check the cast for you. Therefore, the cast always succeeds (and something else will fail later down the line). See also this post. IntelliJ should have given you an "unchecked cast" warning here.
So rather than checking the type using T, you can check the type using the property argument:
class ColorDelegate<T> {
    operator fun getValue(thisRef: Palette, property: KProperty<*>) =
        // assuming such an item always exists
        thisRef.colorCollection.list.first {
            property.returnType.classifier == it::class
        } as T
}

fun main()  {
    val palette = Palette()
    println(palette.black) // prints "black"
    println(palette.white) // prints "white"
}

Here, I've checked that the class of the returnType of the property (i.e. the property on which you are putting the delegate) is equal to the list element's runtime class. You can also e.g. be more lenient and check isSubclassOf.
Do note that this wouldn't find any element in the list if the property's type was another type parameter, rather than a class, e.g.
class Palette<T> {
    ...
    val foo: T by ColorDelegate()
    ...
}

But alas, that's type erasure for you :(

A: This is due to type erasure with generics. Casting to a generic type always succeeds because generic types are not known at runtime. This can cause a runtime exception elsewhere if the value is assigned to a variable of a concrete mismatched type or a function it doesn't have is called on it.
Since casting to generic types is dangerous (it silently works, allowing for bugs that occur at a different place in code), there is a compiler warning when you do it like in your code. The warning says "unchecked cast" because the cast occurs without type-checking. When you cast to a concrete type, the runtime checks the type at the cast site and if there is a mismatch it immediately throws ClassCastException, or resolves to null in the case of a safe-cast as?.
Info about type erasure in the Kotlin documentation


Q: python regex capturing array indicies and brackets this issue has me scratching my head. I have not yet been able to construct a regex which returns the captured groups I require. I've also been working with Pythex, and experimentation has not yet been successful.
Example source string: 'token[0][1]'
I'm interested in a regex which will capture each of the array offsets, including the square brackets in separate groups. e.g. g1 = '[0]', g2 = '[1]', for example.
The closest I can get is something like this:
r'(\[[\w]\])*'

Of course, this does not work. Any tips would be appreciated. Thanks.

A: Use r'(\[\d+\])' should capture what you want, like this:
import re

s = 'token[0][1]'

g1, g2 = re.findall(r'(\[\d+\])', s)

print g1, g2
[0] [1]


Q: Insert rows with unique numeric ID I have table dbo.Register with unique ID column. I need to insert many rows into this table with, but any with unique identifier, like:
INSERT INTO dbo.Register (ID, Name, State, Comment)
Select
NEWID(),
Name,
State,
Comment
From dbo.OtherTable

But NEWID() returns long string of characters: 2D0D098E-2FFE-428A-B4EF-950C89FFF83A, but i need unique integer ID. e.g next free ID in this table.
Edit.
I can't modify this table. I only need to insert rows into current structure.
Sample Records:
+--------+------------+--------------+------------+
|   ID   |    Name    |    State     |  Comment   |
+--------+------------+--------------+------------+
| 153299 | Zapytania  | Przyjeto     | NieDotyczy |
| 153300 | Zapytania  | Przyjeto     | NieDotyczy |
| 153301 | Zapytania  | Przyjeto     | NieDotyczy |
| 153302 | Zapytania  | Przyjeto     | NieDotyczy |
| 153303 | Zapytania  | Przyjeto     | NieDotyczy |
| 153304 | Dyspozycje | Zakonczono   | NieDotyczy |
| 153305 | Zapytania  | DoRealizacji | NULL       |
| 153306 | Zapytania  | Przyjeto     | NieDotyczy |
| 153307 | Zapytania  | Przyjeto     | NieDotyczy |
| 153308 | Dyspozycje | Przyjeto     | NieDotyczy |
+--------+------------+--------------+------------+

Definition of ID column already is:
[ID] [int] IDENTITY(1,1) NOT NULL,

A: You can do this by doing like below
DECLARE @ID INT;
SELECT @ID=ISNULL(MAX(ID),0) FROM dbo.Register
--Isnull to handle first record for the table

INSERT INTO dbo.Register (ID, Name, State, Comment)
Select
ROW_NUMBER() OVER(ORDER BY(SELECT 1))+ @ID,
Name,
State,
Comment
From dbo.OtherTable

Per the edit there is no need of specifying the column in Insert list. You can skip the column and do INSERT & SELECT.
INSERT INTO dbo.Register ( Name, State, Comment)
Select
    Name,
    State,
    Comment
    From dbo.OtherTable

Better you need to look at IDENTITY (Property) (Transact-SQL)

A: Run next script ....
ALTER TABLE dbo.Register
DROP column ID

ALTER TABLE dbo.Register
add ID int identitity (1, 1)

INSERT INTO dbo.Register (Name, State, Comment)
Select
 Name,
 State,
 Comment
From dbo.OtherTable

EDIT:
With new info, just do
INSERT INTO dbo.Register (Name, State, Comment)
Select
    Name,
    State,
    Comment
From dbo.OtherTable

ID Column will take care of itself ...

A: If you can't make ID an IDENTITY column which would be a much better idea, you could instead use a SEQUENCE.
CREATE SEQUENCE [dbo].[RegisterId]
    START WITH 153309
    INCREMENT BY 1;
GO

and then,
INSERT [dbo].[Register]
    (
        [ID],
        [Name],
        [State],
        [Comment]
    )
SELECT
        NEXT VALUE FOR [dbo].[RegisterId] [ID],
        [Name],
        [State],
        [Comment]
    FROM
        [dbo].[OtherTable];

alternatively, if you can't change the schema you could use a temporary table to make use of an IDENTITY column,
DECLARE @maxId INT = SELECT MAX([ID]) + 1 FROM [dbo].[Register];

DECLARE @createTemp NVARCHAR(4000) = N'
CREATE TABLE #TempRegister
(
    [ID] INT IDENTITY(' + CAST(@maxId, NVARCHAR(14)) + ', 1),
    [Name] NVARCHAR(?),
    [State] NVARCHAR(?),
    [Comment] NVARCHAR(?)
);';

EXEC sp_executesql @createTemp;
GO

INSERT #TempRegister
    (
        [Name],
        [State],
        [Comment]
    )
SELECT
        [Name],
        [State],
        [Comment]
    FROM
        [dbo].[OtherTable];

INSERT [dbo].[Register]
SELECT
        [ID],
        [Name],
        [State],
        [Comment]
    FROM
        #TempRegister;

DROP TABLE #TempRegister;


Q: Adding a project to Xcode Workspace like CocoaPods I like Xcode workspaces and CocoaPods. So I want to stick to them and their setup and want to create a workspace, containing other projects, like this structure:
- MyApp.workspace
  |-- MyApp.project
  |-- Pods.project
  |-- AnotherApp.project

Most of the posts about adding dependencies to existing projects suggests nesting them, like:
- MyApp.workspace
  |-- MyApp.project
      |-- AnotherApp.project
  |-- Pods.project

But, I'm not sure if this is the correct approach. I think I should put them to the same level as both Pods and AnotherApp provide libs/reusable codes to MyApp.
Which one do you suggest and why?
And also if you provide any walkthroughs or tutorials about the first setup I would be very appreciated, because most of them gives examples like the second one but without the workspace.

A: I am not sure if I fully understand the question so please forgive if I miss something.
I desired a similar setup, multiple projects in a workspace, but all managed by Cocoapods. I needed the projects to link to each other. My motive was promoting MVC separation, so I had an App project (view), a Controller project, a Model project. The shell of a project is here: https://github.com/premosystems/iOSMVCTemplate/tree/1.0/MVC-Example/iOS/MVCApp
Here are the basic steps:

*

*Create your projects, and add a podspec to each one. (e.g. controller podspec like this one: https://github.com/premosystems/iOSMVCTemplate/blob/1.0/MVC-Example/iOS/MVCApp/Controller/ProximityController/ProximityController.podspec)

*Add a Podfile that links all of the podspecs together. https://github.com/premosystems/iOSMVCTemplate/blob/1.0/MVC-Example/iOS/MVCApp/Podfile

*And of course pod install :)
Be sure to reference the podspecs you create in the Podfile using the :path=> development directive before they are referenced by any podspecs so cocoapods will know not to look in the public repository.
I have been using this a month or so, and it works pretty well. Only drawback is that indexing and compile time take longer than I would like, and pod update is really slow. Before adding and new files, .h, .m to any podspecs you must run pod update.
Best of luck!


Q: UIViewController isEditing - Property observer doesn't work I was trying to implement property observers on my custom UIViewController but I noticed it was not working with the isEditing property.
Do you guys have an idea why?
class MasterViewController: UIViewController {

    // MARK: - Properties

    override var isEditing: Bool {
        didSet {
            print("VC is editing")
        }
    }
}

A: According to the documentation for isEditing

Use the setEditing(_:animated:) method as an action method to animate the transition of this state if the view is already displayed.

And from setEditing(_:animated:)

Subclasses that use an edit-done button must override this method to change their view to an editable state if isEditing is true and a non-editable state if it is false. This method should invoke super’s implementation before updating its view.

TL;DR
You'll want to override setEditing(_:animated:) instead.

A: It's for those who can't find any example how setEditing works.

SWIFT 5 :

override func setEditing(_ editing: Bool, animated: Bool) {
        if yourTableView.isEditing == true {
            yourTableView.isEditing = false //change back

        } else {
            yourTableView.isEditing = true // activate editing
            editButtonItem.isSelected = true // select edit button
        }
    }


Q: Add extra fields via hook woocommerce_default_address_fields? We want to add extra fields to the billing and shipping addresses to the account of registered customers (users with Customer role). We also want the user to be able to edit those extra fields in their settings panel, under  ”My Account” -> ”Addresses” -> ”Edit"
I found a way to do this, namely to implement the hook woocommerce_default_address_fields, and append extra address fields there. When doing so I noticed the fields were saved to the user account, and showed up in the checkout.
So this seems to work. Now I wonder if this is the best way to add extra address fields?


Q: How can I make PHP think that the files are in a parent directory? As the title says, how can I make PHP think that the files are in a parent directory?
For example, my file structure looks like this:
- website
- - css
- - js
- - images

And I want PHP to think that the directory js is always in ../js (parent directory)? Can this be done with .htaccess?
Thanks.

A: You can place this rule in /website/js/.htaccess:
RewriteEngine On
RewriteBase /website/js/

RewriteRule ^(.*)$ /js/$1 [L]

A: You can change the current directory to something like this:
<?php
    // Get current directory
    $cur_dir = getcwd();

    //change the dir
    chdir("../js");

    //do something here

    //back to your main current dir if you have still something to do
    chdir($cur_dir);
?>


Q: VS Code doesn't process Erlang Makefile I'm working on an old erlang code that uses Makefiles to compile.
The makefile defines some "include" paths:
# Erlang include directories.
HRL_INCLUDE_DIRS = \
    ../include

My module imports modules from that path and uses it:
-include("logger.hrl").

VS Code doesn't seem to find this file (red squiggly line under the include statement and function calls.), because logger should have relative or absolute path.
The Makefile does the magic behind the scenes but VS Code doesn't read it.
How to configure VS Code to read the makefile?

A: The question is where the red squiggly line is coming from. Are you using the erlang-ls extension? If so, you probably need to configure include_dirs in an erlang_ls.config file in the root of your project.
include_dirs:
  - "path/to/include"


Q: How do you specify a minimum required version with the Mozilla addon-sdk cfx tool? Building a traditional Firefox extension, you would set the minVersion field in the install.rdf. Since that is abstracted away by package.json and cfx, is there any way to set a minVersion?
Motivation:
Because of certain changes to behavior in the contextMenu API, my add-on only works as expected from a certain versions of the Addon-SDK and upwards. I'd like to enforce this constraint.

A: From the Add-on SDK docs
Changing minVersion and maxVersion Values