text:
Q: Accessing relations of a table with inheritance I have an Inheritance class as shown here:

As you can easily see users, buildings and hotels have addresses (more than one) and address table keeps the id of the owner in whose column.

*

*Is my logic correct?

*Let's say I want to get the address of user (or buildings or hotels) whose id is 2; must I run a DQL statement (and how?) or can I get it with find() function without DQL?

And I'll be happy if you give example since Doctrine documentation doesn't help much.
Thanks.
Edit: users, buildings and hotels are just symbolic names that is why they can have multiple addresses otherwise buildings and hotels would have only one address.
Edit 2:I think I couldn't make myself clear, when I talk about the Class Table Inheritance I mean entity class has the Discriminator column as
/**
 * ...
 *
 * @DiscriminatorColumn(name="classname", type="string")
 * @DiscriminatorMap({"Entities\users" = "Entities\users",
 * "Entities\buildings" = "Entities\buildings"}) ... etc
 */

Each and every subclass is related to parent (Entity) with the foreign key relation as "id". But of course doctrine creates this relation already for me.

A: Usually an Address is a typical value object. Value objects are usually stored with the entity compositing the value object so it is neither about relations nor about class table inheritance. If your domain indicates otherwise (e.g. you can do something with your address, meaning), they might be an entity, than entity Hotel holds an entity Address (persisted in a n:m relation table) and entity Building holds and Address too (in a different n:m relation table).
If you go the value object route, things are different. You would store the address with the Building entity as well as with the Hotel entity (as you would do it with other value objects may it be Moneyor Email or Password). So you don't need relations at all, just a few more fields. The issue with Doctrine 2 is, that it does not support Component mapping. Component mapping would be used to nicely store value objects. T accomplish the same thing with Doctrine 2, you would implement a @prePersist and a @postLoad handler like that:
class Hotel
{
    private ;

    /** These fields are persisted */

    /** @Column(type=string) */
    private $addressStreet;
    /** @Column(type=string) */
    private $addressCity;
    /** @Column(type=string) */
    private $addressZip;
    /** @Column(type=string) */
    private $addressCountry;

    /** @prePersist */
    public function serializeValueObjects()
    {
        $this->addressStreet = ->address->getStreet();
        $this->addressCity = ->address->getCity();
        $this->addressZip = ->address->getZip();
        $this->addressCountry = ->address->getCountry();
    }

    public function unserializeValueObjects()
    {
        $this->address = new Address(->addressStreet, ->addressCity, ->addressZip, ->addressCountry);
    }
}

As you need to serialize/unserialize Address value objects in various places, you might want to extract the serializing code into a separated class.

A:
/**
 *
 * @Entity
 * @Table(name="proposaltemplate")
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="entitytype", type="string")
 * @DiscriminatorMap({"proposal" = "ProposalTemplate","page" = "PageTemplate"})
 *
 */

abstract class AbstractProposalTemplate
{
    /**
     *
     * @var integer
     * @Id
     * @Column(type="integer")
     * @generatedValue(strategy="AUTO")
     *
     */
    private  $id;
}

next

@Entity

class ProposalTemplate extends AbstractProposalTemplate
{

      @Id
      @Column(type="integer")
      @generatedValue(strategy="AUTO")

    private  $id;

}
next another class

  @Entity

class PageTemplate extends AbstractProposalTemplate
{
   /**
     *
     * @var integer
     * @Id
     * @Column(type="integer")
     * @generatedValue(strategy="AUTO")
     *
     */
    private  $id;
}

A: So you've got a superclass called "Entity", which has subclasses "User", "Building", and "Hotel".
Your "Entity" entity should have a OneToMany relation to Address.  Let's imagine it looks like this, in your Entity definition:
/**
 * @OneToMany(targetEntity="Address", mappedBy="whose"
 */
protected $addresses;

This is a more-or-less fine approach, though the use of inheritance is a little smelly.
Then if you want to iterate over the addresses, from inside User, Building, or Hotel:
foreach($this->addresses as $address){
    //do something with adderess
}

Does that answer your question?


text:
Q: Is there a way to check a function's signature in Python? I'm looking for a way to check the number of arguments that a given function takes in Python.  The purpose is to achieve a more robust method of patching my classes for tests.  So, I want to do something like this:
class MyClass (object):
    def my_function(self, arg1, arg2):
        result = ... # Something complicated
        return result

def patch(object, func_name, replacement_func):
    import new

    orig_func = getattr(object, func_name)
    replacement_func = new.instancemethod(replacement_func,
                           object, object.__class__)

    # ...
    # Verify that orig_func and replacement_func have the
    # same signature.  If not, raise an error.
    # ...

    setattr(object, func_name, replacement_func)

my_patched_object = MyClass()
patch(my_patched_object, "my_function", lambda self, arg1: "dummy result")
# The above line should raise an error!

Thanks.

A: You should use inspect.getargspec.

A: The inspect module allows you to examine a function's arguments. This has been asked a few times on Stack Overflow; try searching for some of those answers. For example:
Getting method parameter names in python

A: You can use:
import inspect
len(inspect.getargspec(foo_func)[0])

This won't acknowledge variable-length parameters, like:
def foo(a, b, *args, **kwargs):
    pass

A: inspect.getargspec is deprecated in Python 3. Consider something like:
import inspect
len(inspect.signature(foo_func).parameters)

redpajama_set_name: RedPajamaStackExchange


text:
Q: File download using React Django? able to download file but content is missing getting file correpted error Backend
@api_view(['POST'])
def download_attachment(request):
    body_unicode = request.body.decode('utf-8')
    body_data = json.loads(body_unicode)
    file_name = body_data['file_name']
    migration_typeid = body_data['migration_typeid']
    attach_type = body_data['AttachmentType']
    object_type = body_data['object_type']
    featurename = body_data['fname']
    fid = body_data['feature_id']
    filter_files = Attachments.objects.filter(
        Feature_Id=fid, AttachmentType=attach_type, filename=file_name)
    filter_values = list(filter_files.values_list())
    file_path = filter_values[0]
    fl = open(file_path[4], 'rb')
    mime_type, _ = mimetypes.guess_type(file_path[4])
    response = HttpResponse(fl, content_type=mime_type)
    response['Content-Disposition'] = "attachment; filename=%s" % file_name
    return response

Frontend(React)
const handleDownload = (att_Type, migtypeid, id, obj_type, att_name, fid) => {

    let body = {
      file_name: att_name,
      migration_typeid: migtypeid,
      object_type: obj_type,
      AttachmentType: att_Type,
      id: id,
      fname: detaildata.Feature_Name,
      feature_id: fid,
      responseType: "blob",
    };
    let conf = {
      headers: {
        Authorization: "Bearer " + config.ACCESS_TOKEN(),
        "Content-Type": "application/json",
      },
    };
    // console.log(conf.headers);
    axios
      .post(`${config.API_BASE_URL()}/api/download_att`, body, conf)
      .then((res) => {
        fileDownload(res.data, att_name);
      })
      .catch((err) => { });
  };

i am able to download the file but content is not coming in the file
for txt files it is working but other than txt not supporting getting corrupted error
can you anyone tell me the solution how it works?


text:
Q: How to rename columns to get one line of column names? I have this pandas DataFrame df:
df.head()
windIntensity   year    month   day hour    AOBT    delay
3               2015    1   1   0   0       0.0     15.0
2               2015    1   1   0   0       0.0     10.0
2               2015    1   1   1   0       0.0     5.0
2               2015    1   1   1   0       0.0     0.0
1               2015    1   1   2   0       0.0     0.0

When I execute this code:
df = dfj.groupby(["year","hour"]).agg({'windIntensity':'mean','delay':['mean','count']}).reset_index()

I get this result:
year    hour    windIntensity   delay
                mean            mean        count
0   2015    0   4.239207        24.240373   857
1   2015    1   4.029024        15.770449   758
2   2015    2   3.863928        7.431322    779
3   2015    3   3.859801        4.161290    806
4   2015    4   3.782659        4.722230    6851

But how can I rename columns to get one line of column, not two lines?
Expected result:
year    hour    windIntensity_mean  delay_mean  count
0   2015    0   4.239207            24.240373   857
1   2015    1   4.029024            15.770449   758
2   2015    2   3.863928            7.431322    779
3   2015    3   3.859801            4.161290    806
4   2015    4   3.782659            4.722230    6851

A: Demo:
source DF with multi-level columns:
In [223]: r
Out[223]:
  year hour windIntensity delay
                     mean  mean count
0    1    0          2015   6.0     5

solution:
In [224]: r.columns = r.columns.map(lambda c: ('_' if c[1] else '').join(c))

result:
In [225]: r
Out[225]:
   year  hour  windIntensity_mean  delay_mean  delay_count
0     1     0                2015         6.0            5


text:
Q: List of supported JavaScript events on iPad Is there a list of all supported JavaScript events on the iPad Safari?
Preferably from official Apple pages.

A: It depends which version the operating system is, but here is a list of supported events under 'Supported Events'.


text:
Q: GKE: Google Compute Engine: Required 'compute.networks.get' but permissions are there? When attempting to create a GKE cluster via gcloud, web console, or pulumi I'm receiving the error: Google Compute Engine: Required 'compute.networks.get.
The permission for this account have Owner, Editor, and Compute Admin. Testing for compute.networks.get using the troubleshooter also shows that it is good.
Not sure why this is happening. It seemed to have been working fine the day before.
Thanks in advance.
Edit:
I can also run gcloud compute regions describe us-east1 --project=myproj as well as the list command without issue so something is not adding up.
Edit 2:
Full error is:
googleapi: Error 403: Retry budget exhausted (5 attempts): Google Compute Engine: Required 'compute.regions.get' permission for 'projects/myproj/regions/us-central1'., forbidden

A: It seems that the issue is with shared VPC. You need to allow the service accounts in the service project to use the sub-network with a binding resource. To do this:
Enable the permissions in the service account(s) to include 'roles/compute.networkUser' . This provides access to a shared VPC network.
I've found a similar issue on the terraform GitHub, and this is the workaround a user proposed.
Also you can disabling and then re-enabling both Compute API and Kubernetes API
You could also check the following documentation: Enabling the Google Kubernetes Engine API in your projects
Additionally at this moment Google Kubernetes Engine is reporting issues: Incident began at 2021-02-19 05:47 (all times are US/Pacific).
You can track the current status  on https://status.cloud.google.com/ and for this particular error you could check https://status.cloud.google.com/incident/container-engine/21004

Description: We are experiencing an intermittent issue with Google Kubernetes Engine creation.
Our engineering team continues to investigate the issue.
We will provide an update by Friday, 2021-02-19 10:30 US/Pacific with current details.


