Title: column operation in csv [python]

Body:
I have a scenario where I am extracting a row value from a csv file.

(CSV) test1:

    Host, Time Up, Time Down, Time Unreachable, Time Undetermined
server1.test.com:1717,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000
server2.test.com:1717,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000
Average,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000

(CSV) test2:

Host,Service, Time OK, Time Warning, Time Unknown, Time Critical, Time Undetermined
server1.test.com:1717,application_availability_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,server_hit_rate,99.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,max_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_log_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_sessions_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
server2.test.com:1717,application_availability_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,server_hit_rate,99.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,max_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_log_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_sessions_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
Average,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000

This is my code:

df = pd.read_csv('test1.csv',skipfooter=1)
df2 = pd.read_csv('test2.csv',skipfooter=1)
combined = pd.merge(df[['Host',' Time Up']],df2[['Host',' Time OK']], on='Host')
combined[' Time OK'] = combined[' Time OK'].apply(lambda x: x.split('(')[0])
combined[' Time Up'] = combined[' Time Up'].apply(lambda x: x.split('(')[0])

Here I am trying to get the value of "server_hit_rate" which is 99% & belongs to 3rd row data.
But with this above code I am able to get the data which is in first row only. i.e.

                    Host    Time Up    Time OK
0  server1.test.com:1717  100.000%   100.000%
1  server2.test.com:1717  100.000%   100.000%

The required output should be:

                    Host    Time Up    Time OK
0  server1.test.com:1717  100.000%    99.000%
1  server2.test.com:1717  100.000%    99.000%

Any advice to achieve the following will be helpful.

Edit1:

import pandas as pd
import pandas
import os, shutil, glob
import sys
import datetime
import time
def t1():
    import pandas as pd
    import pandas
    today=datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S %Z %Y")
    print "date :", today
    df = pd.read_csv('t1.csv',skipfooter=1, engine='python')
    df2 = pd.read_csv('t2.csv',skipfooter=1, engine='python')
    temp = df2.ffill()[df2['Service']=='server_hit_rate']
    combined = pd.merge(df[['Host',' Time Up']],temp[['Host',' Time OK']], on='Host')
    combined[' Time OK'] = combined[' Time OK'].apply(lambda x: x.split('(')[0])
    combined[' Time Up'] = combined[' Time Up'].apply(lambda x: x.split('(')[0])
    combined.to_csv('test.csv',index=False)
t1()

O/P:

Wed Nov 15 10:07:01  2017
Empty DataFrame
Columns: [Host, % Time Up, % Time OK]
Index: []

Body:
To answer your challenge was a nice coffee break in my day. See my code below. It works for both CSV1 and CSV2 files because I've made server-name and search-key variable for your search. For the learning-curve "# + comment" implemented where needed. No additional imports or whatsoever need. Just plain pythonic writing.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# lists: csv1 and csv2 mimick reading from file.

csv1 =  ["Host, Time Up, Time Down, Time Unreachable, Time Undetermined",
         "server1.test.com:1717,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000",
         "server2.test.com:1717,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000",
         "Average,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000"]

csv2 =  ["Host,Service, Time OK, Time Warning, Time Unknown, Time Critical, Time Undetermined",
         "server1.test.com:1717,application_availability_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000",
         ",server_hit_rate,99.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000",
         ",max_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000",
         ",application_log_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000",
         ",application_sessions_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000",
         "server2.test.com:1717,application_availability_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000",
         ",server_hit_rate,99.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000",
         ",max_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000",
         ",application_log_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000",
         ",application_sessions_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000",
         "Average,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000"]

# assuming your provided data comes from a static file on hdd and can be read by using readline().

total_servers        = 2
count_server         = 0
current_server_name  = ''
result_dict          = {}

# added implementable server-number; just in case you got multiple servers as your example shows.
server_name = "server%s.test.com:"
search_key = ",server_hit_rate"

# the while-loop ploughs/iters through the file for a reason: > someone may have changed the order of servernames randomly.

while count_server < total_servers:
    for line in csv2:
    #    print line  # -> to check output on screen

        current_server_name = server_name % str(count_server + 1) # Some folks..start counting at "1"...

        if line.startswith((current_server_name)):
            print current_server_name

        if not line.startswith((search_key)):
            continue
        else:
#            print current_server_name
            print 'got your line of interest : "%s"' % line  # -> to check output on screen
            items = line.split(',')
            value = items[2]
            result_dict[current_server_name] = value

            count_server +=1

print result_dict

Enjoy!


来源: stackexchange

问:
How can I set a height of an element relative to her parent and her sibling?

#parent {
  height: 150px;
  width: 200px;
  border-style: solid;
  border-color: red;
  /*overflow: hidden; this only hides */
}

#sibling1 {
  position: relative;
  width: 100%;
}

#sibling2{

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
  <h3 id="sibling1">Variable Length Title</h3>
  <div id="sibling2"> Variable lenght text... Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</div>
</div></code>```

How can I get something like this?

Is there a way in css to model the sibling2 height based on the size of the parent and the height occupied by sibling1?

i.e sibling2.height = parent.height - sibling1.height

答:
I think you may want to check out the position property.
If you have text in a div container you could position that
 element relative to the div container that it is inside using position: relative.

W3Schools: Position

ContentLicense: CC BY-SA 3.0

Body:
#parent {
  height: 150px;
  width: 200px;
  border-style: solid;
  border-color: red;
  /*overflow: hidden; this only hides */
}

#sibling1 {
  position: relative;
  width: 100%;
}

#sibling2{

}

Variable Length Title

 Variable lenght text... Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.

How can I get something like this?

Is there a way in css to model the sibling2 height based on the size of the parent and the height occupied by sibling1?

i.e sibling2.height = parent.height - sibling1.height


问:
What is wrong with my loop code?
I wrote a loop code to extract my table files names into a string or an array and meanwhile collect the data into arrays. But I found my code went wrong as only one file was read and repeated in the loop over and over again. I had no idea where my code is wrong and it already took me several hours to look for the problem. Could somebody help me?

```<code>DataCircle      = dir('*-circle.xls');
MeanAreaCircle  = [];
ColonyNumCircle = [];
PlateNameCircle = [];

for zz = 1:numel(DataCircle)
   basefilenamedata1 = DataCircle(w).name;             % generate the base name
   DataName1         = regexprep(basefilenamedata1,'-circle.xls',''); %replace part of the name and the extension
   PlateNameCircle   = [PlateNameCircle DataName1];    % collect the file name into a string
   T1                = readtable(basefilenamedata1);   % read data in
   MeanAreaCircle    = [MeanAreaCircle mean(T1.area)]; % collect the mean for area
end
</code>```

What I got is like this, which is wrong:

```<code>>> PlateNameCircle
PlateNameCircle ='IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813'
>>  MeanAreaCircle
MeanAreaCircle =
   1.0e+03 *
    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152
</code>```

My input file list:

```<code>IMG_0809-CC.xls
IMG_0809-circle.xls
IMG_0810-CC.xls
IMG_0810-circle.xls
IMG_0812-CC.xls
IMG_0812-circle.xls
IMG_0813-CC.xls
IMG_0813-circle.xls
</code>```

What I want is a column or a character array or a string like this:

```<code>PlateNameCircle = 'IMG_0809' 'IMG_0810' 'IMG_0811' 'IMG_0812' 'IMG_0813'
</code>```

答:
I think the w in

```<code>basefilenamedata1 = DataCircle(w).name;
</code>```

should be zz instead. Otherwise you are always looking at the first file in the list.

Title: What is wrong with my loop code?

Body:
I wrote a loop code to extract my table files names into a string or an array and meanwhile collect the data into arrays. But I found my code went wrong as only one file was read and repeated in the loop over and over again. I had no idea where my code is wrong and it already took me several hours to look for the problem. Could somebody help me?

DataCircle      = dir('*-circle.xls');
MeanAreaCircle  = [];
ColonyNumCircle = [];
PlateNameCircle = [];

for zz = 1:numel(DataCircle)
   basefilenamedata1 = DataCircle(w).name;             % generate the base name
   DataName1         = regexprep(basefilenamedata1,'-circle.xls',''); %replace part of the name and the extension
   PlateNameCircle   = [PlateNameCircle DataName1];    % collect the file name into a string
   T1                = readtable(basefilenamedata1);   % read data in
   MeanAreaCircle    = [MeanAreaCircle mean(T1.area)]; % collect the mean for area
end

What I got is like this, which is wrong:

>> PlateNameCircle
PlateNameCircle ='IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813'
>>  MeanAreaCircle
MeanAreaCircle =
   1.0e+03 *
    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152

My input file list:

IMG_0809-CC.xls
IMG_0809-circle.xls
IMG_0810-CC.xls
IMG_0810-circle.xls
IMG_0812-CC.xls
IMG_0812-circle.xls
IMG_0813-CC.xls
IMG_0813-circle.xls

What I want is a column or a character array or a string like this:

PlateNameCircle = 'IMG_0809' 'IMG_0810' 'IMG_0811' 'IMG_0812' 'IMG_0813'

Body:
I think the w in

basefilenamedata1 = DataCircle(w).name;

should be zz instead. Otherwise you are always looking at the first file in the list.


问:
object oriented JavaScript
Is there any error in my code esp var newpoint[0] =  new Point; . I wnat to know on how to do oop in javascript

```<code>function Point()
{
    var x;
    var y;
}

var length = 1;
var arrayindex;
var newpoint[0] =  new Point;
newpoint[0].x = 10;
newpoint[0].y = 10;
for(i=0 ; i<10; i ++)
{
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}
</code>```

EDIT : Thanks all . I have come up with two code need to know which one is better any any sugesstion and protips . both work

```<code>function Point()
{
    this.x;
    this. y;
}

var length = 0;
var newpoint = [];

