text:
Q: Accessing the index in 'for' loops How do I access the index while iterating over a sequence with a for loop?
xs = [8, 23, 45]

for x in xs:
    print("item #{} = {}".format(index, x))

Desired output:
item #1 = 8
item #2 = 23
item #3 = 45

A: You can use the index method:
ints = [8, 23, 45, 12, 78]
inds = [ints.index(i) for i in ints]

It is highlighted in a comment that this method doesn't work if there are duplicates in ints. The method below should work for any values in ints:
ints = [8, 8, 8, 23, 45, 12, 78]
inds = [tup[0] for tup in enumerate(ints)]

Or alternatively
ints = [8, 8, 8, 23, 45, 12, 78]
inds = [tup for tup in enumerate(ints)]

if you want to get both the index and the value in ints as a list of tuples.
It uses the method of enumerate in the selected answer to this question, but with list comprehension, making it faster with less code.

A: Use the built-in function enumerate():
for idx, x in enumerate(xs):
    print(idx, x)

It is non-pythonic to manually index via for i in range(len(xs)): x = xs[i] or manually manage an additional state variable.
Check out PEP 279 for more.

A: Tested on Python 3.11.2
Here's how you can access the indices with their corresponding array's elements using for loops, while loops and some looping functions.
1. Looping elements with counter and += operator.
items = [8, 23, 45, 12, 78]
counter = 0

for value in items:
    print(counter, value)
    counter += 1

Result:
#    0 8
#    1 23
#    2 45
#    3 12
#    4 78

2. Looping elements using enumerate() method.
items = [8, 23, 45, 12, 78]

for i in enumerate(items):
    print("index/value", i)

Result:
#    index/value (0, 8)
#    index/value (1, 23)
#    index/value (2, 45)
#    index/value (3, 12)
#    index/value (4, 78)

3. Using index and value separately.
items = [8, 23, 45, 12, 78]

for index, value in enumerate(items):
    print("index", index, "for value", value)

Result:
#    index 0 for value 8
#    index 1 for value 23
#    index 2 for value 45
#    index 3 for value 12
#    index 4 for value 78

4. You can change the index number to any increment.
items = [8, 23, 45, 12, 78]

for i, value in enumerate(items, start=1000):
    print(i, value)

Result:
#    1000 8
#    1001 23
#    1002 45
#    1003 12
#    1004 78

5. Automatic counter incrementation with range(len(...)).
items = [8, 23, 45, 12, 78]

for i in range(len(items)):
    print("Index:", i, "Value:", items[i])

Result:
#    ('Index:', 0, 'Value:', 8)
#    ('Index:', 1, 'Value:', 23)
#    ('Index:', 2, 'Value:', 45)
#    ('Index:', 3, 'Value:', 12)
#    ('Index:', 4, 'Value:', 78)

6. Using for loop inside function.
items = [8, 23, 45, 12, 78]

def enum(items, start=0):
    counter = start

    for value in items:
        print(counter, value)
        counter += 1

enum(items)

Result:
#    0 8
#    1 23
#    2 45
#    3 12
#    4 78

7. Of course, we can't forget about while loop.
items = [8, 23, 45, 12, 78]
counter = 0

while counter < len(items):
    print(counter, items[counter])
    counter += 1

Result:
#    0 8
#    1 23
#    2 45
#    3 12
#    4 78

8. yield statement returning a generator object.
def createGenerator():
    items = [8, 23, 45, 12, 78]

    for (j, k) in enumerate(items):
        yield (j, k)

generator = createGenerator()

for i in generator:
    print(i)

Result:
#    (0, 8)
#    (1, 23)
#    (2, 45)
#    (3, 12)
#    (4, 78)

9. Inline expression with for loop and lambda.
items = [8, 23, 45, 12, 78]

xerox = lambda upperBound: [(i, items[i]) for i in range(0, upperBound)]
print(xerox(5))

Result:
#    [(0, 8), (1, 23), (2, 45), (3, 12), (4, 78)]

10. Iterate over two lists at once using Python's zip() function.
items = [8, 23, 45, 12, 78]
indices = [0, 1, 2, 3, 4]

for item, index in zip(items, indices):
    print("{}: {}".format(index, item))

Result:
#    0: 8
#    1: 23
#    2: 45
#    3: 12
#    4: 78

11. Loop over 2 lists with a while loop and iter() & next() methods.
items = [8, 23, 45, 12, 78]
indices = range(len(items))

iterator1 = iter(indices)
iterator2 = iter(items)

try:
    while True:
        i = next(iterator1)
        element = next(iterator2)
        print(i, element)
except StopIteration:
    pass

Result:
#    0  8
#    1  23
#    2  45
#    3  12
#    4  78

A: A simple answer using a while loop:
arr = [8, 23, 45, 12, 78]
i = 0
while i < len(arr):
    print("Item ", i + 1, " = ", arr[i])
    i += 1

Output:
Item  1  =  8
Item  2  =  23
Item  3  =  45
Item  4  =  12
Item  5  =  78

A: As is the norm in Python, there are several ways to do this. In all examples assume: lst = [1, 2, 3, 4, 5]

*

*Using enumerate (considered most idiomatic)

for index, element in enumerate(lst):
    # Do the things that need doing here

This is also the safest option in my opinion because the chance of going into infinite recursion has been eliminated. Both the item and its index are held in variables and there is no need to write any further code to access the item.

*Creating a variable to hold the index (using for)

for index in range(len(lst)):   # or xrange
    # you will have to write extra code to get the element

*Creating a variable to hold the index (using while)

index = 0
while index < len(lst):
    # You will have to write extra code to get the element
    index += 1  # escape infinite recursion

*There is always another way

As explained before, there are other ways to do this that have not been explained here and they may even apply more in other situations. For example, using itertools.chain with for. It handles nested loops better than the other examples.

A: To print a tuple of (index, value) in a list comprehension using a for loop:
ints = [8, 23, 45, 12, 78]
print [(i,ints[i]) for i in range(len(ints))]

Output:
[(0, 8), (1, 23), (2, 45), (3, 12), (4, 78)]

A: You can simply use a variable such as count to count the number of elements in the list:
ints = [8, 23, 45, 12, 78]
count = 0
for i in ints:
    count = count + 1
    print('item #{} = {}'.format(count, i))

A: Old fashioned way:
for ix in range(len(ints)):
    print(ints[ix])

List comprehension:
[ (ix, ints[ix]) for ix in range(len(ints))]

>>> ints
[1, 2, 3, 4, 5]
>>> for ix in range(len(ints)): print ints[ix]
...
1
2
3
4
5
>>> [ (ix, ints[ix]) for ix in range(len(ints))]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
>>> lc = [ (ix, ints[ix]) for ix in range(len(ints))]
>>> for tup in lc:
...     print(tup)
...
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
>>>

A: Accessing indexes & Performance Benchmarking of approaches
The fastest way to access indexes of list within loop in Python 3.7 is to use the enumerate method for small, medium and huge lists.
Please see different approaches which can be used to iterate over list and access index value and their performance metrics (which I suppose would be useful for you) in code samples below:
# Using range
def range_loop(iterable):
    for i in range(len(iterable)):
        1 + iterable[i]

# Using enumerate
def enumerate_loop(iterable):
    for i, val in enumerate(iterable):
        1 + val

# Manual indexing
def manual_indexing_loop(iterable):
    index = 0
    for item in iterable:
        1 + item
        index += 1

See performance metrics for each method below:
from timeit import timeit

def measure(l, number=10000):
    print("Measure speed for list with %d items" % len(l))
    print("range: ", timeit(lambda :range_loop(l), number=number))
    print("enumerate: ", timeit(lambda :enumerate_loop(l), number=number))
    print("manual_indexing: ", timeit(lambda :manual_indexing_loop(l), number=number))

# Measure speed for list with 1000 items
measure(range(1000))
# range:  1.161622366
# enumerate:  0.5661940879999996
# manual_indexing:  0.610455682

# Measure speed for list with 100000 items
measure(range(10000))
# range:  11.794482958
# enumerate:  6.197628574000001
# manual_indexing:  6.935181098000001

# Measure speed for list with 10000000 items
measure(range(10000000), number=100)
# range:  121.416859069
# enumerate:  62.718909123
# manual_indexing:  69.59575057400002

As the result, using enumerate method is the fastest method for iteration when the index needed.
Adding some useful links below:

*

*What is the difference between range and xrange functions in Python 2.X?

*What is faster for loop using enumerate or for loop using xrange in Python?

*range(len(list)) or enumerate(list)?

A: You can use enumerate and embed expressions inside string literals to obtain the solution.
This is a simple way:
a=[4,5,6,8]
for b, val in enumerate(a):
    print('item #{} = {}'.format(b+1, val))

A: In addition to all the excellent answers above, here is a solution to this problem when working with pandas Series objects. In many cases, pandas Series have custom/unique indices (for example, unique identifier strings) that can't be accessed with the enumerate() function.

xs = pd.Series([8, 23, 45])

xs.index = ['G923002', 'G923004', 'G923005']

print(xs)

Output:
#    G923002     8
#    G923004    23
#    G923005    45
#    dtype: int64

We can see below that enumerate() doesn't give us the desired result:

for id, x in enumerate(xs):
    print("id #{} = {}".format(id, x))

Output:
#    id #0 = 8
#    id #1 = 23
#    id #2 = 45

We can access the indices of a pandas Series in a for loop using .items():

for id, x in xs.items():
    print("id #{} = {}".format(id, x))

Output:
#    id #G923002 = 8
#    id #G923004 = 23
#    id #G923005 = 45

A: One-liner lovers:
[index for index, datum in enumerate(data) if 'a' in datum]

Explaination:
>>> data = ['a','ab','bb','ba','alskdhkjl','hkjferht','lal']
>>> data
['a', 'ab', 'bb', 'ba', 'alskdhkjl', 'hkjferht', 'lal']
>>> [index for index, datum in enumerate(data) if 'a' in datum]
[0, 1, 3, 4, 6]
>>> [index for index, datum in enumerate(data) if 'b' in datum]
[1, 2, 3]
>>>

Points to take:

*

*Python list doesn't provide an index; if you are using for

*If you enumerate a list it will return you ANOTHER list

*

*BUT that list will have a different type

*it will wrap each and every element with an index as tuple

*we can access tuples as variables, separated with comma(,)

Thanks. Keep me in your prayers.

A: It's pretty simple to start it from 1 other than 0:
for index, item in enumerate(iterable, start=1):
   print index, item  # Used to print in python<3.x
   print(index, item) # Migrate to print() after 3.x+

A: First of all, the indexes will be from 0 to 4. Programming languages start counting from 0; don't forget that or you will come across an index-out-of-bounds exception. All you need in the for loop is a variable counting from 0 to 4 like so:
for x in range(0, 5):

Keep in mind that I wrote 0 to 5 because the loop stops one number before the maximum. :)
To get the value of an index, use
list[index]

A: You can use range(len(some_list)) and then lookup the index like this
xs = [8, 23, 45]
for i in range(len(xs)):
    print("item #{} = {}".format(i + 1, xs[i]))