text:
Q: Convert array with tree structure to object in Javascript I have an array with the following format
 let array = [{id: 1, desc: 'd1', children:[{id:1.1, desc:'d1.1', children:[]}]},
                 {id:2, desc:'d2', children:[] },
                 {id:3, desc:'d3', children:[] }];

Where each child is of the same time as the parent element. I would like it to transform it into an object with the format { [id]: {values} }:
{
 1: { id: 1, desc: 'd1', children: {1.1: {id:1.1, desc:'d1.1'}},
 2: { id:2, desc:'d2' },
 3: { id:3, desc:'d3' }
}

I tried in many ways but with no success. For instance:
let obj = array.map(a => mapArrayToObj(a));

mapArrayToObj = (e) => {
     let obj = {[e.id]: e };
     if(e.children.lenght > 0){
       e.children = e.children.map(c => mapArrayToObj(c));
     }
     else{
       return {[e.id]: e };
     }
}

Is it even feasible in Javascript?

A: You could use a recursive function which generates an object out of the given items without mutating the original data.

function getObjects(array) {
    var object = {};
    array.forEach(function (item) {
        object[item.id] = Object.assign({}, item, { children: getObjects(item.children) });
    });
    return object;
}

var array = [{ id: 1, desc: 'd1', children: [{ id: 1.1, desc: 'd1.1', children: [] }] },        { id: 2, desc: 'd2', children: [] },        { id: 3, desc: 'd3', children: [] }];

console.log(getObjects(array));
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: Let's try with this code...
let array = [{id: 1, desc: 'd1', children:[{id:1.1, desc:'d1.1', children:[]}]},
    {id:2, desc:'d2', children:[] },
    {id:3, desc:'d3', children:[] }]

let object = {}

array.forEach(item => {
    let children = item.children
    object[item.id] = item
    object[item.id].children = {}
    children.forEach(child => {
        object[item.id].children[child.id] = child
    })
})

console.log(object)

Result:
{ '1': { id: 1, desc: 'd1', children: { '1.1': [Object] } },
  '2': { id: 2, desc: 'd2', children: {} },
  '3': { id: 3, desc: 'd3', children: {} } }

A: You could use reduce() method to create recursive function and return object object as a result.

let array = [{id: 1, desc: 'd1', children:[{id:1.1, desc:'d1.1', children:[]}]}, {id:2, desc:'d2', children:[] }, {id:3, desc:'d3', children:[] }]

function build(data) {
  return data.reduce(function(r, {id, desc, children}) {
    const e = {id, desc}
    if(children && children.length) e.children = build(children);
    r[id] = e
    return r;
  }, {})
}

const result = build(array)
console.log(result)


text:
Q: Recursive Binary Search Python 3 prints solution but doesn't return it def binarySearch( a, l, r, num ):

    m = (l+r) // 2

    if l < r:

        if num <= a[m]:
            binarySearch(a, l, m, num)
        else:
            binarySearch(a, m+1, r, num)

    else:

        print( m )

If instead of print(m) i write return(m) and then try to print the function it returns None and I don't understand why.
Can someone explain?
Thanks

A: def binarySearch( a, l, r, num ):

    m = (l+r) // 2

    if l < r:

        if num == a[m]:
            return m

        elif num < a[m]:
            return binarySearch(a, l, m, num)

        else:
            return binarySearch(a, m+1, r, num)
    else:
        return  -1

 # If return statement with the thing that need to be return is not mentioned explicitly  by default we get None

'''
--tested using
for i in range(0,8):
    print('result for item', i ,binarySearch( [0,1,2,5,7], 0, 5,i ))
'''


text:
Q: winverify trust results 2148204800 only in windows server 2012 r2 standard VM We are doing the MSI validation using below code.
WinTrustData wtd = new WinTrustData(fileName);
Guid guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2);
WinVerifyTrustResult result = NativeMethods.WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd);
bool ret = (result == WinVerifyTrustResult.Success);

The MSI file is having proper digital sign and it is working fine in all the OS versions except windows server 2012 R2 standard.
Ay suggestions or solutions will be highly appreciated.

A: We have identified that the root certificate was disabled in the certificate store and after enabling the particular root certificate of the msi file, the issue got resolved, Thank you


text:
Q: How to ensure double quote in multiline strings I wrote an SQL query which uses data passed in from WTForms as parameters.
How do I ensure double quotes on the variable?
q = """
select * from table
where dt_date >= %(date)s""" % {'date':date}

Right now it shows as
select * from table
where dt_date >= 23-06-2016

which then throws error. How to make it become:
select * from table
where dt_date >= "23-06-2016"

A: Python doesn't stop you from using double-quotes inside your multiline strings. The trouble is only when you place them next to each other (""""). You can either escape your double quotes as \" or simply leave a space between them and the triple-quotes (" """).
Escaping:
q = """
select * from table
where dt_date >= \"%(date)s\""""%{'date':date}
>>> print q

select * from table
where dt_date >= "asdf"

Space before the triple-quotes:
q = """
select * from table
where dt_date >= "%(date)s" """%{'date':date}
>>> print q

select * from table
where dt_date >= "asdf"

A: Try escaping the double quotes in your multine.
>>> q = """
... select * from table
... where dt_date >= \"%(date)s\""""%{'date':date}
>>> q
'\nselect * from table\nwhere dt_date >= "23-06-2016"'
>>> print q

select * from table
where dt_date >= "23-06-2016"


text:
Q: How to assign value of the array position in Android Java? I know how to get value of a position of the array and Compare the values of the array.
for (int i = 0; i < listadosWifi.size(); i++) {
            /* pega o SSID e o BSSID */
            providerName = "\n"+(listadosWifi.get(i).SSID).toString()+ "\n"+(listadosWifi.get(i).level);
            listViwProvider = (ListView) findViewById(R.id.list_view_wifi);
            listaFornecedores.add(providerName);
            t1.speak("Redes Disponíveis: " + providerName, TextToSpeech.QUEUE_ADD, null, null);
            t1.setPitch(1);

                if (listadosWifi.get(i).level < -10 && listadosWifi.get(i).level > -50 ) {
                    t1.speak("Você está próximo de: " + providerName, TextToSpeech.QUEUE_FLUSH, null, null);
                    t1.setPitch(1);
                    if(listadosWifi.get(i).level < -50){
                        t1.speak("Você está próximo de: " + providerName, TextToSpeech.QUEUE_FLUSH, null, null);
                        t1.setPitch(1);
                    }
              }
 }

finally how can i assign the value of one array position to the one on another array in java.
I DO NOT want to copy the values from one array to another.
I need to match the values of an array to another.
For Exemple: the WiFi name and it's signal
WifiName is one array and WiFiSignal is in another array.


text:
Q: ES6 import both all (*) and a specific name in the same statement I have an ES6 module, mod.mjs:
export default { f1, f2 };
export function f1() {}
export function f2() {}

Which I can import and use like this:
import { default as mod, f2 } from "./mod.mjs"
mod.f1();
mod.f2();
f2();

Can I do the same without declaring default export inside mod and without de-structuring * alias after importing it?
I've tried the following but it gives a syntax error:
import { * as mod, f2 } from "./mod.mjs"
mod.f1();
mod.f2();
f2();

Basically I want this, but using the import statement syntax only, if possible:
import * as mod from "./mod.mjs"
const { f2 } = mod;

mod.f1();
mod.f2();
f2();

If there is no pure JavaScript solution to that, perhaps, TypeScript has a syntax for something like that?

A: I am not sure if this is what you are expecting.
The Best approach you can follow is this:
import * as mod from "./mod.js";
import { f2 } from "./mod";
mod.f1();
mod.f2();
f2();

A: You can use code below
import mod, { f1, f2 } from "./fun.mjs";

mod.f1();
mod.f2();
f1();
f2();


text:
Q: index number for the line time using JavaScript I am using the below code in the google tag manager custom JavaScript variable, but it returns same index value for every line item, what can be the issue?
Web page link: https://www.amity.edu/programe-list.aspx?fd=all
function() {
var elements = document.querySelectorAll('.staff-container');
for (var i = 0; i < elements.length; i++){
     (function(index){
       elements[i].children[0].children[0].addEventListener("click", myScript);
       function myScript(){
         return("Clicked : ",index);
       }
     })(i);
   }
}

A: There is an error in the 5th line.
It should be elements[index].children... in that case.
The updated code:
function() {
  var elements = document.querySelectorAll('.staff-container');
  for (var i = 0; i < elements.length; i++){
    (function(index){
      elements[index].children[0].children[0].addEventListener("click", myScript);
      function myScript(){
        return("Clicked : ",index);
      }
    })(i);
  }
}

A: Here is an alternative way from Simo's blog
Blog link
Although the post is say about visibility element. I test it with click on my website.
This might work
function() {
  var list = document.querySelectorAll('.staff-container a'),
      el   = {{Click Element}};
  return [].indexOf.call(list, el) + 1;
}

If it is not working, you might need to provide the screenshot about the click element from your GTM preview.


text:
Q: How do I make a batch file create another one with code in it I made this batch file and then I wanted to make an installer for that with batch but then I got stuck on the making the batch file with code part.
I tried using this:
cat > %drev%:\Notekeeper\Program.bat << EOF
script script script
script script script
EOF

but then I realized I needed to add echo before every line. And that is a problem when you have 300+ lines of code...
So, is there a easier way to do it where I don't have to add echo before everything?

A: This is one way to do this:
@echo off
setlocal

rem Get the number of the "<resource>" line
for /F "delims=:" %%a in ('findstr /N "<resource>" "%~F0"') do set "start=%%a"

rem Skip such number of lines and show the rest of this file
(for /F "usebackq skip=%start% delims=" %%a in ("%~F0") do echo %%a) > Program.bat

goto :EOF

<resource>
script script script
script script script

There are several modifications that can be done on this code, for example:

*

*Place the section of code at other place (not at end of this file).

*More than one section of code.

*Expand some %variables% when the code is being copied.

*Et cetera...

Note: the inclusion of code in other types of files is managed in a section called <resource>, so I just used the same term.

A: @echo off & setlocal enabledelayedexpansion
(
scriptA
scriptB
)2>>fileA.txt:stream1

for /f %%p in (fileA.txt:stream1) do (
    set a=%%p
    set a=!a:'=!
        echo !a!>> fileA.txt
)

The script above will do:

*

*Redirect scriptA..... into fileA.txt's stream1 (you can't see that)

*As fileA.txt's stream1 will be filled with:

'scriptA' is not a regonized.....

*The for loop will remove the unneeded text and redirect them into
the correct fileA.txt
Here's another way, but it only shortens the >>"file.txt", not the echo
(
echo script
echo script
echo script
)>>"file.txt"

Taken from this Stack Overflow question
Edit:
As @Aacini commented, special characters will need to be escaped.


text:
Q: 'was' versus 'had been'
When I asked the driver/ to come with me to the temple/ he had been reluctant./ No error.