for(i=0 ; i<10; i ++)
{
    newpoint[length] =new Point();
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}
</code>```

and

```<code>var length = 0;
var newpoint = [];
for(i=0 ; i<10; i ++)
{
    newpoint[length] = {};
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}
for(var arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}
</code>```

答:
Are you trying to use the x and y as properties?
you do not need to declare them in function. You can directly use them on a javascript object.

```<code>var newpoint = []; // Declares newpoint as array
var length = 1;
for(var i=0 ; i<10; i ++)
{
    newpoint[length] = {}; //Declares a new object.
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}
</code>```

The .x and .y are automatically associated as properties for the object

ContentLicense: CC BY-SA 2.5

Title: object oriented JavaScript

Body:
Is there any error in my code esp var newpoint[0] =  new Point; . I wnat to know on how to do oop in javascript

function Point()
{
    var x;
    var y;
}

var length = 1;
var arrayindex;
var newpoint[0] =  new Point;
newpoint[0].x = 10;
newpoint[0].y = 10;
for(i=0 ; i<10; i ++)
{
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}

EDIT : Thanks all . I have come up with two code need to know which one is better any any sugesstion and protips . both work

function Point()
{
    this.x;
    this. y;
}

var length = 0;
var newpoint = [];

for(i=0 ; i<10; i ++)
{
    newpoint[length] =new Point();
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}

and

var length = 0;
var newpoint = [];
for(i=0 ; i<10; i ++)
{
    newpoint[length] = {};
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}
for(var arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}

Body:
Are you trying to use the x and y as properties?
you do not need to declare them in function. You can directly use them on a javascript object.

var newpoint = []; // Declares newpoint as array
var length = 1;
for(var i=0 ; i<10; i ++)
{
    newpoint[length] = {}; //Declares a new object.
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

The .x and .y are automatically associated as properties for the object


问:
How to retrieve columns data which are distinct
I need to retrieve columns of data which are having distinct values

For Ex:

```<code>Location FoodType Gender Alive
India    Veg      M      Y
India    NonVeg   M      N
</code>```

I need a query to list rows of data which are having distinct values
Expected Output Is:

```<code>FoodType Alive
Veg      Y
NonVeg   N
</code>```

Distinct and Unique may not work as i dont know what column will have distinct values.

答:
If you need a list then you could use unpivot, count distinct values, and optionally aggregate them together with listagg():

```<code>with t(Location, FoodType, Gender, Alive) as (
    select 'India', 'Veg',    'M', 'Y' from dual union all
    select 'India', 'NonVeg', 'M', 'N' from dual )

-- end of test data, the exact query starts here:

select col, listagg(val, ', ') within group (order by val) list
  from (
    select col, val, count(distinct val) over (partition by col) cnt
      from t
      unpivot (val for col in (Location, FoodType, Gender, Alive)))
  where cnt > 1
  group by col
</code>```

We have this:

```<code>COL       LIST
--------  -------------
ALIVE     N, Y
FOODTYPE  NonVeg, Veg
</code>```

If you insist on output in separate columns You need dynamic SQL to produce list of non distinct columns to pivot data again.

If there are null values in table and non nulls and you want to show such pairs use unpivot with include nulls and then nvl().

Body:
I need to retrieve columns of data which are having distinct values

For Ex:

Location FoodType Gender Alive
India    Veg      M      Y
India    NonVeg   M      N

I need a query to list rows of data which are having distinct values
Expected Output Is:

FoodType Alive
Veg      Y
NonVeg   N

Distinct and Unique may not work as i dont know what column will have distinct values.

Body:
If you need a list then you could use unpivot, count distinct values, and optionally aggregate them together with listagg():

with t(Location, FoodType, Gender, Alive) as (
    select 'India', 'Veg',    'M', 'Y' from dual union all
    select 'India', 'NonVeg', 'M', 'N' from dual )

-- end of test data, the exact query starts here:

select col, listagg(val, ', ') within group (order by val) list
  from (
    select col, val, count(distinct val) over (partition by col) cnt
      from t
      unpivot (val for col in (Location, FoodType, Gender, Alive)))
  where cnt > 1
  group by col

We have this:

COL       LIST
--------  -------------
ALIVE     N, Y
FOODTYPE  NonVeg, Veg

If you insist on output in separate columns You need dynamic SQL to produce list of non distinct columns to pivot data again.

If there are null values in table and non nulls and you want to show such pairs use unpivot with include nulls and then nvl().


问:
Boost::thread how to synchronise between main and worker thread?
I am trying to achieve a multi-threaded design and need some help on thread synchronisation.

I have two classes, class A and class B. I'll explain using pseudo-code
class A is created in main function.

```<code>class A
{
   public:
   A();
   ~A();

   void tick();
   void addEntity();
   private:
   std::list<entity> entityList;
   B* _b;
};
</code>```

Class B is as follows:

```<code> class B
{
   public:
   B();
   ~B();

   void createSimulation();
   void startSimulation();
   void registerCallbacks(SimEngine& sim);
   void entityCreatedCallback();

   boost::signal<void()> signalEntityCreated;

   private:
   simEngine* sim;

};
</code>```

Class A implementation is somewhat like that:

```<code>A::A()
{
    _b = new B();
    _b->signalEntityCreated.connect(boost::bind(&A::AddEntity, this));
    _b->createSimulation();
}

A::~A()
{

}

void A::tick()
{
    entity ent = entityList.pop_front();
    //process the entity
}

void A::addEntity(entity ent)
{
     entityList.push_back(entity);
}
</code>```

Class B implementation is somewhat like that:

```<code>B::B()
{
}

B::~B()
{
}

 B::registerCallback(SimEngine& sim)
 {
     sim.connect("ENTITY_CREATED", entityCreatedCallback);
 }

 void B::createSimulation()
 {
     boost::thread sim_thread(boost::bind(&B::startSimulation, this));
 }

 void B::startSimulation()
 {
      sim =  new SimEngine();
      registerCallback(sim);

      sim->start();

 }

 void B::entityCreatedCallback(simEngine& sim)
{
    signalEntityCreated(sim.lastEntity);
}
</code>```

So, main idea is class A creates class B, in turn class B start a simulation thread. before starting the simulation, it register some callback function with the simulation. these callbacks functions are called when some states changes in the simulation (i.e. entity created).

Class a uses boost signal slot mechanism to connect a signal (signalEntityCreated) in class B with a local member function in class A.
in Class B, callback call the signal to trigger the member function call in class A. In this case addEntity, which is adding new entry to the std::list.

Class A has a tick function that ticks in every frame, and need to process any entity that is added by the addEntity function.

Now, I need to properly synchronise this producing and consuming entity mechanism. class A is running in main thread and it is bind to render thread, so it cannot wait on mutex (for long) otherwise rendering performance can reduce.

My observation,
When simulation is running in different threads, all callbacks are belong to that thread. when member function in called using boost::signal that member function is also running in simulation thread. However, the processing (inside tick) needs to run in main thread.

any suggestion?

答:
You would just want to create a message queue that is polled from within the rendering event loop.

In addition, you could model the simulation and or renderer (A) follow the Active Object Pattern¹.

Note that when passing the event message across thread boundaries, you will want to pass the entity too, because otherwise there would be a race condition (when multiple entities have been created before the event is being handled).

¹ see e.g.
 - https://en.wikipedia.org/wiki/Active_object
 - http://www.drdobbs.com/parallel/prefer-using-active-objects-instead-of-n/225700095
 -
 - https://rosettacode.org/wiki/Active_object#C.2B.2B is actually a nice example

Body:
I am trying to achieve a multi-threaded design and need some help on thread synchronisation.

I have two classes, class A and class B. I'll explain using pseudo-code
class A is created in main function.

class A
{
   public:
   A();
   ~A();

   void tick();
   void addEntity();
   private:
   std::list<entity> entityList;
   B* _b;
};

Class B is as follows:

 class B
{
   public:
   B();
   ~B();

   void createSimulation();
   void startSimulation();
   void registerCallbacks(SimEngine& sim);
   void entityCreatedCallback();

   boost::signal<void()> signalEntityCreated;

   private:
   simEngine* sim;

};

Class A implementation is somewhat like that:

A::A()
{
    _b = new B();
    _b->signalEntityCreated.connect(boost::bind(&A::AddEntity, this));
    _b->createSimulation();
}

A::~A()
{

}

void A::tick()
{
    entity ent = entityList.pop_front();
    //process the entity
}

void A::addEntity(entity ent)
{
     entityList.push_back(entity);
}

Class B implementation is somewhat like that:

B::B()
{
}

B::~B()
{
}

 B::registerCallback(SimEngine& sim)
 {
     sim.connect("ENTITY_CREATED", entityCreatedCallback);
 }

 void B::createSimulation()
 {
     boost::thread sim_thread(boost::bind(&B::startSimulation, this));
 }

 void B::startSimulation()
 {
      sim =  new SimEngine();
      registerCallback(sim);

      sim->start();

 }

 void B::entityCreatedCallback(simEngine& sim)
{
    signalEntityCreated(sim.lastEntity);
}

So, main idea is class A creates class B, in turn class B start a simulation thread. before starting the simulation, it register some callback function with the simulation. these callbacks functions are called when some states changes in the simulation (i.e. entity created).

Class a uses boost signal slot mechanism to connect a signal (signalEntityCreated) in class B with a local member function in class A.
in Class B, callback call the signal to trigger the member function call in class A. In this case addEntity, which is adding new entry to the std::list.

Class A has a tick function that ticks in every frame, and need to process any entity that is added by the addEntity function.

Now, I need to properly synchronise this producing and consuming entity mechanism. class A is running in main thread and it is bind to render thread, so it cannot wait on mutex (for long) otherwise rendering performance can reduce.

My observation,
When simulation is running in different threads, all callbacks are belong to that thread. when member function in called using boost::signal that member function is also running in simulation thread. However, the processing (inside tick) needs to run in main thread.

any suggestion?


问:
Why TypeScript doesn't generate code for interfaces?
I'm using TS Playground to learn TypeScript. What I found strange is that TypeScript doesn't generate a specific code for interfaces.

Example:

```<code>interface Person {
    id: number,
    fullName: string,
    sayHello: Function
}