Or use the Python's built-in enumerate function which allows you to loop over a list and retrieve the index and the value of each item in the list
xs = [8, 23, 45]
for idx, val in enumerate(xs, start=1):
    print("item #{} = {}".format(idx, val))

A: According to this discussion: object's list index
Loop counter iteration
The current idiom for looping over the indices makes use of the built-in range function:
for i in range(len(sequence)):
    # Work with index i

Looping over both elements and indices can be achieved either by the old idiom or by using the new zip built-in function:
for i in range(len(sequence)):
    e = sequence[i]
    # Work with index i and element e

or
for i, e in zip(range(len(sequence)), sequence):
    # Work with index i and element e

via PEP 212 – Loop Counter Iteration.

A: You can do it with this code:
ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
    index +=1
    print index, value

Use this code if you need to reset the index value at the end of the loop:
ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
    index +=1
    print index, value
    if index >= len(ints)-1:
        index = 0

A: If I were to iterate nums = [1, 2, 3, 4, 5] I would do
for i, num in enumerate(nums, start=1):
    print(i, num)

Or get the length as l = len(nums)
for i in range(l):
    print(i+1, nums[i])

A: In your question, you write "how do I access the loop index, from 1 to 5 in this case?"
However, the index for a list runs from zero.  So, then we need to know if what you actually want is the index and item for each item in a list, or whether you really want numbers starting from 1.  Fortunately, in Python, it is easy to do either or both.
First, to clarify, the enumerate function iteratively returns the index and corresponding item for each item in a list.
alist = [1, 2, 3, 4, 5]

for n, a in enumerate(alist):
    print("%d %d" % (n, a))

The output for the above is then,
0 1
1 2
2 3
3 4
4 5

Notice that the index runs from 0. This kind of indexing is common among modern programming languages including Python and C.
If you want your loop to span a part of the list, you can use the standard Python syntax for a part of the list. For example, to loop from the second item in a list up to but not including the last item, you could use
for n, a in enumerate(alist[1:-1]):
    print("%d %d" % (n, a))

Note that once again, the output index runs from 0,
0 2
1 3
2 4

That brings us to the start=n switch for enumerate().  This simply offsets the index, you can equivalently simply add a number to the index inside the loop.
for n, a in enumerate(alist, start=1):
    print("%d %d" % (n, a))

for which the output is
1 1
2 2
3 3
4 4
5 5

A: If there is no duplicate value in the list:
for i in ints:
    indx = ints.index(i)
    print(i, indx)

A: for i in range(len(ints)):
   print(i, ints[i]) # print updated to print() in Python 3.x+

A:
Using a for loop, how do I access the loop index, from 1 to 5 in this case?

Use enumerate to get the index with the element as you iterate:
for index, item in enumerate(items):
    print(index, item)

And note that Python's indexes start at zero, so you would get 0 to 4 with the above. If you want the count, 1 to 5, do this:
count = 0 # in case items is empty and you need it after the loop
for count, item in enumerate(items, start=1):
    print(count, item)

Unidiomatic control flow
What you are asking for is the Pythonic equivalent of the following, which is the algorithm most programmers of lower-level languages would use:

index = 0            # Python's indexing starts at zero
for item in items:   # Python's for loops are a "for each" loop
    print(index, item)
    index += 1

Or in languages that do not have a for-each loop:

index = 0
while index < len(items):
    print(index, items[index])
    index += 1

or sometimes more commonly (but unidiomatically) found in Python:

for index in range(len(items)):
    print(index, items[index])

Use the Enumerate Function
Python's enumerate function reduces the visual clutter by hiding the accounting for the indexes, and encapsulating the iterable into another iterable (an enumerate object) that yields a two-item tuple of the index and the item that the original iterable would provide. That looks like this:
for index, item in enumerate(items, start=0):   # default is zero
    print(index, item)

This code sample is fairly well the canonical example of the difference between code that is idiomatic of Python and code that is not. Idiomatic code is sophisticated (but not complicated) Python, written in the way that it was intended to be used. Idiomatic code is expected by the designers of the language, which means that usually this code is not just more readable, but also more efficient.
Getting a count
Even if you don't need indexes as you go, but you need a count of the iterations (sometimes desirable) you can start with 1 and the final number will be your count.
count = 0 # in case items is empty
for count, item in enumerate(items, start=1):   # default is zero
    print(item)

print('there were {0} items printed'.format(count))

The count seems to be more what you intend to ask for (as opposed to index) when you said you wanted from 1 to 5.

Breaking it down - a step by step explanation
To break these examples down, say we have a list of items that we want to iterate over with an index:
items = ['a', 'b', 'c', 'd', 'e']

Now we pass this iterable to enumerate, creating an enumerate object:
enumerate_object = enumerate(items) # the enumerate object

We can pull the first item out of this iterable that we would get in a loop with the next function:
iteration = next(enumerate_object) # first iteration from enumerate
print(iteration)

And we see we get a tuple of 0, the first index, and 'a', the first item:
(0, 'a')

we can use what is referred to as "sequence unpacking" to extract the elements from this two-tuple:
index, item = iteration
#   0,  'a' = (0, 'a') # essentially this.

and when we inspect index, we find it refers to the first index, 0, and item refers to the first item, 'a'.
>>> print(index)
0
>>> print(item)
a

Conclusion

*

*Python indexes start at zero

*To get these indexes from an iterable as you iterate over it, use the enumerate function

*Using enumerate in the idiomatic way (along with tuple unpacking) creates code that is more readable and maintainable:

So do this:
for index, item in enumerate(items, start=0):   # Python indexes start at zero
    print(index, item)

A: You can also try this:
data = ['itemA.ABC', 'itemB.defg', 'itemC.drug', 'itemD.ashok']
x = []
for (i, item) in enumerate(data):
      a = (i, str(item).split('.'))
      x.append(a)
for index, value in x:
     print(index, value)

The output is
0 ['itemA', 'ABC']
1 ['itemB', 'defg']
2 ['itemC', 'drug']
3 ['itemD', 'ashok']

A: It can be achieved with the following code:
xs = [8, 23, 45]
for x, n in zip(xs, range(1, len(xs)+1)):
    print("item #{} = {}".format(n, x))

Here, range(1, len(xs)+1); If you expect the output to start from 1 instead of 0, you need to start the range from 1 and add 1 to the total length estimated since python starts indexing the number from 0 by default.
Final Output:
item #1 = 8
item #2 = 23
item #3 = 45

A: This serves the purpose well enough:
list1 = [10, 'sumit', 43.21, 'kumar', '43', 'test', 3]
for x in list1:
    print('index:', list1.index(x), 'value:', x)

A: A loop with a "counter" variable set as an initialiser that will be a parameter, in formatting the string, as the item number.
The for loop accesses the "listos" variable which is the list. As we access the list by "i", "i" is formatted as the item price (or whatever it is).
listos = [8, 23, 45, 12, 78]
counter = 1
for i in listos:
    print('Item #{} = {}'.format(counter, i))
    counter += 1

Output:
Item #1 = 8
Item #2 = 23
Item #3 = 45
Item #4 = 12
Item #5 = 78


text:
Q: Is it possible to use IBM watson-intu and Choregraphe (Nao/Pepper) together I would like to know if it is possible to create behaviors (using the tablet and using motors) in Choregraphe for Pepper, and call them from intu?
Or is there a way to use native function of Naoqi in intu directly?
Thanks

A: You should write a Qi Service and run it on the robot. Qi Services (formerly ALModules) registered in NAOqi's Service Directory can be called remotely using libQi in a client (formerly ALProxy).
I don't know IBM Watson Intu, but if you can write a client using jointly libQi and Watson IBM Intu, I think you can easily bridge from one to the other.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Pass object from sub activity to main activity? From ActivityA I'm starting ActivityB.
In ActivityB I'm creating a new Serializable object.
After the object has been created I want to close ActivityB and pass the new object to ActivityA.
How can I do it?

A: start Activity B with startActivityForResult().
In activity B, when the object is created create an Intent to pack the object in:
Intent result = new Intent();
result.putExtra("result", object);
setResult(RESULT_OK, result);

Then you will receive that intent in the onActivityResult() method of Activity A, where you can extract it like so:
data.getSerializableExtra("result");

A: Start the Activity B using startActivityForResult method.
When you finish creating object call setResult in Activity B. Set Your Data in Intent. You don't need to finish this.
Override function onActivityResult in Activity A. This will be called when you call setResult in Activity B. You can receive the data from Intent passed from Activity B.
But most of the time, you need separate Activities if only you have different screens with different tasks. Otherwise accomplish the task within the same Activity. *(A Good and Standard Practice).*

A: after the object is created, create an intent object, put that object to that intent and then start activity A. In the Activity A's onRestart() get that intent and from that intent get that object.

A: Why are you doing that? If you're using activity B only for creating new object, you can do it in a plain simple java class. What are you trying to accomplish?


text:
Q: How to check which image is set in imageview android I have a star image in action bar. When I click on it, then the image should change to ON star. This is working fine. But how to know whether image is at ON state or OFF state.I want something that, if the image is at OFF mode and user taps on ON star, then it should set to ON star image. Initially, the image is set to OFF mode. So for this, I've wrote give line to turn on as user tap on it :
v.setBackgroundResource(android.R.drawable.star_big_on);

Guys pls suggest me for OFF mode if star image is already on. I am not getting any idea.

A: you can check it easily by setting tag of each image or by comparing there resource
comparision of resource method is shown below:
if (regProfile.getDrawable().getConstantState() ==
    getResources().getDrawable(R.drawable.ivpic).getConstantState()){
      Toast.makeText(_con, "Image is ivPic", Toast.LENGTH_LONG).show();
} else{
      Toast.makeText(_con, "Image isn't ivPic", Toast.LENGTH_LONG).show();
}

A: If my guess is correct you can achieve the functionality like this.change this code accordingly for image onclick
 private Button button;
 public static boolean isclick=false;
 button.setOnClickListener(seathtlistner);
 private View.OnClickListener seathtlistner = new View.OnClickListener() {
 public void onClick(View v) {
// TODO Auto-generated method stub
  if(isclick){
  button.setBackgroundResource(R.drawable.onstarimage);
}else{
  button.setBackgroundResource(R.drawable.offstarimage);
}
isclick=!isclick;
 }

A: You can use Tag property.
img_view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Boolean tag_isOn = (Boolean) v.getTag();

                tag_isOn = !tag_isOn;
                v.setBackgroundResource(tag_isOn ?android.R.drawable.star_big_on:android.R.drawable.star_big_off);

                v.setTag(tag_isOn);

            }
        });

A: if (img_like.getTag() != null && img_like.getTag().toString().equals("red")) {
                        img_like.setImageResource(R.drawable.heart);
                        img_like.setTag("heart");
                    } else {
                        img_like.setImageResource(R.drawable.red);
                        img_like.setTag("red");
                    }`enter code here`


text:
Q: How to properly iterate through this two dimensional javascript array? I have a sheet like this:

And I have this function:
    function getRangeAsArrays(sheet) {
  var dataRange = sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn());
  var data = dataRange.getValues();
  var array = [];
  for (var r=0; r<sheet.getLastColumn(); r++) {
  for (i in data) {
    var row = data[i];
    array.push(row);
       }
    }
  return array;
}