I think instead of 'had been', there should be 'was'. Even the answer key points that the error is in the 'he had been reluctant' part. But I am not sure why exactly is 'had been' wrong.
If we replace the first part with 'when I had asked the driver', would that make 'had been' in the third part correct?

A: You use past perfect tense ("had been") when you are trying to show which of two events in the past happened first. "He had been reluctant when I asked him to come with me" indicates his reluctance came first, which doesn't seem right.
"He had been reluctant to go to the temple, but came with me when I asked."  or "When I asked him to come with me, he was reluctant." makes more sense. The "when" indicates the time that the events happened (at the same time that I asked), so the past perfect tense isn't needed.


text:
Q: ejabberd mod_rest installation warning & crash report I've tried to test mod_rest for my ejabberd. Received 'OK' result but with warning : "Warning: undefined callback function depends/2 (behaviour 'gen_mod')" during installation of the module. When I tried to test mod_rest that I installed using REST client, there's CRASH REPORT in log.
ejabberd version : 16.08.23
URL : http://localhost:5280/rest
ejabberd.yml
hosts:
  - "localhost"
  - "192.168.88.88"
  - "127.0.0.1"

listen:
  -
      port: 5280
      module: ejabberd_http
      request_handlers:
        "/websocket": ejabberd_http_ws
        "/rest": mod_rest
      web_admin: true
      http_bind: true
      captcha: true

modules:
  mod_rest: {}

INSTALLATION INFO
$/sbin/ejabberdctl module_install mod_rest
src/mod_rest.erl:27: Warning: undefined callback function depends/2 (behaviour 'gen_mod')
ok

ejabberd.log

2016-08-24 11:14:31.516 [error] <0.3683.0> CRASH REPORT Process
  <0.3683.0> with 0 neighbours crashed with reason: bad argument in call
  to erlang:binary_to_list({127,0,0,1}) in str:tokens/2 line 242

crash.log

2016-08-24 14:42:20 =CRASH REPORT====
    crasher:
      initial call: ejabberd_http:init/2
      pid: <0.3274.0>
      registered_name: []
      exception error: bad argument: [{erlang,binary_to_list,[{127,0,0,1}],[]},{str,tokens,2,[{file,"src/str.erl"},{line,242}]},{acl,parse_ip_netmask,1,[{file,"src/acl.erl"},{line,536}]},{mod_rest,'-ip_matches/2-fun-0-',2,[{file,"src/mod_rest.erl"},{line,144}]},{lists,any,2,[{file,"lists.erl"},{line,1225}]},{mod_rest,check_member_option,3,[{file,"src/mod_rest.erl"},{line,134}]},{mod_rest,process,2,[{file,"src/mod_rest.erl"},{line,55}]},{ejabberd_http,process,5,[{file,"src/ejabberd_http.erl"},{line,363}]}]
      ancestors: [<0.3190.0>,ejabberd_listeners,ejabberd_sup,<0.2578.0>]
      messages: []
      links: [#Port<0.35648>]
      dictionary: []
      trap_exit: false
      status: running
      heap_size: 1598
      stack_size: 27
      reductions: 1894
    neighbours:


text:
Q: Import several sheets from the same excel into one dataframe in pandas I have one excel file with several identical structured sheets on it (same headers and number of columns) (sheetsname: 01,02,...,12).
How can I get this into one dataframe?
Right now I would load it all seperate with:
df1 = pd.read_excel('path.xls', sheet_name='01')
df2 = pd.read_excel('path.xls', sheet_name='02')
...

and would then concentate it.
What is the most pythonic way to do it and get directly one dataframe with all the sheets? Also assumping I do not know every sheetname in advance.

A: read the file as:
collection =  pd.read_excel('path.xls', sheet_name=None)

combined = pd.concat([value.assign(sheet_source=key)
                      for key,value in collection.items()],
                     ignore_index=True)

sheet_name = None ensures all the sheets are read in.
collection is a dictionary, with the sheet_name as key, and the actual data as the values. combined uses the pandas concat method to get you one dataframe. I added the extra column sheet_source, in case you need to track where the data for each row comes from.
You can read more about it on the pandas doco

A: you can use:
df_final = pd.concat([pd.read_excel('path.xls', sheet_name="{:02d}".format(sheet)) for sheet in range(12)], axis=0)


text:
Q: What is the best tool to save a HTML file? Suppose I see a HTML page and I want to save it on disk. Using all methods I found, the saved sites are never same as they look in a browser.
So is there any free tool that can be used to save websites? It should also download every file, like CSS, JavaScript and images.

A: httrack works well enough that i often use it for converting dynamic websites into static sites for various reasons. Needs a little tweaking to get just right (how deep you want to download, whether you want external files, etc), but in terms of output, its as good as it gets.


text:
Q: condition for the existence of lines on degree four hypersurface in P^3.. i just wanted to know some necessary and sufficient conditions

A: The point of this answer is to show that the answer should be a degree 320 hypersurface in $\mathbb{P}^{34}$. This suggests that you should NOT want to compute the answer explicitly if you can possibly avoid it. On the other hand, as I suggest in the comments to my other answer, it should be tractable to check whether individual points are in it.
Note: This is a standard example of how to do computations with Chern classes. I'm not going to explain all the terminology I use. The standard references are Griffiths and Harris, or Fulton. There was also a superb course taught by Joe Harris at Harvard in 2002. There used to be notes from it online; I don't know if they are still available somewhere.
So: Let $G(2,4)$ be the Grassmannian of lines in $\mathbb{P}^3$. Let $X \to G(2,4) \times \mathbb{P}^3$ be the incidence variety of pairs (line, point on line) in $\mathbb{P}^3$. So $X \to G(2,4)$ is a $\mathbb{P}^1$-bundle.
Then we can pull back $\mathcal{O}(4)$ from $\mathbb{P}^3$ to $X$, getting a line bundle, and we can push this line bundle forward from $X$ to $G(2,4)$ getting a rank $5$ vector bundle $V$ on $G(2,4)$. Conceptually, for $\ell$ a line in $\mathbb{P}^3$, the fiber of $V$ above the point $[\ell]$ of $G(2,4)$ is $H^0(\ell, \mathcal{O}(4)|_{\ell})$.
In particular, if $F$ is any section in $H^0(\mathbb{P}^3, \mathcal{O}(4)$, we can pull-push $F$ to a section of $V$ on $G(2,4)$. This section, on $\ell$, is $F|_{\ell}$ and, in particular, vanishes at $[\ell]$ if and only if $F$ vanishes on $\ell$.
Now, a generic $F$ will not vanish on any line. We want to know the degree of the hypersurface of $F$'s that will. In other words, given two sections $F_1$ and $F_2$ of $V$, we want to know how many of the linear combinations $a_1 F_1 + a_2 F_2$ have zeroes somewhere on $G(2,4)$. Now, such $a_1$ and $a_2$ exist if and only if $F_1$ and $F_2$ are linearly dependent somewhere on $G(2,4)$. What one expects (but needs to prove) is that, for each point of $G(2,4)$ where $F_1$ and $F_2$ become linearly dependent, one finds exactly one degree $4$ form $a_1 F_1  + a_2 F_2$ (up to scalar) such that $a_1 F_1 + a_2 F_2$ vanishes at that point.
Now, the places where $2$ sections of $V$ become linearly dependent are counted (with multiplicity) by the Chern class $c_4(V)$. One expects that there are no multiplicites, so one wants to compute $c_4(V)$.
The cohomology ring of $G(2,4)$ is
$$\mathbb{Z}[u, v]^{\mathrm{sym}}/(u^3+u^2v+uv^2+v^3,\ u^4+u^3v+u^2v^2+u v^3+ v^4)$$
where the superscript means to only take symmetric polynomials in $u$ and $v$.
In particular, $H^4(G(2,4))$ is spanned by $u^4+v^4$, $u^3 v + u v^3$, $u^2 v^2$ modulo the relations $u^3 v + u v^3 = - u^2 v^2$ (because  $u^3 v + u^2 v^2 + u v^3 = (u+v)(u^3+u^2 v + u v^2 + v^3) - (u^4+u^3v+u^2v^2+u v^3+ v^4)$) and $u^4 + v^4 = 0$ (because $u^4 + v^4 = -(u+v)(u^3+u^2 v + u v^2 + v^3) +2 (u^4+u^3v+u^2v^2+u v^3+ v^4)$).
The Chern roots of $V$ are $4u$, $3u+v$, $2u+2v$, $u+3v$ and $4v$. (Write $V = \mathrm{Sym}^4 (S^*)$, where $S$ is the tautological bundle, and recall that the Chern roots of $S$ are $-u$ and $-v$.)  So $c_4(V)$ is the fourth degree term in $(1+4u)(1+3u+v)(1+2u+2v)(1+u+3v)(1+4v)$. Thanks to Mathematica, this is $24 u^4 + 304 u^3 v + 624 u^2 v^2 + 304 u v^3 + 24 v^4$. Modulo the relations $u^3 v + u v^3 = - u^2 v^2$ and $u^4 + v^4 = 0$, this is $320 u^2 v^2$. Recalling that $u^2 v^2$ is the fundamental class, we get that there are $320$ lines on which $F_1$ and $F_2$ become linearly dependent, so the hypersurface in question has degree $320$.

A: I don't know if there is a necessary and sufficient condition, but there are a few things you can say. Let's say $X$ is a $K3$
1) If a $X$ it contains a line, then it contains a smooth rational curve
2) If a $X$ contains a smooth rational curve $C$, then $C^2=-2$.
3) If $X$ contains a smooth rational curve, then its Picard number is at least $2$.

4) If there is any effective $1$-cycle on $X$ whose self-intersection is negative, then $X$ contains a class with self-intersection $-2$.
5) If $X$ contains a class with self-intersection $-2$, then it contains a smooth rational curve.
6) If the Picard number of $X$ is at least $12$, then it contains a smooth rational curve.

7) A degree four surface in $\mathbb P^3$ is a $K3$ with a very ample Cartier divisor $H$ such that $H^2=4$ and $\dim |H|=4$.
8) A $K3$ surface embedded into $\mathbb P^3$ as a degree four surface contains a line if and only if it contains an effective $1$-cycle $L$ with $L^2=-2$ and $H\cdot L=1$ where $H$ is the very ample line bundle from 5). (Edit: originally here I said "indecomposable" $1$-cycle, but I just realized that the condition $H\cdot L=1$ implies that) Unfortunately, I don't think this is a very useful criterion as this is just a reformulation of the fact that $L$ is a line on a degree four surface in $\mathbb P^3$.

