text:
Q: How to access the method in another method? In this code, i am not able to call the user() method in facto1() method but I am not able to access the value of n in for loop
import java.util.*;
public class fecto {
    //Scanner sc = new Scanner(System.in);
    //int n;

    public int user() {
        Scanner sc = new Scanner(System.in);
        int n;
        System.out.println("Enter the number:");
        n = sc.nextInt();
        return n;
    }

    public int facto1() {
        int i, fac = 1;
        //int p = user();
        //System.out.println(p);
        user()
        for (i = 0; i <= n; i++) {
            fac = fac * i;
        }
        return fac;
    }

    public static void main(String[] args) {
        fecto fe = new fecto();
        fe.facto1();
    }
}

A: The call to user() does not store the result locally. Change
//int p = user();
//System.out.println(p);
user()
for (i = 0; i <= n; i++) {

to
int n = user(); // <-- you want `n`, not `p`.
for (i = 1; i <= n; i++) { // <-- 0 * x == 0, do not start with i = 0

Further, in main you aren't printing the result.
fecto fe = new fecto();
int result = fe.facto1();
System.out.println(result);


text:
Q: Infopath ,sharepoint 2013 I have a list in SharePoint 2013 which contain 4 checkbox.I want to calculate the percentage how many checkbox is selected?
I have full control.
I have access to InfoPath form.
for example. if 3 checkbox is checked total = 75%
I tried with avg() function in InfoPath but it is not working properly.
it shows correct output when all field is checked otherwise it shows "NaN".
I am not able to set default value of checkboxes to "1" or as Selected.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Did Chromecast update break debugging? Before the recent firmware update, web-based debugging (at port 9222) would persist between activities. Now any transition, say from the home screen to my app, stops the debugger with a message at the top saying...

Detached from the target
Remote debugging has been terminated with reason: target_closed.
Please re-attach to the new target.

It's not a huge problem to start a new debug window, but I'm worried that if the debugger isn't running when my app is loaded I won't get the benefit of the "Disable cache (while DevTools is open)" option.
Any details or workarounds would be appreciated.
UPDATE
Confirmed! In my case at least, the debugger stops with the above error and the latest version of my html, javascript, etc. does not get loaded

A: Try this as a work around and see if it works: when your page is loaded, run window.location.reload() in the debug console to reload the page (so you get a full debugging info from the beginning without missing anything) or window.location.reload(true) to do the same and clear cache as well.


text:
Q: Validadate old password with current password before change password i tried to change password. but i enter another password which is not used to login. With this i can change the password. How to check the old password and current password is same in mvc core

A: Here is a simple demo about how to reset the password:
1.Model:
public class Account
{
    public int Id { get; set; }
    public string Username { get; set; }
    [DataType(DataType.Password)]
    public string Password { get; set; }
}
public class LoginViewModel
{
    public string UserName { get; set; }
    [DataType(DataType.Password)]
    public string Password { get; set; }
}

2.View:
@model LoginViewModel
<form method="post" asp-action="Login">

        <input asp-for="UserName" />

        <input asp-for="Password" />

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

3.Controller:
public class HomeController : Controller
{
    private readonly WebApplication1Context _context;

    public HomeController(WebApplication1Context context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<IActionResult> Login()
    {
        return View();
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        var user =  _context.Accounts.Where(a => a.Username == model.UserName).FirstOrDefault();
        if (user != null)
        {
            if (user.Password == model.Password)
            {
                return RedirectToAction(nameof(Index));
            }
            var data = new Account()
            {
                Id = user.Id,
                Username = model.UserName,
                Password = model.Password
            };
            _context.Update(data);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Login));
        }

        return View();
    }
}

4.DbContext:
public class WebApplication1Context : DbContext
{
    public WebApplication1Context (DbContextOptions<WebApplication1Context> options)
        : base(options)
    {
    }

    public DbSet<Account> Accounts { get; set; }
}


text:
Q: How to remove elements which i find with find() jQuery? I have an element in which i want to find a specific class and remove those class.
example
editingElm = `<p><span class="editing-target">hello</span><span class="editing-target">Welcome to this virtual world</span></p>`

 let elements = editingElm.find('.editing-target');// elements= [span,span] with the class
    editingElm.removeClass('editing-target');

How can i loop over the elements array and remove those classes i found?

A: Remove class from elements instead of editingElm
editingElm = `<p><span class="editing-target">hello</span><span class="editing-target">Welcome to this virtual world</span></p>`

let elements = editingElm.find('.editing-target');// elements= [span,span] with the class

elements.removeClass('editing-target');


text:
Q: User can only enter O or E anything other than that will loop for correct input JAVA I am trying to code as user can only enter 'O' or 'E', other than that should prompt try again and allow user to enter again until valid input but i have tried few ways but couldn't solve it.
System.out.println("Lets play a game called Odds and Evens");
System.out.print("What is your name? ");`
Scanner input = new Scanner(System.in);
String name = input.next();
System.out.print("Hi "+ name + ", Which do you choose? (O)dds or (E)vens? ");
String select = input.next();
do {
    if(select.equalsIgnoreCase("O")) {
        System.out.println(name + " is Odd! The computer will be Even!");
    } else if(select.equalsIgnoreCase("E")) {
        System.out.println(name + " is Even! The computer will be Odd!");
    }
} while(!select.equalsIgnoreCase("e") || !select.equalsIgnoreCase("o"));

A: !select.equalsIgnoreCase("e") || !select.equalsIgnoreCase("o") will always be true. The input cannot be simultaneously equal to both "e" and "o", so it will be unequal to one of those. A good IDE will warn you about this by default. Also, the loop is not reprompting for input. Either way, it's going to spin forever.
How about something like this instead?
String select;
do {
    select = input.next();
    if(select.equalsIgnoreCase("O")) {
        System.out.println(name + " is Odd! The computer will be Even!");
    } else if(select.equalsIgnoreCase("E")) {
        System.out.println(name + " is Even! The computer will be Odd!");
    }
} while(!select.equalsIgnoreCase("e") && !select.equalsIgnoreCase("o"));


text:
Q: Правильное создание релизного приложения в visual studio 13 Подключил к проекту glut.h. Необходимо, что бы приложение запускалось на других устройствах. Как это сделать?
Что выставлять в настройках проекта и возможно ли вообще это сделать с подключенным OpenGL?


text:
Q: How to change icon image of button on mouse entered/mouse exit in java here's my code.
    private void caddMouseEntered(java.awt.event.MouseEvent evt) {
setRolloverIcon(Icon) (no need for the MouseListener)
        cadd = new javax.swing.JButton();
        cadd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/rent/PNG/Add-Male.png")));
        cadd.setBackground(Color.black);
        cadd.setForeground(Color.white);
        //v.setBackground(Color.black);
    }


text:
Q: HTML table for each date in multiple date range I currently have a table that stores a few events, it looks like that :
+----+---------+------------+
| ID |   Name  |    date    |
+----+---------+------------+
|  1 | Event1  | 2018-10-01 |
|  2 | Event2  | 2014-10-01 |
|  3 | Event3  | 2014-10-04 |
+----+---------+------------+

Then, I display it in multiple HTML table for each date :
$current_date = null;

while ($donnees = $reponse->fetch()) {
   $date = $formatter->format(date_create($donnees['date'])); //I translate the dateformat in french

   if ($date != $current_date) {
      $current_date = $date;
      echo "
";
      echo "

{$current_date}

";
      echo "
";
   }

   echo "
" . $donnees["name"] . "
";
}
echo "

";

And it displays this (which is what I expected) :
https://imgur.com/a/BHzoFjY (I'm sorry the date is in french format)
Now, I'd like to evolve my table so that some events can take place on several days :
+----+---------+----------------+--------------+
| ID |   Name  |   date_start   |   date_end   |
+----+---------+----------------+--------------+
|  1 | Event1  |   2018-10-01   |  2018-10-01  |
|  2 | Event2  |   2014-10-01   |  2018-10-05  |
|  3 | Event3  |   2014-10-03   |  2018-10-05  |
+----+---------+----------------+--------------+

The objective is to get more or less the same kind of HTML table as before, like that : https://imgur.com/a/KuPyoqe
If you want a real exemple, you can check this website : https://vide-greniers.org/01-Ain?_otid=home-list
It shows a lot of garage sales anywhere in France, and I'm trying to do the same for events in small cities !
A potential solution would be a calendar table, but I don't know how it works, and, if possible, I'd like to work on only one table (it sounds easier...)
Thanks a lot for your time ! :)

A: I think you simply need to change the logic of your if statement.
$current_date = date("Y-m-d");
while ($donnees = $reponse->fetch()) {
   $date_start = date_create($donnees['date_start']))
   $date_end = date_create($donnees['date_end']);
   if ($date_start <= $current_date && $date_end >= $current_date) {
      echo "
";
      echo "

";
      echo  $formatter->format($current_date);
      echo "

";
   }
   echo "
" . $donnees["name"] . "
";
   echo "

";
   $current_date = date("Y-m-d", strtotime("$current_date +1 day"));
}


text:
Q: Tie a select element to a input element in ruby/haml Have a ruby hash @vars
Would like a select control to display the keys, and an input element to display the value of the selected key.
Easy enough to do the first part, but I'm at a loss on how to use the select value to index the ruby hash.
%select{:name=>'var', :onchange =>"document.getElementById('var_val').value=value"}
  -@vars.each do |k,v|
    %option #{k}
%input#var_val{:type => 'text', :name => 'var_val', :value => '0'}

This successfully sets the input field to the selected text itself, but how do I set it to essentially @vars[select.value]?

A: I'm sure there's an easier way, but this seems to do the trick:
  %select{:id=>'var', :onchange =>"document.getElementById('var_val').value=this.options[this.selectedIndex].attributes[0].value"}
    -@vars.each do |k,v|
      %option{:name => v} #{k}
  %input#var_val{:type => 'text', :name => 'var_val', :value => @vars.first[1]}

Will hold out for a better answer...


text:
Q: A fair coin is tossed $5$ times. It is known that there are more than $2$ heads in the $5$ tosses. What is the probability... A fair coin is tossed $5$ times. It is known that there are more than $2$ heads in the $5$ tosses. What is the probability that there are exactly $3$ heads in the $5$ tosses?
I believe the answer is $\binom{5}{3}$, but I'm confused by the second sentence. How does this change the outcome?
Thanks for answering.

A: $$P(H=3|H> 2)= \frac{P([H=3] \cap [H>2])}{P(H>2)}=\frac{P(H=3)}{P(H>2)}$$
This is a trivial application of Bayes Theorem. What changes the probability here is the fact that we know the number of heads was at least 2. This information reduced the sample space for any further questions asked. For example if we ask what is the probability that number of heads is 1 when it is known that the number of heads was greater than 2. The probability is 0. This is an example of reduction of sample space.


text:
Q: Limiting the range of values allowed in multiple textboxes For my current assignment, I've been asked to create a form to allow customers to enter desired quantities of shoes in a textbox and then total the cost in a second textbox. However, the customer cannot purchase more than 3 of any one particular shoe. I attempted to do the first two shoes in the code below but am running into issues once I added the code for the second model.
    Private Sub btnCompute_Click(sender As Object, e As EventArgs) Handles btnCompute.Click
        Dim qntyClassy, qntyHigh As Double
        txtQntyClassy.Text = qntyClassy
        txtQntyHigh.Text = qntyHigh
        If 0 < Int(txtQntyClassy.Text) And Int(txtQntyClassy.Text) < 4 Then
            txtTotalClassy.Text = FormatCurrency(txtQntyClassy.Text * 43)
            txtQntyClassy.Text = Int(txtQntyClassy.Text)
        Else
            MsgBox("Enter a quantity no greater than 3.")
        End If
        If 0 < Int(txtQntyHigh.Text) And Int(txtQntyHigh.Text) < 4 Then
            txtTotalHigh.Text = FormatCurrency(txtQntyHigh.Text * 48.95)
            txtQntyHigh.Text = Int(txtQntyHigh.Text)
        Else
            MsgBox("Enter a quantity no greater than 3.")
        End If
    End Sub
End Class


text:
Q: Can I make both images with different opacity's on jquery hover I am trying to make the small plus rounded button to be with full opacity and still clickable on my effect
At the moment it is taking the opacity for the whole link (which i would like to stay like that), if i change the z-index it goes on top of the link but then it is not launching the fancybox.
.img-hover > a  {
    position:relative;
}
.img-hover {
    display:inline-block;
    position:relative;
    cursor:pointer;
}
.img-hover .hover {
    display:none;
    background:#000;
    border-radius:50px;
    height:35px;
    width:30px;
    font-size:42px;
    font-weight:bold;
    color:#fff;
    padding:10px 15px 20px 20px;
    position:absolute;
    cursor:pointer;
    right:180px;
    top:180px;
}

Here is the jsfiddle i created http://jsfiddle.net/W9uju/1/
Thanks in advance

A: Edit:
sorry, I've understood the opposite of what you re looking for, here an example with what you need:
http://jsfiddle.net/W9uju/9/

Use rgba or hsla as background color:
rgba(0,0,0,0.5);

rgba(
  0,  // R red
  0,  // G green
  0,  // B blue
  0.5 // A alpha
)

hsla(0,0%,0%,0.5);

hsla(
  0,  // H hue
  0%, // S saturation
  0%, // L lightness
  0.5 // A alpha
)

To provide fallback compatibility you should write:
background-color: #000; /* Old browsers (IE8<) */
background-color: hsla(0,0%,0%,0.5); /* Modern browsers */

A: You could set z-index and then use this snippet:
$(function() {
    $(".img-hover").hover(
        function() {
            $(this).children("a").fadeTo(200, 0.5).end().children(".hover").show();
        },
        function() {
            $(this).children("a").fadeTo(200, 1).end().children(".hover").hide();
        });
}).on('click',function(e){
    if($(e.target).hasClass('hover'))
        $(this).find('.fancybox')[0].click();
});

DEMO
On modern browsers, you could set pointer-events:none; too
DEMO pointer-events


text:
Q: How can a vector of integers hold objects if an integer is not a class? While I was reading C++ primer fifth edition I came across this definition of a vector:

A vector is a collection of objects, all of which have the same type.
Every object in the collection has an associated index, which gives
access to that object. A vector is often referred to as a container
because it "contains" other objects.

If I have a vector of integer values then what class do all these objects belong? Because "int" is not a class as these answers from this link already explain:
Is int (built in data types) a class in c++?
I also came across the concept of "Data Objects" from IBM, are these the objects that the vectors hold in this case? Because I have been reading this concept of "Data object" a lot and it still puzzles me. And even if it is the object that the vectors hold, my question still remains: what class does it belong?

A:
If I have a vector of integer values then what class do all these objects belong?

No class at all. The elements of a vector of integers are objects of the integer type. Integer types are fundamental types.


text:
Q: Is there any code that can use to find complete cases in JSON? I'm new to the JSON thing. But I need to know which of the responses contains NA or missing values. Do anyone knows any code can be used in Python to print out the responses that are not completed.
This type of response that I have. The example below shows that ID 134-bc has no age, gender and job information.
[{"user_id":"123-ab",
"language":"English",
"demographic_data":{"age":22,"gender":"F","job":4}
"responses":{"Question 1":3,"Question 2":2,"Question 4":1}},
{"user_id":"134-bc",
"language":"Chinese",
"demographic_data":{"age":"","gender":"","job":""}
"responses":{"Question 1":3,"Question 2":2,"Question 4":1}},
{"user_id":"123-bc",
"language":"Chinese",
"demographic_data":{"age":"21","gender":"M","job":2}
"responses":{"Question 1":3,"Question 2":2,"Question 4":1}}
]

Output
I want it in two separate files.
The complete cases in one file.
[{"user_id":"123-ab",
"language":"English",
"demographic_data":{"age":22,"gender":"F","job":4}
"responses":{"Question 1":3,"Question 2":2,"Question 4":1}},
{"user_id":"123-bc",
"language":"Chinese",
"demographic_data":{"age":"21","gender":"M","job":2}
"responses":{"Question 1":3,"Question 2":2,"Question 4":1}}
]

The uncomplete cases in another file that will have probably more than this example.
[{"user_id":"134-bc",
"language":"Chinese",
"demographic_data":{"age":"","gender":"","job":""}
"responses":{"Question 1":3,"Question 2":2,"Question 4":1}}
]

A: In a Python dict, you can test whether attributes are totally missing with in or not in.  If you consider a blank field as "missing", then you can use dict.get(), which returns None for missing data.
DEFAULT_FIELDS = ["age", "gender", "job"]

def is_missing_data(record, field_names=None):
    field_names = DEFAULT_FIELD_NAMES if field_names is None else field_names
    demographic_data = record["demographic_data"]

    # If "not all" fields are present/truthy, then some data is missing.
    return not all(demographic_data.get(name) for name in field_names)

Then, you can split data as follows:
incomplete_records = [rec for rec in records if is_missing_data(rec)]
complete_records = [rec for rec in records if not is_missing_data(rec)]

with open('incomplete.json', 'w') as f:
    json.dump(incomplete_records, f)

with open('complete.json', 'w') as f:
    json.dump(complete_records, f)

A: Try using the below code to output the txt files:
with open('complete cases.txt', 'w') as f, open('incomplete cases.txt', 'w') as f2:
    f.write(str([i for i in list_of_json if i['demographic_data']['age']]))
    f2.write(str([i for i in list_of_json if not i['demographic_data']['age']]))

A: You can do a couple things:
Check for the existence of the key:
'key' in [userid] #return true or false

Likewise if it is not present:
if 'key' not in [userid]:
    return something

Check if the key has a value, else return default value:
userId.get('key', 'null')

def get_attribute(data, attribute, default_string):
    return data.get(attribute) or 'default_string'


text:
Q: Azure pipeline - dotnet swagger tofile --output this is my first post @stackoverflow :)
I would really appreciate your help.
Currently the service pipelines create only a hardcoded version 1.0.0 of ApiClients. I need to able to detect and create all the ApiClients present in the application.
Input:
arguments: >-
tofile
--output $(Build.SourcesDirectory)/$(sourceFolderPrefix).V1.json
$(sourceFolderPrefix).Api.dll
v1
Output: (from pipeline)
/opt/hostedtoolcache/dotnet/dotnet swagger tofile --output /home/vsts/work/1/s/<cust_name>.V1.json  <cust_name>.Api.dll v1
json file contains:
{
"openapi": "3.0.1",
"info": {
"title": "<cust_name>",
"version": "1.0"
}
If the application version change, the name of the json should be with the new version too.
Not sure if I explained it well, I don't even proper know how it works. I have google it and read docs but everywhere is v1, v2 or v3..
Thanks gurus!
google, read documentations, ask friends


text:
Q: Does $(document).off('.data-api') have an "on" equivalent? In a project where we use Bootstrap, we have a page where lots of partial tempaltes can be loaded in the centre, using ajax.
In a partial template, I have a modal, but it doesn't work, because the behaviour needs to be bound somehow. I could manually bind it as part of the template, but I feel this is too messy.
I'd like to be able to "refresh the API to allow the behaviour i need.
I've seen that the following function $(document).off('.data-api') will unbind all the functions associated with that API.
Is there an equivalent where I can manually turn it back on? Or otherwise update the binding in a general way that takes care of any new content?
Perhaps I'm going about this the wrong way and another solution or approach is better?

A: $(document).off( events [, selector ] [, handler(eventObject)]) is the right syntax for this.
So, you pass the even as the first param in the function and then selector. or you can unbind all the events from particular selector like: $(document).off();
use any of them and then try biding with $(document).on(event, [selector], [handler]);
Good luck!


text:
Q: cannot open source file "d3dx9.h" I've been having problems with this for months, I've looked at many pages and still couldn't fix it.
I'm on windows 10, using Visual Studio 2019, I've added this to include directories -> C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Include, and this to my library directories C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Lib\x86. I've also tried adding this to my include and library directories -> $(DXSDK_DIR)Include, $(DXSDK_DIR)Lib\x86.

A: Your paltform is x64, but your settings C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Lib\x86 and  are x86. So, I suggest that you should make sure that these two settings are consistent.


text:
Q: Passing javascript parameter into flask/sqlAlchemy/python database Trying to pass javascript number variable with GET request into flask/sqlAlchemy/python file so that I can sort and retrieve data using that parameter
The variable I am referring to is user1
See below for code that I have tried. I know that I am close but do not know where to go from here. Right now I have hardcoded the variable "user1" to 32 but will be making it dynamic once the basics work.
As of right now I am trying to pass user1 with
JAVASCRIPT FILE:
    const user1 = "32"; // PASSING THIS VARIABLE IN
    try {
      const response = await fetch(
        `http://localhost:5000/produce/<${user1}>/`,
        {
          method: "GET",
          headers: { "Content-Type": "application/json" }
        }
      );