Which I use to build a listboxthis way:
   var recipientArray = getRangeAsArrays(activeSheet);
  var item3Panel = app.createHorizontalPanel();
  item3Panel.add(app.createLabel("recipient"));
  var listBox = app.createListBox().setName('item3');
  for(var i = 0; i < (recipientArray.length); i++){
  Logger.log("recipientArray[i][2] = " + recipientArray[i][3]);
  Logger.log(" i = " + i);
      listBox.addItem(recipientArray[i][4]);
    }
  item3Panel.add(listBox);

But when I iterate over the array length (4 rows), I got this (unexpected to me) result and the logs shows i variable goes until 14:

Since recipientArray.length should give me the first dimension of the 2 dimensional array and recipientArray[i].length the second dimension, and since I want the first dimension (number of rows) row to fix that? What is going wrong here?

A: Even if I'm still unsure that I understood what you need (I guess I'm a bit tired or I become stupid... go figure...:), I wonder why you try using separate functions since the value returned by range.getValues() is already an array... A 2D array but still an array.
If you want to create one listBox per row and add the following cells as items then a double loop like this will do the job. (tell me if I'm completely off the subject, thx).
I wrote an example code with the main structure and comments to explain where things go.
function test() {
  var dataRange = SpreadsheetApp.getActiveSheet().getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn());
  var data = dataRange.getValues();
  Logger.log(data)
  var array = [];  // this is useless
  for (var r=0; r<data.length; r++) {

    // create listBox widget here
    //var listBox = app.createListBox().setName('listBox'+r);
    for (i in data[0]) {
      var cell = data[r][i];

      //add items to listBox here
      // listBox.addItem(cell);
      array.push(cell);// this is useless
    }
  }
  Logger.log(array);//useless
  return array;//useless
}


text:
Q: Running external functions before schema.save method As far as I know Mongooses schema.save() method is Asynchronous is nature. Is it possible to run external functions before the schema.save() method in sequence so schema.save() doesn't get called until the external functions are done processing.
//External function
incrementTotal(req,res);

    newSurvey.save(function (err, data) {
        if(err) {
             sendJsonResponse(res, 400, err)
        } else{
            console.log("3")
             sendJsonResponse(res, 200, data);
        }
    });

The issue:
There are certain situations where newSurvey.save runs before incrementTotal can finish processing. How can I fix this issue?

A: You can save your things inside the incrementTotal callback. Libraries like Promises etc helps in these kind of problems.
incrementTotal(req,function(err,res){
  if(!err){
     newSurvey.save(function (err, data) {
       if(err) {
          sendJsonResponse(res, 400, err)
       } else{
         console.log("3")
         sendJsonResponse(res, 200, data);
       }
     });
  }else{
    console.log(err);
   }
});

A: If you use the async library you can make use of waterfall. It takes an array of functions which are executed in series, each passing their results to the next in the array. If any of the tasks pass an error to the callback, the next function is not executed, and the main callback is immediately called with the error.
async.waterfall([
  incrementTotal,
  mySaveFunction,
],
function (err, result) {
  if (err) {
    sendJsonResponse(res, 400, err)
  } else {
    console.log("3")
    sendJsonResponse(res, 200, data);
  }
});

function incrementTotal(callback) {
  callback(null, data);
}

function mySaveFunction(data, callback) {
  // 'data' is the result of incrementTotal
  // so this should be newSurvey.save
  callback(null, data);
}


text:
Q: Why can't I use newid() in a user-defined table-valued function? I recently found out that SQL Server 2005 doesn't allow the use of newid() within user-defined functions. Why is this?
I have an alternate solution that suits my needs, so I'm not looking for ways to get around this. I'm curious why the designers would make this decision.

A: SQL Server only allows deterministic functions to be used within user-defined functions. Since the value of NEWID() is not deterministic, it cannot be used. You will find the same thing is true with GETDATE() and any other non-deterministic function.
I'm not qualified to answer why they would make that decision. It annoys me as well but I'm sure the SQL team at MS are not slouches.
EDIT: It turns out that my knowledge about GETDATE() is out-of-date. As the commenter says, you can use GETDATE() within functions from SQL Server 2005 onward. However, you still cannot use NEWID(), which I believe has to do with the same non-determinism constraint.

A: Microsoft's NEWID() documentation does not explain, but I agree that the likely reason is related @Payload's comment on another answer:

NEWID() is a non Deterministic function, which after 2005 is allowed
  in UDF but, as NEWID changes some of the internal counters and values
  inside the database structure it is considered to have a 'side effect'
  and as UDF's are not allowed to have side effects it is not allowed in
  the UDF, the same goes for RAND() as each call to RAND changes the
  seed value in the inner workings of MSSQL and this again is considered
  a side effect. GETDATE()/GETUTCDATE() and the allowed lists of
  functions have no side effects, so are allowed.

For those willing to risk it, see @dio-phung's workaround suggested in another comment on that same answer:

@DavidSpillett: FYI you can get around the ban of newid() by reading
  from a view : CREATE VIEW vw_NewGuid AS SELECT NEWID() AS new_guid .
  Then in your UDF, you can do : SELECT new_guid FROM vw_NewGuid

Note @david-spillett's caution:

@Dio: I would be very wary of workarounds that involve conning the
  engine that something is deterministic when it in fact isn't. You are
  either using a bug that may be fixed later (perhaps it should detect
  that the column in the view is not deterministic and they'll fix that
  in SQL Sever {Nextversion}) or relying upon "undefined behaviour" that
  similarly isn't guaranteed to work the same in later versions (or even
  in your current version if other circumstances change in the query).

That workaround/trick is offered in several other answers.

A: I believe the answer is that NEWID() is a non-deterministic function - i.e. it has side effects. User defined functions are not allowed to have side effects.


text:
Q: Module not Defined When Simulating Using Modelsim So I've upgraded from Vivado 2015.4 to 2016.2. I use Vivado to compile the simulation files for the encrypted IPs. When I launch Modelsim 10.4, a new error appears:
sources_1/ip/output_buffer/sim/output_buffer.v(289): Module 'fifo_generator_v13_1_1' is not defined.

The first thing I noticed is that in my project flow, generated simulation files are now verilog which could be the source of my problems since I usually simulated VHDL.
First I compile the various libraries such as the fifo_generator library:
compile_simlib -simulator questa

Then I generate the simulation files:
import_files -norecurse -fileset sources_1 cgen/output_buffer/output_buffer.xci
upgrade_ip [get_ips output_buffer]
generate_target simulation [get_files output_buffer.xci]
export_simulation -simulator questa -of_objects [get_files output_buffer.xci]
exec echo exit | vsim -c -do top/top.srcs/sources_1/ip/output_buffer_sim/questa/compile.do -modelsimini modelsim.ini

My modelsim.ini file then maps these libraries:
[Library]

fifo_generator_v13_1_1 = msim/fifo_generator_v13_1_1
output_buffer = top/top.srcs/sources_1/ip/output_buffer/questa

Finally my .tcl script will build the project and add the simulation files:
vlog top/top.srcs/sources_1/ip/output_buffer/sim/output_buffer.v
Yet when I launch my project, it complains it cannot find the fifo_generator. Any ideas why this might be?
EDIT
As requested, the generated compile.do:
vlib work
vlib msim

vlib msim/xil_defaultlib
vlib msim/xpm
vlib msim/fifo_generator_v13_1_1

vmap xil_defaultlib msim/xil_defaultlib
vmap xpm msim/xpm
vmap fifo_generator_v13_1_1 msim/fifo_generator_v13_1_1

vlog -work xil_defaultlib -64 -sv \
"/software/CAD/Xilinx/2016.2/Vivado/2016.2/data/ip/xpm/xpm_memory/hdl/xpm_memory_base.sv" \
"/software/CAD/Xilinx/2016.2/Vivado/2016.2/data/ip/xpm/xpm_memory/hdl/xpm_memory_dpdistram.sv" \
"/software/CAD/Xilinx/2016.2/Vivado/2016.2/data/ip/xpm/xpm_memory/hdl/xpm_memory_dprom.sv" \
"/software/CAD/Xilinx/2016.2/Vivado/2016.2/data/ip/xpm/xpm_memory/hdl/xpm_memory_sdpram.sv" \
"/software/CAD/Xilinx/2016.2/Vivado/2016.2/data/ip/xpm/xpm_memory/hdl/xpm_memory_spram.sv" \
"/software/CAD/Xilinx/2016.2/Vivado/2016.2/data/ip/xpm/xpm_memory/hdl/xpm_memory_sprom.sv" \
"/software/CAD/Xilinx/2016.2/Vivado/2016.2/data/ip/xpm/xpm_memory/hdl/xpm_memory_tdpram.sv" \

vcom -work xpm -64 \
"/software/CAD/Xilinx/2016.2/Vivado/2016.2/data/ip/xpm/xpm_VCOMP.vhd" \

vlog -work fifo_generator_v13_1_1 -64 \
"../../output_buffer/fifo_generator_v13_1_1/simulation/fifo_generator_vlog_beh.v" \

vcom -work fifo_generator_v13_1_1 -64 \
"../../output_buffer/fifo_generator_v13_1_1/hdl/fifo_generator_v13_1_rfs.vhd" \

vlog -work fifo_generator_v13_1_1 -64 \
"../../output_buffer/fifo_generator_v13_1_1/hdl/fifo_generator_v13_1_rfs.v" \

vlog -work xil_defaultlib -64 \
"../../output_buffer/sim/output_buffer.v" \

vlog -work xil_defaultlib "glbl.v"

It copies the modelsim.ini file and then you can run one or all three of these commands. All I want to do actually is compile so I have the object which can be used by my simulation later, which is the output_buffer.v file which is created.
# RUN_STEP: <compile>
compile()
{
  # Compile design files
  source compile.do 2>&1 | tee -a compile.log

}

# RUN_STEP: <elaborate>
elaborate()
{
  source elaborate.do 2>&1 | tee -a elaborate.log
}

# RUN_STEP: <simulate>
simulate()
{
  vsim -64 -c -do "do {simulate.do}" -l simulate.log
}

# STEP: setup
setup()
{
  case $1 in
    "-lib_map_path" )
      if [[ ($2 == "") ]]; then
        echo -e "ERROR: Simulation library directory path not specified (type \"./output_buffer.sh -help\" for more information)\n"
        exit 1
      fi
     copy_setup_file $2
    ;;
    "-reset_run" )
      reset_run
      echo -e "INFO: Simulation run files deleted.\n"
      exit 0
    ;;
    "-noclean_files" )
      # do not remove previous data
    ;;
    * )
     copy_setup_file $2
  esac

  # Add any setup/initialization commands here:-

  # <user specific commands>

}

A: Module fifo_generator_v13_1_1 is compiled to fifo_generator_v13_1_1 library and I think that this could be a problem. Try add -L fifo_generator_v13_1_1 to your vsim command to search for modules in this library also.