Summary there are some relatively good criteria to check whether or not $X$ contains a smooth rational curve, at least if you think that knowing the Picard number, or the range of self-intersection numbers is a good criterion. It is harder to tell whether it is a line.
On the other hand, if you make up any even quadratic form of signature $(1,\varrho-1)$ on a lattice of rank at most $11$, then it will occur as the Picard lattice of a $K3$, so if you ensure that your quadratic form has an $H$ and an $L$ as above, then there is a good chance that there is a degree four surface with that Picard lattice. It is not entirely certain of course, because the lattice does not tell you $\dim|H|$ but I think it suggests that there are many possibilities.
Another interesting fact is that if you take any degree four surface that contains two lines contains many other smooth rational curves as well. In other words, knowing that locating smooth rational curves is very far from locating lines.

A: Here's how to obtain such a condition in principle. Doing it in practice will require a computer algebra system, and may need a lot of computer power:
The generic line in $\mathbb{P}^3$ can be parameterized as $(x:y:ax+by:cx+dy)$ for some $(a,b,c,d)$. More specifically, this is the dense Schubert cell in $G(2,4)$. Let your degree $4$ polynomial be $F$. Write
$$F(x,y,ax+by,cx+dy) = A(a,b,c,d) x^4 + B(a,b,c,d) x^3 y + \cdots + E(a,b,c,d) y^4.$$
So $A$, $B$, $C$, $D$ and $E$ are $5$ polynomials in $4$ variables, each non-homogenous with maximal degree $4$. Let their resultant be $R$. (If you haven't heard of multivariate resultants, skip to the end.) Then $R=0$ is a necessary condition for $F$ to contain a line. There will most likely be some factor $Q$ of $R$ which is a necessary and sufficient condition, but I don't immediately see a better way to obtain $Q$ than by factoring $R$ and trying points on each irreducible component.
Why does this happen? Well, if there is a line $\ell$ in $F=0$, and $\ell$ lies in the dense cell of $G(2,4)$, then $(A,B,C,D,E)$ have a common root so $R$ vanishes. If we have a pair $(F, \ell)$, but $\ell$ is not in the dense cell, then let $g(t)$ be a generic path in $PGL_4$, with $g(0) = \mathrm{Id}$. Then $g(t) \ell$ is in the dense cell for $t \neq 0$, and the preceeding argument shows that $R$ vanishes on $g(t)^* F$. By continuity, $R$ vanishes on $F$.
Why isn't this argument invertible? The vanishing of $R$ is equivalent to the homogenized versions of $(A,B,C,D,E)$ having a common root in $\mathbb{P}^4$. But what we want to know is whether the hypersurfaces they define have a common root in $G(2,4)$. There is a birational map $G(2,4)$ to $\mathbb{P}^4$, but it is not an isomorphism, so the hypersurfaces might meet in $\mathbb{P}^4$ but become disjoint in $G(2,4)$. I don't know for sure whether this happens in this case, but it often does. The good thing is that we suspect that the actual locus we are hunting for is codimension $1$, so we can find it as a factor of the polynomial $R$.
There is a computation we should do before this one, because it will help check for errors and tell us what to expect. We should compute what we expect the degrees of $Q$ and $R$ to be. EDIT: In my pother answer, I show that $Q$ should have degree $320$.
Finally, I wanted to point you to a quick online reference for computing resultants of multi-variate polynomials, but all the sources I checked only had the one variable case (or, equivalently, two variables with homogenous polynomials). The famous reference here is the book of Gelfand, Kapranov and Zelevinsky, but that is quite an undertaking. The one thing I will do is alert you to the Cayley trick: The resultant of $(A,B,C,D,E)$ is the same as the discriminant of
$$A(a,b,c,d) + B(a,b,c,d) w + \cdots + E(a,b,c,d) z$$
where $(w,x,y,z)$ are auxilliary variables. So you can compute a disciminant in $8$ variables instead of a resultant in $4$, if your software prefers that.


text:
Q: How to combine small pages of varying size to A4 I have about 80 PDF pages, all of which have width of 8.27 inches ( A4 width), but the height varies - e.g. some are 4" tall, others are 2.5" tall - there is no standard height. Let me call them snippets. I am looking to combine them so that they can fit into A4 size pages.
I have come across some utilities like nup or pdfnup but these all assume that the pages to be combined are of identical size ( say A5, to be combined into A4) . I don't care about the order of the pages, but I need to make sure that these snippets don't get cut off  (or spill over into the next page) when combined.
Think of it like how one would handle pasting snippets in a scapbook. If a snippet fits into a A4 page, I add to the page (no rotation etc). If some space gets left on the page, I can add another snippet that can fit in the space available. If not, I can use another page. However, the snippet must not get cut or spillover to another page.
I doubt if there is any utility/command that can do it automatically. I can work by adding snippets manually one by one - I am just looking for a suggestion on how to do it, or just help me get started.

A: If I execute
for i in /usr/local/texlive/2017/texmf-dist/tex/latex/mwe/*.pdf; do echo '\begin{center}\includegraphics{'`basename $i`'}\end{center}';done > list.tex

in a (bash) command window then I get a document list.tex that looks like
\begin{center}\includegraphics{example-grid-100x100bp.pdf}\end{center}
\begin{center}\includegraphics{example-grid-100x100pt.pdf}\end{center}
\begin{center}\includegraphics{example-image.pdf}\end{center}
\begin{center}\includegraphics{example-image-10x16.pdf}\end{center}
\begin{center}\includegraphics{example-image-16x10.pdf}\end{center}
\begin{center}\includegraphics{example-image-16x9.pdf}\end{center}
\begin{center}\includegraphics{example-image-1x1.pdf}\end{center}
\begin{center}\includegraphics{example-image-4x3.pdf}\end{center}
\begin{center}\includegraphics{example-image-9x16.pdf}\end{center}
\begin{center}\includegraphics{example-image-a.pdf}\end{center}
\begin{center}\includegraphics{example-image-a3.pdf}\end{center}
\begin{center}\includegraphics{example-image-a3-landscape.pdf}\end{center}
\begin{center}\includegraphics{example-image-a4.pdf}\end{center}
\begin{center}\includegraphics{example-image-a4-landscape.pdf}\end{center}
\begin{center}\includegraphics{example-image-a4-numbered.pdf}\end{center}
\begin{center}\includegraphics{example-image-a5.pdf}\end{center}
\begin{center}\includegraphics{example-image-a5-landscape.pdf}\end{center}
\begin{center}\includegraphics{example-image-b.pdf}\end{center}
\begin{center}\includegraphics{example-image-c.pdf}\end{center}
\begin{center}\includegraphics{example-image-golden.pdf}\end{center}
\begin{center}\includegraphics{example-image-golden-upright.pdf}\end{center}
\begin{center}\includegraphics{example-image-letter.pdf}\end{center}
\begin{center}\includegraphics{example-image-letter-landscape.pdf}\end{center}
\begin{center}\includegraphics{example-image-letter-numbered.pdf}\end{center}

then I just need a file
\documentclass[a4paper]{article}
\usepackage{graphicx}
\begin{document}

\input{list}
\end{document}

which produces the following. Obviously the list.tex file could be hand edited to re-order or scale the images as required.
The first four pages look like:

which is a bit of a mess, but you said your pdfs all have the same width so it should work better.


text:
Q: Can't run python GUI on thread started by main thread. Any alternatives or workarounds? I've been trying out python GUI frameworks for a multithreaded project that requires the GUI to run entirely on a thread started from the main thread with a reference to a variable being updated on a different thread. However, when I run the GUI on a thread other than the main one it instantly closes and I get

"QApplication::exec: Must be called from the main thread"

when using pyqt5 and

"RuntimeError: main thread is not in main loop"

when using tkinter.
I was wondering if anyone knew another python GUI framework that would let me run it on a thread other than the main thread or if there is a way to work around this errors.
Here is an example replicating the first message with pyqt5
import  threading, sys

from PyQt5.QtCore import QObject
from PyQt5.QtWidgets import QMainWindow, QApplication

class Example(QMainWindow):

    def __init__(self, app):
        super().__init__()

        self.app=app
        self.initUI()

    def initUI(self):
        self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle('Example')
        self.show()

    def principal(self):

        sys.exit(self.app.exec_())

def main():

    app = QApplication(sys.argv)
    example = Example(app)

    #sys.exit(example.app.exec_())

    exampleThread = threading.Thread(target=example.principal, name='example')
    exampleThread.start()

main()


text:
Q: Jquery for duplicate tabs I am trying to create tabs in jquery and have been successful. However, there is one issue I am unable to solve and that is duplicate tabs.
With a single tab, jquery works fine but when I copy and paste that tab it does not work properly. I did add some extra code to find the tab in which the use is currently in by using the closest function but still no result.
Have a look at the code.
//HTML

            Tab One

            Tab Two

            Tab Three

            This is tab 1

            This is tab 1

            This is tab 1

            This is tab 2

            This is tab 2

            This is tab 2

            This is tab 3

            This is tab 3

            This is tab 3

//2nd tab

            Tab One

            Tab Two

            Tab Three

            This is tab 1

            This is tab 1

            This is tab 1

            This is tab 2

            This is tab 2

            This is tab 2

            This is tab 3

            This is tab 3

            This is tab 3

CSS Code
.tabsContainer{
    overflow:hidden;
}
.tabs-nav{
    overflow:hidden;
    margin:0;
    padding:0;
    list-style:none;
}
.tabs-nav li {
    display: inline-block;
    background: #34495E;
    border-width: 1px 1px 0 1px;
    border-style: solid;
    border-color: #34495E;
    margin-right: 5px;
}
.tabs-nav li a {
    display: block;
    padding: 10px 15px;
    font-weight: bold;
    color: #fff;
}
.tabs-nav li a.active {
    background: #FFF;
}

.tabs-nav li a.active {
    color: inherit;
}
.tabs-content {
    border: 1px solid #34495E;
    padding: 10px;
    background: #FFF;
    margin-top: -1px;
    overflow:hidden;
}
.tabs-content .tabs{
    overflow:hidden;
    display:none;
    margin:0 0 30px;
}
.tabs-content .tabs.active{
    display:block;
}

JAVAScript
$(function() {

    //listeing for click events
    $('.tabsContainer .tabs-nav li a').on('click', function(){

        //if more than 1 tab find out which tab you are currently in using the closest function
        //by clicking on the a tag it will find which container it is a part of.
        var $tab = $(this).closest('.tabsContainer');

        $tab.find('.tabs-nav li a.active').removeClass('active');
        $(this).addClass('active');
        //grabbing the tab which is clicked using the attribute "href"
        var currentClick = $(this).attr('href');

        //hiding the current panel
        //using a call back function. What this does is wait for the slideup to finish and then it will excute the call back function
        $tab.find('.tabs-content .tabs.active').slideUp(300, nextTab);

        //the call back function to show the new tab
        function nextTab(){
            $(this).removeClass('active');
            $(currentClick).slideDown(300, function(){
                $(this).addClass('active');
            });
        }
    });
});

A: Your $(currentClick) will select elements started from body since you don't specify the parent scope. So if the currentClick value is #tab1, the select result is comes from the first tab, not from the current a parent.
I prefer to wrap the tab processing to each tab scope. Example:
$('.tabContainer').each(function() {
    var tab = $(this);
    // Do the tab processing here.
});

See the JSFiddle sample.

A: I figured out the problem, made a rookie mistake in the html. In both the tabs container I did not change the  tag href. In the 1st tab container it is #tab1, #tab2, #tab3. This is the same in the 2nd container which was causing the problem, the tab numbering should be different. That is why the tabs for not working properly.
@Nanang Mahdaen El-Agu Thank you for your code, I learned something new with your help :)


text:
Q: AngularJS: Where to put which logic when building an HTML widget I'm very(!) new to Angular.js and am trying to understand where to put the various parts of my logic in order to follow best practices and separate business and presentation logic.
My specific use case is that I have a list of courses with a number of signups and a number of available seats. Based on these values I want to present a progress bar (or, if the available seats is not set, just a text).
My question is where to put the various parts of the logic, and how to pass the values along properly. So far I've created the HTML-part of a directive, like so:
<signupprogress available="{{course.available_seats}}" filled="{{course.filled_seats}}"></signupprogress>

My question is then (first and foremost) if a directive is the proper way to do this and, of so, if the logic for constructing the progress bar should go in the compile function, link function, in a template, or some other place. To me the compile of link function seems to be most correct, but I don't want to fill them with HTML, nor am I able to properly get the attribute values from the HTML (the attrs.$observe examples I've seen only implement the getting of one attribute).

A: The directive is the way to go in my opinion.
I would have my HTML content inside of a template, the logic inside of the link function (the compile function is usually more for repeaters etc).
And use the "scope" property in the directive definition, set to "=", that way changes are reflected automatically.

A: Yes, use a directive since you need to modify the DOM.
If all of the HTML for the progress bar and the alternative text can be placed in the directive's template, then do that.  And, if that is possible, use '@' for one-way binding, which makes it clear that the directive does not need to modify the "available" and "filled" values.  If you find you need a linking function, then as @ShaiRez mentioned, '=' is probably easier. (BTW, here is a way to $watch multiple attributes, instead of using $observe.  Maybe the same technique can be used for $observe.)
To display either a progress bar or the alternative text in the template, use ng-hide or ng-show in the template.  Here's a simple example of that (which also uses '@').


text:
Q: Move files to a specific folder when run the setup file for VB.Net Application I have created deployment package for VB.Net appolication and it runs fine. When setup is rnning, I want deployment package to move a file from bin folder to other specific folder.
Please suggest, how can I move this file to specific folder.
Any help would be appreciated.
Thanks, Yogi

A: In Visual Studio 2008 setup project,
Select File System on Target Machine and then from Action menu select Add Special folder and then Custom folder. A new folder will apear on left hand side under the "File System on Traget Machine". Add files, into this custom folder, which you want to copy into into specified location,
Now go into the property of this custom folder and set the DefaultLocation where you want to copy files under this custom folder.
Now when you run the setup this file under the custom folder will copy into the specified location which you set in DefaultLocation.
Yogi..


text:
Q: How does one pass parameters to a function in Swift? Missing argument in call Swift function parameters not accepted. Missing argument?
Calculate(theA, theB) //error: Missing argument label 'sideB:' in call

func Calculate(sideA: Int, sideB: Int) -> Int {
    var ans = sideA + sideB
    return ans;
}

A: You are missing the sideB: in your function call. I didn't want to rewrite your code (since you posted an image) but here's the working function call.
func calcButton(sender: AnyObject) {
    let a: Int = 10
    let b: Int = 11

    calculate(a, sideB: b) //<-- Missing it here
}

func calculate(sideA: Int, sideB: Int) -> Int {
    let a = sideA + sideB
    return a
}

you might also want to have both variables in the function call so you can do this instead:
func calcButton(sender: AnyObject) {
    let a: Int = 10
    let b: Int = 11

    calculate(sideA: a, sideB: b)
}

func calculate(sideA A: Int, sideB B: Int) -> Int {
    return A + B
}

Just an FYI, use tab completion instead of writing out the function. Xcode will let you know all the function variables with placeholders so you can type them in.

A: you have missed the sideB param name in swift 3 first parameter is optional but second param is Mandatory that _ in there That's an underscore. It changes the way the method is called. To illustrate this, here's a very simple function:
func doStuff(thing: String) {
    // do stuff with "thing"
}

It's empty, because its contents don't matter. Instead, let's focus on how it's called. Right now, it's called like this:
doStuff(thing: "Hello")

You need to write the name of the thing parameter when you call the doStuff() function. This is a feature of Swift, and helps make your code easier to read. Sometimes, though, it doesn't really make sense to have a name for the first parameter, usually because it's built into the method name.
When that happens, you use the underscore character like this:
func doStuff(_ thing: String) {
    // do stuff with "thing"
}

That means "when I call this function I don't want to write thing, but inside the function I want to use thing to refer to the value that was passed in.


text:
Q: How can I export drawing from Notes to an image with background on an iPad? When I save drawing from the Notes app to Photos, the saved image has a transparent background instead of the background I see in the Notes app.
You can see the transparent background if you open the image in Google Photos or share the picture to any other app, e.g. opening that in the Preview app on macOS.
It is annoying when I share the image to some people and they couldn't see it clearly because of the transparent background.
Is there any way to export the drawing with the background (grids and lines) I've selected for the note?

A: A third, more crude method, which you can use if a certain part of your doodle requires background lines/grids is taking  screenshot of the doodle.
Step 1;
Expand the note using the button in the top right of the screen.
Step 2;
Hide the panel showing pens and colors using the "x" at the bottom right of the panel.
Step 3;
Take a screenshot by pressing the home and power buttons at the same time.
Step 4; Crop the screenshot to show only the desired result.
The end result is something like this;

A: There are two methods of saving a doodle in notes to Photos I have seen so far. First one saves the doodle as JPG and the latter as PNG. JPG would keep the background as the default white while PNG would render pixel-less areas.
Method 1. On the image, tap for some seconds and select share from the tooltip that appears. Tap save image.
Result:

Method 2. Use the share button in the top right and tap save image.
Result:


text:
Q: Check if user is in AD group using Javascript I need to check if user is part of an AD Group with Javascript.
I've created a SP group and I added an AD Group to it and I am part of this group.
I removed my user from Site Administrators and Site owners (group with full control).
Then I tried the code found here: https://stackoverflow.com/a/43673723/2185964
But the code above did not worked. Is it possible that it is an issue caused by users profile sync? Or there is a way to add to SharePoint user profile the AD group or OU or AD directory where an user belongs and get this property using JavaScript?


text:
Q: Fill NAs in a Column with samples from itself Simple toy dataframe:
df = pd.DataFrame({'mycol':['foo','bar','hello','there',np.nan,np.nan,np.nan,'foo'],
                  'mycol2':'this is here to make it a DF'.split()})
print(df)

   mycol mycol2
0    foo   this
1    bar     is
2  hello   here
3  there     to
4    NaN   make
5    NaN     it
6    NaN      a
7    foo     DF

I'm trying to fill the NaNs in mycol with samples from itself, e.g. I want the NaNs to be replaced with samples of foo,bar,hello etc.
# fill NA values with n samples (n= number of NAs) from df['mycol']

df['mycol'].fillna(df['mycol'].sample(n=df.isna().sum(), random_state=1,replace=True).values)

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

# fill NA values with n samples, n=1. Dropna from df['mycol'] before sampling:

df['mycol'] = df['mycol'].fillna(df['mycol'].dropna().sample(n=1, random_state=1,replace=True)).values

# nothing happens

Expected Output: Nas filled with random samples from mycol:
   mycol mycol2
0    foo   this
1    bar     is
2  hello   here
3  there     to
4    foo   make
5    foo     it
6  hello      a
7    foo     DF

edit for answer: @Jezrael's answer below sorted it, I had a problem with my indexes.
df['mycol'] = (df['mycol']
               .dropna()
               .sample(n=len(df),replace=True)
               .reset_index(drop=True))

A: Interesting problem.
For me working set values with loc with converting values to numpy array for avoid data alignment:
a = df['mycol'].dropna().sample(n=df['mycol'].isna().sum(), random_state=1,replace=True)
print (a)
3    there
7      foo
0      foo
Name: mycol, dtype: object

#pandas 0.24+
df.loc[df['mycol'].isna(), 'mycol'] = a.to_numpy()
#pandas below
#df.loc[df['mycol'].isna(), 'mycol'] = a.values
print (df)
   mycol mycol2
0    foo   this
1    bar     is
2  hello   here
3  there     to
4  there   make
5    foo     it
6    foo      a
7    foo     DF

Your solution should working if length of Series and index same like original DataFrame:
s = df['mycol'].dropna().sample(n=len(df), random_state=1,replace=True)
s.index = df.index
print (s)
0    there
1      foo
2      foo
3      bar
4    there
5      foo
6      foo
7      bar
Name: mycol, dtype: object

df['mycol'] = df['mycol'].fillna(s)
print (df)

#   mycol mycol2
0    foo   this
1    bar     is
2  hello   here
3  there     to
4  there   make
5    foo     it
6    foo      a
7    foo     DF

A: you can do forward or backward fill:
#backward fill
df['mycol'] = df['mycol'].fillna(method='bfill')

#forward Fill
df['mycol'] = df['mycol'].fillna(method='ffill')


text:
Q: Does "current directory" refer to where I run the command `javac`? the java doc says

The default value of the class path is ".", meaning that only the current directory is searched. Specifying either the CLASSPATH variable or the -cp command line switch overrides this value.

Does "current directory" refer to where I run the command javac?
For example, I sign in my Windows with the account ubuntu, so the command prompt starts at C:\Users\ubuntu. And then I run the command
C:\programs\java\jdk8\bin\javac D:\soucecode\Hello.java. In this situation, does current directory refer to C:\Users\ubuntu\ or D:\soucecode\?

A: Current directory is the directory where you run your command.
Since you ran your command (javac) in C:\Users\ubuntu it will be the directory.


text:
Q: Tag badge not granted in long time, more than a few weeks I seem to be due a tag badge on pointfree tag for a long time now, more than a few weeks I think, but I've yet to receive it. I'm the first one that made the cut there.

Yes, I did retagged many of the posts now in the tag, but not all of them were with my answers, and all of them were valid edits IMHO. This answer says it's OK and "improves the site" as long as "edit is accurate". Naturally it was easier for me to find such posts among my answers, but I did manage to find a few others and tagged them as well.
Is this a bug?

A:
A tag must appear on a minimum of 100 questions to be considered for tag badges.

Only 66 questions are under that tag.


text:
Q: Progressively store the path from root node to node of multiway tree during insertion so that the storage operation does not have a complexity of O(n) I would like to ask if someone knows a performant way to store the path from the root node to a new node of a multiway tree during the insertion of the new node. E.g., if I have the following tree:

For each node, I currently store an array of the path to the node from the root node during insertion in the following way by assigning a unique int ID to each children on the same depth:
Root node -> [1]

Depth 1, child 1 of root -> [1, 1]
Depth 1, child 2 of root -> [1, 2]

Depth 2, child 1 of parent 1 -> [1, 1, 1]
Depth 2, child 2 of parent 1 -> [1, 1, 2]
Depth 2, child 3 of parent 1 -> [1, 1, 3]
Depth 2, child 1 of parent 2 -> [1, 2, 4]
Depth 2, child 2 of parent 2 -> [1, 2, 5]

Depth 3, child 1 of parent 3 -> [1, 1, 3, 1]

...

If I now insert a new node from the leaf node 1 on depth 3, I would have to create a new path array for it storing all the nodes of the parent 1 (i.e. [1, 1, 3, 1]) plus the new child ID, which is 1 for the first child:
Depth 4, child 1 of parent 1 -> [1, 1, 3, 1, 1]

As my tree grows a lot in height (the number of children per depth is relatively low, but the depth can be high), the slow part of this algorithm would be this array recreation process. Just imagine a tree of depth 1.000.000, if I insert a new node from a node of depth 1.000.000, I would have to create a new array for this new node storing all the 1.000.001 IDs of the parent plus appending the new node's ID:
Depth 1.000.001, child 1 of parent x -> [...1 million and one IDs... , 1]

Is there a more efficient way to store the path on each node during node's insertion?
I basically need this to determine if any given node is a child of a possible parent node in the tree and as I have the path stored in each node, I can easily do that by checking the path array of the child, like this:
// Ex. 1
Is node 4 of depth 2 the parent/ancestor of node 1 of depth 3?

node 1 of depth 3 has the following path array: pathArray = [1, 1, 3, 1]
Its ancestor ID on depth 2 is: pathArray[2] -> 3

3 != 4 and therefore I know that node 4 of depth 2
is not a parent of node 1 of depth 3.

// Ex. 2
Is node 1 of depth 1 the parent/ancestor of node 1 of depth 3?

node 1 of depth 3 has the following path array: pathArray = [1, 1, 3, 1]
Its ancestor ID on depth 1 is: pathArray[1] -> 1

1 == 1 and therefore I know that node 1 of depth 1
is a parent of node 1 of depth 3.

This lookup operation would be fast, the problem is the creation of the path array as the tree goes deeper.
Any suggestions would be appreciated.
Thank you for the attention.

A: Right now, your solution has O(1) lookup time, O(h) insert time and O(n^2) space conpelxity, where n is the number of nodes and' h is the height, which is at most n.
You can achieve a tradeoff with O(log n) lookup, O((log n)^2) insert and O(n log n) space in the following way:
Let every node store one jump pointer to each of its ancestors with distance 1 (its parent), 2 (grandparent), 4 (grandparent's grandparent), 8, 16 and so on, until the root is reached or passed. The maximum distance from any node to the root is n, so for every node you store O(log n) jump-pointers. Since you do this for every node, the total space complexity is O(n log n).
Answering the query of whether y is an ancestor of x is trivial if y doesn't have a lower depth than x. Name the depths of the nodes dy and dx. You know that if y is an ancestor of x, then it is the dx-dy'th ancestor of x. That is, if dy = 5 and dx = 17, you know that if y is x's ancestor, then it is 17 - 5 levels above x.
Therefore, you can perform lookups by recursively jumping the largest possible distance upwards in the tree from x without overshooting the target ancestor. For instance, if you're starting at depth 16 and want to find the ancestor at depth 6, you're interested in the ancestor 10 levels above. You cannot jump 16 levels up, as this would overshoot the target ancestor, so you jump 8 instead. Now you're at depth 16-8=8, and the remaining distance to the target ancestor, which is 6, is 2. Since there is a pointer which goes exactly two steps up, you follow that and you've arrived at the target ancestor.
Every time you follow a pointer upwards in the tree, you're getting at least half way to your target, so the maximum number of pointers you can follow is O(log n).
When inserting a node e as a child of another node x you can construct e's jump-pointers by finding x's ancestors with distance 1, 3, 7, 15, etc. (since e is one level further away from all of these than x is). There are O(log n)such searches. As we argued above,  each of the lookups take O(log n) time. Thus the total is O((log n)^2).
This operation might even be made even faster by storing some additional information, but I can't see exactly how just now.
NOTE
This idea is actually a part of the classical solution for the Level Ancestor Problem. The classical solution allows for lookups as you have described them in O(1) time, while keeping the space of the entire data structure to O(n). However, the data structure is static, so the solution does not specify how to do insertions. There might be a way to adapt the level ancestor to a dynamic scenario and get even better running times than I've described here, but I'm not sure how.

A: Arrays have all their values stored contiguously in the memory. If you want to retain this property you must use them. Or, if you are OK with hoping through several memory locations, you can store in every node only its immediate parent and trace up to the required level to do the check required.

A: Map your nodes in a HashMap<node-id, node>.

Now, when you have to

determine if any given node is a child of a possible parent node,

You can find the exact location of that node in the tree from the HashMap and then travel back up the tree using the parent pointers to see if the possible parent lies on the path to root.
In a fairly balanced tree, this will be O(Log n) run-time (to traverse up the tree) and O(n) space (of HashMap).

If you go with your current design of storing the path from each node to root, then you would have O(Log n) run-time (assuming a balanced tree) and O(n * Log n) space to store the Log n length path for each of the n nodes.


text:
Q: How to configure DNS Server on Fedora I want to learn how to configure my home PC server into a web server with domain and host.
My IP is 109.99.141.133 and now points to a phpinfo page host on my home server. My registed domain is: anunta-anunturi.ro
I searched for a tutorial and I've read that I have to configure /etc/named.conf and the file sources for the new zone that I create.
So, from the tutorials, my /etc/named.conf looks like this:
 //
// named.conf
//
// Provided by Red Hat bind package to configure the ISC BIND named(8) DNS
// server as a caching only nameserver (as a localhost DNS resolver only).
//
// See /usr/share/doc/bind*/sample/ for example named configuration files.
//

options {
        listen-on port 53 { 127.0.0.1; };
        listen-on-v6 port 53 { ::1; };
        directory       "/var/named";
        dump-file       "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
        allow-query     { localhost; };
        recursion yes;
        dnssec-enable yes;
        dnssec-validation yes;
        dnssec-lookaside auto;
        /* Path to ISC DLV key */
        bindkeys-file "/etc/named.iscdlv.key";
        managed-keys-directory "/var/named/dynamic";
};
logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};
zone "anunta-anunturi.ro" IN {
        type master;
        file "/etc/anunta-anunturi.db";
};
zone "." IN {
        type hint;
        file "named.ca";
};
include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";