let p: Person;
p.id = 123;
p.fullName = 'John Doe';
p.sayHello = function () {return "Hello from " + p.fullName;}
</code>```

Will be translated to:

```<code>var p;
p.id = 123;
p.fullName = 'John Doe';
p.sayHello = function () { return "Hello from " + p.fullName; };
</code>```

Is there an explanation why TypeScript doesn't generate any code for the interface ?

答:
Remember that TypeScript type system only exist in the scope of TypeScript itself.

In the end, it will be all pure JavaScript. The compiler is smart, it will only generate code when it's needed. That means that interfaces that contain only informations useful for TypeScript's type cheking and no real JavaScript code, will not result in any JavaScript code after compilation : There's simply no reason to generate unused code.

That's what happens with your code here : All the interface does is telling TypeScript which type should the variable be, without any actual JavaScript  call. Once the compiler did its job to check the types, the interface has no reason to exist in JavaScript.

Body:
I'm using TS Playground to learn TypeScript. What I found strange is that TypeScript doesn't generate a specific code for interfaces.

Example:

interface Person {
    id: number,
    fullName: string,
    sayHello: Function
}

let p: Person;
p.id = 123;
p.fullName = 'John Doe';
p.sayHello = function () {return "Hello from " + p.fullName;}

Will be translated to:

var p;
p.id = 123;
p.fullName = 'John Doe';
p.sayHello = function () { return "Hello from " + p.fullName; };

Is there an explanation why TypeScript doesn't generate any code for the interface ?


问:
How to display exact timing with Chrome Dev Tools?
In this link, it shows how to use network timing pane/window. But, I realized that the timings are shown in relative: there is no "exact timing" here. For example I wanted to see the exact time of the starting of an ajax and it's end of course. This should be the string that I need to see in this pane as an "exact start time" of an ajax request

11.17.2017 10:00:00(GMT+1)

How can I achieve this in Chrome Developer Tools? Are there any place written the exact date of the network events?

答: Not necessarily what you asked for, but since you asked for any exact dates of network events, it's possible to capture the Response Date (time the response message was originated). If you right click on one of your columns, then choose Response Headers->Manage Header Columns->Add custom header->(type in Date). Unfortunately, it is not the actual start date of the request. I don't know if there's a way to capture that in devtools aside from modifying code to console.log your start date.


问:
Installation C# application without dot net framework
I have created a new application on C# 2010. After creating a Setup file I came to know that for installation purposes user must have a dot net framework. Is there any way I can get rid of installing dot net framework on a user computer. Each time I try to install my application on the user computer it redirects to install the dot net framework. Any suggestion?</p>

答: While creating installation bundle you can add dot net frame work exe file as prerequisites, then while installing your application it can check whether the system having .net framework or not.  if it is not installed it your application can install the frame work.</p>

ContentLicense: CC BY-SA 4.0


问:
TypeError: window.initMap is not a function
I am following this tutorial, basically copy all the code

https://developers.google.com/maps/documentation/javascript/tutorial

but got an error saying that the initMap function is not a function.
I am using angularjs in my project, could that be causing problems?

I copied the same code into plunker and it works just fine...
What are the possible issues?

Body:
In addition to @DB.Null's answer, I used Function.prototype as no-op (no-operation) function on #3 instead of angular.noop (I don't have angular in my project).

So this...

<script async defer src="https://maps.googleapis.com/maps/api/js?key=API_KEY_HERE&callback=Function.prototype" type="text/javascript"></script>


问:
How to fetch data from 2nd sheet in Google SpreadSheets
Hi I am referring this blog for fetching data from google spreadsheets ,i am able to get data from first sheet using the code mentioned in the article ,but how to fetch data from 2nd Sheet in Same SpreadSheet.

I have not included any code because i am using the same code which is there in the blog.

答:
Just Pass the Range as Follows in the Main Method

Original Code

```<code>var range = "A:B";
</code>```

change it to

```<code> var range = "SecondSheetName!A:B";
</code>```

Body:
Just Pass the Range as Follows in the Main Method

Original Code

var range = "A:B";

change it to

 var range = "SecondSheetName!A:B";


问:
Method Not Allowed HTTP Exception in Laravel 5.4
I have a form with two text fields and two buttons (edit and delete), when I press edit button, it works fine but when I press delete button, it gives the 'MethodNotAllowedHttp' exception. My code is as follows:

```<code><form action="/laboratory/doctors/update" method="POST">
    {{ csrf_field() }}
    {{ method_field('DELETE') }}
    <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" class="form-control" id="name" aria-describedby="name" value="{{ $doctor->name }}">
    </div>
    <div class="form-group">
        <label for="percentage">Percentage:</label>
        <input type="text" class="form-control" id="percentage" value="{{ $doctor->percentage }}">
    </div>
     <button type="submit" class="btn btn-success">Save Changes</button>
    <a href="/laboratory/doctors/{{ $doctor->id }}/delete" class="btn btn-danger">Delete</a>
</form>
</code>```

My Routes are as follows:

```<code>Route::post('/doctors/update', 'DoctorsController@update');
Route::delete('/doctors/{doctor}/delete', 'DoctorsController@destroy');
</code>```

Any help is appreciated.

答:
Href on an anchor html element will result in a GET call but your route expect a Delete call. You have some ways to make sure you will result in a delete call.

One of the most common ways is to use a form instead to post data to your server.

DELETE

```<code>{{ Form::open(['url' => '/laboratory/doctors/{{ $doctor->id }}/delete', 'method' => 'DELETE']) }}
{{ Form::button('delete', ['type' => 'submit',
                           'class' => 'btn btn-danger']) }}
{{ Form::close() }}
</code>```

For best practise I recommend to use {{ Form::open(...) }} {{ Form::close() }} only once and refactor your controller code so it can read the value from the buttons and translate that in the corresponding {doctor} of the delete post so you dont have multiple html forms in your code.

Body:
I have a form with two text fields and two buttons (edit and delete), when I press edit button, it works fine but when I press delete button, it gives the 'MethodNotAllowedHttp' exception. My code is as follows:

<form action="/laboratory/doctors/update" method="POST">
    {{ csrf_field() }}
    {{ method_field('DELETE') }}

        Name:
        <input type="text" class="form-control" id="name" aria-describedby="name" value="{{ $doctor->name }}">

        Percentage:
        <input type="text" class="form-control" id="percentage" value="{{ $doctor->percentage }}">

     <button type="submit" class="btn btn-success">Save Changes</button>
    id }}/delete" class="btn btn-danger">Delete
</form>

My Routes are as follows:

Route::post('/doctors/update', 'DoctorsController@update');
Route::delete('/doctors/{doctor}/delete', 'DoctorsController@destroy');

Any help is appreciated.

Body:
Href on an anchor html element will result in a GET call but your route expect a Delete call. You have some ways to make sure you will result in a delete call.

One of the most common ways is to use a form instead to post data to your server.

DELETE

{{ Form::open(['url' => '/laboratory/doctors/{{ $doctor->id }}/delete', 'method' => 'DELETE']) }}
{{ Form::button('delete', ['type' => 'submit',
                           'class' => 'btn btn-danger']) }}
{{ Form::close() }}

For best practise I recommend to use {{ Form::open(...) }} {{ Form::close() }} only once and refactor your controller code so it can read the value from the buttons and translate that in the corresponding {doctor} of the delete post so you dont have multiple html forms in your code.


问:
Clean debug output function?
I want to write an function that will print out error messages/warnings in my program together with the file & line number. There are these two macros in C:

```<code>__FILE__
__LINE__
</code>```

but there's a problem in my opinion... When I'm writing a function like this:

```<code>#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
#ifdef DEBUG
  printf("Error at %s: %s\n", location, msg);
#endif
}
int main(int , char**)
{
  error(AT, "fake error");
  return 0;
}
</code>```

There are still a lot of useless function calls & trash (the values of __FILE__ and __LINE__ at every call) in the binary file, even if I undefine DEBUG for the release build.
So how can I accomplish this more elegant? I want something like this:

```<code>#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
  printf("Error at %s: %s\n", location, msg);
}
int main(int , char**)
{
#ifdef DEBUG
  error(AT, "fake error");
#endif
  return 0;
}
</code>```

But not writing #ifdef DEBUG and #endif before and after every function call - that would be too huge for such an task. And remove every  error(AT, "fake error"); call manually isn't really elegant as well...

Any ideas? Maybe inline the function (would not help, wouldn't it)? Some macro or an change of this construct?

答:
```<code>#ifdef DEBUG
#define ERROR(msg) error(AT, msg)
#else
#define ERROR(msg)
#endif

int main( int argc, char * argv[] )
{
   ERROR( "fake error");
   return 0;
}
</code>```

Title: Clean debug output function?

Body:
I want to write an function that will print out error messages/warnings in my program together with the file & line number. There are these two macros in C:

__FILE__
__LINE__

but there's a problem in my opinion... When I'm writing a function like this:

#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
#ifdef DEBUG
  printf("Error at %s: %s\n", location, msg);
#endif
}
int main(int , char**)
{
  error(AT, "fake error");
  return 0;
}

There are still a lot of useless function calls & trash (the values of __FILE__ and __LINE__ at every call) in the binary file, even if I undefine DEBUG for the release build.
So how can I accomplish this more elegant? I want something like this:

#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
  printf("Error at %s: %s\n", location, msg);
}
int main(int , char**)
{
#ifdef DEBUG
  error(AT, "fake error");
#endif
  return 0;
}

But not writing #ifdef DEBUG and #endif before and after every function call - that would be too huge for such an task. And remove every  error(AT, "fake error"); call manually isn't really elegant as well...

Any ideas? Maybe inline the function (would not help, wouldn't it)? Some macro or an change of this construct?


问:
How to correctly check the browser engine and apply the needed code?
Something like this:

If (Gecko) do caseOne
else do caseTwo

答:
You can use user agent as follows

{
  var browser = "";
  if (navigator.userAgent.indexOf("Gecko") != -1) browser = "Gecko";

  if (browser == "Gecko") {

  console.log('browser: ' + browser);

  } else {

  console.log('browser: ' + browser);

  }

}```