PYTHON FILE:
@app.route('/produce/<user1>', methods=['GET'])
def produce_get_user(user1):
    user_id=user1
    print("INCOMING ID", user_id)

The print statement in the python file never gets executed.
The following is the message outputted by the backend python file:
[25/Mar/2019 12:17:03] "OPTIONS /produce/%3C32%3E/ HTTP/1.1" 404 -
The following are the two messages outputted by the javascript:
error#1
OPTIONS http://localhost:5000/produce/%3C32%3E/ 404 (NOT FOUND)
error#2
Access to fetch at 'http://localhost:5000/produce/%3C32%3E/' from origin 'http://localhost:3000' has been blocked by CORS policy:


text:
Q: Galois theory, resolvent, Frobenius group I need to prove that the Galois group of the polynomial $x^5+15x+12\in \mathbb{Q}[x]$ is the Frobenius group of order 20.
The discriminant of that polynomial is $D=2^{10}\cdot 3^4\cdot 5^5$, i.e. it is not a square and therefore not a subgroup of the alternating group $A_5$. So far so good, it shows me that it can't be $D_{10},Z_5$ or $A_5$, but how can I show, that the Galois group is not the symmetric group $S_5$?
In my paper they often mention a so-called resolvent method. But unfortunately they don't describe how this is done exactly. How is a resolvent polynomial constructed? Or how would you prove that the corresponding Galois group is not $S_5$?
Thank you already in advance.

A: Here's some incomplete work that someone might be able to help me patch up:
Let's view $\operatorname{Gal}(f)$ as a permutation group acting on the roots of $f$.  It is a theorem that a $2$-cycle together with a $p$-cycle generates the entire symmetric group $S_p$.  Using this as motivation, we first show that $\operatorname{Gal}(f)$ contains a $p$-cycle.  Let $\alpha$ be a root of $f$ and consider the tower of fields $\mathbb{Q} \subset \mathbb{Q}[\alpha] \subset K$, where $K$ is the splitting field of $f$.  Since $f$ is irreducible (guaranteed by Eisenstein), then we know $\mathbb{Q}[\alpha]$ is a degree $5$ extension of $\mathbb{Q}$.  Therefore, $5$ divides $[K: \mathbb{Q}] = |\operatorname{Gal}(f)|$, and by Cauchy's theorem, $\operatorname{Gal}(f)$ therefore contains an element of order $5$, which is necessarily a $5$-cycle in $S_5$.
Given our work above, showing $\operatorname{Gal}(f) \ncong S_5$ is equivalent to showing that it does not contain a $2$-cycle.  Since $f$ has four complex roots, complex conjugation is out of the question (this will be a composition of $2$-cycles).  With some work that I won't include at the moment, I have also shown that $( \text{Real Root} ) \mapsto ( \text{Any of the complex roots} )$ cannot be a $2$-cycle.
All that remains to show is that $\text{Complex root} \mapsto \text{Another complex root that is not its conjugate}$ is not a $2$-cycle.
I will post what I have in the hopes that it'll help you or someone else finish up.  In the meanwhile, I'll give this some more thought.  Ultimately, I will delete my answer if nothing fruitful comes of it.

A: The $F_5$ resolvent of the quintic $x^5 + 15x + 12$ is $$y^{6} + 120 y^{5} + 9000 y^{4} + 540000 y^{3} + 20250000 y^{2} + 324000000 y$$ (calculated using a computer algebra system)
This has an obvious rational root $y=0$ which implies the Galois group is contained in the Frobenius group $F_5$.
This answer is probably not very helpful, since the formula for the resolvent is so long and complex it may have been just as easy to ask the computer for the Galois group directly. Anyway I hope it's of some interest.


text:
Q: How to install a trial version of Sitecore I want to explore Sitecore CMS more. However, I am not able to download any trial or free version of Sitecore.
https://dev.sitecore.net/Downloads/Sitecore_Experience_Platform/100/Sitecore_Experience_Platform_100.aspx
Is there any community edition or free version provided by Sitecore?

A: As of December 12, 2020 there has been a change in how you can access downloads for Sitecore software. You no longer need the proper license or certification or even to login to download the software. You will still need a license to run the software, though.
Sitecore software is now available to download for everybody, anywhere in the world, no restrictions.

A: As you mention the Url for Sitecore download this is correct, but if you want to download you need to be certified for that. Once you have been certified the you get the Sitecore user detail for Dev Portal then you will get the option.


text:
Q: ¿Cómo acceder a un atributo de un select en javascript? encontré la respuesta a esta pregunta pero con jQuery como acceder a un atributo de un select con jquery? y he estado tratando de pasar la respuesta a javascript pero no lo consigo dejo el código aquí del enlace
function elegirsaldo(el){ // recibimos por parametro el elemento select
  // obtenemos la opción seleccionada .
  var saldo = $('option:selected', el).attr('parametro2');
  console.log(saldo);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="idgiftpro" onchange="elegirsaldo(this);">
  <option value="0" parametro2="0">Seleccionar</option>
  <option value="1"  parametro2="10">50</option>
  <option value="2"  parametro2="20">100</option>
  <option value="3"  parametro2="30">200</option>
</select>

A: Puedes usar [selector].selectedOptions[0] para obtener la opcion seleccionada (selectedOptions puede tener mas de un valor si es multiple)

function elegirsaldo(el){ // recibimos por parametro el elemento select
  // obtenemos la opción seleccionada .
  var saldo = el.selectedOptions[0].getAttribute('parametro2');
  console.log(saldo);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="idgiftpro" onchange="elegirsaldo(this);">
  <option value="0" parametro2="0">Seleccionar</option>
  <option value="1"  parametro2="10">50</option>
  <option value="2"  parametro2="20">100</option>
  <option value="3"  parametro2="30">200</option>
</select>


text:
Q: UIProgressView+Activity Indicator View on a UITableView during data upload I have a uitableview.
I saw this "effect" and I would replay it:
When the user taps on a button to upload some data on a server, I would a gray (transparent) view with a progress bar (maybe with also an activity indicator) appears on the table.
The table is disabled and can be viewed through the gray view (that is the gray transparent view covers all the table).
How can I achieve this?
Have I create a view with a progressive view on it and then put it in the same xib of the table, disabling it properly programmatically? Or?

A: Lay a large black UIView over top of the UITableView with an alpha value of 0.5. Then put a spinner (UIActivityIndicatorView) on top of that.
Something like this:
UIView *view = [[UIView alloc] init];
view.frame = myTableView.frame;
// save this view somewhere

UIActivityIndicatorView *ac = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
CGRect frame = view.frame;
ac.center = CGPointMake(frame.size.width/2, frame.size.height/2);
[view addSubview:ac];
[ac startAnimating];
[ac release];

[myTableView addSubview:view];
[view release];

Then remove it later with [view removeFromSuperview]


text:
Q: Azure sql server backup to Azure blob - CherrySafe replacement I am new to Azure SQL server and trying to understand how do I backup Azure SQL databases to Azure blob few times a day.
My company is currently using [Cherry Safe][1] to backup Azure SQL Databases but Cherry Safe is shutting down in 2 weeks.
As I read more about it, it seems like I can configure export to Azure blob but I do not see that option. I see history of exports but I do not know where is the configuration to schedule or change it.
For long term retention, I see an option to configure retention vault.
Are there replacement services out there that Cherry Safe users are using?
Do I need an external service or I can configure the backups myself?
Thanks.

A: It seems that you could backup sql server to azure blob storage, not the azure sql server.

You could use SQLBackupAndFTP to backup Azure sql database to local machine.
1.Connect SQLBackupAndFTP to the logical SQL Server in the Azure

2.Create a job for regular Azure SQL Database backup

Also as you have said, you could use long-term backup retention to backup.
It allows you to preserve weekly, monthly, and yearly backups for an extended period of time up to 10 years.

Restore a database from a specific long-term backup if the database has been configured with a long-term retention policy. This allows you to restore an old version of the database to satisfy a compliance request or to run an old version of the application. See Long-term retention.

A: You don't need to use any third party to backup Azure SQL database, they have much better backup and retention tool on portal. Read this https://learn.microsoft.com/en-us/azure/sql-database/sql-database-long-term-backup-retention-configure


text:
Q: stack with jquery - accordion I have code sample here
I want is when the accordion close color back to yellow.
"In the sample when i click the red to close the tab color will change to yellow"
$("#accordion > li").click(function(){
  $('.active').removeClass('active');

  $(this).addClass('active');
    if(false == $(this).next().is(':visible')) {
        $('#accordion > ul').slideUp(300);
    }
    $(this).next().slideToggle(300);
});

var animationIsOff = $.fx.off;
$.fx.off = true;
$('#accordion > li:eq(0)').click()
$.fx.off = animationIsOff;

A: Toggle the class instead of unconditionally adding it. Here is a demonstration:
$("#accordion > li").click(function () {
    $('.active').not(this).removeClass('active');

    $(this).toggleClass('active');

    if (false == $(this).next().is(':visible')) {
        $('#accordion > ul').slideUp(300);
    }

    $(this).next().slideToggle(300);
});


text:
Q: Issues with Php Music File Uploader So I'm trying to upload music files with php but the files aren't going to the folder, here's my code what are my mistakes and what am i missing
        <form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="text" placeholder="File Name" name="file_name">
    <input type="text" placeholder="Artist Name" name="artist_name">
    <textarea rows="5" placeholder="Description" name="description"></textarea>
    <input type="submit" class="btn btn-warning bgcolor" name="submit" value="Upload"/>
    </form>

    <?php
    if(isset($_POST['submit'])){
    function GetMusicExtension($musictype)
         {
           if(empty($musictype)) return false;
           switch($musictype){
               case 'audio/mp3': return '.mp3';
               default: return false;
           }
        }

        if (!empty($_FILES["file"]["name"])) {

            $file_name=$_FILES["file"]["name"];
            $temp_name=$_FILES["file"]["tmp_name"];
            $music_type=$_FILES["file"]["type"];
            $size = $_FILES['file']['size'];
            $ext= GetMusicExtension($music_type);
            $musicname = $_POST['file_name'].$ext;
            $target_path = "music/".$musicname;

        if(move_uploaded_file($temp_name, $target_path)) {
            $query = "insert into music(name,artist,description)
            values('".$musicname."','".$_POST['artist_name']."','".$_POST['description']."')";
            mysqli_query($link,$query) or die("error in $query == ----> ".mysqli_error($link));
            }
        }else{

           exit('<script>alert("Error Saving Data... try again");</script>');
        }
    }
    ?>

PS: If i change the mime to an image mime and try uploading it uploads
UPDATE:
If i change post_max_size and upload_max_size it works. Thanks all.


text:
Q: About wrapper class
Possible Duplicate:
Wrapper class in java

I learnt about wrapper class that it is used to wrap the primitive values. Can any of you explain me about Wrapper class in detail? Why should we go for wrapper class and when?

A: You need a wrapper class (like Integer, or Byte) when you want to use a primitive data type in a place where only Objects are accepted (for example to add them to a Collection).
There is no class Wrapper, but you have a separate class for every primitive type (Integer for int, Boolean for bool, Byte for byte, and so on).
How these wrapper classes work is that they are objects that have a instance field with the primitive they wrap. Also, in Java5 the compiler knows how to automatically convert between them and the primitives (which is called boxing/unboxing).
When designing an API, you should take a primitive  as a method argument when it is not an optional parameter. When it is optional, you should use a wrapper so that null can be used.
For example
List<String> result = search( "keyword", limit);
// you can set a limit (Integer) or leave it null (no limit).
// easier to understand (I think) than using -1 or 0 or Integer.MAX_VALUE


text:
Q: React Hook "useState" is called in function I have button click system and it works.
function clickCreate(msg){
    console.log(msg);
}
const CreateButton = (props) =>{
  return(

     clickCreate("test")} id="createBtn" className="fas fa-5x fa-microphone-alt">

  );
}

Now I want to fetch the API inside the function.
So, change the function clickCreate like this
function clickCreate(msg){
  const [result, setResult] = useState([]);
  useEffect(() => {
    axios.get('http://localhost:8000/api/genres/')
      .then((res)=> {
      console.log(res.data.items);
      setResult(res.data.items);
    }).catch(err=>{console.log(err);});
  }, []);
}

However there comes error like this.
I should not use useState and useEffect in function, but how can trigger the API by btn click??
./src/views/Components/Components.js
  Line 168:31:  React Hook "useState" is called in function "clickCreate" which is neither a React function component or a custom React Hook function   react-hooks/rules-of-hooks
  Line 170:3:   React Hook "useEffect" is called in function "clickCreate" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

Search for the keywords to learn more about each error.

A: You should move the hook to component level (Rules of hooks), then you can fetch on click and use the hook's setter:
const CreateButton = (props) => {
  const [result, setResult] = useState([]);

  // should be in scope with `setResult`
  function clickCreate() {
    axios
      .get("http://localhost:8000/api/genres/")
      .then((res) => {
        console.log(res.data.items);
        setResult(res.data.items);
      })
      .catch((err) => {
        console.log(err);
      });
  }

  return (

  );
};

A: I think a better approach would be to move the function in the component and take useState out.
const CreateButton = (props) =>{
  const [result, setResult] = useState([]);

  const clickCreate = async (msg) => {
      console.log(msg);
      let res = await axios.get('http://localhost:8000/api/genres/');
      setResult(res.data.items);
  }

  return(

     clickCreate("test")} id="createBtn" className="fas fa-5x fa-microphone-alt">

  );
}