My /etc/anunta-anunturi.db file looks like this — I'm not sure if this is okay, or if it's the easy one.
$TTL    86400
anunta-anunturi.ro. IN SOA serveur.anunta-anunturi.ro. root.serveur.anunta-anunturi.ro. (
                                                1997022700 ; Serial
                                                28800      ; Refresh
                                                14400      ; Retry
                                                3600000    ; Expire
                                                86400 )    ; Minumun

        IN              NS              serveur.anunta-anunturi.ro.
        IN              MX      10      mail.anunta-anunturi.ro.

serveur.anunta-anunturi.ro.     IN      A       192.168.1.37
www.anunta-anunturi.ro.         IN      A       192.168.1.37
mail.anunta-anunturi.ro.        IN      A       192.168.1.37

Extra info:

*

*At home I receive internet from my ISP through a router. My home PC and server recieve their IP automatically from the router when I start/restart.

*In my local home network, my server receives the IP 192.168.1.37 from the router.

*When I enter 109.99.141.133 in my browser, it points to the rooter that forwards port 80 to local IP 192.168.1.37 (my home server)
Questions:

*

*Are my two files good?

*What/where is my nameserver that I need to copy/paste to my top level domain (where I registered my domain: rotld.ro)?

A: Hey if your not familiar with DNS configuration I would look at webmin. It provides a web interface for easily configuring stuff like this and takes out a lot of work.
Once the DNS server is up and running you can manually set your computer to use said DNS server IP to make sure the name resolution is working. Also make sure you have set some forward lookup addresses so you can resolve domains other than your own.
After that you will need to enable port forwarding on port 53 to the internal DNS/webserver (192.168.1.37). Lastly set the NS records for your domain through your domain providers DNS configuration page to your public IP address (109.99.141.133).
I didn't think you NEED two DNS servers but it's probably advised.