问:
System.Drawing Out of Memory Exception On Main() Method - C#
My program is a CRM, I used Rad Ribbon Bar, so Many Buttons with images, RadGridView (which some columns contain images) and so many other controls which contain images. It's a mdi parent/child program.

In so many cases while loading a mdi child or working with some grid views the program will hang and give me this error:

```<code>OutOfMemoryException occurred in System.Drawing.dll
</code>```

I tried GC.Collect() on certain parts but no success. For setting images there is no code! for example for setting an image for a button I used its properties in visual studio. I have set All other control images in this way using the properties panel in visual mode.

and These are some designer codes related to drawing:

```<code>    btnCustomerList.Image = global::MyApp.Properties.Resources.CustomerList32;

    gridViewCommandColumn1.Image = global::MyApp.Properties.Resources.ViewShop32;
</code>```

and When The error comes after a while working with the app, it will appear in Program.cs and in the line Application.Run(new MainForm());:

```<code>    static void Main()
    {
        AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", AppDomain.CurrentDomain.BaseDirectory + "\\Settings.config");
        bool ok;
        Mutex m = new Mutex(true, WindowsIdentity.GetCurrent().Name.ToString().Split('\\')[1] + "MyApp", out  ok);
        if (ok)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // The Error will cause HERE
            Application.Run(new MainForm());

            GC.KeepAlive(m);
        }
        else
            Application.Exit();
    }
</code>```

MainForm is the mdi parent which contains Ribbon Bar.
and this is the Full stack trace:

```<code>at System.Drawing.Image.FromHbitmap(IntPtr hbitmap, IntPtr hpalette)
at System.Drawing.Image.FromHbitmap(IntPtr hbitmap)
at System.Drawing.Icon.ToBitmap()
at System.Windows.Forms.ThreadExceptionDialog..ctor(Exception t)
at System.Windows.Forms.Application.ThreadContext.OnThreadException(Exception t)
at System.Windows.Forms.Control.WndProcException(Exception e)
at System.Windows.Forms.Control.ControlNativeWindow.OnThreadException(Exception e)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at MyApp.Program.Main() in d:\\MyApp\\Application\\MyApp\\Program.cs:line 36"
</code>```

UPADTED:

the code for calling mdi-children by clicking on ribbon bar buttons is here:

```<code>private void btnCustomerList_Click(object sender, EventArgs e)
{
    OpenForm(new FormCustomerList(), "Customer List");
}

private void btnCustomerRelated_Click(object sender, EventArgs e)
{
    OpenForm(new FormCustomerRelated(), "Customer Related");
}
</code>```

and Here is OpenForm method:

```<code>private void OpenForm(Form formType, string Caption)
{
    foreach (Form nform in Application.OpenForms)
    {
        if (nform.GetType() == formType.GetType())
        {
            nform.Activate();
            return;
        }
    }
    this.MdiChildren.OfType<Form>().ToList().ForEach(x => x.Dispose());
    GC.Collect();

    Form form = formType;
    form.MdiParent = this;
    form.Dock = DockStyle.Fill;
    form.Show();
    this.Text = Caption;
}
</code>```

and in every mdi child's form constructor, after InitializeComponent(); I wrote GC.Collect(); also. But as told in comments, the GDI objects in task manager will increase and increase till 10000 objects and then application will crash.

UPADTED: THE MOST ISSUE

It seems I have found the part which cause the most GDI objects. In every form there are some controls like textboxes, drop down list etc. I have set some rules for them, for example if user enter a textbox, its back color should be yellow and after leave it should be white again. So there is a main method which I call in form load to literate through all controls and find the target ones and add for example enter and leave events with the defined rules. something Like This:

```<code>private void FormCustomerList_Load(object sender, EventArgs e)
{
    ClassCRMControls.AddEventHandler(this);
}
</code>```

and inside ClassCRMControls class:

```<code>public static void AddEventHandler(Control parent)
{
    foreach (Control c in parent.Controls)
    {
        if (c.GetType() == typeof(RadTextBox))
        {
            c.Enter += new EventHandler(ClassCRMControls.EnterEvent);
            c.Leave += new EventHandler(ClassCRMControls.LeaveEvent);
        }
        else
            AddEventHandler(c);
    }
}

private static void EnterEvent(object sender, EventArgs e)
{
    (sender as RadTextBox).TextBoxElement.TextBoxItem.BackColor = Color.FromArgb(255, 251, 147);
}

private static void LeaveEvent(object sender, EventArgs e)
{
      (sender as RadTextBox).TextBoxElement.TextBoxItem.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local);
}
</code>```

答:
There can be multiple reasons for OutOfMemoryExceptions. I have discussed 6 of them in another question.

In this case, after the comments and the edit, it became clear that GDI issues occur as well. You can detect these issues by showing an additional column in task manager:

GDIView is a far better application for GDI Leak analysis, because it also tells you the type of the GDI handle that got lost. It also has absolute and relative counters, so you can see how many of them get lost during a particular action.

The number of GDI handles can be configured in Registry. Do not use that as a permanent solution. Instead, with the additional info from GDIView, find the piece of code that leaks the GDI object.

When you run into the limit of GDI handles, the application typically starts looking bad: things are not painted any more and you get black rectangles in some places. However, this behavior is not necessary. In OP's case, black rectangles were not part of the description.

Body:
My program is a CRM, I used Rad Ribbon Bar, so Many Buttons with images, RadGridView (which some columns contain images) and so many other controls which contain images. It's a mdi parent/child program.

In so many cases while loading a mdi child or working with some grid views the program will hang and give me this error:

OutOfMemoryException occurred in System.Drawing.dll

I tried GC.Collect() on certain parts but no success. For setting images there is no code! for example for setting an image for a button I used its properties in visual studio. I have set All other control images in this way using the properties panel in visual mode.

and These are some designer codes related to drawing:

    btnCustomerList.Image = global::MyApp.Properties.Resources.CustomerList32;

    gridViewCommandColumn1.Image = global::MyApp.Properties.Resources.ViewShop32;

and When The error comes after a while working with the app, it will appear in Program.cs and in the line Application.Run(new MainForm());:

    static void Main()
    {
        AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", AppDomain.CurrentDomain.BaseDirectory + "\\Settings.config");
        bool ok;
        Mutex m = new Mutex(true, WindowsIdentity.GetCurrent().Name.ToString().Split('\\')[1] + "MyApp", out  ok);
        if (ok)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // The Error will cause HERE
            Application.Run(new MainForm());

            GC.KeepAlive(m);
        }
        else
            Application.Exit();
    }

MainForm is the mdi parent which contains Ribbon Bar.
and this is the Full stack trace:

at System.Drawing.Image.FromHbitmap(IntPtr hbitmap, IntPtr hpalette)
at System.Drawing.Image.FromHbitmap(IntPtr hbitmap)
at System.Drawing.Icon.ToBitmap()
at System.Windows.Forms.ThreadExceptionDialog..ctor(Exception t)
at System.Windows.Forms.Application.ThreadContext.OnThreadException(Exception t)
at System.Windows.Forms.Control.WndProcException(Exception e)
at System.Windows.Forms.Control.ControlNativeWindow.OnThreadException(Exception e)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at MyApp.Program.Main() in d:\\MyApp\\Application\\MyApp\\Program.cs:line 36"

UPADTED:

the code for calling mdi-children by clicking on ribbon bar buttons is here:

private void btnCustomerList_Click(object sender, EventArgs e)
{
    OpenForm(new FormCustomerList(), "Customer List");
}

private void btnCustomerRelated_Click(object sender, EventArgs e)
{
    OpenForm(new FormCustomerRelated(), "Customer Related");
}

and Here is OpenForm method:

private void OpenForm(Form formType, string Caption)
{
    foreach (Form nform in Application.OpenForms)
    {
        if (nform.GetType() == formType.GetType())
        {
            nform.Activate();
            return;
        }
    }
    this.MdiChildren.OfType<Form>().ToList().ForEach(x => x.Dispose());
    GC.Collect();

    Form form = formType;
    form.MdiParent = this;
    form.Dock = DockStyle.Fill;
    form.Show();
    this.Text = Caption;
}

and in every mdi child's form constructor, after InitializeComponent(); I wrote GC.Collect(); also. But as told in comments, the GDI objects in task manager will increase and increase till 10000 objects and then application will crash.

UPADTED: THE MOST ISSUE

It seems I have found the part which cause the most GDI objects. In every form there are some controls like textboxes, drop down list etc. I have set some rules for them, for example if user enter a textbox, its back color should be yellow and after leave it should be white again. So there is a main method which I call in form load to literate through all controls and find the target ones and add for example enter and leave events with the defined rules. something Like This:

private void FormCustomerList_Load(object sender, EventArgs e)
{
    ClassCRMControls.AddEventHandler(this);
}

and inside ClassCRMControls class:

public static void AddEventHandler(Control parent)
{
    foreach (Control c in parent.Controls)
    {
        if (c.GetType() == typeof(RadTextBox))
        {
            c.Enter += new EventHandler(ClassCRMControls.EnterEvent);
            c.Leave += new EventHandler(ClassCRMControls.LeaveEvent);
        }
        else
            AddEventHandler(c);
    }
}

private static void EnterEvent(object sender, EventArgs e)
{
    (sender as RadTextBox).TextBoxElement.TextBoxItem.BackColor = Color.FromArgb(255, 251, 147);
}

private static void LeaveEvent(object sender, EventArgs e)
{
      (sender as RadTextBox).TextBoxElement.TextBoxItem.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local);
}


问:
Is checking for true explicity bad by design?
Is it considered bad to explicitly check for the boolean true. Would it be better to do a simple if(success) ?

