text:
Q: Swift 3 - How to remove all Subviews from Superview as well as Array I currently have a double for-loop that creates an X by Y grid of UIView CGRect squares. The loop also adds each UIView/Square of the grid to a 2D array allowing me to access each Cell of the grid and alter color/positioning by the index values of the loop.
The loop seems to work fine and displays the Cells/Squares perfectly, however after a while I want to remove all of the squares and also empty the array (but not entirely delete) to make room for a new next grid (which may be of a different size). I created a function to remove all the views from the superview.
This is how I am creating each "Cell" of the grid and placing each into the 2D array:
let xStart = Int(size.width/2/2) - ((gridSizeX * gridScale)/2)
let yStart = Int(size.height/2/2) - ((gridSizeY * gridScale)/2)

let cell : UIView!
cell = UIView(frame: CGRect(x: xStart + (xPos * gridScale), y:yStart + (yPos * gridScale), width:gridScale, height:gridScale))

cell.layer.borderWidth = 1
cell.layer.borderColor = UIColor(red:0.00, green:0.00, blue:0.00, alpha:0.02).cgColor
cell.backgroundColor = UIColor(red:1.00, green:1.00, blue:1.00, alpha:0)

cell.tag = 100

self.view?.addSubview(cell)

gridArray[xPos][yPos] = cell

The 2D array is being created on application load like so:
gridArray = Array(repeating: Array(repeating: nil, count: gridSizeY), count: gridSizeX)

I have tried to search for a solution to remove the UIViews from the superview however all answers from other Questions don't seem to work for me. I have tried to add cell.tag = 100 to each UIView and then remove all UIViews with the Tag Value of 100 like:
for subview in (self.view?.subviews)! {
    if (subview.tag == 100) {
        subview.removeFromSuperview()
    }
}

However no luck. I have also tried to use this method:
self.view?.subviews.forEach({
    $0.removeConstraints($0.constraints)
    $0.removeFromSuperview()
})

The main differences I notice in my code compared to other peoples answers is that I have "?" and "!" at places in the code. I researched about what they mean and understood most of it however I still do not know how to fix my code because if it, and feel as though that is the issue. All I know is that the attempts to remove the UIViews from the superview does not work, and without the "?" and "!"s the code doesn't run at all.

A: How about to create tag for each cell you are using for example:
    //Init value for for the tag.
    var n = 0

    func prepareCell() -> UIView {
             let xStart = Int(size.width/2/2) - ((gridSizeX * gridScale)/2)
             let yStart = Int(size.height/2/2) - ((gridSizeY * gridScale)/2)

         let cell : UIView!
         cell = UIView(frame: CGRect(x: xStart + (xPos * gridScale), y:yStart + (yPos * gridScale), width:gridScale, height:gridScale))

         cell.layer.borderWidth = 1
         cell.layer.borderColor = UIColor(red:0.00, green:0.00, blue:0.00, alpha:0.02).cgColor
         cell.backgroundColor = UIColor(red:1.00, green:1.00, blue:1.00, alpha:0)

        cell.tag = n

        //Each cell should have new value
        n += 1

        return cell
}

And now remove required views.
func removeViews() {
    for z in 0...n {
        if let viewWithTag = self.view.viewWithTag(z) {
           viewWithTag.removeFromSuperview()
        }
        else {
           print("tag not found")
        }
    }
}

Example that is working in the playground:
var n = 0

let mainView = UIView()

func createView() -> UIView {
    let view = UIView()
    view.tag = n
    n += 1
    return view
}

for i in 0...16 {
    mainView.addSubview(createView())
}

func removeViews() {
    for z in 0...n {
        if let viewWithTag = mainView.viewWithTag(z) {
            viewWithTag.removeFromSuperview()
             print("removed")
        }
        else {
            print("tag not found")
        }
    }
}

A: You might be overlooking a much, much simpler way to do this...
You have built a 2D Array containing references to the "cells" as you populated your view. So, just use that Array to remove them.
// when you're ready to remove them
for subArray in gridArray {
    for cell in subArray {
        cell.removeFromSuperview()
    }
}

// clear out the Array
gridArray = Array<Array<UIView>>()


text:
Q: Github in Rstudio giving 'The directory name is invalid' I have a github repository that I want to connect to Rstudio. I can clone the repository without problem using the new project button and using the version control, but then cannot pull, push, diff, or look at history.
To be more specific: When I click on any of the actions related to version control from within Rstudio I get a pop-up error window with the message 'The directory name is invalid', with only an 'OK' button. Pressing OK closes the error message and also the related window for history, push, etc.
The directory name and the repository name do not have any non-ascii characters. I am using Rstudio version 0.99.486 on windows 7.
This is not a problem with git, since I can pull, push and diff from the command-line without any errors.
I should probably mention that I am not using the public github repository but a business github.
A similar question (39698320) was asked without an answer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is "latest activity" = today on some questions when all the activity happened months ago? I've noticed that when I scroll through the "Questions" for Superuser.com that sometimes questions show up as "recent" when from my perspective they are any but recent.
By that I mean I look at the date for the question, the answers, and the comments, and all of them are months ago. Yet the summary latest activity for the question will have the status today.
Here's a link to one example: Disable internal display on Macbook Pro without closed lid mode? Perhaps I'm just overlooking the latest activity in which case please just show me where I went wrong. But I didn't see anything newer than Dec 2009.
What's up with this? Because this happens I've found myself wasting time trying to answer questions that no one probably gives a fig about any longer because so much time has passed.

A: Clicking the entry for "latest activity" will always navigate you straight to when that last activity was.
If the last activity brings you to the question post, and yet the question hasn't been edited (or silently converted to CW), then one scenario is a deletion or activity inside of a deleted post. Without being 10k, you can't see the deleted post, so it instead brings you to the top.
Also, if the Community User bumps a question, this would also cause "latest activity" as the current date, yet direct you at the question post. But you can only confirm this if you can see the question on the front page, by manually locating it through surfing the Active sort of the Questions page, or if you're a 10k user who isn't directed to the deleted post.
The example you linked was in fact bumped by the Community User. The timestamp on the bump is 2010-06-26 21:00:04Z, which matches the timestamp for the "latest activity".


text:
Q: REST - how design an URI with composite keys? I have a question about how design a resource URI with composite keys.
I have a resource called freight that has 4 keys/ids: partner ID, initial zipcode, final zipcode and weight.
Actually my resource was designed to have an incremental ID generated by database, but this approach is not so good to API consumers, for example if a consumer/partner needs to update a freight info they have to do:
GET freight?initialZipcode={VALUE}&finalZipcode={VALUE}&weight={VALUE}
The response of the operation above would be the freight ID, so finally they can update the info:
PUT freight/{ID}
The partner ID is implicit by the authentication mechanism.
For me it seems strange force the partners to obtain the freight ID before update the info.
So my question is: how can I design this URI?
PUT freight/initialZipcode/{VALUE}/finalZipCode/{VALUE}/weight/{VALUE}
Have I to consider the design above?
Another question: is a good practice to embedded the partnerId in authentication mechanism? I know the pros (easy to consumers) and cons (cache, impossibility to share an URI, etc), but I don't know if generally is a good or bad practice.
Thanks!

A: There is nothing wrong with
PUT freight?initialZipcode={VALUE}&finalZipcode={VALUE}&weight={VALUE}

Query parameters are part of the resource identification too.
Path parameters are useful for defining resources that fit nicely in a hierarchy.  In your case the resource doesn't fit well in a hierarchy, so don't try and squeeze the parameters into path segments.
The only challenge is what to do when the client re-arranges the order of the query params.  Do you you treat it as the same resource, or do you 404?  If you are not caching the GET responses then it probably doesn't matter.
If you provided your client with a URI template for them to fill in then there is less chance that they will give you the params in the wrong order.

The other option, if you go with your original suggestion is that your GET returns a redirect and a Location header to a URI with the freight ID. e.g.
GET freight?initialZipcode={VALUE}&finalZipcode={VALUE}&weight={VALUE}
=>
302 See Other
Location:  freight/1232321322

By doing this, your client doesn't have to know anything about the freight ID, it can just grab the location header, and follow the redirect to do a GET, or do a PUT directly against whatever URI is in the Location header.  This means that if you decide you don't like exposing the ID in the future, you can change the URI without breaking any clients.


text:
Q: Provide Response to user who call the RestApi without waiting for the microservice rest call using spring boot I am developing a web API for an application. I had got a situation where the user will send a few data to my API. After processing the data I have to forward a few data to other API.
But I don't want to concentrate on the response from the second API to where I had called.
After calling the second API I want to send my response to the user without waiting for the second API response.
Can anyone tell me how to handle this situation?
My API is written in JAVA spring boot REST, The Second API to where am calling is in PYTHON.

A: @Async will make it execute in a separate thread, i.e. the caller will not wait for the completion of the called method.

Limitations

*

*it must be applied to public methods only

*self-invocation – calling the async method from within the same class
– won't work

Example:
Spring Doc, Example 1, Example 2


text:
Q: How to check if Attribute of entity is "secured" only using crm 4.0 assemblies? (field level security) In Dynamics 2011 installation i have an Attribute with "Secured" option enabled. And I develope a software, where I use only assemblies from crm 4.0.
With CRM 4.0 assemblies I can retrieve permissions (for particular user), but not prohibitions (i achieve this just quering following dynamic entities:  fieldpermission, fieldsecurityprofile). The fact, whether the field is secure i can only read from Metadata and i need crm 2011 assemblies for it (in CRM 4.0 AttributeMetadata class has no property "isSecured").
My Question is: how can i retrive, if the Attribute has field "isSecured" enabled, not using Metadata from CRM 2011, only using CRM 4.0 assemblies ? Maybe i schould query something? Or use SQL (i can use only webservices, i have no direct access to dynamics database)?

A: Why can you not use the 2011 assemblies?
If you are forced to stick with CRM 4 assemblies, then I would do a fiddler trace of what the 2011 assemblies do and then execute a similar SOAP XML request.


text:
Q: ¿Como mostrar un GIF en un PictureBox usando hilos en C#? Tengo dos Windows Form, el principal tiene en el medio de la pantalla un PictureBox que a su vez este contiene un GIF de una animación "cargando". La idea es que cuando el segundo Form se le active el evento load se cargue primero el método donde tengo el hilo, posteriormente se ejecute todo el código restante (métodos,etc) y al final se ejecute otro método que cambiara la propiedad visible  a false.
Me explico con el código:
    private void FrmHijo_Load(object sender, EventArgs e)
    {
       FrmPrincipal.Instancia.mCarga();
       /*---------------------Codigo-----------------------------*/
       FrmPrincipal.Instancia.mDefault();
     }

Este es el método mCarga():
public void mCarga()
  {
      ThreadStart delegado = new ThreadStart(mostrasPTBX);
      Thread hilo = new Thread(delegado);
      hilo.Start();
      Cursor.Hide();
  }