text:
Q: Set Oval throwing error I am currently working on a project, I get this error Java.lang.NullPointerException, I undrestand that this error happen when you try to refer to a null object instance, but what I do not know, is how I can fix it.
This is my code:
public void paint(Graphics g) {
    g.setColor(Color.red);
    g.drawOval(150, 150, 10, 10);
}

/** Main Method **/
public static void main(String [] args) {
    Run run = new Run();
    run.paint(null);
}

Please help me with a solution and also explain it, so that I learn it. Many thanks in advance. Andre

A: You may not pass null to your paint method! Here is a small example how to do it:
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawOval (10, 10, 200, 200);
    }
}

public class DrawOval {
    public static void main(String[] a) {
        JFrame window = new JFrame();
        window.setBounds(30, 30, 300, 300);
        window.getContentPane().add(new MyCanvas());
        window.setVisible(true);
    }
}

A: You are not doing it the right way. In order to use graphics in java you need to build upon Swing/AWT components. Currently you are passing Graphics as null.
run.paint(null);

You need to implement this using JFrame and other swing components.

A: Since you are sending null to paint, Graphics g contains null (points to nowhere).
Then inside paint(...) you call setColor(...) on g, which is null. null.setColor(...) causes NullPointerException.

A: *

*You almost never call paint methods (including paintComponent) directly as this is what the JVM should be doing.

*Don't override the paint(Graphics g) method of a JComponent or JComponent derived class such as a JPanel if you can avoid it. This method, paint, is responsible for not only painting the component but also its borders and its child components, and if not done carefully, overriding this method will not infrequently result in unwanted side effects.

*Later when you want to do graphics animation, overriding paint(Graphics g) will result in jerky graphics since it does not do double buffering by default.

*By overriding the paintComponent(Graphics g) method instead you fix these issues.

*Don't forget to call the super's paintComponent(g) method in your override to erase any unwanted previously drawn images.

*Read the Swing Graphics tutorials, both the basic and advanced tutorials. Links at the bottom.

Better code:
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class MyBetterCanvas extends JComponent {

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      g.drawOval(10, 10, 200, 200);
   }

   public static void main(String[] a) {
      MyBetterCanvas canvas = new MyBetterCanvas();
      canvas.setPreferredSize(new Dimension(300, 300));
      JFrame window = new JFrame("My Better Canvas");
      window.getContentPane().add(canvas);
      window.setLocationByPlatform(true);
      window.pack();
      window.setVisible(true);
   }
}

Better Still:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RenderingHints;

import javax.swing.JComponent;
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class MyBetterStillCanvas extends JComponent {
   private static final int PREF_W = 500;
   private static final int PREF_H = 500;
   private static final int OVAL_X = 10;
   private static final int OVAL_Y = OVAL_X;
   private static final Paint BG_PAINT = new GradientPaint(0, 20,
         Color.black, 20, 0, Color.darkGray, true);

   private static final Paint FILL_PAINT = new GradientPaint(0, 0,
         Color.blue, 20, 20, Color.red, true);

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      // to smooth out graphics
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
      // let's draw something funky

      g2.setPaint(BG_PAINT);
      g2.fillRect(0, 0, getWidth(), getHeight());

      g2.setPaint(FILL_PAINT);
      // avoid use of "magic" numbers
      g.fillOval(OVAL_X, OVAL_Y, getWidth() - 2 * OVAL_X, getHeight() - 2
            * OVAL_Y);
   }

   // a cleaner way to set the preferred size of a component
   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   public static void main(String[] a) {
      JFrame window = new JFrame("My Better Canvas");
      window.getContentPane().add(new MyBetterStillCanvas());
      window.setLocationByPlatform(true);
      window.pack();
      window.setVisible(true);
   }
}

Which displays as:

Tutorials:

*

*Java Tutorials, Really Big Index

*Java Swing Tutorials

*Basic Swing Graphics Tutorial: Lesson: Performing Custom Painting

*More Advanced Graphics Article: Painting in AWT and Swing


text:
Q: Confirm if my entity is saved using doctrine After I persist and existing or a new entity using entity manager, How do I confirm whether this entity is saved?
$em->persist($entity);
$em->flush();

A: If your entity has an auto generated value column like id:
@ORM\GeneratedValue(strategy="AUTO")

you may check if the entity was saved by doing
if($entity->getId())


text:
Q: Divisibility of $a^p-r$ and $a^q-r$ by the primes $p,q$ Let $p, q$ be prime and $a$ some positive integer such that $a = pq + r$ where $r$ is the remainder. Show that $p \mid a^p – r$ and $q \mid a^q – r$.
Example: $p = 3$ and $q = 5$, $a = 17$ and $r = 17 – 3\cdot5 = 2$:
$$\begin{align*}\frac{17^5 – 2}5
                                     &= \frac{1419857 – 2}5\\
                               &      = 1419855/5\\
                     &                = 283971\end{align*}$$

A: Hint: Corollary to Euler's Theorem: For prime $p$ and integer $a$, $a^p\equiv a \pmod{p}$


text:
Q: Use mercurial "out of tree" I'm looking to use a repository from "out of tree", that is, the .hg directory is not located in a parent directory of the working directory.  As an example, consider that my repository root (.hg) is at ~/src/dotfiles. I wish to diff ~, as though the working copy was checked out at ~, but the .hg folder is actually at ~/src/dotfiles/.hg. The -R option doesn't allow this,
$ hg -R ~/src/dotfiles diff ~
abort: /Users/anacrolix not under root '/Users/anacrolix/src/dotfiles'

I'd prefer not to have .hg in ~, or use a symlink.

A: The .hg directory is always a sub-folder of the repository root and there is no way to change that.
Depending on the usage scenario behind your question you might want to look at some of the available repository hooks. You could use for instance the changegroup and / or commit hooks in order to run a script which updates another repository when new changes are added to your repository, e.g. for deployment purposes

A: See Mercurial Documentation for a reference of the first paragraph!


text:
Q: which web framework suit for build admin app? I'm a beginner Codeigniter(PHP) and Javascript programmer. I want to build an app for administration purpose that support desktop and mobile. I think I prefer to make a web. But I confuse about what framework to choose and which one is suit for this purpose. is meteor suit for this purpose?.

A: It completely depends on what Scenario you have, to create Admin App on web.
You can use below theme to make a Admin Panel.
To View live theme : Click Here
To Download the theme : Download Here
Now comming to the point, If you need a real time Web Application to create a Admin App in very less time, still secure, robust, much better than REST API, massive read-writes to DB, then Meteor 1.5.2 is really heaven (also keep in mind how complex is your database going to be, because Meteor comes with MongoDB inbuilt support and MongoDB does not support mapping constraints. You may use "Linking". Though Meteor now supports other databases like 'postgres' and 'mysql', you may need to study how to merge them.Click Here)

Also keep in mind how many concurrent users are going to use your application if built with meteor. If you that is huge number you might be interested in hosting your application to Cheap and yet powerful Virtual Private Server VPS

If you do not have a real time requirement then Meteor is overkill and not really required, definitely there are other frameworks available as in PHP you may use Yii2 PHP Framework which is very mature framework or you may use Laravel 5.x. Code Igniter is little Immature and lacks many advanced feature that can make application real secure and developed fast.
The reason to find why you may use Meteor : Click Here


text:
Q: Список в центре блока Помогите, пожалуйста, никак не могу установить список в центре блока. Я уже пробовал устанавливать text-align:center как для блока так и для списка и даже margin:0 auto для списка делал, но и это не помогает.
css:
#menu {
    width: 100 % ;
    height: 40px;
    text-align: center
}
ul.top - menu {
    margin: 0 auto;
    /*border:1px solid black*/
}
ul.top - menu li {
    width: 150px;
    height: 40px;
    line-height: 40px;
    float: left;
    /*border:1px solid black*/
}

html:

Главная

Общение

Файлы

Новости

Биография

A: Попробуй так:
Для текста- text-align:center !important;
Для блока - margin:0 auto !important;

!important - используется когда перекрывается каким то другим стилем.
А так смотри конфликт в firebug-e.
Посмотрел ваш код:
#menu{
    width: 100 % ;
    height: 40px;
    /*text-align: center - не нужно здесь */
}
/*убрал пробелы между top-menu */
#menu .top-menu{
    margin: 0 auto;
    /*border:1px solid black*/
}
/*либо*/
#menu ul{
    margin: 0 auto;
    padding: 0;
    /*border:1px solid black*/
}
#menu li{
    width: 150px;
    height: 40px;
    line-height: 40px;
    float: left;
    /*border:1px solid black*/
}

Вроде так. Не тестил.
A: Посмотрите, надеюсь поможет. Для родителя добавляем - text-align: center;, а для дочернего элемента - display: inline-block; и все работает.
Удачи.
A: Если вы используете такое свойство как margin: 0 auto; то обязательно указывайте ширину блока иначе как он выровнит.

ul.top - menu { margin: 0 auto;
/border:1px solid black/ }

здесь нужно указать его ширину и все. width: 980px; тогда он выровнит по центру


text:
Q: How to have a external config file in react app with vite bundler I am learning React and don't know the correct way to create config files. I want to have an external configuration file in my React-based project with Vite bundler. As I want to change the configurations according to my wish while using the app and the configuration file should not bundle with my app.
I have created a config.js file in a public folder that didn't work.


text:
Q: Batch insertion Cassandra How could i realize batch insertion in Cassandra to populate with data?

A: Use one of the clients here: http://wiki.apache.org/cassandra/ClientOptions
Exact syntax for batches depends on the language and client.


text:
Q: Wireless super slow - network adaptor RTL8723BE refuses to work I am trying to make my WiFi connection working on Ubuntu 16.04 (the same was happening with Ubuntu 14.04). I've already tried different solutions and reinstalled Ubuntu more than 5 times. Here are my results:
It seems that my network adapter RTL8723BE is giving problems to Ubuntu users for a very long time.
I followed the solution presented here https://askubuntu.com/a/543626/250716:
sudo -i
echo "options rtl8723be fwlps=0"  >  /etc/modprobe.d/rtl8723be.conf
modprobe -r rtl8723be
modprobe rtl8723be
exit

and my wifi started to work but it is now super slow (way faster on Windows).
I also tried this one:
echo "options rtl8723be ant_sel=2"  | sudo tee /etc/modprobe.d/rtl8723be.conf

Same thing, wifi works but super slow.
I tried installing new drivers as suggested by some solutions: Wifi problems with rtl8723be in Ubuntu 14.04
sudo apt-get install build-essential git
git clone https://github.com/lwfinger/rtlwifi_new/
cd rtlwifi_new
make
install
sudo make install

and I also tried these drivers:
sudo add-apt-repository ppa:hanipouspilot/rtlwifi
sudo apt-get update
sudo apt-get install rtlwifi-new-dkms linux-firmware

