text:
Q: How do you make these buttons appear side by side rather than stacked? I've tried inline and inline-block, but it's not working.
I've also tried setting a width and height for buttonsDiv in case not having one is somehow causing it to mess up.
I'm a little confused here, what is the way to get these buttons side by side rather than on top of each other?
https://codepen.io/hiarooo/pen/vYxYdOj
HTML

Button 1

Button 2

CSS
/*FancyButtonStuff*/
.buttonsDiv{

}

.buttonContainer{
    margin-top:100px;
    text-align:center;
}

h4{
    color:rgba(69, 69, 69, 1);
    /*line-height:2em;*/
}

/* BUTTON CSS
------------------------------------------- */

a.fancyButton{
  display:inline-block;

    /*font:normal normal 300 1.3em 'Open Sans';*/
  font-size:0.8em;
    text-decoration:none;

    color:rgba(28, 190, 131, 1);
    background-color:transparent;
    border:1px solid rgba(28, 190, 131, 1);
    border-radius:100px;

    padding: .3em 1.2em;
    margin:5px;

    background-size: 200% 100%;
    background-image: linear-gradient(to right, transparent 50%, rgba(28, 190, 131, 1) 50%);
    transition: background-position .3s cubic-bezier(0.19, 1, 0.22, 1) .1s, color .5s ease 0s, background-color .5s ease;
}

a.fancyButton:hover{
    color:rgba(255, 255, 255, 1);
    background-color:rgba(28, 190, 131, 1);
    background-position: -100% 100%;
}

A: Add this style
.buttonsDiv{
  display: flex;
}

/*FancyButtonStuff*/
.buttonsDiv{
  display: flex;
}

.buttonContainer{
    margin-top:100px;
    text-align:center;
}

h4{
    color:rgba(69, 69, 69, 1);
    /*line-height:2em;*/
}

/* BUTTON CSS
------------------------------------------- */

a.fancyButton{
  display:inline-block;

    /*font:normal normal 300 1.3em 'Open Sans';*/
  font-size:0.8em;
    text-decoration:none;

    color:rgba(28, 190, 131, 1);
    background-color:transparent;
    border:1px solid rgba(28, 190, 131, 1);
    border-radius:100px;

    padding: .3em 1.2em;
    margin:5px;

    background-size: 200% 100%;
    background-image: linear-gradient(to right, transparent 50%, rgba(28, 190, 131, 1) 50%);
    transition: background-position .3s cubic-bezier(0.19, 1, 0.22, 1) .1s, color .5s ease 0s, background-color .5s ease;
}

a.fancyButton:hover{
    color:rgba(255, 255, 255, 1);
    background-color:rgba(28, 190, 131, 1);
    background-position: -100% 100%;
}

a.fancyButton2{
  display:inline-block;

    /*font:normal normal 300 1.3em 'Open Sans';*/
  font-size:0.8em;
    text-decoration:none;

    color:rgba(28, 190, 131, 1);
    background-color:transparent;
    border:1px solid rgba(28, 190, 131, 1);
    border-radius:100px;

    padding: .3em 1.2em;
    margin:5px;

    background-size: 200% 100%;
    background-image: linear-gradient(to right, transparent 50%, rgba(28, 190, 131, 1) 50%);
    transition: background-position .3s cubic-bezier(0.19, 1, 0.22, 1) .1s, color .5s ease 0s, background-color .5s ease;
}

a.fancyButton2:hover{
    color:rgba(255, 255, 255, 1);
    background-color:rgba(28, 190, 131, 1);
    background-position: -100% 100%;
}

Button 1

Button 2

A: One way is to add display: inline-block to the h4 element like this:
h4{
    color:rgba(69, 69, 69, 1);
    /*line-height:2em;*/
    display: inline-block;
}

See demo here: Demo

A: to make the buttons appear side-by-side, you will have to change the display properties of the parent element to flex.
.buttonsDiv{ display:flex; }
You can refer to this article on CSS-Tricks for more information on Flexbox

A: There are many ways to do that, but most people use this nowdays

*

*Using flexbox, more about flexbox here
    .buttonsDiv {
      display: flex;
      flex-direction: row;
      /* set the gap with this */
      gap: 10px;
    }

*Using Grid, more about grid here
.buttonsDiv {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 10px;
}

A: Add this in css file:
.buttonsDiv {
  display: flex;
}


text:
Q: Unable to handle square brackets (=[]) when parsing of URL to server I am calling the following URL from my iPhone app
NSString *resourcePath = [NSString stringWithFormat:@"/sm/search?limit=100&term=%@&types[]=users&types[]=questions", searchTerm];

However, when the server call is made, I found that the actual URL sent was this
/sm/search?term=mi&types%5B%5D=questions&limit=100

How can I resolve this so that the correct URL is sent to the server?

A: I assume that you use the NSURL method
initWithScheme:host:path:

to create the URL. According to the documentation, this method automatically escapes path with the stringByAddingPercentEscapesUsingEncoding: method.
The square brackets are escaped, because they are "unsafe" in the sense of RFC 1738 - Uniform Resource Locators (URL):

Characters can be unsafe for a number of reasons. [...] Other characters
  are unsafe because    gateways and other transport agents are known to
  sometimes modify    such characters. These characters are "{", "}",
  "|", "\", "^", "~",    "[", "]", and "`".
All unsafe characters must always be encoded within a URL.

If you create the URL with
NSString *s = [NSString stringWithFormat:@"http://server.domain.com/sm/search?limit=100&term=%@&types[]=users&types[]=questions", searchTerm];
NSURL *url = [[NSURL alloc] initWithString:s];

then no escape sequences are added, because initWithString expects the string to contain any necessary percent escape codes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Errors with defining global variable I'm getting errors while declaring a global variable. I defined a global variable inside a definition.
import os
import time as t
s = t.time()
import numpy as np
#print(os.getcwd())
#print(os.listdir(os.getcwd()))
chDir = os.chdir("/storage/emulated/0/OS-TEST-FOLDER")
print(chDir)
#print(dir(os))
file = open("Times.txt",'w')
tann = []

def tanns():
    while True:
        epochs = int(input("Enter how many epochs please >>> "))

        for i in range(epochs):
            aa = np.tan(i)
            print(f'Writing Tan{i} in Process')
            aaa = f'tan {i} degree = {aa}'
        #   t.sleep(0.01)
            tann.append(aaa)
        #with open(file) as f:
        file.write(str(tann))
        #print(file)

        f = t.time()
        dur = f - s
        print(f'Finished writing {epochs} tan')
        print(f"The Program Finished in {dur} seconds ")

        global choice = str(input("Do you want to continue running the Program >>> "))

        if choice == "n":
            break

if choice == 'y':
    tanns()

This was the error I got when I ran this code.
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 34
    global choice = str(input("Do you want to continue running the Program >>> "))
                  ^
SyntaxError: invalid syntax

[Program finished]

A: You must declare the global variable before assigning a value to it.
change global c = ... to
global c
c = ...


text:
Q: JScript in Microsoft Orchestrator I've tried to run JScript in system center orchestrator,  instead of powershell however I've run into some problems:
Here's little the code snippet:
var location = '{location from "InitializeData"}';

However when I run this script Im getting error,

"Object reference not set to an instance of an object."

Im getting this error when I'm trying to get value of the location through Published data.
Thank you for any help.

A: That should be var location = {location from "InitializeData"} (no quotes)
also, afair, you should return something from the powershell step, else it will fail.


text:
Q: Why won't my function work with parameters? I'm trying to make a typewriter effect for a web project, I tried making my own, which had parameters, and it didn't work for some reason. I found someone elses typewriter and tried to edit it to understand it better, but it didn't work with parameters.The original code used variables outside of the function that worked fine, but variables failed.
Ive tried editing the functions in small ways that shouldnt matter, but it all fails in the end.
//The Working Function
var i = 0;
var txt = "Old McDonald Had a farm";
var speed = 50;

function typeWriter() {
  if (i < txt.length) {
    document.getElementById("demo").innerHTML += txt.charAt(i);
    i++;
    setTimeout(typeWriter, speed);
  }
}
typeWriter();

// The edited function that failed
var i = 0;
var text = "Old McDonald Had a farm";
var spe = 50;

function typeWriter(txt, spe) {
  if (i < txt.length) {
    document.getElementById("demo").innerHTML += txt.charAt(i);
    i++;
    setTimeout(typeWriter, speed);
  }
}
typeWriter(text, spe);

The edited code only outputs the first character than stops, I want it to do all of them. My web text editor doesn't like jQuery so finding an actual error is complicated

A: I'll assume you meant to change the function signature to typewriter(txt, speed) which would fix the issue raised in my comment.
The second problem is that you do not pass any parameters to the function when you call it for a second time. This means that txt is undefined & txt.length results in an error.
The below could will allow you to pass the parameters to the function using setTimeout:
function typeWriter(txt, speed) {
    if (i < txt.length) {
        document.getElementById("demo").innerHTML += txt.charAt(i);
        i++;
        setTimeout(function() { typeWriter(txt, speed); }, speed);
    }
}

A: The second parameter is not correct, change function typeWriter(txt, spe) to function typeWriter(txt, speed).


text:
Q: .begin_search not a function I have typescript function. Here is code
 export class Step1{
  constructor(){
    this.begin_search();
    this.results_ready();

  }

  private begin_search():void {
    setTimeout(() => {
      Searchfield.show_searchfield()
    }, 100);

    $('.search_box_overlay').show()
    $('.search_box_overlay_top').show()
    if (gon.search['search_type'] == 'package')
      $('.search_box_overlay_top .package').show()
    else if (gon.search['search_type'] == 'hotel')
      $('.search_box_overlay_top .hotel').show()
    else
      $('.search_box_overlay_top .air').show()

    window.seach_status_task = setInterval(Itinerary.check_search_status, 2000)
    window.search_loading_itineraries = false
  }

And then I importing this code into pack
Like this
 $(document).ready(() => {
  Translation.addDict(gon.translations);
  Track.initialize();

  new Searchfield();
  if (!gon.search['searched']) {
    Step1.begin_search();

  }
  if (gon && gon.search['id'] && $('.offer_hotel_addon').length > 0) {
    check_status();
  }
});

But when I run project, I have this error.

WEBPACK_IMPORTED_MODULE_3__components_step1.a.begin_search is not a function

Where can be problem and how I need to fix it?

A: The code defines begin_search as an instance method (a part of an instance), but is trying to use them as if they were static (a part of the class itself). Mark the method as static so that it belongs to the Step1 class itself:
private static begin_search():void {

See the handbook for more info on static methods. I'd also remove the this.begin_search(); call from the constructor as well. When the method is static, it doesn't exist on this anymore.


text:
Q: Reading a variable number of columns in R I have a large tab-separated data file I am reading (in R) using:
read.delim(file, header = FALSE, sep = "\t", stringsAsFactors=FALSE)

Most of the lines have 6 columns, but some have extra columns with more text. For example:
1 2 3 4 5 ThisTextIsOkay
1 2 3 4 5 ThisTextContinues InTheNextColumn

I would like to merge the last N columns into the last string field for column 6. I don't mind preserving the tab character in the resulting string.


text:
Q: Programmatically sync dropbox without daemon running I would like to 'manually' force dropbox to sync at certain times (eg at regular, daily intervals using cron, as part of a larger backup script).  My goal is to substitute the dropbox daemon with single "sync" command invocations at only the times that I control.
Looking at the documentation for the dropbox command on Ubuntu, I only see a way to start/stop the daemon, but not to force it to sync.
Is there a lower level api available that can accomplish this?

A: Using @Rat2000's suggestion, I did this. In one terminal,
while true; do dropbox status; sleep 1; done;

In another terminal:
touch ~/Dropbox/test

The first terminal shows approximately the following output:
Idle
Idle
Idle
...
...
Updating (1 file)
Indexing 1 file...
Updating (1 file)
Indexing 1 file...
...
...
Downloading file list...
Downloading file list...
...
...
Idle
Idle

So we can define a script, using expect, to do a one-time dropbox sync at controlled times, assuming that the dameon does not report "Idle" until it has finished syncing.

Edit:
This solution seems to work for me:
#!/usr/bin/python
import subprocess, time, re

print "Starting dropbox daemon"
print subprocess.check_output(['dropbox', 'start'])

started_sync = False
conseq_idle = 20
while True:
    status = subprocess.check_output(['dropbox', 'status'])
    print status
    if re.search("Updating|Indexing|Downloading", status):
        started_sync = True
        conseq_idle = 20
    elif re.search("Idle", status):
        conseq_idle-=1
        if not conseq_idle:
            if started_sync:
                print "Daemon reports idle consecutively after having synced. Stopping"
                time.sleep(5)
            else:
                print "Daemon seems to have nothing to do. Exiting"
            subprocess.call(['dropbox', 'stop'])
            break
    time.sleep(1)

Notes:

*

*Depending on your Dropbox release you might have to replace
elif re.search("Idle", status):

with
elif re.search("Up to date", status):

*To reduce the impact on system performance you can experiment with utilities such as nice, ionice, and nocache, e.g.:
print subprocess.check_output(['nice', '-n10', 'ionice', '-c3', 'nocache', 'dropbox', 'start'])

Setting the script up with anacron
Of course, I schedule this script to run via anacron, like this:
1 10  dropbox_do_sync  su myuser -p -c "python /home/myuser/scripts/dropbox_do_sync.py" >> /home/myuser/logs/anacron/dropbox_do_sync

A: Here is a very simplstic way to accomplish this:
I have a slow internet connection, and don't want Dropbox running at all during the day when I am working, but want it running all night when I am supposed to be asleep.
I set up a cron job like this:
At a terminal type crontab -e
Add these lines:
#This line will stop Dropbox at 7 AM every morning:
 * 7 * * * dropbox stop
#This line will start dropbox at 10 PM every evening:
 * 22 * * * dropbox start

A: Using user84207 and Loony answers:

*

*Create 2 scripts:

startDropbox.sh:
dropbox start

stopDropbox.sh:
result=$(dropbox status)
if [ "$result" = "Up to date" ];
then
   dropbox stop
fi

*

*Add in crontab, with crontab -e

# starts only after each 5 minutes
  */5 * * * * startDropbox.sh
  # try to stop every minute
  */1 * * * * stopDropbox.sh


text:
Q: Marshaling, StringBuilder, and char pointer in DllImport I was looking at SoundTouchWrapper for .NET and I saw this:
[DllImport (SoundTouchDLLName)]
internal static extern void soundtouch_getVersionString2 (StringBuilder versionString, int bufferSize);

And in the header file from the orginal C++ library:
__declspec(dllimport) void __stdcall soundtouch_getVersionString2(char* versionString, int bufferSize);

Where can I read about how it works? How StringBuilder passed to this function is filled with data?

A: The called libraray expects a pointer to a char-array with the size of bufferSize to write the text to.
soundtouch_getVersionString2(char* versionString, int bufferSize);

So you need a mutable object with predefined size that you can pass to the C++ library. Here the StringBuilder comes in place. Put it simple: since the usage of the memory of StringBuilder and the char-array is similiar, the caller can treat it as a char-array and fill it the common way.
Then use the function this way:
int bufferSize = 50;
StringBuilder versionString = new StringBuilder(" ", bufferSize);
soundtouch_getVersionString2(versionString, bufferSize);
string realString = versionString.ToString(); //convert it to unmutable stringstring


text:
Q: How to find the closest corresponding vectors between two coordinate matrices? I have the following problem in Python I need to solve:
Given two coordinate matrices (NumPy ndarrays)  A and B, find for all coordinate vectors a in A the corresponding coordinate vectors b in B, such that the Euclidean distance ||a-b|| is minimized. The coordinate matrices A and B can have different number of coordinate vectors (that is, different number of rows).
This method should return a matrix of coordinate vectors C where the ith vector c in C is the vector from B that minimizes the Euclidean distance with the ith coordinate vector a in A.
For example, lets say
A = np.array([[1,1], [3,4]]) and B = np.array([[1,2], [3,6], [8,1]])
The Euclidean distances between the vector [1,1] in A and the vectors in B are:
1, 5.385165, 7

So the first vector in C would be [1,2]
Similarly the distances for the vector [3,4] in A and the vectors in B are:
2.828427, 2, 5.830952

So the second and last vector in C would be [3,6]
So C = [[1,2], [3,6]]
How to code this efficiently in Python?

A: You could use cdist from scipy.spatial.distance to efficiently get the euclidean distances and then use np.argmin to get the indices corresponding to minimum values and use those to index into B for the final output. Here's the implementation  -
import numpy as np
from scipy.spatial.distance import cdist

C = B[np.argmin(cdist(A,B),1)]

Sample run -
In [99]: A
Out[99]:
array([[1, 1],
       [3, 4]])

In [100]: B
Out[100]:
array([[1, 2],
       [3, 6],
       [8, 1]])

In [101]: B[np.argmin(cdist(A,B),1)]
Out[101]:
array([[1, 2],
       [3, 6]])


text:
Q: Make an existing Git branch track a remote branch? I know how to make a new branch that tracks remote branches, but how do I make an existing branch track a remote branch?
I know I can just edit the .git/config file, but it seems there should be an easier way.

A: For Git versions 1.8.0 and higher:
Actually for the accepted answer to work:
git remote add upstream <remote-url>
git fetch upstream
git branch -f --track qa upstream/qa
# OR Git version 1.8.0 and higher:
git branch --set-upstream-to=upstream/qa
# Gitversions lower than 1.8.0
git branch --set-upstream qa upstream/qa

A: This isn't a direct answer to this question, but I wanted to leave a note here for anyone who may be having the same issue as me when trying to configure an upstream branch.
Be wary of push.default.
With older git versions, the default was matching, which would cause very undesirable behaviour if you have, for example:
Local branch "master" tracking to origin/master
Remote branch "upstream" tracking to upstream/master
If you tried to "git push" when on the "upstream" branch, with push.default matching git would automatically try to merge the local branch "master" into "upstream/master", causing a whole lot of chaos.
This gives more sane behaviour:
git config --global push.default upstream

A: For git version 2.25.1, use the command:
git push --set-upstream origin <local_branch_name>

A: You might find the git_remote_branch tool useful. It offers simple commands for creating, publishing, deleting, tracking & renaming remote branches. One nice feature is that you can ask a grb command to explain what git commands it would execute.
grb explain create my_branch github
# git_remote_branch version 0.3.0

# List of operations to do to create a new remote branch and track it locally:
git push github master:refs/heads/my_branch
git fetch github
git branch --track my_branch github/my_branch
git checkout my_branch

A: In case you got "error: the requested upstream branch 'origin/foo' does not exist" after running:
git branch -u origin/foo

*

*Make sure origin does have a foo branch.

*Make sure the remote.origin.fetch variable is set to +refs/heads/*:refs/remotes/origin/*:
$ git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'
$ git config --get remote.origin.fetch
+refs/heads/*:refs/remotes/origin/*

*Run git fetch -v. You should see git updating from origin/foo:

$ git fetch -v
From github.com:davidhcefx/test
 * [new branch]      foo             -> origin/foo
 = [up to date]      master          -> origin/master

*Upon success, git branch -avv will show square brackets, indicating tracked remote branches:

$ git branch -u origin/foo
branch 'foo' set up to track 'origin/foo'.
$ git branch -avv
* foo                            92c5ada [origin/foo] Initial commit
  master                         92c5ada [origin/master] Initial commit

A: 1- update your local meta-data using  : git fetch --all

2- show your remote and local branches using : git branch -a
, see the following Screenshot

3- switch to target branch , that you want to linked with the remote: using
git checkout branchName
example :

4- Link your local branch to a remote branch using:
git branch --set-upstream-to  nameOfRemoteBranch
N.B  : nameOfRemoteBranch : to copy from the output of step 2 " git branch -r "
Example of use:

A: In a somewhat related way I was trying to add a remote tracking branch to an existing branch, but did not have access to that remote repository on the system where I wanted to add that remote tracking branch on (because I frequently export a copy of this repo via sneakernet to another system that has the access to push to that remote). I found that there was no way to force adding a remote branch on the local that hadn't been fetched yet (so local did not know that the branch existed on the remote and I would get the error: the requested upstream branch 'origin/remotebranchname' does not exist).
In the end I managed to add the new, previously unknown remote branch (without fetching) by adding a new head file at .git/refs/remotes/origin/remotebranchname and then copying the ref (eyeballing was quickest, lame as it was ;-) from the system with access to the origin repo to the workstation (with the local repo where I was adding the remote branch on).
Once that was done, I could then use git branch --set-upstream-to=origin/remotebranchname

A: I believe that in as early as Git 1.5.x you could make a local branch $BRANCH track a remote branch origin/$BRANCH, like this.
Given that $BRANCH and origin/$BRANCH exist, and you've not currently checked out $BRANCH (switch away if you have), do:
git branch -f --track $BRANCH origin/$BRANCH

This recreates $BRANCH as a tracking branch. The -f forces the creation despite $BRANCH existing already. --track is optional if the usual defaults are in place (that is, the git-config parameter branch.autosetupmerge is true).
Note, if origin/$BRANCH doesn't exist yet, you can create it by pushing your local $BRANCH into the remote repository with:
git push origin $BRANCH

Followed by the previous command to promote the local branch into a tracking branch.

A: Given a branch foo and a remote upstream:
As of Git 1.8.0:
git branch -u upstream/foo

Or, if local branch foo is not the current branch:
git branch -u upstream/foo foo

Or, if you like to type longer commands, these are equivalent to the above two:
git branch --set-upstream-to=upstream/foo

git branch --set-upstream-to=upstream/foo foo

As of Git 1.7.0 (before 1.8.0):
git branch --set-upstream foo upstream/foo

Notes:

*

*All of the above commands will cause local branch foo to track remote branch foo from remote upstream.

*The old (1.7.x) syntax is deprecated in favor of the new (1.8+) syntax.  The new syntax is intended to be more intuitive and easier to remember.

*Defining an upstream branch will fail when run against newly-created remotes that have not already been fetched. In that case, run git fetch upstream beforehand.

See also: Why do I need to do `--set-upstream` all the time?

A: or simply by  :
switch to the branch if you are not in it already:
[za]$ git checkout branch_name

run
[za]$ git branch --set-upstream origin branch_name
Branch origin set up to track local branch brnach_name by rebasing.

and you ready to :
 [za]$ git push origin branch_name

You can alawys take a look at the config file to see what is tracking what by running:
 [za]$ git config -e

It's also nice to know this, it shows which branches are tracked and which ones are not. :
  [za]$ git remote show origin

A: Make sure you run :
git config push.default tracking

to be able to push trouble free

A: You can do the following (assuming you are checked out on master and want to push to a remote branch master):
Set up the 'remote' if you don't have it already
git remote add origin ssh://...

Now configure master to know to track:
git config branch.master.remote origin
git config branch.master.merge refs/heads/master

And push:
git push origin master

A: Editing .git/config is probably the easiest and fastest way. That's what the Git commands for handling remote branches are doing, anyway.
If you don't want to muck with the file by hand (and it's not that hard to do), you can always use git config to do it...but again, that's just going to edit the .git/config file, anyway.
There are, of course, ways to automatically track a remote branch when using git checkout (by passing the --track flag, for example), but these commands work with new branches, not existing ones.

A: In very short
git branch --set-upstream yourLocalBranchName origin/develop

This will make your yourLocalBranchName track the remote branch called develop.

A: I do this as a side-effect of pushing with the -u option as in
$ git push -u origin branch-name

The equivalent long option is --set-upstream.
The git-branch command also understands --set-upstream, but its use can be confusing. Version 1.8.0 modifies the interface.

git branch --set-upstream is deprecated and may be removed in a relatively distant future.  git branch [-u|--set-upstream-to] has been introduced with a saner order of arguments.
…
It was tempting to say git branch --set-upstream origin/master, but that tells Git to arrange the local branch "origin/master" to integrate with the currently checked out branch, which is highly unlikely what the user meant. The option is deprecated; use the new --set-upstream-to (with a short-and-sweet -u) option instead.

Say you have a local foo branch checked out and want it to use a branch by the same name as its upstream. Make this happen with
$ git branch --set-upstream-to=origin/foo

A: For 1.6.x, it can be done using the git_remote_branch tool:
grb track foo upstream

That will cause Git to make foo track upstream/foo.

A: I use the following command (Suppose your local branch name is "branch-name-local" and remote branch name is "branch-name-remote"):
$ git branch --set-upstream-to=origin/branch-name-remote branch-name-local

If both local and remote branches have the same name, then just do the following:
$ git branch --set-upstream-to=origin/branch-name branch-name

A: Here, using github and git version 2.1.4, just do:
$ git clone git@github.com:user/repo.git

And remotes come by itelsef, even if not linked locally:
$ git remote show origin

* remote origin
  Fetch URL: git@github.com:user/repo.git
  Push  URL: git@github.com:user/repo.git
  HEAD branch: master
  Remote branches:
    develop tracked         <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    master  tracked
  Local branch configured for 'git pull':
    master merges with remote master
  Local ref configured for 'git push':
    master pushes to master (up to date)

But of course, still no local branch:
$ git branch
* master                  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

See? Now if you just checkout develp, it will do the magic automatically:
$ git checkout develop
Branch develop set up to track remote branch develop from origin.
Switched to a new branch 'develop'

So easy!

Summary. Just run this 2 commands:
$ git clone git@github.com:user/repo.git
$ git checkout develop

A: Use '--track' Option

*

*After a git pull :
git checkout --track <remote-branch-name>

*Or:
git fetch && git checkout <branch-name>

A: For creating new branch, we could use following command
 git checkout --track -b example origin/example
For the already created branch to create link between remote then from that branch use below command
 git branch -u origin/remote-branch-name

A: For anyone who, like me, just wants to sync up your local branch name with the remote branch name, here's a handy command:
git branch -u origin/$(git rev-parse --abbrev-ref HEAD)

A: To avoid remembering what you need to do each time you get the message:

Please specify which branch you want to merge with. See git-pull(1)
  for details.
  .....

You can use the following script which sets origin as upstream for the current branch you are in.
In my case I almost never set something else than origin as the default upstream. Also I almost always keep the same branch name for local and remote branch. So the following fits me:
#!/bin/bash
# scriptname: git-branch-set-originupstream
current_branch="$(git branch | grep -oP '(?<=^\* )(.*)$')"
upstream="origin/$current_branch"
git branch -u "$upstream"

A: This would work too
git branch --set-upstream-to=/< remote>/< branch> < localbranch>


text:
Q: Changing the value of one attribute in a Ruby collection Say for example I've got a collection like this:
[{"name" => "Ganesh", "magic_number" => 7}, {"name" => "Comrade", "magic_number" => 2}...]

How can I change the value of ALL the magic_numbers in the collection to be the same value (e.g. 8)?
I'm sure it's using something like map or collect but I can't seem to do it at the moment and return me the whole collection with the changes, just one or the other...

A: Just use .each:
a = [{"name" => "Ganesh", "magic_number" => 7}, {"name" => "Comrade", "magic_number" => 2} ]
a.each { |x| x['magic_number'] = 8 }
# a is now [{"magic_number"=>8, "name"=>"Ganesh"}, {"magic_number"=>8, "name"=>"Comrade"}]

The argument to the block is a reference to the original elements so you can change them as desired. Note that this changes a in-place which I think is what you're after.

A: This works:
x = [{"name" => "Ganesh", "magic_number" => 7}, {"name" => "Comrade", "magic_number" => 2}]
x.map{|i| i["magic_number"] = 0; i }

=> [{"magic_number"=>0, "name"=>"Ganesh"}, {"magic_number"=>0, "name"=>"Comrade"}]


text:
Q: REST API versioning in Laravel I wanted to make versioning like a domain. So inside app directory i want to move all folders into v1, v2, etc. So it will be App\v1, App\v2 namespaces. I need an advice, how to re-write bootstrap/app.php file, to instruct laravel to load only providers needed for the particular version. Where to put admin panel ? Thanks for answer.

A: Don't modify the bootstrap classes, instead go with this structure for API:
App
  Http
    Api
      V1
        -ApiController.php
 Controllerphp
 OtherWebController.php


text:
Q: Do I need the second "as" in the following text?
I stopped her with a kiss. I thought she would push me away, tell me she just saw me as a friend, or worse, just as another member of the club.

Do I need that second as? Why or why not?

A: You do not need the second as. It's ok if you keep it or delete it.
If you keep it, it would be more common to change its position with just so you would have:

I thought she would push me away, tell me she just saw me as a friend, or worse, as just another member of the club.

We often delete (omit) a piece of language in grammatically predictable sentence positions, and depend on the reader or listener to supply it for themselves (or to understand that it's implicitly there).
The linguistic concept is called ellipsis, the process is called deletion. (At least by linguists like the author of Ellipsis Happens, and Deletion Is How.)
Ellipsis is a complex topic in grammar and linguistics (different experts conceive of and describe it in different ways and using different terms), and it can cause a great deal of difficulty for English learners because it is widespread and common in English. It is likely a larger problem for learners who are, who at least believe they are, learning English in a conscious process of accumulating facts and information about the language.
For further information, see also Wikipedia, for example, and if searching for the term ellipsis, don't confuse it with the punctuation mark, ( . . . ), which has the same name.
There are two kinds of ellipsis: situational and textual.
In situational ellipsis, we leave out pieces of spoken English when the context makes it clear enough what the listener should understand. A common example is to leave out I, I'm, etc., in speech like

Q: Is it raining now? A: Not sure.

Textual ellipsis happens in both speech and writing. Under textual ellipsis, we can leave out pieces of language that we think can be supplied by the listener or reader because their existence can be implied using predictable grammatical patterns.

Textual ellipsis occurs most frequently after and and but, when we leave out subjects, verbs, articles and nouns if these are already specified in the previous clause.
   You ought to clean your teeth and brush your hair.
   (You ought to clearn your teeth and [you ought to] brush your hair.)

--From Grammar for English Language Teachers, pp. 319-20.
In your example, we have an extension of this idea: As can be left out because proficient English users can supply it implicitly. While it would be too difficult or impossible to specify all the rules describing when we can and cannot leave out every particular possible language chunk in every potential situation, it's a good idea for English learners to try to remember that ellipsis may be at work when confronted with something that appears to be missing.
Natural learning and "input hypothesis" linguists and learning experts believe that learner's minds are quite good at learning about ellipsis mostly unconsciously while exposed to enough langauge under the right conditions.

A: You need it. That part of the sentence is a shortened version of:

tell me she just saw me as a friend
or worse
(tell me she just saw me) just as another member of the club

If anything I'd lose the second 'just'.


text:
Q: WP_Query based on a custom field result I would like to know if there's a way to do a query filtered by a custom field result. In this case, I have 6 posts I would like to retrieve, but only if they have "true" selected in a custom field I've previously created. The name of the custom field is called "featured".
Here's my code
<?php
$recentPosts = new WP_Query();
$recentPosts->query('showposts=6');
?>
<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>

        <?php if ( has_post_thumbnail() ) {?>

            <a href="<?php the_permalink() ?>"><?php the_post_thumbnail( 'post-thumb-140' ); ?>

        <?php } ?>

        <a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?>

<?php endwhile; ?>

I've checked WordPress documentation on possible WP_Query arguments, but there are no filters based on a custom field.
Any ideas?

A: Here's the corrected code, thanks @Milo!

<?php
    $recentPosts = new WP_Query();
    $recentPosts->query('showposts=6&cat=1&meta_key=ticker&meta_value=yes');
?>
<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>

    <?php if ( has_post_thumbnail() ) {?>

    <a href="<?php the_permalink() ?>"><?php the_post_thumbnail( 'post-thumb-140' ); ?>

    <?php } ?>

        <a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?>

<?php endwhile; ?>


text:
Q: Selenium 2.53 not working on Firefox 54 I am trying to run my Selenium tests using Selenium 2.53 and Firefox 54 , it does not work . Has anyone else faced the same problem and have any solutions to it?

A: Firefox 54 is too new for Selenium 2.53, latest Firefox versions works only with latest Selenium version.
You can download and install Firefox 46 - that should work fine with Selenium 2.53. Make sure to disable auto updates in Firefox.
Or you can update your selenium to latest 3.4.0.


text:
Q: Basic recording example using FreeBSD OpenSoundSystem outputs all 0 values I am trying to implement a basic example to record a few seconds of audio in FreeBSD, which uses a modified OSS version.
Following the sample files included in the FreeBSD source code and the OSS programming guide I have prepared the following sample program:
#include <sys/soundcard.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>

#define MAX_FILENAME_LENGTH 1024
#define MAX_SECONDS_TO_RECORD 3600                      // UP TO 1 HOUR RECORDING
#define MAX_BUFFER_LENGTH 8000*MAX_SECONDS_TO_RECORD

int main(int argc, char *argv[]) {

        unsigned char buffer[MAX_BUFFER_LENGTH];        // BUFFER TO STORE AUDIO
        char dspfile[MAX_FILENAME_LENGTH];              // /dev/dsp FILENAME
        int fd;                                         // /dev/dsp FILE DESCRIPTOR
        unsigned int seconds_to_record;                 // NUMBER OF SECONDS TO RECORD
        unsigned long samples_to_record;                // NUMBER OF SAMPLES TO RECORD
        unsigned long samples_recorded;                 // NUMBER OF SAMPLES RECORDED
        int format;                                     // FORMAT
        int channels;                                   // CHANNELS (1=MONO 2=STEREO)
        int sampling_rate;                              // SAMPLING RATE
        int error;                                      // AUX VARIABLE ERROR

        // STEP 1: READ /dev/dsp PARAMETER
        if(argc!=3) {
                fprintf(stderr, "ERROR: Incorrect number of arguments.\n");
                fprintf(stderr, "USAGE: %s /dev/dsp seconds\n", argv[0]);
                exit(1);
        } else if( strlen(argv[1]) >= MAX_FILENAME_LENGTH ) {
                fprintf(stderr, "ERROR: /dev/dsp filename parameter too long. Maximum size is %d.\n", MAX_FILENAME_LENGTH);
                exit(1);
        } else {
                strncpy(dspfile, argv[1], MAX_FILENAME_LENGTH);
                sscanf(argv[2], "%u", &seconds_to_record);
        }
        if( seconds_to_record >= MAX_SECONDS_TO_RECORD) {
                fprintf(stderr, "ERROR: Too many seconds requested. Maximum recording time is %u.\n", MAX_SECONDS_TO_RECORD);
                exit(1);
        }

        // STEP 2: OPEN FILE
        fd = open(dspfile, O_RDWR);
        if(fd==-1) {
                fprintf(stderr, "ERROR: Can not open /dev/dsp file %s. Error code %d %s\n", dspfile, errno, strerror(errno));
                exit(1);
        }

        // STEP 3: CONFIGURE MONO, 8 BITS UNSIGNED SAMPLES, 8KHz SAMPLING RATE
        channels = 1;
        error = ioctl(fd, SNDCTL_DSP_CHANNELS, &channels);
        if(error==-1) {
                fprintf(stderr, "ERROR: Can not configure 1 channel. Error code %d %s\n", errno, strerror(errno));
                exit(-1);
        }
        format = AFMT_U8;
        error = ioctl(fd, SNDCTL_DSP_SETFMT, &format);
        if(error==-1) {
                fprintf(stderr, "ERROR: Can not configure audio format. Error code %d %s\n", errno, strerror(errno));
                exit(-1);
        }
        sampling_rate = 8000;
        error = ioctl(fd, SNDCTL_DSP_SPEED, &sampling_rate);
        if(error==-1) {
                fprintf(stderr, "ERROR: Can not configure sampling rate. Error code %d %s\n", errno, strerror(errno));
                exit(-1);
        }

        // STEP 4: RECORD N SAMPLES CORRESPONDING TO THE REQUESTED NUMBER OF SECONDS TO RECORD
        samples_to_record = seconds_to_record * 8000;
        samples_recorded = 0;
        while(samples_to_record > 0) {
                ssize_t samples_read = read(fd, buffer + samples_recorded, samples_to_record);
                samples_to_record -= (unsigned long)samples_read;
                samples_recorded += (unsigned long)samples_read;
                write(STDOUT_FILENO, buffer + samples_recorded, samples_read);
        }

        // STEP 5: CLOSE FILE
        if(close(fd)==-1) {
                fprintf(stderr, "ERROR: Can not close /dev/dsp file %s. Error code %d %s\n", dspfile, errno, strerror(errno));
                exit(1);
        }

        // DISENGAGE
        return(0);

}

But I get a 24000 bytes empty file.
Doing the following works:
cat /dev/dsp > test.raw
cat test.raw > /dev/dsp

So it seems that I am missing something wrong or I am missing one step.


text:
Q: LateInitializationError flutter why does this error occur
I've been trying to figure this out for two days
thank you to those who helped
LateInitializationError: Field '_ANADATA@583274105' has not been initialized.
var test =  databaseHelper();

test.ogrenciEkle(ogrenci("Ahmet", 1));

import 'dart:async';
import 'dart:io';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';
import '../model/Ogrenci.dart';

class databaseHelper {
  static late databaseHelper _ANADATA;
  static late Database _DATABASE;
  String ogrenciTablosu = "ogrenci";
  String columID = "id";
  String columName = "ad_soyad";
  String columnActv = "aktif";

  factory databaseHelper() {
    if (_ANADATA == null) {
      _ANADATA = databaseHelper.init();
      return _ANADATA;
    } else {
      return _ANADATA;
    }
  }

  databaseHelper.init();

  Future<Database> getDatabase() async {
    if (_DATABASE == null) {
      _DATABASE = await _initializeDatabase();
      return _DATABASE;
    } else {
      return _DATABASE;
    }
  }

  _initializeDatabase() async {
    Directory dir = await getApplicationDocumentsDirectory();
    String dbPath = join(dir.path, "db.sql");
    var ogrenciDb =
        await openDatabase(dbPath, version: 1, onCreate: _createDatabase);
    return ogrenciDb;
  }

  Future<void> _createDatabase(Database db, int version) async {
    await db.execute(
        "CREATE TABLE $ogrenciTablosu ($columID INTEGER PRIMARY KEY AUTOINCREMENT,$columName TEXT,$columnActv INTEGER) ");
  }

  Future<int> ogrenciEkle(ogrenci ogrenci) async {
    var db = await getDatabase();
    var sonuc = await db.insert(ogrenciTablosu, ogrenci.toMap());

    return sonuc;
  }
}


text:
Q: Blazor JSInterop intermitant fail - Could not find '' Every so often, when i load my page, i get this error, which stops my page from working.. Weird as i can load the page, 3-4 times and everything is fine, but when i try and refresh my page in quick succession i get this error..
STACK -
Microsoft.JSInterop.JSException: Could not find 'search' ('search' was undefined). Error: Could not find 'search' ('search' was undefined). at http://localhost:26661/_framework/blazor.server.js:1:67390 at Array.forEach () at e.findFunction (http://localhost:26661/_framework/blazor.server.js:1:67350) at v (http://localhost:26661/_framework/blazor.server.js:1:69092) at http://localhost:26661/_framework/blazor.server.js:1:70038 at new Promise () at e.beginInvokeJSFromDotNet (http://localhost:26661/_framework/blazor.server.js:1:70011) at http://localhost:26661/_framework/blazor.server.js:1:26293 at Array.forEach () at e.invokeClientMethod (http://localhost:26661/_framework/blazor.server.js:1:26263) at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, Object[] args) at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(IJSRuntime jsRuntime, String identifier, Object[] args) at
Interop call -
protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            try
            {
                await Js.InvokeVoidAsync("search");
            }
            catch (Exception e)
            {
                ErrorIsHidden = false;
                ErrorDescription = e.ToString(); //Show error description on page
                StateHasChanged();
                throw;
            }

        }

JS -
function search(){$(document).ready(function () {
    $("#myInput").on("keyup", function () {
        var value = $(this).val().toLowerCase();
        $('div[data-role="apps"]').filter(function () {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    });
});}

PS.. i also thought that try-catch would allow the program to continue functioning (obviously) without the search function in this case?
ON FURTHER TESTING
This is clearly not right, but the silly thing is if i again add the JS call to the catch - the JS actually loads.. my error shows up, but the app crashes still, but the JS works (obviously because the error has been registered by then).
Strange.. Not sure what the issue is here.


text:
Q: Google Action : Failed to parse Dialogflow response into AppResponse My Google Assistance working without any issue until April 26, 2022, After April 26  its start getting throwing below error when we access from Google assistance.
Before APril 26 I used Asp.Net 4.6 to implement my backend service, which I called it from Dialog flow fulfilment. After that I migrate my code into Asp.net core 5.0
{
  "responseMetadata": {
    "status": {
      "code": 10,
      "message": "Failed to parse Dialogflow response into AppResponse because of invalid platform response: Could not find a RichResponse or SystemIntent in the platform response for agentId: d538361c1 and intentId: 9b 0dc5. WebhookStatus: code: 5\nmessage: \"Webhook call failed. Error: NOT_FOUND, State: URL_ERROR, Reason: ERROR_NOT_FOUND, HTTP status code: 404.\"\n."
    }
  }
}


text:
Q: Appending to a dictionary in a list I want to append different values to the same dictionary structure inside a JSON list. Here is an example:
myJson = {"list": []}

element = {"value": []}
myJson["list"].append(element)
myJson["list"].append(element.copy())

myJson["list"][0]["value"].append("first")
myJson["list"][1]["value"].append("second")
print(myJson)

What this prints out is:
{'list': [{'value': ['first', 'second']}, {'value': ['first', 'second']}]}

But I want:
{'list': [{'value': ['first']}, {'value': ['second']}]}

What am I doing wrong? I created a copy of element so why is it still the same? Thanks!


text:
Q: Display validation message on button click for multiple tabs in jquery I have 7-8 tabs and each tab consist of next button. At the last tab there is Submit button.

So, what I want is if user does not fill any fields in any of the tabs, A validation message should pop up saying that this field is not filled and the field should get highlighted.

I have written the validaton part in javascript like below
function SiteDetailsValidate() {
if ($("#ddlSiteType").val() == '--Select--' || $("#ddlSiteType").val() == null) {
    jAlert('Type of Site cannot be blank', 'INFORMATION');
    return false;
}
if ($('#txtSitePlotDimension').val() == "" || $('#txtSitePlotDimension').val() == null) {
    jAlert('Site/Plot Dimension cannot be blank', 'INFORMATION');
    return false;
}
if ($("#ddlTechnolgy").val() == '--Select--' || $("#ddlTechnolgy").val() == 0) {
    jAlert('Technology cannot be blank', 'INFORMATION');
    return false;
}
if ($("#ddlMountType").val() == '--Select--' || $("#ddlMountType").val() == 0) {
    jAlert('Mount Type cannot be blank', 'INFORMATION');
    return false;
}
if ($("#ddlAntennaSize").val() == '--Select--' || $("#ddlAntennaSize").val() == 0) {
    jAlert('Antenna size cannot be blank', 'INFORMATION');
    return false;
}
if ($('#txtAMSL').val() == "" || $('#txtAMSL').val() == null) {
    jAlert('AMSL cannot be blank', 'INFORMATION');
    return false;
}
if (!$("input[name='Platform']:checked").val()) {
    jAlert('Platform Required cannot be blank', 'INFORMATION');
    return false;
}
if ($('#txtPlatformHeight').val() == "" || $('#txtPlatformHeight').val() == null) {
    jAlert('Platform Height cannot be blank', 'INFORMATION');
    return false;
}
if (!$("input[name='Rooftype']:checked").val()) {
    jAlert('Rooftype Site cannot be blank', 'INFORMATION');
    return false;
}
if ($('#txtNoofFloorsBldg').val() == "" || $('#txtNoofFloorsBldg').val() == null) {
    jAlert('No Of Floors in Building cannot be blank', 'INFORMATION');
    return false;
}
if ($('#txtAddRoofTopSite').val() == "" || $('#txtAddRoofTopSite').val() == null) {
    jAlert('In addition to standard space requirement for Roof top Site additional space 5 Mtr * 4 Mtr for VSAT Antenna cannot be blank');
    return false;
}
if ($('#txtStructuralStability').val() == "" || $('#txtStructuralStability').val() == null) {
    jAlert('Structural Stability Certificate (SST) from Local Consultant cannot be blank', 'INFORMATION');
    return false;
}
if ($('#txtSatelliteBand').val() == "" || $('#txtSatelliteBand').val() == null) {
    jAlert('Satellite Band cannot be blank', 'INFORMATION');
    return false;
}
else {
    var abc = true;
    return abc;
}}

Here is my tab html and button click:-

Site Details

Antenna Orientation

LOS Clearance

Cables & Electrical

Other Details

Panoramic Photos

Satellite LOS Snaps

Site /Plot Layout

Site Finalization Report

<input class="formbutt submit" type="button" id="btnSubmit" value="Submit" onclick="return ValidateTSSRFields('Save');" />

Please suggest how should I will be able to fire the validation message on submit click and show on which tab it is giving alert.


text:
Q: jQuery forms.js with multiple forms per page I would like to submit information to a mySql database using php and ajax.
The page that the info is being sent from (form.php) has multiple forms that are generated from a "while()" loop.
On success, I would a response to update a div above the particular form from which the data was submitted.
I am currently using jQuery and the jquery form plugin.
I have been successful in getting the data to the database, however I am having trouble with the response being sent back to the proper div. I have been successful in getting a response back to a div that is outside of the while() loop. I have not, however, been successful in getting a response back to a div within the loop. I have placed in the code below a div called:
    ">
Where I would like the note to be placed.
I know that this has everything to do with my  javascript function:

The #noteReturn function does not specify which businesses div it should be placed in.
I hope that this makes sense.
Thank you for your help.
The code is below:

<?php
$query = mysql_query("SELECT * FROM businesses");
while( $row = mysql_fetch_assoc( $query ) ):
    $b_id = $row['bid'];
?>

<?php
// query the db for notes associated with business... return notes texts and notes dates
$notesQuery = mysql_query("SELECT business_id, notes, messageDate FROM notes WHERE notes.business_id = $b_id ORDER BY messageDate");
while( $NoteRow = mysql_fetch_assoc( $notesQuery ) ) {
extract($NoteRow);
echo "$notes
$messageDate
";
}  // end while$notesQuery
?>

<div id="noteReturn<?php echo $b_id; ?>">

<form name="noteForm" action="notesProcess.php" method="post">
    <input type="text"  name="note" />
    <input type="hidden" value="<?php echo $b_id ?>" name="bid" />
    <input type="submit" class="button"  value="Send" />
</form>

<?php
endwhile;
?>

<?php
$note = $_POST['note'];
$id = $_POST['bid'];
$sql = "INSERT INTO notes (business_id, notes) VALUES ('$id', '$note')";
$result = mysql_query( $sql );
if( $result ) {
echo " $note"; }
?>

A: Change this code:
jQuery('form').ajaxForm({
    target: '#noteReturn',
    success: function() {
        $('#noteReturn').fadeIn('slow');
    }
});

To this:
jQuery('form').ajaxForm({
    target: '#noteReturn',
    dataType: 'json',
    success: function(data) {
        $('#noteReturn' + data.id).html(data.note).fadeIn('slow');
    }
});

And this code:
<?php
$note = $_POST['note'];
$id = $_POST['bid'];
$sql = "INSERT INTO notes (business_id, notes) VALUES ('$id', '$note')";
$result = mysql_query( $sql );
if($result) {
    echo " $note";
}
?>

To this:
<?php
$note = mysql_real_escape_string($_POST['note']);
$id = mysql_real_escape_string($_POST['bid']);
$sql = "INSERT INTO notes (business_id, notes) VALUES ('$id', '$note')";
$result = mysql_query( $sql );
if($result) {
    print json_encode(array("id" => $id, "note" => $note));
}
?>

What happened?
The change to the PHP code is making use of PHP's json_encode function to print out the id of the business to which the note was added as well as the actual note text. In the javascript code, I added the dataType of 'json' to tell the script what format of response to expect. Once the request is received in the success callback, the data variable is an object with the values we passed through json_encode. So data.id has the business id and data.note has the new note. Using jQuery's html() manipulation function, the inner html of the div is updated to the latest note. The div selector uses the id we passed, so we can update the corresponding div.
Also, this is slightly off topic, but make sure you always use mysql_real_escape_string when putting values into a query like you are. If you do not use this, your queries will be vulnerable and susceptible to injection attacks, and they are not pretty. If a customer decided to enter a note value of ');DROP TABLE businesses; you'd really feel the pain. Preferably, switch to PDO or MySQLi and use prepared statements, as they are the 'correct' way of doing queries nowadays.


text:
Q: Как сделать выдачу доступа к каналу новой роли? как сделать чтобы роль созданная через команду сразу получала доступ к каналу который так-же создаётся с ней одновременно
мой код:
@client.command()
@commands.has_permissions(administrator = True)
async def clancreate(ctx, *, name : str):
   guild = ctx.guild
   await guild.create_role(name=name)
   guild = ctx.message.guild
   category = discord.utils.get(ctx.guild.categories, name="Клан типа")
   channel = await guild.create_voice_channel(name, category=category)
   await ctx.message.add_reaction('✅')


text:
Q: How do I get the innerHTML of the selected Selenium WebElement using javascript? I need to get the text enclosed in the returned span elements.
  driver.findElements(By.className("lvHighlightSubjectClass")).then(async (subjects) => {
      for (let i = 0; i < 10; i++) {
        const subject = subjects[i];
        if (subject) {
          console.log(await subject.getAttribute('innerHTML'));
        }
      }
  });

I seem to be getting a Promise back from each console.log call.  How can I access the attributes of the WebElements returned by findElements?

A: You would just "await" the promise:
driver.findElements(By.className("lvHighlightSubjectClass")).then(async (subjects) => {
  for(let subject of subjects) {
    console.log(await subject.getInnerHtml())
  }
});


text:
Q: Django model property field calculated with field from another child model class BusinessFunction(models.Model):
     name = models.CharField(max_length=200)
     priority_rating = models.PositiveIntegerField(null=True, blank=True)
     location = models.CharField(max_length=200)
     network_service_related = models.CharField(max_length=200)

     class Meta:
         ordering = ['name']

     def __str__(self):
         return self.name

class CriticalImpact(models.Model):
     businessfunction = models.ForeignKey(BusinessFunction, on_delete=models.CASCADE)
     priority = models.PositiveSmallIntegerField(null=True, blank=True)
     financial = models.PositiveSmallIntegerField(null=True, blank=True)
     legal = models.PositiveSmallIntegerField(null=True, blank=True)
     score = models.PositiveSmallIntegerField(null=True, blank=True)
     percentage = models.PositiveIntegerField(null=True, blank=True)

     class Meta:
         ordering = ['businessfunction']

class TimeImpact(models.Model):
     businessfunction = models.ForeignKey(BusinessFunction, on_delete=models.CASCADE)
     impact_score_financial = models.DecimalField(max_digits=5, decimal_places=2, blank=True,
     null=True)
     impact_score_asset = models.DecimalField(max_digits=5, decimal_places=2,
     blank=True, null=True)
     final_score = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True)

     class Meta:
         ordering = ['businessfunction']

     @property
     def final_rating(self):
         final_rating = (self.final_score + ????????)/2
         return  final_rating

I have code as above and would like to add property of final rating using calculation from own table(TimeImpact) field final_score  and field from CriticalImpact field ie percentage. The problem is how i can get the field percentage from CriticalImpact table which is the child of business function table.
I've searched before but most of the answer is calculated field coming from field in own table and parent table, not with another child table.

A: Currently, you have no relation, make ForeignKey in TimeImpact model which would have Many-to-One relation with CriticalImpact model, then you can take percentage field via chaining, so:
class TimeImpact(models.Model):
     businessfunction = models.ForeignKey(BusinessFunction, on_delete=models.CASCADE)
     impact_score_financial = models.DecimalField(max_digits=5, decimal_places=2, blank=True,
     null=True)
     impact_score_asset = models.DecimalField(max_digits=5, decimal_places=2,
     blank=True, null=True)
     final_score = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True)
     critical_impact=models.ForeignKey(CriticalImpact,on_delete=models.CASCADE)

     class Meta:
         ordering = ['businessfunction']

     @property
     def final_rating(self):
         final_rating = (self.final_score + self.critical_impact.percentage)/2
         return  final_rating


text:
Q: DKIM passes but SPF fails in policy_evaluated The SPF failure is not preventing email from sending, but I'm curious if there's a way to get it to pass. Is there any scenario where an email server would reject receipt based on this DMARC record?
<?xml version="1.0"?>
<feedback>
  <report_metadata>
    <org_name>Verizon Media</org_name>
    <email>dmarchelp@verizonmedia.com</email>
    <report_id>1619141439.695059</report_id>
    <date_range>
      <begin>1619049600</begin>
      <end>1619135999</end>
    </date_range>
  </report_metadata>
  <policy_published>
    <domain>openpathtutoring.com</domain>
    <adkim>r</adkim>
    <aspf>r</aspf>

none

    <pct>100</pct>
  </policy_published>
  <record>
    <row>
      <source_ip>12.345.678.90</source_ip>
      <count>1</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>openpathtutoring.com</header_from>
    </identifiers>
    <auth_results>
      <dkim>
        <domain>bnc3.mailjet.com</domain>
        <selector>mailjet</selector>
        <result>pass</result>
      </dkim>
      <dkim>
        <domain>openpathtutoring.com</domain>
        <selector>mailjet</selector>
        <result>pass</result>
      </dkim>
      <spf>
        <domain>bnc3.mailjet.com</domain>
        <result>pass</result>
      </spf>
    </auth_results>
  </record>
</feedback>

SPF record:
v=spf1 include:spf.mailjet.com ?all

A: I'm not sure why that SPF check is failing since the IP it is reporting for is included in the mailjet SPF, which covers 87.253.232.0-87.253.239.255 in its first subnet. I would expect it not to be counted because your SPF uses a default ?all mechanism, which is about equivalent to not having an SPF record at all, plus your DMARC record says p=none, so you're asking receivers not to reject messages even if they fail to verify.
In short, I would not expect a mail server to reject anything on the basis of the settings you have.


text:
Q: Tapestry - How to pass parameters from tml page to event handler in tapestry? I am new to tapestry. Can someone help me on following issue I am having hard time solving?
I have a form in my page tags.tml

    <t:form t:id="addTagForm" t:zone="tagsZone" class="hideForReadOnlyMode addTagForm" style="display:inline-block;">
        <t:textfield t:id="newTag" t:mixins="salsaautocomplete" size="25" placeholder="add a tag" validate="required" value="newTag" />
    </t:form>

When this form is submitted, following method is called on the server side java class tags.java
Object onSuccessFromAddTagForm() {
      // some logic
}

I want to know how can I pass a parameter(say "testParameter") from tml file to this method which is invoked when the form is submitted.
I would like to do something like below.

    <t:form t:id="addTagForm" t:zone="tagsZone" t:testParameter="testValue" class="hideForReadOnlyMode addTagForm" style="display:inline-block;">
        <t:textfield t:id="newTag" t:mixins="salsaautocomplete" size="25" placeholder="add a tag" validate="required" value="newTag" />
    </t:form>

And access it in method like,
Object onSuccessFromAddTagForm(String testParameter) {
      // some logic
}

A: Use context parameter of form. You can pass a single parameter or multiple parameters (using context='[param1, param2]') and then in the submit handler you can use
Object onSubmitFromMyForm(Object param1, Object param2){
....
}

Please note, the parameters are type coerced.


text:
Q: Pandas + Delete specific rows not by index I've started learning pandas and have found an issue which I can't seem to resolve.
I am loading a data from a csv file and need to delete some rows matching a few strings.
CSV:
id fullname city  tst
999      bbb  CIT  aaa
888      bbb  CIT  aaa
777      xxx  JJJ  aaa

What I've tried:
import pandas as pd

df = pd.read_csv('zzz.csv')

#to_drop = ['xxx', 'aaa']

df = df.drop('xxx',axis=0)

but I am getting the error below:
KeyError: "['xxx'] not found in axis"

What I am missing here? Also, what if I want to pass a list and delete all rows matching strings from the list? Example:
to_drop = ['xxx', 'aaa']

df = df.drop(to_drop,axis=0)

A: I suggest:
df = df[df.fullname!='xxx']

and for a list:
names=['xxx','bbb']
df = df[~df.fullname.isin(names)]

the ~ operator means "not"


text:
Q: Expand a collapsible panel after pagr redirect Im having three panels(about us, contacts and Feedback form namely) with CollapsiblePanelExtender in a page named Home.aspx..the panels work fine in the page(showing and hiding of panels). And i have a master page which consists of three LinkButtons with the names of the panel. when i click 'about us' from any other page, im redirected to Home page..
But i also want the 'about us' panel to be expanded now.
How to make the panel expand when redirected from any other page?
im aware of codes like

panel1_CollapsiblePanelExtender.collapsed = true:

what im currently doing is, since the links are in master page, i create querystring like

Response.Redirect("Home.aspx?pg=1")

for 'about us' and 2 and 3 for contacts and Feedback panels respectively.
And in Page_Load() of Home.aspx, i check the value in querystring and then i set
this

Panel1_CollapsiblePanelExtender.Collapsed = false;

for About Us and respectively.. but when im redirected first time to this page, the panel does no expand. but when i click the link again, the respective panel expands.
What am i missing here. And also would like to know about

Panle1_CollapsiblePanelExtender_ClientState


text:
Q: Recovering my Clash of clans and save to other device I want to recover my clash of clans that connected to facebook. And i will save it to google play store. But I dont know how.

A: Clash of clans is not connected to your facebook. Your data is only covered by Game Center (iOS) or Google Play Store/Games (Android). You can always contact Supercell through Help and Support in the settings (cog icon above Shop button). Provided by your problem/issue, your in-game name, etc. describing your account. Don't worry, Supercell will asked more questions regarding your account for recovery.


text:
Q: Cannot fit a modal window with google chart I want to show modal window with google chart inside after pressing a button.
But my is always looks very ugly and don't fit the modal size.
What I want to do that increase size of modal, increase the size of the chart and put them together for good-looking.
Here the result I have, it looks like:

Here the html for modal:
<button id="getChart" type="submit" class="btn btn-outline-info" data-toggle="modal" data-target="#exampleModalCenter"> Result</button>

                <button type="button" class="close" data-dismiss="modal">×</button>

Here the CSS styles:
    .chart {
    align-content: center;
    display: flex;
    justify-content: center;
}

.modal {
    text-align: center;
}

@media screen and (min-width: 768px) {
    .modal:before {
        content: " ";
        display: inline-block;
        height: 100%;
        vertical-align: middle;
    }
}

.modal-dialog {
    display: inline-block;
    text-align: center;
    vertical-align: middle;
}

.modal-footer {
    color: #00b5e6;
    font-size: 25px;
    text-align: center;
}

And js code:
$('#getChart').click(getCheckboxesValues);

google.charts.load('current', {'packages':['corechart']});

function drawChart() {
    var data = google.visualization.arrayToDataTable(chartObject);

    var options = {
        title: 'Company Performance',
        curveType: 'none',
        legend: {position: 'bottom'}
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

    // The select handler. Call the chart's getSelection() method
    function selectHandler() {
        var selectedItem = chart.getSelection()[0];
        if (selectedItem) {
            var task = data.getValue(selectedItem.row, 0);
            alert('The user selected ' + task);
        }
    }

    google.visualization.events.addListener(chart, 'select', selectHandler);

    chart.draw(data, options);
}

A: You should use the actual date (not a string) as a key for data and format: 'YYYY-MM-dd' to properly format date for a chart.
check this:
google.visualization.arrayToDataTable([
  ['date', 'speedKpi'],
  [new Date('2018-10-01T00:00:00.000Z'), 66.60145829628313],
  [new Date('2018-10-02T00:00:00.000Z'), 329.1959406713505],
  [new Date('2018-10-03T00:00:00.000Z'), 0.0],
  [new Date('2018-10-04T00:00:00.000Z'), 0.0],
  [new Date('2018-10-05T00:00:00.000Z'), 0.0],
  [new Date('2018-10-06T00:00:00.000Z'), 0.0],
  [new Date('2018-10-07T00:00:00.000Z'), 0.0],
  [new Date('2018-10-08T00:00:00.000Z'), 0.0],
  [new Date('2018-10-09T00:00:00.000Z'), 0.0],
  [new Date('2018-10-10T00:00:00.000Z'), 0.0],
  [new Date('2018-10-11T00:00:00.000Z'), 0.0],
  [new Date('2018-10-12T00:00:00.000Z'), 0.0],
  [new Date('2018-10-13T00:00:00.000Z'), 0.0],
  [new Date('2018-10-14T00:00:00.000Z'), 0.0],
  [new Date('2018-10-15T00:00:00.000Z'), 0.0],
  [new Date('2018-10-16T00:00:00.000Z'), 72.62773722627736],
  [new Date('2018-10-17T00:00:00.000Z'), 0.0],
  [new Date('2018-10-18T00:00:00.000Z'), 0.0],
  [new Date('2018-10-19T00:00:00.000Z'), 0.0],
  [new Date('2018-10-20T00:00:00.000Z'), 0.0],
  [new Date('2018-10-21T00:00:00.000Z'), 0.0],
  [new Date('2018-10-22T00:00:00.000Z'), 0.0],
  [new Date('2018-10-23T00:00:00.000Z'), 0.0],
  [new Date('2018-10-24T00:00:00.000Z'), 0.0],
  [new Date('2018-10-25T00:00:00.000Z'), 0.0],
  [new Date('2018-10-26T00:00:00.000Z'), 0.0]
]);

...
var options = {
  title: 'Company Performance',
  curveType: 'none',
  legend: { position: 'bottom' }, hAxis: { format: 'YYYY-MM-dd' }
};

EDIT:
Also, you can use slantedText option to rotate keys a bit, so you'll be able to see them:
hAxis: {slantedText: true}

Summary here: https://codepen.io/extempl/pen/aRXvLY
Please also check Documentation for more options and control over the result.


text:
Q: ignore url mod-rewrite via htaccess i use Prestashop and force https for all url.
I need to add script with this url:
src="//c.imedia.cz/js/retargeting.js"
i need url keep like this in html.
but htaccess seems change it to
src="https://c.imedia.cz/js/retargeting.js"
which doesn't work then.
i tried to add Rewrite rule to prevent override this url
RewriteRule retargeting\.js$ - [L,NC]

Any solution please?

A: htaccess does not change the src in your HTML. The browser will replace // with the protocol that is used in the request. i.e. https. It's commonly referred to as protocol relative URL.
More info in this answer about that
So if you don't want it to use https then you should explicitly set it as http. That will however cause mixed content when served over https and modern browsers will probably block it. So if you force https then ALL your resources have to be https as well or it will be blocked and not loaded even using http.
So then you should get a wildcard SSL certificate for your subdomains so that your resources can be served as https as well.


text:
Q: send private details to each socket with socket.io I have 2 players in a multiplayer quiz.
Each client has true answers and false answers.
True answers : socket.true
False answers : socket.false
I'm increasing each variables answer by answer and finally, after 5 answers, i'm calling finishgame function.
I want to send a data that contains count of true answers and false answers to each client in finishgame function.
How can I do this ?
If I use socket.emit or socket.broadcast.to(socket.room).emit it sends only one socket's data.
For example :
Send joe -> joe has 3 true , 2false answers;
Send tim -> tim has 1 true , 4 false answers.

But it doesn't happen.

A: Create a new object called answers now when a client starts the quiz you create a new answers object with the socket.id as index, if you need to add a true or false answer you just edit/create a property for that answers object (example answers[socket.id]['trueAnswers']++). Now when you want to send true and false answers to the client you can easily read the answers object with a supplied socket.id as index from the client you want the data from.
Example:
        // Create the object
        Answers = new Object();

        // Client starts the quiz:
        Answers[socket.id] = {
            trueAnswers: 0,
            falseAnswers: 0
        };

        // Client made a correct answer:
        Answers[socket.id].trueAnswers++;

        // Send answers data back that is owned by this socket.id
        io.sockets.socket(socket.id).emit(Answers[socket.id]); // Shows 'Object {trueAnswers: 1, falseAnswers: 0}'

Edit: If you want to send this via a forEach way like you describe I belief this might be what you are looking for:

*

*Please note that this function is not available anymore in socket.io versions higher then 1.0, it is recommended to keep a array of your socket.id's so you can iterate over them if need be.
    io.sockets.clients().forEach(function (socket) {
                // This will go trough all connected sockets
    });


text:
Q: Git rebase duplicates functions I am pretty new to Git, and I can't find anything like what I am seeing, so I figure maybe I am just doing something wrong.
I am trying to rebase the branch onto master so that the branch has the latest commits from master, so I can test it before a final merge.
Here is the workflow I am following:
> git clone <master>
> git remote add branch_repo <branch>
> git fetch branch_repo
> git checkout -b new_branch branch_repo/branch
> git fetch origin
> git rebase origin/master

Other important information:

*

*This branch has several significant changes throughout the code base

*Master has been refactored at least once since the initial branch

The result is, after the rebase completes, and I resolve all merge conflicts, the resulting files have many duplicate functions. Sometimes the auto-merge makes no sense to me - like the body of one function is placed with the declaration of a completely different function.
Is my workflow wrong, or is this just the unfortunate by-product of a refactor+ major revision which must be resolved manually?

A: Okay, so if I understand the situation correct, this is how it is. You branched off master, made some changes but before you could push your changes to master, someone else updated master. So now you have to rebase off master so that you get the new changes been made to master. Well here is how you do it. You were not totally wrong.
(Assuming you are in you branch)

1. > git checkout master
2. > git pull (assuming your remote points to origin/master)
3. > git checkout your_branch (assuming there were no merge conflicts during the pull)
4. > git rebase -i master (now that your local master is up to date you can rebase off it)

Sort out the merge conflicts and you should be good to go.


text:
Q: @IndexedEmbedded on class containing other @IndexedEmbedded fields I'm trying to manage hibernate search indexing on a class with a field mapped by @IndexedEmbedded on a custom @Embeddable entity. This entity also contains others @IndexedEmbedded fields in the @MappedSuperclass.
These are the entities involved:
@Builder
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Indexed
@GeoPointBinding(fieldName = "location")
public class Insertion {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "INSERTION_SEQ")
    private Long id;

    @NotNull
    @GenericField
    private Boolean publicated;

    @NotNull
    @Latitude
    private Double latitude;

    @NotNull
    @Longitude
    private Double longitude;

    @JsonIgnore
    private Point location;

    @FullTextField(analyzer = "generic_text")
    @KeywordField(name="city_sort", sortable = Sortable.YES, normalizer = "sort")
    private String city;

    @NotNull
    @Embedded
    @Valid
    @IndexedEmbedded
    private Amount amount;

    @IndexedEmbedded(name = "insertion_mate_preferences")
    @Embedded
    @Valid
    private MatePreference matePreferences;

}

And these classes:
@SuperBuilder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Embeddable
public class MatePreference extends BaseProfile {

    @NotNull
    @GenericField
    private Integer minAge;

    @NotNull
    @GenericField
    private Integer maxAge;

}

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@MappedSuperclass
public abstract class BaseProfile implements BaseProfileView {

    @GenericField
    private Boolean smoker;

    @GenericField
    private Boolean children;

    @GenericField
    private Boolean hasAnimals;

    @GenericField
    private Boolean student;

    @GenericField
    private Boolean employed;

    @GenericField
    private String animalsDescription;

    @Enumerated(EnumType.STRING)
    @GenericField
    private Genre genre;

    @Enumerated(EnumType.STRING)
    @GenericField
    private OccupationSector occupation;

    @Enumerated(EnumType.STRING)
    @ElementCollection(fetch = FetchType.EAGER)
    @GenericField
    @IndexedEmbedded
    private Set<Personality> personalities;

    @Enumerated(EnumType.STRING)
    @ElementCollection(fetch = FetchType.EAGER)
    @GenericField
    @IndexedEmbedded
    private Set<Lifestyle> lifestyles;

    @ElementCollection(fetch = FetchType.EAGER)
    @GenericField
    @IndexedEmbedded
    private Set<Language> languages;

    @Enumerated(EnumType.STRING)
    @GenericField
    private StudyTitle titleOfStudy;

    @Enumerated(EnumType.STRING)
    @GenericField
    private StudyField studyField;
}

When running the application, Hibernate Search throws the following error:
org.hibernate.search.util.common.SearchException: HSEARCH000520: Hibernate Search encountered failures during bootstrap. Failures:

    Hibernate ORM mapping:
        type 'it.friendshome.api.common.model.insertion.Insertion':
            path '.matePreferences<no value extractors>.languages':
                index 'Insertion':
                    field 'insertion_mate_preferences':
                        failures:
                          - HSEARCH400520: Duplicate index field definition: 'languages'. Index field names must be unique. Look for two property mappings with the same field name, or two indexed-embeddeds with prefixes that lead to conflicting index field names, or two custom bridges declaring index fields with the same name.
            path '.matePreferences<no value extractors>.lifestyles':
                index 'Insertion':
                    field 'insertion_mate_preferences':
                        failures:
                          - HSEARCH400520: Duplicate index field definition: 'lifestyles'. Index field names must be unique. Look for two property mappings with the same field name, or two indexed-embeddeds with prefixes that lead to conflicting index field names, or two custom bridges declaring index fields with the same name.
            path '.matePreferences<no value extractors>.personalities':
                index 'Insertion':
                    field 'insertion_mate_preferences':
                        failures:
                          - HSEARCH400520: Duplicate index field definition: 'personalities'. Index field names must be unique. Look for two property mappings with the same field name, or two indexed-embeddeds with prefixes that lead to conflicting index field names, or two custom bridges declaring index fields with the same name.
        type 'it.friendshome.api.common.model.profile.Profile':
            path '.languages':
                index 'Profile':
                    index schema root:
                        failures:
                          - HSEARCH400520: Duplicate index field definition: 'languages'. Index field names must be unique. Look for two property mappings with the same field name, or two indexed-embeddeds with prefixes that lead to conflicting index field names, or two custom bridges declaring index fields with the same name.
            path '.lifestyles':
                index 'Profile':
                    index schema root:
                        failures:
                          - HSEARCH400520: Duplicate index field definition: 'lifestyles'. Index field names must be unique. Look for two property mappings with the same field name, or two indexed-embeddeds with prefixes that lead to conflicting index field names, or two custom bridges declaring index fields with the same name.
            path '.personalities':
                index 'Profile':
                    index schema root:
                        failures:
                          - HSEARCH400520: Duplicate index field definition: 'personalities'. Index field names must be unique. Look for two property mappings with the same field name, or two indexed-embeddeds with prefixes that lead to conflicting index field names, or two custom bridges declaring index fields with the same name.
        type 'it.friendshome.api.common.model.search.Search':
            path '.matePreference<no value extractors>.languages':
                index 'Search':
                    field 'matePreference':
                        failures:
                          - HSEARCH400520: Duplicate index field definition: 'languages'. Index field names must be unique. Look for two property mappings with the same field name, or two indexed-embeddeds with prefixes that lead to conflicting index field names, or two custom bridges declaring index fields with the same name.
            path '.matePreference<no value extractors>.lifestyles':
                index 'Search':
                    field 'matePreference':
                        failures:
                          - HSEARCH400520: Duplicate index field definition: 'lifestyles'. Index field names must be unique. Look for two property mappings with the same field name, or two indexed-embeddeds with prefixes that lead to conflicting index field names, or two custom bridges declaring index fields with the same name.
            path '.matePreference<no value extractors>.personalities':
                index 'Search':
                    field 'matePreference':
                        failures:
                          - HSEARCH400520: Duplicate index field definition: 'personalities'. Index field names must be unique. Look for two property mappings with the same field name, or two indexed-embeddeds with prefixes that lead to conflicting index field names, or two custom bridges declaring index fields with the same name.

I'm running it with the following dependencies:

Any suggestion on how to manage this scenario?

A: This code is incorrect:
    @GenericField
    @IndexedEmbedded
    private Set<Language> languages;

With @GenericField, you are asking Hibernate Search to generate a "value" field (string, integer, ...) for languages. This generally won't work, because Hibernate Search doesn't know how to convert a Language into a string/integer/..., so that's a first problem.
But the second problem, and the one being reported by Hibernate Search, is that by also putting @IndexedEmbedded on the same property, you are also asking Hibernate Search to generate an "object" (composite) field, with the same name as the "value" field from @GenericField. So there's a conflict: both the "value" field and the "object" field have the same name, "languages".
You should remove @GenericField wherever you use @IndexedEmbedded.

Note that technically, you could use both @GenericField and @IndexedEmbedded on the same property, as long as you explicitly set a different name on either annotation using @GenericField(name = ...) or @IndexedEmbedded(name = ...). But @GenericField would not work unless you use a custom value bridge, and I don't think your intention was to do that anyway. So please don't do that unless you have an actual reason and @IndexedEmbedded does not do what you want.


text:
Q: React-Admin - como que eu passo um id de um ReferenceInput para o filtro de outro ReferenceInput? Estou tentando passar o exampleId que é o valor do primeiro ReferenceInput no filter do outro ReferenceInput, como que eu faço isso?
O segundo precisa ser carregado dinâmico baseado na seleção do de cima
<ArrayInput source="list">
  <SimpleFormIterator>

    <ReferenceInput source="exampleId" reference="Example">
        <SelectInput optionText="name" />
    </ReferenceInput>

    <ReferenceInput source="exampleIdTwo" reference="ExampleTwo" filter={{ id: exampleId }}>
        <SelectInput optionText="name" />
    </ReferenceInput>

  </SimpleFormIterator>
</ArrayInput>

Se eu tento jogar para dentro de um Component para usar com o useState e onChange, acontece isso: resources.undefined.fields.exampleId
const MyComponent  = () => {
  const [exampleId, setExampleId] = useState(null);

  const handleOnChange = (e) => setExampleId(e.target.value);

  return (
          <SimpleFormIterator>

            <ReferenceInput source="exampleId" reference="Example" onChange={handleOnChange}>
                <SelectInput optionText="name" />
            </ReferenceInput>

            <ReferenceInput source="exampleIdTwo" reference="ExampleTwo" filter={{ id: exampleId }}>
                <SelectInput optionText="name" />
            </ReferenceInput>

          </SimpleFormIterator>
  )
}

..
<ArrayInput source="list">
  <MyComponent />
</ArrayInput>

Edit: lib utilizada: https://marmelab.com/react-admin/

A: Consegui resolver.. precisa utilizar o FormDataConsumer
<SimpleFormIterator>
    <ReferenceInput source="exampleId" reference="Example">
        <SelectInput optionText="name" />
    </ReferenceInput>

    <FormDataConsumer >
    {
        ({ getSource, scopedFormData }) => {
        const exampleId = scopedFormData?.exampleId;
        return (
            <ReferenceInput
                source={getSource('exampleIdTwo')}
                reference="ExampleTwo"
                filter={{ id: exampleId }}
            >
                <SelectInput optionText="name" />
            </ReferenceInput>
        )
        }
    }
    </FormDataConsumer>
</SimpleFormIterator>


text:
Q: jqGrid ASP.NET Parent Row Selection and Child Edit Issue I am attempting to use jqGrid ASP.NET for the first time and I'm having an issue with properly using a parent and child grid on my form.
Scenario: On my form I have two grids, one a parent that displays product information, and a second child grid that is used for editing a collection of prices for the product in the parent row. When a user clicks the plus sign in a parent row, the OnDataRequesting event is handled and I load the child grid with that product's prices. When the user clicks a price in the child grid, I use ClientSideEvents RowSelect and the server side RowEditing event to perform inline editing.
All of this was fairly trivial to set up and works great. Where I'm having an issue is that I'd like the selected row in the parent grid to act like a context for the rest of the page, i.e. the rest of the page displays information related to the product selected (charts, graphs, etc). For this I set up an event handler for the OnRowSelecting event and then trap the RowKey from the event args. That works great. However... the unintended side effect of setting up that handler is that once a user selects a row in the child grid to edit, the OnRowSelecting event fires in the parent, the page posts back, and when the page reloads the child grid is closed and the attempted edit is thwarted.
What I would like to know is, is there any built in way to handle this sort of scenario either through the client side jqGrid library or the Trirand.Web library? Or will I need to write some custom script to either send the selected parent row asynchronously or possibly trap the expanded child grid and attempt to reopen it once the post back is complete? Thanks.

A: I thought I'd brush off the tumbleweeds here and inject the answer I finally received from Trirand's support. As of the time of this writing, you can't do this. If you handle the OnRowSelecting event, you cannot use an editable child grid as they built it to specifically fire the parent's OnRowSelecting event anytime you select a row in a child grid.


text:
Q: copying one Array value to another array I have 2 array of object. 1st array of object have property which I want to copy to other array.
1st array of object
HotelRoomResponse[] hr=new HotelRoomResponse[100];

2nd array of object
RateInfos[] rt = new RateInfos[100];

now what i want to do is copy a property of 1st array like
rt=hr[].RateInfo;

but it give error. What is correct way to do this????

A: You can't just project an array like that. You effectively have to loop - although you don't need to do that manually in your own code. LINQ makes it very easy, for example:
RateInfos[] rt = hr.Select(x => x.RateInfo).ToArray();

Or you could use Array.ConvertAll:
RateInfos[] rt = Array.ConvertAll(hr, x => x.RateInfo);

In both of these cases there's still a loop somewhere - it's just not in your code.
If you're quite new to C# and don't understand LINQ, lambda expressions, delegates etc yet, then you could just write the code yourself:
RateInfos[] rt = new RateInfos[hr.Length];
for (int i = 0; i < rt.Length; i++)
{
    rt[i] = hr[i].RateInfo;
}

All of these three will achieve the same result.

*

*The first approach is probably the most idiomatic in modern C#. It will work with any input type, and you can change from ToArray() to ToList() to get a List<RateInfos> instead of an array, etc.

*The second approach is slightly more efficient than the first and will work with .NET 2.0 (whereas LINQ was introduced in .NET 3.5) - you'll still need a C# 3 compiler or higher though. It will only work as written with arrays, but there's a similar ConvertAll method for List<T>.

*The third approach is the most efficient, but obviously more code as well. It's simpler for a newcomer to understand, but doesn't express what you're trying to achieve as clearly when you know how all the language features work for the first two solutions.

A: RateInfos[] rt = hr.Select(item => item.RateInfo).ToArray();

A: Use LINQ:
RateInfos[] rt = hr.Select(x => x.RateInfo).ToArray();


text: Q: How to stream audio from iOS to IIS web server I'd like to stream audio from multiple iOS clients to a central Windows server running IIS 7 for further processing. IIS Media Services seems to be the solution for the opposite problem, of distributing audio from IIS, are there existing libraries for streaming audio to IIS? Or do I have to write, say a WCF TCP service myself? (I'll need to send status messages back to the client, so duplex TCP seems the way to go.)


text:
Q: Kubernetes: Having same host name but different paths in ingresses in different namespaces in Kubernetes I want to use the same hostname e.g. example.com in two different namespaces with different paths. e.g. in namespace A I want example.com/clientA and in namespace B I want example.com/clientB. Any ideas on how to achieve this?

A: nginxinc has Cross-Namespace Configuration feature that allows you do exactly what you described.
You can also find there prepared examples with deployments, services, etc.
The only thing you most probably wont like..nginxinc is not free..
Also look here

Cross-namespace Configuration You can spread the Ingress configuration
for a common host across multiple Ingress resources using Mergeable
Ingress resources. Such resources can belong to the same or different
namespaces. This enables easier management when using a large number
of paths. See the Mergeable Ingress Resources example on our GitHub.
As an alternative to Mergeable Ingress resources, you can use
VirtualServer and VirtualServerRoute resources for cross-namespace
configuration. See the Cross-Namespace Configuration example on our
GitHub.

A: If you do not want to change your default ingress controller (nginx-ingress), another option is to define a service of type ExternalName in your default namespace that points to the full internal service name of the service in the other namespace.
Something like this:
apiVersion: v1
kind: Service
metadata:
  labels:
    app: my-svc
  name: webapp
  namespace: default
spec:
  externalName: my-svc.my-namespace.svc # <-- put your service name with namespace here
  type: ExternalName


text:
Q: What is the difference between = and - in haml while writing ruby code? So I am a newbie at HAML.
While going through the HAML tutorial the way to represent ruby code was mentioned as =
eg: %strong= item.title
but when I ran this code:
= @list.documents.each do |doc|
  %tbody
    %tr
      %td= doc.display_name

along with all the list data which was displayed there was also alot of junk data displayed which was related to the actual list data which was displayed.
This is what I got:
val1 val2 val3 [#Document......@id : val1, @id:val2.....]

When i try the same code while replacing the = with a - the unwanted data is not received.
- @list.documents.each do |doc|
      %tbody
        %tr
          %td= doc.display_name

output:
val1 val2 val3

can someone explain the difference between  - and = while writing ruby code in haml?

A: They are both indicators that what follows needs to be processed as Ruby code. But - doesn't output the result to view whereas = does.
For example, consider the following helper:
def hlp
  [1,2].each(&:succ) # using example relevant to your code sample
end

each will return the enumerator that it is called upon. So the return value of that helper method will be [1,2].
The following in your HAML view will not display [1,2]:
- hlp

But the following will display it:
= hlp

Therefore in the sample code you have shared, you will use -, and not =, because you don't want to display all @list.documents once each is done with them.

A: In haml
= is used to write ruby code and displays the result as output
Where as - is used to write ruby code within haml and no output is diplayed.
You can read more about haml from this
http://haml.info/tutorial.html


text:
Q: How to Pivot using Python (Columns not fixed/Columns Dynamic ) How should I pivot the below data frame?
Dataframe value as below:
VNOTIFY ITEM    VALUE
820001  00001   5089571
820001  00002   5089580
820102  00001   5089491
820102  00001   5089492
820102  00001   5000133
820103  00001   5000137

to
VNOTIFY ITEM   VALUE1  VALUE2 VALUE3
820001  00001  5089571
820001  00002  5089580
820102  00001  5089491 5089492 5000133
820103  00001  5000137

df.pivot_table(index=['VNOTIFY','ITEM'], columns=['VNOTIFY','ITEM'], values='VALUE',aggfunc='first')

Didn't work
VNOTIFY ITEM   VALUE1  VALUE2 VALUE3
820001  00001  5089571
820001  00002  5089580
820102  00001  5089491 5089492 5000133
820103  00001  5000137


text:
Q: Where is the ClipboardContent class in JAVA? Though a Java novice, I managed to import plain text from the clipboard (sourced in Excel). It looks like the ClipboardContent class would allow me to import formatted text (html, xml...) but my attempts so far always result in "class not found" for any reference to ClipboardContent.
I suspect there's an import (or full reference) that will fix this but my references and on-line searches have not been fruitful so far.
I'll appreciate any clues I can get.

A: Java has some pretty great documentation online.
here is where you can find anything about that you could need that has to do with basic java's classes.  I recommend going here using a ctrl+F for whatever class you need and click on it.  on that page it will give you everything you need to know about it.

A: javafx clipboardcontent api
Make sure you import "javafx.scene.input.ClipboardContent" (assuming this is what you need).
Just a FYI - you can run into cases were you find similar or identical named classes in other packages.  If you are using Eclipse IDE, you can hover over an class object and it will provide you a hint on where to import it from if Eclipse has those dependencies.  If it doesn't have it, then you will need to add that dependency (like a jar file) and add it as part of your library.


text:
Q: Pegar valor em laço Javascript/Jquery Como posso imprimir o valor de cada alt no for?

A: Já que está usando jQuery, poderia usar o .each():

$(".pai .filho").each(function(){
   var teste = $("img", this).attr("alt");
   console.log(teste);
});

O código $("img", this).attr("alt") irá buscar em cada elemento .filho dentro de .pai a tag img e seu respectivo atributo alt.

A: O problema é que, com a linha abaixo:

 var teste = $(elementos[i].className).attr('alt');

Você está selecionando a div em que a imagem está contida. Logo, quando você captura o atributo alt desse elemento, você não recebe nada, já que a div não possui atributo alt.
Logo, você poderia corrigir o código selecionando as imagens:
var elementos = $('.pai .filho > img');

Ficando assim:

Se você quiser buscar o elemento filho dentro do laço for, pode fazer assim:

var elementos = $('.pai .filho');
var countElementos = elementos.length;
var intervalo = 1;
var comeco = 0;

for(var i = comeco; i < countElementos; i += intervalo) {
    // Note abaixo que adicionei o "children".
    // Também removi o `className`, já que o `elementos[i]` já é suficiente para que o jQuery reconheça o elemento:
    var teste = $(elementos[i]).children('img').attr('alt');
    console.log(teste);
}


text:
Q: Make sure you invite Jill herself(,)  [The syntactic function of 'too' and usage of comma] The Cambridge Grammar of the English Language (Pages 438-9) has this:

An NP may contain more than one peripheral modifier, with multiple layers of embedding:
[8] i Make sure you invite [Jill herself too].
The bracketed NP in [i] has the NP Jill herself as head and the adverb too as peripheral modifier; at the next level, the NP Jill is head and the NP herself is peripheral modifier. A peripheral modifier is thus in peripheral position (initial or final) in the NP of which it is an immediate constituent, but need not be in peripheral position in a larger NP containing it.

I think traditional grammar would treat too in [i] as an adverb modifying the verb invite or the VP invite Jill herself.
Which analysis would you think is correct, and why?
EDIT
Is CGEL's analysis of the too as part of the bracketed NP attributable to the lack of a comma right before it?
I'm asking this because if I had intended the too to be modifying the verb or the VP, I would have put a comma there:

Make sure you invite Jill herself, too.

If so, does this mean that the lack of a comma there makes the traditional grammar reading less likely or even impossible? (Although I think comma usage is not strictly followed.)