text:
Q: How to turn off keyboard icon at TimePicker? I have a timepicker, everything works well but the problem is that I can't make it look like designer wants. For now it looks like this:

I need to hide this keyboard icon under the buttons. How can I do it? It's just a prototype, so here's only its xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  android:tag="ww">

  <TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Time"
    android:textAppearance="?android:attr/textAppearanceLarge" />

  <TimePicker
    android:id="@+id/timePicker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:amPmBackgroundColor="#6400AA"
    android:numbersSelectorColor="#6400AA" />

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

    <Button
      android:id="@+id/button2"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="Cancel"
      android:textColor="#6400AA" />

    <Button
      android:id="@+id/button1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="OK"
      android:textColor="#6400AA" />

  </LinearLayout>

</LinearLayout>

A: I just inspected the hierarchy in layout inspector and found that keyboard icon. For portrait and landscape hierarchy is different, so we have a orientation check for this and also have OS check from Oreo(from Oreo only this icon is availble), I tried this code and it is working fine.
PS: Kotlin Code
    fun hideKeyboardInputInTimePicker(orientation: Int, timePicker: TimePicker)
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            try
            {
                if (orientation == Configuration.ORIENTATION_PORTRAIT)
                {
                    ((timePicker.getChildAt(0) as LinearLayout).getChildAt(4) as LinearLayout).getChildAt(0).visibility = View.GONE
                }
                else
                {
                    (((timePicker.getChildAt(0) as LinearLayout).getChildAt(2) as LinearLayout).getChildAt(2) as LinearLayout).getChildAt(0).visibility = View.GONE
                }
            }
            catch (ex: Exception)
            {
            }

        }
    }

Call like this
hideKeyboardInputInTimePicker(this.resources.configuration.orientation, startTimePicker)

A: As far as I can tell you cannot remove this icon, it is part of the UI on Android O.
The icon is there to make the manual editing of the time more apparent because in previous versions it was not obvious that you could click on the time and change it via keyboard

A: Okay this is my solution. After inspecting the Layout I found that the keyboard is AppCompatImageButton. So you just do a recursion over the TimePicker which is a Viewgroup. So you can call it for example like this:
private fun initTimePicker() {
    timePicker.setIs24HourView(true)
    setImageButtonToGone(timePicker)
}

private fun setImageButtonToGone(viewGroup: ViewGroup) {
    for (i in 0 until viewGroup.childCount) {
        val child = viewGroup.getChildAt(i)
        if (child is LinearLayout) {
            setImageButtonToGone(child)
        } else if (child is AppCompatImageButton) {
            child.visibility = View.GONE
        }
    }
}

And you will get the desired layout.
WARNING!!! This depends heavely that the keyboard button is the only AppCompatImageButton if they change the XML of TimePicker this will not work properly anymore.

A: Try to use:
timePicker.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);

You also can use android:descendantFocusability="blocksDescendants" in xml.

A: Android N :
Date/Time picker come with rolling clock and that improved interaction with users to make entry but that made minute selection more tedious .Rolling clock sucks big time in 24h mode and while using thumb it was impossible to see exact time .

Android O :
Date/Time picker (in Calendar, Clock, etc) gets one small icon(manual entry) at the bottom left: a keyboard. Tapping it switches to text-based entry where you can manually type in the exact precise time.


text:
Q: first_or_initialize not working on json type column I want to use first_or_initialize on a table having a json type column as :
A.where("name=? and email=? and address->>'city'=? and address->>'state'=?", "John", "john@gmail.com", "New York", "New York").first_or_initialize
But, this doesn't seem to work. Any idea if we can use this on such a table?

A: Please try this
A.where("'name'=? and 'email'=? and 'address.city'=? and 'address.state'=?", "John", "john@gmail.com", "New York", "New York").first_or_initialize

I think this should help you..

A: It seems your request is correct according Rails guide
As they say :
  Query based on JSON document
  The -> operator returns the original JSON type (which might be an object), whereas ->> returns text

What is the return of the query (without .first_or_initialize)?
An error, an empty array ?
These posts may help you to build the query you want : Post1, Post2, PostgresqlHelp
Edit : Sorry, I misunderstood the question
––––––––––––––––––––––––––––––––
If the request is the problem, you can try this: (from here Rails guide)
A.includes(:address).where(name: "John", email: "john@gmail.com", address: {city: "New York", state: "New York"})

If the request is not the problem, could you give us more information on the error ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dimension of a null-space (Halmos) I am working on problem 3 from the exercises following the section on Annihilators in the text "Finite Dimensional Vector Spaces".
Problem: Prove that if $y$ is a linear functional on an $n$-dimensional vector space $V$, then the set of all those vectors for which $[x,y]=0$ is a subspace of $V$; what is the dimension of that subspace.
Showing that it is a subspace was not terribly difficult, given $\chi_{1},\chi_{2}\in V$, such that $[\chi_{j},y]=0$, $j=1,2$ it follows from the linearity of the functional that $$[\beta_{1}\chi_{1}+\beta_{2}\chi_{2},y]=\beta_{1}[\chi_{1},y]+\beta_{2}[\chi_{2},y]=0$$
For all $(\beta_{1},\beta_{2})\in\mathbb{C}^{2}$
Now showing the dimension of the subspace has been more difficult. A few sections previous to this question it was introduced the concept of a dual space for which the set of linear functionals over an $n$-dimensional vector space has an $n$-dimensional basis $\lbrace y_{j}\rbrace $. Where $\left[x_{i},y_{j}\right]=\delta_{ij}$, $\lbrace x_{i}\rbrace$ being an $n$-dimensional basis for $V$.
My intuition tells me that if a subspace of $V$ vanishes over a subspace of the dual space $V'$ then the dimension of the subspace of $V$ will be equal to that of the dimension of the subspace of the dual. If anyone has any hints on how to proceed I would greatly appreciate it.

A: The square bracket notation is rather unusual.  Most mathematicians tend to use the triangular brackets for this pairing: $\langle x,y\rangle$, if $x\in V$ and $y\in V^*$.  (The star notation is also the usual way to denote the dual space.)
Let me answer in the most general form; that is, when the base field is an arbitrary field $F$.  To answer your question, the dimension of $\text{ker}(y)=\big\{x\in V\,\big|\,\langle x,y\rangle=0\big\}$ depends on $y$.  If $y$ is the zero map, then the dimension of $\text{ker}(y)=V$ is clearly $\dim_F(V)=n$.  If $y$ is nonzero, then $\text{im}(y)=\left\{\langle x,y\rangle\,\big|\,x\in V\right\}$ is $F$ itself.  Now, we know that
$$\dim_F\big(\text{ker}(y)\big)+\dim_F\big(\text{im}(y)\big)=\dim_F(V)=n\,.$$
As $\dim_F(F)=1$, we conclude that $\dim_F\big(\text{ker}(y)\big)=n-1$.
A next question you might answer yourself is: if $y_1,y_2\in V^*$, what is the dimension of $\text{ker}\left(y_1\right)\cap\text{ker}\left(y_2\right)$?  There are three cases to consider.

A: Show that if $y\not=0$ then the null space of $y$ has co-dimension $1$. That is, fix $z$ where $y(z)\not=0$. Observe that any $x$ is $az+w$ for some scalar $a$ and some $w$ satisfying $y(w)=0$. Let $a=y(x)/y(z)$ and $w=x-az$. Hence if $B$ is a vector-space basis for the null space of y, then $Bu\{z\}$ is a basis for $V$, so B has $n-1$ members.


text:
Q: Branch.initSession function is not hit I am trying to redirect my users to correct page manually if the clicked a branch link to open my app.
I am fairly new to the concept and I don't fully understand the deeplinking, so this maybe wrong way of handling the issue but I am trying it as follows;
I am inside cordova environment, Cordova@7.1.0
installed branch-cordova-sdk 2.6.15
inside deviceready and resume, I initialize branch docs
document.addEventListener('deviceready', function() {
    branchInit();
}, false);

document.addEventListener('resume', function() {
    branchInit();
}, false);

function branchInit() {
    // Branch initialization
    console.log("branch init")
    Branch.initSession(function(data) { // this function doesn't get called
        console.log("branch init session:")
        console.log(data)
        if (data['+clicked_branch_link']) {
            $location.path(data['$location_path']); // redirect user to correct path
        }
    }).then(function(q) {
        console.log("initSession success");
        console.log(q);
    }).catch(function(e) {
        console.log("initSession error");
        console.log(e);
    });
}

And I create quick links from dashboard (docs). Send them to my phone(whatsapp) and click the links from whatsapp.
Branch opens my app successfully, but user doesn't get redirected to the correct page. And I got following console logs after click,
branch init
initSession success
{+clicked_branch_link: false, +is_first_session: false}

I think, since clicked_branch_link is false, initSession Callback function doesn't get called.

A: There was a bug on the Branch Cordova SDK v2.6.15 which was causing this issue. Please update your Branch Cordova SDk to 2.6.16.
Here are the release notes/comments: https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/issues/384#issuecomment-340621951


text:
Q: Confused by JTables & ActionPerformed I am trying to create a JTable that when a user presses a button on the GUI it sets the values inside the if statement to that JTable.
Being quite new to java I am most likely going about this wrong. I have done some research and I believe that using DefaultTableModel would be the best.
I understand how to implement the Jtable with a set of preset values but I am struggling to understand how to set the values with a JButton.
Thanks

A: Start with How to Use Tables. This related example shows one approach to altering the table's data model using buttons.


text:
Q: Module gets reloaded every request so initialized data are lost I store a value in a class variable inside of a module, such as:
module TranslationEnhancer
  def self.install! klass
    @dictionaries ||= [] << klass
  end
  ...
end

I call this from an initializer in config/initializers:
require Rails.root + "lib" + "translation_enhancer.rb"
TranslationEnhancer::install! TranslationDictionary

Now, if I start the server in development environment, everything is ok during the first request. However, after that request, @dictionaries are suddenly nil. I have commented all other code in TranslationEnhancer, so I am absolutely sure the whole module must get reloaded every time I do a request.
I tried to move the module outside of the lib directory (moved it to lib_unloadable), then I tried:
ActiveSupport::Dependencies.explicitly_unloadable_constants << "TranslationEnhancer"

but failed again. I have no idea how to solve this, please help.
Got Ruby 1.9.2 @ Rails 3.1.rc4.
EDIT: I know I could set the dictionaries as a constant. But I would like to use TranslationEnhancer as a library - so I could use it unchanged in a different project and install different Directories, such as:
TranslationEnhancer.install! EnglishDirectory, FrenchDirectory

These values won'd change during the runtime, they will just change project to project.