A: You need two or more publicly routable DNS servers for your domain.
Back in the day, you could host one yourself and provide the second one through a free service such as Granite Canyon. But Granite Canyon is gone.
If the servers are mentioned by domain name, then you'll need to make sure that you also provide glue records for those servers.
Ask your ISP or registrar if they will host your DNS for you -- hosting it yourself is painful.


text:
Q: How can I make Supervisor run on a different port than the default 6001? I have a laravel project and I am using Laravel-Websockets which run under the port 6001. However, I'm installing Supervisor to help run commands automatically, but the Supervisor is running on the same 6001 port and I get
Failed to listen on "tcp://0.0.0.0:6001": Address already in use (EADDRINUSE)
Is there any way to change the Supervisor and make it run under another port? Thank you in advance.


text:
Q: How to manage DirectoryInfo writing/reading exceptions? How to manage DirectoryInfo writing/reading exceptions?
 DirectoryInfo di = new DirectoryInfo(tbKeresesHelye.Text);
 foreach (var f in di.GetFiles("*", SearchOption.AllDirectories))
 {
   richTextBox1.Text = richTextBox1.Text + f.Directory + "\\" + f.Name + " >> " + f.Length + "\n";
 }

A: If I understand correctly:
string address = "D:";
DirectoryInfo di = new DirectoryInfo(address);
try
  {
     foreach (var f in di.GetFiles("*", SearchOption.AllDirectories))
     {
        richTextBox1.Document.Blocks.Clear();
        richTextBox1.Document.Blocks.Add(new Paragraph(new Run(f.DirectoryName + f.Name + " >> " + f.Length + "\n")));
     }
   }
catch (Exception ex)
   {
       richTextBox1.Document.Blocks.Add(new Paragraph(new Run(ex.Message)));
   }

Just for your information, it is good practice of exception handling like that:

*

*The most exact exception

*The less exact exception

*the common exception