In both situations the wireless connection disappears from Ubuntu as you can see in the image below:
This image shows that I dont have wifi
I also have the PCIe bus error messages described here: PCIe bus error messages on boot and shutdown it seems that the network adaptor RTL8723BE is a real pain!!
My laptop is brand new HP Pavillon Gaming Notebook. I really need Ubuntu for my Work. All the help is welcome.
Information about my system:
joao
    description: Computer
    width: 64 bits
    capabilities: smbios-2.8 vsyscall32
  *-core
       description: Motherboard
       physical id: 0
     *-memory
          description: System memory
          physical id: 0
          size: 15GiB
     *-cpu
          product: Intel(R) Core(TM) i7-6700HQ CPU @ 2.60GHz
          vendor: Intel Corp.
          physical id: 1
          bus info: cpu@0
          size: 3276MHz
          capacity: 3500MHz
          width: 64 bits
          capabilities: fpu fpu_exception wp vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp x86-64 constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx rdseed adx smap clflushopt xsaveopt xsavec xgetbv1 dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp cpufreq
     *-pci
          description: Host bridge
          product: Sky Lake Host Bridge/DRAM Registers
          vendor: Intel Corporation
          physical id: 100
          bus info: pci@0000:00:00.0
          version: 07
          width: 32 bits
          clock: 33MHz
        *-pci:0
             description: PCI bridge
             product: Sky Lake PCIe Controller (x16)
             vendor: Intel Corporation
             physical id: 1
             bus info: pci@0000:00:01.0
             version: 07
             width: 32 bits
             clock: 33MHz
             capabilities: pci pm msi pciexpress normal_decode bus_master cap_list
             configuration: driver=pcieport
             resources: irq:122 ioport:5000(size=4096) memory:93000000-93ffffff ioport:80000000(size=301989888)
           *-display
                description: 3D controller
                product: GM107M [GeForce GTX 950M]
                vendor: NVIDIA Corporation
                physical id: 0
                bus info: pci@0000:01:00.0
                version: a2
                width: 64 bits
                clock: 33MHz
                capabilities: pm msi pciexpress bus_master cap_list
                configuration: driver=nouveau latency=0
                resources: irq:130 memory:93000000-93ffffff memory:80000000-8fffffff memory:90000000-91ffffff ioport:5000(size=128)
        *-display
             description: VGA compatible controller
             product: Intel Corporation
             vendor: Intel Corporation
             physical id: 2
             bus info: pci@0000:00:02.0
             version: 06
             width: 64 bits
             clock: 33MHz
             capabilities: pciexpress msi pm vga_controller bus_master cap_list rom
             configuration: driver=i915_bpo latency=0
             resources: irq:131 memory:92000000-92ffffff memory:a0000000-afffffff ioport:6000(size=64)
        *-generic:0
             description: Signal processing controller
             product: Intel Corporation
             vendor: Intel Corporation
             physical id: 4
             bus info: pci@0000:00:04.0
             version: 07
             width: 64 bits
             clock: 33MHz
             capabilities: msi pm bus_master cap_list
             configuration: driver=proc_thermal latency=0
             resources: irq:16 memory:94320000-94327fff
        *-usb
             description: USB controller
             product: Sunrise Point-H USB 3.0 xHCI Controller
             vendor: Intel Corporation
             physical id: 14
             bus info: pci@0000:00:14.0
             version: 31
             width: 64 bits
             clock: 33MHz
             capabilities: pm msi xhci bus_master cap_list
             configuration: driver=xhci_hcd latency=0
             resources: irq:126 memory:94300000-9430ffff
           *-usbhost:0
                product: xHCI Host Controller
                vendor: Linux 4.4.0-21-generic xhci-hcd
                physical id: 0
                bus info: usb@2
                logical name: usb2
                version: 4.04
                capabilities: usb-3.00
                configuration: driver=hub slots=8 speed=5000Mbit/s
           *-usbhost:1
                product: xHCI Host Controller
                vendor: Linux 4.4.0-21-generic xhci-hcd
                physical id: 1
                bus info: usb@1
                logical name: usb1
                version: 4.04
                capabilities: usb-2.00
                configuration: driver=hub slots=16 speed=480Mbit/s
              *-usb:0
                   description: Video
                   product: HP Truevision HD
                   vendor: Generic
                   physical id: 3
                   bus info: usb@1:3
                   version: 0.03
                   serial: DETGB01BI9E3L7
                   capabilities: usb-2.00
                   configuration: driver=uvcvideo maxpower=500mA speed=480Mbit/s
              *-usb:1
                   description: Bluetooth wireless interface
                   product: Bluetooth Radio
                   vendor: Realtek
                   physical id: 7
                   bus info: usb@1:7
                   version: 2.00
                   serial: 00e04c000001
                   capabilities: bluetooth usb-2.10
                   configuration: driver=btusb maxpower=500mA speed=12Mbit/s
        *-generic:1 UNCLAIMED
             description: Signal processing controller
             product: Sunrise Point-H Thermal subsystem
             vendor: Intel Corporation
             physical id: 14.2
             bus info: pci@0000:00:14.2
             version: 31
             width: 64 bits
             clock: 33MHz
             capabilities: pm msi bus_master cap_list
             configuration: latency=0
             resources: memory:94332000-94332fff
        *-communication
             description: Communication controller
             product: Sunrise Point-H CSME HECI #1
             vendor: Intel Corporation
             physical id: 16
             bus info: pci@0000:00:16.0
             version: 31
             width: 64 bits
             clock: 33MHz
             capabilities: pm msi bus_master cap_list
             configuration: driver=mei_me latency=0
             resources: irq:132 memory:94333000-94333fff
        *-storage
             description: SATA controller
             product: Sunrise Point-H SATA Controller [AHCI mode]
             vendor: Intel Corporation
             physical id: 17
             bus info: pci@0000:00:17.0
             version: 31
             width: 32 bits
             clock: 66MHz
             capabilities: storage msi pm ahci_1.0 bus_master cap_list
             configuration: driver=ahci latency=0
             resources: irq:128 memory:94330000-94331fff memory:94336000-943360ff ioport:6080(size=8) ioport:6088(size=4) ioport:6060(size=32) memory:94334000-943347ff
        *-pci:1
             description: PCI bridge
             product: Sunrise Point-H PCI Express Root Port #5
             vendor: Intel Corporation
             physical id: 1c
             bus info: pci@0000:00:1c.0
             version: f1
             width: 32 bits
             clock: 33MHz
             capabilities: pci pciexpress msi pm normal_decode bus_master cap_list
             configuration: driver=pcieport
             resources: irq:123 ioport:7000(size=4096) memory:94200000-942fffff ioport:7c900000(size=2097152)
           *-generic
                description: Unassigned class
                product: Realtek Semiconductor Co., Ltd.
                vendor: Realtek Semiconductor Co., Ltd.
                physical id: 0
                bus info: pci@0000:07:00.0
                version: 01
                width: 32 bits
                clock: 33MHz
                capabilities: pm msi pciexpress bus_master cap_list
                configuration: driver=rtsx_pci latency=0
                resources: irq:127 memory:94200000-94200fff
        *-pci:2
             description: PCI bridge
             product: Sunrise Point-H PCI Express Root Port #6
             vendor: Intel Corporation
             physical id: 1c.5
             bus info: pci@0000:00:1c.5
             version: f1
             width: 32 bits
             clock: 33MHz
             capabilities: pci pciexpress msi pm normal_decode bus_master cap_list
             configuration: driver=pcieport
             resources: irq:124 ioport:4000(size=4096) memory:94100000-941fffff
           *-network
                description: Wireless interface
                product: RTL8723BE PCIe Wireless Network Adapter
                vendor: Realtek Semiconductor Co., Ltd.
                physical id: 0
                bus info: pci@0000:08:00.0
                logical name: wlo1
                version: 00
                serial: 18:4f:32:a1:aa:03
                width: 64 bits
                clock: 33MHz
                capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
                configuration: broadcast=yes driver=rtl8723be driverversion=4.4.0-21-generic firmware=N/A ip=192.168.1.4 latency=0 link=yes multicast=yes wireless=IEEE 802.11bgn
                resources: irq:17 ioport:4000(size=256) memory:94100000-94103fff
        *-pci:3
             description: PCI bridge
             product: Sunrise Point-H PCI Express Root Port #7
             vendor: Intel Corporation
             physical id: 1c.6
             bus info: pci@0000:00:1c.6
             version: f1
             width: 32 bits
             clock: 33MHz
             capabilities: pci pciexpress msi pm normal_decode bus_master cap_list
             configuration: driver=pcieport
             resources: irq:125 ioport:3000(size=4096) memory:94000000-940fffff
           *-network
                description: Ethernet interface
                product: RTL8101/2/6E PCI Express Fast/Gigabit Ethernet controller
                vendor: Realtek Semiconductor Co., Ltd.
                physical id: 0
                bus info: pci@0000:09:00.0
                logical name: eno1
                version: 0a
                serial: b0:5a:da:d5:2e:33
                size: 100Mbit/s
                capacity: 100Mbit/s
                width: 64 bits
                clock: 33MHz
                capabilities: pm msi pciexpress msix bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd autonegotiation
                configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=full firmware=rtl8107e-2_0.0.2 02/26/15 ip=192.168.1.6 latency=0 link=yes multicast=yes port=MII speed=100Mbit/s
                resources: irq:129 ioport:3000(size=256) memory:94004000-94004fff memory:94000000-94003fff
        *-isa
             description: ISA bridge
             product: Sunrise Point-H LPC Controller
             vendor: Intel Corporation
             physical id: 1f
             bus info: pci@0000:00:1f.0
             version: 31
             width: 32 bits
             clock: 33MHz
             capabilities: isa bus_master
             configuration: latency=0
        *-memory UNCLAIMED
             description: Memory controller
             product: Sunrise Point-H PMC
             vendor: Intel Corporation
             physical id: 1f.2
             bus info: pci@0000:00:1f.2
             version: 31
             width: 32 bits
             clock: 33MHz (30.3ns)
             capabilities: bus_master
             configuration: latency=0
             resources: memory:9432c000-9432ffff
        *-multimedia
             description: Audio device
             product: Sunrise Point-H HD Audio
             vendor: Intel Corporation
             physical id: 1f.3
             bus info: pci@0000:00:1f.3
             version: 31
             width: 64 bits
             clock: 33MHz
             capabilities: pm msi bus_master cap_list
             configuration: driver=snd_hda_intel latency=32
             resources: irq:133 memory:94328000-9432bfff memory:94310000-9431ffff
        *-serial UNCLAIMED
             description: SMBus
             product: Sunrise Point-H SMBus
             vendor: Intel Corporation
             physical id: 1f.4
             bus info: pci@0000:00:1f.4
             version: 31
             width: 64 bits
             clock: 33MHz
             configuration: latency=0
             resources: memory:94335000-943350ff ioport:6040(size=32)
     *-scsi:0
          physical id: 2
          logical name: scsi0
          capabilities: emulated
        *-disk
             description: ATA Disk
             product: SAMSUNG MZNLF128
             physical id: 0.0.0
             bus info: scsi@0:0.0.0
             logical name: /dev/sda
             version: 1H1Q
             serial: S2HUNXAG836074
             size: 119GiB (128GB)
             capabilities: gpt-1.00 partitioned partitioned:gpt
             configuration: ansiversion=5 guid=8130209d-cb2b-4427-a2cb-5f1be6d0fd2c logicalsectorsize=512 sectorsize=512
           *-volume:0
                description: Windows FAT volume
                vendor: MSDOS5.0
                physical id: 1
                bus info: scsi@0:0.0.0,1
                logical name: /dev/sda1
                logical name: /boot/efi
                version: FAT32
                serial: 9e5f-9cd1
                size: 255MiB
                capacity: 259MiB
                capabilities: boot precious readonly hidden nomount fat initialized
                configuration: FATs=2 filesystem=fat label=SYSTEM mount.fstype=vfat mount.options=rw,relatime,fmask=0077,dmask=0077,codepage=437,iocharset=iso8859-1,shortname=mixed,errors=remount-ro name=EFI system partition state=mounted
           *-volume:1
                description: reserved partition
                vendor: Windows
                physical id: 2
                bus info: scsi@0:0.0.0,2
                logical name: /dev/sda2
                serial: 31c5ba9e-05bb-4f66-810c-39eea4a14bb1
                capacity: 127MiB
                capabilities: nofs precious readonly hidden nomount
                configuration: name=Microsoft reserved partition
           *-volume:2
                description: Windows NTFS volume
                vendor: Windows
                physical id: 3
                bus info: scsi@0:0.0.0,3
                logical name: /dev/sda3
                version: 3.1
                serial: 30009556-0524-644e-a3dd-921bbc262c96
                size: 118GiB
                capacity: 118GiB
                capabilities: ntfs initialized
                configuration: clustersize=4096 created=2015-08-29 08:34:46 filesystem=ntfs label=Windows name=Basic data partition state=clean
           *-volume:3
                description: Windows NTFS volume
                vendor: Windows
                physical id: 4
                bus info: scsi@0:0.0.0,4
                logical name: /dev/sda4
                version: 3.1
                serial: a4f8-c088
                size: 840MiB
                capacity: 862MiB
                capabilities: boot precious readonly hidden nomount ntfs initialized
                configuration: clustersize=4096 created=2016-01-10 03:42:47 filesystem=ntfs modified_by_chkdsk=true mounted_on_nt4=true resize_log_file=true state=dirty upgrade_on_mount=true
     *-scsi:1
          physical id: 3
          logical name: scsi2
          capabilities: emulated
        *-disk
             description: ATA Disk
             product: HGST HTS541010A9
             physical id: 0.0.0
             bus info: scsi@2:0.0.0
             logical name: /dev/sdb
             version: A710
             serial: JA1080SB0SVK2P
             size: 931GiB (1TB)
             capabilities: gpt-1.00 partitioned partitioned:gpt
             configuration: ansiversion=5 guid=fd09d250-f1ab-463f-8b9d-90a9bcc9c61f logicalsectorsize=512 sectorsize=4096
           *-volume:0
                description: Windows NTFS volume
                vendor: Windows
                physical id: 1
                bus info: scsi@2:0.0.0,1
                logical name: /dev/sdb1
                version: 3.1
                serial: 4efe49d7-60b5-c24b-979a-40bab471e293
                size: 279GiB
                capacity: 279GiB
                capabilities: ntfs initialized
                configuration: clustersize=4096 created=2015-10-01 11:18:29 filesystem=ntfs label=DATA name=Basic data partition state=clean
           *-volume:1
                description: Windows NTFS volume
                vendor: Windows
                physical id: 2
                bus info: scsi@2:0.0.0,2
                logical name: /dev/sdb2
                version: 3.1
                serial: cabde1a0-c9ea-9e44-b1ef-4f11e8bb9d28
                size: 16GiB
                capacity: 16GiB
                capabilities: boot precious readonly hidden nomount ntfs initialized
                configuration: clustersize=4096 created=2015-10-01 11:18:34 filesystem=ntfs label=RECOVERY modified_by_chkdsk=true mounted_on_nt4=true name=Basic data partition resize_log_file=true state=dirty upgrade_on_mount=true
           *-volume:2
                description: Windows FAT volume
                vendor: mkfs.fat
                physical id: 3
                bus info: scsi@2:0.0.0,3
                logical name: /dev/sdb3
                version: FAT32
                serial: c1d2-04f6
                size: 487MiB
                capacity: 511MiB
                capabilities: boot fat initialized
                configuration: FATs=2 filesystem=fat name=EFI System Partition
           *-volume:3
                description: EXT4 volume
                vendor: Linux
                physical id: 4
                bus info: scsi@2:0.0.0,4
                logical name: /dev/sdb4
                logical name: /
                version: 1.0
                serial: 41c00ae8-a35f-499e-8eb4-6f57e27e621b
                size: 619GiB
                capabilities: journaled extended_attributes large_files huge_files dir_nlink recover extents ext4 ext2 initialized
                configuration: created=2016-05-03 11:23:25 filesystem=ext4 lastmountpoint=/ modified=2016-05-04 20:34:38 mount.fstype=ext4 mount.options=rw,relatime,errors=remount-ro,data=ordered mounted=2016-05-04 20:34:42 state=mounted
           *-volume:4
                description: Linux swap volume
                vendor: Linux
                physical id: 5
                bus info: scsi@2:0.0.0,5
                logical name: /dev/sdb5
                version: 1
                serial: 13ad6819-9463-464c-860a-704b4f929050
                size: 15GiB
                capacity: 15GiB
                capabilities: nofs swap initialized
                configuration: filesystem=swap pagesize=4095
     *-scsi:2
          physical id: 4
          logical name: scsi3
          capabilities: emulated
        *-cdrom
             description: DVD-RAM writer
             product: DVDRW  SU208GB
             vendor: hp
             physical id: 0.0.0
             bus info: scsi@3:0.0.0
             logical name: /dev/cdrom
             logical name: /dev/cdrw
             logical name: /dev/dvd
             logical name: /dev/dvdrw
             logical name: /dev/sr0
             version: HH00
             capabilities: removable audio cd-r cd-rw dvd dvd-r dvd-ram
             configuration: ansiversion=5 status=nodisc

And here's my ridiculous experience with HP support:
08:45 Support session established with Pauline.
08:45 Pauline: Welcome to HP Chat Support. My name is Pauline and I will be your technical support specialist today.  Please allow me a few minutes while I review your information.
Meanwhile I request you to provide us with  your  Phone number and operating system so that we can update it in our records.
08:46 João Abrantes: phone number: +44 xxxxx
08:46 João Abrantes: OS: Windows and Ubuntu (dual boot)
08:48 Pauline: Thank you for your patience.
08:49 Pauline: Joao unfortunately at HP we do not support dual boot OS as we do not have much expertise over the same. However please contact Ubuntu so that they can help you further. If further support is required from HP you will need to reinstall the original operating system back on the PC and we will be able to help you further.
08:50 João Abrantes: I have the original OS installed
08:52 João Abrantes: Ubuntu is used by millions of users. If your hardware and customer service don't support such widely used Software you will lose all these clients..
08:52 Pauline: I am sorry however as I said we do not have much expertise over the same and hence kindly contact Ubuntu for the same.
08:54 João Abrantes: Ubutnu is not a company, they gave me their software for free. I paid you more than a thousand euros and all I get is incompatible hardware and no support.
08:54 João Abrantes: Is it possible to replace my laptop or my network adaptor? I still have warranty
08:55 Pauline: If the Pc is still under a month, you can approach the place of purchase to get it replaced.
08:55 João Abrantes: It's not under a month
08:55 João Abrantes: it's under 2 years which is my warranty period
08:56 Pauline: Joao unfortunately we cannot replace the PC if the time of purchase is more than a month.
08:56 João Abrantes: Not even my incompatible network adaptor?
08:57 Pauline: You will need to contact the place of purchase and check with their return and replacement policy.
08:58 João Abrantes: Ok this is useless. I am going to share this conversation in the Ubuntu forums. At least I can save time and money to other users by making them avoid buying HP incompatible hardware.
09:00 Pauline: I am sorry about the inconvenience caused, however please understand we do not have the expertise or required tools to help with another operating system issue.
09:00 João Abrantes: The network adaptor also causes problems on windows
09:00 João Abrantes: I can't start an hotspot
09:05 Pauline: Joao as I said if you will need to reinstall the original operating system on the Pc for us to troubleshoot. as in the original operating system, should be the only operating system on the PC.
09:06 João Abrantes: Windows is my original OS!
09:06 João Abrantes: and it is installed
09:07 Pauline: Joao I understand but currently there is a dual Os in the Pc and hence I will not be able to troubleshoot the same.
09:07 Pauline: Please run a recovery on the PC and get back to us with only the windows image loaded
09:07 Pauline: we will be able to help you with the same.

A: This solution was obtained from collaborative effort with the question poster.
Step 1. Disable secure boot from BIOS.
 (new modules will be added to the kernel)
Step 2. Add repository for the driver and install it.
sudo add-apt-repository ppa:hanipouspilot/rtlwifi
sudo apt-get update
sudo apt-get install rtlwifi-new-dkms linux-firmware
Your wifi-adapter should be working now (though maybe having weak signal).
Step 3. Edit the configuration file for the new driver for specific antenna selection and power management,
--First make a backup.
sudo cp /etc/modprobe.d/rtl8723be.conf   /etc/modprobe.d/rtl8723be.old.conf
then,
echo "options rtl8723be fwlps=0 ips=0 ant_sel=2" | sudo tee /etc/modprobe.d/rtl8723be.conf
Step 4. reboot
Your wifi-adapter should be working better now. It is suggested to test wireless connection under load for some time. User may test with ant_sel=1  or removing this parameter to ascertain best working condition.
More information: With kernel update, no additional configuration is needed since linux-firmware is also installed.
Refering solutions : Another issue with rtl8723be


text:
Q: Split line at point doesn't split lines less than 30 meters I have a bunch of lines in line layer that should be split at midpoint.
I tried to use both Feature Vertices to Points and Feature to Point to get a new layer with point at the middle of lines. I even used topology check to fit points and lines at coordinate grid.

Eventually lines that have a length more than 25-30 meters are split while others are not! And I need to split all the lines in layer.

On a picture above you can see that two last lines at right are not split.
I also tried to use different projections but it didn't help.
Is there any solution or this is a bug of a tool whcih cannot split lines with length that is less than 30 meters?
UPDATE
Found out that export lines to shapefile gives positive result, i.e. lines can be split in that way.
But I try to use only GDB file format so that and the final result of this operation will be presented in ModelBuilder.


text:
Q: Why would a report work in Pentaho Report Designer but not in BI Server I am building a report via Pentaho's Report designer.
I have a code/value table that provides values for a parameter used in the report. The value is shown in the dropdown, while the corresponding code is used as the filter in the backend sql query used to run the report.
In report designer, it runs perfectly.  When a value is selected, the SQL statement is executed with the code in place, and the report runs.
However, when I deploy the report into BI Server and attempt to run the report using the parameter, all values in the parameter show "bad value".
I have found no guidance on this, and was hoping someone might have seen this before and knows what to do.
Thank you very much.

A: When you define the parameter for your report please uncheck the radio button of validate parameter and then again publish it to BI server. sometimes validating parameter causes problem in BI server.
I hope this will help for you.


text:
Q: PHP Convert separate day,month and year to date I looked in many threads regarding this issue but still can't get to the bottom of this one. Here is my code:
$birthdate_ts = strtotime("$year-$num_month-$day");
$birthdate = date("d/m/Y",$birthdate_ts);