A: Solved!
I realized that the whole application.rb and environment.rb files are reloaded along with all other files. The only thing that does not get reloaded are initializers (config/initializers/*). The solution was to move the initialization to application.rb.

A: @dictionaries is not a "class variable". It is a "class-level instance variable".
Look here for a better explanation: Class and instance variables
Try using @@dictionaries instead.


text:
Q: Using provided Cross-Sectional survey weights in a Longitudinal model I'm running a longitudinal model using data from 3 waves of a survey.
I want to use the pre-calculated survey weights provided but I only have cross-sectional weights (1 per wave).
Do I weight each dataset first using the survey weights, and then merge them together? Or is there some way I should calculate a new longitudinal weight using these given weights?
I'm working in R and this is my code so far but as you can see there is only 1 weight included.
svydesign(data$psu, probs=NULL, strata = data$strata, variables = NULL, fpc=NULL,
          data = data, nest = FALSE, check.strata = TRUE, weights=data$i_indinui_xw,pps=FALSE)

A: You want the weights to add up to the population size, so you will typically need to divide weights by 3 if you have 3 waves.  See, for example, this advice on combining multiple waves of the NHANES survey.


text:
Q: Using chdir to move up a directory in Python Want to move up one directory from a given directory. I achieve this by doing:
import os
os.chdir(given_dir)
os.chdir('..')

But, I was wondering if there was a better more explicit way using (ideally) one statement or if there exists a built-in feature that I may not be aware of.

A: How about
import os, os.path
print os.chdir(os.path.join(given_dir, os.pardir))

OR
os.chdir(os.path.dirname(given_dir))

(as Selcuk suggested)


text:
Q: Como integro un lector de QR a mi sitio web? Tengo un sitio en el cual validare cupones en codigo QR, como integro una app externa que abra en mi sitio para que pueda leer el QR?

A: Es de suponer que el usuario visitante a tu web ya debe tener un lector de QR instalado en su dispositivo, aunque claro que solo podrá leer el QR que se muestre en otra pantalla, pero si buscas integrar uno a tu sitio para arrastrar un QR en formato de imagen, mira AQUÍ.---------


text:
Q: Using Python's max to return two equally large values I'm using Python's max function to find the largest integer in a dictionary called count, and the corresponding key (not quite sure if I'm saying it properly; my code probably explains itself better than I'm explaining it). The dictionary count is along the lines of {'a': 100, 'b': 210}, and so on.
number = count[max(count.items(), key=operator.itemgetter(1))[0]]
highest = max(count, key=count.get)

What would I do if there were two equal largest values in there? If I had {'a': 120, 'b': 120, 'c': 100}, this would only find the first of a and b, not both.

A: Idea is to find max value and get all keys corresponding to that value:
count = {'a': 120, 'b': 120, 'c': 100}

highest = max(count.values())

print([k for k, v in count.items() if v == highest])

A: Same idea as Asterisk, but without iterating over the list twice. Bit more verbose.
count = { 'a': 120, 'b': 120, 'c': 100 }
answers = []
highest = -1

def f(x):
    global highest, answers
    if count[x] > highest:
        highest = count[x]
        answers = [x]
    elif count[x] == highest:
        answers.append(x)

map(f, count.keys())
print answers

A: Fast single pass:
a = { 'a': 120, 'b': 120, 'c': 100 }
z = [0]
while a:
    key, value = a.popitem()
    if value > z[0]:
        z = [value,[key]]
    elif value == z[0]:
        z[1].append(key)

print z
#output:
[120, ['a', 'b']]

And an amusing way with defaultdict:
import collections
b = collections.defaultdict(list)
for key, value in a.iteritems():
    b[value].append(key)
print max(b.items())
#output:
(120, ['a', 'b'])

A: This could be a way (probably not the most efficient).
value = max(count.values())
filter(lambda key: count[key]==value,count)

A: Sometimes simplest solution may be the best:
max_value = 0
max_keys = []

for k, v in count.items():
    if v >= max_value:
        if v > max_value:
            max_value = v
            max_keys = [k]
        else:
            max_keys.append(k)

print max_keys

The code above is slightly faster than two pass solution like:
highest = max(count.values())
print [k for k,v in count.items() if v == highest]

Of course it's longer, but on the other hand it's very clear and easy to read.

A: To print a list without bucket. use :
' '.join(map(str, mylist))

or, more verbosely:
' '.join(str(x) for x in mylist)


text:
Q: BPE multiple ways to encode a word With BPE or WordPiece there might be multiple ways to encode a word. For instance, assume (for simplicity) the token vocabulary contains all letters as well as the merged symbols ("to", "ke", "en"). Then the word "token" could be encoded as ("to", "ke", "n") or ("to", "k", "en"). Such ambiguous encodings are also mentioned in this tutorial https://blog.floydhub.com/tokenization-nlp/
However, in the hugginface tutorial it is mentioned that "BPE and WordPiece [...] work out rules in a certain order that you can then apply in the same order when tokenizing new text", see https://huggingface.co/transformers/master/tokenizer_summary.html.
How exactly are these rules stored and applied when using BPE/WordPiece, e.g., in my example above, how is it determined which tokenization to use?

A: In the parsing step of BPE, the merging order matters. For instance, if the merging order is
(p, e), (pe, n), (pen, _), (a, p), (ap, p), (app, l), (appl, e), (apple, _), (pen, apple_)

Applepen PenapplePen should be segmented into this: [a, p, p, l, e, pe, pen, a, p, p, l, e, pen], given k = 2. We just use (p, e), (pe, n) for parsing. Since the merging order is fixed, the result should be fixed for the test data for any k. You just use the first k merges in the parsing step.
For the details please refer to my answer to the question: Explain bpe (Byte Pair Encoding) with examples?

A: The BPE algorithm learns the merge rules in a particular order based on the frequencies of subtokens. This ordering is used greedly during the encoding process for new text.
Considering the example from above, let's say the pair (e, n) appears 10 times in your training corpus, (t, o) appears 6 times and (k, e) appears 4 times. The BPE algorithm will learn 3 rules and apply them in the following order:
1. e, n -> en
2. t, o -> to
3. k, e -> ke

Encoding the new text token doesn't proceed from left to right, but instead it applies the rules based on their order. Therefore, the text will be encoded as follows:
Rule 1: t o k e n -> t o k en
Rule 2: t o k en -> t o k en
Rule 3: t o k en -> to k en

The Byte-Pair Encoding tokenization course on huggingface provides a reference implementation.


text:
Q: Из текста вычленить последнее значение в скобках с учетом условия Необходимо сформировать столбец значений для таблицы по исходным значениям другого столбца той же таблицы, содержащего в каждой ячейке значение вида:

1(ADCD);2(EFG);3(HJKLN)

Как мы видим, элементы разделены точкой с запятой ";". Требуется вычленить последний элемент 3(HJKLN) и его значение в скобках HJKLN использовать в ячейке нового столбца. При этом, если последний элемент имеет вид 5(CGHL), то есть за скобками стоит 5, то этот элемент пропускается и берётся предпоследний. Все элементы с пятёрками пропускаются:

Как это сделать в средствами Excel?

A: Function get_last_not_5(source As Range)
get_last_not_5 = ""
If source.Cells.Count > 1 Then
    Exit Function
End If
Dim tmp() As String
tmp = Split(source.Value, ";")
Dim i As Integer
For i = UBound(tmp) To LBound(tmp) Step -1
    If Left(tmp(i), 1) <> "5" Then
        get_last_not_5 = tmp(i)
        Exit Function
    End If
Next
End Function

A: 1- Нужное значение можно извлечь формулой листа:
=СЖПРОБЕЛЫ(ПРАВБ(ПОДСТАВИТЬ(ЛЕВБ("kk"&A2;ПОИСК(5;A2&"kk5")-1);"(";ПОВТОР(" ";9));9))

2-  Вариант UDF:
Function fExtractVal(sStr As String) As String
    Dim j As Long, sTemp As String

    sTemp = Split(";" & sStr, ";5")(0)
    j = InStrRev(sTemp, "(") + 1

    fExtractVal = Replace(Mid$(sTemp, j), ")", "")
End Function

В ячейку:
=fExtractVal(A2)


text:
Q: IEF reference show parent field as title using Auto Entity Label I am new to Drupal 8 want to add a field value to IEF reference title. for now I am using Auto Entity Label version 2.x-dev to automatically generate title for my Entities but when it comes to IEF references I wan to get name of parent as title of IEF. as example see below image

Then I wan to add a new IEF entity which is using Auto Entity label to generate title automatically

As you can see it only says 15% complete but I want it to be Stack Overflow 15% Complete
here is tokens that I selected to Auto Entity label to show name in IEF reference.
[entity-x:field_name] - [task:field_percent_complete] % Completed

This token pattern placed inside Task entity
Note: I Entity-x and Task are two different Entity in system


text:
Q: How to swap out a sprite in Unity2D based on a Dictionary entry? I'm very new to Unity and programming in C# altogether, so apologies if this is a little elementary;
Basically I want to change a sprite in my game for 10 seconds, and then change back to the original sprite. I have stored this sprite in a dictionary entry, as well as the sprites that I wish to change to in a List. I create these dictionary entries with a loop that filters in the correct name for the sprites and other entry values based on our position in the loop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;

public class PaddleAbilities : MonoBehaviour
{

    public Dictionary<string, Ability> AbilitiesDictionary = new Dictionary<string, Ability>();

    [Header("GUI Sprites")]
    public List<Sprite> abilitySprites;

    [Header("Ability Costs")]
    public int Q_Cost;
    public int W_Cost;
    public int E_Cost;
    public int R_Cost;

    [Header("Ability Cooldowns")]
    public float Q_Cooldown;
    public float W_Cooldown;
    public float E_Cooldown;
    public float R_Cooldown;

    //ability ready timers
    public bool Q_Ready = true;
    public bool W_Ready = true;
    public bool E_Ready = true;
    public bool R_Ready = true;

    //access Scripts
    [Header("Other")]
    public GameManager gameManager;
    public Paddle paddle;
    public int Score;
    public string thisPlayer;
    private Vector2 Position;

    void Awake()
    {
        //get our Game Objects
        gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
        paddle = this.gameObject.GetComponent<Paddle>();

        //Get resource position
        Position = this.gameObject.transform.position;
    }

    void Start()
    {
        //which player is this script assigned to?
        if (Position.x < 0)
        {
            thisPlayer = "P1";
            Score = gameManager.scoreValueP1;
        }
        else if (Position.x > 0)
        {
            thisPlayer = "P2";
            Score = gameManager.scoreValueP2;
        }

        for (int i = 1; i < 5; i++)
        {
            int Cost = 0;
            switch (i)
            {   case 1:
                    Cost = Q_Cost;
                    break;
                case 2:
                    Cost = W_Cost;
                    break;
                case 3:
                    Cost = E_Cost;
                    break;
                case 4:
                    Cost = R_Cost;
                    break;
            }

            float Cooldown = 0;
            switch (i)
            {   case 1:
                    Cooldown = Q_Cooldown;
                    break;
                case 2:
                    Cooldown = W_Cooldown;
                    break;
                case 3:
                    Cooldown = E_Cooldown;
                    break;
                case 4:
                    Cooldown = R_Cooldown;
                    break;
            }

            if(thisPlayer == "P1")
            {
                string P1Name = "Ability" + i + "_P1";
                AbilitiesDictionary.Add(P1Name, new Ability(P1Name, GameObject.Find(P1Name).GetComponent<SpriteRenderer>().sprite, Cost, Cooldown));
            }
            else if (thisPlayer == "P2")
            {
                string P2Name = "Ability" + i + "_P2";
                AbilitiesDictionary.Add(P2Name, new Ability(P2Name, GameObject.Find(P2Name).GetComponent<SpriteRenderer>().sprite, Cost, Cooldown));
            }
        }
    }

    public class Ability
    {
        public string SpriteName { get; set; }
        public Sprite AbilitySprite { get; set; }
        public int AbilityCost { get; set; }
        public float AbilityCooldown { get; set; }

        public Ability(string spriteName, Sprite abilitySprite, int abilityCost, float abilityCooldown)
        {
            this.SpriteName = spriteName;
            this.AbilitySprite = abilitySprite;
            this.AbilityCost = abilityCost;
            this.AbilityCooldown = abilityCooldown;
        }
    }

    void Update()
    {
        AbilitiesRead();

        if (thisPlayer == "P1")
        {
            Score = gameManager.scoreValueP1;
        }
        else if (thisPlayer == "P2")
        {
            Score = gameManager.scoreValueP2;
        }
    }

    //Key press check gets called in update
    public void AbilitiesRead()
    {
        if (Input.GetKeyDown(KeyCode.Q) && Q_Ready && Score >= AbilitiesDictionary["Ability1_" + thisPlayer].AbilityCost)
        {
            Debug.Log(thisPlayer + " attempted to spawn a ball.");
            StartCoroutine(ServeBall());
        }
    }

    //ENUMERATORS v
    private IEnumerator SkillDuration(float WaitTime)
    {
        //Debug.Log("Skill is active. Waiting for skill to deactivate.");
        yield return new WaitForSeconds(WaitTime);
    }

    private IEnumerator ServeBall()
    {
        gameManager.serveTowards = paddle.Opponent; //make sure we serve at our opponent when this ability is called
        gameManager.SpawnBall(1); //spawn a Ball (the ball will use this paddle.Opponent to determine which direction to go in.)

        Q_Ready = false; //this ability is now on cooldown.

        Score -= AbilitiesDictionary["Ability1_" + thisPlayer].AbilityCost; //deduct our Ability Cost
        AbilitiesDictionary["Ability1_" + thisPlayer].AbilitySprite = abilitySprites[1]; //swap out Q_sprite for this player to the greyscale version "Q_Ability_onCooldown.psd"
        yield return StartCoroutine(SkillDuration(AbilitiesDictionary["Ability1_" + thisPlayer].AbilityCooldown)); //WaitForSeconds for the amount of time we want to cooldown for.
        AbilitiesDictionary["Ability1_" + thisPlayer].AbilitySprite = abilitySprites[0]; //swap out Q_sprite for this player to the color version "Q_Ability.psd"

        Q_Ready = true; //this ability is now ready to be used again.
    }
}

Here are my sprites in the Hierarchy. I was able to confirm that my dictionary entry DOES find the sprites, but when I set that entry equal to the sprite in the list that I want to change to, nothing happens on the Unity side of things.
Ability Sprites in Hierarchy

A:  AbilitiesDictionary.Add(P1Name, new Ability(P1Name, GameObject.Find(P1Name).GetComponent<SpriteRenderer>().sprite, Cost, Cooldown));

Instead of referencing the sprite itself, you should reference the SpriteRenderer and exchange the sprite of the SpriteRenderer like this:
In your AbilityClass reference the Renderer:
 public class Ability
{
    public string SpriteName { get; set; }
    public SpriteRenderer AbilitySprite { get; set; }
    public int AbilityCost { get; set; }
    public float AbilityCooldown { get; set; }

    public Ability(string spriteName, Sprite abilitySprite, int abilityCost, float abilityCooldown)
    {
        this.SpriteName = spriteName;
        this.AbilitySprite = abilitySprite;
        this.AbilityCost = abilityCost;
        this.AbilityCooldown = abilityCooldown;
    }
}

Add the Renderer to your Class
if(thisPlayer == "P1")
        {
            string P1Name = "Ability" + i + "_P1";
            AbilitiesDictionary.Add(P1Name, new Ability(P1Name, GameObject.Find(P1Name).GetComponent<SpriteRenderer>(), Cost, Cooldown));
        }

Exchange the sprite:
AbilitiesDictionary["Ability1_" + thisPlayer].AbilitySprite.sprite = abilitySprites[1];

The code is untested so no guaratee there are no spelling errors ;)


text:
Q: What is providing the argument in this lambda function? If there's a list and we have something like this:
var myNumbers  = new List<int> { 0, 1, 2, 3, 4};
var numbersOver1 = myNumbers.Where(n => n > 1);

intuitively I can understand that the n argument is a list element. But I'm watching a tutorial where the lambda argument is not intuitive. Here's a screenshot:

In the screenshot what is providing the "table" argument?


text:
Q: AVX vs. SSE: expect to see a larger speedup I expected AVX to be about 1.5x faster than SSE. All 3 arrays (3 arrays * 16384 elements *4 bytes/element = 196608 bytes) should fit in L2 cache (256KB) on an Intel Core CPU (Broadwell).
Are there any special compiler directives or flags that I should be using?
Compiler Version
$  clang --version
Apple LLVM version 9.0.0 (clang-900.0.38)
Target: x86_64-apple-darwin16.7.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

Compile line
$  make avx
clang -O3 -fno-tree-vectorize -msse -msse2 -msse3 -msse4.1 -mavx -mavx2 avx.c ; ./a.out 123
n: 123
  AVX Time taken: 0 seconds 177 milliseconds
vector+vector:begin int: 1 5 127 0

  SSE Time taken: 0 seconds 195 milliseconds
vector+vector:begin int: 1 5 127 0

avx.c
#include <stdio.h>
#include <stdlib.h>
#include <x86intrin.h>
#include <time.h>
#ifndef __cplusplus
#include <stdalign.h>   // C11 defines _Alignas().  This header defines alignas()
#endif
#define REPS 50000
#define AR 16384

// add int vectors via AVX
__attribute__((noinline))
void add_iv_avx(__m256i *restrict a, __m256i *restrict b, __m256i *restrict out, int N) {

    __m256i *x = __builtin_assume_aligned(a, 32);
    __m256i *y = __builtin_assume_aligned(b, 32);
    __m256i *z = __builtin_assume_aligned(out, 32);

    const int loops = N / 8; // 8 is number of int32 in __m256i
    for(int i=0; i < loops; i++) {
        _mm256_store_si256(&z[i], _mm256_add_epi32(x[i], y[i]));
    }
}

// add int vectors via SSE; https://en.wikipedia.org/wiki/Restrict
__attribute__((noinline))
void add_iv_sse(__m128i *restrict a, __m128i *restrict b, __m128i *restrict out, int N) {

    __m128i *x = __builtin_assume_aligned(a, 16);
    __m128i *y = __builtin_assume_aligned(b, 16);
    __m128i *z = __builtin_assume_aligned(out, 16);

    const int loops = N / sizeof(int);
    for(int i=0; i < loops; i++) {
        //out[i]= _mm_add_epi32(a[i], b[i]); // this also works
        _mm_storeu_si128(&z[i], _mm_add_epi32(x[i], y[i]));
    }
}

// printing
void p128_as_int(__m128i in) {
    alignas(16) uint32_t v[4];
    _mm_store_si128((__m128i*)v, in);
    printf("int: %i %i %i %i\n", v[0], v[1], v[2], v[3]);
}

__attribute__((noinline))
void debug_print(int *h) {
    printf("vector+vector:begin ");
    p128_as_int(* (__m128i*) &h[0] );
}

int main(int argc, char *argv[]) {
    int n = atoi (argv[1]);
    printf("n: %d\n", n);

    int *x,*y,*z;
    if (posix_memalign((void**)&x, 32, 16384*sizeof(int))) { free(x); return EXIT_FAILURE; }
    if (posix_memalign((void**)&y, 32, 16384*sizeof(int))) { free(y); return EXIT_FAILURE; }
    if (posix_memalign((void**)&z, 32, 16384*sizeof(int))) { free(z); return EXIT_FAILURE; }
    x[0]=0; x[1]=2; x[2]=4;
    y[0]=1; y[1]=3; y[2]=n;

    // touch each 4K page in x,y,z to avoid copy-on-write optimizations
    for (int i=512; i<AR; i+= 512) { x[i]=1; y[i]=1; z[i]=1; }

    // warmup
    for(int i=0; i<REPS; ++i) { add_iv_avx((__m256i*)x, (__m256i*)y, (__m256i*)z, AR); }
    // AVX
    clock_t start = clock();
    for(int i=0; i<REPS; ++i) { add_iv_avx((__m256i*)x, (__m256i*)y, (__m256i*)z, AR); }
    int msec = (clock()-start) * 1000 / CLOCKS_PER_SEC;
    printf("  AVX Time taken: %d seconds %d milliseconds\n", msec/1000, msec%1000);
    debug_print(z);

    // warmup
    for(int i=0; i<REPS; ++i) { add_iv_sse((__m128i*)x, (__m128i*)y, (__m128i*)z, AR); }
    // SSE
    start = clock();
    for(int i=0; i<REPS; ++i) { add_iv_sse((__m128i*)x, (__m128i*)y, (__m128i*)z, AR); }
    msec = (clock()-start) * 1000 / CLOCKS_PER_SEC;
    printf("\n  SSE Time taken: %d seconds %d milliseconds\n", msec/1000, msec%1000);
    debug_print(z);

    return EXIT_SUCCESS;
}

A: The problem is that that your data doesn't fit in the L1 cache.
The L1 bandwidth of Broadwell is much larger than the L2 bandwidth.
The L1 bandwidth is large enough to load two 32 byte vectors every cpu cycle. So, a better AVX vs. SSE speedup
might be expected if your data set is much smaller. However, note that
the combined L1 read/write bandwidth is less than 2*32(r)+32(w)=96 bytes per cycle.
In practice 75 bytes per cycle is possible, see here.
The second graph on this page shows that indeed the L2 bandwidth is much smaller:
At Test_block_size=128KB (=32KB per core) the bandwidth is 900GB/s.
At Test_block_size=1MB (=256KB per core) the bandwidth is only 300GB/s.
(Note that Haswell 4770k has more or less the same L1 and L2 cache architecture as Broadwell.)
Try to reduce AR to 2000 and to increase NREP to 1000000 and see what happens with the SSE vs. AVX speedup.


text:
Q: Is it possible to create 3D-Images with optical distortion and transparency effects? Is it possible to create 3D-Images like this one:

with LaTeX (preferably tikz)? How do you do it? Are there good tutorials / documentations?
(I have seen some examples from tikz-3dplot, but these images always have axis (e.g. this or those) and the colors don't look as nice as in the image above)

A: As @canaaerus said, it is possible to do such images in Tikz, but it is not a good idea. Tikz processing is slow for complicated pictures, and even if it may process transparency and 3D coordinates (this is all in the PGF reference), you will work much better with a dedicated software and export either to PNG, PDF or even tikz for some programs. The partial illumination effects for example would be really hard to get right with Tikz. My advice: use the tool best adapted to your graphics.
Note also that transparency in PDF sometimes does not work correctly with certain printers (especially for posters; the processing software is sometimes old on these machines ; I've had this problem several times a few years ago), so bitmap is sometimes a better idea (and tikz does not generate bitmaps). Using a better-suited program with export capabilities will ensure that you can produce high-quality documents and printables documents.


text:
Q: Angular2: issues the barcode function is undefined I am fresher in angular 2, I am developing an ionic 2 app in that i am using bar-code scanner plugin, the problem is I am scanning the bar-code depending on the number of orders, but unfortunately I'm getting an error showing below
error.log
**EXCEPTION: Error in ./AcceptOrdersFromVanPage class AcceptOrdersFromVanPage - inline template:64:8 caused by: this.barcode(...) is undefined  main.js:64726:9
ORIGINAL EXCEPTION: this.barcode(...) is undefined  main.js:64728:13
ORIGINAL STACKTRACE:  main.js:64731:13
AcceptOrdersFromVanPage/this.vendorbarcode@http://localhost:8100/build/main.js:26913:17
AcceptOrdersFromVanPage</AcceptOrdersFromVanPage.prototype.AcceptOrderfromVendor@http://localhost:8100/build/main.js:27016:9
anonymous/View_AcceptOrdersFromVanPage2.prototype.handleEvent_14@/AppModule/AcceptOrdersFromVanPage/component.ngfactory.js:428:21
DebugAppView</DebugAppView.prototype.eventHandler/<@http://localhost:8100/build/main.js:127682:24
decoratePreventDefault/<@http://localhost:8100/build/main.js:46755:36
O</d</t.prototype.invokeTask@http://localhost:8100/build/polyfills.js:3:9712
onInvokeTask@http://localhost:8100/build/main.js:44826:28
O</d</t.prototype.invokeTask@http://localhost:8100/build/polyfills.js:3:9640
O</v</e.prototype.runTask@http://localhost:8100/build/polyfills.js:3:7064
t/this.invoke@http://localhost:8100/build/polyfills.js:3:10834
EventListener.handleEvent*u@http://localhost:8100/build/polyfills.js:2:27976
O</d</t.prototype.scheduleTask@http://localhost:8100/build/poly[…]  main.js:64732:13
ERROR CONTEXT:  main.js:64735:13
Object { _view: Object, _nodeIndex: 14, _tplRow: 64, _tplCol: 8 }  main.js:647**

this is my template.html
<ion-content>

  <ion-card *ngFor='let d of torders; let i = index;'>
    <ion-card-header>

Total Order(s) : {{d.Total_Orders}}

    </ion-card-header>
    <ion-row>
      <ion-col>
        <button ion-button icon-left clear small (click)="Accept(i, torders)">
          Accept
        </button>
      </ion-col>
    </ion-row>
  </ion-card>

</ion-content>

and this my .ts file
export class AcceptPage implements OnInit {
 bartxt: any;
  orderids: any;
  orderarray: any;
  orderstring: any;
  totalorders: any;
  _i: number = 0;
barcode(index, torders) {
    BarcodeScanner.scan().then((barcodeData) => {
      if (barcodeData.cancelled) {
        alert("User cancelled the action!");
        return false;
      }
      this.bartxt = barcodeData.text;
      if (this.bartxt != '') {
        this.authservice.validate(this.bartxt, this.orderids)
          .subscribe(data => {
            if (data == "BARCODE_FOUND") {
               alert("scanned successfully");
                if (this._i == (this.totalorders - 1)) {
                  this._i = 0;
                  this.finalacceptvendor(index, torders);
                } else {
                  this._i++;
                  this.vendorbarcode(index, torders);
                }
            } else {
              alert("wrong qr code")
              this.vendorbarcode(index, torders);
            }
          });
      }
    });
  }

public vendorbarcode = function (index, torders) {
    this.totalorders = this.torders[index].Total_Orders;
    this.orderarray = this.orderstring.split(',');
    this.orderids = this.orderarray[this._i];
    while (this._i < this.totalorders) {
      this.barcode(index, torders)
        .then(function (response) {
        });
    }
  }
Accept(index, torders) {
    this.vendorbarcode(index, torders);
  }

finalacceptvendor(index, torders) {
    this.authservice.finalFunction(this.torders[index].OrderId)
      .subscribe(data => {
        if (data == 'UPDATE_SUCCESS') {
          alert("success");
        } else {
          alert("fail");
        }
      },
      err => {
        console.log('err');
      });
  }
}

I have gone through some posts related to my problem but unable to sort the issue.. Please help me sort this issue...

A: You are not returning from your barcode() method so you should be using as
barcode(index, torders) : Promise<any> { ///////////////
   return BarcodeScanner.scan().then((barcodeData) => {
      if (barcodeData.cancelled) {
        alert("User cancelled the action!");
        //return false;//////////remove this line
      }
      this.bartxt = barcodeData.text;
      if (this.bartxt != '') {
        this.authservice.validate(this.bartxt, this.orderids)
          .subscribe(data => {
            if (data == "BARCODE_FOUND") {
               alert("scanned successfully");
                if (this._i == (this.totalorders - 1)) {
                  this._i = 0;
                  this.finalacceptvendor(index, torders);
                } else {
                  this._i++;
                  this.vendorbarcode(index, torders);
                }
            } else {
              alert("wrong qr code")
              this.vendorbarcode(index, torders);
            }
          });
      }
    });
  }

A: barcode  method should return a promise if vendorbarcode method is trying to do this.barcode(index, torders).then(...)


text:
Q: Python and regex: create a template I need to find a lot of substrings in string but It takes a lot of time, so I need to combine it in pattern:
I should find string
003.ru/%[KEYWORD]%
1click.ru/%[KEYWORD]%
3dnews.ru/%[KEYWORD]%

where % - is an any symbols
and [KEYWORD] - can be ['sony%xperia', 'iphone', 'samsung%galaxy', 'lenovo_a706']
I try to do a search with
keywords = ['sony%xperia', 'iphone', 'samsung%galaxy', 'lenovo_a706']
for i, key in enumerate(keywords):
    coding['keyword_url'] = coding.url.apply(lambda x: x.replace('[KEYWORD]', key).replace('%', '[a-zA-Z0-9-_\.\?!@#$%^&*+=]+') if '[KEYWORD]' in x else x.replace('%', '[a-zA-Z0-9-_\.\?!@#$%^&*+=]+'))
    for (domain, keyword_url) in zip(coding.domain.values.tolist(), coding.keyword_url.values.tolist()):
        df.loc[df.event_address.str.contains(keyword_url), 'domain'] = domain

Where df contains only event_address (urls)
coding
domain  url
003.ru  003.ru/%[KEYWORD]%
1CLICK  1click.ru/%[KEYWORD]%
33033.ru    33033.ru/%[KEYWORD]%
3D NEWS 3dnews.ru/%[KEYWORD]%
96telefonov.ru  96telefonov.ru/%[KEYWORD]%

How can I improve my pattern to do it faster?

A: First, you should consider using re module. Look at the re.compile function for your patterns and then you can match them.


text:
Q: Delphi Firemonkey ios Background Fetch i'm trying to use delphi Firemonkey to develop an iphone App. I need to download an xml every x minutes and process it, if there are new data send notification. It's very easy if the app is in use, but i can't find the way to use this procedure when the app is in background....
Please help me...
Tnx a lot...But i can't do this....
this is my simpliest code that doesn't work... What is my error???
procedure TForm1.Button1Click(Sender: TObject);
var
  IdHTTP1 : TIdHTTP;
  MyFile          : TFileStream;
  Notification: TNotification;
  UIApp : UIApplication;
begin
  UIApp := TUIApplication.Wrap(TUIApplication.OCClass.sharedApplication);
  UIApp.setIdleTimerDisabled(True);

  TThread.CreateAnonymousThread(procedure ()
  var
I: Integer;
Total: Integer;
  begin
Total := 0;

while true do
  begin

    // Carico l'XML
    MyFile:= TFileStream.Create(TPath.GetDocumentsPath + TPath.DirectorySeparatorChar+'listticket',fmCreate);

    IdHTTP1 := TIdHTTP.Create(nil);
    IdHTTP1.Get('http://www.google.com', MyFile);
    IdHTTP1.Free;
    MyFile.Free;

  end;

sleep(5*60*1000);

TThread.Synchronize (TThread.CurrentThread,
  procedure ()
  begin
  end);
  end).Start;
end;

A: See these articles to get you started.
Disable The IOS Device Idle Time Out In Your Delphi XE5 Firemonkey App
Programatically Disable the Idle Timer on iOS using the ObjectiveC Bridge
Providing background services support to your iOS apps with Delphi
Handle Android And IOS Lifecycle Events In Delphi XE5 Firemonkey


text:
Q: Javascript Inline SVG Help Needed I am unable to translate the bar_position using javascript.
slider3.oninput = function() {
output3.innerHTML = this.value;
bar_position.style.transform='translate(0)';
}

See the Pen Position Gauge by John (@johnkelton) on CodePen.

A: You have three numbers: start, value, and end. You can get the percentage value is between start and end with the following equation:
( value - minimum ) / ( maximum - minimum)

You can then convert that percentage to the UI by multiplying by the width of the element, which is hardcoded to be 50.834 pixels in the codepen:
const x = ( this.value - output1.innerHTML ) / ( output2.innerHTML - output1.innerHTML ) * 50.834;
bar_position.style.transform=`translate(${x}px)`;


text:
Q: SL4 Facebook application no longer retrieves access_token I have an SL4 Out of Browser application which has been working for several months. As of right now, it appears it will not longer retrieve an access_token from Facebook. I am using facebook-c#-sdk v4.1.1. Some partial code is posted below:
    void FacebookLoginBrowser_Loaded(object sender, RoutedEventArgs e)
    {
        if (!loggedIn)
        {
            LoginToFacebook();
        }
    }

    private void LoginToFacebook()
    {

        dynamic parms = new System.Dynamic.ExpandoObject();
        parms.display = "popup";
        parms.client_id = appId;
        parms.redirect_uri = successUrl;
        parms.cancel_url = failedUrl;
        parms.scope = requestedFbPermissions;
        parms.type = "user_agent";

        loggingInUri = fbApp.GetLoginUrl(parms);

        FacebookLoginBrowser.Source = (loggingInUri);

    }

Below is the code for the html page the browser is redirected to:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    Complete
</body>
<script type="text/javascript">
    window.external.notify(window.location.href);
</script>
</html>

The javascript then fires the following:
    private void FacebookLoginBrowser_ScriptNotify(object sender, NotifyEventArgs e)
    {

        if (e.Value != "Failed")
        {
            string url = e.Value.Replace('#', '?');

            url = HttpUtility.UrlDecode(url);

            Uri ur = new Uri(url);

            string[] str = ur.Query.Split('&');
            access_token =  str[0].Split('=')[1];

            if(!String.IsNullOrEmpty(access_token)){
                fbApp = new FacebookApp(access_token);

                App app = (App)Application.Current;
                app.Fuid.fbApp = fbApp;

                loggedIn = true;
                loginSucceeded(e);
            }

        }

        if (fbApp.Session == null)
        {

            failedLogin();
        }
    }

It appears the querystring which normally contains the access_token value is not longer there. Using Fiddler, I was able to see the redirect from facebook which does contain the access_token value. I am not sure where it is being lost at. Let me know if any one needs any additional information. Thanks!

A: There has been a change in Facebook behavior regarding the structure of the query string. This is discussed in http://facebooksdk.codeplex.com/discussions/261528. My code uses WPF and not Silverlight; I'm not sure whether the same issue applies to the Silverlight control.
Note that the current version of Facebook C# SDK is 5.0.40 per http://facebooksdk.codeplex.com/.
Also see Does Facebook Client-Side Flow still give out access tokens?.


text:
Q: GCP List Folders Via API - "methodResource() takes 1 positional argument but 2 were given" Using the API from their documentation page works: https://cloud.google.com/resource-manager/reference/rest/v2beta1/folders/list?apix_params=%7B%22parent%22%3A%22organizations%2F319808429458%22%7D
However, when using the API within Python, I'm presently receiving the error:
"methodResource() takes 1 positional argument but 2 were given"
My code is as follows:
credentials = ServiceAccountCredentials.from_json_keyfile_name(JSONPath)
cloudresman = discovery.build('cloudresourcemanager', 'v2beta1', credentials=credentials)
ORGID = "organizations/12345678910"
folderdicts = cloudresman.folders(ORGID).list().execute()

From what I've read online, this seems to be a problem with the class; but of course, Google have made the 'discovery' class. Am I doing something wrong? Can anyone else use the Python API to list folders within their GCP organisation?

A: In my code, I have this working example for a search.
...
    CREDENTIALS = GoogleCredentials.get_application_default()
    SERVICE_RESOURCE_MANAGER_FOLDER = discovery.build('cloudresourcemanager', 'v2', credentials=CREDENTIALS)
    request = SERVICE_RESOURCE_MANAGER_FOLDER.folders().search(body=body)
    response = request.execute()
    return response

In your beta API, I guess that the problem is the ORGID set on the folders() method. Did you try to set it in the list() as the body param name in my code?


text: Q: Appropriate Background Image Size My app keeps crashing due to an "Out of memory" exception. I'm almost positive that it has something to do with all of my images used within the app. I threw them in my drawable folder in the beginning without ever considering their size. For example, I use a background .png image in all of my Fragments. It's size is 832x561. Is that too large for say a standard android phone like a nexus 5? Is there a reference chart for appropriate image size based on device? Thank you.


text:
Q: How to drag and drop multiple element bottom of selected element I want to develop playing card game and want to move the multiple cards between decks. So I just built simple drag and drap example.
index.html
<!DOCTYPE HTML>

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>

        item1

        item2

         item3

         item4

      dropzone

style.css
body{
width: 40%;
}

.example-parent {
border: 2px solid #DFA612;
color: black;
display: flex;
font-family: sans-serif;
font-weight: bold;
}

.example-origin {
flex-basis: 100%;
flex-grow: 1;
padding: 10px;
}

.example-draggable {
background-color: #4AAE9B;
font-weight: normal;
margin-bottom: 10px;
margin-top: 10px;
padding: 10px;
}

.example-dropzone {
background-color: #6DB65B;
flex-basis: 100%;
flex-grow: 1;
padding: 10px;
}

script.js
function onDragStart(event) {
event
  .dataTransfer
  .setData('text/plain', event.target.id);
event.currentTarget.style.backgroundColor = 'yellow';
}

function onDragOver(event) {
    event.preventDefault();
}

function onDrop(event) {
const id = event
  .dataTransfer
  .getData('text');

const draggableElement = document.getElementById(id);
const dropzone = event.target;
dropzone.appendChild(draggableElement);
event.dataTransfer.clearData();
}

function onDragStart(event) {
    event
      .dataTransfer
      .setData('text/plain', event.target.id);
    event.currentTarget.style.backgroundColor = 'yellow';
}

function onDragOver(event) {
    event.preventDefault();
}

function onDrop(event) {
    const id = event
      .dataTransfer
      .getData('text');

    const draggableElement = document.getElementById(id);
    const dropzone = event.target;
    dropzone.appendChild(draggableElement);
    event.dataTransfer.clearData();
}
body{
    width: 40%;
}

.example-parent {
    border: 2px solid #DFA612;
    color: black;
    display: flex;
    font-family: sans-serif;
    font-weight: bold;
  }

  .example-origin {
    flex-basis: 100%;
    flex-grow: 1;
    padding: 10px;
  }

  .example-draggable {
    background-color: #4AAE9B;
    font-weight: normal;
    margin-bottom: 10px;
    margin-top: 10px;
    padding: 10px;
  }

  .example-dropzone {
    background-color: #6DB65B;
    flex-basis: 100%;
    flex-grow: 1;
    padding: 10px;
  }

This is how it is working.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>

            item1

            item2

             item3

             item4

          dropzone

But I want to drag multiple elements. For example, when I drag item2, item3 and item4 must be draggable with item2 or when I drag item3, item4 must be draggable with it. And also when I drag items how to change their position with the mouse.

A: Here is the code,I found it my question.

var x="";
var y="";
var selected="";
var allelement="";

function onDragStart(event) {
  x=event.pageX;
  y=event.pageY;
  event
      .dataTransfer
      .setData('text/plain', event.target.id);

  allelement = Array.prototype.slice.call( document.getElementById(event.target.id).parentElement.children )

  var index = allelement.indexOf(event.target)
  selected= allelement.slice(index)
  event.dataTransfer.setDragImage(new Image("0", "0"), -10, -10);
  event.currentTarget.style.backgroundColor = 'yellow';
}
function drag(event){
  const movex=event.pageX - x;
  const movey=event.pageY - y;

  selected.forEach((item)=>{
  var element = document.getElementById(item.id);
  var css=
  "z-index:9999;pointer-events: none; transform: scale(1.05, 1.05) rotate(0deg) translate(" +
  movex +
  "px, " +
  movey +
  "px);";
  element.style.cssText = css;
})
}

function onDragEnter(event) {
    event.preventDefault();
    console.log("dragenter ", event.target.id);
}

function onDragOver(event) {
    event.preventDefault();
}

function onDrop(event) {

    const id = event
      .dataTransfer
      .getData('text');

    const dropzone = event.target;
    selected.forEach((element)=>{

      var css = "z-index:0;pointer-events:auto;";
      element.style.cssText = css;
      dropzone.appendChild(element);
    })

}
body{
    width: 80%;
}

.example-parent {
    border: 2px solid #DFA612;
    color: black;
    display: flex;
    font-family: sans-serif;
    font-weight: bold;
  }

  .example-origin {
    flex-basis: 100%;
    flex-grow: 1;
    padding: 10px;
  }

  .example-draggable {
    background-color: #4AAE9B;
    font-weight: normal;
    margin-bottom: 10px;
    margin-top: 30px;
    padding: 10px;
    width: 50px;
  }

  .example-dropzone {
    background-color: #6DB65B;
    flex-basis: 100%;
    flex-grow: 1;
    padding: 10px;
    margin-left:100px ;
  }
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>

            item1

            item2

             item3

             item4

          dropzone

          dropzone

          dropzone

          dropzone


text:
Q: How to create non-unique index on column in sqlalchemy? I'm trying to create a non-unique index on the file_name column.  I'm expecting a high cardinality, say for 1,000 rows, there are 950 unique file names.
file_collection = Table ('file_collection', metadata,
    Column('id', Integer, primary_key=True),
    Column('full_path', String, unique=True, nullable=False),
    Column('file_name', String, index=True, nullable=False)
)

My dialect is sqlite. When I create the table, a non-unique key is not created on the file_name column
CREATE TABLE file_collection (
        id INTEGER NOT NULL,
        full_path VARCHAR NOT NULL,
        file_name VARCHAR NOT NULL,
        PRIMARY KEY (id),
        UNIQUE (full_path)
)

How can I create a non-unique key on the file_name column?

A: Remember that SQLite requires you to create a non-unique index as a separate statement rather than in the actual CREATE TABLE statement like some RDBMs allow. Assuming I have the following table:
class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), index=True)

The creation will run as follows.
2014-01-03 17:28:48,229 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("users")
2014-01-03 17:28:48,229 INFO sqlalchemy.engine.base.Engine ()
2014-01-03 17:28:48,229 INFO sqlalchemy.engine.base.Engine
CREATE TABLE users (
        id INTEGER NOT NULL,
        email VARCHAR(255),
        PRIMARY KEY (id)
)

2014-01-03 17:28:48,230 INFO sqlalchemy.engine.base.Engine ()
2014-01-03 17:28:48,230 INFO sqlalchemy.engine.base.Engine COMMIT
2014-01-03 17:28:48,230 INFO sqlalchemy.engine.base.Engine CREATE INDEX ix_users_email ON users (email)
2014-01-03 17:28:48,230 INFO sqlalchemy.engine.base.Engine ()
2014-01-03 17:28:48,231 INFO sqlalchemy.engine.base.Engine COMMIT

Note that the CREATE TABLE statement does not show the index being created, but it IS being created in a follow-up statement slightly after.


text:
Q: MVC Custom Attribute - Client-side Validation - Warning: No message defined for 'field' I tried to create a custom data annotation validation attribute (NameValidationAttribute) in MVC 5 project using VS2013. I was able to successfully add the client side validation and the error message for custom validation is getting displayed as soon as the focus leaves the textbox. However, the standard attributes like [Required] and [Range] validators are now not showing proper error messages, says 'Warning: No message defined for 'field' ' (See below screenshot).
Question:
- Why the standard validation error messages are showing as "Warning: No message defined for UnitsInStock"? What am I missing?

Below is my custom client validation script:

I included following scripts in EditProducts page.

Please note that the error messages for UnitPrice, UnitsInStock and ReorderLevel fields are defined with Range validation attribute (see below).

FYI, I tried to change the order of the scripts in ProductEdit page but still its showing the same message.
Please advise!

A: I ran into this issue. I had created an MVC attribute called PasswordAttribute, with a client side validator called 'password'.
$.validator.addMethod('password', function (value, element, params) {
    ...[validation logic]
});

$.validator.unobtrusive.adapters.addBool('password');

As soon as I added this logic to the solution I got the error you saw on my Password and ConfirmPassword fields. Note that this occurred before the attribute was even used. Simply renaming the client side validator to 'passwordcheck' fixed the issue. I initially thought that the name 'password' possibly clashed with one of the pre-defined validators (cf. jQuery Validation Documentation) but this doesn't appear to be the case. I suspect now that it is a clash with the name or value for some input field attribute. Anyway, the solution was simply to rename the validator.

A: jQuery unobtrusive need data-msg for default validate message.
This is how to apply dynamic error message from your model to Html
  $.validator.unobtrusive.adapters.add("requireif", function (options) {
        $('#' + options.element.id).attr("data-msg", options.message);
        // Add rule ...
    });

You can change default warning message.
 $.validator.addMethod("requireif", function (value, element, pair) {
        // validate logic
        return true/false;
 }, "YOUR DEFAULT MESSAGE HERE");

Or
  @Html.TextBoxFor(m => m.Property1, new { Class = "form-control", data_msg = "YOUR DEFAULT MESSAGE HERE" })

Or if you can put it directly to your Html like this.
<input class="form-control" data-msg="YOUR DEFAULT MESSAGE HERE"/>


text:
Q: Hibernating a machine from within I have a script running on an EC2 instance that may choose to hibernate.
If I was going for stop, I could just sudo poweroff. But I'm not sure how hibernation is done internally.
I'm considering the following approach

*

*set up aws on the instance following https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-metadata.html

*get instance id from metadata

*aws ec2 stop-instances --instance-ids $OWN_INSTANCE_ID --hibernate
Is there a better way?

A: I couldn't really get hibernation to work, but some steps in that direction:
sudo systemctl start hibagent
sudo systemctl hibernate

A: At least for the Ubuntu 20.04 AMI, hibernation is triggered by the acpid service, which effectively runs the following command:
sudo /etc/acpi/actions/sleep.sh button/sleep SBTN 00000080 00000000

If you examine the script, all that really matters is that the second argument is SBTN. (Thus you can substitute the command with sleep.sh x SBTN.) The script first enables the extra swap created by the hibinit-agent service in the file /swap-hibinit and then runs systemctl hibernate.
Note: for reference, I also see the following ACPI event (viewable with acpi_listen):
button/sleep LNXSLPBN:00 00000080 00000003


text:
Q: Show all errors after click submit How can I show all errors when a user clicks on submit. As example I have this piece of code:
if(strlen($username) < 5){ echo "Show error message"; }
if($password != $passwordRetype){ echo "Show error message"; }
if(strlen($password) < 8){ echo "Show error message"; }

How can I show all error message in a time? Now it shows, first error, if this is fixed the second one and after the second one the thirth. Is there a way to do this?

A: You can use a list/array to keep track of all errors that occur, then present them back to the user like so, in this very simple demonstration.
$errors = []; // Array creation
if (strlen($username) < 5) {
    // Add this error to our list
    $errors[] = 'Username not valid.';
}

if ($password != $passwordRetype) {
    // Add this error to our list
    $errors[] = 'Password does not match our records.';
}

// Repeat this process for other errors
// Then handle your list of errors
foreach ($errors as $error) {
    echo "Error Found: $error
";
}

A: Do something as
$error = false ;
$msg = '';
if(strlen($username) < 5){ $msg .= "Show error message
"; $error = true ;}
if($password != $passwordRetype)){ $msg .= "Show error message
"; $error = true ;}
if(strlen($password) < 8){ $msg .="Show error message
"; $error = true ;}

if($error === true){
 echo $msg ;
}

A: UPDATED to show <form> tags and using jQuery to submit form.
Really, you should be doing this field testing in javascript/jQuery rather than in PHP.  By the time it gets to the PHP side, if something fails validation and you need to go back, the screen will refresh and you either have to store/replace the values or else already-inputted field values will be lost.
With javascript/jQuery you can stop the validation prior to the redirection and preserve field values and save yourself a bit of work.
Here's a simple example:
jsFiddle Working Example
HTML:
<form id="myForm" action="some_file.php" method="post">
One: <input type="text" id="f1">

Two: <input type="text" id="f2">

Three: <input type="text" id="f3">

Four: <input type="text" id="f4">

</form>

<input type="button" id="mybutt" value="Go" />

javascript/jQuery

Notes:

*

*It is not necessary to use a button with type="submit". Using jQuery to submit the form works perfectly well.

*If form fails validation, use return false; to stop processing at that point and return control to the user.

*If form passes validation, use $('#formID').submit(); to submit the form

*Ensure your action= and method= attributes (form tag) are correct.
ALSO Note that the above example uses jQuery. Make sure to include the jQuery library in your document, usually between the head tags, thus:

A: Personally, what I always do for showing errors to users is basically this:
$email = $_POST['email'];
$address = $_POST['address'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
 $_SESSION['errors'][] = 'Email was invalid';
}
if($address == '') {
 $_SESSION['errors'][] = 'Address was invalid';
}

if(isset($_SESSION['errors'])) {
 header("Location: " . $_SERVER['PHP_SELF']);
 exit();
} else {
 //everything okay, do other stuff like send mail or save to database
}

Then, on the page itself, I use a list:
if(isset($_SESSION['errors'])) {
 echo '
';
 foreach($_SESSION['errors'] as $err) {
  echo '
' . $err . '
';
 }
 echo '
';
 unset($_SESSION['errors']); //show them just once
}

That way users will not be able to re-post data already submitted by hitting F5 and they will not get an ugly url like ?post=success.


text:
Q: Chebyshev Inequality I am reading a research paper, and the author claims to get to a desired result by making use of the Chebyshev Inequality. I can get to the desired result also with some reasoning, but I fail to understand how to use the Chebyshev Inequality to get to it.
Let $\{c_i\}_{i=1}^{i=M}$ be elements of $\mathbb{R^n}$, such that they satisfy the constraint  $\frac{1}{M}\sum_{i=1}^{i=M}||c_i||^2\leq nP$ where $P,\tilde{P}\in \mathbb{R^+},\ P<\tilde{P}$.
Given such a set $\{c_i\}_{i=1}^{i=M}$ that satisfies the constraint, I would like to count the number of elements $i$ such that $||c_i||^2 > n\tilde P$. To put it concisely I want to know #$\{i:||c_i||^2 > n\tilde P\}$. Simple reasoning shows that #$\{i:||c_i||^2> n\tilde P\}\leq M\frac{P}{\tilde P}$.
Please share the insight to get to the result with the Chebyshev Inequality.
My reasoning works like this: Imagine the above is not true, and then I count the number of elements with $||c_i||^2 > n \tilde P$ and the elements that $\leq n\tilde P$ and arrive at the contradiction to the above constraint.

A: The reasoning is quite simple: now that I think about it.
Recall Chebyshev Inequality (or simply Markov Inequality):
$\boldsymbol{P}(\{\omega:X(\omega)\geq\epsilon\})\leq\frac{\boldsymbol E(X)}{\epsilon}$
Let $X=||Y||^2$ so $X$ is also a RV and $X\geq0$ as needed. Let $Y\in \{c_i\}_{i=1}^{i=M}$ with uniform probability. So $\boldsymbol E(X)\leq nP$.
Now the $\boldsymbol{P}(\{\omega:X(\omega)\geq n\tilde P\})\leq\frac{\boldsymbol E(X)}{n \tilde P}$ and this is also implies from above that $\boldsymbol{P}(\{\omega:X(\omega)\geq n\tilde P\})\leq\frac{P}{\tilde P}$
But we can also interpret $\boldsymbol{P}(\{\omega:X(\omega)\geq n\tilde P\})=\frac{\#\{i:||c_i||^2>n\tilde P\}}{M}$, and thus we get $\#\{i:||c_i||^2>n\tilde P\} \leq M \frac{P}{\tilde P}$, as needed.


text:
Q: error installing xmms on ubuntu 12.04 I want to install XMMS media player on UBUNTU 12.04. I'm following instructions, but when type ./configure I receive message bellow:
* The glib-config script installed by GLIB could not be found
 If GLIB was installed in PREFIX, make sure PREFIX/bin is in
 your path, or set the GLIB_CONFIG environment variable to the
 full path to glib-config.
configure: error:  GLIB >= 1.2.2 not installed - please install first *
I installed libglib2.0-dev, but still continue to receive this message.
What have to do and where to find this glib-configv script ?

A: XMMS requires glib version 1.2 series libraries (2.0 series will not work). You can get sufficiently new version of that from levien's PPA:
sudo apt-add-repository ppa:levien/thbio
sudo apt-get update
sudo apt-get install libglib1.2-dev libgtk1.2-dev

But even then you'll likely run into problems with undefined references in libgdk 1.2.


text:
Q: merging TEX file form my gitlab in a live connectivity I have multiply tex files in different libraries within my gitlab account
I am trying to create one tex file which will "pull" other tex files upon creation. the other tex files are located like this:
(example:https://gitlab.com/XXX/-/blob/master/Documents/XXXXXX/maximum.tex)
How can I merger few tex files like this so the merged tex file will be updated with the other updated tex files?
I checked here and here but couldn't find how to make it "live" connection.
pls advice,


text:
Q: No scilab gui (Ubuntu 12.04) I installed scilab in Ubuntu 12.04.  When I start in terminal or from KDE application menu, I only get a scilab console.  Why don't I get the gui?

A: try install it,
apt-get install scilab

scilab-cli is just the console in a terminal.

A: It was some kind of X or QT problem.  I'm using XFCE, but it works in KDE.


text:
Q: Call to undefined method Tests\Unit\TopPageTest::get() in Unit test in Laravel 8 I am writing a code to make Unit test for each pages in my project and started with the Main page. The main page consists of shop lists, genre lists and area lists.
tests\Unit\ToppageTest.php :
<?php

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;
// use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Models\Shop;

class TopPageTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testIndex()
    {
        $response = $this->get('/');
        $this->assertContains('data', $response->content());
        $response->assertSuccessful();
    }
}

phpunit.xml:
 <php>
        <server name="APP_ENV" value="testing"/>
        <server name="BCRYPT_ROUNDS" value="4"/>
        <server name="CACHE_DRIVER" value="array"/>
        <server name="MAIL_DRIVER" value="array"/>
        <server name="DB_CONNECTION" value="sqlite"/>
        <server name="DB_DATABASE" value=":memory:"/>
        <server name="MAIL_MAILER" value="array"/>
        <server name="QUEUE_CONNECTION" value="sync"/>
        <server name="SESSION_DRIVER" value="array"/>
        <server name="TELESCOPE_ENABLED" value="false"/>
    </php>

App\Http\Controllers\TopController.php:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\ToppageService;

class TopController extends Controller
{
    private $shop;

    public function __construct(ToppageService $shop)
    {
        $this->shop = $shop;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = $this->shop->getAllServicer();
         return view('index', compact('data'));

    }

}

App\Http\Services\ToppageService.php:
<?php

namespace App\Services;

use App\Services\BaseService;
use App\Models\Shop;
use App\Models\Genre;
use App\Models\Area;

class ToppageService extends BaseService
{
    protected $shop, $genre, $area;

    public function __construct(Shop $shop, Genre $genre, Area $area)
    {
        $this->shop = $shop;
        $this->genre = $genre;
        $this->area = $area;
    }

    public function getAllServicer()
    {
        $data = [] ;
        $data['shoplist'] = $this->shop->with('attribute','content','coupon','menu_categoly','area','genre')->whereHas('servicer',function($query){$query->where('name', config('const.system.setting.servicer'));})->orderBy('created_at', 'DESC')->get();
        $data['genrelist'] = $this->genre->get();
        $data['arealist'] = $this->area->get();
        return $data;
    }
}

When I enter php artisan test or vendor/bin/phpunit in command prompt, I get an error like:
Call to undefined method Tests\Unit\TopPageTest::get()

  at E:\tulsi\wparijat\laravel\laravel-awapass\app.awapass.com\tests\Unit\ToppageTest.php:20
     16▕      */
     17▕     public function testIndex()
     18▕     {
     19▕         //not working
  ➜  20▕         $response = $this->get('/');
     21▕         $this->assertContains('data', $response->content());
     22▕         $response->assertSuccessful();
     23▕     }
     24▕ }

  1   E:\tulsi\wparijat\laravel\laravel-awapass\app.awapass.com\vendor\phpunit\phpunit\phpunit:76
      PHPUnit\TextUI\Command::main()

  Tests:  1 failed
  Time:   0.05s

when I add  use Tests\TestCase; instead of use PHPUnit\Framework\TestCase;
I get error:
Warning: TTY mode is not supported on Windows platform.

I searched for solution for could't get the exact solution for this. Can anyone please help me?

A: You seem to be mixing syntax between whatever Laravel's TestCase is doing with PHPUnit's TestCase.  If you're just using PHPUnit you probably need to do is something more like
public function testIndex()
{
    $mockService = $this->createMock(ToppageService::class);
    $controller = new TopController($mockService);

    $mockData = 'MOCK DATA';

    $mockService
        ->expects($this->once()
        ->method('getAllServicer')
        ->willReturn($mockData);

    $response = $controller->index();

    $this->assertContains('data', $response->content());
}

This is purely a Unit Test, not a Functional Test, so it's just mocking whatever the service is doing.  It's probably also not exactly what you need; I've no idea what view or compact are doing, and you probably need to mock up something more accurate in your data.

A: uncomment this line:
// use Tests\TestCase;

and comment this one:
use PHPUnit\Framework\TestCase;


text:
Q: React URL changes but component does not render If I go to "/" or "/details" with Reloading the page manually in browser everything renders fine.
If I go to "/" or "/details" with navbar links the URL changes but the content does not renders.
I tried using "exact" keyword at "/details" route , but it is the same .
React-router-dom: Version: 5.1
App.js:
import { BrowserRouter , Redirect, Route , Switch } from 'react-router-dom';
import './App.css';
import Navbar from './Navbar.js'
import Home from './pages/Home'
import Details from './pages/Details';

function App() {
  return (

      <BrowserRouter>
        <Navbar />
        <Switch>
          <Route exact path="/" >
            <Home />
          </Route>
          <Route path="/details" >

          </Route>
          <Route path="*">
            <Redirect to="/" />
          </Route>
        </Switch>
      </BrowserRouter>

  );
}

export default App;

Navbar:
import './Navbar.css'
import { NavLink , Link } from 'react-router-dom'
export default function Navbar() {

  return (

<Link to="/">Home</Link>

<Link to="/details">Details</Link>

Google

  )
}

A: Upgrade to React-router-dom: Version: 5.3.3 because  Version: 5.1 has bug.
1.Uninstall whatever version you are having
npm uninstall -s react-router-dom@5.1
npm uninstall -s react-router-dom
2.Install React-router-dom: Version: 5.3.3
npm install -s react-router-dom@5.3.3
Or go to this post: Click Me to go to Post

A: Try using Routes instead of switch.

*

*import Routes
import { BrowserRouter , Redirect, Route , Routes, Switch } from 'react-router-dom';

*Change the Switch to *Routes
        <Routes>
          <Route exact path="/" >
            <Home />
          </Route>
          <Route path="/details" >

          </Route>
          <Route path="*">
            <Redirect to="/" />
          </Route>
        </Routes>

I hope this helps


text:
Q: if $S_{m}=\frac{m}{n},S_{n}=\frac{n}{m}(n\neq m)$,then $S_{m+n}$ and $4$ which is bigger? let $\{a_{n}\}$ is  arithmetic sequence,and $S_{n}=a_{1}+a_{2}+\cdots+a_{n}$,and such
$$S_{m}=\dfrac{m}{n},S_{n}=\dfrac{n}{m}(n\neq m)$$
then
$S_{n+m}$ and $4$ which is bigger?
My try: With out loss of we let
$n\ge m$
$$S_{n+m}=S_{n}+a_{n+1}+a_{n+2}+\cdots+a_{n+m}$$
maybe this problem have nice methods,Thank you

A: $\{a_n\}$ is an arithmetic progression, so $S_n=\frac{n(a_1+a_n)}2=\frac nm$. So $m=\frac2{a_1+a_n}$. Since $m$ is an integer, it implies that $a_1+a_n=1$ or $a_1+a_n=2$. Similarly, $n=\frac2{a_1+a_m}$. So $a_1+a_m=1$ or $a_1+a_m=2$.
Since an arithmetic sequence is monotonous and $n\neq m$, we have $a_n\neq a_m$. So WLOG $a_1+a_n=1$, $a_1+a_m=2$. Then $m=2$ and $n=1$.
Now we can see that $a_1=\frac12$, $a_2=\frac32$. So $d=a_2-a_1=1$ and $a_3=\frac52$. Then
$$S_{m+n}=S_3=\frac{3(\frac12+\frac52)}{2}=\frac92>4$$

A: Note this
$$S_{m+n}=\dfrac{(S_{m}-S_{n})(m+n)}{m-n}$$
then
$$S_{m+n}=\dfrac{(m+n)^2}{mn}>4$$
since $m\neq n$

A: If the sequence is given by $a_k=a+kd$ then you should know that $S_n = na+\frac{n(n+1)}{2}d$. So you have the two lienar equations
$$ ma+\frac{m(m+1)}{2}d=\frac mn,\qquad na+\frac{n(n+1)}{2}d=\frac nm$$
which yoiu can solve for $a$ and $d$ (because $m\ne n$) and hence can eliminate $a,d$ from
$S_{m+n}=a+\frac{(m+n)(m+n+1)}2d$. Once you have that expression, it should nto be difficult to show that it is or is not greater than $4$.


text:
Q: ¿Cómo puedo capturar un índice con JavaScript en una vista de listado en RoR? Tengo la siguiente vista index.slim con código JS.
- ind = 0
- enlace = []
h1 Posts
table
    thead
        tr
            th Content
    tbody
        - @posts.each_with_index do |post,i|
            - ind = i
            - enlace[i] = "https://midominio.com/#{i}"
            tr
                td= post.content
                td
                    a.mx-1.btn.btn-sm.btn-outline-warning href="javascript:copiaURL();" Copiar URL
                td= i

javascript:
    function copiaURL() {
        var aux = document.createElement("input");
        aux.setAttribute("value","#{enlace[ind]}");
        document.body.appendChild(aux);
        aux.select();
        document.execCommand("copy");
        document.body.removeChild(aux);
        alert("URL copiada\n#{enlace[ind]}");
    }

Tengo un dominio de un cliente con ciertos parámetros, para efectos de la pregunta resumo los parametros con el índice del helper each_with_index, el problema que tengo es que me trae el último valor del arreglo y no me trae la selección que hice, adjunto una imagen que representa el problema que tengo.

Selecciono el índice 4 (puede ser cualquier de la lista) y siempre me trae el último.
¿Cómo puedo hacer para que me seleccione el índice que quiero?

A: El problema es que estás mezclando variables de tu template slim con javascript, que son evaluadas en distintos momentos.
En otras palabras, estás iterando en @posts.each_with_index donde cada ciclo le asigna un valor distinto a a tu variable ind siendo 15 el último valor asignado. Luego FUERA del bloque de iteración, estás asignando enlace[ind], o sea, enlace[15] a tu js. De hecho, si vas a revisar tu código fuente en el explorador, verás que siempre va a imprimir lo mismo, porque en el js resultante ya fue evaluado como:
alert("URL copiada\nhttps://midominio.com/15");

Una posible solución, sería algo como:
a.mx-1.btn.btn-sm.btn-outline-warning href="#" onclick="copiaURL('#{enlace[i]}')" Copiar URL

Lo que te generaría links del tipo onclick="copiaURL('https://midominio.com/1')".
Luego, en la función recibir el parámetro como:
function copiaURL(url) {
    var aux = document.createElement("input");
    aux.setAttribute("value",url);
    document.body.appendChild(aux);
    aux.select();
    document.execCommand("copy");
    document.body.removeChild(aux);
    alert(`URL copiada\n${url}`);
}


text:
Q: Setting contentInset on UITableView after coming back from different thread How can  I set the content inset on a UITableView after coming back from a separate thread?
Here is some code to get the gist of what I am doing, feel free to provide suggestions outside of the scope of this question as well.
My main goal is to collapse the area that the webview would go into (the area above the table created by the contentInset) if there is no ad available.
//In View did Load
[NSThread detachNewThreadSelector:@selector(getBannerAdContent) toTarget:self withObject:nil];

-(void)getBannerAdContent
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSString *html = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://192.168.0.18:83/PhotoGalleryService.svc/LoadBannerAd/"]];
    [self performSelectorOnMainThread:@selector(loadBannerAd:) withObject:html waitUntilDone:NO];
    [pool release];
}

-(void)loadBannerAd:(NSString*)html
{
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 2, 300, 40)];

    [webView loadHTMLString:html baseURL:nil];
    webView.delegate = self;
    webView.scalesPageToFit = NO;
    webView.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin);
    [self.view addSubview:webView];
    [webView release];
    UITableView *myTableView = (UITableView*)[self.view.subviews objectAtIndex:0 ];
    //The following line is doing nothing.
    myTableView.contentInset = UIEdgeInsetsMake(44,0.0,0,0.0);
}

Any help you can give me would be much appreciated.
EDIT:
A little more thorough of an explanation...
In my view did load I spark off a separate thread.  This thread loads the html from a service i set up, and then sets that on the webview.  However, as I'm stepping through, before it gets to the line
myTableView.contentInset = UIEdgeInsetsMake(44,0.0,0,0.0);

The table view is already loaded, and then the above line has no effect.
Cheers,

A: contentInset sets the inset size, but doesn't scroll your tableview to display it.  After setting the contentInset, set the contentOffset if you want it to scroll up to show the top of the table view.
myTableView.contentOffset = CGPointZero;

A: For Swift5 and UITableView
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if shouldAddContentInset {
        tableView.contentInset = UIEdgeInsets(top: 100, left: 0, bottom: 0, right: 0)
        tableView.contentOffset = CGPoint(x: 0, y: -tableView.contentInset.top)
    }
}

