text:
Q: Passing Objekt to JqueryPlugin and iterates through them I wrote a Jquery Calendar Plugin.
Now I want to learn to Pass Parameter to it, to change the View of the calendar.
$.kalender({element: "#Clock", property: "display", value: "none"},{element:"#MainDiv", property:"width" ,value:"500px"});

these are my objects that im passing to my Plugin.
;(function (namespace, $) {
$.extend({
    kalender: function (options) {

        //Use Parameter

        if (options !== undefined) {
            $.each(options, function () {
                $(options.element).css(options.property, options.value);
            });
        }

Jquery always just takes the first object.(So the Plugin doesn't display the clock). What am I doing wrong?

A: You never access the iteratee object in your $.each function. The code should be:
 $.each(options, function (index, option) {
        $(option.element).css(option.property, option.value);
    });

And when you call it should be:
$.kalender([{element: "#Clock", property: "display", value: "none"},{element:"#MainDiv", property:"width" ,value:"500px"}]);

Hope this helps.


text:
Q: Why isn't two-spaced YAML parsed like four-spaced YAML? I'm seeing strange behavior when parsing YAML (using Ruby 2.5/Psych) created using two space indentations. The same file, indented with four spaces per line works -- to my mind -- as expected.
Two spaces:
windows:
  - shell:
    panes:
      - echo hello

results in the following hash:
{"windows"=>[{"shell"=>nil, "panes"=>["echo hello"]}]}

Whereas using four space indentations:
windows:
    - shell:
        panes:
            - echo hello

results in:
{"windows"=>[{"shell"=>{"panes"=>["echo hello"]}}]}

I just skimmed through the spec and didn't see anything relevant to this issue.
Is this behavior expected? If so, I'd greatly appreciate links to resources explaining why.

A: The trouble is that you cannot simply replace every two spaces with four spaces.  That is because in this pair of lines:
  - shell:
    panes:

these two spaces in the second line:
    panes:
  ^^

Are an abbrevation for the "- " in the line above.  If the second line were not abbreviated, then the pair of lines would be:
  - shell:
  - panes:

So when doubling the indentation, the second of these line should only have its first pair of spaces doubled, not the second.  That would yield the correct indentation for the pair:
    - shell:
      panes:

So, if you only expand the first pair of spaces in the "panes:" line, you get:
windows:
    - shell:
      panes:
          - git status

Which correctly parses to the expected result.

A: While Wayne's solution is correct, the explanation seems a bit off, so I'll throw in mine:
In YAML, the - for block sequence items (like ? and : for block mappings) is treated as indentation (spec):

The "-", "?" and ":" characters used to denote block collection entries are perceived by people to be part of the indentation. This is handled on a case-by-case basis by the relevant productions.

Moreover, all block collections (sequences and mappings) take their indentation from their first item (since there is no explicit starting indicator). So in the line - shell:, the - defines the indentation level of the newly started sequence, while at the same time, shell: defines the indentation level of the newly started mapping, which is the content of the sequence item. Note how the - is treated as indentation for defining the indentation level of the mapping.
Now, revisiting your first example:
windows:
  - shell:
    panes:
      - echo hello

panes: is on the same level as shell:. This means that YAML parses it as key of the mapping started by shell:, meaning that the key shell has an empty value. Mapping values of implicit keys, if not on the same line, must always be indented more than the corresponding mapping key (spec):

The block node's properties may span across several lines. In this case, they must be indented by at least one more space than the block collection, regardless of the indentation of the block collection entries.

OTOH, in the second example:
windows:
    - shell:
        panes:
            - echo hello

panes: is on a deeper indentation level compared to shell:. This means that it is parsed as value of the key shell and thus starts a new, nested block mapping.
Finally, mind that since - is treated as part of the indentation, "indenting by two spaces" could also mean this:
windows:
- shell:
    panes:
    - echo hello

Note how the - are not more indented than their mapping keys. This works because the spec says:

Since people perceive the "-" indicator as indentation, nested block sequences may be indented by one less space to compensate, except, of course, if nested inside another block sequence (block-out context vs. block-in context).

redpajama_set_name: RedPajamaStackExchange


text:
Q: c++ :std::bad_alloc when passing class object as a parameter i am trying to pass class object as  a parameter gameobject
but i am getting this error
ERROR:
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
this is some code :
vector<gameobject*> objects;

void addObject(gameobject* object)
    {
        objects.push_back(object);
    }
// in another class

gameobject* pla = new player(32,32);

hand->addObject(pla); //  the function above ----> here i get the error

thank you
edit :
the error is when i call the function it doesn't even enter it


text:
Q: iterate over pyspark Dataframe and then for each row interact with mongoDB I have a pyspark Dataframe and now i want to iterate over each row and insert/update to mongoDB collection.
 #Did every required imports
 #dataframe
 +---+----+
 |age|name|
 +---+----+
 | 30|   c|
 |  5|   e|
 |  6|   f|
 +---+----+
  db = mongodbclient['mydatabase']
  collection = db['mycollection']
  #created below function to insert/update
  def customFunction(row):
      key = {'name':row.name}
      data = dict(zip(columns,[row.x for x in columns]))
      collection.update(key, data, {upsert:true})
      #return a_flag #commented it as of now, a_flag can be 0 or 1

If a name exist in the mongoDB collection 'mycollection' it should update that row/record else insert that new record.
i am getting following error when tried to map this function over spark-dataframe
 result = my_dataframe.rdd.map(customFunction)
 #.....TypeError: can't pickle _thread.lock objects....
 #AttributeError: 'TypeError' object has no attribute 'message'

Can anybody please figure out 'what is wrong here in that function and/or anywhere else' or please suggest if any other alternative is there to this type of task.
Basically iterate each row(without a collect call is that even possible??)
And, on each row apply  a function to run outside-spark work.
Please suggest, Thanks in Advance..:)
My data in mongoDB
name  age
 a    1
 b    2
 c    3 #new update should make age as 30 and 2 more new recs should inserted

A: It looks like connection object cannot be pickled. I'd use foreachPartition:
def customFunction(rows):
    db = mongodbclient['mydatabase']
    collection = db['mycollection']

    for row in rows:
        key = {'name':row.name}
        data = dict(zip(columns,[row.x for x in columns]))
        collection.update(key, data, {upsert:true})

my_dataframe.rdd.foreachPartition(customFunction)

but keep in mind that fatal failure might leave the database in inconsistent state.

A: If you have 500k records to be upserted in MongoDB the bulk mode will be probably more efficient way to handle this. Executing requests inside mongoDB will require much more power compared to what you actually do in spark (just creating requests) and even executing this in parallel may cause instabilities on mongo side (and be slower than "iterative" approach).
You can try the following code. It does not use collect(), so it's memory efficient on driver:
bulk = collection.initialize_unordered_bulk_op()
for row in rdd.toLocalIterator():
    key = {'name':row.name}
    data = dict(zip(columns,[row.x for x in columns]))
    bulk.update(key, data, {upsert:true})

print(bulk.execute())


text:
Q: How can I reference part of a file name in a FOR loop? Trying to mux video and audio using FFMPEG and a FOR loop.  I have a folder full of files that look like this
movie1_audio.m4a
movie1_video.mp4
movie2_audio.m4a
movie2_video.mp4

I need a way to only reference everything before the underscore, rather than the whole file name. The below script looks for a matching .mp4 and .m4a file with identical names to match together.  I'm trying to modify it to look for files that have identical names before the underscore.
FOR %%A IN (*.mp4) DO (
    ffmpeg -i "%%~nA.mp4" -i "%%~nA.m4a" -vcodec copy -acodec copy -movflags faststart "output\%%~nA.mp4"
)

I know I can batch rename my files to solve this easily, but if there's a way to only look at the first part of the filename in batch, I think that knowledge may be useful in future projects.  Thanks!

A: You just need another nested FOR command that utilizes a few of its options. I don't know how you need to fit into your FFMPEG command so I am leaving that up to you.
@echo off
FOR %%A IN (*.mp4) DO (
    FOR /F "tokens=1,* delims=_" %%G IN ("%%~A") DO (
        REM %%G will be the file name before the underscore.
        REM %%H will be everything after the underscore
        ffmpeg ......
    )
)


text:
Q: Nagios could be support on a google cloud instances? I'm trying to install Nagios in GCP Linux instances, I have a curiosity, it will work in GCP or not?

A: You can install any legitimate software in a GCP instance. Before installing any software, it is advisable to check that you are not violating any ToS of Google Cloud Platform.
In your case, you could be able to install and run 'Nagios' in a GCP instance with out any issue. But, make sure that your 'instances' have met the system requirements for the particular software as well. (For Nagios XI, the system requirements are mentioned here.)


text:
Q: Angular Slider snap to value I'm having some trouble figuring out how to make snap spots to different values inside the slider in Angular. Slider:
<mat-slider
        min="0" max="90" step="1" tickinterval="auto" thumbLabel (input)="positionChanged(component, 'north.dx', $event.value)" (input)="positionChanged(component, 'north.dy', $event.value)"
></mat-slider>

I need to have three snap spots: [33, 45, 90].
Link to documentation: Angular mat-slider
Is there a way to do this inside the html? I hope someone is able to help me. Thanks in advance!

A: HTML:
    <mat-slider #screen
      thumbLabel
      [displayWith]="formatLabel"
      tickInterval="1000"
      min="1"
      max="100000"></mat-slider>

In component.ts:
import { Component } from "@angular/core";

@Component({
  selector: "slider-formatting-example",
  templateUrl: "slider-formatting-example.html",
  styleUrls: ["slider-formatting-example.css"]
})
export class SliderFormattingExample {
  @ViewChild('screen') screen: ElementRef;
  @ViewChild('canvas') canvas: ElementRef;
  @ViewChild('downloadLink') downloadLink: ElementRef;
  formatLabel(value: number) {
    if (value >= 1000) {
      console.log(value); // Your slider value is here
      if (value === 33) {
       html2canvas(this.screen.nativeElement).then(canvas => {
         this.canvas.nativeElement.src = canvas.toDataURL();
         this.downloadLink.nativeElement.href =
         canvas.toDataURL('image/png');
         this.downloadLink.nativeElement.download = '33.png';
         this.downloadLink.nativeElement.click();
       });

      } else if (value === 45) {
      html2canvas(this.screen.nativeElement).then(canvas => {
         this.canvas.nativeElement.src = canvas.toDataURL();
         this.downloadLink.nativeElement.href =
         canvas.toDataURL('image/png');
         this.downloadLink.nativeElement.download = '45.png';
         this.downloadLink.nativeElement.click();
       });
      } else if (value === 90) {
       html2canvas(this.screen.nativeElement).then(canvas => {
          this.canvas.nativeElement.src = canvas.toDataURL();
          this.downloadLink.nativeElement.href =
          canvas.toDataURL('image/png');
          this.downloadLink.nativeElement.download = 'marble-diagram.png';
          this.downloadLink.nativeElement.click();
       });
      }
      return Math.round(value / 1000) + "k";
    }
    return value;
  }
}

Please find the working stackblitz answer here. Now along with it you need to have the html2canvas library installed in the project Please find html2canvas here. Its fairly straight forward to take snapshot in it. I'll share the stackblitz sample of taking snapshot with you here. What you need to do is programmtically take the snapshot if it is the having the value of 33,45,90 which I have done in the relevent if and else if blocks in the answer.


text:
Q: regular expression replace '1-3' format with 'from 1 to 3' format I am inexperienced with regular expressions and need to know the following:
I have a sentence:

"Repeat these steps 1-3 times and read the chapters 10-12 followed by 100-150 push-ups"

How do I replace this with:

"Repeat these steps from 1 to 3 times and read the chapters from 10 to 12 followed by from 100 to 150 pushups"

So the regular expression that I tried to use to identify the format 'digit-digit' is as follows:
r'\d\D\d'

where the \d's represent single digits and the \D represents a non-digit.
But this only identifies the '1-3'... how can I get a regex that will take any number from 1-1000 and then the hyphen?
Overall how do I replace any number followed by a hyphen with the 'from to' format shown above?

A: You can use \d+ to match more than one digits, here + means one or more; And then you can capture the digits pattern with parenthesis, use back reference to reformat the pattern the way you need:
import re
re.sub(r"(\d+)-(\d+)", r"from \1 to \2", "Repeat these steps 1-3 times and read the chapters 10-12 followed by 100-150 push-ups")
# 'Repeat these steps from 1 to 3 times and read the chapters from 10 to 12 followed by from 100 to 150 push-ups'

A more strict quantifier than + might be {1,4} which matches one to four digits as commented by @NolenRoyalty. so you can use (\d{1,4})-(\d{1,4}) as well depending on your need.

A: You have to add a quantifier like + which means 1 to * times.
r'\d+\D\d+'
Or as @Nolen Royalty suggested use  {1,4} like r'\d{1,4}\D\d{1,4} so you just allow 1 to 4 digits


text:
Q: Is there any method to append the value to the list in JSON file (Python)? My exercise idea is to append new value from the input prompt to the list. Instead of adding new value, my list in JSON file always give the newly inputted value.
    import json

    file = 'database.json'

    namelist = []
    name = input("Enter your name:\n")

    with open(file, 'w') as file_object:
        namelist.append(name)
        json.dump(namelist, file_object)

A: with open('database.json', "r+") as file_object:
    data = json.load(file)
    # data.update(your_dict) or data.append(new_data)
    file.seek(0)
    json.dump(data, file)


text:
Q: Installing e text editor I am trying to get e-text editor to run. I read http://www.e-texteditor.com/forum/viewtopic.php?p=14953#14953 and Compile e-text editor on Linux as well. But on my 10.04 Lucid it fails at the following step:
./build_externals_linux.sh debug
with the following error messages:
Building debug binaries
Building 32-bit binaries
Going to place output in /opt/etexteditor/external/out.debug
./build_externals_linux.sh: line 41: pushd: bakefile: No such file or directory
./build_externals_linux.sh: line 42: ./configure: No such file or directory
Cannot compile bakefile
./build_externals_linux.sh: line 46: popd: directory stack empty
./build_externals_linux.sh: line 49: pushd: metakit: No such file or directory
./build_externals_linux.sh: line 50: cd: builds: No such file or directory
Cannot compile MetaKit
./build_externals_linux.sh: line 56: popd: directory stack empty
./build_externals_linux.sh: line 59: pushd: pcre: No such file or directory
./build_externals_linux.sh: line 60: ./configure: No such file or directory
Cannot compile pcre
./build_externals_linux.sh: line 66: popd: directory stack empty
./build_externals_linux.sh: line 69: pushd: tinyxml: No such file or directory
make: *** No rule to make target `clean'.  Stop.
cannot compile TinyXML
./build_externals_linux.sh: line 77: popd: directory stack empty
./build_externals_linux.sh: line 80: pushd: libtommath: No such file or directory
make: *** No rule to make target `clean'.  Stop.
Cannot compile LTM
./build_externals_linux.sh: line 85: popd: directory stack empty
./build_externals_linux.sh: line 88: pushd: libtomcrypt: No such file or directory
make: *** No rule to make target `clean'.  Stop.
Cannot compile LTC
./build_externals_linux.sh: line 93: popd: directory stack empty
./build_externals_linux.sh: line 96: pushd: wxwidgets: No such file or directory
./build_externals_linux.sh: line 97: ./configure: No such file or directory
Cannot compile wxWidgets
./build_externals_linux.sh: line 104: popd: directory stack empty
./build_externals_linux.sh: line 107: pushd: webkit: No such file or directory
make: *** No rule to make target `clean'.  Stop.
./build_externals_linux.sh: line 109: ./WebKitTools/Scripts/build-webkit: No such file or directory
Cannot compile WebKit
./build_externals_linux.sh: line 113: popd: directory stack empty

what am I missing?

A: You need to install bakefile, there is no package from the official repositories, try: http://www.bakefile.org/wiki/Debian

A: *

*install bakefile from sources

*try compiling from latest in http://github.com/tea/e branch

A: Which source files are you using?
Appears to be answered at:
https://stackoverflow.com/questions/2404998/compile-e-text-editor-on-linux
suggests to use:
https://github.com/ajpalkovic/e/tarball/linux


text:
Q: Protocol violation using Github api I'm getting data from Github for my application.
The first 2 OAuth steps are ok, but in the third I got the following error:
"the server committed a protocol violation. Section=ResponseStatusLine ERROR"
This is my code:
protected String WebRequest(string url)
    {
        url += (String.IsNullOrEmpty(new Uri(url).Query) ? "?" : "&") + "access_token=" + _accessToken;
        HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
        webRequest.Method = "GET";
        webRequest.ServicePoint.Expect100Continue = false;
        try
        {
            using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
                return responseReader.ReadToEnd();
        }
        catch
        {
            return String.Empty;
        }
    }

The program goes in exception after using the StreamReader object, that returns me the error.
If I follow these instructions The server committed a protocol violation. Section=ResponseStatusLine ERROR , the error turns into "403 forbidden".
When Github used api V2, different from now, there was no problem with this code.
So, can't be a .NET limitation but something connected with Github server.
Any suggestions?

A: You need to set UserAgent like this:
webRequest.UserAgent = "YourAppName";

Otherwise it will give The server committed a protocol violation. Section=ResponseStatusLine error.


text:
Q: Unable to checkout multiple repositories to a single directory Following is the playbook that I'm trying to run.
---
- hosts: all
  sudo : true
  sudo_user : ganesh

  tasks:
  - name: git repo clone
    git: repo=https://ganesh:mypassword@github.com/myrepo/root-repo.git dest=/home/ganesh/rootrepo version=master recursive=no
    git: repo=https://ganesh:mypassword@github.com/myrepo/subrepo1.git dest=/home/ganesh/rootrepo/subrepo1 version=master recursive=no
    git: repo=https://ganesh:mypassword@github.com/myrepo/subrepo2.git dest=/home/ganesh/rootrepo/subrepo2 version=master recursive=no
    git: repo=https://ganesh:mypassword@github.com/myrepo/subrepo3.git dest=/home/ganesh/rootrepo/subrepo3 version=master recursive=no

I'm expecting the following directory structure after running this playbook.

rootrepo
    - root repo contents
    - subrepo1
        - subrepo1 contents
    - subrepo2
        - subrepo2 contents
    - subrepo3
        - subrepo3 contents

But there is only one repo,i.e.,subrepo3, remaining under rootrepo directory after the playbook is executed. Everything else is getting deleted. Even rootrepo contents are getting deleted.

rootrepo
    - subrepo3
        - subrepo3 contents

Why is it so? How can achieve the directory structure that I'm expecting?

A: The explanation as to why this isn't working as exepected is that Ansible plays are read in as yaml files and "tasks" is a list of dictionaries.  In your case you are duplicating the module "git" (a key in the dictionary) so the last one wins.
To do exactly what you want the following play will work
---
- hosts: all
  sudo : true
  sudo_user : ganesh

  tasks:
  - name: git repo clone
    git: repo=https://ganesh:mypassword@github.com/myrepo/root-repo.git dest=/home/ganesh/rootrepo version=master recursive=no
  - name: clone subrepos
    git: repo=https://ganesh:mypassword@github.com/myrepo/{{ item }}.git dest=/home/ganesh/rootrepo/{{ item }} version=master recursive=no
    with_items:
      - subrepo1
      - subrepo2
      - subrepo3

In general though, it is not a good idea to have repositories checked out in other repositories.
More likely what you want to do is add subrepo{1,2,3} as submodules to root-repo.
Assuming you have commit access to your root repo clone it and then run.
git submodule add https://ganesh:mypassword@github.com/myrepo/subrepo1.git subrepo1
git submodule add https://ganesh:mypassword@github.com/myrepo/subrepo2.git subrepo2
git submodule add https://ganesh:mypassword@github.com/myrepo/subrepo3.git subrepo3

Check in those changes and then in your play set recursive=true when you checkout root-repo.git


text:
Q: Why calling a function inside a Python class __init__ can be both Attribute and Method? I am quite confused with the method and attribute of a Python class. Suppose we have a Python class like this:
# case 1
class Person:

    def __init__(self, first, last):

        self.first = first
        self.last = last
        self.fun()

    def fun(self):
        value = self.first + '---' + self.last
        self.fun = value
        return value

person_1 = Person('A', 'B')
person_1.fun

---> "A---B"

As we can see, in case_1 we initialize an instance person_1. And we can get the result we want by calling fun as an attribute. However, if we change our code to the following, fun becomes a method instead.(case_2)
# case 2
class Person:

    def __init__(self, first, last):

        self.first = first
        self.last = last
        self.fun()

    def fun(self):
        value = self.first + '---' + self.last
        return value

person_1 = Person('A', 'B')
person_1.fun

---> <bound method Person.fun of <__main__.Person object at 0x7fd4f79168d0>>

We still contain the init process in the class. But now fun becomes a method but not an attribute. (case_2)
If we remove the self.fun() in init but keep the self.fun = value, it is still a method. (case_3)
# case 3
class Person:

    def __init__(self, first, last):

        self.first = first
        self.last = last

    def fun(self):
        value = self.first + '---' + self.last
        self.fun = value
        return value

person_1 = Person('A', 'B')
person_1.fun

---> <bound method Person.fun of <__main__.Person object at 0x7fd4f797f390>>

Would you mind giving me some instructions about why this happens? And what is the proper way to use the function as an attribute inside a Python Class? Thank you so much in advance!

A: In case 1, your constructor calls fun() which has a line inside of it to overwrite itself with an attribute value. This is confusing and not a good thing to do because it is confusing.
In case 2, your fun method does not include the line to overwrite itself so it doesn't get overwritten.
In case 3, you never actually call your fun method so it never has a chance to overwrite itself. If you called it with person_1.fun() i.e. with parentheses, then it would execute and overwrite itself and from that point on, person_1.fun would be an attribute value.
Remember that in python, a function/method ONLY executes if it is called with parentheses. If you don't express it with parentheses, then the result of evaluation is not the output of the function, but instead the expression produces a reference to the function itself, which can be put in another variable or in a data structure and called later.
To illustrate this:
>>> def my_func():
...     print('got called')
...     return 42
...
>>> x = my_func #no parentheses, x becomes an alias to my_func
>>> y = my_func()  #parentheses means actually execute
got called
>>> y
42
>>> x
<function my_func at 0x765e8afdc0>
>>> x()  #x is a reference to my_func and can be called itself
got called
42
>>>

A: Aha, I think I figure it out!
In case 1, we simply run the function fun() when we init the instance. And because it defines the attribute self.fun = value inside the fun(), hence fun can be used as an attribute. (It cannot be used as the method anymore, because it has been replaced as an attribute.)
In case 2, we only call and run this function. But fun is not been defined as an attribute inside the class. That's why it remains as a method.
In case 3, fun is a method, but in this method, we define an attribute fun. Hence we can first init an instance, then run the function fun. After that, the attribute fun is added to this instance, and then we can call it as person_1.fun.


text:
Q: How to reduce MacOS X Leopard footprint?
Possible Duplicate:
What do you remove from a default os x install?

Hello.
Is it any guides available how to reduce an HDD space occupied by Mac OS X? Languages i don't use etc.

A: For languages that you no longer uses and have no plan of using again you can use the following software: Monolingual
It frees up a few gigabytes of space.
You can also see what is using up all your space by using a program called Disk Inventory X
You could also upgrade to Snow Leopard which gets rid of 10-20GB of bulk that Leopard takes up. I only recommend this if you have no customization on your system because it will break these installs.


text:
Q: terminal stuck at "login" - blank screen (after installing oh-my-zsh, I think) (I originally posted this on apple.stackexchange but then I found this one which is probably a better place)
I have a big problem. I've freshly installed mac os and was setting up my terminal. I installed iTerm, zsh and oh-my-zsh (following this tutorial, basically: https://medium.com/ayuth/iterm2-zsh-oh-my-zsh-the-most-power-full-of-terminal-on-macos-bdb2823fb04c)
After installing oh-my-zsh, I got this error message (this is just a random question showing that same error message):
https://stackoverflow.com/questions/61554566/how-to-avoid-bunch-of-oh-my-zsh-messages-showing-whenever-i-open-iterm-termi
I remember that the fix to this was running the suggested command (I've done this a few years ago):
compaudit | xargs chmod g-w,o-w
I think that was the last thing I did. Now every time I start a terminal (either Mac OS' Terminal or iTerm, doesn't matter) it gets stuck at "login" with a blank screen. I don't get any input prompt.
Even worse, I can't even shut down the mac anymore. When I click on shut down or restart, every app is closed and I see my wallpaper and nothing happens. I have to kill it via the power button.
After restarting, the terminal works perfectly again until I close it with CMD-q. Once I reopen it, it's stuck again at "login".
I've looked everywhere and can't find a solution.
I've seen this question (https://apple.stackexchange.com/questions/267668/terminal-login-hangs) but it didn't help. I tried almost everything proposed there.
I would greatly appreciate any help or thoughts on this.
Also, it works when I boot into safe mode. There, everything is fine.

A: Without being able to reproduce your issue, I cannot assert that this will fix it, but I'll put this out as something to try.
I suggest you try making the following configuration modification to iTerm2:

*

*Go to Preferences, then the Profiles tab at the top, then the General sub-tab

*Select your profile on the left, likely Default

*On the right, find the Command drop-down; it likely currently says "Login Shell"

*Change the Command to "Command"

*Enter the command /bin/zsh --login
With that configuration in place, close iTerm2 and then start it again.  Does that yield a working environment?  If not, do you see any error messages?
If that doesn't help, then I suggest you rename ~/.zshrc to something else (there's some way to get Finder to show dot files, but I don't remember how off the top of my head).  Then try again.
If none of the above helps, you might try switching your shell to bash long enough to debug the problem.  You'd follow the steps above, but change /bin/zsh --login to /bin/bash --login, then restart iTerm2.

A: The problem is caused by iTerm having problems with the first beta version of Mac OS Big Sur. A specific setting causes the problems I've experienced. See https://gitlab.com/gnachman/iterm2/-/issues/8965 for details.
Until fixed, the workaround is this (taken from the GitLab issue):

Workaround:
Disabling Enable session restoration under Preferences > Advanced > Session resolves prevents the hang ups, albeit with the obvious loss of functionality.

Note: A computer restart may be required before this change takes effect.


text:
Q: Convert JSON Array to display in Android List View with multiple items I am trying to display a ListView of Items in Android from JSONArray that is given below
{"myArray":[{"id":"816","name":"Shopping","uid":"20"},{"id":"817","name":"Grocery","uid":"20"},{"id":"818","name":"Entertainment","uid":"20"},{"id":"819","name":"Maid\/Driver","uid":"20"}]}

I want to display these in Listview as given below
816 Shopping 20
817 Grocery 20
818 Environment 20
819 Maid\/Driver 20

This is the java code am working on
    JSONArray the_json_array = jObj.getJSONArray("myArray");

    List<String> list = new ArrayList<String>();
    for (int i=0; i<the_json_array.length(); i++) {
        list.add( the_json_array.getString(i) );
    }
    String[] stringArray = list.toArray(new String[list.size()]);

    final ArrayAdapter adapter = new ArrayAdapter<String>(TransactionCategory.this,android.R.layout.simple_list_item_1,stringArray);
    ListView listView = (ListView) findViewById(R.id.listView2);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
     @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

     // my actions on list items
    }
  });

I am having trouble with the for loop
I just need to get values to each item in ListView.

A: Try to use Gson to parse the json like in the code below:
public class Item {

    @SerializedName("id")
    private String id;

    @SerializedName("name")
    private String name;

    @SerializedName("uid")
    private String uid;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return id + " " + name + " " + uid;
    }
}

public class ItemList {

    @SerializedName("myArray")
    private List<Item> items;

    public List<Item> getItems() {
        if (items == null) {
            items = new ArrayList<>();
        }

        return items;
    }

}

Then change your code:
...

Gson gson = new Gson();
ItemList itemList = gson.fromJson(jObj, ItemList.class);

final ArrayAdapter adapter = new ArrayAdapter<Item>(TransactionCategory.this,android.R.layout.simple_list_item_1, itemList.getItems());
ListView listView = (ListView) findViewById(R.id.listView2);
listView.setAdapter(adapter);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // my actions on list items
    }
}