I've seen various jokes made about how if (someBoolean === true) is horrible code in a strongly typed language but is it also considered bad in weakly typed languages?

This would apply for any weakly typed language that does type coercion on an if statement.

A specific example would be :

```<code>var onSuccess = function (JSONfromServer) {
    // explicitly check for the boolean value `true`
    if (JSONfromServer === true) {
         // do some things
    }
}

// pass it to an ajax as a callback
doSomeAjax(onSuccess);
</code>```

[Edit]

In this particular case the success variable is any valid JSON returned from a server. So it could be anything. if its the boolean true then a success happened. If it's some error handling object then it will be handled. If it's something else then it will probably be handled quietly.

The question was is getting the server to return true as JSON and checking for a good way to handle the case where the action succeeded.

I wanted to avoid being specific to JavaScript & AJAX though.

答:
I've read quite a bit about JavaScript, and I've never seen anyone say that if(success) was a bad practice. I would do it. Are you sure the success parameter will always be boolean? Right now, if that would ever change to something else, you'd have to edit the function. But if you just use if(success), it would work for other "truthy" and "falsey" values, like a string vs. an empty string, or 1 vs 0.

If you want to convert whatever that parameter is to its boolean value, you can just double-negate it: !!success; but that's not necessary inside an conditional like that.

Body:
Is it considered bad to explicitly check for the boolean true. Would it be better to do a simple if(success) ?

I've seen various jokes made about how if (someBoolean === true) is horrible code in a strongly typed language but is it also considered bad in weakly typed languages?

This would apply for any weakly typed language that does type coercion on an if statement.

A specific example would be :

var onSuccess = function (JSONfromServer) {
    // explicitly check for the boolean value `true`
    if (JSONfromServer === true) {
         // do some things
    }
}

// pass it to an ajax as a callback
doSomeAjax(onSuccess);

[Edit]

In this particular case the success variable is any valid JSON returned from a server. So it could be anything. if its the boolean true then a success happened. If it's some error handling object then it will be handled. If it's something else then it will probably be handled quietly.

The question was is getting the server to return true as JSON and checking for a good way to handle the case where the action succeeded.

I wanted to avoid being specific to JavaScript & AJAX though.


问:
Android - How to remove app name from ActionBar
This is my app:

Now i want to remove the app name from my ActionBar...

I want it like this:

my code:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myapp="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/phone"
        android:title="@string/phone"
        android:icon="@drawable/phone"
        myapp:showAsAction="ifRoom" />

    <item
        android:id="@+id/computer"
        android:title="@string/computer"
        android:icon="@drawable/computer"
        myapp:showAsAction="ifRoom"  />

</menu>
</code>```

答:
If you want to hide it use this code

```<code>getSupportActionBar().setDisplayShowTitleEnabled(false)
</code>```

or if you want to change the name use this

```<code>getSupportActionBar().setTitle("type yor title here");
</code>```

Body:
This is my app:

Now i want to remove the app name from my ActionBar...

I want it like this:

my code:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myapp="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/phone"
        android:title="@string/phone"
        android:icon="@drawable/phone"
        myapp:showAsAction="ifRoom" />

    <item
        android:id="@+id/computer"
        android:title="@string/computer"
        android:icon="@drawable/computer"
        myapp:showAsAction="ifRoom"  />

</menu>

Body:
If you want to hide it use this code

getSupportActionBar().setDisplayShowTitleEnabled(false)

or if you want to change the name use this

getSupportActionBar().setTitle("type yor title here");


问:
How to get all user details in rest api wordpress
I am trying to get all the user details from wordpress 4.7 through the rest api - wp-json/wp/v2/users.

Currently I am seeing a lot of fields for the user object (close to 100 fields, amr user plugin installed) in the wordpress site, but the api is returning very few fields.

How can I get all the fields of user object in the rest api, should I install any other plugin for the same?

答:
You are only receiving the user fields which are stored in the wp_users table, but not the fields which are stored in the wp_usermeta table.

In order to get all information about a user, you have to get the user meta fields of this user from the REST API.

How to get user meta fields from the REST API:

Look into register_rest_field() to register meta with the rest api.

```<code>add_action( 'rest_api_init', 'adding_user_meta_rest' );

function adding_user_meta_rest() {
   register_rest_field( 'user',
                        'collapsed_widgets',
                         array(
                           'get_callback'      => 'user_meta_callback',
                           'update_callback'   => null,
                           'schema'            => null,
                            )
                      );
}
</code>```

And then put your get_user_meta bit in the callback.

function user_meta_callback( $user, $field_name, $request) {
       return get_user_meta( $user[ 'id' ], $field_name, true );
   }

The WP_REST_Meta_Fields class may provide more useful insight as well.

The later part of this answer I have found in this answer on WordPress Stackexchange: https://wordpress.stackexchange.com/questions/270154/getting-user-meta-data-from-wp-rest-api

Body:
You are only receiving the user fields which are stored in the wp_users table, but not the fields which are stored in the wp_usermeta table.

In order to get all information about a user, you have to get the user meta fields of this user from the REST API.

How to get user meta fields from the REST API:

Look into register_rest_field() to register meta with the rest api.

add_action( 'rest_api_init', 'adding_user_meta_rest' );

function adding_user_meta_rest() {
   register_rest_field( 'user',
                        'collapsed_widgets',
                         array(
                           'get_callback'      => 'user_meta_callback',
                           'update_callback'   => null,
                           'schema'            => null,
                            )
                      );
}

And then put your get_user_meta bit in the callback.

function user_meta_callback( $user, $field_name, $request) {
       return get_user_meta( $user[ 'id' ], $field_name, true );
   }

The WP_REST_Meta_Fields class may provide more useful insight as well.

The later part of this answer I have found in this answer on WordPress Stackexchange: https://wordpress.stackexchange.com/questions/270154/getting-user-meta-data-from-wp-rest-api


问:
Dealing with Promises
I wanted to ask a question about the way I am using Promises, since I'm not sure if I have over complicated things.

Firstly I am trying to create some methods that I want to execute one after another as the rely on the outcome of each previous method.

My project structure is like so

```<code>my_project
csv
helpers
  FileDownload.js
scripts
  getCSVData.js
app.js
</code>```

Each file at the moment looks like

```<code>## FileDownload.js
const fetch = require('node-fetch');
const fs = require('fs');

module.exports = function(url, target) {
  return fetch(url)
  .then(function(res) {
    return new Promise((resolve, reject) => {
      var dest = fs.createWriteStream(target);
      res.body.pipe(dest)
      .on('finish', () => resolve()) // ** Resolve on success
      .on('error', reject);        // ** Reject on error
    });
  }).then(result => {
    console.log(`File saved at ${target}`)
    return result;
  });

}

## getCSVData.js

const file_download = require('../helpers/FileDownload')

function getPremierLeagueData() {
  file_download("http://www.football-data.co.uk/mmz4281/1718/E0.csv", "./csv/premier_league/premier_league.csv")
}

module.exports = {
  getPremierLeagueData: getPremierLeagueData
}

## app.js
const premier_league = require('./scripts/getCSVData')

premier_league.getPremierLeagueData()
  .then(function(result){ console.log(result)})
</code>```

When running node app.js i get the error TypeError: Cannot read property 'then' of undefined

If I go back to my FileDownload function and console.log(result) that is undefined.

My confusion here is that because resolve() is called I am thinking that the Promise is resolved? So that should carry through to the .then.

I am clearly misunderstanding something here.

答:
Your getPremierLeagueData function does not return a Promise. It does not return anything…

You just need to return the result of file_download, which is already a Promise:

function getPremierLeagueData() {
  return file_download(args)
}
```

Title: Dealing with Promises

Body:
I wanted to ask a question about the way I am using Promises, since I'm not sure if I have over complicated things.

Firstly I am trying to create some methods that I want to execute one after another as the rely on the outcome of each previous method.

My project structure is like so

my_project
csv
helpers
  FileDownload.js
scripts
  getCSVData.js
app.js

Each file at the moment looks like

## FileDownload.js
const fetch = require('node-fetch');
const fs = require('fs');

module.exports = function(url, target) {
  return fetch(url)
  .then(function(res) {
    return new Promise((resolve, reject) => {
      var dest = fs.createWriteStream(target);
      res.body.pipe(dest)
      .on('finish', () => resolve()) // ** Resolve on success
      .on('error', reject);        // ** Reject on error
    });
  }).then(result => {
    console.log(`File saved at ${target}`)
    return result;
  });

}

## getCSVData.js

const file_download = require('../helpers/FileDownload')

function getPremierLeagueData() {
  file_download("http://www.football-data.co.uk/mmz4281/1718/E0.csv", "./csv/premier_league/premier_league.csv")
}

module.exports = {
  getPremierLeagueData: getPremierLeagueData
}

## app.js
const premier_league = require('./scripts/getCSVData')

premier_league.getPremierLeagueData()
  .then(function(result){ console.log(result)})

When running node app.js i get the error TypeError: Cannot read property 'then' of undefined

If I go back to my FileDownload function and console.log(result) that is undefined.

My confusion here is that because resolve() is called I am thinking that the Promise is resolved? So that should carry through to the .then.

I am clearly misunderstanding something here.


问:
how to read avro files in python 3.5.2
I am trying to read avro files using python.

I installed Apache Avro successfully (I think I did because I am able to "import avro" in the python shell) following the instruction here

```<code>https://avro.apache.org/docs/1.8.1/gettingstartedpython.html
</code>```

However, when I try to read avro files following the code in the above instruction. I keep receiving errors when importing avro related stuff.