And then from some callback function or delegate:
func gotResponseFromSomewhere() {
    shouldAddContentInset = true
    viewDidLayoutSubviews()
}


text:
Q: Finding the smallest centrally symmetric region that contains a convex planar region
*

*Given a convex polygonal region C, how does one find/characterize the smallest zonogon (centrally symmetric convex polygon https://en.wikipedia.org/wiki/Zonogon) that contains C?

Note 1: In question 1, smallest could mean least area or least perimeter. So, one can also ask which C maximizes the difference between its least area and least perimeter convex centrally symmetric container.

*Given a convex planar region C, how does one find/characterize the largest zonogon contained within C?

Guess: At least the largest area internal zonogon of C seems to have its center on the medial axis of C. Not sure about the least perimeter one - this zonogon could degenerate into a zero area one in some cases.
Note 2: Analogous questions can be asked about axisymmetric containers - and containees - of C.
Note 3: Some similar questions are recorded at Curves of constant width that contain triangles, Smallest triangles that contain 2D convex regions with reflection symmetry and linked pages.

A: Question 1, in the minimum-area setting, has been studied by Guibas, Nguyen and Zhang (SODA 2003). They prove the following algorithmic result:

Theorem 4.5 The minimum area zonotope containing a set of $n$ points in $\mathbb{R}^2$ can be computed in $O(n \log^2 n)$ [time].

If you set the center of the zonotope at $O$, then the zonotope must contain the original vertices (of your convex polygon) and their reflections (with respect to $O$), and the minimum-area solution is the convex hull of those two point sets. So you can define a function $f$ that maps $O$ to the minimum area. They prove that this area function is unimodal and piecewise affine, and they design an efficient algorithm that finds its minimum.
Guibas, Leonidas J.; Nguyen, An; Zhang, Li, Zonotopes as bounding volumes, Proceedings of the fourteenth annual ACM-SIAM symposium on discrete algorithms, Baltimore, MD, USA, January 12–14, 2003. New York, NY: Association for Computing Machinery; Philadelphia, PA: Society for Industrial and Applied Mathematics (ISBN 0-89871-538-5/pbk). 803-812 (2003). ZBL1092.68697.
(A freely available version of their paper is in ResearchGate.)
Here is an illustration by myself of a minimum-area zonogon around a triangle. The contours illustrate zonogon area as a function of the centerpoint $O$. Observe that the function is indeed piecewise affine (as proven by Guibas et al.), and that somewhere inside the input triangle, there is a nonzero-size region (dark blue) where the area function attains its minimum, so $O$ can be chosen freely from that area (here: randomly).


text:
Q: How xpath works for tags in tags I am trying to find out the xpath for first name of the facebook page and I have ended it with the following xpath: "**//div[1]/div[1]/div[1]/div[1]/input[@class='inputtext _58mg _5dba _2ph-']**" which is correct. My question is that, there are total 9 div tags on the page but I got it with the fourth div, I am not getting the reason how it's finding it in fourth div?
Page is Facebook home Page and element to find with xpath is Fist name input box
Please help me to understand how it's finding the element using above xpath
I know there are other ways to find xpath but I want to know the reason how it's finding it
I hope I am providing the complete information for the asked question if not let me know

A: Well it's because your xpath starts with a //. In literal english, it says find a DIV whose child is a DIV whose child is a DIV whose child is a DIV whose child is your INPUT. In your case, it does find a DIV which has INPUT as described by your xpath.
If you replace that // to single /, it will find the first DIV and then will try finding your input. Which it won't be able to find since .. like you said there are 9 DIVs.
Hope that paints a picture. Let me know if you need more explanation.


text:
Q: Can iOS apps be removed from iTunes Music Folder after upgrading to iTunes 12.7?
Now that iTunes no longer syncs apps to iOS devices, can apps be removed from the folder that iTunes stored them in? (~/Music/iTunes/iTunes Music/Mobile Applications in my case)
I have updated iTunes, and was surprised to see that the applications were not deleted.

A: The short answer is: YES you can delete the folder.
The longer answer is: It depends on which apps you have. If you have some apps that you no longer can download from the App Store, you still need them as a backup, so that you can drop them onto your device when/if needed. So you can delete the apps that you know you still can update/download from the App Store.
And when you decide if you still need the old app, you should also see at the app's spec. - is it a 32-bit or a 64-bit app ?? only 64-bit will work with iOS 11

A: Yes, the .ipa files can be safely removed/deleted, since iTunes 12.7 will no longer use them.
However, if an app is no longer available for download again, you can restore via the old .ipa file, per this TechCrunch article (includes Apple support links):

People who have been syncing apps through iTunes need to redownload
  them onto their devices. Previously downloaded iOS apps, ringtones
  and books for PC can be found in the iTunes Media folder, but if
  something is no longer available to download again, it can still be
  transferred from computer to iOS devices with a USB cable.

Also this Apple support page notes:

If you have an iOS app, ringtone, or book that's no longer available
  for redownload, you can move that content to your iOS device while
  plugged in to a computer with a USB cable.


text:
Q: Show / Hide entire HTML pages clicking on menu links - pure JS Kindly ask for your advice making working a javascript navigation bar.
It should be supposed to:

*

*open a page preview clicking on the link (I think to have achieve that, even though with a too long code block);

*open the selected page with the second click (the first is just for the preview -- i tried with a container.classList.toggle("active"); inside each element.onclick function but didn't work)

*give you the chance to open the page clicking directly on the preview (I don't have a clue how to do so)

const hamburger_menu = document.querySelector(".hamburger-menu");
const container = document.querySelector(".container");

hamburger_menu.addEventListener("click", () => {
  container.classList.toggle("active");

  document.getElementById("home-btn").onclick = function() {
    document.getElementById("home").style.display = "block";
    document.getElementById("services").style.display = "none";
    document.getElementById("portfolio").style.display = "none";
    document.getElementById("about").style.display = "none";
    document.getElementById("contact").style.display = "none";
  };

  document.getElementById("services-btn").onclick = function() {
    document.getElementById("services").style.display = "block";
    document.getElementById("home").style.display = "none";
    document.getElementById("portfolio").style.display = "none";
    document.getElementById("about").style.display = "none";
    document.getElementById("contact").style.display = "none";
  };

  document.getElementById("portfolio-btn").onclick = function() {
    document.getElementById("portfolio").style.display = "block";
    document.getElementById("home").style.display = "none";
    document.getElementById("services").style.display = "none";
    document.getElementById("about").style.display = "none";
    document.getElementById("contact").style.display = "none";
  };

  document.getElementById("about-btn").onclick = function() {
    document.getElementById("about").style.display = "block";
    document.getElementById("home").style.display = "none";
    document.getElementById("services").style.display = "none";
    document.getElementById("portfolio").style.display = "none";
    document.getElementById("contact").style.display = "none";
  };

  document.getElementById("contact-btn").onclick = function() {
    document.getElementById("contact").style.display = "block";
    document.getElementById("home").style.display = "none";
    document.getElementById("services").style.display = "none";
    document.getElementById("portfolio").style.display = "none";
    document.getElementById("about").style.display = "none";
  };

});
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.container {
  min-height: 100vh;
  width: 100%;
  background-color: #485461;
  background-image: linear-gradient(135deg, #485461 0%, #28313b 74%);
  overflow-x: hidden;
  transform-style: preserve-3d;
}

.navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 100;
  height: 5rem;
}

.menu {
  max-width: 72rem;
  height: inherit;
  width: 100%;
  margin: 0 auto;
  padding: 0 2rem;
  display: flex;
  align-items: center;
  color: #fff;
}

.logo {
  font-size: 1.1rem;
  font-weight: 600;
  letter-spacing: 2px;
  line-height: 4rem;
}

.logo span {
  font-weight: 300;
}

.hamburger-menu {
  height: 4rem;
  width: 3rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-left: auto;
}

.bar {
  width: 1.9rem;
  height: 1.5px;
  border-radius: 2px;
  background-color: #eee;
  transition: 0.5s;
  position: relative;
}

.bar::before,
.bar::after {
  content: "";
  position: absolute;
  width: inherit;
  height: inherit;
  background-color: #eee;
  transition: 0.5s;
}

.bar::before {
  transform: translateY(-9px);
}

.bar::after {
  transform: translateY(9px);
}

.main {
  position: relative;
  width: 100%;
  left: 0;
  z-index: 5;
  overflow: hidden;
  transform-origin: left;
  transform-style: preserve-3d;
  transition: 0.5s;
}

header {
  min-height: 100vh;
  width: 100%;
  background: url("../milky_way.jpg") no-repeat top center / cover;
  position: relative;
}

.overlay {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: rgba(43, 51, 59, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
}

.inner {
  max-width: 50rem;
  text-align: center;
  color: #fff;
  padding: 0 2rem;
}

.title {
  font-size: 2.72rem;
  margin-bottom: 1.25rem
}

.description {
  font-family: "Open Sans";
  margin-bottom: 3rem;
}

.btn {
  font-size: 0.75rem;
  margin: 1rem;
  padding: 0.6rem 1.2rem;
  background-color: #1179e7;
  border: 2px solid #1179e7;
  border-radius: 25px;
  color: #fff;
  background-color: transparent;
  text-transform: uppercase;
  cursor: pointer;
  text-decoration: none;
}

.btn:hover {
  animation: pulse 1s;
  box-shadow: 0 0 0 2em transparent;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 #1179e7;
  }
}

.container.active .bar {
  transform: rotate(360deg);
  background-color: transparent;
}

.container.active .bar::before {
  transform: translateY(0) rotate(45deg);
}

.container.active .bar::after {
  transform: translateY(0) rotate(-45deg);
}

.container.active .main {
  animation: main-animation 0.5 ease;
  cursor: pointer;
  transform: perspective(1300px) rotateY(20deg) translateZ(310px) scale(0.5);
}

@keyframes main-animation {
  from{
    transform: translate(0);
  }

  to{
    transform: perspective(1300px) rotateY(20deg) translateZ(310px) scale(0.5);
  }
}

.links {
  position: absolute;
  width: 30%;
  right: 0;
  top: 0;
  height: 100vh;
  z-index: 2;
  display: flex;
  justify-content: center;
  align-items: center;
}

ul {
  list-style: none;
}

.links a {
  text-decoration: none;
  color: #bbb;
  padding: 0.7rem 0;
  display: inline-block;
  font-size: 1rem;
  font-weight: 300;
  text-transform: uppercase;
  letter-spacing: 1px;
  transition: 0.3s;
  opacity: 0;
  transform: translateY(10px);
  animation: hide 0.5s forwards ease;
}

.links a:hover {
  color: #fff;
}

.container.active .links a {
  animation: appear 0.5s forwards ease var(--i);
}

@keyframes appear {
  from{
    opacity: 0;
    transform: translateY(10px);
  }

  to{
    opacity: 1;
    transform: translateY(0px);
  }
}

@keyframes hide {
  from{
    opacity: 1;
    transform: translateY(0px);
  }

  to{
    opacity: 0;
    transform: translateY(10px);
  }
}

.shadow {
  position: absolute;
  width: 100%;
  height: 100vh;
  top: 0;
  left: 0;
  transform-style: preserve-3d;
  transform-origin: left;
  transition: 0.5s;
  background-color: white;
}

.shadow.one {
  z-index: -1;
  opacity: 0.15;
}

.shadow.two {
  z-index: -2;
  opacity: 0.1;
}

.container.active .shadow.one {
  animation: shadow-one 0.6s ease-out;
  transform: perspective(1300px) rotateY(20deg) translateZ(215px) scale(0.5);
}

@keyframes shadow-one {
  0%{
    transform: translate(0);
  }

  5%{
    transform: perspective(1300px) rotateY(20deg) translateZ(310px) scale(0.5);
  }

  100%{
    transform: perspective(1300px) rotateY(20deg) translateZ(215px) scale(0.5);
  }
}

.container.active .shadow.two {
  animation: shadow-two 0.6s ease-out;
  transform: perspective(1300px) rotateY(20deg) translateZ(120px) scale(0.5);
}

@keyframes shadow-two {
  0%{
    transform: translate(0);
  }

  5%{
    transform: perspective(1300px) rotateY(20deg) translateZ(310px) scale(0.5);
  }

  100%{
    transform: perspective(1300px) rotateY(20deg) translateZ(120px) scale(0.5);
  }
}

.container.active .main:hover + .shadow.one {
  transform: perspective(1300px) rotateY(20deg) translateZ(230px) scale(0.5);
}

.container.active .main:hover {
  transform: perspective(1300px) rotateY(20deg) translateZ(340px) scale(0.5);
}

#services,
#portfolio,
#about,
#contact {
  display: none;
}

home

services

portfolio

about

contact

            Home

            Services

            Portfolio

            About

            Contact


text:
Q: Python Selenium get text out of a class Hey I want to have the text which is in this class and print it in the console.
How can I do this?
I have tried:
profileName = driver.find_element_by_class_name("._7UhW9.fKFbl.yUEEX.KV-D4.fDxYl").text()
print(profileName)

I would be very happy if you could help me.
Tom Rudolph

A: In case that element has all these class names you just have to change from find_element_by_class_name to find_element_by_css_selector, as following:
profileName = driver.find_element_by_css_selector("._7UhW9.fKFbl.yUEEX.KV-D4.fDxYl").text()
print(profileName)

However I'm quite sure these class names are dynamically changing so this will not work.
Also, make sure you added some delay / wait before accessing the element.

A: maybe try this
is from the BeautifulSoup library
from the beginning:
import requests
from bs4 import BeautifulSoup

url = 'my_site'
r = request.get (url)
re1 = BeautifulSoup (r.text, "lxml")
re2 = re1.body.find_all ('div', {'class': '._7UhW9.fKFbl.yUEEX.KV-D4.fDxYl'})
for syntax in re2 [:]:
     print (syntax)

where there is div you can put another tag where this class is (a, p, h)
where there is div you can put another tag where this class is (a, p, h)
and in selenium, instead of 'element' use 'elements', when harvesting it is better to collect everything: D
But when you want to click an element or type something (send_keys () or click ()) you have to use a single number of characters, which is 'element' and not 'elements'
I do this for seleneium webdriver
data1 = driver.find_elements_by_class_name('class')
data2 = driver.find_elements_by_css_selector('css_selector")

if len(data1) >  0:
  do something
if len(data2) > 0:
 do something

you can always add an else if you want to see how the error pops up, print (len (data1)) or data2 to see how much data you have collected etc.

A: it not text() in python,  it is .text
also this ._7UhW9.fKFbl.yUEEX.KV-D4.fDxYl looks dynamic and a css_selector not class_name.
Code 1 :
profileName = driver.find_element_by_css_selector("._7UhW9.fKFbl.yUEEX.KV-D4.fDxYl").text
print(profileName)

Code 2 :
profileName = driver.find_element_by_css_selector("._7UhW9.fKFbl.yUEEX.KV-D4.fDxYl").get_attribute('innerHTML')
print(profileName)


text:
Q: $H_\infty$ norm of a transfer function by Matlab Consider the simplest case:
   $$H(z) = \frac{z+1}{z+2}$$
I use two methods to find $H_\infty$-norm:
H = tf([1 1],[1 2],.001);

[ninf,fpeak] = norm(H,inf)
ninf =

0.6667
fpeak =

0
[ninf1,fpeak1] = hinfnorm(H)
ninf1 =

Inf

It seems odd, the answers are different.
What did I miss?

A: If the system is unstable, the $H_\infty$ norm is infinite. You have a discrete time system with a pole greater than 1 in absolute value hence the answer inf. First one doesn't check for stability and converts it to state space system.
The discrepancy is due to the fact that norm() command only checks for $L_\infty$ not necessarily $H_\infty$ (for stable real-rational systems these coincide). That should be emphasized more in the documentation in my opinion.
For example, 2-norm is correctly caught.
>> [ninf,fpeak] = norm(H)
Warning: The H2 norm is infinite because the system is unstable.
> In ctrlMsgUtils.warning (line 25)
  In ltipack.ssdata/normh2 (line 70)
  In ltipack.ltidata/normh2 (line 85)
  In ltipack.SystemArray/normh2_ (line 7)
  In DynamicSystem/norm (line 40)

ninf =

   Inf

fpeak =

     []

This is even worse because now it reassures that the command is checking Hardy spaces. Matlab being matlab again.