Where $day $num_month and $year are numbers (example 1 10 1990).
The result I'm getting is 1/1/1970 every time. I also tried different variations for the "strtotime()" input and still nothing.
Where am I wrong?

A: Your parse format is "d/m/y" and your format you are creating is "Y-m-d".  They need to match.  Try this:
$birthdate_ts=strtotime("$year-$num_month-$day");
$birthdate=date("Y-m-d",$birthdate_ts);


text:
Q: Find difference in two python dataframes based on specific columns I want to compare the dataframes based on the S/N and Metric column to find the values that changed from the most recent value in df2:
df1
#    S/N   Age  Metric
# 0  001  2.59    1.01
# 1  002  3.57    2.42
# 2  003  3.99    3.12

df2
#    S/N   Age  Metric
# 0  001  2.46    4.29
# 1  001  2.50    2.46
# 2  001  2.54    2.47
# 3  002  1.78    1.24
# 4  002  1.82    2.42
# 5  003  3.57    1.91
# 6  003  3.61    2.47
# 7  003  3.65    1.24

I am looking for the following dataframe:
   S/N   Age  Metric
0  001  2.59    1.01
2  003  3.99    3.12

Data
df1 = pd.DataFrame({
    "S/N": ['001', '002', '003'],
    "Age": [2.59, 3.57, 3.99],
    "Metric": [1.01, 2.42, 3.12]
})

df2 = pd.DataFrame({
    "S/N": ['001','001','001', '002','002', '003', '003', '003'],
    "Age": [2.46, 2.50, 2.54, 1.78, 1.82, 3.57, 3.61, 3.65],
    "Metric": [4.29, 2.46, 2.47, 1.24, 2.42, 1.91, 2.47, 1.24]
})

A: There are roughly two steps involved here. First you need to compare df1 and df2, and based on that comparison you want to filter your data.
Step 1: Comparing
To compare df1 with df2 according to column Metric, you run:
df1['Metric'] != df2['Metric']
0    True
1    False
2    True
3    False

Step 2: Filtering
In pandas, you can filter rows with a pandas Series ("single column dataframe") that contains only True or False values:
inds = df1['Metric'] != df2['Metric']
df2.loc[inds, :]
     S/N   Age  Metric
# 0  001  2.46    4.29
# 2  003  2.00    2.47


text:
Q: How to scale pattern image smoothly in HTML5 canvas? I am using setTransform to scale my background pattern image. The scale starts from 1, and every time the scale decreases 0.01, until it reaches 0.5.
So here is the scaling code:
context.setTransform(scale, 0, 0, scale, position.x, position.y);

In the update:
scale -= 0.01;

Using the above code, when I animate the changes the background pattern image is replaced with the scaled pattern image correctly. However the transition isn't very smooth. It works like the image suddenly flashed to another image in a short time but noticeable. I want the replacement to be smoother and unnoticeable but I have no idea how to achieve that effect.

A: You can use translate() instead of setTransform()

ctx.translate(pt.x,pt.y);
ctx.scale(factor,factor);
ctx.translate(-pt.x,-pt.y);

In short, you want to translate() the canvas context by your offset,
  scale() it to zoom in or out, and then translate() back by the
  opposite of the mouse offset. Note that you need to transform the
  cursor position from screen space into the transformed canvas context.

Check this question for more information and live examples.

A: You can use setTransform
The first two numbers are the direction and length (scale) of the x axis, the next two are the direction and length of the y axis and the last two are the location of the origin.
The quickest way to set translation, scale, and rotation
var scale = ?
var originX = ?
var originY = ?
var rotation = ?
ctx.setTransform(scale,0,0,scale,originX,originY);
ctx.rotate(rotation);

or you can set the rotation in the setTransform by calculating the axis directions
var scale = ?
var originX = ?
var originY = ?
var rotation = ?
// get the x axis direction and length
var xdx = Math.cos(rotation) * scale;
var xdy = Math.sin(rotation) * scale;
// if you are not skewing then the y axis is at 90deg so x is neg y and y is x
ctx.setTransform(xdx,xdy,-xdy,xdx,originX,originY);

Then if you need to restore to the default transform
ctx.setTransform(1,0,0,1,0,0); // restore default transform

All the values for setTransform are in pixels and set transform basically describes where and what shape the renderer will create the pixel at 0,0
Smoothing out the pan and zoom.
This answer goes into more depth and gives a working example of using the mouse to scale and zoom a image using the mouse via setTransform (no need to use save restore) It also shows how to smooth the zoom and pan Pan and Zoom


text:
Q: CSS boxes has arrows except one I am creating a messaging system where one user speaks to the other. I have created message boxes with the arrows. So far all the boxes has arrows except one (see pics below). Also the height is not auto adjusting to the content. Can someone take a look at my code to see what is going on?

HTML

Friday 12:34

12:47

            Hey there!

            I noticed that not only are you a football fan
            but you also go to a lot of games! What do you think about the upcoming season and who is your favorite team? Looks to me like you are a Pats fan!

Saturday 22:40

12:47

            Wow! That's awesome. I love football and im a beat writer for the Pats & have the luxury of catching their games!

            What about you? Are you a Pats fan yourself?

12:47

                Oh yeah! Brady with the SB win again this year!

12:47

            Thats pretty cool! No idea how much of a Pats fan you were to already have season tix! I dont even have them yet!

CSS
.live-chat-feed {
    margin-left: 50%;
    margin-top: -310%;
    background-color: #000;

}

.new-live-chat {
    margin-top: 20%;
}

.chat-avatar {
    position: relative;
    left: -30%;
    top: 85px;
}

.chat-date,
.chat-content,
.time-posted {
     color: #8785ab;
}

.chat-date {
    position: relative;
    left: 30%;
}

.single-post-box {
    width: 729.9px;
    height: auto;
    border-radius: 2px;
    background-color: #ffffff;
    box-shadow: 0 2px 4px 0 rgba(167, 169, 197, 0.55);
    margin-bottom: 10%;
    padding: 20px;
}

#current-user .single-post-box {
    position: relative;
    left: -15%;
    border-radius: 2px;
    background-color: #1ac384;
    box-shadow: 0 2px 4px 0 rgba(167, 169, 197, 0.55);

}

.single-post-box::after {

    content: '';
    height: 0;
    position: absolute;
    width: 0;
    border: 10px solid transparent;
    border-right-color: #fff;
    right: 97.5%;
    top: 115px;

}

#current-user .single-post-box::after {

    content: '';
    height: 0;
    position: absolute;
    width: 0;
    border: 10px solid transparent;
    border-left-color: #1ac384;
    left: 100%;
    top: 0px;

}

A: I always use height: inherit; for height property. It will create a box containing the the text without any free space at the bottom. So if you have like text of 3 rows it will create a height like 20% or something, if you have 6 rows, it will create height of 40%, etc. Hope that helps.


text:
Q: Installing pybloomfiltermmap version 0.3.14 via pip I'm trying to install pybloomfiltermmap version 0.3.14 via pip
(it is on a virtual machine ubuntu 16.04)
sudo pip install pybloomfiltermmap==0.3.14

But I get an error and I don't know why or how to fix it:
rptk99@ubuntu:~/w3af$ sudo pip install pybloomfiltermmap==0.3.14
The directory '/home/rptk99/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/rptk99/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting pybloomfiltermmap==0.3.14
  Downloading pybloomfiltermmap-0.3.14.tar.gz (446kB)
100% |████████████████████████████████| 450kB 313kB/s
Installing collected packages: pybloomfiltermmap
  Running setup.py install for pybloomfiltermmap ... error
Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-VUo2JI/pybloomfiltermmap/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-uyHOdy-record/install-record.txt --single-version-externally-managed --compile:
info: Building from C
running install
running build
running build_ext
building 'pybloomfilter' extension
creating build
creating build/temp.linux-x86_64-2.7
creating build/temp.linux-x86_64-2.7/src
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c src/mmapbitarray.c -o build/temp.linux-x86_64-2.7/src/mmapbitarray.o
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c src/bloomfilter.c -o build/temp.linux-x86_64-2.7/src/bloomfilter.o
src/bloomfilter.c:11:14: warning: always_inline function might not be inlinable [-Wattributes]
 BloomFilter *bloomfilter_Create_Malloc(size_t max_num_elem, double error_rate,
              ^
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c src/md5.c -o build/temp.linux-x86_64-2.7/src/md5.o
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c src/primetester.c -o build/temp.linux-x86_64-2.7/src/primetester.o
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c src/MurmurHash3.cpp -o build/temp.linux-x86_64-2.7/src/MurmurHash3.o
cc1plus: warning: command line option '-Wstrict-prototypes' is valid for C/ObjC but not for C++
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c src/pybloomfilter.c -o build/temp.linux-x86_64-2.7/src/pybloomfilter.o
In file included from src/pybloomfilter.c:348:0:
/usr/include/python2.7/pythread.h:5:1: warning: 'always_inline' attribute ignored [-Wattributes]
 typedef void *PyThread_type_lock;
 ^
src/pybloomfilter.c:828:1: warning: function declaration isn't a prototype [-Wstrict-prototypes]
 __PYX_EXTERN_C DL_IMPORT(int) errno;
 ^
creating build/lib.linux-x86_64-2.7
c++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wl,-Bsymbolic-functions -Wl,-z,relro -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/src/mmapbitarray.o build/temp.linux-x86_64-2.7/src/bloomfilter.o build/temp.linux-x86_64-2.7/src/md5.o build/temp.linux-x86_64-2.7/src/primetester.o build/temp.linux-x86_64-2.7/src/MurmurHash3.o build/temp.linux-x86_64-2.7/src/pybloomfilter.o -lcrypto -o build/lib.linux-x86_64-2.7/pybloomfilter.so
/usr/bin/ld: cannot find -lcrypto
collect2: error: ld returned 1 exit status
error: command 'c++' failed with exit status 1

----------------------------------------
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-VUo2JI/pybloomfiltermmap/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-uyHOdy-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-VUo2JI/pybloomfiltermmap/
rptk99@ubuntu:~/w3af$

How do I fix this problem?

A: /usr/bin/ld: cannot find -lcrypto

-lcrypto means libcrypto.so
Solution:
sudo apt-get install libssl-dev

A: Install pybloomfiltermmap 0.3.14-0.1 using this .deb package on Launchpad.
or
sudo apt-get install build-essential libssl-dev libffi-dev python-dev
pip install pybloomfiltermmap


text:
Q: How to save the result to self in Python? I'm have the following piece of code:
def merge(self, list2):
   from heapq import merge
   self = list(merge(self, list2))
   return self

My intention is to return the output of the merge to the self argument. The above code doen't work. Is it possible to do this or am I trying to do something stupid?
Thanks.
Edit:
This is part of this class:
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)

Here's how I call this:
list1 = MyList[0, 1, 2, 3]
list1.merge([1, 2, 3, 4])

I am trying to save the result to list1 itself.
list1
[0, 1, 2, 3, 1, 2, 3, 4]

A: Assigning to self doesn't make a lot of sense. You are changing the class type.
What you probably want is something like: self.copyfrom(list(merge(self, list2))
That being said and given python's flexibility you will likely be able to get that code to work, but it will be very confusing to use and maintain.

A: Couldn't use a loop and the lists append class?
def merge(self, list2):
    for k in list2:
        self.append(k)

    return self


text:
Q: MD5 results are different between DigestUtils and MessageDigest I have tried to use java.security.MessageDigest or org.apache.commons.codec.digest.DigestUtils to do md5, but there comes out different results.
The sample code as below:
public static void main( String[] args )
{
    System.out.println("MessageDigest: " +  MD5("12345") );

    MessageDigest md5Digest = DigestUtils.getMd5Digest();
    System.out.println("MD5Hex with digest: " + DigestUtils.md5Hex(md5Digest.digest("12345".getBytes())));

    System.out.println("MD5Hex: " + DigestUtils.md5Hex("12345"));
}

public final static String MD5(String s) {
    char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

    try {
        byte[] btInput = s.getBytes();
        // 獲得MD5摘要算法的 MessageDigest 對象
        MessageDigest mdInst = MessageDigest.getInstance("MD5");
        // 使用指定的字節更新摘要
        mdInst.update(btInput);
        // 獲得密文
        byte[] md = mdInst.digest();
        // 把密文轉換成十六進制的字符串形式
        int j = md.length;
        char str[] = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {
            byte byte0 = md[i];

            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        System.out.println();
        return new String(str);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

The results as below:
MessageDigest: 827CCB0EEA8A706C4C34A16891F84E7B
MD5Hex with digest: aad43635bbd353cef6ea6546093fa0c7
MD5Hex: 827ccb0eea8a706c4c34a16891f84e7b

If I have give md5Digest.digest() into DigestUtils.md5Hex, the result is different from MessageDigest. But if I just do md5Hex(), it will be the same. What's the different between this two way?
Thanks

A: When you are calling DigestUtils.md5Hex(md5Digest.digest("12345".getBytes()))), you actually calculate the MD5 of the result of the previous MD5 calculation. Thus no wonder that double-MD5 differs from single MD5.


text:
Q: How to convert raw image into signed 32 bit I have a file created with dd command (raw file). I opened it with bless as shown in the image below:

Now I would like to extract the data from this file and get what appears under Signed 32 bit (If you see the image 84 is the number I want). Therefore, I want to convert the following string in this way:
10 00 00 00 --> 84
54 00 00 00 --> 70185301

In order to do this conversion I built the following program which opens the file, decode the line and write the result in a new file.
Here is the piece of code that does the extraction (@Duncan Helped me to create it):
try
  {

    File input = new File(inputFileField.getText());
    File output = new File(fileDirectoryFolder.getText() +"/"+ input.getName());

    byte[] buffer = new byte[8];
    DataOutputStream out = new DataOutputStream(new FileOutputStream(output));
    DataInputStream in = new DataInputStream(new FileInputStream(input));

    int count = 0;

    while (count < input.length() - 4) {

        in.readFully(buffer, 4, 4);
        String s= Long.toString(ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getLong());
        out.writeBytes( s+ " ");
        count += 4;
     }
   }
   System.out.println("Done");

}
catch(FileNotFoundException e1){}

However, the result I get is
10 00 00 00 --> 68719476736
54 00 00 00 --> 360777252864

Do you understand where my problem is?
Thanks

A: String s=
Integer.toString(
   ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getInt());

Long has 8 bytes, you want to convert only 4.
And don't use an offset
in.readFully( buffer, 0, 4 );

$ echo $[0x1000000000]
68719476736
$ echo $[0x5400000000]
360777252864

This is due to the (incorrect) offset of 4 bytes when reading.
And another one, that should be corrected:
 while (count < input.length() - 3) {


text:
Q: Plotly: How to remove white space after saving an image? I have a question about saving plotly table as an image. I wrote the following code:
import plotly.graph_objects as go

layout = go.Layout(autosize=True, margin={'l': 0, 'r': 0, 't': 0, 'b': 0})

fig = go.Figure(data=[go.Table(header=dict(values=['A Scores', 'B Scores']),
                           cells=dict(values=[[100, 90, 80, 90], [95, 85, 75, 95]]))
                  ], layout=layout)

fig.write_image("fig1.png", scale=5)

But unfortunately, there is a big white space at the bottom of the table.

Can I cut it from the image? The height setting doesn't fit because the table may have a different number of rows.

A: You can do it by setting the cell height and the entire image height according to this cell height:
import plotly.graph_objects as go

CELL_HEIGHT = 30
a_scores = [100, 90, 80, 90]
b_scores = [95, 85, 75, 95]

layout = go.Layout(
    autosize=True,
    margin={'l': 0, 'r': 0, 't': 0, 'b': 0},
    height=CELL_HEIGHT * (len(a_scores) + 1)
)

fig = go.Figure(
    data=[
        go.Table(
            header=dict(values=['A Scores', 'B Scores']),
            cells=dict(values=[a_scores, b_scores],
            height=CELL_HEIGHT)
        )
    ],
    layout=layout
)

fig.write_image("fig1.png", scale=5)

If you want to give a different height to the headers:
import plotly.graph_objects as go

CELL_HEIGHT = 30
HEADER_CELL_HEIGHT = 100
a_scores = [100, 90, 80, 90]
b_scores = [95, 85, 75, 95]

layout = go.Layout(
    autosize=True,
    margin={'l': 0, 'r': 0, 't': 0, 'b': 0},
    height=CELL_HEIGHT * len(a_scores) + HEADER_CELL_HEIGHT
)

fig = go.Figure(
    data=[
        go.Table(
            header=dict(values=['A Scores', 'B Scores'], height=HEADER_CELL_HEIGHT),
            cells=dict(values=[a_scores, b_scores],
            height=CELL_HEIGHT)
        )
    ],
    layout=layout
)

fig.write_image("fig1.png", scale=5)

I tried it with different data sizes, header cells size and cells size and it was always perfectly cropped.


text:
Q: MultiAttachment Distribution of varing files to multiple recipients I have researched this topic and found great code - but not quite what I need.  I have created an Excel file to setup a range for email distribution of an attachment to 3 hundred recipients - which works fine.  But I have multiple attachments which need to go to the same recipient. Column A is the field where the file name is chosen - which picks up a pdf for recipient 1. Is it possible to use Column B for the second pdf file for recipient 1 and how do I loop that in?

Sub Mail_Report()
  Dim OutApp As Object
  Dim OutMail As Object

'Use presence of a Path to determine if a mail is sent.
  Set Rng = Range(Range("J2"), Range("J" & Rows.Count).End(xlUp))
  For Each cell In Rng
    Rw = cell.Row

    Path = cell.Value
    If Path <> "" Then
    'Get Date info from Path
      'Dte = Right(Path, Len(Path) - InStrRev(Path, "\"))

    'Get Territory to check for filename (Column A)
      FilNmeStr = cell.Offset(0, -9).Value
   'Email Address
      ToName = cell.Offset(0, -5).Value
   'Subject Line
      SL = Cells(1, "K")

   'Create Recipient List
      For x = 1 To 4
        Recp = cell.Offset(0, -x).Value
        If Recp <> "" Then
          Recp = cell.Offset(0, -x).Value
        End If
        RecpList = RecpList & ";" & Recp
      Next

      ccTo = RecpList

  'Get  Name
      FirstName = cell.Offset(0, -7).Value
      LastName = cell.Offset(0, -6).Value

  'Loop through files in Path to see if
      ClientFile = Dir(Path & "\*.*")

      Do While ClientFile <> ""
        If InStr(ClientFile, FilNmeStr) > 0 Then
          AttachFile = Path & "\" & ClientFile
          MailBody = "Hi " & FirstName & "," & vbNewLine & vbNewLine _
        End If
        ClientFile = Dir
      Loop

      Set OutApp = CreateObject("Outlook.Application")
      Set OutMail = OutApp.CreateItem(o)
      With OutMail
        .SentOnBehalfOfName = """TechSupport"" <TechSupport@anycompany.com>"
        .To = ToName
        .cc = ccTo
        .Subject = SL & " - " & cell.Offset(0, -9).Value
        .Body = MailBody
        .Attachments.Add (AttachFile)
        .Display
        '.Send
      End With
      Set OutMail = Nothing
      Set OutApp = Nothing
      RecpList = ""
    End If
  Next
End Sub

A: Try it this way.
Make a list in Sheets("Sheet1") with :
In column A : Names of the people
In column B : E-mail addresses
In column C:Z : Filenames like this C:\Data\Book2.xls (don't have to be Excel files)

The Macro will loop through each row in "Sheet1" and if there is a E-mail address in column B
and file name(s) in column C:Z it will create a mail with this information and send it.
Sub Send_Files()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
    Dim OutApp As Object
    Dim OutMail As Object
    Dim sh As Worksheet
    Dim cell As Range
    Dim FileCell As Range
    Dim rng As Range

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set sh = Sheets("Sheet1")

    Set OutApp = CreateObject("Outlook.Application")

    For Each cell In sh.Columns("B").Cells.SpecialCells(xlCellTypeConstants)

        'Enter the path/file names in the C:Z column in each row
        Set rng = sh.Cells(cell.Row, 1).Range("C1:Z1")

        If cell.Value Like "?*@?*.?*" And _
           Application.WorksheetFunction.CountA(rng) > 0 Then
            Set OutMail = OutApp.CreateItem(0)

            With OutMail
                .to = cell.Value
                .Subject = "Testfile"
                .Body = "Hi " & cell.Offset(0, -1).Value

                For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
                    If Trim(FileCell) <> "" Then
                        If Dir(FileCell.Value) <> "" Then
                            .Attachments.Add FileCell.Value
                        End If
                    End If
                Next FileCell

                .Send  'Or use .Display
            End With

            Set OutMail = Nothing
        End If
    Next cell

    Set OutApp = Nothing
    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With
End Sub

https://www.rondebruin.nl/win/s1/outlook/amail6.htm


text:
Q: Unable to catch SIGHUP signal I am facing a strange problem while handling the SIGHUP signal.
I need to execute some commands in interactive mode.
So I wrote some code using the pseudo terminal concept. Below is the link I referred to this article.
In the link, they use the fork concept to start the master and slave terminals.
Once the task is completed, both master and file descriptors are closed using close(fd) command.
However, since fork will display the duplicate process and this is not allowed in our project, I have used thread instead of fork.
I am able to close the slave file descriptor properly without any problem.
But I am not able to close the master fd.
After some analysis, I observe that while trying to close the master fd, it sends SIGHUP signal. This is ok if I use fork() concept, but unfortunately I have used thread and so my process is getting terminated.
If I don't close it there is a fd leakage.
So I want to ignore the SIGHUP signal. But when I wrote the program to catch the signal, I was able to catch all signals except this one.
Could anyone please help me on this part?
Is the way to catch SIGHUP different from other signals?
Note: We are using amf framework to keep our service available. When I keep service independent, I am able to catch the signal and when it is in amf, I am not able to catch the signal.
Any quick help is appreciated. Now I don't have time to do any design changes. I simply want to avoid the memory leakage.