```<code>>>> import avro.schema
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
import avro.schema
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 954, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 896, in _find_spec
File "<frozen importlib._bootstrap_external>", line 1139, in find_spec
File "<frozen importlib._bootstrap_external>", line 1115, in _get_spec
File "<frozen importlib._bootstrap_external>", line 1096, in _legacy_get_spec
File "<frozen importlib._bootstrap>", line 444, in spec_from_loader
File "<frozen importlib._bootstrap_external>", line 533, in spec_from_file_location
File "I:\Program Files\lib\site-packages\avro-_avro_version_-py3.5.egg\avro\schema.py", line 340
except Exception, e:
                ^
SyntaxError: invalid syntax

>>> from avro.datafile import DataFileReader, DataFileWriter
Traceback (most recent call last):
File "I:\Program Files\lib\site-packages\avro-_avro_version_-py3.5.egg\avro\datafile.py", line 21, in <module>
from cStringIO import StringIO
ImportError: No module named 'cStringIO'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
from avro.datafile import DataFileReader, DataFileWriter
File "I:\Program Files\lib\site-packages\avro-_avro_version_-py3.5.egg\avro\datafile.py", line 23, in <module>
from StringIO import StringIO
ImportError: No module named 'StringIO'

>>> from avro.io import DatumReader, DatumWriter
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
from avro.io import DatumReader, DatumWriter
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 954, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 896, in _find_spec
File "<frozen importlib._bootstrap_external>", line 1139, in find_spec
File "<frozen importlib._bootstrap_external>", line 1115, in _get_spec
File "<frozen importlib._bootstrap_external>", line 1096, in _legacy_get_spec
File "<frozen importlib._bootstrap>", line 444, in spec_from_loader
File "<frozen importlib._bootstrap_external>", line 533, in spec_from_file_location
File "I:\Program Files\lib\site-packages\avro-_avro_version_-py3.5.egg\avro\io.py", line 200
bits = (((ord(self.read(1)) & 0xffL)) |
                                  ^
SyntaxError: invalid syntax
</code>```

So did I install avro successfully? Why am I receiving those errors? I am using python 3.5.2 on windows 7.

Edited
I fixed the issue following the suggestion by Stephane Martin. Then I try to read avro files into python. I have a bunch of avros in a directory which has already been set as the right path in the python. Here is my code

```<code>import avro.schema
from avro.datafile import DataFileReader, DataFileWriter
from avro.io import DatumReader, DatumWriter

reader = DataFileReader(open("part-00000-of-01733.avro", "r"), DatumReader())
for user in reader:
   print (user)
reader.close()
</code>```

And it returns the error

```<code>Traceback (most recent call last):
File "I:\DJ data\read avro.py", line 5, in <module>
reader = DataFileReader(open("part-00000-of-01733.avro", "r"), DatumReader())
File "I:\Program Files\lib\site-packages\avro_python3-1.8.1-py3.5.egg\avro\datafile.py", line 349, in __init__
self._read_header()
File "I:\Program Files\lib\site-packages\avro_python3-1.8.1-py3.5.egg\avro\datafile.py", line 459, in _read_header
META_SCHEMA, META_SCHEMA, self.raw_decoder)
File "I:\Program Files\lib\site-packages\avro_python3-1.8.1-py3.5.egg\avro\io.py", line 525, in read_data
return self.read_record(writer_schema, reader_schema, decoder)
File "I:\Program Files\lib\site-packages\avro_python3-1.8.1-py3.5.egg\avro\io.py", line 725, in read_record
field_val = self.read_data(field.type, readers_field.type, decoder)
File "I:\Program Files\lib\site-packages\avro_python3-1.8.1-py3.5.egg\avro\io.py", line 515, in read_data
return self.read_fixed(writer_schema, reader_schema, decoder)
File "I:\Program Files\lib\site-packages\avro_python3-1.8.1-py3.5.egg\avro\io.py", line 568, in read_fixed
return decoder.read(writer_schema.size)
File "I:\Program Files\lib\site-packages\avro_python3-1.8.1-py3.5.egg\avro\io.py", line 170, in read
input_bytes = self.reader.read(n)
File "I:\Program Files\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
</code>```

UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 863: character maps to

I am indeed aware that in the example in the instruction, a schema is created first. But what is a avsc file? How shall I create it and the corresponding schema in my case?

答:
With recent versions of the avro package, this should no longer be an issue.

Original answer:

When installing through pip or a similar package manager: install the avro-python3 package instead of just avro.

Title: how to read avro files in python 3.5.2

Body:
I am trying to read avro files using python.

I installed Apache Avro successfully (I think I did because I am able to "import avro" in the python shell) following the instruction here

https://avro.apache.org/docs/1.8.1/gettingstartedpython.html

However, when I try to read avro files following the code in the above instruction. I keep receiving errors when importing avro related stuff.

>>> import avro.schema
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
import avro.schema
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 954, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 896, in _find_spec
File "<frozen importlib._bootstrap_external>", line 1139, in find_spec
File "<frozen importlib._bootstrap_external>", line 1115, in _get_spec
File "<frozen importlib._bootstrap_external>", line 1096, in _legacy_get_spec
File "<frozen importlib._bootstrap>", line 444, in spec_from_loader
File "<frozen importlib._bootstrap_external>", line 533, in spec_from_file_location
File "I:\Program Files\lib\site-packages\avro-_avro_version_-py3.5.egg\avro\schema.py", line 340
except Exception, e:
                ^
SyntaxError: invalid syntax

>>> from avro.datafile import DataFileReader, DataFileWriter
Traceback (most recent call last):
File "I:\Program Files\lib\site-packages\avro-_avro_version_-py3.5.egg\avro\datafile.py", line 21, in <module>
from cStringIO import StringIO
ImportError: No module named 'cStringIO'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
from avro.datafile import DataFileReader, DataFileWriter
File "I:\Program Files\lib\site-packages\avro-_avro_version_-py3.5.egg\avro\datafile.py", line 23, in <module>
from StringIO import StringIO
ImportError: No module named 'StringIO'

>>> from avro.io import DatumReader, DatumWriter
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
from avro.io import DatumReader, DatumWriter
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 954, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 896, in _find_spec
File "<frozen importlib._bootstrap_external>", line 1139, in find_spec
File "<frozen importlib._bootstrap_external>", line 1115, in _get_spec
File "<frozen importlib._bootstrap_external>", line 1096, in _legacy_get_spec
File "<frozen importlib._bootstrap>", line 444, in spec_from_loader
File "<frozen importlib._bootstrap_external>", line 533, in spec_from_file_location
File "I:\Program Files\lib\site-packages\avro-_avro_version_-py3.5.egg\avro\io.py", line 200
bits = (((ord(self.read(1)) & 0xffL)) |
                                  ^
SyntaxError: invalid syntax

So did I install avro successfully? Why am I receiving those errors? I am using python 3.5.2 on windows 7.

Edited
I fixed the issue following the suggestion by Stephane Martin. Then I try to read avro files into python. I have a bunch of avros in a directory which has already been set as the right path in the python. Here is my code

import avro.schema
from avro.datafile import DataFileReader, DataFileWriter
from avro.io import DatumReader, DatumWriter

reader = DataFileReader(open("part-00000-of-01733.avro", "r"), DatumReader())
for user in reader:
   print (user)
reader.close()

And it returns the error

Traceback (most recent call last):
File "I:\DJ data\read avro.py", line 5, in <module>
reader = DataFileReader(open("part-00000-of-01733.avro", "r"), DatumReader())
File "I:\Program Files\lib\site-packages\avro_python3-1.8.1-py3.5.egg\avro\datafile.py", line 349, in __init__
self._read_header()
File "I:\Program Files\lib\site-packages\avro_python3-1.8.1-py3.5.egg\avro\datafile.py", line 459, in _read_header
META_SCHEMA, META_SCHEMA, self.raw_decoder)
File "I:\Program Files\lib\site-packages\avro_python3-1.8.1-py3.5.egg\avro\io.py", line 525, in read_data
return self.read_record(writer_schema, reader_schema, decoder)
File "I:\Program Files\lib\site-packages\avro_python3-1.8.1-py3.5.egg\avro\io.py", line 725, in read_record
field_val = self.read_data(field.type, readers_field.type, decoder)
File "I:\Program Files\lib\site-packages\avro_python3-1.8.1-py3.5.egg\avro\io.py", line 515, in read_data
return self.read_fixed(writer_schema, reader_schema, decoder)
File "I:\Program Files\lib\site-packages\avro_python3-1.8.1-py3.5.egg\avro\io.py", line 568, in read_fixed
return decoder.read(writer_schema.size)
File "I:\Program Files\lib\site-packages\avro_python3-1.8.1-py3.5.egg\avro\io.py", line 170, in read
input_bytes = self.reader.read(n)
File "I:\Program Files\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]

UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 863: character maps to

I am indeed aware that in the example in the instruction, a schema is created first. But what is a avsc file? How shall I create it and the corresponding schema in my case?


问:
HTML data is hidden from urllib
How do I get the real content from this page:
http://kursuskatalog.au.dk/da/course/74960/105E17-Demokrati-og-diktatur-i-komparativt-perspektiv

All I get from the code below is some links to javascript and CSS files. Is there a way out of this?

```<code>from urllib.request import urlopen
html = urlopen("http://kursuskatalog.au.dk/da/course/74960/105E17-Demokrati-og-diktatur-i-komparativt-perspektiv")
print(html.read())
</code>```

Best regards, Kresten

答: Content in this URL is created with JavaScript after page is loaded.</p>

Title: HTML data is hidden from urllib

Body:
How do I get the real content from this page:
http://kursuskatalog.au.dk/da/course/74960/105E17-Demokrati-og-diktatur-i-komparativt-perspektiv

All I get from the code below is some links to javascript and CSS files. Is there a way out of this?

from urllib.request import urlopen
html = urlopen("http://kursuskatalog.au.dk/da/course/74960/105E17-Demokrati-og-diktatur-i-komparativt-perspektiv")
print(html.read())

Best regards, Kresten


问:
passing values between custom components in Flex - mxml
how can i pass values from my custom components back to the main.mxml?
 i need to do this to pass back ana array collection </p>

答: got it; just needed to import mx.core.Application;</p>

OwnerDisplayName: luckoftheirish