text:
Q: How do you merge the two functions (32-x)/4=y and (48-x)/2=y into one? There are two functions: $\frac{32-x}4=y$ and $\frac{48-x}2=y$
For instance, if the two $x$s are $18$ and $24$, the two $y$s will be $3.5$ and $12$. I would like to add the two $x$s and two $y$s: $18+24=42$, $3.5+12=15.5$.
How can I merge the two functions into only one so that I set the $x=42$, I can directly get the $y=15.5$?

A: You have the two functions
$$y_1 = (32-x_1)/4 \\
y_2 = (48-x_2)/2$$
Adding them together gives
$$y_1+y_2 = (32-x_1)/4 + (48-x_2)/2$$
which can be simplified to
$$y_1+y_2 = (128-(x_1+2x_2))/4$$
or
$$Y = (128-X)/4$$
where $Y=y_1+y_2$ and $X=x_1+2x_2$.
This is not a function of $x_1+x_2$, which you wanted, but it is a function of $x_1+2x_2$ instead.
So for your example, instead of an input of $18+24=42$ you will have to use an input of $18+2*24=66$ to get your answer of $15.5$.

A: COMMENT.- It is not possible because you have TWO  DISTINCT functions. However if you remember the theory of conics it is a fact that there are cases in which the conic is degenerate to two right lines.
Because of you have two distinct lines $$ 32-x=4y\\24-x=2y$$ if you make the product
$$(32-x-4y)(24-x-2y)=0$$ you get a degenerate conic whose graph is exactly the graph of the two lines above.

A: If I am right, your hope is to obtain a linear function $$y=ax+b$$
from two other linear functions
$$y=a'x+b'$$ and$$y=a''x+b''$$ in such a way that the image of the sum of two $x$'s is the sum of the corresponding $y$'s:
$$a(x_1+x_2)+b=a'x_1+b'+a''x_2+b''.$$
For this to occur, you need to identify the coefficients and ensure
$$\begin{cases}a=a'\\a=a'',\\b=b'+b''.\end{cases}$$
Then if $a'\ne a''$, this is impossible.

The best that you can do is to realize the equality for two particular pairs of $x$ values, say $x_1,x_2$ and $x_3,x_4$. After solving a $2\times2$ system for $a$ and $b$, there will be an infinity of pairs $x_5,x_6$ such that
$$a(x_5+x_6)+b=a'x_5+a''x_6+b'+b'',$$ for instance by setting
$$x_6=-\frac{(a'-a)x_5+b'+b''-b}{a''-a}.$$


text:
Q: 2D array or 2D slice for Tic-Tac-Toe board? I started to learn GoLang and meet trouble. When i tried to pass array (which size is defined after enter them from output) to the function a get error like "sorry but you type [][]string is not like [][]string". I tried different ways but can't cope with it. Any suggestions?
There is the main func:
func main(){
fmt.Println("Enter number of rows: ")
fmt.Scanf("%d", &size)
var board [size][size]string
for i:=0;i<size;i++{
    for j:=0;j<size;j++{
        board[i][j] = "_"
    }
}
fmt.Println("Choose side of fight (X, 0): ")
fmt.Scanf("%s", &opt)
fmt.Printf("Your side is %s\n", opt)
for !win{
    printBoard(board, size)
    fmt.Println("Your move(a b, \"a\" is number of row, \"b\" is number of column: ")
    fmt.Scanf("%d %d", &move[0], &move[1])
    if move[0]>=1 && move[1]>=1 && move[0]<=3 && move[1]<=3{
        board[move[0]-1][move[1]-1] = opt
    }
    bot(&board, size)
    win, winner = checkWin(board, opt, size)
}
}

And example of function which depart take array:
func printBoard(in [][]string, size int){
for k:=0;k<size+1;k++{
    fmt.Printf("%d\t", k)
}
fmt.Println()
    for i:=0;i<size;i++{
        fmt.Printf("%d ", i+1)
    for j:=0;j<size;j++     {
        fmt.Printf("\t%s", in[i][j])
    }
    fmt.Print("\n")
}
fmt.Print("\n")
}

The ouput that I am trying to achieve is for Tic/Tac toe game. for eg:-
Enter number of rows: 3 Choose side of fight (X, 0): X
Your side is X  0   1   2   3   1 _ _   _ 2 _   _   _ 3 _   _   _
Your move(a b, "a" is number of row, "b" is number of column: 1 1 0 1   2   3   1 X _   _ 2 _   _   _ 3 _   _   _
Your move(a b, "a" is number of row, "b" is number of column: 2 2 0 1   2   3   1 X _   _ 2 _   X   _ 3 _   _   _
Your move(a b, "a" is number of row, "b" is number of column: 3 3 0 1   2   3   1 X _   _ 2 _   X   _ 3 _   _   X You're winner!!!

A: Don't use Go arrays. Array size is a compile-time constant. An array, the entire array, is passed by value as an argument to a function parameter or receiver.
Use slices. Declare a slice-based Board type. Give the type a set of methods; pass that type as the method receiver.

For example,
package main

import "fmt"

type Board [][]string // [rows][cols]

func NewBoard(rows, cols int) Board {
    b := make([][]string, rows)
    for r := range b {
        b[r] = make([]string, cols)
    }
    return Board(b)
}

func (b Board) Rows() int {
    return len(b)
}

func (b Board) Cols() int {
    if len(b) == 0 {
        return 0
    }
    return len(b[0])
}

func (b Board) Print() {
    maxWidth := 0
    for r := range b {
        for c := range b[r] {
            if width := len(b[r][c]); maxWidth < width {
                maxWidth = width
            }
        }
    }
    width := maxWidth + 2
    for r := range b {
        for c := range b[r] {
            fmt.Printf("%-*s", width, b[r][c])
        }
        fmt.Printf("\n")
    }
}

func main() {
    rows, cols := 3, 2 // input from user?
    board := NewBoard(rows, cols)

    for r := range board {
        for c := range board[r] {
            board[r][c] = fmt.Sprintf("[R%d, C%d]", r, c)
        }
    }
    board.Print()

    fmt.Printf("\n%v\n%v %v\n%v\n",
        board,
        board.Rows(), board.Cols(),
        board[1][1],
    )
}

Output:
[R0, C0]  [R0, C1]
[R1, C0]  [R1, C1]
[R2, C0]  [R2, C1]

[[[R0, C0] [R0, C1]] [[R1, C0] [R1, C1]] [[R2, C0] [R2, C1]]]
3 2
[R1, C1]

References:
The Go Blog: Go Slices: usage and internals
The Go Programming Language Specification

A: In Go []string is a slice and [42]string is an array. Those types are very different.
See https://blog.golang.org/slices
In this case you should use slices as the board is of variable size.
board := make([][]string, size)
for i:=0;i<size;i++{
    board[i] = make([]string, size)
    for j:=0;j<size;j++{
        board[i][j] = "_"
    }
}

A: Since you are passing an array when calling printBoard function but in function definition you have passed Slice as an argument that's why the error of type mismatch. So my suggestion will be you can pass slice to the printBoard function.
func main() {
    fmt.Println("Enter number of rows: ")
    fmt.Scanf("%d", &size)
    var board [][]string
    board = make([][]string, size, (2*size)+1)

    fmt.Println("Choose side of fight (X, 0): ")
    var opt int
    fmt.Scanf("%s", &opt)
    fmt.Printf("Your side is %s\n", opt)
    var win bool
    for !win {
        printBoard(board, size)
        fmt.Println("Your move(a b, \"a\" is number of row, \"b\" is number of column: ")
        fmt.Scanf("%d %d", &move[0], &move[1])
        if move[0] >= 1 && move[1] >= 1 && move[0] <= 3 && move[1] <= 3 {
            board[move[0]-1][move[1]-1] = opt
        }
        bot(&board, size)
        win, winner = checkWin(board, opt, size)
    }
}

For more information on Slice Check Go Slices: usage and internals blog


text:
Q: "git merge --squash" with libgit2 Is it possible to perform a squash-type merge through libgit2?
Adding some filler words to satisfy SO's "inadequate" message size restriction. I know, it's beyond ridiculous :D

A: The typical merge workflow involves calling git_merge to merge into the working directory and index, checking for conflicts, and then calling git_commit with multiple parents (the HEAD and the upstream commits you're merging).
To emulate --squash simply omit the commit (or commit with HEAD as the only parent). In either case you want to explicitly clean up the merge state with git_repository_state_cleanup.


text:
Q: using hyperlink column in gridview and getting 'does not exist in the current context' error in page_load HI,
I have a HyperLink column in a gridview that when clicked should navigate the user to another page. I pass parameters to the page using a querystring. I am implemeting this action in the grid's onrowdatabound event. here is the code:
            HyperLink btnDetails = (HyperLink)ea.Row.FindControl("btnDetails");
            btnDetails.NavigateUrl = "ManageFlaggedSecurities.aspx?portfolioID=" + obPortfolioId.ToString() + "&testID=" + obTstId.ToString();

I can set a breakpoint in my page_load event of the ManageFlaggedSecurities page but when I want to check the values of some string parameters i set  I get 'does not exist in the current context' on the variables. I even tried something simple like
string strTest = "testing";
and got the error. What am I doing wrong?
Mike

A: It sounds like you are trying to access variables declared inside the event handler while having a break point on Page_Load, hence having them out of scope, or trying to access variables that were declared in the caller up the stack.
Show some code...


text:
Q: Sage Pay / Opayo Form integration - replacing mcrypt with openssl We use the Sage Pay / Opayo form integration to pass customer orders to Sage Pay for payment, then to process the report that comes back.
Sage Pay's example code relies on the PHP mcrypt functions which are no longer supported from PHP 7.2, so we need to update the scripts to OpenSSL.
Encryption was covered by a great post here:
Upgrade mcrypt to OpenSSL encryption in SagePay form

*

*this works fine for me:

    function encryptAes_new ($string, $key) {
      $key = str_pad($key,16,"\0"); # if supplied key is, or may be, less than 16 bytes
      $crypt = openssl_encrypt($string, 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $key);
      // Perform hex encoding and return.
      return "@" . strtoupper(bin2hex($crypt));
    }

...but I can't find a matching code to fix the decrypt function.
The current code is:

    function decryptAes($strIn, $password)
    {
        // HEX decoding then AES decryption, CBC blocking with PKCS5 padding.
        // Use initialization vector (IV) set from $str_encryption_password.
        $strInitVector = $password;

        // Remove the first char which is @ to flag this is AES encrypted and HEX decoding.
        $hex = substr($strIn, 1);

        $strIn = pack('H*', $hex);

        // Perform decryption with PHP's MCRYPT module.
        $string = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, $strIn, MCRYPT_MODE_CBC, $strInitVector);
        return removePKCS5Padding($string);
    }

Could anyone help with an OpenSSL version, please?

A: When decrypting, the @ prefix must first be removed, then hex decoding must be done, and finally decryption can be performed. openssl_decrypt() implicitly removes the padding, so that no explicit removal is required. This is implemented in decryptAes_new() below:
<?php
function encryptAes_new ($string, $key) {
    $key = str_pad($key,16,"\0"); # if supplied key is, or may be, less than 16 bytes
    $crypt = openssl_encrypt($string, 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $key);
    // Perform hex encoding and return.
    return "@" . strtoupper(bin2hex($crypt));
}

function decryptAes_new($string, $key) {
    $key = str_pad($key,16,"\0");
    $binary = hex2bin(substr($string, 1));
    return openssl_decrypt($binary, 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $key);
}

$plaintext = 'The quick brown fox jumps over the lazy dog';
$key = '0123456789012345';
$ciphertext = encryptAes_new($plaintext, $key);
$decrypted = decryptAes_new($ciphertext, $key);
print('Ciphertext: ' . $ciphertext . PHP_EOL);
print('Plaintext:  ' . $decrypted . ' - Size: ' . strlen($decrypted) . PHP_EOL);
?>

which produces the output:
Ciphertext: @3089E6BC224BD95B85CF56F4B967118AAA4705430F25B6B4D953188AD15DD78F3867577E7D58E18C9CB340647C8B4FD8
Plaintext:  The quick brown fox jumps over the lazy dog - Size: 43

Checking the length of the plaintext after decryption, 43 bytes, shows that the padding has been automatically removed.

A: Thank you, Mike, for asking the question and user16205441 for your answer.
I found the answer was applicable to my problem.
I have been trying for weeks to do the following:
the string must be encrypted using AES (block size 128-bit) in CBC mode with PKCS#5 padding. Use the provided password as both the key and initialisation vector and encode the result in hex (making sure the letters are in upper case).
When I operated the following code:
<?php

function encryptAes_new ($string, $key) {
    $key = str_pad($key,16,"\0"); # if supplied key is, or may be, less than 16 bytes
    $crypt = openssl_encrypt($string, 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $key);
    // Perform hex encoding and return.
    return "@" . strtoupper(bin2hex($crypt));
}

function decryptAes_new($string, $key) {
    $key = str_pad($key,16,"\0");
    $binary = hex2bin(substr($string, 1));
    return openssl_decrypt($binary, 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $key);
}

$plaintext = 'theLongStringIwasTryingToSend';

$key = 'abcdefghijklmnop';

$ciphertext = encryptAes_new($plaintext, $key);

$decrypted = decryptAes_new($ciphertext, $key);

print('Ciphertext: ' . $ciphertext . PHP_EOL);

print('Plaintext:  ' . $decrypted . ' - Size: ' . strlen($decrypted) . PHP_EOL);

?>

It produced the encrypted version the Opayo team were saying my string should have produced.
I am a little surprised as the Opayo team mention the initialisation vector ($iv) which user16205441's answer doesn't mention explicitly. But if it works, that's all that matters to me.
I shall now try the form integration process again and see what the team says!
All the best
NeverSayDai


text:
Q: jQuery UI autocomplete for multiple key/value selections in ASP.NET How do I handle selection of multiple items with autocomplete? The objects I return from my JSON web service contain an ID and a Label - the ID is the ID of the entity in the database, and the Label is some text to display for the user.
At the moment, when I select an item in the autocomplete dropdown, the value of the item's ID is stored in a hidden field, and the label is displayed. When I remove the label, I clear the ID of the hidden field - this is done by adding an anchor element to the DOM that handles this.
Now, I want to have multiple selections. I want to be able to enter some text, get an autocomplete dropdown, select an item and some other options, then be able to click an 'Add New' button or the likes to be able to select another instance.
For example, I'd type in a person's name and get an autocomplete selection. I'd select a person, and then enter their age, and click 'Add'. The person's id, name, and age will be stored somewhere so that I can retrieve it on the server side when I post back.
I'm not quite sure how to do it? I'm thinking of a hidden field - I assume that many hidden fields of the same name/id turn up on the server side as an array, which I can then use. But I haven't tried this yet in ASP.NET.
How have you gone about this problem?

A: Well, no suggestions. I did it eventually by, in the autocomplete selection, creating a nicely styled span. It's text contains the label, it contains an anchor element that I bind a click event to that removes the element if necessary, and I use the jQuery data API to store the ID value on the span. This span gets added to a container div, before the textbox that I'm using to autocomplete. I also bind a keyup event to the textbox to check for backspace - when it's pressed and the textfield is empty, then I remove the last autocomplete item. It's a little more complex though, since by the time the keyup event is pressed, the character that was being removed from the textbox has already been removed, so I store the actual value in the keydown event too using the jQuery API and check this in the keyup event.
There is a hidden field on the form, that I keep populated with a comma-separated list of ID values extracted from the span's data. This can be kept in sync when adding/removing items, or only when I post back - it's simplest to just clear it and repopulate it, and is quite efficient as far as I can tell.
When loading the page, the spans and hidden field must be generated.
Hope this helps anyone else looking for a solution.


text:
Q: Iterate over a column and find the sum I need to sum the results of three different parameters (1-3) into a new column called "New". The results should only be added if the SiteID is equal to 'One','Two','Three','Four','Five' & the date of sample collection is the same for each parameter. The time of collection does not matter as long as the date is the same.
I am a novice in R and tried If, While, and For loops but did not get very far...
Thank you
Below is what the results should look like:
Results

A: One option would be to do a group by 'SiteID', 'Date' column and then mutate to create a new column which is the sum of 'Result'
library(dplyr)
df2 <- df1 %>%
         group_by(SiteID, Date) %>%
         mutate(New = sum(Result))


text:
Q: Show $T(r, \theta) = (r \cos \theta , r \sin \theta)$ is injective So I need to show $r = r'$ and $\theta = \theta '$ using:
$$r \cos \theta = r' \cos \theta ' $$
and
$$r \sin \theta = r' \sin \theta '$$
I don't know how to solve this system of equations because we have 4 unknown variables with 2 equations and we need to show $r = r'$ and $\theta = \theta '$.

A: I'm assuming that domain of $T$ is $(0,\infty)\times[0,2\pi)$.
Square both equations and add them to obtain:
$$r^2=r'^2$$
so $r=r'$.
Now the angles $\theta$ and $\theta'$ have the same $\sin$ and $\cos$. Hence, they are the same angle.


text:
Q: Will php stop supporting apache in the windows binaries? I noticed in the latest 5.3.13 release that there is no binary for windows running apache. Its all IIS. They only have binary for 5.2 running apache.
http://windows.php.net/download/
Will future Windows binaries be all IIS only?

A: From what I can see there, you just can't use it with the binaries from apache.org. VC9 supports the binaries from Apachelounge.


text:
Q: Generate unique values with javascript I have two variables and I would like to add them randomly in a function, I do with math.random but the problem is that the value is sometimes the same, while I would like it to play between them two values, if it gives the first then the next time it will be the second and vice versa ... I hope I explained it well. Thank you.

     const btn = document.getElementById('button')
     function random(){
            var variable = 2
            var arr = [];
            var tabprenom=new Array('prenom 1','prenom 2')
            while(arr.length < 2){
              var r = Math.floor(Math.random() * variable-1) + 1;
              if(arr.indexOf(r) === -1) arr.push(r);
            }

            console.log(tabprenom[r]);
        }
        btn.addEventListener('click',random)
<button id="button"> Generer aleatoire unique </button>

A: If you want to play with only 2 values, you can do the following instead of  randomizing.

const btn = document.getElementById('button')
let option = 0;

function random() {
  var tabprenom = new Array('prenom 1', 'prenom 2');

  console.log(tabprenom[option]);
  option = option ? 0 : 1;
}

btn.addEventListener('click', random);
<button id="button"> Generer aleatoire unique </button>


text:
Q: 18.04: How to install hindi phonetic dictionary? I recently installed Ubuntu 18.04 and am planning to move all my activities from Windows 10 to Ubuntu 18.04.
In Windows, I can type using English-Hindi transliteration keyboard with transliteration dictionary. That keyboard helped me to type in Hindi using English keyboard.
I am looking for something similar but have not been able to find one.I have installed Hindi (Wx) keyboard and Hindi (Phonetic) keyboard which works fine with some difficulty because there is no dictionary to assist.
Is there a English-Hindi phonetic transliteration dictionary for Ubuntu?


text:
Q: Нужно ли добавлять в requirements.txt зависимости зависимостей (рекурсивно)? У меня есть небольшой репозиторий, в котором хранятся принятые в команде стандарты кодирования Python в форме конфигурации pylint. Также там есть инструкция и requirements.txt для установки через pip:
pip install -r requirements.txt

Очевидно, что в requirements.txt должен быть pylint. Но официальная документация по pylint явно указывает, что для работы pylint необходим ещё и пакет astroid.
Я убедился, что команда pip install pylint успешно устанавливает astroid и остальные зависимости:
До:
(venv)➜  pip list
pip (7.1.2)
setuptools (18.2)
wheel (0.24.0)

После:
(venv)➜  pip list
astroid (1.4.6)
colorama (0.3.7)
lazy-object-proxy (1.2.2)
pip (7.1.2)
pylint (1.5.6)
setuptools (18.2)
six (1.10.0)
wheel (0.24.0)
wrapt (1.10.8)

Вроде бы всё и так работает. Но ведь зависимость по какой-то причине явно указана в документации, и даже дана отдельная инструкция по установке.
Вопрос: должен ли я добавить astroid и прочие зависимости в requirements.txt? Есть ли стандарт, который даёт однозначный ответ на этот вопрос?

A: *

*Не удалось найти PEP, регламентирующего это.

*Зато есть документация к pip. Цитата:

Requirements files are used to hold the result from pip freeze for the
  purpose of achieving repeatable installations. In this case, your
  requirement file contains a pinned version of everything that was
  installed when pip freeze was run.

Файл зависимостей используется для сохранения результатов команды pip freeze, чтобы достигнуть одинаковой повторяемой установки. В этом случае в файл зависимостей помещается всё, что было получено от pip freeze с явно указанными версиями.

Using pip freeze to generate the requirements file will ensure that
  not only the top-level dependencies are included but their
  sub-dependencies as well, and so on.

Если вы используете pip freeze для генерации файла зависимостей, то туда помещаются не только зависимости верхнего уровня, но также и зависимости зависимостей и т. д.
То есть файл зависимостей призван собрать зависимости для всего окружения, для всего-всего. Напротив, если использовать install_requires в setup.py (то есть только для одного приложения), то в нем не рекомендуется указывать под-зависимости. Источник - http://python-packaging-user-guide.readthedocs.io/en/latest/requirements/#requirements-files

A: Нет, не нужно.
Если разработчики других пакетов указали у себя зависимости(а обычно это так), то pip сам установит их.


text:
Q: Is there a way to make clickable/interactable particles in Unity? I want to create a bubble-pop mechanic where bubbles will fall from the top of the screen, and the player will be able to 'pop' them by clicking/tapping on them.
Basically this: https://www.youtube.com/watch?v=OH4dcpSk7n0
I started by creating a particle system. But is there a way to attach a script to the particle? Or should I go about it in a completely different way?

A: you should not use particles to achieve this, instead you should make a GameObject with rigidBody and collider attached to it, and spawn those GameObjects in the position you want.


text:
Q: Any simple way to get a list of data with certain elements and not counting the 0? I have a question in a list of list, which contains 3 possible routes, for example:
routes=[[(0, 1), (1, 2), (2, 0)],[(0, 1), (1, 0)],[(0, 2), (2, 0)]]
position 0 concerns the depot. Now I would like to obtain a list of list that tells me which positions will be visited, without repeating and without counting the 0, for each route, that is, to obtain something similar:
route_positions=[[1,2],[1],[2]]
In other words, in routes.index[0], I will have the position [1,2] to visit.
I've been trying to solve the problem as follows, but still without success. Something like:
route_positions=[]
for route in routes:
route_positions+=[x for x in route if x!=0]

Thanks in advance for your help.

A: I dont know if i understood your question properly but this could work:
route_positions=[]
for route in routes:
    route_position_inside=set()
    for route_node in route:
        route_position_inside.update([for content in route_node if content != 0])
    route_positions.append(route_position_inside)

A: Since you have an answer and mentioned comprehensions, I see no harm in suggesting this as an alternative way to approach the problem:
routes=[
    [(0, 1), (1, 2), (2, 0)],
    [(0, 1), (1, 0)],
    [(0, 2), (2, 0)]
]

route_stops = [
    [
        segment[1]  # the second element of the tuple
        for segment
        in route
        if segment[1] != 0
    ]
    for route
    in routes
]

print(route_stops)

This should give you:
[[1, 2], [1], [2]]


text:
Q: Calculate days remaining with workflow I'm making a project in sharepoint where I have a list of user id's and a last logon date.  The scope of the project is to have sharepoint email a warning when there is 30 days remaining before their logon id is disabled for non use.  (90 days)
So i have my list established with user id and last login date and days remaining fields.  I have my workflow setup to look at days remaining and if less than 31 days the email triggers to the user.
My problem is can i make the days remaining field calculate the days remaining before the id is disabled?
For example, today Bob is at 31 days remaining.  But tomorrow he'll be at 30 days remaining which is when I want the notification to go out.  In other words the days remaining needs to calculate based on today and not a static value.  Can this be done?  I'd like to try it without using code. I'm not a coder. yet.

A: there are two possibilities for actual date/time.

*

*add a calculated column with =DAY(NOW()) or =TEXT(YEAR(NOW());"####") or find expression what suit your self and make it hidden for users in content type.

*in workflow set wf variable type date to current date (by clicking on ellipsis)
Set Variable: Date to Today


text:
Q: Character limit in string variables when I export my data from a .dta file to .sps, my string variables get cut off and the data contains signs, which look like a UTF-8 problem. I think, the problem might be that some string variables have a width over 261- at least they are cut at that point.
Does SPSS have a character limit, and if so, how can I increase the number?

A: "The values of string variables can contain numbers, letters, and special characters and can be up to 32,767 bytes. "
You seem to be trying to export STATA data (.sta) to SPSS Statistics (.sav).  What mechanism are you using in STATA to do this?  Does STATA have a limitation on the width of string fields?
As horace_vr has already pointed out, an SPSS Statistics command file has the *.sps extension.  Are you truly trying to have STATA write SPSS Statistics Command Syntax for you and save as *.sps?  Perhaps you meant you were exporting from *.dta (in STATA) to *.sav (in SPSS Statistics).
Note also that if you have created an SPSS Statistics data file (*.sav) in Codepage mode, but then open it while SPSS Statistics is in Unicode mode, your string widths will triple in size.  This is an artifact of the conversion of the various codepages to unicode.
"When code page data files are read in Unicode mode, the defined width of all string variables is tripled. You can use ALTER TYPE to automatically adjust the width of all string variables."
I hope this helps
-ddwyer


text:
Q: Implement a method for ordered_vowel_words I've been going over some of the many coding interview questions. I was wondering about implementing an ordered_vowel words method.  I'm working on algorithm question to implement this method for purposes of the understanding algorithm. I have the below:
This method takes a string of lowercase words and returns a string with just the words containing all their vowels (excluding "y") in alphabetical order. Vowels may  be repeated ("afoot" is an ordered vowel word)
def ordered_vowel_words(str)
  words = str.split(" ")

  ordered_vowel_words = words.select do |word|
    ordered_vowel_word?(word)
  end

  ordered_vowel_words.join(" ")
end

def ordered_vowel_word?(word)
  vowels = ["a", "e", "i", "o", "u"]

  letters_arr = word.split("")
  vowels_arr = letters_arr.select { |l| vowels.include?(l) }

  (0...(vowels_arr.length - 1)).all? do |i|
    vowels_arr[i] <= vowels_arr[i + 1]
  end
end

I added the following test cases:
puts("\nTests for #ordered_vowel_words")
puts("===============================================")
    puts "ordered_vowel_words(\"amends\") == \"amends\": "  + (ordered_vowel_words("amends") == "amends").to_s
    puts "ordered_vowel_words(\"complicated\") == \"\": "  + (ordered_vowel_words("complicated") == "").to_s
    puts "ordered_vowel_words(\"afoot\") == \"afoot\": "  + (ordered_vowel_words("afoot") == "afoot").to_s
    puts "ordered_vowel_words(\"ham\") == \"ham\": "  + (ordered_vowel_words("ham") == "ham").to_s
    puts "ordered_vowel_words(\"crypt\") == \"crypt\": "  + (ordered_vowel_words("crypt") == "crypt").to_s
    puts "ordered_vowel_words(\"o\") == \"o\": "  + (ordered_vowel_words("o") == "o").to_s
    puts "ordered_vowel_words(\"tamely\") == \"tamely\": "  + (ordered_vowel_words("tamely") == "tamely").to_s

What is the runtime analysis for this one?
Why is it true that we can get O(m)O(m) runtime for mm function calls.
I appreciate your explanation for this. thank you.

A: This method is short and should be reasonably readable :
def ordered_vowel_words(str)
  str.split(" ").select{|w| ordered_vowel_word?(w) }.join(" ")
end

def ordered_vowel_word?(word)
  vowels = word.scan(/[aeiou]/)
  vowels == vowels.sort
end

It might not be very efficient to sort an array just to check it's already sorted, so here's an alternative :
def ordered_vowel_word?(word)
  word.scan(/[aeiou]/).each_cons(2).all?{ |vowel1, vowel2| vowel1 <= vowel2 }
end

With this method, the whole complexity should be O(n), n being the number of characters in str.
Complexity cannot be any better, because the whole string needs to be parsed at least once to find the vowels. There might be faster implementations, though.

A: It seems you're just using the solution provided by App Academy for this question. When preparing for these interview questions, it's important that you try to solve them all yourself - they won't ask you these exact questions, but variations of the same logic (breaking up data structures, applying some methods to them, and comparing results or building new responses based on the input.)
So, if you're serious about applying, don't look at the solutions. I also advise trying to find a mentor.
Now, on to your question.
require 'benchmark'

def ordered_vowel_words(str)
  words = str.split(" ")

  ordered_vowel_words = words.select do |word|
    ordered_vowel_word?(word)
  end

  ordered_vowel_words.join(" ")
end

def ordered_vowel_word?(word)
  vowels = ["a", "e", "i", "o", "u"]

  letters_arr = word.split("")
  vowels_arr = letters_arr.select { |l| vowels.include?(l) }

  (0...(vowels_arr.length - 1)).all? do |i|
    vowels_arr[i] <= vowels_arr[i + 1]
  end
end

puts Benchmark.measure {ordered_vowel_words("amends")}
puts Benchmark.measure {ordered_vowel_words("complicated")}
puts Benchmark.measure {ordered_vowel_words("afoot")}
puts Benchmark.measure {ordered_vowel_words("ham")}
puts Benchmark.measure {ordered_vowel_words("crypt")}
puts Benchmark.measure {ordered_vowel_words("o")}
puts Benchmark.measure {ordered_vowel_words("tamely")}

Refer to here for some easy benchmarking tools: https://ruby-doc.org/stdlib-1.9.3/libdoc/benchmark/rdoc/Benchmark.html


text:
Q: How to install Rust using power shell? I want to install rust automatically via command line on Windows. It doesn't matter if it's power shell or not but I think power shell is the easiest without having to install other stuff manually.
I found https://www.powershellgallery.com/packages/AppVeyorBYOC/1.0.170/Content/scripts%5CWindows%5Cinstall_rust.ps1 but at
 Add-SessionPath "$env:USERPROFILE\.cargo\bin"

it says that Add-SessionPath is a cmdlet that does not exist.

A: I had the same error. I changed that line to this and the script worked with Powershell 7.
$env:Path = "$env:USERPROFILE\.cargo\bin"

A: # Make new environment variables available in the current PowerShell session:
function reload {
   foreach($level in "Machine","User") {
      [Environment]::GetEnvironmentVariables($level).GetEnumerator() | % {
         # For Path variables, append the new values, if they're not already in there
         if($_.Name -match 'Path$') {
            $_.Value = ($((Get-Content "Env:$($_.Name)") + ";$($_.Value)") -split ';' | Select -unique) -join ';'
         }
         $_
      } | Set-Content -Path { "Env:$($_.Name)" }
   }
}
Write-Host "Installing Rust..." -ForegroundColor Cyan
$exePath = "$env:TEMP\rustup-init.exe"

Write-Host "Downloading..."
(New-Object Net.WebClient).DownloadFile('https://static.rust-lang.org/rustup/dist/x86_64-pc-windows-msvc/rustup-init.exe', $exePath)

Write-Host "Installing..."
cmd /c start /wait $exePath -y
Remove-Item $exePath

$addPath = "$env:USERPROFILE\.cargo\bin"
[Environment]::SetEnvironmentVariable
     ($addPath, $env:Path, [System.EnvironmentVariableTarget]::Machine)

reload

cargo --version
rustup --version
rustc --version


text:
Q: Defining a shortcut to open Chrome from the command line on MacOS I'd like to open .html and .xml files from the command line using Google Chrome on a Mac. Usually I just used the open command, but for .xml files I've noticed that the default application is XCode, so I'd like to specify the application with the -a argument.
The following command works:
Kurts-MacBook-Pro:MacOS kurtpeek$ open -a "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" ~/Documents/Seattle/comparables.xml

Here I've enclosed the path to Google Chrome - which has spaces in it - in quotes. In order to make this easier to type in the future, I'd like to define an environment variable $chrome in by .bash_profile containing this path, which I did as follows:
export chrome="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"

The echo command does print this out:
Kurts-MacBook-Pro:~ kurtpeek$ echo $chrome
/Applications/Google Chrome.app/Contents/MacOS/Google Chrome

However, if I try to rerun the open -a with this environment variable to specify the application, I get the following error:
Kurts-MacBook-Pro:~ kurtpeek$ open -a $chrome Documents/Seattle/comparables.xml
The files /Users/kurtpeek/Chrome.app/Contents/MacOS/Google and /Users/kurtpeek/Chrome do not exist.

Apparently, in this case, the Bash shell does not 'recognize' the quotation marks I put in the definition of chrome. How can I make this work?

A: Following Set environment variable with having space linux, this can be done by enclosing $chrome in quotes:
Kurts-MacBook-Pro:~ kurtpeek$ open -a "$chrome" Documents/Seattle/comparables.xml
Kurts-MacBook-Pro:~ kurtpeek$

and the XML document gets opened in Chrome:

Update
It would appear (from https://superuser.com/questions/157484/start-google-chrome-on-mac-with-command-line-switches/157486#157486) that the open command looks in the Applications directory by default. So it suffices to just pass "Google Chrome" as an -a argument:
Kurts-MacBook-Pro:~ kurtpeek$ open -a "Google Chrome" Documents/Seattle/comparables.xml
Kurts-MacBook-Pro:~ kurtpeek$


text:
Q: Database connection issue in MySQL with PHP Issue Is with the database connection for an open source Project(PHP).
Everything works fine apart from the database connection required for login. Following is the error that can be seen after login.

Warning: require_once(../mysqli_connect.php): failed to open stream:
No such file or directory in
/Applications/XAMPP/xamppfiles/htdocs/airline-ticket-reservation-system-master/login_handler.php
on line 44
Fatal error: require_once(): Failed opening required
'../mysqli_connect.php'
(include_path='.:/Applications/XAMPP/xamppfiles/lib/php') in
/Applications/XAMPP/xamppfiles/htdocs/airline-ticket-reservation-system-master/login_handler.php
on line 44

mysqli_connect.php
<?php
DEFINE('DB_USER','Harry');
DEFINE('DB_PASSWORD','passpasshello');
DEFINE('DB_HOST','localhost');
DEFINE('DB_NAME','airline_reservation');

$dbc=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME)
OR dies('Could not connect to MySQL:' .
    mysqli_connect_error());
?>

A: try to include the mysqli_connect file where the error occur
require_once(../MySql DatabaseConnection file/mysqli_connect.php)
reference


text:
Q: Creating a python dictionary with preset Keys that return Lists as Values So it turns out my code environment was malfunctioning. The dictionary I was trying to create does actually work after I cleaned things up.
I'm using python to build a responsive menu that will change depending on another menu's selection. I have a list of items from the first menu that I would like to use as keys in a dictionary, with each key (menu item) returning a specialized list of possible options based on the selection, so that when a user chooses an item from the first menu, the second menu's options will change.
The first approach I thought of was a dictionary that uses the first menu's list items as the keys which return the options as a list from the specialized dictionary. Unfortunately, constructing this dictionary with preset keys (the list items) and preset values (a list of values) has proven difficult. I have seen several answers on StackOverflow that deal with creating a dictionary of automated numerical keys (so that the final result is (1:['a','b','c']) etc.; but that solution doesn't work, as I'll need the keys themselves to be pre-determined strings. e.g. ('name one': ['a','b','c'], 'name two':['b','c','d'], etc.).
Is there a way to get this kind of thing done? Or is there a more efficient approach that I'm not considering?
UPDATE: To clarify, I don't need a literal 'name one', 'name two' with incrementally increasing values as the keys. I have a list of 148 names that I need to use as keys for their individual return values. So the result needs to be a dictionary like this:
'John Doe':['a','b','c'],
'Jane Doe':['b','c','d'],
'Mickey Mouse':['a','c','e'], etc.

I'm not sure how to go about constructing this, since Python doesn't want to take a list of strings as a dictionary value in a straightforward manner.

A: import inflect
i = inflect.engine()
val=[['a','b','c'],['b','c','d']]
{"name "+i.number_to_words(k):v for (k,v) in list(enumerate(val,1))}

Output:
{'name one': ['a', 'b', 'c'], 'name two': ['b', 'c', 'd']}


text:
Q: Installshield: file duplicate because of merge module I have an InstallShield (2018, also happens in IS 11) setup with a lot of 3th party libraries. Among other things a merge module. This merge module have a file (call F).
Now, there is an other library as a directory with a bunch of different files, sadly also a file with the name "F".
I can't add this file:

A work around is creating a new merge module just containing this file and adding it to the feature. But the drawback is: When updating the libary directory, the merge module has also to be updated. But do I remember at this moment to this? What if other persons are doing this? So I want to avoid this work around. Is there a better way?

A: what worked for me is i removed merge module from the project and re-added them after adding files to the project.


text:
Q: How do I make one button rotate through multiple inputs? How do I use one push of a button to go from 1 input to 9 outputs?
Where the 1st push turns line A on, then the second push will turn line A off and line B will turn on. Push the button a third time and line B turns off and line C turns on. And so on until I get to the 9th output.
I am doing this for a level system. I made a wave spawner and the level is displayed. I need to connect the level display to the start button.


text:
Q: Why can't the pseudosphere be completed in $R^3$? Without appealing to Hilbert's theorem on the non-embeddability of complete hyperbolic surfaces in $R^3$, is there a way to "see" that one can't extend the pseudosphere / surface of revolution of a tractrix to a complete surface in $R^3$?
I mean, it is clear from the construction of the tractrix as the involute of a caternary that one cannot just keep going using the original construction, but I don't really see why it is impossible in principle. In what sense does one run out of room? From the picture of a pseudo-sphere it seems like one runs out of angle, if that makes sense.


text:
Q: Cannot play after pausing tvOS (TVML/TVJS) I am developing a tvml/tvjs application and I have added the following code to allow audio to play in the background (applicationDidBecomeActive):
 let audioSession = AVAudioSession.sharedInstance()

 do {
     try audioSession.setCategory(AVAudioSessionCategoryPlayback)
     try audioSession.setActive(true)
 } catch {
     print("no audio to assign")
 }

I also set the first item in Required Background Modes in info.plist to App plays audio or streams audio/video using AirPlay.
My problem now is that although I can play audio in the background and pause the audio from anywhere in tvOS, I cannot play the audio after pausing. I am looking for the functionality like the Podcast app where I can freely play and pause the current streaming audio.
I cannot seem to find anything in the documentation for TVML/TVJS that points me in the right direction. Thanks!


text:
Q: "... business card with the writing facing the recipient..." What does the highlighted part mean in the following passage please?

In Japan, there are strict norms involving the exchange of business
  cards. One person presents his or her business card with the writing
  facing the recipient, who looks at it for a moment and asks a
  question about some of the information on the card. The question may
  be irrelevant, but it tells the giver that the recipient has read the
  card and acknowledges the person and his or her company. A Japanese
  executive who receives a business card and does not take the time to
  look at it and ask a question would be considered deviant.

A: If you hand over the card, there are multiple ways it might be turned - in theory, you could even turn the back side up.
"With the writing facing the recipient"
means oriented in such a way that the recipient can read the card directly, without turning it, or, from the giver's point of view it would be upside down. (Assuming two people facing each other when the card is presented as it's customary in Japan.)
In Japan, the exchange of business cards is a bit like a ballet choreography with strict rules. I like this video, for example. Remember: While in most western cultures a business card is basically a scrap of paper with contact information, a business card in Japan symbolizes the  owner/giver, therefore handling the cards with respect and attention is required - lack of this would be a direct insult to the giver or (in case of your card being less than pristine or handed over carelessly) reflect badly on you.


text:
Q: Is the waveform the "raw" audio data? (Pytorch) I am using PyTorch in an audio deep learning project. I am using the torchaudio.load method to load the waveform and sample rate. Now, my question is, is the waveform considered the "raw" audio data? Is it the PCM data? If not, then how can I get PCM data from .ogg format?

A:  Solution
Yes, it's raw data.
For the explanation read below. If you know about sampling theory and how sound is generated, skip to the last paragraph.
 PCM
PCM is a fancy way to explain the process by which a continuous time wave is represented inside a computer. You can learn more in any introductory course/book of digital signal processing such chapter 3 of The Scientist and Engineer's Guide to Digital Signal Processing.
Briefly in a computer you can only represent finite quantities, so you need to take discrete samples in time (sampling) at a certain amplitudes (quantization).
When loading any audio file this process has been already done for you.
 RAW DATA
If you connect a speaker and you play a wave, the membrane will oscillate as the amplitude of such wave at every instant. This is the "raw" audio, a signal that contains the amplitude at each "time" instant. If you can "see" the wave changing with no discontinuity from left to right when plotting your data, it is very likely a raw vector.
What is non-raw data then? Every compression algorithm modifies the input vector with any sort of mathematical function, so that it occupies less space, but also is not understandable anymore by just looking at it. This is because the samples don't represent anymore an amplitude over time. If you'd play the compressed wave through a speaker you wouldn't get any sound, only noise.
 Pytorch
In the example you provided from the pytorch documentation we can clearly see that the plot represents raw data, sampled at 16kHz.
To exclude the possibility that

*

*torchaudio.load could still give a sort of compressed object

*the raw data is generated and plotted by plot_waveform
We can see that the waveform variable is long 54400 samples and sampled at 16kHz. This means it represents 54400*(1/16000) seconds, which are exactly 3.4s.
The plot shows 3.4seconds, thus telling us that what is represented in the variable waveform returned by the load function is the raw data.


text:
Q: Is "lessor" used for more than property? Does the term "lessor" refer to only parties that lease property?
All of the definitions I have been researching (http://dictionary.reference.com/browse/lessor, https://www.google.co.uk/search?q=define%3A%20lessor, https://en.wikipedia.org/wiki/Lease) have only regarded property leasing.
Is it accurate (in casual use, rather than legal use) to use the term "lessor" to refer to someone leasing, say, building equipment? e.g.

Lorem Supplies Ltd were the lessors of the cement mixer we used when we made that path.

A: This is a sample of an Equipment Leasing Contract which quite clearly refers, as I suspected, to a Lessor and a Lessee

A: M-W Unabridged (subscription required) provides a second definition for lessor:

2. a bailor under a bailment agreement providing a rental for personal property

If I understand your question, no, leases (and therefore lessors) aren't restricted to real estate. It's pretty common to lease automobiles, for example.


text:
Q: What's the name of the sound that a hungry stomach makes? When the stomach makes a sound like croaking of a frog or similar to it (mine just did, it's trying to speak to me), that alert when you are hungry, is there a name for it?
I mean the name for this very sound?

A: Yes, there is a term for that in English. It's called a growl:

Why is my stomach growling, but I'm not hungry?
I can hear my stomach growling. I'm gonna go grab a bite.

There are actually a number of terms in English that are used to describe abdominal sounds (sometimes called bowel sounds) among which are words like gurgle, grumble, rumble et cetera, but growl is by far the most common. Here's another example straight from Oxford English Living Dictionaries (OELD):

My stomach gurgled.

A: In medical speak, they use a delightful little word called borborygmi, which is the rumbling or gurgling noise made by the movement of fluid and gas in the intestines. That said, it would be unlikely to be used in casual conversation.
Personally, I would say:

My stomach is rumbling

Or even

My stomach is talking

A: In addition to a stomach growl, it can be also referred as a stomach moan. Or it could be a stomach drone.
(Droning is making a deep, low-pitched humming noise, discontinuously.)

A: In my locale of southern England, the term is "my stomach is rumbling".
Other locales use different terms.


text:
Q: How can I work around int overflow in c In C, is it possible to do the below operation without causing an integer overflow?
My answer needs to be an integer which I use later on in the program. The code prints -337.
The correct answer should be 2014.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main() {
   int i;
   i = (10000 * 735625 + 14780)/3652425;
   printf("%d",i);
   return 0;
}

A: Based on usual arithmetic conversions, it will overflow as 10000 * 735625 + 14780 (out of int's range) is trying to save into int.

Integral promotions are performed on the operands as follows:

*

*If either operand is of type unsigned long, the other operand is converted to type unsigned long.

*If preceding condition not met, and if either operand is of type long and the other of type unsigned int, both operands are converted to type unsigned long.

*If the preceding two conditions are not met, and if either operand is of type long, the other operand is converted to type long.

*If the preceding three conditions are not met, and if either operand is of type unsigned int, the other operand is converted to type unsigned int.

*If none of the preceding conditions are met, both operands are converted to type int.

To work out, you need to use long long (with larger range) stead.
A simple way, as @JoachimIsaksson suggested, is to put LL after 10000 to calculate with long long's precision:
i = ( 10000LL * 735625 + 14780)/3652425;

See it live: http://ideone.com/pA2Pvm

A: i = (int)((10000.0 * 735625.0 + 14780.0)/3652425.0);

printf("%d",i);

valter


text:
Q: why does unicode(u'') passed an errors parameter raise TypeError Using python 2.7.3, the following does not raise TypeError.
>>> unicode(u'')
    u''

But passing errors parameter raises TypeError: decoding Unicode is not supported
>>> unicode(u'',errors='replace')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: decoding Unicode is not supported

>>> unicode(u'',errors='ignore')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: decoding Unicode is not supported

>>> unicode(u'',errors='strict')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: decoding Unicode is not supported

Any guesses why this behaves so differently?   IMO, this is a surprising quirk to the unicode function.

Browsing python source code, (I'm just taking a guess that I'm following the correct code path)

*

*in Python/unicodeobect.c in function PyUnicode_FromEncodedObject we find the error strings "decoding Unicode is not supported".  The error string is set if PyUnicode_Check(obj) return non-0.

*in Include/object.h , PyUnicode_Check evaluates to the expression (((Py_TYPE(obj))->tp_flags & (Py_TPFLAGS_UNICODE_SUBCLASS)) != 0) ,
However, I could not find where the Python code takes a different code path due to passing the errors parameter.

A: unicode in Python (docs) is a function that converts a string to the unicode representation of the string in Python. However, the behaviour is different if you pass in the encoding or error parameters.

If encoding and/or errors are given, unicode() will decode the object
  which can either be an 8-bit string or a character buffer using the
  codec for encoding. The encoding parameter is a string giving the name
  of an encoding; if the encoding is not known, LookupError is raised.
  Error handling is done according to errors; this specifies the
  treatment of characters which are invalid in the input encoding. If
  errors is 'strict' (the default), a ValueError is raised on errors,
  while a value of 'ignore' causes errors to be silently ignored, and a
  value of 'replace' causes the official Unicode replacement character,
  U+FFFD, to be used to replace input characters which cannot be
  decoded. See also the codecs module.
If no optional parameters are given, unicode() will mimic the
  behaviour of str() except that it returns Unicode strings instead of
  8-bit strings. More precisely, if object is a Unicode string or
  subclass it will return that Unicode string without any additional
  decoding applied.

The reason that you cannot convert u'' to unicode is because it is already a unicode representation. When Python tries to decode it with the ascii codec (the default codec, since you didn't specify one), it realises that the string is already in Unicode, and throws an error ("Python: Oi why are you trying to convert unicode strings into unicode?")
When you do not specify the error param, as you can see in the docs, Python is ok with converting unicode strings to unicode. If it is already unicode, it will return the unicode string without any additional decoding.
The standard link for people to help them understand what unicode is.
If you actually want to be able to perform this operation (for example, if you wanted to write code that accepts both regular strings and unicode strings), you would encode your string before you convert it back into Unicode.
Example:
>>> unicode(u''.encode('ascii', errors='replace'))

If you wanted to use a different encoding (ascii is the default):
>>> unicode(u''.encode('utf-8', errors='replace'), 'utf-8')

A: I believe that the unicode() function is supposed to take data of type string and not type unicode:
The unicode() constructor has the signature unicode(string[, encoding, errors]). All of its arguments should be 8-bit strings. The first argument is converted to Unicode using the specified encoding; if you leave off the encoding argument, the ASCII encoding is used for the conversion, so characters greater than 127 will be treated as errors:
>>> unicode('abcdef')
u'abcdef'
>>> s = unicode('abcdef')
>>> type(s)
<type 'unicode'>
>>> unicode('abcdef' + chr(255))
Traceback (most recent call last):
...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 6:
ordinal not in range(128)

u'' is encoding the empty string (which I believe is not a character greater than 127). It should be fine without encoding arguments, but I believe unicode raises an error because it's not supposed to accept Unicode regularly.
I'm throwing my best guess at this one at the moment, so any corrections would be appreciated.


text:
Q: grab two values from command output in a for loop I'm trying to loop through all of the repositories on our satellite servers and list the number of rpms in each.  I need the repository ID and NAME which I can get from
hammer --csv repository list | grep -v 'Id,Name' | cut -d, -f1,2`

Given ID and NAME, I can get the number of packages and print out:
SUM=$(hammer repository info --id ${ID} | grep Packages | awk '{ print $2 }');
echo "In repository, ${NAME}, there are ${SUM} packages."

I just can't figure out how to put that in a loop.  Any suggestions?

A: You could try something like:
hammer --csv repository list | grep -v 'Id,Name' | while IFS=, read -r ID NAME; do
  SUM=$(hammer repository info --id ${ID} | grep Packages | awk '{ print $2 }')
  echo "In repository, ${NAME}, there are ${SUM} packages."
done


text:
Q: Thymeleaf select sets null I'm trying to set the ingredient's unit of measure, but it sets their ID's to null. The object I send is a wrapper that contains IngredientsCommand objects.
<select th:field="*{ingredientsWrapper[__${iter.index}__].unitOfMeasure}" name="unitOfMeasure.id">
   <option value="NULL"></option>
   <option th:each="unit : ${unitOfMeasureSet}"
        th:value="${unit.id}"
        th:text="${unit.unitName}">Test
   </option>
</select>

>
@Getter @Setter
@NoArgsConstructor
public class IngredientsCommand {

private Long Id;
private String ingredientName;
private Long recipeId;
private BigDecimal amount;
private String countryOfOrigin;
private BigDecimal ingredientCost;
private RecipeCommand recipe;
private UnitOfMeasureCommand unitOfMeasure;
}

>
@Getter @Setter
@NoArgsConstructor
public class UnitOfMeasureCommand {

private Long id;
private String unitName;

}

A: I hadn't autowired the unit of measure converter when it converts from command to ingredient. I've also changed from th:field="*{ingredientsWrapper[__${iter.index}__].unitOfMeasure}" to th:field="*{ingredientsWrapper[__${iter.index}__].unitOfMeasure.id}" and it works now. Thanks for the help.


text:
Q: How to prove injectivity of a map matrix Let $K$ be a field. Show that the map
$$f : K \rightarrow K^{2×2}$$
$$ x \mapsto
 \begin{pmatrix}
  1 & x  \\
  0 & 1  \\
 \end{pmatrix}
$$
 is injective and that for $x,y \in K: f(x+y)=f(x)\cdot f(y)$.
This task confuses me in its triviality, what do I need to formally prove? Of course $x=y \iff f(x)=f(y)$, because all matrix elements will match.
The last part also seems easy, or is there also something to formally be proven there?

A: The first part of injective property is easily shown by your example of or by noting it is homomorphic and proceeding to show that the kernel is trivial.
The second part is relating to the homomorphism properties of $f$ which is easily shown as a consequence of the dot product, so yes, it is that easy.
$$\begin{bmatrix}1 & x \\ 0 &  1\\\end{bmatrix}\cdot\begin{bmatrix}1 & y \\ 0 & 1 \end{bmatrix} =  \begin{bmatrix}1 & x + y \\ 0 & 1\end{bmatrix}$$ Where matrix multiplication is the operation in $K^{2x2}$ and $K$ is the field with addition.


text:
Q: Jquery call .load function success but immediately fresh back I have a simple JQuery
<script>
$(function() {
$("#button_overview").on("click", function(){   $("#homepagecontent").load("../description/overview.htm");   });

});
</script>

By clicking the button, htm is loaded for 1 sec and than the page fresh back to previous stage. Looks like entire page is refreshed. Am I missing something in script?

A: You need to remove JavaScript immediate function invoke $(function() {});
<script>

$("#button_overview").on("click", function(){   $("#homepagecontent").load("../description/overview.htm");   });

</script>


text:
Q: Setting Visualforce page URL different from file name How to set a Visualforce page URL that is different from a file name?
At the moment my VF page URLs are the same as the file names:
MyPage.page URL will be /apex/MyPage
How to leave file name as is (for example MyPage.page) but change the URL to different one (for example /apex/YourPage)

A: One simple solution would be to create a new "dummy" visualforce page with a name you wished ("YourPage") that will redirect user to another page.
Redirect using javasript. Disadvantage of this solution is that a seocond page name appears on the browser url.
<apex:page>
    <script>
        window.location.href = '/apex/MyPage';
    </script>
</apex:page>

The second solution with an apex:include:
<apex:page>
    <apex:include pageName="MyPage" />
</apex:page>

Here a name of the first page ("YourPage") is not disappearing from the URL so this is preferred solution.

A: If you're working in the context of Sites, you can utilize the URL Rewriter.


text:
Q: What factors affect the critical temperature of a material? I recently started learning electricity in A level physics and came across the concept of superconductivity. I find this very intriguing due to its capabilities.
My questions are:

*

*What are the factors which affect the critical temperature for superconductivity of a material?

*Based on this, is it possible to create new materials which have a high critical temperature?

*Currently, what is the highest critical temperature of a material?

A: The electrical resistance arises due to collisions of charge carriers with the Atoms of the conductor. These collisions occur especially due to thermal Brownian Motion. If the conductor is cooled, the thermal Brownian Motion fades away and, depending on the material composition of the conductor, collisions go to Zero. Material composition, but also the external pressure influences the critical temperature of a material.
Since Generations of Research, scientists try to find new superconducting materials and aim for a higher critical temperature. Electrical Energy is also wasted in the wires and if we could find a superconductor that works on room temperature, we can save a lot of Energy.
It was found that the material consisting of mercury, Barium, Copper, Calcium and Oxygen ($HgBa_2Ca_2Cu_3O_{8+\delta}$) has the highest critical temperature (found since 1993). This critical temperature can be up to 138K.