Este es el método al que apunta el delegado:
public void mostrasPTBX()
  {
      FrmPrincipal.Instancia.ptbImagenCarga.Visible = true;
      FrmPrincipal.Instancia.ptbImagenCarga.BringToFront();
  }

Y este es el método mDefault que solo oculta el PictureBox:
public void mDefault()
   {
      FrmPrincipal.Instancia.ptbImagenCarga.Visible = false;
      FrmPrincipal.Instancia.ptbImagenCarga.BringToFront();
      Cursor.Show();
   }

El problema esta en que al momento de abrir el FormHijo y se activa el evento Load no pone visible el PictureBox simplemente me oculta el Cursor como lo indique en el mismo método, ya intente poniendo un MessageBox en el método mostrasPTBX() y si me los mostro al carga el FormHijo. Otra cosa, intente hacerlo sin hilos solo llame el metodo mostrasPTBX() dentro del método  mCarga() pero igual tuve el mismo problema. Probablemente el problema sea ajeno a los hilos ademas que soy relativamente nuevo programando. Espero que me puedan ayudar gracias.


text:
Q: How to Check the Developer Office tools for Visual Studio 2015 is installed in the machine, using launch condition I have an Installer for our product which requires "Developer office tools for Visual Studio 2015" to be installed in the machine.
How can I add Launch condition to the installer to check whether "Developer office tools for Visual Studio 2015" is installed or not in the machine.
Thanks in advance for your suggestions.
Regards,
Devaraj


text:
Q: 1px DropShadow Is Thicker on Bottom I have a rounded rectangle and I am trying to apply a 1px blur, 1px vertical offet drop shadow to it. My problem is that the bottom drop-shadow looks significantly thicker then the one ones on the side. Is there a way to correct this so the bottom shadow will be the same width as the ones on the side? I thought of using outline but that would not work due to my rounded corners. Also, I do not want a border on the top of my rectangle.
box-shadow: 0 1px 1px #000;
http://jsfiddle.net/Zw4QA/317/

A: Try setting your box shadow to:
box-shadow: rgba(0,0,0,0.8) 1px 1px 1px, rgba(0,0,0,0.8) -1px 1px 1px, rgba(0,0,0,0.8) 0 1px 1px;

You can use multiple box shadows and negative values to pull them to the left or top when needed.


text:
Q: ANDROID Swipe-able Tabs I've swipe-able tabs in one activity. When a user clicks on an EditText field to enter , I launch another activity to take the input and then I revert back to the tab activity. However, whenever I return to this activity with tabs, only the 1st tab is shown.
How do I display a different tab when I revert back to this activity after taking input from a different activity? Ideally, I'd want to return to the tab/fragment from which the intent was passed.
EDIT : FIXED
This piece of code helped me solve this issue.
int pos = bundle.getInt("pos");
TabLayout.Tab tab = tabLayout.getTabAt(pos);
tab.select();

A: In Activity when user clicks the edittext should Lauch another activity.
 case R.id.btn_edit_text_clicked:
 Intent i = new Intent(this,  SecondActivity.class);
                startActivityForResult(i, 1);

In onActivityResult()
if (requestCode == 1) {
        if(resultCode == RESULT_OK){
            // do your stuff
        }
    }

After user types the text in edit text of SecondActivity.
Intent intent = new Intent();
intent.putExtra("ANY_VARIABLE_NAME", [YOUR_EDIT_TEXT_VALUE]);
setResult(RESULT_OK, intent);
finish();

A: This piece of code helped me resolve the issue.
 int pos = bundle.getInt("pos");
 TabLayout.Tab tab = tabLayout.getTabAt(pos);
 tab.select();


text:
Q: Read value from multiple similar tags with attributes I have an .xml file which looks like this:
<Products>
<Product>
    <Denumire>Carcasa rigida THULE Legend GoPro, black (TLGC101)</Denumire>
    <Cod>TLGC101</Cod>

    <Atribut denumire="Tip">geanta/husa</Atribut>
    <Atribut denumire="Compatibilitate">GoPro</Atribut>
    <Atribut denumire="Dimensiuni">150 x 210 x 80 mm (exterior), 35 x 185 x 125 mm (interior)</Atribut>
    <Atribut denumire="Greutate">0.24 kg</Atribut>
    <Atribut denumire="Culoare">negru</Atribut>
    <Atribut denumire="Altele">interior spuma EVA</Atribut>
    <Atribut denumire="Cod">TLGC101</Atribut>
</Product>

I just can't find a way to extract the values of "Atribut" tags ("geanta/husa", "GoPro" and so on). My code looks like this:
    $products = simplexml_load_file("http://abc.xyz/feed.xml");
foreach($products->Product as $prod)
    {
        foreach($prod->Atribut as $key=>$atr)
            {
                //extract the value for "denumire" attribute
                $nume_atribut = (string)$atr->attributes()[0];

                //get the value of the "Atribut" tag
            }
    }

Dumping the $prod->Atribut gives me:
object(SimpleXMLElement)#6 (8) {
  ["@attributes"]=>
  array(1) {
    ["denumire"]=>
    string(3) "Tip"
  }
  [0]=>
  string(11) "geanta/husa"
  [1]=>
  string(5) "GoPro"
  [2]=>
  string(58) "150 x 210 x 80 mm (exterior), 35 x 185 x 125 mm (interior)"
  [3]=>
  string(7) "0.24 kg"
  [4]=>
  string(5) "negru"
  [5]=>
  string(18) "interior spuma EVA"
  [6]=>
  string(7) "TLGC101"
}

... while dumping $prod->Atribut[0] gives:

object(SimpleXMLElement)#8 (1) {   ["@attributes"]=>   array(1) {
      ["denumire"]=>
      string(3) "Tip"   } }

Many thanks!

A: Just use method __toString of SimpleXMLElement directly:
$atr->__toString()

or use type casting (actually it will use __toString internally):
(string)$atr