问:
object oriented JavaScript
Is there any error in my code esp var newpoint[0] =  new Point; . I wnat to know on how to do oop in javascript

```<code>function Point()
{
    var x;
    var y;
}

var length = 1;
var arrayindex;
var newpoint[0] =  new Point;
newpoint[0].x = 10;
newpoint[0].y = 10;
for(i=0 ; i<10; i ++)
{
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}
</code>```

EDIT : Thanks all . I have come up with two code need to know which one is better any any sugesstion and protips . both work

```<code>function Point()
{
    this.x;
    this. y;
}

var length = 0;
var newpoint = [];

for(i=0 ; i<10; i ++)
{
    newpoint[length] =new Point();
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}
</code>```

and

```<code>var length = 0;
var newpoint = [];
for(i=0 ; i<10; i ++)
{
    newpoint[length] = {};
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}
for(var arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}
</code>```

答:
newpoint has to be an array first, you cannot use:

```<code>var newpoint[0] = new Point(); //newpoint has to be declared on its own to be an array if you like to use [0] indexing;
</code>```

Use

```<code>var newpoint = [];
newpoint[0] = new Point();
</code>```

or

```<code>var newpoint = [new Point()];  //Cipi's suggestion for oneliner
</code>```

You need () after the type. The new keyword calls the constructor method which can accept parameters so you need to use ().

```<code>var newpoint[0] = new Point();
</code>```

Also the class ddeclaration is not right
The declaration is your constructor and has to return it self:

```<code>function Point()
{
    this.x = null; //Or whatever default value you like
    this.y = null;
    /*
    "This" makes the x and y variables members of the object instead of
    local variables if the constructor function, without "this" they will
    be forgotten as soon as the function ends. */
}
</code>```

You can add methods either in the constructor

```<code>function Point()
{
    this.x = null; //Or whatever default value you like
    this.y = null;
    this.list = function ()
    {
        alert(this.x);
    };
}
</code>```

or using prototype

```<code>function Point()
{
    this.x = null; //Or whatever default value you like
    this.y = null;
}
Point.prototype.list = function ()
{
     alert(this.x);
}
</code>```

Title: object oriented JavaScript

Body:
Is there any error in my code esp var newpoint[0] =  new Point; . I wnat to know on how to do oop in javascript

function Point()
{
    var x;
    var y;
}

var length = 1;
var arrayindex;
var newpoint[0] =  new Point;
newpoint[0].x = 10;
newpoint[0].y = 10;
for(i=0 ; i<10; i ++)
{
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}

EDIT : Thanks all . I have come up with two code need to know which one is better any any sugesstion and protips . both work

function Point()
{
    this.x;
    this. y;
}

var length = 0;
var newpoint = [];

for(i=0 ; i<10; i ++)
{
    newpoint[length] =new Point();
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}

and

var length = 0;
var newpoint = [];
for(i=0 ; i<10; i ++)
{
    newpoint[length] = {};
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}
for(var arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}

Body:
newpoint has to be an array first, you cannot use:

var newpoint[0] = new Point(); //newpoint has to be declared on its own to be an array if you like to use [0] indexing;

Use

var newpoint = [];
newpoint[0] = new Point();

or

var newpoint = [new Point()];  //Cipi's suggestion for oneliner

You need () after the type. The new keyword calls the constructor method which can accept parameters so you need to use ().

var newpoint[0] = new Point();

Also the class ddeclaration is not right
The declaration is your constructor and has to return it self:

function Point()
{
    this.x = null; //Or whatever default value you like
    this.y = null;
    /*
    "This" makes the x and y variables members of the object instead of
    local variables if the constructor function, without "this" they will
    be forgotten as soon as the function ends. */
}

You can add methods either in the constructor

function Point()
{
    this.x = null; //Or whatever default value you like
    this.y = null;
    this.list = function ()
    {
        alert(this.x);
    };
}

or using prototype

function Point()
{
    this.x = null; //Or whatever default value you like
    this.y = null;
}
Point.prototype.list = function ()
{
     alert(this.x);
}


问:
How can I get Chrome GPU information through scripts or any other means?
I want to run diagnostics of Chrome GPU, before loading a new tab which can view 3D data. I want to run a diagnostics to check if some GPU options are turned on, before loading the new tab.

How can I get Chrome GPU information through scripts or any other means?

答:
Not sure what you're asking.

You can get the GPU info by using the WEBGL_debug_renderer_info extension.

function getGPUInfo() {
  const gl = document.createElement("canvas").getContext("webgl");
  const ext = gl.getExtension('WEBGL_debug_renderer_info');
  return ext ? {
    vendor: gl.getParameter(ext.UNMASKED_VENDOR_WEBGL),
    renderer: gl.getParameter(ext.UNMASKED_RENDERER_WEBGL),
  } : {
    vendor: "unknown",
    renderer: "unknown",
  };
}

console.log(getGPUInfo());```


问:
Styling JQuery UI Autocomplete
Fiddle

I'm trying to style the sections inside the AutoComplete, but I don't know what to put in the CSS for the sections. I'm specifically trying to make:

```<code>color: #96f226;
border-radius: 0px;
border: 1px solid #454545;
</code>```

Any suggestions???

答:
Based on @md-nazrul-islam reply, This is what I did with SCSS:</p>

```<code>ul.ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border: 1px solid #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    //@include border-radius(5px);
    @include box-shadow( rgba(0, 0, 0, 0.1) 0 5px 10px );
    @include background-clip(padding-box);
    *border-right-width: 2px;
    *border-bottom-width: 2px;

    li.ui-menu-item{
        padding:0 .5em;
        line-height:2em;
        font-size:.8em;
        &.ui-state-focus{
            background: #F7F7F7;
        }
    }

}
</code>```

Title: Styling JQuery UI Autocomplete

Body:
Fiddle

I'm trying to style the sections inside the AutoComplete, but I don't know what to put in the CSS for the sections. I'm specifically trying to make:

color: #96f226;
border-radius: 0px;
border: 1px solid #454545;

Any suggestions???

Body:
Based on @md-nazrul-islam reply, This is what I did with SCSS:

ul.ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border: 1px solid #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    //@include border-radius(5px);
    @include box-shadow( rgba(0, 0, 0, 0.1) 0 5px 10px );
    @include background-clip(padding-box);
    *border-right-width: 2px;
    *border-bottom-width: 2px;

    li.ui-menu-item{
        padding:0 .5em;
        line-height:2em;
        font-size:.8em;
        &.ui-state-focus{
            background: #F7F7F7;
        }
    }

}


问:
Kivy : Run .py file onclick on image

demo.Kv

```<code>AsyncImage:
            canvas:
                Rectangle:
                    texture: CoreImage("add.jpg").texture
                    size: self.width, self.height
                    size: 30, 30
                    pos: self.x - 1, self.y
                    #on_release: os.system("python test.py")
</code>```

Can anyone help me?

 1. This code is in my .kv file. How to run test.py file onclick on add.jpg image.

Any advise or guidance would be greatly appreciated..!!

答:
You have to make a custom widget:

.py:

```<code>from kivy.uix.image import AsyncImage
import os

MyAsyncImage(AsyncImage)

    #other stuff

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            os.system('python file.py')
</code>```

Then in your .kv:

```<code>MyAsyncImage:
    canvas:
        Rectangle:
            texture: CoreImage("add.jpg").texture
            size: self.width, self.height
            size: 30, 30
            pos: self.x - 1, self.y
</code>```

Title: Kivy : Run .py file onclick on image

Body:
demo.Kv

AsyncImage:
            canvas:
                Rectangle:
                    texture: CoreImage("add.jpg").texture
                    size: self.width, self.height
                    size: 30, 30
                    pos: self.x - 1, self.y
                    #on_release: os.system("python test.py")

Can anyone help me?

 1. This code is in my .kv file. How to run test.py file onclick on add.jpg image.

Any advise or guidance would be greatly appreciated..!!

Body:
You have to make a custom widget:

.py:

from kivy.uix.image import AsyncImage
import os

MyAsyncImage(AsyncImage)

    #other stuff

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            os.system('python file.py')

Then in your .kv:

MyAsyncImage:
    canvas:
        Rectangle:
            texture: CoreImage("add.jpg").texture
            size: self.width, self.height
            size: 30, 30
            pos: self.x - 1, self.y


问:
How to remove nan values from a dictionaries list of values in python 3?
Hi I have a list of dictionaries, each dictionary has a list of values. In that list there are nan values which I wish to remove. Here is an example dictionary;

```<code>temp = {'A': ['field1', 'field2', 'field3', np.nan, np.nan], 'B': ['field1', 'field2', 'field3', 'field4', np.nan]}
</code>```

which looks like;

```<code>{'A': ['field1', 'field2', 'field3', nan, nan], 'B': ['field1', 'field2', 'field3', 'field4', nan]}
</code>```

I desired output is :

```<code>{'A': ['field1', 'field2', 'field3'], 'B': ['field1', 'field2', 'field3', 'field4']}
</code>```

I've tired the following with no success;

```<code>res = {k:v for k,v in temp2.items() if v is not np.nan}
</code>```

Any help is appreciated

答:
You are comparing the whole value (v in your case) with np.nan, but only single elements of the value of the dictionary are np.nan.
You want:</p>

```<code>res = {k:[elem for elem in v if elem is not np.nan] for k,v in temp.items()}
</code>```

Body:
Hi I have a list of dictionaries, each dictionary has a list of values. In that list there are nan values which I wish to remove. Here is an example dictionary;

temp = {'A': ['field1', 'field2', 'field3', np.nan, np.nan], 'B': ['field1', 'field2', 'field3', 'field4', np.nan]}

which looks like;

{'A': ['field1', 'field2', 'field3', nan, nan], 'B': ['field1', 'field2', 'field3', 'field4', nan]}

I desired output is :

{'A': ['field1', 'field2', 'field3'], 'B': ['field1', 'field2', 'field3', 'field4']}

I've tired the following with no success;

res = {k:v for k,v in temp2.items() if v is not np.nan}

Any help is appreciated

Body:
You are comparing the whole value (v in your case) with np.nan, but only single elements of the value of the dictionary are np.nan.
You want:

res = {k:[elem for elem in v if elem is not np.nan] for k,v in temp.items()}


问:
What is wrong with my "won" function
I am working on PSET3 of Harvard CS50 online and having problems with the "won" function for CS50 game of fifteen.

The function works fine with a 4x4 grid puzzle but not with 3x3

The function returns true a couple of steps too early in case of a 3x3.

The function is required to look through a 2D array for numbers in ascending order from 1 to 8 for a 3x3 size game and 1 to 15 in a 4x4 size game with the last element of the array being zero.

My thought process for the code is that i set the counter initially to 1 and check it against the first element of the array. If it matches then increase the counter by 1 and repeat for the next element.

If the counter reaches the total number of elements in the array it returns true and, if the counter does not match the corresponding array element at any time it returns false.

Can you see what I am doing wrong?

```<code>/**
 * Returns true if game is won (i.e., board is in winning configuration)
 * else false.
 */
bool won(void)
{
    // TODO

    int counter = 1;

    for (int i=0; i < d; i++)
    {
        for (int j=0; j < d; j++)
        {
            if (board[i][j] == counter)
            {
                counter++;
            }
            if (counter == (d*d))
            {
                return true;
            }
        }
    }
    return false;
}
</code>```

答:
Your won routine returns true if all the elements are in order, ignoring the element with value zero. Thus, if the elements are:

```<code>1 2 3
_ 4 5
6 7 8
</code>```

Then your code will increment counter when it sees 1, 2, and 3. It will not increment counter when it sees the 0 where _ is shown above. Then it will increment counter when it sees 4, 5, 6, 7, and 8. Then counter is 9, so it equals d*d, and won returns true.

Fundamentally, your won routine is too flexible. At each step, it increments counter if the current element equals counter—but it is passive otherwise. That is, it continues examination even if the desired condition was not met. Since there is only one “winning” position, if any element is out of position, you can return false as soon as you see it.

Title: What is wrong with my "won" function

Body:
I am working on PSET3 of Harvard CS50 online and having problems with the "won" function for CS50 game of fifteen.

The function works fine with a 4x4 grid puzzle but not with 3x3

The function returns true a couple of steps too early in case of a 3x3.

The function is required to look through a 2D array for numbers in ascending order from 1 to 8 for a 3x3 size game and 1 to 15 in a 4x4 size game with the last element of the array being zero.

My thought process for the code is that i set the counter initially to 1 and check it against the first element of the array. If it matches then increase the counter by 1 and repeat for the next element.

If the counter reaches the total number of elements in the array it returns true and, if the counter does not match the corresponding array element at any time it returns false.

Can you see what I am doing wrong?

/**
 * Returns true if game is won (i.e., board is in winning configuration)
 * else false.
 */
bool won(void)
{
    // TODO

    int counter = 1;

    for (int i=0; i < d; i++)
    {
        for (int j=0; j < d; j++)
        {
            if (board[i][j] == counter)
            {
                counter++;
            }
            if (counter == (d*d))
            {
                return true;
            }
        }
    }
    return false;
}

Body:
Your won routine returns true if all the elements are in order, ignoring the element with value zero. Thus, if the elements are:

1 2 3
_ 4 5
6 7 8

Then your code will increment counter when it sees 1, 2, and 3. It will not increment counter when it sees the 0 where _ is shown above. Then it will increment counter when it sees 4, 5, 6, 7, and 8. Then counter is 9, so it equals d*d, and won returns true.

Fundamentally, your won routine is too flexible. At each step, it increments counter if the current element equals counter—but it is passive otherwise. That is, it continues examination even if the desired condition was not met. Since there is only one “winning” position, if any element is out of position, you can return false as soon as you see it.


问:
Convert Html file to pdf in specific colour
```<code>options = {
    'page-size': 'Letter',
    'margin-top': '0.75in',
    'margin-right': '0.75in',
    'margin-bottom': '0.75in',
    'margin-left': '0.75in',
    'encoding': "UTF-8",
    'custom-header' : [
        ('Accept-Encoding', 'gzip')
    ]

}

pdfkit.from_file('htmlfile.html', 'tjprofile.pdf', options=options)
</code>```

<p>I want to change the html file to pdf with specific colour, how i do that? </p>

答:
use BeautifulSoup to convert HTML to pdf</p>

```<code>  import sys
  from bs4 import BeautifulSoup
  from PDFWriter import PDFWriter

def usage():
sys.stderr.write("Usage: python " + sys.argv[0] + " html_file pdf_file\n")
sys.stderr.write("which will extract only the text from html_file and\n")
sys.stderr.write("write it to pdf_file\n")

def main():

# Create some HTML for testing conversion of its text to PDF.
html_doc = """
<html>
    <head>
        <title>
        Test file for HTMLTextToPDF
        </title>
    </head>
    <body>
    This is text within the body element but outside any paragraph.
    <p>
    This is a paragraph of text. Hey there, how do you do?
    The quick red fox jumped over the slow blue cow.
    </p>
    <p>
    This is another paragraph of text.
    Don't mind what it contains.
    What is mind? Not matter.
    What is matter? Never mind.
    </p>
    This is also text within the body element but not within any paragraph.
    </body>
</html>
"""

pw = PDFWriter("HTMLTextTo.pdf")
pw.setFont("Courier", 10)
pw.setHeader("Conversion of HTML text to PDF")
pw.setFooter("Generated by xtopdf: http://slid.es/vasudevram/xtopdf")

# Use method chaining this time.
for line in BeautifulSoup(html_doc).get_text().split("\n"):
    pw.writeLine(line)
pw.savePage()
pw.close()

if __name__ == '__main__':
main()
</code>```

Body:
options = {
    'page-size': 'Letter',
    'margin-top': '0.75in',
    'margin-right': '0.75in',
    'margin-bottom': '0.75in',
    'margin-left': '0.75in',
    'encoding': "UTF-8",
    'custom-header' : [
        ('Accept-Encoding', 'gzip')
    ]

}

pdfkit.from_file('htmlfile.html', 'tjprofile.pdf', options=options)

I want to change the html file to pdf with specific colour, how i do that?

Body:
use BeautifulSoup to convert HTML to pdf

  import sys
  from bs4 import BeautifulSoup
  from PDFWriter import PDFWriter

def usage():
sys.stderr.write("Usage: python " + sys.argv[0] + " html_file pdf_file\n")
sys.stderr.write("which will extract only the text from html_file and\n")
sys.stderr.write("write it to pdf_file\n")

def main():

# Create some HTML for testing conversion of its text to PDF.
html_doc = """
<html>
    <head>
        <title>
        Test file for HTMLTextToPDF
        </title>
    </head>
    <body>
    This is text within the body element but outside any paragraph.
    <p>
    This is a paragraph of text. Hey there, how do you do?
    The quick red fox jumped over the slow blue cow.
    </p>
    <p>
    This is another paragraph of text.
    Don't mind what it contains.
    What is mind? Not matter.
    What is matter? Never mind.
    </p>
    This is also text within the body element but not within any paragraph.
    </body>
</html>
"""

pw = PDFWriter("HTMLTextTo.pdf")
pw.setFont("Courier", 10)
pw.setHeader("Conversion of HTML text to PDF")
pw.setFooter("Generated by xtopdf: http://slid.es/vasudevram/xtopdf")

# Use method chaining this time.
for line in BeautifulSoup(html_doc).get_text().split("\n"):
    pw.writeLine(line)
pw.savePage()
pw.close()

if __name__ == '__main__':
main()


问:
excel formula to move value in a row to column
Column B needs to be moved into different columns like

B5 in one column, B6 in another column like wise

Row 2 -7 needs to be moved into individual columns

答: Put this in B2: INDEX(Sheet1!$B:$B,4 +(ROW()-1)*7 + COLUMN()-1) and extend it right to H2 and down as much is you need


问:
How to uppercase first char in the C input?
My output doesn't uppercase next argument after space-character (' ').

```<code>int main(void)
{
    int i = 0;
    int flag = OUT;
    char name[100];
    int leng = strlen(name);

    printf("Value pls: \n");
    fgets(name, 100, stdin);
    printf("%c", toupper(name[0]));

    while(name[i])
    {
        printf("%c", name[i + 1]);
        if(i == ' ')
        {
            printf("%c", toupper(name[i + 1]));
        }
        i++;
    }
}
</code>```

It's always shows somthing like this:
Value pls:
jon smith
Jon smith

Word "smith" is always lowercase.

答:
This is a fine opportunity to learn more about the other operators at your disposal - in this case "?:":

```<code>#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void)
  {
  char name[100];

  printf("Value pls: \n");
  fgets(name, 100, stdin);

  for(int i = 0 ; i < strlen(name) ; ++i)
    printf("%c", (i == 0 || name[i-1] == ' ') ? toupper(name[i]) : name[i]);
  }
</code>```

Best of luck.

Body:
My output doesn't uppercase next argument after space-character (' ').

int main(void)
{
    int i = 0;
    int flag = OUT;
    char name[100];
    int leng = strlen(name);

    printf("Value pls: \n");
    fgets(name, 100, stdin);
    printf("%c", toupper(name[0]));

    while(name[i])
    {
        printf("%c", name[i + 1]);
        if(i == ' ')
        {
            printf("%c", toupper(name[i + 1]));
        }
        i++;
    }
}

It's always shows somthing like this:
Value pls:
jon smith
Jon smith

Word "smith" is always lowercase.

Body:
This is a fine opportunity to learn more about the other operators at your disposal - in this case "?:":

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void)
  {
  char name[100];

  printf("Value pls: \n");
  fgets(name, 100, stdin);

  for(int i = 0 ; i < strlen(name) ; ++i)
    printf("%c", (i == 0 || name[i-1] == ' ') ? toupper(name[i]) : name[i]);
  }

Best of luck.