...


text:
Q: Un-nesting a nested SQL query I am new to building sql queries and could use some help. I built a query that works fine as a standalone query. The problem is I need to use it in a report using ExecuteScalar function and nested queries are not allowed, I tried to rebuild using joins but I seem to be lost.
Can anyone help me "un-nest" this query?
SELECT
StockType2Job.Loaded
FROM
  StockType2Job
WHERE
  StockType2Job.IdStockType =
  (SELECT StockType.IdStockType
  FROM StockType
  WHERE StockType.Number = '1001716.00')
AND
  StockType2Job.IdStockType2JobGroup =
  (SELECT StockType2JobGroup.IdStockType2JobGroup
  FROM StockType2JobGroup
  WHERE StockType2JobGroup.IdJob =
          (SELECT Job.IdJob
          FROM Job
          WHERE Job.Number = '18-0085.02'
          AND StockType2JobGroup.Caption = 'Breakout Room 1'))

Any help appreciated. Thanks

A: this query should work(on Oracle DB):
SELECT
   StockType2Job.Loaded
FROM
   (((StockType2Job a JOIN StockType b ON a.IdStockType=b.IdStockType)
      JOIN StockType2JobGroup c ON a.IdStockType2JobGroup=c.IdStockType2JobGroup)
        JOIN Job d ON c.IdJob=d.IdJob)
WHERE
   b.Number = '1001716.00' AND
   d.Number = '18-0085.02' AND
   c.Caption = 'Breakout Room 1'


text:
Q: AppFabric: Large cluster slow to respond compared with small cluster I am using AppFabric for caching on my website. We have recently added more hosts to the cache cluster and since it is likely that we will be adding more in the [medium] future, we decided to reconfigure the cluster as a large cluster rather than small. We are now seeing some troubling side affects of this - namely AppFabric takes a long time to come back up after a restart.
OK, so if you have got this far, I have got your attention and I can tell you the full story :O). AppFabric always took a long time to come back up after a restart, but we were able to configure and code for this so that our users saw no adverse affects. In web.config we have:
<dataCacheClient channelOpenTimeout="5" requestTimeout="1000" >
    <!-- cache host(s) -->
    <hosts>
        <host name="localhost" cachePort="22233"/>
    </hosts>
</dataCacheClient>

Which (unless I've misunderstood the documentation) will cause the AppFabric client to throw an exception if it doesn't receive a response within 1 second. In our code, we handle this and fall back to reading the data we are attempting to read directly from the database:
public object Get(object key)
{
    if ( key == null )
    {
        return null;
    }

    try
    {
        return cache[key.ToString()];
    }
    catch ( CacheException ex )
    {
        if ( ex.ErrorCode == DataCacheErrorCode.ConnectionTerminated || ex.ErrorCode == DataCacheErrorCode.RetryLater || ex.ErrorCode == DataCacheErrorCode.Timeout )
        {
            // Calling code should try reading from the database instead
            return null;
        }
        else
        {
            throw;
        }
    }
}

Since we have started using the large cluster configuration, it is as though the requestTimeout attribute of the dataCacheClient config entry is having no affect. After issuing the Restart-CacheCluster command our website stops responding for between 3 and 5 minutes which is about how long it currently takes for the cluster to come back up again after a restart.
To troubleshoot this further I did some testing on my local machine to see how long it took the home page of the website to load after a full refresh ([ctrl] [f5]) with AppFabric in various states. The results are as follows (times are average times in seconds):
Small Cache up:   11.4462
Small Cache down: 12.4346
Small Cache restarted: 11.5794
Small Cache restarted[1]: 14.99
Large Cache up: 11.5534
Large Cache down: 16.576
Large Cache restarted: 59.4582
Large Cache restarted[1]: 62.9526
As you can see from the results above, there is a significant difference between the time it takes for the homepage to load normally, and after AppFabric is restarted.
In case you are wondering why we are restarting the cluster at all, we sometimes want to invalidate the cache for the purpose of forcing changes to values such as settings which have a very large TTL, to take affect immediately.
[1] Second restart tests are with the channelOpenTimeout and requestTimeout attributes removed from web.config

A: You can always enumerate over all cache items and remove them from the cache. This way you will achieve your goal without restarting the cache.
DataCache cache; // TODO: initialize
foreach (var regionName in cache.GetSystemRegions())
{
    Trace.WriteLine(string.Format("Enumerating objects in region '{0}'", regionName));
    foreach (var item in cache.GetObjectsInRegion(regionName))
    {
        Trace.WriteLine(string.Format("Removing cache item '{0}'", item.Key));
        cache.Remove(item.Key);
    }
}

Also Small cache cluster means 1-5 cache servers while Large means more than 15 cache servers. When you restart the cluster it means it has to stop AppFabricCachingService on all of those machines, wait for all of them to stop and then start them all and wait for all that.


text:
Q: Allowing users to login via FB and login by making an account on your website I want to give people the opportunity of logging into my site using FB or by making an account on my site. At the moment I have separate pages for the two options.
urls.py
 path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),

path('abc/',TemplateView.as_view(template_name='blog/index.html'), name="facebook")

I changed the name from facebook to abc to make sure that the name had nothing to do with the issue. When I click on the Login With Facebook button, every thing works fine.

When I click Login on this screen, everything works fine. When I click Login with FB, nothing happens.

The account with username RossSymondsFacebook does not have a username because this account was generated by me logging into my Facebook account.

index.html
{% load socialaccount %}
{% providers_media_js %}

            <title>Facebook Registration</title>

<button class="btn">Login With Facebook</button>

login.html
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% load socialaccount %}
{% providers_media_js %}
{% block content %}

    <form method="POST">
        {% csrf_token %}
        <fieldset class="form-group">
            <legend class="border-bottom mb-4">Log In</legend>
            {{ form|crispy }}
        </fieldset>

            <button class="btn btn-outline-info" type="submit">Login</button>

    </form>

            Need An Account? Sign Up Now

<button class="btn">Login With Facebook</button>

{% endblock content %}

A: I resolved my problem by changing my code to the below.
login.html
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}

        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Log In</legend>
                {{ form|crispy }}
            </fieldset>

                <button class="btn btn-outline-info" type="submit">Login</button>

        </form>

                Need An Account? Sign Up Now

{% load socialaccount %}
{% providers_media_js %}

<button class="btn btn-outline-info">Login With Facebook</button>

 {% endblock content %}


text:
Q: Running JUnit Tests Command Line I have two files: thing.java and thingTester.java, the latter is using the methods defined in the "thing" class so I can test those methods.
In addition to those two files, I have junit-4.12.jar in the same directory, so I have only those 3 files in my working directory.
Compiled using this (on Unix):
javac -cp .:junit-4.12.jar thingTester.java thing.java

Trying to run using the line below, but I get "java.lang.NoClassDefFoundError":
java -cp .:junit-4.12.jar junit.textui.TestRunner thingTester thing

What am I doing wrong? I can't really find any clear documentation or general examples.


text:
Q: ANGULAR: Can't get my data to show on my HTML file I am fetching the api json placeholder and i am trying to get a page matching with the id of the route en the object. By console logging everything seems to work, when i navigate to the specific page, the object with the matching id shows up on my console but when i try to put the data on my html it just won't show up. And i get no errors. I don't know what to do.  screenshot of the page
//SERVICE FILE//
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Stream } from './stream';
import { Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class StreamService{

constructor(private http: HttpClient) { }

getStream():Observable<Stream[]>{
  return this.http.get<Stream[]>("https://jsonplaceholder.typicode.com/albums/1/photos");
  }

getLiveStream(id: number): Observable<Stream> {
  const url = `https://jsonplaceholder.typicode.com/albums/1/photos?id=${id}`;
  return this.http.get<Stream>(url);
  }
}

//TS FILE//
import { Component, OnInit } from '@angular/core';
import { StreamService } from '../stream.service';
import { DomSanitizer } from '@angular/platform-browser';
import {ActivatedRoute} from '@angular/router';
import { Stream } from '../stream';

@Component({
  selector: 'app-livestream',
  templateUrl: './livestream.component.html',
  styleUrls: ['./livestream.component.scss']
})
export class LivestreamComponent implements OnInit {
  liveStream!: Stream;

  constructor(
    private streamService: StreamService,
    private sanitizer: DomSanitizer,
    private route: ActivatedRoute,
    ) { }

    //is voor de "sanitizing unsafe style value url" error te vermijden//
    public getSantizeUrl(url : string) {
      return this.sanitizer.bypassSecurityTrustUrl(url);
  }

  ngOnInit() {
    this.getLiveStream();

  }
      getLiveStream():void{
        const id = Number(this.route.snapshot.paramMap.get('id'));
        this.streamService.getLiveStream(id).subscribe(liveStream =>{
            this.liveStream = liveStream;
            console.log(this.liveStream);
        })
      }

}

//INTERFACE FILE
export interface Stream {
  id: number;
  title: string;
  url: string;
  thumbnailUrl: string;
}

// HTML FILE

Livestream

 {{liveStream?.title}}

A: As established in other answer, what you receive is an array with one object. I would extract the object from the array and also like to use the async pipe. So what I would do is:
import { map } from 'rxjs/operators';

//....

getLiveStream(id: number): Observable<Stream> {
  const url = `https://jsonplaceholder.typicode.com/albums/1/photos?id=${id}`;
  return this.http.get<Stream[]>(url).pipe(
    map((streams: Stream[]) => streams => streams[0] || {} as Stream)
  );
}

Component:
import { Observable} from 'rxjs';

// ...

liveStream$: <Observable>Stream;

getLiveStream():void{
  const id = Number(this.route.snapshot.paramMap.get('id'));
  this.liveStream$ = this.streamService.getLiveStream(id);

Template:

 {{liveStream.title}}

A: you can't call {{liveStream?.title}} directly because the api returns an array of livestream. You can do {{liveStream['title']}} however not the best approach. I would suggest using ng-for

Livestream

 {{stream.title}}

you can find more example in angular docs

A: As other answers pointed out the problem, it was because i get an array and wasn't looping over it, so i just assigned array brackets to my observable types in my service file and component file, looped over it and it works now.
//TS file //
export class LivestreamComponent implements OnInit {
liveStream!: Stream[];

// SERVICE FILE //
getLiveStream(id:number):Observable<Stream[]> {
  const url = `https://jsonplaceholder.typicode.com/albums/1/photos?id=${id}`;
  return this.http.get<Stream[]>(url);
  }

Livestream

 {{liveStream.id}}

 {{liveStream.title}}


text:
Q: Referring to MediaPlayer Breaks Script? NullPointerException (JavaFX) Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
    at game.updateLocation(game.java:52)
    at worldMap.startGame(worldMap.java:72)
    at gameRun.lambda$start$0(gameRun.java:63)
    at gameRun$$Lambda$1/424873723.handle(Unknown Source)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:204)
    at javafx.scene.Node.fireEvent(Node.java:8175)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:204)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3746)
    at javafx.scene.Scene$MouseHandler.access$1800(Scene.java:3471)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1695)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2486)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:314)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:243)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:345)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:526)
    at com.sun.glass.ui.View.notifyMouse(View.java:898)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.access$300(WinApplication.java:39)
    at com.sun.glass.ui.win.WinApplication$4$1.run(WinApplication.java:112)
    at java.lang.Thread.run(Thread.java:745)

The trigger for the following code is from gameRun.java:
worldMap map = new worldMap();
map.startGame(game);

Is the error I get when I attempt to click the play button. The code snippet in worldMap.java is as follows
Location YourHometown, Beach;
Location newLocation;
public void createLocations()
{
    YourHometown = new Location("Your Hometown", "Everyone smiles here and talks about sunshines and rainbows. It has a familiar scent of roasted pigs and handknit socks.", "YourHometown.mp3", "Town");
    newLocation = YourHometown;
    Beach = new Location("Beach", "It's Beachy", "Beach.mp3", "Zone");
}

public void startGame(game Game)
{
    createLocations();
    Game.updateLocation(newLocation);
}

And Game.updateLocation() refers to game.java
public void updateLocation (Location newLocation){
...
}

Location is its own separate class, and is an Object. ideally, what this code is supposed to do is change newLocation every time a button with a different Location than the current one is pressed. The objective of the code displayed is to set the default Location to the YourHometown Location Object.
However, the code breaks once we run Game.updateLocation(newLocation); with the following error, and though I know what a NullPointerException is, I don't know how to fix it in the given JavaFX context.
My reasoning is in order for the code to run, the code is forced into createLocations(); with the startGame() method, so there shouldn't ever be a reason why newLocation is null (Since newLocations is set equal to YourHometown). To test my logic, I ran the following code under startGame(), and it still returned the same error:
public void startGame(game Game)
{
    createLocations();
    if(newLocation != null)
    {
        Game.updateLocation(newLocation);
    }
    else
    {
        System.out.println("Break");
    }
}

The console did not print the "Break" line, meaning that newLocation is indeed not null, but the script for updateLocation() runs and the error is returned
TL;DR Conclusion
public void updateLocation (Location newLocation){
    if(bgm.getStatus().equals(Status.PLAYING))
    {
        timeline = new Timeline(new KeyFrame(Duration.seconds(2), new KeyValue(bgm.volumeProperty(), 0)));
        timeline.play();
        bgm.stop();
    }

    bg = new Media(new File(newLocation.getMusic()).toURI().toString());
    bgm = new MediaPlayer(bg);
    bgm.play();

    timeline = new Timeline(new KeyFrame(Duration.seconds(2), new KeyValue(bgm.volumeProperty(), 1)));
    timeline.play();
}

Everything is supposedly working except for the method given above. I think this might be some sort of File/Mediaplayer issue, but I don't know how to approach solving it. The function for updateLocation()is supposed to be a smooth transition from the music in the previous location to the next (previous music fade out --> nextLocation music fade in). It calls the .mp3 files that are located in the same folder that the script is in.
Any help is appreciated, and I can include any extra info if it is missing. I tried simplifying it to make it less of a read.

A: When you call
map.startGame(game);

game is null. I can't see if you assign any value to it from the code you pasted.


text:
Q: Find all Ethernet interface and associate IP address How do I get all interface and associate IP address like following
[root@centso ]# ifconfig
enp3s0f0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet addr:10.5.2.10  Bcast:10.5.7.255  Mask:255.255.248.0
        inet6 fe80::e611:5bff:feea:5e50  prefixlen 64  scopeid 0x20<link>
        ether e4:11:5b:ea:5e:50  txqueuelen 1000  (Ethernet)
        RX packets 638000416  bytes 763371981799 (710.9 GiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 16607280  bytes 9787019600 (9.1 GiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

enp3s0f1: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether e4:11:5b:ea:5e:52  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

enp4s0f0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether e4:11:5b:ea:5e:44  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

enp4s0f1: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether e4:11:5b:ea:5e:46  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1  (Local Loopback)
        RX packets 45015  bytes 4371658 (4.1 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 45015  bytes 4371658 (4.1 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

I want output like following, also I believe there is a command ip link or something does that but didn't recall, also some machine has nic name different like enoX or ethX
enp3s0f0: 10.5.2.10
enp3s0f1:
enp4s0f0:
enp4s0f1:

A: I think i found something, i am sure there must be more smart way but for now i am all set.
[root@server1 ~]# ip -o -4 addr show | awk '{print $1" " $2": "$4}'
1: lo: 127.0.0.1/8
2: eno1: 192.168.100.190/24
3: eno2: 10.5.8.33/21

A: Try this:
ip addr show | awk -F '[: ]+' '
    /^[^ ]/      { iface=$2 }               # Start of section, we memorize the interface name
    $2 == "inet" { print iface ": " $3 }    # IPv4 address => print the line
'

A: There is an example:
ip address show | awk '/inet / {split($2,var,"/*"); print $7,":",var[1]}'

the output should be somthing like:
 : 127.0.0.1
enp3s0f0: 10.5.2.10
enp3s0f1: .......
enp4s0f0: .......
enp4s0f1: .......

A: This gives a report in the format you requested:
# ip -o -4 addr show | awk '{print $2": "$4}'

A: This command displays the all the interfaces and their respective ip adress separated by a space in a line
ip r|grep " src "|cut -d " " -f 3,12 | xargs

reference: https://stackoverflow.com/questions/38041163/display-only-network-interface-and-ip-address-using-ifconfig-and-awk


text:
Q: How to use TypeForwardedTo in Portable Class Libraries? I'm trying to build a Portable Class Library which uses implementations from the platform when available.  For example, Lazy<T> is available on .NET 4.5, Windows Store Apps, Windows Phone 8, BUT it's not available on Windows Phone 7, Silverlight 4.  When my PCL is loaded on one of the platforms that has a Lazy<T> implementation, I want to use the platform's implementation.  When it's not available on the platform, I want to use my own implementation. It seems to be possible because the Microsoft BCL is doing it, but I haven't figured out how to implement it.
I've read that by using the TypeForwardedToAttribute, you can redirect the PCL to use the implementation from the platform.  I'm not quite sure how to configure my Visual Studio Projects to achieve this result.  If CoreLib is my library, and ShimLib contains my implementation of Lazy<T>. Where do I add the TypeForwardedToAttribute? The attribute requires an actual Type reference typeof(System.Lazy<>), which doesn't work when Windows Phone 7 is targeted in the PCL.  If I remove Windows Phone 7, then I can't add a reference from CoreLib to ShimLib because ShimLib doesn't support all the platforms that CoreLib does. How do I handle this?
Yes, I know Lazy<T> is super easy to implement, but it's just an example, and my actual situation applies to many more classes that are less trivial to implement.

A: The way Microsoft.Bcl does this by shipping two assemblies with the same identity; one with the type itself, and one with the type forward. You reference the one with the type when targeting platforms that don't support Lazy (include portable library combinations that include one of these platforms). And reference the one with the type-forward when targeting platforms with Lazy, this enables to consume libraries built against the older platforms.
Make note, Microsoft.Bcl has a little advantage that you don't have. We ship an assembly that has the same identity as one that is already in later versions, which means that when a Windows Phone 7 app runs on Windows Phone 8, they get the version that's built in, not the one in the shim library. You are unable to mimic that, but that's probably something you can live with in your situation.

A: The principle idea of type forwarding is very well explained in this question and this article and I'm not repeating the details here. In summary, however, the idea is to be able to reuse a library A without recompiling, even though it references a library B that is being replaced by library C. To that end, library B has to be modified such that it forwards the reference to library C, which is exactly what the TypeForwardedTo attribute does.
How does this help you? Well, you could create your ShimLib such that it is referenced by all your projects, but uses conditional compilation and type forwarding to link it to the framework libraries if they exist. Fortunately, someone already did that for you :)
Edit in response to Matt's comment: You're right, I overlooked that Theraot doesn't fall back to the original implementation. And I guess that will be very hard to achieve without recompiling. The best you can do is probably to follow this strategy, i.e. to have different build configurations for the different framework versions. That way, you can conditionally compile the TypeForwardedToAttribute. At least, this saves you from having to duplicate code. If you really don't want to distribute different versions of your code, you might implement a bootstraper that determines the framework version and loads the version of your assembly that has been compiled using the build configuration for this version


text:
Q: I thought you couldn't mix types in an array (Java) This is more of theory question. I have this piece of code:
        String[] contacts = new String[10];

    for (int x = 0; x < contacts.length; x++)
    {
        contacts[x] = "Person" + x;
        System.out.println(contacts[x]);

    }

I understand that arrays can only have one type but I have concatenated the variable x (which is an int) on to the end of the String and stored this into an array.
However when I try to do this int based array it doesn't like it which makes sense because you can't mix types in an array that is declared to be holding int variables.
Im confused because you can add Boolean as well to the end of the statement.
contacts[x] = "Person" + x + false

As long as the array starts with a String you can get away with it.
Is this because the String in an object itself?
I'm really sorry if this is an obvious question. I believe this is related to this question but it doesn't quite answer it to my satisfaction Multiple type array

A: That's because if the first element is a string, then it calls toString() on x and it calls toString() on the boolean variable. So you'll just get Person1false, Person2false and so on. And they are all String.
Print them out, you'll see.

A: You're not adding multiple types into the array. Like in the following statement, any + operator that follows a string will concatenate the next variable as if it were parsed to a call to toString().
contacts[x] = "Person" + x + false

So the above is the same as;
contacts[x] = "Person" + Objects.toString(x) + Objects.toString(false)

Note that in the above the variables x and the value false are auto-boxed.
Further reading;

*

*Autoboxing and Unboxing - Official Tutorial

*How does the String class override the + operator?


text:
Q: How to retrieve dropped stored procedure, function, table in SQL Server 2008 I verified the link below as some one (@Oliver) posted as duplicate of my Question. But this query returns last execution script. It is not related to my question.
Last executed queries for a specific database
I have a database with Sample_Training and I created a stored procedure in it and later on I deleted it and now I want to retrieve that deleted stored procedure.
I am employee in company so that I don't have administrative permissions
DECLARE @Date_From DATETIME = '2015-01-02'
DECLARE @Date_To DATETIME = '2015-01-05'

SELECT
    CONVERT(VARCHAR(MAX), SUBSTRING([RowLog Contents 0], 33, LEN([RowLog Contents 0]))) AS [Script]
FROM
    fn_dblog(NULL,NULL)
WHERE
    [Operation] = 'LOP_DELETE_ROWS'
    AND [Context] = 'LCX_MARK_AS_GHOST'
    AND [AllocUnitName] = 'sys.sysobjvalues.clst'
    AND [TRANSACTION ID] IN (SELECT DISTINCT [TRANSACTION ID]
                             FROM sys.fn_dblog(NULL, NULL)
                             WHERE Context IN ('LCX_NULL') AND Operation IN ('LOP_BEGIN_XACT')
                               AND [Transaction Name] = 'DROPOBJ'
                               AND CONVERT(NVARCHAR(11), [Begin Time]) BETWEEN @Date_From AND @Date_To)
                               AND SUBSTRING([RowLog Contents 0], 33, LEN([RowLog Contents 0])) <> 0

By the above query I can get stored procedure and now my question is how to get function, table.

A: I got Solution to my question. First Need to create a procedure
CREATE PROCEDURE [dbo].[sp_Recover_Dropped_Objects]
    @Database_Name NVARCHAR(MAX),
    @Date_From DATETIME,
    @Date_To DATETIME
AS

DECLARE @Compatibility_Level INT

SELECT @Compatibility_Level=dtb.compatibility_level
FROM master.sys.databases AS dtb WHERE dtb.name=@Database_Name

IF ISNULL(@Compatibility_Level,0)<=80
BEGIN
    RAISERROR('The compatibility level should be equal to or greater SQL SERVER 2005 (90)',16,1)
    RETURN
END

Select [Database Name],Convert(varchar(Max),Substring([RowLog Contents 0],33,LEN([RowLog Contents 0]))) as [Script]
from fn_dblog(NULL,NULL)
Where [Operation]='LOP_DELETE_ROWS' And [Context]='LCX_MARK_AS_GHOST'
And [AllocUnitName]='sys.sysobjvalues.clst'
AND [TRANSACTION ID] IN (SELECT DISTINCT [TRANSACTION ID] FROM    sys.fn_dblog(NULL, NULL)
WHERE Context IN ('LCX_NULL') AND Operation in ('LOP_BEGIN_XACT')
And [Transaction Name]='DROPOBJ'
And  CONVERT(NVARCHAR(11),[Begin Time]) BETWEEN @Date_From AND @Date_To)
And Substring([RowLog Contents 0],33,LEN([RowLog Contents 0]))<>0

Execute the procedure as below
EXEC sp_Recover_Dropped_Objects 'Sample_Training','2015/12/24','2015/01/07'


text:
Q: Hibernate: require a property to be set for logging We are using Hibernate Envers to do our logging, but there was a requirement to set the type of event on the object which we are tracking the history. The property is required so we had the idea to put it to null each time the lastEvent wasn't set.
So we tried to set the property with @PrePersist
@PrePersist
public void checkIfLastEventWasModified() {
    if (!lastEventModified) {
        lastEvent = null;
    }
}

But apparantly hibernate considers these interceptors to mark the object as dirty or not. So when this code was run on the dirty check, lastEventModified is still false and lastEvent will be set to null each time even if nothing changed on the object.
We also tried it with the EventListeners from Hibernate but they ran outside the transaction and we could set the property, but they weren't saved to the db.
Both solutions don't feel right, but I have no clue how we can solve this problem in the best way.

A: If your are using a Hibernate version above 3.6.8, you might want to create your own EntityTrackingRevisionListener (javadoc). It is called every time an entity is changed (i.e. every time a new revision is created), and you can change the properties of an entity that is audited by Envers before it is persisted.


text:
Q: css few links on a menu steps to a new line I create CSS menus day in, day out and I've never come across this problem before and its really baffling me! :S
I've tried everything I can think of with no luck. In Chrome it works fine, but in Firefox the last link steps onto a new line, in IE the last 2 links steps onto a new line.
If I remove the padding all the links stay on the same line.
Take a look at what I mean here... http://dlclients.com/estates/ but here's a summary of the CSS and HTML thats causing the issue.
nav{
    background: url(images/background_nav.png) repeat-x;
    height: 30px;
    position: absolute;
    left: 0;
    width: 100%;
    margin-top: 20px;
 }

 #nav-inner{width: 1000px; height: 30px;}

 #nav-inner ul{list-style: none; margin: 0; padding: 0; width: 1070px;}
 #nav-inner ul li{
     display: inline;
     overflow: auto;
 }
 #nav-inner ul li a{
     display: block;
     color: white;
     text-decoration: none;
     font-size: 12px;
     float: left;
     height: 30px;
     line-height: 30px;
     border-right: 1px solid #6D6E71;
     padding: 0 14px;
 }
 #nav-inner ul li a.last{border: none;}
 #nav-inner ul li a:hover{
     border-bottom: 4px solid white;
 }

THE HTML:

Home

Buy

Sell

Rent

Landlords

Property Maintenance

Commercial/Land

Short Term Let/Olympics

About Us

Contact Us

Hope you can help resolve this because I've spent over 2 hours trying to figure this out?!?

A: ul and li have pre-set values for padding and margin, as defined by the browser, unless explicitly set in the CSS. Try adding the following above your first line of CSS and style the remaining classes accordingly:
ul, li {margin:0; padding:0;}


text:
Q: dotnet.exe uses cache even when cshtml file is changed I deployed an ASP.NET Core MVC application to my server, and hosted it in IIS. Configured binding and everything is working. Here's the problem:

*

*I change a cshtml file

*I only upload that cshtml file onto the server, inside the relevant folder

*I call the public action, that returns the PartialView of that cshtml file

*It's not the updated version

*I delete cshtml file from server, and call that action again

*It serves the file, while file is not there anymore physically

*I restart IIS, again file is served

*I kill dotnet.exe, again file is served

*I completely remove Views folder, still file is served

What can be wrong here?

A: For anyone who might have this problem in future, it was because ASP.NET Core MVC 2.0.5 had view precompilation enabled out of the box.
This means that while we didn't want our views to be precompiled, we saw *.PrecompiledViews.dll in our publish folder that has been uploaded to the server.
Thus it doesn't find views from the Views folder, rather it loads them from the relevant dll file.
If you want to change this behavior, simply include <MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish> in your .csproj file.
Read more in this GitHub issue


text:
Q: How to deal with multiple async calls in the Wikipedia API I want to find all the links contained on a Wikipedia page, but how can I get around the async execution?
The below code fetches a list of page links. That I can do. The problem is if I need to get the second page of links (500 links per request), I don't know how to make it run sequentially.
The reason I need it sequentially is I'm wrapping it around a function that gets 'all' the links. I am not sure if this is even good practice.
function findLinksInPage(parent, plcontinue) {
    var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&prop=links&titles=' + parent + '&pllimit=500'
    if(plcontinue != undefined) {
        url += '&plcontinue=' + plcontinue
    }

    var links = []
    var plcontinue
    fetch(url)
        .then(response => response.json())
        .then(data => {
            if(data.continue != undefined) {
                plcontinue = data.continue.plcontinue
            }
            for(key in data.query.pages) {
                const linksPart = data.query.pages[pageId].links
                linksPart.forEach( value => {
                    const link = value.title
                    // console.log('Link found: ' + link)
                    links.push(link)
                })
                var nextLinks = findLinksInPage(parent, plcontinue)
                links.concat(nextLinks)
                return links
            }
        })

        .catch(error => {
            console.log(console.error(error))
        })
}

A: If you are not limited to some browser version, I would suggest to use the async/await syntax to get it more clear:
async function findLinksInPage(parent, plcontinue) {
    var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&prop=links&titles=' + parent + '&pllimit=500'
    if(plcontinue != undefined) {
        url += '&plcontinue=' + plcontinue
    }

    var links = []
    var plcontinue

    try {
        let response = await fetch(url);
        let data = await response.json()

        if(data.continue != undefined) {
            plcontinue = data.continue.plcontinue
        }

        for(key in data.query.pages) {
            const linksPart = data.query.pages[pageId].links
            linksPart.forEach( value => {
                const link = value.title
                // console.log('Link found: ' + link)
                links.push(link)
            })
            var nextLinks = await findLinksInPage(parent, plcontinue)
            links.concat(nextLinks)
        }
        return links // <- not inside for
    }
    catch(error) {
        console.error(error)
    }
}

The function findLinksInPage is a promise, so in the first call you can add a findLinksInPage(parent, plcontinue).then(allLinks=> console.log(allLinks)) call.


text:
Q: Frame rate of 11 FPS in World of Warcraft after upgrading to Yosemite Any ideas why this started after upgrading to Yosemite? I checked the activity monitor and not much else is going on the network.

A: It seems you are facing a known issue. Wait for an update I suppose.
http://us.battle.net/wow/en/forum/topic/14926302581#3


text:
Q: Array from XML Issues using SimpleXMLElement Okay So heres the issue, using an api (lyris hq) i am being returned this xml dataset
<DATASET>
    <TYPE>success</TYPE>
    <RECORD>
        <DATA type="name" id="205199">Dev1</DATA>
        <DATA type="messages">4</DATA>
        <DATA type="last-sent">Jun. 26, 2012</DATA>
        <DATA type="members">1</DATA>
        <DATA type="status">active</DATA>
        <DATA type="cache-time">2012-06-26T18:21:18+00:00</DATA>
    </RECORD>
    <RECORD>
        <DATA type="name" id="206378">Dev2</DATA>
        <DATA type="messages">1</DATA>
        <DATA type="last-sent"></DATA>
        <DATA type="members">2</DATA>
        <DATA type="status">active</DATA>
        <DATA type="cache-time">2012-05-31T14:47:12+00:00</DATA>
    </RECORD>
    <RECORD>
        <DATA type="name" id="206379">Dev3</DATA>
        <DATA type="messages">1</DATA>
        <DATA type="last-sent"></DATA>
        <DATA type="members">1</DATA>
        <DATA type="status">active</DATA>
        <DATA type="cache-time">2012-05-31T14:47:12+00:00</DATA>
    </RECORD>
    <RECORD>
        <DATA type="name" id="206380">Dev4</DATA>
        <DATA type="messages">1</DATA>
        <DATA type="last-sent"></DATA>
        <DATA type="members">1</DATA>
        <DATA type="status">active</DATA>
        <DATA type="cache-time">2012-05-31T14:47:12+00:00</DATA>
    </RECORD>
</DATASET>

What I'm attempting to do is create an array using SimpleXMLElement using it in this format recursively
$response = array(
    '{listid (id attribute from name element)}' => array(
        '{other attribute type}' => '{value}'
    ),
);

example of this using the dev1 (first record)
$response = array(
    '205199' => array(
        'name' => 'Dev1',
        'messages' => '4',
        'last-sent' => 'Jun. 26, 2012',
        'members' => '1',
        'status' => 'active',
        'cache-time' => '2012-06-26T18:21:18+00:00'
    ),
);

me and several members of the web team here have bashed our heads on this for a while and are getting no where so I'm hoping i can get some assistance from the hives mind so to speak lol
heres a pitiful example of what i was last attempting to use to get my result which failed obviously
    foreach ($responseobj->RECORD as $value) {

        $returnarray[(string)$value->DATA['id']] = array();

        foreach ($value->DATA as $k => $v) {
            echo '<pre>';
            print_r($v);
            echo '</pre>';

            $returnarray[(string)$v['id']] = array((string)$v['type'] => (string)$v,);
        }
    }

A: <?php
$x = simplexml_load_file('example.xml');
$returnarray = array();
foreach($x->RECORD as $value){
    $returnarray[(string)$value->DATA['id']] = array();
    foreach ($value->DATA as $k => $v) {
        $returnarray[(string)$value->DATA['id']][(string)$v['type']] = (string)$v;
    }
}
var_dump($returnarray);


text:
Q: Yii2 deployment for contributing I am beginner Yii2 contributor. When I contribute in yiisoft/yii2 project, it is quite clear how to deploy the project and run its phpunit-tests. But I have some questions about working with extensions:

*

*First I add an extension with composer require. Then git clone the same extension inside my home directory.  After that I replace the first directory with symlink, which pointed to the second one. It is quite convenient due to I can see changes on the site, but I can't use composer anymore.

*How to run the extension`s tests? They often depend on Yii2 app class, but
$ vendor/bin/phpunit vendor/yiisoft/yii2-elasticsearch/tests/
PHP Fatal error:  Class 'yiiunit\extensions\elasticsearch\TestCase' not found in /var/www/yii2.test/vendor/yiisoft/yii2-elasticsearch/tests/ActiveDataProviderTest.php on line 11

$ vendor/bin/phpunit vendor/yiisoft/yii2-queue/tests/
PHP Fatal error:  Class 'tests\TestCase' not found in /var/www/yii2.test/vendor/yiisoft/yii2-queue/tests/JobEventTest.php on line 22

Should I specify a config file? Or should I run these tests independently
of the framework?
So, would you please share with me the best practices about this situation?

A: You should run these tests outside of the framework. From extension perspective, yiisoft/yii2 is a dependency and should be installed in vendor directory inside of extension directory. So in short, you should go to extension directory and call composer install. After this you should get directory structure similar to this:
extension/
├── src/
│   └── ...
├── vendor/
│   ├── yiisoft/
│   │   ├── yii2/
│   │   └── ...
│   └── ...
├──composer.json
└── ...

Then you can run tests directly from extension directory (probably by vendor/bin/phpunit command).


text:
Q: MS Access select the most recent date for each GroupID I have three MS Access tables, tblGroup, tblItem, tblStatus:
[tblItem]
ItemID
ItemName
ItemDate
GroupID
StatusID

[tblGroup]
GroupName
StatusID

[tblStatus]
StatusID
StatusName

I am trying to write a VBA SQL query to select all rows in tblItem with the most recent date (i.e. Max(ItemDate)) for each GroupID where the StatusID of tblGroup is equal to "1".
I have been trying variations of the following (see below) but I don't  understand how to filter the results based on another table i.e. where the StatusID of tblGroup is equal to "1" in another table.
DoCmd.OpenForm "frmItem"
Forms!frmItem.frmItemSubform.Form.RecordSource = "SELECT tblItem.ItemID, Max(tblItem.ItemDate) FROM tblItem GROUP BY tblItem.ItemID, tblItem.ItemDate"
Forms!frmItem.frmItemSubform.Requery

Any help would be most appreciated!
George

A: If I am understanding correctly, then this is almost a direct translation of your requirements:
select i.*
from tblItem as i
where i.date = (select max(i2.date)
                from tblItems as i2 inner join
                     tblGroup as g
                     on i2.GroupId = g.GroupId
                where i2.GroupId = i.GroupId and g.StatusId = 1
               );

Or, alternatively:
select i.*
from tblItem as i inner join
     (select i.GroupId, max(i2.date) as date
      from tblItems as i2 inner join
           tblGroup as g
           on i2.GroupId = g.GroupId
      where g.StatusId = 1
      group by GroupId
     ) gmax
     on gmax.GroupId = i.GroupId and gmax.date = i2.date;

These versions are not exactly the same.  The first might not work if there are ties for dates across groups for an item.  This fixes that problem.


text:
Q: Raspberry Pi control over SSH I have raspbery which is controlling LEDs in the room, I made a command which I can send over SSH (using iPhone shortcuts).
This code is running and animates LEDs, to turn all LEDs off I need to ctrl+c. Is there any way I can do this also over SSH, even I headed it has some problems I'd you reconnect to wifi after sending 1st command because it doesnt track already active commands?
I can share code also.
Kind Regards,
Thanks

A: If you just need to kill the process, you can do that either with killall nameoftheprocess, or if you know the process id, using kill pid.
Here is the manpage for kill: https://man7.org/linux/man-pages/man2/kill.2.html
Assuming you start the command with a bash script, you should be able to get the pid using $!, you could then write that to a temporary file from which you can read for killing the process.
If you want more detail, it would be helpful if you shared your code.


text:
Q: Initializing map in companion object throws ExceptionInInitializerError Consider the following class:
sealed class Fruit(val id: String, val label: String) {
  object orange : Fruit("Citrus sinensis", "orange")
  object watermelon : Fruit("Citrullus lanatus", "watermelon")

  companion object {
    val values = listOf(orange, watermelon)
    val valuesByID = values.associateBy { it.id } // <<< error here
  }
}

This class compiles fine, but when it is referenced at runtime (eg: val oj = Fruit.orange) an error will be thrown.
java.lang.ExceptionInInitializerError
        at com.example.sandbox.App.<clinit>(App.kt:13)
        at java.lang.reflect.Constructor.newInstance(Native Method)
        at java.lang.Class.newInstance(Class.java:1606)

However, if the valuesByID line is removed, then the error will not be thrown. Why is this happening?
The runtime environment is Android, if that matters.

A: It is a known issue https://youtrack.jetbrains.com/issue/KT-25738 reported in July 2018.
General problem is using object which is subclass of a sealed class in its companion

A: To add onto Sergei's answer, you can workaround the issue by lazily initializing the companion object's values.
sealed class Fruit(val id: String, val label: String) {
  object orange : Fruit("Citrus sinensis", "orange")
  object watermelon : Fruit("Citrullus lanatus", "watermelon")

  companion object {
    val values by lazy { listOf(orange, watermelon) } // Lazy init
    val valuesByID by lazy { values.associateBy { it.id } } // <<< Lazy init, no error here
  }
}

And yes, you do need to wrap every reference in a lazy block, not just the line that emits the error.


text:
Q: Find number of selfloops and multilinks in a graph I have a graph with N nodes and E links that may contain selfloops and multilinks.
How can I calculate the number of selfloops and the number of multilinks that it contains?
I created a graph in R and then I convert it into an adjacency matrix.
I created a function that should calculate the two values but doesn't always work.
My code:
ident <- function(...) {
  args <- c(...)
  if(length(args) > 2L) {
    # recursively call ident()
    out <- c(identical(args[1], args[2]), ident(args[-1]))
  }
  else {
    out <- identical(args[1], args[2])
  }
  return(all(out))
}

net <- static.power.law.game(no.of.nodes = 10,
                             no.of.edges = 15,
                             exponent.out = 3,
                             exponent.in = 3,
                             loops = TRUE,
                             multiple = TRUE)

netmatr <- as_adjacency_matrix(net)

n_self_mul <- function(network_matrix) {
  selfloops <- 0
  multiarchi <- 0
  for(j in 1:nrow(network_matrix)) {
    if(ident(netmatr[j, j], 1)) {
      selfloops <- selfloops + 1
    }
    for(i in 1:ncol(network_matrix)) {
      if(netmatr[i, j] > 1) {
        multiarchi <- multiarchi + 1
      }
    }
  }
  ret <- list("self" = selfloops, "mul" = multiarchi)
  return (ret)
}

For example, if I have this graph, my function returns: selfloops = 2 and multilinks = 1.
How can I solve?
Thanks

A: You can do this very simply using the adjacency matrix. If a node has an edge to itself (a self-loop) than there will be a non-zero entry on the diagonal of the adjacency matrix. If there is a multi-link then there will be an entry in the adjacency matrix that is greater than 1.
Here is an example.
set.seed(42)
net <- static.power.law.game(no.of.nodes = 5,
                              no.of.edges = 10,
                              exponent.out = 3,
                              exponent.in = 3,
                              loops = TRUE,
                              multiple = TRUE)

# Get the adjacency matrix. I like it with zeros (sparse=F)
# but if your graph is really big leave sparse
netmatr <- as_adjacency_matrix(net, sparse=F)
netmatr
      [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    0    0    0    0    0
[3,]    0    0    0    0    2
[4,]    0    0    0    2    1
[5,]    3    1    0    0    1

On this small example you can see by visual inspection that there are three multiedges ([3,5],[4,4] and [5,1]) and two self-loops at [4,4] and [5,5]. However, this can be computed as:
no.of.selfloops <- sum(diag(netmatr)) # This counts each edge in multi-edged self-loop
no.of.multilinks <- sum(netmatr>1)


text:
Q: Jest webpack 4 babel 7 syntaxError 'import' inside .test.js files Setup

react 16.4.2 (not cra, homebrewed)
  babel v7
  jest v24
  webpack v4.17

PROBLEM
getting error below when I use 'import' syntax inside my test files (i.e. inside component.test.js).
How can I tell Jest to parse the test files using es6?
Have done a lot of googling but no joy
    C:\repos\sandbox\my_react_starter\src\temp.test.js:2
    import React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)

jest config:

  "jest": {
    "rootDir": ".",
    "verbose": true,
    "transform": {
      "^.+\\.jsx?$": "babel-jest",
      ".+\\.(css|styl|less|sass|scss)$": "<rootDir>/node_modules/jest-css-modules-transform"
    }
  },

.babelrc

{
  "presets": [
    "@babel/preset-env",
    "@babel/react"
  ],
  "env": {
    "test": {
      "plugins": [
        "transform-es2015-modules-commonjs"
      ]
    }
  }
}

webpack:

module.exports = {
    entry: './src/index.js',
    output: { path: __dirname + '/dist', publicPath: '/', filename: 'bundle.js' },
    devServer: { contentBase: './dist' },
    module:
    {
        rules:
            [
                {
                    test: /\.(js|jsx)$/,
                    exclude: /node_modules/,
                    use: {
                        loader: 'babel-loader',
                        options: { presets: ['es2015'] }
                    }
                }
            ]
    }
};


text:
Q: Invoking $setValidity from jQuery I have a file uploader that I like for my UI that's written in jQuery.  It is bound to my file element on a change action.  The change action shows a nifty preview and other cool stuff.  It also checks to see if the mime-type is in my list of valid mime-types.
Additionally, I have angularJS wired up and its monitoring my form and I've written a number of directives that do all my validations.  I tried writing a validation for my file input field but for some reason it never gets fired.  Doing some googling suggests that its because angular doesn't support the file input type.
So I added the following code directly to my jQuery change action:
    angular.element(myinput).scope().$apply(function(scope){
      scope.project.avatar.$setValidity('image',false);
    });

I can see that the validity is properly getting set to false in the debugger but the ng-class action that I have is not seeing it.  So outside of this, i have the following tag:

You did it wrong

That class never gets added.
From the Angular docs it appeared that $apply was supposed to force a refresh of the model so that everything ended up back in sync.  Thats obviously not happening, but I'm not sure what I'm doing wrong. Googling found me alot of examples of how to invoke jQuery from within Angular, but very little info on how to invoke Angular from within jQuery.  Any advice would be much appreciated!

A: can you try with the below code

You did it wrong

Here the validationErrorKey is image, so the $error object of the input type file will have a key called image which will be true or false based on what you set after validation.

A: What you might be looking for is
Markup

You did it wrong

JS
    var valid = some logic;
    angular.element(this).scope().$apply(function(scope){
        scope.project.avatar.$setValidity('image', valid);
    });

Demo: Fiddle


text:
Q: Json Array return blank ("") when run Oncreate (android) I am trying to fetch json data from server using volley library and store in array list then display data using spinner.
my code on php server side:
echo json_encode(array('result'=>$result));

My fetch data function:
private void getEventRespondTest (RequestQueue requestQueue) {
        //Creating a string request
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,Config.DATA_URL,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject respond) {
                            try {
                                eventArray = respond.getJSONArray("result");
                                Toast.makeText(Beacon_MainActivity.this,eventArray.toString(),Toast.LENGTH_LONG).show();
                                eventDetail = getEventDetail(eventArray);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
//                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                            Toast.makeText(Beacon_MainActivity.this, "Unable to fetch data: " +error.getMessage(),Toast.LENGTH_LONG).show();
                        }
                    }
                );
        //Adding request to the queue
        requestQueue.add(jsonObjectRequest);
    }

    private ArrayList getEventDetail(JSONArray j) {
        ArrayList event = new ArrayList();
        //Traversing through all the items in the json array
        for (int i = 0; i < j.length(); i++) {
            try {
                //Getting json object
                JSONObject json = j.getJSONObject(i);

                //Adding the name of the event to array list
                event.add(json.getString(Config.EVENT_TITLE));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Toast.makeText(Beacon_MainActivity.this,event.toString(),Toast.LENGTH_LONG).show();
        return event;
    }

And on my OnCreate method I am trying to fetch the data and display result using spinner but when run, result return first time is blank "
eventDetail = new ArrayList<>();
        eventArray = new JSONArray();

//        //get event from server
        getEventRespondTest(Volley.newRequestQueue(Beacon_MainActivity.this));
        spinner.setAdapter(new ArrayAdapter<>(Beacon_MainActivity.this, android.R.layout.simple_spinner_dropdown_item, eventDetail));

Any help is much appreciate. Thanks.

A: Your function private void getEventRespondTest is returning null as it is Void. What are you doing with eventDetail = getEventDetail(eventArray); getEventRespondTest  function? Or tried to change POST to GET?
UPDATE CHECK THIS CODE
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getEventRespondTest();
    }

 private void getEventRespondTest () {
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        StringRequest request = new StringRequest("http://vinhvumobile.com/phpconnect/geteventdetail.php", new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                // we got the response, now our job is to handle it
                getDataFromJson(response);
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                //something happened, treat the error.
                Log.e("Error", error.toString());
            }
        });
        queue.add(request);
    }

    private ArrayList getDataFromJson(String json) {
        ArrayList events=new ArrayList();
        JSONArray array;
        try {

            JSONObject gallery=new JSONObject(json);
            array=gallery.getJSONArray("result");
            //Do sth with it

            for(int i=0;i<array.length();i++){
                JSONObject jsonOBJ = (JSONObject) array.get(i);
                events.add(jsonOBJ.get("EventID"));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return events;
    }

A: I think you response in method  public void onResponse(JSONObject respond) respond  is null because you use JsonObjectRequest to make request but your server(php) return a String it mean nothing JsonObject to return. Try use StringRequest instead of JsonObjectRequest . In best solution is change code your server for it return a `JsonObject' follow this (php file):
header('Content-Type: application/json');
echo json_encode(array('result'=>$result), 256); // 256 for UTF-8 data


text:
Q: A question on the remainders of integer division This is a question on the remainders of integer division from my student.
Notations.
Let $p$ be a positive odd prime integer.
We write $r_{i,j}$ for the remainder of $i \times j \div p$.
Now for an integer $u \in \{1, 2, \dots, p-2\}$, we define
\begin{align*}
K_1 =&\{ i : 1 \le i \le p-2,\ r_{i,u}+u<p,\ r_{i,p-u-1} <u+1\}, \\
K_2 =&\{ i : 1 \le i \le p-2,\ r_{i,u}+u<p,\ r_{i,p-u-1} >u+1\}, \\
K_3 =&\{ i : 1 \le i \le p-2,\ r_{i,u}+u>p,\ r_{i,p-u-1} <u+1\}, \\
K_4 =&\{ i : 1 \le i \le p-2,\ r_{i,u}+u>p,\ r_{i,p-u-1} >u+1\}.
\end{align*}
And for another $u' \in \{1, 2, \dots, p-2\}$, we can define $K_\nu'$ for $\nu=1,2,3,4$.
Question.
If $K_1 =K_1'$ and $K_4=K_4'$, then either $K_2=K_2'$ and $K_3=K_3'$, or $K_2=K_3'$ and $K_3=K_2'$.
What I have done.
1.
With the help of computer, I checked the correctness of this question for $p<100$.
2.
Still with the help of computer, I found that, at least for $p<100$, if $K_1 =K_1'$ and $K_4=K_4'$, then either $u \equiv u' \pmod{p}$ or $u+u' \equiv p-1 \pmod{p}$.
The first case corresponds to the result $K_2=K_2'$ and $K_3=K_3'$, and the second one corresponds to the result  $K_2=K_3'$ and $K_3=K_2'$.
3.
I observed the definitions of the $K_\nu$'s, and found some equivalent conditions.
Firstly, we have
\begin{align*}
r_{i,u}+u<p &\quad\Leftrightarrow\quad r_{i+1,u} =r_{i,u} +u,\\
r_{i,u}+u>p &\quad\Leftrightarrow\quad r_{i+1,u} =r_{i,u} +u-p,
\end{align*}
and similarly,
\begin{align*}
r_{i,p-u-1} <u+1 &\quad\Leftrightarrow\quad r_{i+1,p-u-1} =r_{i,p-u-1} +(p-u-1),\\
r_{i,p-u-1} >u+1 &\quad\Leftrightarrow\quad r_{i+1,p-u-1} =r_{i,p-u-1} +(p-u-1) -p.
\end{align*}
4.
Using the discussion in (3), we obtain
\begin{align*}
i \in K_1
&\;\Leftrightarrow\; r_{i,u}+r_{i,p-u-1}<p \text{ but } r_{i+1,u}+r_{i+1,p-u-1}>p, \\
i \in K_4
&\;\Leftrightarrow\; r_{i,u}+r_{i,p-u-1}>p \text{ but } r_{i+1,u}+r_{i+1,p-u-1}<p, \\
i \in K_2 \cup K_3
&\;\Leftrightarrow\; \text{both $r_{i,u}+r_{i,p-u-1}$ and $r_{i+1,u}+r_{i+1,p-u-1}$ are $<p$ or $>p$}.
\end{align*}
5.
Now by the result in (4), we can see that $K_1 =K_1'$ and $K_4=K_4'$ if and only if for every $i \in \{1, 2, \dots, p-1\}$, the signatures of $r_{i,u}+r_{i,p-u-1}-p$ and $r_{i,u'}+r_{i,p-u'-1}-p$ are the same (i.e., both positive or both negative).
However, I really do not know how to solve this question, so if you have any idea, please help me.
Thank you very much for your attention.

Any ideas or hints are welcome. Please.

A: To continue with your argument: you have the property that
$r_{i,u}+r_{i,p−u−1}−p$ and $r_{i,u′}+r_{i,p−u′−1}−p$ have the same sign for all $i$. This is equivalent to saying that
$r_{i,u} - r_{i,u+1}$ and $r_{i,u'} - r_{i,u'+1}$ have the same sign for all $i$.
This difference is always $p-i$ or $-i$, so this means that
$$
r_{i,u} - r_{i,u+1} = r_{i,u'} - r_{i,u'+1}
$$
for all $i=1,2,\ldots,p-2$.
One can also argue that this means that for all $i$ the sum of fractional parts
$$
\{\frac{iu}p\}
+
\{\frac{i(u'+1)}p\}
+\{\frac{i(-u')}p\}
=1+\{\frac{i(u+1)}p\}.
$$
This becomes a statement that some toric cyclic singularity in dimension three is terminal. These have been classified. I believe that corollary 1.3 of
"TERMINAL QUOTIENT SINGULARITIES IN DIMENSIONS THREE AND FOUR"
DAVID R. MORRISON AND GLENN STEVENS
http://www.ams.org/journals/proc/1984-090-01/S0002-9939-1984-0722406-4/S0002-9939-1984-0722406-4.pdf
should give you the desired statement.


text:
Q: std::map on gcc 3.2.3 Red Hat Linux 3.2.3-20 I am an ATE engineer in a semiconductor company and I need to develop as well as maintain test programs. Recently I would like to add a config file parsing function in the ATE platform. However, the standard test platform is not up-to-date (I am not sure whether this caused the problem).
I checked some resources and found several candidates: getpot(http://getpot.sourceforge.net/), inih(https://github.com/benhoyt/inih). With both, I could use directly compile and run on my windows 7 with gcc 4.8.1. However I would have to use it on my ATE Red Hat 3.2.3. I can not change the platform (like update the gcc version, install new packages), but I could include all necessary codes as raw files.
Here is what I have tried with inih:
1: I copied the codes to shared folder (between host windows and virtual redhat machine). On windows, I make it to compile and run correctly. However, on red hat it shows error as below . Here is the part which showed error:
string INIReader::Get(string section, string name, string default_value) const
{
    string key = MakeKey(section, name);
    return _values.count(key) ? _values.at(key) : default_value;
}

I just tried to modify it to implement std::map::at as below:
template<typename T1, typename T2, typename T3, typename T4>
T2 mapAt(std::map<T1, T2, T3, T4>& m, const T1& key)
{
    typeof(m.begin()) mit = m.find(key);
    if (mit == m.end() || mit->first != key)
    {
        throw std::out_of_range("map::at");
    }
    return mit->second;
}

string INIReader::Get(string section, string name, string default_value) const
{
    string key = MakeKey(section, name);
    return _values.count(key) ? mapAt(_values, key) : default_value;
}

and still it generates error as below:

2:when I add the sources in the job file, I have comfirmed that there is tab instead of 8 blank on the line, still it showed missing separator error.

A: The error is indicating that the function std::map::at does not exist in your environment.
This function is introduced in C++11, so your old GCC version does not support it.
Try to replace this function with alternatives, like std::map::find or similar.

A: You could implement std::map::at yourself, for exmaple:
#include <iostream>
#include <stdexcept>
#include <map>

template<typename T1, typename T2, typename T3, typename T4>
T2 mapAt(std::map<T1, T2, T3, T4>& m, const T1& key)
{
    typeof(m.begin()) mit = m.find(key);
    if (mit == m.end() || mit->first != key)
    {
        throw std::out_of_range("map::at");
    }
    return mit->second;
}

int main()
{
    std::map<int, int> mp;
    mp[2] = 3;
    std::cout<<mapAt(mp, 2)<<std::endl;
    std::cout<<mapAt(mp, 3)<<std::endl; // will raise an exception
    return 0;
}

Sorry I implemented the template incorrectly (this is incorrect for std::string and sorry I don't how to correct it). Here is a degraded version. It restricts type of map but should work on every C++ version.
std::string& mapAt(std::map<std::string, std::string>& m, const std::string& key)
{
    std::map<std::string, std::string>::iterator mit = m.find(key);
    if (mit == m.end() || mit->first != key)
    {
        throw std::out_of_range("map::at");
    }
    return mit->second;
}

A: Your implementation of mapAt accepts its first argument as non-const reference:
T2 mapAt(std::map<T1, T2, T3, T4>& m, const T1& key)

yet you try to call it from inside the const method INIReader::Get, where _values are treated as a constant map.
It is generally better to declare ref-arguments as consts provided you do not have a clear intention to modify them.

A: I tried suggestions here and still some issues remain. So I put forward an issue on the project's github repo and the writer gave a validated solution. It is to change _values.at(key) to _values.find(key)->second.
I just checked and confirmed that it works here. You can go to this site (https://github.com/benhoyt/inih/issues/49) for the detailed discussion.
Still, thanks for involvement and discussion here.