text:
Q: Win7-64 %windir%, %path% environment variables disappear, can't reload I am having recurring intermittent problems with "losing" my environment variables, most onerously %windir% and %path%. The problem occurs when I have locked the keyboard and log back in. Rebooting the system (cold- and warm-boot) does not reliably bring them back, but eventually multiple iterations of booting has (so far) brought everything back.
If I open a command window and type echo %windir% and echo %path% and find that the variables exist and are properly defined, and if I leave that command window open, I can leave my system running for days without a problem.
I have captured the results of set to list all envars, both when the system is broken, and when it is fixed. The broken list is much shorter (%windir% is not even defined, %path% contains the definition from registry HKCU\Environment, but not from HKLM\SYSTEM\CurrentControlSet\Control\SessionManager\Environment).
I am guessing that the boot-up process is getting sidetracked.
Spent all morning with Geek Squad but they had no concrete suggestions. (They did suggest "taking the computer back to a previous restore point", but I fear that could cause more problems... and they didn't have confidence it would help.)
Do I have any options beyond possibly reinstalling everything?

A: I did finally find the answer, and although I understand this subject was closed by the commenter, I thought others might want to know. This link explains it pretty well:
https://superuser.com/questions/355594/windows-7s-path-and-environment-variables-are-corrupted
The short version is this: My system PATH exceeded a Windows maximum of 2048 bytes (it was more than 2200 bytes long). When that happens, the boot process fails to instantiate PATH and WINDIR.
The "fix" was to run c:\windows\system32\systempropertiesadvanced.exe from a command prompt (because without WINDIR, you can't open the Control Panel app for environment variables), and manually extract anything from the PATH I thought I could live without, until I whittled the PATH string down to under 2048 bytes.


text: Q: Asana API in python Im doing an API, and I can bring all the projects, task and subtask from my workspace. But i can't bring the Assignee and anothers importants fields. I want to do a table with all the asana data from all my task. If someone can help me. Thanks.


text:
Q: How do we annotate text from images if we only want that object detector to detect Urdu text in the future? I have extracted frames from news videos and cleaned them by removing the frames containing text in English and keeping the frames having Urdu text. But there is still a little bit of English text in frames(like channel and program name etc.) that I don't want to be detected by the text detector. How should I annotate these frames:

*

*Should I only annotate Urdu text (so that my text detector doesn't detect English text)

*Should I annotate both Urdu and English text (But in this way of annotation text detector will also detect English)
Which way will be suitable for annotating frames to detect only Urdu text in future?
Sample Frame


text:
Q: Can a JSON data structure be directly saved as a CouchDB document? I'm a Python programmer with experience using the json module. I've just meet CouchDB and seems very interesting.
I wonder know if JSON data structures can be directly saved as a CouchDB document.
Thanks,

A: You only need to provide an unique ID that will be used as part of the resource name (URI) when PUTting it or you use POST and take an auto-generated ID. You can use any JSON, that does not contain _id and _rev, because these fields are reserved for CouchDB itself.

A: couchDB is inteded to work with JSON.
have a look here: http://wiki.apache.org/couchdb/HTTP_Document_API#POST
you just POST a json document for storage.

A: CouchDB will accept any valid JSON Object as a document.


text:
Q: Java - Regular Expression for tokenzing a string based on white spaces not inside "" I am working on a problem which requires me to tokenize a string on the basis of white spaces except those which occur inside quotation marks. For example for the string :
printf ( " the quick brown fox " ) ;

The tokens generated should be:
printf, (, ", the quick brown fox , ", ), ;

So far I came up with the following code but it does not seem to do what I intend it to.
String m = "printf ( " the quick brown fox " ) ;"

String [] tokens = m.split("([^\"])(\\w)*(\\s)(\\w)*([^\"])");

Any help would be really appreciated !


text:
Q: List iptables rules as append command A while back I was watching over the shoulder of a Linux guru and he issued a command that listed all the iptables rules in the format of the append commands you would need to issue in order to build them, but despite all my googling and man page searching I can't figure out what he did.
For example if the output from iptables -nL INPUT was:
Chain INPUT (policy DROP)
num  target     prot opt source               destination
1    ACCEPT     tcp  --  0.0.0.0/0            192.168.0.1           tcp dpt:80

The output from the command I'm looking for would be something like:
1  -A INPUT -i eth0 -p tcp --dport 80 -d 192.168.0.1 -j ACCEPT

I seem to remember that it was just another option passed into the standard iptables -L command, but I could be wrong.  Does anyone know of a command to accomplish this?

A: You can get similar output by using iptables-save command:
*nat
:PREROUTING ACCEPT [381:53396]
:INPUT ACCEPT [286:22260]
:OUTPUT ACCEPT [1462:92025]
:POSTROUTING ACCEPT [1450:91003]
-A POSTROUTING -s 192.168.123.0/24 ! -d 192.168.123.0/24 -p tcp -j MASQUERADE --to-ports 1024-65535
-A POSTROUTING -s 192.168.123.0/24 ! -d 192.168.123.0/24 -p udp -j MASQUERADE --to-ports 1024-65535

There are numbers and some extra info, but you can remove them by writing something like that:
iptables-save | grep -v -e "^[*:#]" -e "COMMIT" | cat -n

And the output:
     1  -A POSTROUTING -s 192.168.123.0/24 ! -d 192.168.123.0/24 -p tcp -j MASQUERADE --to-ports 1024-65535
     2  -A POSTROUTING -s 192.168.123.0/24 ! -d 192.168.123.0/24 -p udp -j MASQUERADE --to-ports 1024-65535

A: It's super simple:
iptables -S
gives you exactly what you ask for.


text:
Q: Необходимо получить список пользователя вконтакте по uid Я пробовал использовать метод friends.get. Но мне возвращается список моих друзей, вне зависимости от uid. В теории должны возвращаться друзья указанного пользователя.
Общая задача: Есть список пользователей. Необходимо получить кол-во друзей и подписчиков, а так же кол-во "собачек".
Я не понимаю, что я делаю не так
import requests
from VK_parsing_data import offset

i = 0
for user in users:
    print(user)
    member_request_params = (
        ('user_ids', user),
        ('order', 'name'),
        ('count', 1000),
        ('offset', offset),
        ('fields', 'last_seen'),
        ('version', 5.74))
    r = requests.get('https://api.vk.com/method/friends.get', params=member_request_params).json()
    print(user, r)

A: Неверно написал запрос. Необходимо передавать в запрос user_id,  а не user_ids.


text:
Q: Why SVG resizes to width but not to height? I'm trying to understand why my SVG will resize when I change the width of its parent but it won't resize when I change the height.
I just made a very simple jsFiddle. You can try resizing the little window at the bottom right corner.
From what I understand, it's key that the parent has 100% width and height so that a window resize is detected and inner svg can adjust. It's also key to specify the viewBox attribute to allow the svg to resize according to its parent div.
But why is it not resizing accorindg to height?

div {
  height: 100%;
  width: 100%;
}

  <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
    <circle cx="100" cy="100" r="100" />
  </svg>

http://jsfiddle.net/7dz60fkh/

A: You need to give the html, body and svg elements the same percentage sizes too so they all resize in lock step.

div, html, body, svg {
  height: 100%;
  width: 100%;
}

  <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
    <circle cx="100" cy="100" r="100" />
  </svg>

A: SVGs are way more different than pixel images such as jpeg, png ..etc.
The hard part is that you shouldn't think of them like you would with "normal" images, to make things short SVG aren't IMAGES but DOCUMENTS that contains info.

When you include an HTML file with an , you don't expect the
text inside to scale when you change the size of the frame. Same with
SVG. By default, it will be drawn at the size specified in the code,
regardless of the size of the canvas.

If your svg has something called a viewbox ( which is your case ) then it will be scaled to fit it's defined viewport so increasing the height of the img won't make the icons any taller. You'll just end up with the img  in a wider box.
I think mainly your problem is that your SVG have fixed values defined in them. Open up the SVG files and make sure they either:
have no width and height defined, OR have width and height both set to "100%".
you can read more about SVGs in this article, it'll help you understand how things work hopefully


text:
Q: Array_multisort does not sort by the second array I have a multidimensional array and I would like to sort it so that both arrays are sorted by the flag SORT_NATURAL and then either SORT_ASC or SORT_DESC
So from what I understand it should look like this:
array_multisort($array1, SORT_NATURAL, SORT_ASC, $array2, SORT_NATURAL, SORT_ASC, $array);

But it seems to only be applying the SORT_NATURAL to the $array1 and the $array2 is not sorted at all, not even the sort direction is applied.
But as soon as I remove the SORT_NATURAL form $array2, the sort direction works.
So- $array1 sorts perfectly fine, but $array2 does not sort at all.
What could be the problem? Am I missing something?
public function sortMultiDimensional(&$array, $subKey, $subKey2, $sortorder_packing_bool=false, $sortorder_packing_secondary_bool=false) {
    $array1 = array();
    $array2 = array();
    foreach ($array as $key => $row) {
        $array1[$key]  = $row[$subKey];
        $array2[$key] = $row[$subKey2];
    }
    if($sortorder_packing_bool)
        $sortorder_packing_bool = SORT_ASC;
    else
        $sortorder_packing_bool = SORT_DESC;

    if($sortorder_packing_secondary_bool)
        $sortorder_packing_secondary_bool = SORT_ASC;
    else
        $sortorder_packing_secondary_bool = SORT_DESC;

    array_multisort($array1, $sortorder_packing_bool, SORT_NATURAL, $array2, $sortorder_packing_secondary_bool, SORT_NATURAL, $array);
}

A: Check this example,
$data = [];
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);

foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

array_multisort($volume, SORT_DESC,SORT_NATURAL, $edition, SORT_ASC,SORT_NATURAL, $data);

print_r($data);

Check here working code.
It is like group by a,b.
SORT_NATURAL working like this for example.


text:
Q: ingress nginx redirect too many times I have deployed an app in aks with below ingress
kind: Ingress
apiVersion: networking.k8s.io/v1
metadata:
  name: cas-ingress
  namespace: cas
  annotations:
    kubernetes.io/ingress.allow-http: 'false'
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/affinity: cookie
    nginx.ingress.kubernetes.io/configuration-snippet: |
      more_set_headers "X-Frame-Options: SAMEORIGIN";
      more_set_headers "X-Xss-Protection: 0";
      more_set_headers "Referrer-Policy: use strict-origin-when-cross-origin";
    nginx.ingress.kubernetes.io/force-ssl-redirect: 'true'
    nginx.ingress.kubernetes.io/proxy-body-size: 10m
    nginx.ingress.kubernetes.io/rewrite-target: /
    nginx.ingress.kubernetes.io/session-cookie-hash: sha1
    nginx.ingress.kubernetes.io/ssl-passthrough: 'true'
    nginx.ingress.kubernetes.io/ssl-redirect: 'true'

spec:
  tls:
    - hosts:
        - afg-cas-preprod.mocomtest.com
      secretName: mozcomtest-tls
  rules:
    - host: afg-cas-preprod.mocomtest.com
      http:
        paths:
          - path: /
            pathType: ImplementationSpecific
            backend:
              service:
                name: cas-server
                port:
                  number: 6443

when i hit the url "afg-cas-preprod.mocomtest.com/auth" , it show the error
ERR_TOO_MANY_REDIRECTS


text:
Q: Usefulness of having port 135 open in Active Directory environment? During a network review, we noticed that some surface hub that are joined to the domain did not have port 135 (msrpc) opened.
What is the difference between having surface book with port 135 opened, and the others? Considering that both work perfectly in the Active Directory environment.
Thanks.

A: Port 135 is the RPC Endpoint Mapper service. It is a service that allows other systems to discover what services are advertised on a machine and what port to find them on. It is mostly associated with remote access and remote management.
It is a sensitive port that is associated with a slew of security vulnerabilities and should never be exposed to the internet.
However, Port 135 is needed in an active directory and server/client environment for many services to operate properly. For a client, such as a surface, the port can probably be safely closed because services that depend on Port 135 are typically exposed on a server. But, that does come with some drawback that certain remote management functionality will be shutdown - specifically WMI access will be blocked. So, as an admin responsible for managing those devices "remotely," you may want to leave the port open but restrict access to it on the windows firewall to only your local IP addresses for security purposes.
You will not be able to block this port on Active Directory servers or it will break things.
If you would like to see what services depend on Port 135 you can review this document:
Service overview and network port requirements for Windows


text:
Q: How to fetch input from text box and print in React? I am new to React trying to write a very simple project that fetches input of both text boxes and when button is clicked, the 'data' in text boxes is printed on paragraph.
How do I fetch text's in input text boxes when button is clicked?
class Input extends Component {
    state = {
        tagged: false,
        message: '',
    }

    handleClick(e) {
        this.setState({tagged: true});
        e.preventDefault();
        console.log('The link was clicked.');
    }

    render() {
        return (

 hello

                <input
                    style = {textStyle}
                    placeholder="user@email.com"
                    type="text">
                </input>

                <input
                    style = {textStyle}
                    placeholder="tag"
                    type="text">
                </input>
                <button
                    onClick={(e) => this.handleClick(e)}
                    style={buttonStyle}>
                    {this.state.tagged ? 'Tagged' : 'Tag ' }
                </button>

                    {this.state.tagged ? 'Clicked' : 'Still' }

        )
    }
}

A: You can add onChange event handler in each input.
class Input extends Component {
    state = {
        tagged: false,
        message: '',
        input1: '',
        input2: '',
    }

    handleClick(e) {
        // access input values in the state
        console.log(this.state) // {tagged: true, input1: 'text', input2: 'text2'}
        this.setState({tagged: true});
        e.preventDefault();
        console.log('The link was clicked.');
    }

    handleInputChange = (e, name) => {
      this.setState({
       [name]: e.target.value
     })
    }

    render() {
        return (

 hello

                <input
                    style = {textStyle}
                    placeholder="user@email.com"
                    type="text"
                    onChange={(e) => this.handleInputChange(e, 'input1')}
                >
                </input>

                <input
                    style = {textStyle}
                    placeholder="tag"
                    type="text"
                   onChange={(e) => this.handleInputChange(e, 'input2')}
               >
                </input>
                <button
                    onClick={(e) => this.handleClick(e)}
                    style={buttonStyle}>
                    {this.state.tagged ? 'Tagged' : 'Tag ' }
                </button>

                    {this.state.tagged ? 'Clicked' : 'Still' }

        )
    }
}

A: There are two different ways of working with react inputs - you can either make them controlled or uncontrolled. When you say fetch text from inputs, this is called uncontrolled components and means that form data is handled by the DOM itself and not by react.
This is achieved by using ref and literally getting a reference to your input and fetching its value when you need it. you can read more about this approach in react docs.
According to react docs, it is recommended using  controlled components

In most cases, we recommend using controlled
  components to implement forms. In a controlled
  component, form data is handled by a React component.

This means that you don't use references to the inputs and instead handle changes of your inputs with an event handler and update state with the new values that the user has entered into the input fields. According to react docs here is how react handles form with controlled components:

the React component that
  renders a form also controls what happens in that form on subsequent
  user input. An input form element whose value is controlled by React in this way is called a "controlled component".

In your case you can do this if you choose controlled inputs:
class ControlledInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tagged: false,
      firstInput: '',
      secondInput: ''
    }
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(event) {
    this.setState({ [event.target.name]: event.target.value });
  }
  handleClick(e) {
    this.setState({ tagged: true });
    e.preventDefault();
    console.log('The link was clicked.');
  }

  render() {
    const { firstInput, secondInput, tagged } = this.state;
    return (

        {tagged &&
{firstInput} {secondInput}
 }
        <input
          value={firstInput}
          name="firstInput"
          onChange={this.handleChange}
          type="text" />
        <input
          value={secondInput}
          name="secondInput"
          onChange={this.handleChange}
          type="text" />
        <button onClick={(e) => this.handleClick(e)}>
          {tagged ? 'Tagged' : 'Tag '}
        </button>

    )
  }
}

Here you put the inputs' values on state and update state when the user writes something in your inputs. If you however want to use uncontrolled components you can do it this way:
class UncontrolledInput extends React.Component {
  state = {
    tagged: false,
    message: '',
  }

  handleClick(e) {
    e.preventDefault();
    const messageFromInputs = `${this.firstInput.value} ${this.secondInput.value}`;
    this.setState({ tagged: true, message: messageFromInputs });
  }

  render() {
    return (

{this.state.message}

        <input ref={(input) => this.firstInput = input} type="text" />
        <input ref={(input) => this.secondInput = input} type="text" />
        <button onClick={(e) => this.handleClick(e)}>
          {this.state.tagged ? 'Tagged' : 'Tag '}
        </button>

          {this.state.tagged ? 'Clicked' : 'Still'}

    )
  }
}

Here you will actually fetch values from your inputs when the button is clicked.
I made a working example with both ways on codesandbox.


text:
Q: Get textbox value in new window using Jquery I have an array of textboxes each having button on right side which when pressed the text should be displayed on new window using Jquery. For demo, you might have seen jquery lightbox plugin which shows the images in the new window. I want exactly same but instead of images i want to show the text value of the text box when its button is pressed.
Please tell me how can i do that?

A: You can do it like this:
var win = window.open();
var doc = win.document;
doc.write($('#textbox_id').val());
doc.close();

A: testopen.html:

testopener.html:
<!DOCTYPE html>

    <input id="field1" />
    <input id="field2" />

    <button id="opentest">test</button>
</form>

links
http://jquery.com/demo/thickbox/
http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/
http://www.ericmmartin.com/projects/simplemodal/

A: If you would like to show ony texts, I strongly suggest to use dialog instead of the plugin.
There are lots of plugin out there to achieve this,which supports to show both images and texts.
http://fancybox.net/
http://colorpowered.com/colorbox/
http://dev.iceburg.net/jquery/jqModal/#
http://jqueryui.com/demos/dialog/

A: You can do something like this:
$('input#mybutton').click(function() {
    var text = $('textarea#mytextarea').val();
});

So, when the button is clicked, the content from textarea will be collected to a variable. After, you just need to inject that variables content on your destination:

*

*alert()

*plugin for popup window

*custom popup window

*open a new browser window with that content
etc...


text:
Q: Adding files to TFS Programatically using C# code I am working on an app which fetches few files from a specified path and move to TFS on a button click. My first question is , is it possible to add new files to TFS programatically using C#?. If yes, then is there any restriction on the file types we can add to TFS?. Below is the code i have tried to create a workspace in TFS.
TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(<tfs uri>));

tfs.EnsureAuthenticated();
VersionControlServer vcs = tfs.GetService<VersionControlServer>();
Workspace ws = vcs.CreateWorkspace("DCSCode");

//"I:temp" is the location of files which needs to be
  //moved to TFS
int r = ws.PendAdd(@"I:temp");

A: You need to create a new or get the existing workspace ->  pend changes -> check in those changes -> resolve the conflict if you have.
A related code snippet for your reference:
//Get the current workspace
WS = versionControl.GetWorkspace(workspaceName, versionControl.AuthorizedUser);

//Mapping TFS Server and code generated
WS.Map(tfsServerFolderPath,localWorkingPath);

//Add all files just created to pending change
int NumberOfChange = WS.PendAdd(localWorkingPath,true);
//Get the list of pending changes
PendingChange[] pendings = WS.GetPendingChanges(tfsServerFolderPath,RecursionType.Full);

//Auto check in code to Server
WS.CheckIn(pendings,"CodeSmith Generator - Auto check-in code.");

You can also find a sample here : Programatically checkin file to TFS using C#


text:
Q: Best practice to open a download link (as opposed to document.location)? I have a URL I know will usually open a file that the UA will download (with a content-disposition: attachment header), but sometimes will just result in a 500 or other error page.
Currently I am triggering the download by setting document.location in JavaScript.
I don't want to open a new tab or page for this, but I also don't want to have my users end up at a 500 page for no good reason on occasion.
Is there method to this that would address my concerns?
For example, creating an invisible  with the download URL as its source? I don't want to invent something new, but rather am curious if anyone knows of a tried-and-true solution.

A: You could check to see if the URL exists before sending the user over by using an HTTP HEAD request
function CheckFileExists(url)
{
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open('HEAD', url, false);
  xmlhttp.send();

  //You may have to invert this to return true if not 500 || 404, this is up to you
  if(xmlhttp.status == 200)
  {
    return true;
  }
  else
  {
    alert('Sorry, that file does not exist');
    return false;

  }
}

Your hyperlinks could then be written like this
Download this file

The disadvantage of this method is the delay that occurs between clicking and the initiation of the download.
If you're still going to redirect the users via JavaScript, you can redirect based on the value returned from CheckFileExists.


text:
Q: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=200, result=0, data=null} java.lang.NullPointerException My app allows the user to press a button, it opens the camera for video capturing, they can take a video and it will show up in sdcard. If the user presses stop while the camera is open I get this force close - Failure delivering result ResultInfo{who=null, request=200, result=0, data=null} to activity.
the application crashes whenever I stop recording a video.However the videos are stored in the directory, and use the same file naming formats.
this is activity class
public class VideocameraActivity extends Activity {

private Uri fileUri;
public static final int MEDIA_TYPE_VIDEO = 2;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
public static VideocameraActivity ActivityContext =null;
public static TextView output;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.observation);

    ActivityContext = this;

    ImageView buttonRecording = (ImageView)findViewById(R.id.add_rowBtn);
    //output = (TextView)findViewById(R.id.output);

    buttonRecording.setOnClickListener(new Button.OnClickListener(){

        @Override
        public void onClick(View arg0) {

            // create new Intentwith with Standard Intent action that can be
            // sent to have the camera application capture an video and return it.
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

            // create a file to save the video
            fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

            // set the image file name
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

            // set the video image quality to high
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

            // start the Video Capture Intent
            startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);

        }});

}

/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){

      return Uri.fromFile(getOutputMediaFile(type));
}

/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){

    // Check that the SDCard is mounted
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
              Environment.DIRECTORY_PICTURES), "MyCameraVideo");

    // Create the storage directory(MyCameraVideo) if it does not exist
    if (! mediaStorageDir.exists()){

        if (! mediaStorageDir.mkdirs()){

            output.setText("Failed to create directory MyCameraVideo.");

            Toast.makeText(ActivityContext, "Failed to create directory MyCameraVideo.",
                    Toast.LENGTH_LONG).show();

            Log.d("MyCameraVideo", "Failed to create directory MyCameraVideo.");
            return null;
        }
    }

    // Create a media file name

    // For unique file name appending current timeStamp with file name
    java.util.Date date= new java.util.Date();
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                         .format(date.getTime());

    File mediaFile;

    if(type == MEDIA_TYPE_VIDEO) {

        // For unique video file name appending current timeStamp with file name
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
        "VID_"+ timeStamp + ".mp4");

    } else {
        return null;
    }

    return mediaFile;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    // After camera screen this code will executed

    if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {

        if (resultCode == RESULT_OK) {

            //output.setText("Video File : " +data.getData());

            // Video captured and saved to fileUri specified in the Intent
            Toast.makeText(this, "Video saved to:\n" +
                     data.getData(), Toast.LENGTH_LONG).show();

        } /*else if (resultCode == RESULT_CANCELED) {

            output.setText("User cancelled the video capture.");

            // User cancelled the video capture
            Toast.makeText(this, "User cancelled the video capture.",
                    Toast.LENGTH_LONG).show();

        } else {

            output.setText("Video capture failed.");

            // Video capture failed, advise user
            Toast.makeText(this, "Video capture failed.",
                    Toast.LENGTH_LONG).show();
        }*/
    }
}

}

Log Cat Error:
11-07 06:48:59.062: D/dalvikvm(1585): GC_FOR_ALLOC freed 71K, 6% free 2869K/3048K, paused 9ms, total 10ms
11-07 06:48:59.074: I/dalvikvm-heap(1585): Grow heap (frag case) to 7.069MB for 4367372-byte allocation
11-07 06:48:59.090: D/dalvikvm(1585): GC_FOR_ALLOC freed <1K, 3% free 7134K/7316K, paused 17ms, total 17ms
11-07 06:48:59.174: D/dalvikvm(1585): GC_FOR_ALLOC freed 1K, 3% free 7610K/7776K, paused 6ms, total 6ms
11-07 06:48:59.206: D/dalvikvm(1585): GC_FOR_ALLOC freed 5K, 2% free 9140K/9300K, paused 2ms, total 2ms
11-07 06:48:59.562: D/libEGL(1585): loaded /system/lib/egl/libEGL_genymotion.so
11-07 06:48:59.562: D/(1585): HostConnection::get() New Host Connection established 0xb95313a8, tid 1585
11-07 06:48:59.570: D/libEGL(1585): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
11-07 06:48:59.570: D/libEGL(1585): loaded /system/lib/egl/libGLESv2_genymotion.so
11-07 06:48:59.606: W/EGL_genymotion(1585): eglSurfaceAttrib not implemented
11-07 06:48:59.610: E/OpenGLRenderer(1585): Getting MAX_TEXTURE_SIZE from GradienCache
11-07 06:48:59.610: E/OpenGLRenderer(1585): MAX_TEXTURE_SIZE: 8192
11-07 06:48:59.614: E/OpenGLRenderer(1585): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
11-07 06:48:59.614: E/OpenGLRenderer(1585): MAX_TEXTURE_SIZE: 8192
11-07 06:48:59.614: D/OpenGLRenderer(1585): Enabling debug mode 0
11-07 06:49:14.386: W/EGL_genymotion(1585): eglSurfaceAttrib not implemented
11-07 06:49:34.218: D/dalvikvm(1585): GC_FOR_ALLOC freed 645K, 7% free 10544K/11296K, paused 9ms, total 19ms
11-07 06:49:38.050: W/EGL_genymotion(1585): eglSurfaceAttrib not implemented
11-07 06:49:38.614: I/System.out(1585): Url--------login--> http://ilearniteasy.com/new-version/api/get_login.php?salt=8006&sign=85db4eebea8fca6814ad73a75efcdbf5&site_url=http://www.mydistance-learning-college.com/students/&username=teststudent7&password=password1
11-07 06:49:38.730: W/EGL_genymotion(1585): eglSurfaceAttrib not implemented
11-07 06:49:40.362: I/Choreographer(1585): Skipped 97 frames!  The application may be doing too much work on its main thread.
11-07 06:49:44.230: D/dalvikvm(1585): GC_FOR_ALLOC freed 240K, 5% free 12079K/12676K, paused 3ms, total 15ms
11-07 06:49:44.278: W/EGL_genymotion(1585): eglSurfaceAttrib not implemented
11-07 06:49:59.114: W/EGL_genymotion(1585): eglSurfaceAttrib not implemented
11-07 06:50:02.946: W/EGL_genymotion(1585): eglSurfaceAttrib not implemented

A: Please check
if(data!=null) {

...

}


text:
Q: How to use one interface theme with other text-color theme in VS Code? I'm currently using Material Theme (Dark High Contrast) in Visual Studio Code, I really like how the interface looks like, although the color highlighting isn't that great since it uses a lot of red for main elements which I don't like. I tried out Cobalt2 by WesBos and it was the opposite, the text colors worked just right, everything really understandable but I don't like that blueish interface, just doesn't feel ok for me.
How could I wether implement an own theme by grapping the interface of Material Theme and the color highlight of Cobalt2, or simply join together these two.
Not planning on making an theme out of that, it's just a personal choice :)
Thank you stranger!

A: From command palette : Developer: Generate Color Theme From Current Settings
You can copy "colors" from one theme to yours "workbench.colorCustomizations" in settings.json. Perhaps some colors will be absent, use your imagination or whatnot...
Related feature request: Separate workbench theme and syntax theme
Workbench colors reference
https://code.visualstudio.com/docs/getstarted/theme-color-reference


text:
Q: What is the difference between a HashMap and a TreeMap? I started learning Java. When would I use a HashMap over a TreeMap?

A: You almost always use HashMap, you should only use TreeMap if you need your keys to be in a specific order.

A: HashMap is used for fast lookup, whereas TreeMap is used for sorted iterations over the map.

A: HashMap is implemented by Hash Table while TreeMap is implemented by Red-Black tree. The main difference between HashMap and TreeMap actually reflect the main difference between a Hash and a Binary Tree , that is, when iterating,  TreeMap guarantee can the key order which is determined by either element's compareTo() method or a comparator set in the TreeMap's constructor.
Take a look at following diagram.

A: Along with sorted key store one another difference is with TreeMap, developer can give (String.CASE_INSENSITIVE_ORDER) with String keys, so then the comparator ignores case of key while performing comparison of keys on map access. This is not possible to give such option with HashMap - it is always case sensitive comparisons in HashMap.

A: To sum up:

*

*HashMap: Lookup-array structure, based on hashCode(), equals() implementations, O(1) runtime complexity for inserting and searching, unsorted

*TreeMap: Tree structure, based on compareTo() implementation, O(log(N)) runtime complexity for inserting and searching, sorted

Taken from: HashMap vs. TreeMap

A: TreeMap is an example of a SortedMap, which means that the order of the keys can be sorted, and when iterating over the keys, you can expect that they will be in order.
HashMap on the other hand, makes no such guarantee.  Therefore, when iterating over the keys of a HashMap, you can't be sure what order they will be in.
HashMap will be more efficient in general, so use it whenever you don't care about the order of the keys.

A: Use HashMap most of the times but use TreeMap when you need the key to be sorted (when you need to iterate the keys).

A: I'll talk about the HashMap and TreeMap implementation in Java:

*

*HashMap -- implement basic map interface

*

*implemented by an array of buckets, each bucket is a LinkedList of entries

*running time of basic operations: put(), average O(1), worst case O(n), happens when the table is resized; get(), remove(), average O(1)

*not synchronized, to synchronize it: Map m = Collections.synchronizedMap(new HashMap(...));

*Iteration order of the map is unpredictable.

*TreeMap -- implement navigable map interface

*

*implemented by a red-black tree

*running time of basic operations: put(), get(), remove(), worst case O(lgn)

*not synchronized, to synchronize it: SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));

*provide ordered iteration. higherKey(), lowerKey() can be used to get the successor and predecessor of a given key.

To sum, the biggest difference between HashMap and TreeMap is that TreeMap implements NavigableMap<K,V>, which provide the feature of ordered iteration. Besides, both HashMap and TreeMap are members of Java Collection framework. You can investigate the source code of Java to know more about their implementations.


text:
Q: How can I convert PropertyInfo[] to Dictionary? Actually I need the properties of my class to be displayed in a mvc dropdown. I'm using reflection to get those things. But now my problem is to get them as key value pairs to display them in dropdownlist.
I am using the below code...
public static Dictionary<string,string> SetProperties()
    {
        Type T = Type.GetType("Entity.Data.Contact");
        PropertyInfo[] resultcontactproperties = T.GetProperties();

        ViewContactModel viewobj = new ViewContactModel();
        viewobj.properties = resultcontactproperties;
        Dictionary<string, string> dic = new Dictionary<string, string>();
        return dic;
    }

So how to convert them to dictionary to get them in the below dropdown...?
  @Html.DropDownListFor(m=>m.properties, new SelectList(Entity.Data.ContactManager.SetProperties(),"",""), "Select a Property")

Well this is my ViewContactModel

public class ViewContactModel
    {

        public List<Entity.Data.Contact> Contacts;
        public int NoOfContacts { get; set; }
        public Paging pagingmodel { get; set; }
        public PropertyInfo[] properties { get; set; }
    }

In the view I'm using this model

A: If you must use a Dictionary and assuming that the Name and the Value of each dropdown item is the property name itself, you could use something along the following lines:
    public static Dictionary<string, string> GetProperties<T>(params string[] propNames)
    {
        PropertyInfo[] resultcontactproperties  = null;
        if(propNames.Length > 0)
        {
            resultcontactproperties = typeof(T).GetProperties().Where(p => propNames.Contains(p.Name)).ToArray();
        }
        else
        {
            resultcontactproperties = typeof(T).GetProperties();
        }
        var dict = resultcontactproperties.ToDictionary(propInfo => propInfo.Name, propInfo => propInfo.Name);
        return dict;
    }

 @Html.DropDownListFor(m=>m.properties, new SelectList(
 Entity.Data.ContactManager.GetProperties<Contact>(),"Key","Value"),
 "Select a Property")


text:
Q: React native rn-fetch-blob download with post method i need to download a file(.pdf) which is coming from flask rest API by the code
return send_file(file_location, as_attachment=True)

i tried using RNFetchBlob
RNFetchBlob
        .config({
            addAndroidDownloads: {
                useDownloadManager: true, // <-- this is the only thing required
                // Optional, override notification setting (default to true)
                notification: false,
                // Optional, but recommended since android DownloadManager will fail when
                // the url does not contains a file extension, by default the mime type will be text/plain
                mime: 'application/pdf',
                description: 'File downloaded by download manager.',
            },
          })
          .fetch('POST', 'http://192.168.0.199:8000/v1/quote/view', data)
          .then((res)=>console.log('The file saved to ', res.path()))
          .catch((err)=>console.log(err));

but even when i mentioned POST method in the flask its is received as GET method
192.168.0.186 - - [11/Aug/2021 19:05:31] "GET /v1/quote/view HTTP/1.1" 405 -

What am i doing wrong?

A: Thanks @Xhirazi,
the order should be like this fetch(Method, URL, headers, body), fixed the issue


text:
Q: Sensio ParamConverter STI abstract Given an Single Table Inheritance for Location -> A and Location -> B
 * @DiscriminatorMap({
 *     "a" = "A",
 *     "b" = "B"
 * })
 * @Discriminator(field = "discr", map = {
 *     "a" = "A",
 *     "b" = "B",
 * })
abstract class Location

In the Controller, i will send either an A or B type extending Location.
  /**
   * @Rest\Post("", name="create_l")
   * @ParamConverter("location", converter="fos_rest.request_body")
   */
  public function insert(Location $location): JsonResponse

Doctrine tells me the obvious message it cant instaniiate an abstract class, which is true but it should instead create the subtype.
If A comes in, it should be converted to A, not instantiiate Location.
Any solutions?

A: You are not allowed to create an abstract entity class like that. Take a look at the docs on single table inheritance. You can see here that both classes are concrete. In your situation, it looks like you need some subclasses LocationA LocationB, etc. But to be honest, you should provide more details about your use case, because it seems you might be misusing the inheritance structure.

A: So, after doing some research and testing i fixed it myself.
My core problem was that i mixed two Serializers, JMS and Symfony/Serializer. So i decided to go with the Symfony/Serializer as it enabled the creation of the subtypes of abstract classes. This is my setup:
Imports & Entity:
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\DiscriminatorColumn;
use Doctrine\ORM\Mapping\InheritanceType;

/**
 * @ORM\Entity(repositoryClass=AbstractParent::class)
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap(typeProperty="discr", mapping = {
 *     "a"      = "App\Entity\A",
 *     "b"      = "App\Entity\B",
 * })
 * @ORM\Table(
 *    name="abstract_parent",
 * )
 */
abstract class AbstractParent extends PlaceComputable

When sending a post request to save a subtype:
/**
 * @Rest\Post("", name="create_subtype")
 * @ParamConverter("subtype", converter="fos_rest.request_body")
 */
public function insert(AbstractParent $subtype): JsonResponse
{
 // $subtype is now of Either Type 'A' or 'B'
 // depending on what 'discr' member was passed to the controller
}

Its is now also documented in the Symfony/Serializer documentation as to how convert subtypes of abstract classes.


text:
Q: Powershell output for multiple dhcp servers I am trying to get the mibinfo for multiple dhcp servers in our infrastructure. My problem is that when i run the command
invoke-command -computername $dhcpserver -credential $Cred -scriptblock{netsh dhcp server show mibinfo}

I get MIBinfo for all the servers, but i don't get the name of the server in the output. So i need a way where i get the output as
Server1
mibinfo
server2
mibinfo
($dhcpserver has the list of all the dhcp servers.)

A: Is $dhcpserver an array of strings? I didn't know Invoke-Command could do this...
If so, try this:
Foreach ($server in $dhcpserver) {
    $mibOutput = invoke-command -computername $server -credential $Cred -scriptblock{netsh dhcp server show mibinfo}
    Write-Output "$server $mibOutput"
}


text:
Q: generics with a T type and a named function type that takes T I have a module that defines a bunch of types
type Thing1 struct {}

type Thing2 struct {}

and named functions types that take the types above as arguments
type T1 func(t *Thing1)
type T2 func(t *Thing2)

Then it defines a map using these function types
var (
    ModThing1 = map[string]T1{ ... }
    ModThing2 = map[string]T2{ ... }
)

In my app that uses this module, I would like use a generic for Thing1 and Thing2
Something like:
func do[T any](in *T, inMap map[string]func(in *T)) {
  for _, val := range inMap {
     val(in)
  }
}
...
do[mod.Thing1](&mod.Thing1{}, mod.ModThing1)

Of course the problem is that Go wont allow this because the type of the value of the map is not the same as mod.ModThing1 value type.  func(in *T)) vs mod.T1
Is there a way to get this to work?

A: In the function do, declare an additional type parameter F with an approximated constraint that also references T. You take advantage of T1 and T2 having similar underlying types. You don't even have to explicitly instantiate do's type arguments, both can be inferred.
func main() {
    do(&foo.Thing1{}, foo.ModThing1)
    do(&foo.Thing2{}, foo.ModThing2)
}

func do[T any, F ~func(*T)](in *T, inMap map[string]F) {
    for _, val := range inMap {
        val(in)
    }
}

Playground: https://go.dev/play/p/wiWWzXVDG7v

If you have control over the imported package, another solution is to use a generic function type instead of T1 and T2. The principle behind this abstraction is the same. In fact, here you can see more clearly why the first solution works:
type F[T any] func(t *T)

// instead of
// type T1 func(t *Thing1)
// type T2 func(t *Thing2)

Then you declare the map variables with specific instantiations of F[T]:
var (
    ModThing1 = map[string]F[Thing1]{ ... }
    ModThing2 = map[string]F[Thing2]{ ... }
)

Then in the do function you instantiate F with the type parameter:
func do[T any](in *T, inMap map[string]F[T]) {
    for _, val := range inMap {
        val(in)
    }
}

Playground: https://go.dev/play/p/ITBqiqjjVUz

By the way, you can also abstract the map type:
type M[T any] map[string]F[T]

func do[T any](in *T, inMap M[T]) {
    for _, val := range inMap {
        val(in)
    }
}


text:
Q: What is the difference between PACKAGE_USAGE_STATS and LOADER_USAGE_STATS? I have been working on some Android app and I am trying to figure out the difference between the two permissions.
Reading from the Google's manifest:

*

*PACKAGE_USAGE_STATS "Allows an application to collect component usage statistics"
doc

*LOADER_USAGE_STATS "Allows a data loader to read a package's access logs. The access logs contain the set of pages referenced over time. A data loader has to be the one which provides data to install an app." doc
The terms "component" and "package" terms seem to be slightly vague in regards to usage statistics. What I do not understand here is what exactly they collect.
My goal: make the app ask for one of these permissions so it can gather information about users apps' usage, for instance, how much time the user was using YouTube app today etc.


text:
Q: Python Selenium element not visible in pop-up window Not sure why I am receiving the following error.
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible

I am attempting to click on the Box Score link after clicking on the 'More' button for each game (each game that does not have a GT link for that matter). Am I having issues because this button is showing in a pop-up type window?
I have attempted to resolve the situation by using time.sleep(5) or so, however the same error prints to the screen, so it does not seem to be an issue of waiting for the link to load/appear.
Here is my code:
schedule = 'http://www.gamecocksonline.com/sports/m-basebl/sched/scar-m-basebl-sched.html'
options = webdriver.ChromeOptions(); options.add_argument("--start-maximized")
driver = webdriver.Chrome(chrome_options=options)
driver.get(schedule)

#Find 'More' button, scroll to, and click
python_button = driver.find_elements_by_xpath("//a[@class='sch-view-more']")[idx]
driver.execute_script("return arguments[0].scrollIntoView();", python_button)
driver.execute_script("window.scrollBy(0, -150);")
python_button.click()

#Click on Box Score link
python_button = driver.find_element_by_xpath("//a[text()='Box Score']")
python_button.click()

#Pass HTML to Beautiful Soup and close browser window
soup = BeautifulSoup(driver.page_source)
playbyplay(soup) #Reads info from the html
driver.quit()

A: I was able to resolve my own issue here (thanks to @DebanjanB for pointing out a few things in the comments).
Adding a wait time to allow for the links to become available, as well as observing that the games at the top of the page follow the same xpath as the one I was searching for were the main resolutions.
#Click on Box Score link
time.sleep(1)
python_button = driver.find_elements_by_xpath("//span[@class='sch-event-related']")[-1]
python_button.click()


text:
Q: How to do different login by roles ASP.NET Core 2.2 After a little research and with the help of another fellow from here, i managed to create an "Admin" role and assign it to an user ( I only needed one Admin ). Now i have some troubles with making the login redirect to different pages regarding the role the user has.
I am using asp.net core 2.2 default web site template and authentication selected as individual user account.
Here is my CreateRole method:
private async Task CreateUserRoles(IServiceProvider serviceProvider)
{
    var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

    IdentityResult roleResult;
    //Adding Admin Role
    var roleCheck = await roleManager.RoleExistsAsync("Admin");
    if (!roleCheck)
    {
        //create the roles and seed them to the database
        roleResult = await roleManager.CreateAsync(new IdentityRole("Admin"));
    }
    //Assign Admin role to the main User here we have given our newly registered
    //login id for Admin management
    ApplicationUser user = await userManager.FindByEmailAsync("example@gmail.com");
    await userManager.AddToRoleAsync(user, "Admin");
}

And here is the post of my Login method with what i've tried so far:
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");

    if (ModelState.IsValid)
    {
        var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
        var status = await _signInManager.UserManager.GetUsersInRoleAsync("Admin");
        if (Input.Email.Contains(status.ToString()))
        {
            return LocalRedirect(returnUrl);
        }
        if (result.Succeeded)
        {
            _logger.LogInformation("User logged in.");
            return LocalRedirect(returnUrl);
        }
        if (result.RequiresTwoFactor)
        {
            return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
        }
        if (result.IsLockedOut)
        {
            _logger.LogWarning("User account locked out.");
            return RedirectToPage("./Lockout");
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return Page();
        }
    }

    // If we got this far, something failed, redisplay form
    return Page();
}

A: You need to fetch the user's role from the database:
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
var user = await _signInManager.UserManager.FindByEmailAsync(Input.Email);
// Get the roles for the user
var roles = await _signInManager.UserManager.GetRolesAsync(user);

if (roles.Any(role=>"Admin".Equals(role)))
{
    return LocalRedirect("YourURL");
}

Or use UserManager.IsInRoleAsync function :
var user = await _signInManager.UserManager.FindByEmailAsync(Input.Email);

var isInRole = await _signInManager.UserManager.IsInRoleAsync(user, "Admin");
if (isInRole)
{
    return LocalRedirect("YourURL");
}

A: Right after the user logged in you can check their role using HttpContext.User.IsInRole function:
var user = await _userManager.FindByEmailAsync(Input.Email);
var result = await _signInManager.PasswordSignInAsync(user, Input.Password, Input.RememberMe, lockoutOnFailure: true);

if (result.Succeeded)
{
    _logger.LogInformation("User logged in.");
    var principal = await _signInManager.ClaimsFactory.CreateAsync(user);
    if (principal.IsInRole("Admin")) {
        return LocalRedirect("SomeSpecialUrlForAdmin");
    }
    else {
        return LocalRedirect(returnUrl);
    }
}


text:
Q: Returning the following season and year For a particular season and year when it started I have to get the following season and year when it starts, e.g. for Summer 2021 I should get Autumn 2021, and for Winter 2021 I should get Spring 2022.
"Seasons" table has the "Order" column which indicates the order of seasons in a year, so it looks like this:

SeasonID
Order
Name

1
1
Spring

2
2
Summer

3
3
Autumn

4
4
Winter

Remark: "Order" column may seem redundant, but this is actually simplified/adapted version of the problem I have, where "Order" column is neccesary.
I have a stored procedure that has @Year and @SeasonID as input parameters. I have to get following season/year in @FollowingSeasonID and @FollowingYear parameters, which I use later in the stored procedure. I'm not sure if I've used the best technique for that:
(...)

    DECLARE @FollowingSeasonID int;
    DECLARE @FollowingYear int;
    if object_id('tempdb..#Years') is not null drop table #Years
    CREATE TABLE #Years ([Year] int)
    INSERT INTO #Years ([Year]) VALUES (@Year), (@Year + 1)

    SELECT @FollowingSeasonID = FollowingSeasonID, @FollowingYear = FollowingYear
    FROM
        (SELECT SeasonID,
                [Year],
                LEAD(SeasonID) OVER (ORDER BY [Year], Order) AS FollowingSeasonID,
                LEAD([Year]) OVER (ORDER BY [Year], Order) AS FollowingYear
        FROM Seasons
        CROSS JOIN #Years) t
    WHERE SeasonID = @SeasonID AND [Year] = @Year

(...)

Is there a better way to do that? Could it be achieved in just one query?
I need those values in multiple stored procedures/views/... so I wanted to extract that part of code if a function. Scalar valued function can't return two values, so I have to create a table valued function (and I have to use table variable instead of temp table #Years). However, is there a better way to do that instead of having a table valued function that always returns just one row?

A: Unless I've misunderstood, given a single seasonId you just need the following Id and reset it to 1 and increment the year if necessary?
declare @seasonid int=1, @Year int=2021

select  FollowingSeasonID, @Year + yr FollowingYear
from (
    select *,
        IsNull(Lead(SeasonId) over(order by [order]),1) FollowingSeasonID,
        case when Lead(SeasonId) over(order by [order]) is null then 1 else 0 end yr
    from seasons
)s
where SeasonId=@SeasonId

If you don't want to use a TVF you could just use this as a view/cte, joining on currentId and return the followingId and yr value to add to your current year.

A: You can wrap this code in UDF and you should be able to get seasonId, year
DECLARE @season table(SeasonId int, SeasonOrder int, Name varchar(10))
INSERT INTo @season values
(1,    1    ,'Spring')
,(2,    2   ,'Summer')
,(3,    3   ,'Autumn')
,(4,    4   ,'Winter');

DECLARE @FollowingSeasonID int;
DECLARE @FollowingYear int;
DECLARE @year int = 2021, @SeasonId int = 2;

;WITH CTE_YearSeason AS
(
SELECT y,s.* FROM @season as s
CROSS APPLY
(VALUES (@year), (@year+1)
) as t(y)
), cte_ranking as
(
SELECT *, row_number() over (order by y,SeasonOrder) as rnk
FROM CTE_YearSeason)
SELECT SeasonId, Y as year
FROM  cte_ranking as c
where c.rnk = (SELECT c1.rnk
from cte_ranking as c1
where c1.SeasonId = @SeasonId and c1.y = @year) +1

SeasonId
year

3
2021


text:
Q: Achieve 3D model using 2D horizontal polygons sorted by z-axis Please advise me.
I want to construct a 3D model in C++ using 2D horizontal polygons (actually a set of 2D points which form a closed contour) sorted by z-axis (Using frameworks like OpenGL).
How could I do that ?
Thanks.

A: A 3D model usually consists of a vertice array and a triangles array. The vertices are your points where the order is irrelevant.
The triangles array then contains only indices from the vertice-array and describes the triangles that way.
For example if your points are pA, pB, pC and stored in that order in the vertices array, then your triangles array contains 0, 1, 2.
However the actual details depend a lot on your implementation environment. Look up some examples in your desired engine.
By the way, if this is for a research project or stuff like that, I'd recomend a higher level engine than OpenGL. I did a thesis project about code-generated 3D models project by using Unity. That's C# instead of C++, but unless you need large models to be created in Realtime, the speed suffices easily and you will develop much more efficiently.

A: You can take a look at the DOOM engine from id Software, in which they used a very similar principle to display 3D scenes. Also, take a look at the Game Engine Black Book: DOOM
Briefly, the 2D polygons are converted into a BSP tree to create a set of convex nodes, which are then used for rendering. There are other resources for similar techniques, such as the Build engine which uses portal rendering.
Note that this technique you are trying to use has some limitations.


text:
Q: Zend_GData Spreadsheet - Invalid query parameter value for grid-id I am trying to update a google spreadsheet through Zend_GData library. I am sure the user ID and password is correct. I think the issue is with spreadsheet key or worksheet ID. Even I don't know exactly how to get this worksheetID. Kindly help me on this. This is the exact URL to m worksheet.
https://docs.google.com/spreadsheet/ccc?key=0AmW1-CVeX7oOdGRkYURWNXVMRi1DTW9NTGNhZ09OTGc&hl=en_US#gid=0
Here is my code.
$user = 'xxxxxxxxxxxxxxxxxxxxxx';
$pass = 'xxxxxxxxxxxxxxxxxx';
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$spreadsheetService = new Zend_Gdata_Spreadsheets($client);
$spreadsheetKey = "0AmW1-CVeX7oOdGRkYURWNXVMRi1DTW9NTGNhZ09OTGc";
$worksheetId = "Sheet1";
try
{
    $spreadsheetService->insertRow(array('Prasad','10000'),$spreadsheetKey,$worksheetId);

}
catch(Exception $error)
{

    echo $error->getMessage() ;

}

And this is the error message I see on my browser screen.
Expected response code 200, got 400 Invalid query parameter value for grid-id.

A: I fixed the issue. I could find the SpreadsheetKey and WorkSheetID by using bellow code.
$user = 'xxxxxxxxxxxxxxx';
$pass = 'xxxxxxxxxxxxx';
$service            = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$client             = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$spreadsheetService = new Zend_Gdata_Spreadsheets($client);
$feed               = $spreadsheetService->getSpreadsheetFeed();
$sheetName = "Test1";
foreach($feed->entries as $entry)
{
    if($entry->title->text == $sheetName)
    {
        $spreadsheetURL = $entry->id;
        break;
    }
}

$spreadsheetKey = basename($spreadsheetURL);

$query = new Zend_Gdata_Spreadsheets_DocumentQuery();
$query->setSpreadsheetKey($spreadsheetKey);
$feed = $spreadsheetService->getWorksheetFeed($query);

echo "Spreadskeet Key : $spreadsheetKey
";

foreach($feed->entries as $entry)
{
    echo "ID of sheet {$entry->title->text} is " . basename($entry->id) . "
";
}

Once I got those values also my script didn't work. Then I found that when we define the array the 'Key's should mentioned in lower case with no spaces.
$spreadsheetService->insertRow(array('name'=>'Prasad','value'=>'10000'),$spreadsheetKey,$worksheetId);

A: Please try this code also, tested and worked for me
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');

// set credentials for ClientLogin authentication
$user = "xxxxxxxxxxxxxxx";
$pass = "xxxxxxxxxxxxxxx";
try {
  // connect to API
  $service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
  $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
  $service = new Zend_Gdata_Spreadsheets($client);

  // get list of available spreadsheets
  $feed = $service->getSpreadsheetFeed();
} catch (Exception $e) {
  die('ERROR: ' . $e->getMessage());
}
foreach($feed->entries as $entry) {
    $spreadsheetURL = $entry->id;
}
$spreadsheetKey = basename($spreadsheetURL);
$query = new Zend_Gdata_Spreadsheets_DocumentQuery();
$query->setSpreadsheetKey($spreadsheetKey);
$feed = $service->getWorksheetFeed($query);
echo "Spreadsheet Key: $spreadsheetKey
";
foreach($feed as $entry) {
    $sName = $entry->title->text;
    echo "ID of sheet $sName is: ".basename($entry->id)."
";
}
?>


text:
Q: Slick: how to call stored procedure with read-write parameters I'm trying to call from Slick stored procedure which returns nothing but use read parameters as input and writable parameters as output. I combined (in Play application) SimpleDBIO tip found here,
old tip for calling stored proc in Slick 2.x and legacy jsp code calling this procedure:
@javax.inject.Singleton
class UserDao @Inject()(dbp: models.DatabaseProvider) {

def lookupUser(u: User): Boolean = {
    // param 1 is output one, params 2,3 are input ones
    val callProc = """{BEGIN CALL GET_USR_INF(?, ?, ?); END;}"""
    println (s">>>>>> p1. user=${u.username}")
    SimpleDBIO[Unit] {
        implicit session => {
            println (s">>>>>> p2 ")
            val cs = session.connection.prepareCall(callProc)
            // val cs = session.connection.prepareStatement(callProc)
            println (s">>>>>> p2.1 ")
            cs.registerOutParameter(1, java.sql.Types.INTEGER);
            cs.setString(2, u.username);
            cs.setString(3, u.password);
            println (s">>>>>> p3")
            val result = cs.executeUpdate()
            println (s">>>>>> p4. result=${result}")
            val retStatus = cs.getInt(1)  // general result here
            println (s">>>>>> p5. retStatus=${retStatus}")
        }
    }
    println (s">>>>>> p-end ")

but it looks like code inside SimpleDBIO is not running at all, points p2-p5 are not printed and no jdbc calls are traced. How to do it correctly? Where are not much newbie-level examples of SimpleDBIO around.
  DatabaseProvider definition is below if it matter:
import javax.inject.{Inject, Provider, Singleton}
import com.typesafe.config.Config
import slick.jdbc.JdbcBackend.Database  //some imports are skipped for brevity
@Singleton
class DatabaseProvider @Inject() (config: Config) extends Provider[Database] {
  lazy val get = Database.forConfig("myapp.database", config)
}

A: Well, looks like mentioned tip is not complete, one need to run declared SimpleDBIO somehow (do not laugh please, written for newbie like me). Instead of SimpleDBIO I found example for SimpleJdbcAction which is essentially the same. So working code is below:
    val a = SimpleJdbcAction { ctx =>
        val cs = ctx.connection.prepareCall(callProc)
        cs.registerOutParameter(1, java.sql.Types.INTEGER);
        cs.setString(2, u.username);
        cs.setString(3, u.password);
        val result = cs.executeUpdate()
        retStatus = cs.getInt(1)
    }
    Await.result(dbp.get.run(a), Duration.Inf)
    println (s">>>>>> p-end, s=$retStatus")


text:
Q: Changing location of Android Keystore I know this is a rather noob question, but surprisingly this hasn't been asked on SO before.
I recently launched my first application on Google Play, and had stored my Android Keystore on a flash drive as advised in The Busy Coder's Guide to Android Development. I am the only developer and so don't have problems related to sharing of the keystore with my peers.
But now I want to format the flash drive which, though not necessary, would certainly be better as it has some errors in it. So my question, can I actually back up the .jks file to some other location on my machine and still continue updating my app through it?

A: Yes.
The .jks file can be copied, e-mailed, compressed and uncompressed, et cetera and still be used like the original.


text:
Q: Error during harmonisation in TwoSampleMR (R-package)
I am trying to perform Mandalian Randomisation using the R package "TwoSampleMR".
As exposure data, I use instruments from the GWAS catalog. (Phenotype - Sphingolipid levels).
As a outcome data, I use GISCOME ischemic stroke outcome GWAS (http://www.kp4cd.org/index.php/node/391)
I have an error when I do harmonization by the command harmonise_data().
The text of the error is:
**Error in data.frame(…, check.names = FALSE) : arguments imply differing number of rows: 1, 0**.
I have noticed that the error is caused by some exact lines in the file with outcomes. When I make a text file that contains only one line from the original file and use it as outcome data, some lines cause an error, and someones don't.
As an example this one causes an error:
MarkerName CHR POS Allele1 Allele2 Freq1 Effect StdErr P-value
rs10938494 4 47563448 a g 0.2139 0.0294 0.0519 0.5706
This one doesn't:
rs1000778 11 61655305 a g 0.2559 0.0939 0.0493 0.05705
Here is all commands that I use.
library(TwoSampleMR)
library(MRInstruments)
data(gwas_catalog)
exp <- subset(gwas_catalog, grepl("Sphingolipid levels", Phenotype))
exp_dat<-format_data(exp)
exp_dat<-clump_data(exp_dat)
exp_dat
out_dat<-read_outcome_data(
 snps=exp_dat$SNP,
 filename='giscome.012vs3456.age-gender-5PC.meta1.txt'
 sep='\t', snp_col='MarkerName',
 beta_col='Effect',
 se_col='StdErr',
 effect_allele_col='Allele1',
 other_allele_col='Allele2',
 eaf_col='Freq1',
 pval_col='Р-value'
)
dat<-harmonise_data(exporsure_dat=exp_dat, outcome_dat=out_dat)

What would be the reason for this problem?
Thank you.

A: It is difficult to comment without looking at your sample input file but you might encounter this sort of error when there are inconsistencies with naming the exposure columns in your data frame.
Please see this thread on.
https://github.com/MRCIEU/TwoSampleMR/issues/226


text:
Q: How to solve selectOptions.some is not a function while using AsyncCreatableSelect? I am using AsyncCreatableSelect of react-select 2.0 to fetch the options from an API, but I am facing the following error as soon as I type something -
Creatable.js:126 Uncaught TypeError: selectOptions.some is not a function
    at isValidNewOption (Creatable.js:126)
    at Creatable.componentWillReceiveProps (Creatable.js:212)
    at callComponentWillReceiveProps (react-dom.development.js:13047)
    at updateClassInstance (react-dom.development.js:13260)
    at updateClassComponent (react-dom.development.js:14860)
    at beginWork (react-dom.development.js:15716)
    at performUnitOfWork (react-dom.development.js:18750)
    at workLoop (react-dom.development.js:18791)
    at HTMLUnknownElement.callCallback (react-dom.development.js:147)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
    at invokeGuardedCallback (react-dom.development.js:250)
    at replayUnitOfWork (react-dom.development.js:17998)
    at renderRoot (react-dom.development.js:18909)
    at performWorkOnRoot (react-dom.development.js:19812)
    at performWork (react-dom.development.js:19722)
    at performSyncWork (react-dom.development.js:19696)
    at requestWork (react-dom.development.js:19551)
    at scheduleWork (react-dom.development.js:19358)
    at Object.enqueueSetState (react-dom.development.js:12789)
    at Async.push../node_modules/react/cjs/react.development.js.Component.setState (react.development.js:354)
    at Async.js:168

This is what my component looks like -
<AsyncCreatableSelect
                name="search"
                value={this.state.search}
                styles={customStyles}
                placeholder={this.props.position+". Add Skill"}
                loadOptions={this.getOptions}
                onChange={this.updateValue}
                />

and this is the function I am calling for loadOptions -
getOptions(searchTerm){

        return fetch(`https://api.stackexchange.com/2.2/tags?order=desc&sort=popular&inname=${searchTerm}&filter=default&site=stackoverflow`)
        .then(results=>{
            return results.json();
        }).then(data=>{
            let options=[]
            for(let i in data.items){
                options.push({
                    value:data.items[i].name,
                    label:data.items[i].name[0].toUpperCase()+data.items[i].name.substring(1).split('-').join(' ')
                })
            }
            //console.log(options)
            return {'options':options.slice(0,7)}
        })
}

A: I answered in the git repo as well, but will follow up here as well in case it helps anyone else.
loadOptions is a function that passes two parameters: inputValue and callback. You need the second one to resolve the promise.
getOptions(searchTerm, callback){

       ...

        //console.log(options)
        callback(options.slice(0, 7));
  })
}

Please let me know if this helps.


text:
Q: How to @click change the data in the array with Vuejs I have a table with two-button Inch and CM, and I want to change the numbers from Inch to CM on click, Please can someone teach me how to do it

 data() {
        return {

          guild_size_inch: [
            {
              size: "S",
              chest: "92",
              length: "71"
            },
            {
              size: "M",
              chest: "40",
              length: "29"
            },
            {
              size: "L",
              chest: "44",
              length: "30"
            }
          ],
        }
      },

      methods: {
        changeToCM: function() {
          this.guild_size_inch * 2.54;
          alert(this.guild_size_inch)
        }
      }

A: You are trying to multiply the object instead of the numbers contains in your object.
What you should try is loop through your array and multiply both chest and length.
You can perform this with a forEach loop : see documentation here
changeToCM: function() {
   this.guild_size_inch.forEach(item => {
      item.chest = parseInt(item.chest) * 2.54
      item.length = parseInt(item.length) * 2.54
   });
   alert(this.guild_size_inch)
}

A: Define a property called currentUnit initially set to inch which will be changes by the click event, then use a computed property that returns the sizes based on the current unit which you selected :
 data() {
   return {
      guild_size_inch:[....],
      currentUnit:'cm'

   }
 },
computed:{
   sizes(){
      return this.guild_size_inch.map(size=>{
          size.chest=this.currentUnit==='cm'?size.chest*2.54:size.chest*2.54
          size.length=this.currentUnit==='cm'?size.length/2.54:size.length/2.54
         return size;
    })
  }
},
methods:{
  changeUnit() {
     this.currentUnit==='cm'?this.currentUnit='inch':this.currentUnit='cm'
 }
}

then render the sizes in the table.

A: I created a below code snippet as per your requirement. Please find the explanation of the logic inline in the snippet.

const app = new Vue({
  el: '#app',
  data() {
    return {
      guild_size_inch: [
        {
          size: "S",
          chest: "92",
          length: "71"
        },
        {
          size: "M",
          chest: "40",
          length: "29"
        },
        {
          size: "L",
          chest: "44",
          length: "30"
        }
      ],
      isInch: true, // property to enable/disable the 'Inch' button.
      isCM: false // property to enable/disable the 'CM' button.
    }
  },
  methods: {
    // Method used to convert the Inch values into CM.
    changeToCM() {
      this.isCM = true;
      this.isInch = false;
      this.guild_size_inch = this.guild_size_inch.map((obj) => {
        obj.chest = parseInt(obj.chest) * 2.54;
        obj.length = parseInt(obj.length) * 2.54;
        return obj;
      });
    },
    // Method used to convert the CM values into Inch.
    changeToInch() {
        this.isCM = false;
      this.isInch = true;
      this.guild_size_inch = this.guild_size_inch.map((obj) => {
        obj.chest = Math.ceil(parseInt(obj.chest) / 2.54);
        obj.length = Math.ceil(parseInt(obj.length) / 2.54);
        return obj;
      });
    }
  }
})

  <button @click="changeToInch" :disabled="isInch">Inch (Default)</button>
  <button @click="changeToCM" :disabled="isCM">CM</button>

    Size
    Chest
    Length

      {{ item.size }}
      {{ item.chest }}
      {{ item.length }}


text:
Q: What does [`something] some_vector ; mean in verilog? Let's say I have some define macro, and then some other wire that is defined.
 What does it mean when I have them like this? Is it just meaning to take the 2 LSBs from the wire?
`define A_DEFINE  32
// *SOME CODE IN HERE*
output  [`A_DEFINE-1:0] my_out_wire;
// *MORE CODE HERE*

I can't seem to find any explanation of this meaning.

A: The syntax `define A_DEFINE 32 declares a macro called A_DEFINE. A macro is a thing you can use for text replacement in your code.
The syntax `A_DEFINE means expand the A_DEFINE macro. This is essentially taking the value of A_DEFINE and copying in the place where the macro is expanded.
The preprocessor does this for you. In essence, you'll end up with:
// *SOME CODE IN HERE*
output  [32-1:0] my_out_wire;
// *MORE CODE HERE*

Defines are handy if you need to have a configurable element in your code. This way if you have multiple signals that are supposed to be as wide, you just use the define. In case you need to change from 32 to 64, you just modify the define and that's it.
Also have a look at the SystemVerilog parameter. This might also be helpful.


text:
Q: Url.Page returns current URL instead of mentioned Url.Page in ASP.NET Core doesn't returns the correct URL. As you can see in the image below it generate link to /identity/auth/register (which is current url) instead of /identity/auth/confrimemail

A: I have found the solution. I need to use Url.Action, since ConfrimEmail is action and not page.


text:
Q: Can I make an Active Spare disk permanent? We have a ProLiant ML350P Gen8 server with a P420 controller running ESXi 5.5.
It has a RAID 6 array using 7 disks.  One of the disks got marked as Predictive Failure, and in response to this we added an 8th disk to the array as a spare.
We ejected the failing drive, to make the array rebuild on the spare.  (Retrospectively, we probably could have achieved this more gracefully by setting the Spare Activation Mode.)
The spare is now active in the array, and the old disk is marked as Failed:
# /opt/hp/hpssacli/bin/hpssacli ctrl slot=2 pd all show

Smart Array P420 in Slot 2

   array A

      physicaldrive 1I:2:5 (port 1I:box 2:bay 5, SAS, 1200.2 GB, OK)
      physicaldrive 1I:2:6 (port 1I:box 2:bay 6, SAS, 1200.2 GB, OK)
      physicaldrive 1I:2:7 (port 1I:box 2:bay 7, SAS, 1200.2 GB, OK)
      physicaldrive 2I:2:1 (port 2I:box 2:bay 1, SAS, 1200.2 GB, OK)
      physicaldrive 2I:2:2 (port 2I:box 2:bay 2, SAS, 1200.2 GB, Failed)
      physicaldrive 2I:2:3 (port 2I:box 2:bay 3, SAS, 1200.2 GB, OK)
      physicaldrive 2I:2:4 (port 2I:box 2:bay 4, SAS, 1200.2 GB, OK)
      physicaldrive 1I:2:8 (port 1I:box 2:bay 8, SAS, 1200.2 GB, OK, active spare for 2I:2:2)

# /opt/hp/hpssacli/bin/hpssacli ctrl slot=2 array all show detail

Smart Array P420 in Slot 2

   Array: A
      Interface Type: SAS
      Unused Space: 0  MB (0.0%)
      Used Space: 7.6 TB (100.0%)
      Status: Failed Physical Drive
      Array Type: Data
      Spare Type: dedicated
      HP SSD Smart Path: disable

      Warning: One of the drives on this array have failed or has been removed.

So the array presumably has two disks' redundancy again, but this is obviously not the ideal state..
We would like to be able to make the active spare permanent, remove the failed drive from the array, and unassign it in the controller.
We tried to remove the ejected drive from the array configuration, but the controller was clearly not happy with this idea:
# /opt/hp/hpssacli/bin/hpssacli ctrl slot=2 array A remove drives=2i:2:2

Error: This operation is not supported with the current configuration. Use the
       "show" command on devices to show additional details about the
       configuration.
Reason: Array status not ok

Is there any way to do this, or do we just have to add another drive in the failed disk's old slot to relieve the spare, and let the array rebuild a second time?

A: In my experience, you won't get another rebuild. 2I:2:2 will become the spare.
Is there a reason you fear a rebuild? If you're worried about the performance hit, you could set the rebuild priority lower. Just make sure to switch it back once the rebuild completes. You don't want a drive to fail in the future and still be on a low priority rebuild.
/opt/hp/hpssacli/bin/hpssacli ctrl slot=2 modify rp=low

A: If the array is configured with a dedicated spare, you have the option to install a compatible SAS, 1200.2 GB drive into port 2I:box 2:bay 2.  That would trigger a rebuild from the current spare to the new drive.  The spare would then become available for future failures.
Needless to say you must leave the spare in place until the rebuild is complete.
If you did not configure the spare as dedicated then it has been assimilated into the array and future drives could then be configured as additional spares.


text:
Q: how to show date but data in my database type is datetime? i want the output to show the date. but in the same time i want to filter by time.
SELECT CAST(t.req_date as Date) as Date,
SUM(t.Transaction)+SUM(r.Request) as allTransaction,
SUM(t.Success)+SUM(r.RequestSuccess) as allSuccess,  t.Transaction,
t.Success, r.Request, r.RequestSuccess
FROM (select req_date, count(*) as transaction, sum(t.status = 0) as success
from transfer_tx_201503 as t WHERE CAST(t.req_date as Time) >='00:00:00' AND
CAST(t.req_date as Time) <= '23:00:00'
group by req_date desc) as t JOIN
(select req_date, count(*) as Request, SUM(r.status = 0) as RequestSuccess
from request_tx_201503 as r WHERE CAST(r.req_date as Time) >='00:00:00' AND
CAST(r.req_date as Time) <= '23:00:00'
group by req_date desc) as r
ON CAST(t.req_date as Date) = CAST(r.req_date as Date)
GROUP BY CAST(`date` as Date) desc

A: The most simple way would be to use date function on datetime column.
mysql> select date(now());
+-------------+
| date(now()) |
+-------------+
| 2015-03-30  |
+-------------+
1 row in set (0.00 sec)

A: i have find my own solution. i use cast() to convert the data type.
SELECT CAST(t.req_date as Date) as Date, SUM(t.Transaction)+SUM(r.Request) as
allTransaction, SUM(t.Success)+SUM(r.RequestSuccess) as allSuccess,
t.Transaction, t.Success, r.Request, r.RequestSuccess
FROM
(select req_date, count(DISTINCT no_a) as Transaction, sum(t.status = 0) as Success
from transfer_tx_201503 as t WHERE CAST(t.req_date as time)  BETWEEN '00:00:00' AND '$searchterm'
group by CAST(req_date as Date) desc) as t
JOIN
(select req_date, count(DISTINCT no_a) as Request, SUM(r.status = 0) as RequestSuccess
from request_tx_201503 as r WHERE CAST(r.req_date as time) BETWEEN '00:00:00' AND '$searchterm'
group by CAST(req_date as Date) desc) as r
ON CAST(t.req_date as date) = CAST(r.req_date as date)
GROUP BY Date desc


text:
Q: Array of forms in Angular 6 I have following requirement like:
In template:
<div *ngFor="let item of itemArray">
  <form [formGroup]="item.name">
    <input type="text" formControlName="release" />
    <button >Add more input box</button>
  </form>
</div>

In typescript:
it should be like form[] = ["form1","form2"];
    then access this form array forms controls.