And  use the throw keyword without an identifier to preserve the original
exception details like that:
catch (DivideByZeroException ex)
{
    throw;
}
catch (InvalidOperationException ex)
{
    throw;
}
catch (Exception ex)
{
    throw;
}


text:
Q: filter Mongo DB collection Im trying to filter a collection using a particular field called (type) in the collection. The field type has six different values (A, B, C, D, E) for example. I want to get the collection for type A, B, C. I tried the below code and is not working
collection.find(and(eq("type", A), eq("type", B), eq("type", C))

Thanks


text:
Q: python sklearn using more than just the count features for naive bayes learning first of all, I am new to python and nlp / machine learning.
right now I have the following code:
vectorizer = CountVectorizer(
   input="content",
   decode_error="ignore",
   strip_accents=None,
   stop_words = stopwords.words('english'),
   tokenizer=myTokenizer
)
counts = vectorizer.fit_transform(data['message'].values)
classifier = MultinomialNB()
targets = data['sentiment'].values
classifier.fit(counts, targets)

now this actually works pretty well. I am getting a sparse matrix through the CountVectorizer and the classifier makes use of the matrix as well as the targets (0,2,4).
However, what would I have to do if I wanted to use more features in the vector instead of just the word counts? I can't seem to find that out. Thank you in advance.

A: In your case counts is a sparse matrix; you can add columns to it with extra features:
import numpy as np
from scipy import sparse as sp

counts = vectorizer.fit_transform(data['message'].values)
ones = np.ones(shape=(len(data), 1))
X = sp.hstack([counts, ones])

classifier.fit(X, targets)

scikit-learn also provides a built-in helper for that; it is called FeatureUnion. There is an example of combining features from two transformers in scikit-learn docs:
estimators = [('linear_pca', PCA()), ('kernel_pca', KernelPCA())]
combined = FeatureUnion(estimators)

# then you can do this:
X = combined.fit_transform(my_data)

FeatureUnion does almost the same: it takes a list of vectorizers (with names), calls them all for the same input data, then concatenates the result column-wise.
It is usually better to use FeatureUnion because you will have easier time using scikit-learn cross-validation, pickling the final pipeline, etc.
See also these tutorials:

*

*http://scikit-learn.org/stable/auto_examples/feature_stacker.html

*http://scikit-learn.org/stable/auto_examples/hetero_feature_union.html

A: It depends on your data and what you are trying to do. There are different transformation methods you can use beside the word counts: Bag of Words, TFIDF, Word Vector, ...
You can read more from these documentation:
- http://billchambers.me/tutorials/2015/01/14/python-nlp-cheatsheet-nltk-scikit-learn.html
- http://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html


text:
Q: Nodes collision testing - but not on bouding rectangles I'm looking for some simple and somehow efficient way to detect collisions of Nodes (not necessarily Sprites) while ignoring collisions of transparent parts of Nodes' images.
It is easy to implement bounding Rects collision... but it does not reflect the transparency.
There were published other approach named "Pixel-perfect"... ok, but I see it as inefficient and somehow complicated. In cases of full-hd and bigger displays...
I suppose it could be possible to yield some "non-transparent" masks of both sprites, get them only in intersect of their bounding rects and finally perform AND operation on those masks...
Please, did anybody see something similar? Or better? Can I yield transparent and non-transparent parts of image of node?
I also found this and this well. Not studied yet but now I'd like use cocos2d-js .... :)
Thanks a lot

A: Give quadtrees a try. The algorithm works by splitting nodes into 4 quadrants recursively into a list with likely collideables. There are plenty of resources about them.
I combined this with pixel perfect check. I'm afraid it's the only way to properly check images' collisions short of using the per pixel algorithm to create unique concave and convex shapes to represent the collision space and then using other algorithms (such as Minkowski portal refinement). However if you images change or are animated, your game can takr an equal performance hit.
Interestingly enough, pp intersection was used in games like pong, with much less processing power. Pp also gives the most accurate intersection as compared to other algorithns.

A: You can use physics collisions. And set-up physics body to repeat not-transparent part of the node.


text:
Q: "It is not true that all the students drink coffee." $S(x)$ means $x$ is a student.
$C(x)$ means $x$ drinks coffee.
I need to turn the statement

"It is not true that all the students drink coffee."

into predicate logic. This is what I have.
¬(∀x, ¬C(x) ∨S(x))
I think it is somewhat correct but I am not sure. I think I am wrong because the next part asks me to simplify the logical expression using the logical equivalence of
$p \implies q \equiv \neg p \vee q$.
What is that asking me to do? Do I have to use my current answer and convert it or is this a completely new thing?

A: Following from the comments, we have $S(x) = $ "$x$ is a student", and $C(x) = $ "$x$ drinks coffee."
So for every student to drink coffee means: $\forall x(S(x) \to C(x))$. We have the statement that not all students drink coffee, so we will negate our statement. First lets convert $\to$ to its logical equivalent: $p \to q \equiv \lnot p \lor q$.
Now let's throw the negation in front of our statement and converting $\to$ to its logical equivalent, we have:
$$\lnot \forall x(\lnot S(x) \lor (C(x))
\\
\exists x \lnot (\lnot S(x) \lor C(x)) \qquad \lnot \forall x \equiv \exists x
\\
\text{Now we will follow the negation through.}
\\
\exists x(\lnot \lnot S(x) \land \lnot C(x)) \qquad \lnot \lor \equiv \land
\\
\boxed{\exists x(S(x) \land \lnot C(x))} \qquad \lnot \lnot p\equiv p \space \text{Double negation.}
$$
Now this translates to, "There exists a student and they do not drink coffee."


text:
Q: Adding ads in my codeigniter application How can I provide view to advertise ads in my codeigniter application. When client adds ads in my app these adds should display dynamically in my application. If there are 100 people given 100 ads then every time user accesses app he should get different ads on each page refresh. For example if fastrack and Levis are the ads given by clients then these ads must keep changing.
If client who is advertising the product chooses option to publish my add only in india then that ad should published only in  india.
please provide me some link or examples related to my question. Thanks in advance.

A: you can use any free ads server script and integrate it in your app. here you have a list of ten http://www.enfew.com/10-php-advertisement-management-scripts/
you can google for more scripts


text:
Q: I want to set priority of product in category-> product view I want to show products with $0 price on last.
I am trying to make changes in file
app/design/frontend/default/YOUR_TEMPLATE/template/catalog/product/view.phtml

if($_product->price==0):

but can't do it and don't know how to do it. Please anyone tell me how can i do it.

A: Go to Catalog->Manage Categories select a category then go to Category Products Tab and set position of product i.e. 1, 2 3 4 etc as you like, on frontend product will display according to your position set i.e 1 will display first and so on.

A: *

*You need do 2 change one is go to admin -> system -> Configuration -> Catalog there in tab Front end you find 'Product Listing Sort by' select price and save config.

*Copy
app\code\core\Mage\Catalog\Block\Product\List
and copy file Toolbar.php and put
app\code\local\Mage\Catalog\Block\Product\List

then change one line
protected $_direction           = 'asc'; to protected $_direction = 'desc';


text:
Q: Zero Width Height jPanel on start Why does the jPanel return 0 for the height and width when it starts and how can I get the right values on start.
import javax.swing.JPanel;

class ZeroJPanel extends JPanel {

    /**
     * Creates new form ZeroJPanel
     */
    ZeroJPanel() {
        initComponents();

        System.out.println( this.getHeight() );
    }

    public static void main(String Args[]) {
        new ZeroJPanel();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>
    // Variables declaration - do not modify
    // End of variables declaration
}

A: The panel returns 0, 0 because, quite simply, that is the default value.
When you add the panel to a frame, and call pack() on the frame, that will calculate the correct (preferred) size and set it. Until then, you won't be able to find the size because it hasn't been calculated.
Why do you need these values? If you can explain the problem in broader terms, we may be able to help you.


text:
Q: Plotly control relative lengths of each axis maybe there is something in the documentation that I missed, but how do I control the relative length of each axis, so that the plot is a square?
I am basically looking for the equivalent of matlabs
pbaspect([1 1 1])

This is the current image
which I want to turn into this (ignore the additional axis labels):

I made the change by manually setting the image size, but there has to be an easier way to do it.
fig.update_yaxes(scaleanchor = "x",scaleratio = 1,)

Does not work since the axes are using different numbers.
I am happy about any suggestions.

A: it's as simple as setting the height and width as the same
import plotly.graph_objects as go
import numpy as np

go.Figure(go.Scatter(x=np.linspace(0,100,1000), y=np.random.uniform(0,5,1000), mode="markers"), layout={"height":400, "width":400})

approach 2 - use HTML view port heigh / width

*

*css width same as height technique can be used

*create a
 that is sized in same view port units.  embed plotly html within this sized

import plotly.express as px
import io

buffer = io.StringIO()

go.Figure(
    go.Scatter(
        x=np.linspace(0, 100, 1000),
        y=np.random.uniform(0, 5, 1000) * np.random.uniform(0, 1, 1000),
        mode="markers",
    )
).update_layout(margin={"t":0,"b":30,"l":0,"r":0}).write_html(buffer, full_html=False)

# use HTML techniques create a "square", NB height and width defined in same view port units
html = '
' + buffer.getvalue().encode().decode() + "
"
with open("example.html", "w") as f: f.write(html)

# not required if not running in jupyter
from IPython.core.display import display, HTML
HTML(html)


text:
Q: nominal-value inputs for Neural Network I have a set of training data, each item in this set consists of 4 numerical values and 1 nominal-value which is the name of the method that these values have been calculated with. (There are 8 methods)
I'm training a Neural Network with these. To get rid of the nominal-value I simply assigned a value from 1 to 8 to each method and used one input to pass it to Neural Network and 4 other inputs for numerical-values. It is sort of working, but the result is not as amazing as I want.
So my question is could it be because of this simple assignment of numbers to nominal-values? or maybe it is because of mixing two different categories of inputs which are not really at the same level (numbers and method types)

A: As a general note, a better way for coding nominal values would be a binary vector. In your case, in addition to the 4 continuous-valued inputs, you'd have 8 binary input neurons, where only one is activated (1) and the other 7 are inactive.
The way you did it implies an artificial relationship between the computation methods, which is almost certainly an artifact. For example, 1 and 2 are numerically (and from your network's point of view!) nearer than 1 and 8. But are the methods nr. 1 and 2 really more similar, or related, than the methods 1 and 8?

A: Since you don't provide much detail, my answer can't be very specific.
Generally speaking neural networks tend to perform worse when coding nominal values as numeric values since the transformation will impose a (probably) false ordering on the variables. Mixing inputs with very varied levels also tend to worsen the performance.
However, given the little information provided here there is no way of telling if this is the reason that the networks performance is "not as amazing" as you want. It could just as well be the case that you don't have enough training data, or that your training data contains a lot of noise. Perhaps you need to pre-scale your data, perhaps there is an error in your network code, perhaps you have chosen ill-suited values of constants for your learning algorithm...
The reasons a neural network doesn't perform as expected are many and diverse (on of them beeing unreasonably high expectations). Without much more information there is no way of knowing what the problem is in your case.

A: Mapping categories to numerical values is not a good practice in statistics. Especially in the case of neural networks. Bear in mind that neural networks tend to map similar inputs to similar outputs. If you map category A to 1 and category B to 2 (both as inputs), the NN will try to output similar values for both categories, even if they have nothing to do with each other.
A sparser representation is preferred. If you have 4 categories, map them like this:
A -> 0001
B -> 0010
etc
Take a look at the "Subject: How should categories be encoded?" in this link:
ftp://ftp.sas.com/pub/neural/FAQ2.html#A_cat

A: The previous answers are right - do not map nominal values into arbitrary numeric ones. However, if the attribute has an ordinal nature ("Low", "Medium", High" for example), you can replace the nominal values by ascending numeric values. Note that this may not be the optimal solution - since there is no guarantee for example that "High"=3 by the nature of your data. Instead, use one-hot bit encoding as suggested.
The reason for this is that a neural network is very similar to regression in the sense that multiple numeric values go through some kind of an aggregating function - but this happens multiple times. Each input is also multiplied by a weight.
So when you enter a numeric value, it undergoes a series of mathematical manipulations that adjusts its weights in the network. So if you use numeric values for non-nomial data - nominal values that were mapped to closer numeric values will be treated about the same in the best case, in the worst case - it can harm your model.


text:
Q: outsized vs. outsize Like many, I have often come across phrases such as "outsized influence" or "outsized contribution". However, once when trying to apply this myself, it was suggested (I think it was by a grammar checker) that that correct way to say this was actually "outsize influence" etc.
Checking the dictionary, this appears to be correct – though using "outsized" in this context is probably more common, including in literature.
Which is correct? Are both correct?

A: For a term that has—according to Merriam-Webster's Eleventh Collegiate Dictionary (2003)—been around since 1845 as a noun and since 1880 as an adjective, outsize/outsized didn't make much of a dent in Ngram frequency graphs until around 1920. Over the past century, however, the trajectories of outsize (blue line) and outsized (red line) have been quite interesting:

After holding a substantial edge in frequency of appearance in print from 1920 to about 1980, outsize saw it frequency plummet in the early 1980s, only to stabilize gradually after 1990 and increase modestly in the early 2000s. Meanwhile, outsized rose steadily until 1980, then endured a slight drop in frequency for a couple of years before recovering and rising faster that ever starting in about 1990. It passed outsize in frequency in 1994 and as of 2019 seems to be a bit more than twice as common as outsize in recent Google Books database publications.
According to the Eleventh Collegiate, outsize may function as either a noun or an adjective, whereas outsized functions only as an adjective. It seems reasonable to doubt that noun use of outsize has been very significant over the past sixty years, given the vanishingly small frequency of occurrence of outsizes since about 1960 in the following Ngram chart for outsize (blue line) versus outsized (red line) versus outsizes (green line) for the period 1900–2019:

But even if we suppose that all instances of outsize in print involve use of the word as an adjective, outsize as an adjective is now considerably less common in print than outsized as an adjective.
Even in 2003, Merriam-Webster listed outsize in the preferred position of first spelling in its entry for the adjective:

outsize also outsized adj (1880) 1 : unusually large or heavy 2 : exaggerated or extravagant in size or degree

MW has followed that preference since introducing an entry for outsize/outsized as an adjective in the Seventh Collegiate (1963). Real-world usage, however, may be ignoring the prescribed preference in the Eleventh Collegiate and in other dictionaries, such as the American Heritage Dictionary of the English Language, fifth edition (2010).
Only one usage commentator I consulted took up the question of outsize versus outsized—and his treatment is brief to the point of being peremptory.  From Bryan Garner, Garner's Modern American Usage, third edition (2009):

outsize, adj.; outsized. The first is standard. The second is a NEEDLESS VARIANT [defined elsewhere as "two or more forms of the same word without nuance or differentiation—and seemingly without even hope for either"].

When a variant form becomes twice as frequent in print as the standard form, it may be appropriate to revisit the question of which form is standard and which is a needless variant—or whether the concept of a "needless variant" is useful in appraising the situation.
An argument in support of a form on the basis of historical precedence may exert some emotional pull, but it can't stand up to popular usage in the long term. Thus, for example, a search for hath at Early English Books Online (which covers books published in English no later than the seventeenth century) yields 2,604,169 matches in 47,027 records, whereas a search for has yields 423,473 matches in 18,375 records. So you might have argued in 1700 that hath was standard and has was a needless variant, even though momentum was already on the side of has by 1700. At some point, however, the argument that hath is standard because of its older claim to being standard fails against the overwhelming fact that has eventually became much more popular.
Today, outsize still has a substantial number of adherents (I'm one of them). But on the evidence of the Ngram plots, I am not inclined to agree with Bryan Garner that outsize is standard and outsized is a needless variant.


text:
Q: Why when playing images in a pictureBox1 using a timer the playing is getting very slow? At the first time when I click the button it's showing the images in the pictureBox1 one by one fast. But then after some images it's getting very slow.
It's showing the images one by one very slow like in slow motion mode.
This is the button click event code:
private void button5_Click(object sender, EventArgs e)
{
    _files = new List<FileInfo>();
    myTrackPanelss1.trackBar1.Value = 0;
    _indx = 0;
    _files.AddRange(_fi);
    _files = _files.OrderBy(f => f.LastWriteTime).ToList();
    button5.ForeColor = Color.Red;
    button6.ForeColor = Color.Black;
    button7.ForeColor = Color.Black;
    timer3.Start();
    button6.Enabled = true;
    button6.Text = "Pause";
    button7.Enabled = true;
}

The variable _indx is global int.
Then the timer3 tick event:
private void timer3_Tick(object sender, EventArgs e)
{
    try
    {
        myTrackPanelss1.trackBar1.Maximum = _files.Count;
        myTrackPanelss1.trackBar1.Minimum = 0;
        Image iOLd = this.pictureBox1.Image;
        Image img = Image.FromFile(_files[_indx].FullName);
        myTrackPanelss1.trackBar1.Value = _indx;
        label22.Text = _files[_indx].Name;
        this.pictureBox1.Image = img;
        if (iOLd != null)
            iOLd.Dispose();

        _indx++;
        if (_indx >= _files.Count)
        {
            _indx = 0;
        }

        timer3.Interval = 40;
    }
    catch
    {

    }
}

Sometimes when I click the button once the timer start it's showing the images in the pictureBox1 very slow. Sometimes it's showing them fast like interval 40 and then in some point it's getting slow. I can't figure out why it's getting slow.

A: Declare what you can outside of the timer. Instantiating variables every tick will cause some throttle.. actually why even store those variables in memory? get rid of iOld and img if you can...
Declared and instantiated outside of function:
    myTrackPanelss1.trackBar1.Maximum = _files.Count;
    myTrackPanelss1.trackBar1.Minimum = 0;

Timer Tick:
try {
        this.pictureBox1.Image = Image.FromFile(_files[_indx].FullName);
        timer3.Interval = 40;
        _indx++;
}


text:
Q: Couchbase in Spring with default values when saving We're using Couchbase database and Springboot, and we are facing an issue: we'd like to set a default value for a param of our model when it is going to be saved in database (as long as it hasn't already been set).
Our model is something like:
@Document
class Book {

...

@Field("quantity")
int quantity;

...

int getQuantity() {return quantity;}

void setQuantity(int quantity){this.quantity = quantity;}

...

}

So, how could I set a default value without using a default constructor or setting the default value when defining the variable?
Thanks a lot


text:
Q: How do I get getSystemService from a second .java class file to work in Android Studio? I apologise. I'm aware there are many duplicate questions like this, but even after reading through them here I can't get mine to work or properly understand the answer. I'm unable to comment an another post to help explain the answers either because of needing repetition points.

So I'm quite experienced when it comes to JavaScript but I'm still a beginner with Java and learning. I've had some practise with Java on BlueJ a while back.
So lately I've started developing an app with Android Studio with the help of Building Your First App guide, which I had no problem following, learning and understanding.
Now that I'm developing my own app. I keep running into problems when I'm trying to tidy the code snippets I've found by storing them in a second .java file with the help of https://stackoverflow.com/a/3496655/6318164 answer.
I tried to shorten code best I can to show here.
Net.java
package com.nova.netmanager;

import android.content.Context;
import android.net.wifi.WifiManager;

class Net {
    public boolean isWifiEnabled() {
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        return wifi.isWifiEnabled();
    }
}

MainActivity.java
package com.nova.netmanager;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;

public class MainActivity extends AppCompatActivity {
    Switch wifiSwitch;
    WifiManager wifi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        wifiSwitch = (Switch) findViewById(R.id.switch_wifi);
        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        checkNetworkStatus();

        wifiSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                wifi.setWifiEnabled(isChecked);
            }
        });
    }

    @Override
    protected void onResume() {
         super.onResume();

         checkNetworkStatus();
    }

    public void checkNetworkStatus() {
        Net net = new Net();
        wifiSwitch.setChecked(net.isWifiEnabled());
    }
}

Net.java is my own class I'm trying to make that stores all communication and network stuff together such as checking status and toggling them. Now my app keeps crashing and debugger keeps complaining about this line in Net.java after narrowing it down.
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

I've tried adding the extends AppCompatActivity to class Net but brings up issues saying it should run after onCreate which it does from the script flow  logic I see. I've even tried getActivity() that doesn't exist for a class and I've tried using this Context from other answers.
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

I don't understand why it's so difficult asking the Android if WiFi is on or off in a second script. I thought I've read that Android Studio should be easy even if nobody has coded before.
Any help would be appreciated. Sorry about the long post and possible duplicate.

A: You need to pass the context as below
class Net {
    public boolean isWifiEnabled(Context context) {
        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        return wifi.isWifiEnabled();
    }
}

And to use it in your activity :-
public class MainActivity extends AppCompatActivity {
    Switch wifiSwitch;
    WifiManager wifi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        wifiSwitch = (Switch) findViewById(R.id.switch_wifi);
        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        checkNetworkStatus();

        wifiSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                wifi.setWifiEnabled(isChecked);
            }
        });
    }

    @Override
    protected void onResume() {
         super.onResume();

         checkNetworkStatus();
    }

    public void checkNetworkStatus() {
        Net net = new Net();
        wifiSwitch.setChecked(net.isWifiEnabled(MainActivity.this));
    }
}

Edit : You also need to add following permission in AndroidManifest file
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />