text:
Q: Styling the Highlighting in CSS Is it possible to change the background color and foreground color (or text color) of the highlighted portion in a HTML page? In another words, customize the hightlighting of our Webpage

A: If I understand you correctly, you are looking for these styles:

*

*::selection (General)

*::-moz-selection (For Mozilla)

*::-webkit-selection (For Webkit)

More Info:

*

*http://www.quirksmode.org/css/selection.html

A: Only with CSS3 (modern browsers only, obviously), if you want to use pure CSS.
http://css-tricks.com/overriding-the-default-text-selection-color-with-css/


text:
Q: Flutter: can I enable/disable InkWell in ListView builder? I working on education app (Something like udemy app)
In lecture list screen, I use Inkwell to show lecture data card, and onTap (when user click on card) it will go to video player page
Lecture list page image HERE
When lecture list screen loaded:
First I have function to check number of views with http.POST for every lecture
If lecture views less than 2 views I want to make lecture card clickable (user can view lecture one more time)
but if user has views number equal 2 I want to disable the lecture, to prevent user to make another view
I think to use if statement to check number of views then enable Inkwell onTap property or not, but it's doesn't work
I need help about how I can do this situation
=======================
views count function
checkViewsCount() async {
                        var XX = await checkLessonViews(lesson.id.toString(), lesson.lessonType);

                        if(int.parse(XX) >= 2){
                          //////////////////Here want to make lecture card disabled
                        } else {
                          //////////////////Here want to make lecture card enabled
                        }

                      }

============================
and this is InkWell code
return InkWell(

                        onTap: () {
                          setState(() {
                            _activeLesson = lesson;
                          });
                          lessonAction(lesson);
                        },

                        child: Column(
                          children: <Widget>[
                            Container(
                              padding: EdgeInsets.symmetric(
                                  vertical: 10, horizontal: 30),
                              width: double.infinity,
                           child: Row(
                                children: <Widget>[
                                  //////////////////////// Lesson No.
                                  Expanded(
                                      flex: 2,
                                      child: Customtext(
                                        text: lessonCount.toString(),
                                        fontSize: 16
                                      )),
                                  //////////////////////// Lesson title
                                  Expanded(
                                      flex: 8,
                                      child: Column(
                                        crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                        children: <Widget>[
                                          Customtext(
                                            text: lesson.title,
                                            fontSize: 14,
                                            colors: kTextColor,
                                            fontWeight:
                                            FontWeight.bold,
                                          ),
                                          getLessonSubtitle(lesson),
                                        ],
                                      )),
                                ],
                              ),
                            ),
                            Divider(),
                          ],
                        ),
                      );

Thanks in advance

A: You can't disable inkwell in flutter, use an if condition to either display an inkwell or a container (without gesture handling properties) depending on the number of views the user has.

A: var canAddLecture = true;

if(int.parse(XX) >= 2){
  canAddLecture = false;
} else {
  canAddLecture = true;
}

and in onTap:
onTap: () {
   if(canAddLecture == false) return;
   setState(() {
       _activeLesson = lesson;
   });
   lessonAction(lesson);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bourbaki exercise on connected sets This is Exercise I.11.4 of Bourbaki's General Topology.
Let $X$ be a connected space.
a) Let $A$ be a connected subset of $X$, $B$ a subset of $\complement A$ which is both open and closed in $\complement A$. Show that $A\cup B$ is connected.
b) Let $A$ be a connected subset of $X$ and $B$ a component of the set $\complement A$. Show that $\complement B$ is connected (use a)).
I have managed to show a).
My attempts to show b): Let $C$ be a nonempty clopen subset of $\complement B$. By a), $B\cup C$ is connected. Since $B$ is a component of $\complement A$, $B\cup C$ cannot be a subset of $\complement A$. So $C$ has to contain an element of $A$. Since $A$ is connected, $A\subset C$. But I'm stuck here. I can't see how this implies $C=\complement B$.
Can someone point me in the right direction?

A: Suppose $B^{c} = U \cup V$ with $U,V$ disjoint and open. Then $U$ and $V$ are also closed and if they are non-empty, they both must contain $A$ by your argument, so they can't be disjoint.


text:
Q: Edit description in Ms teams composeExtensions.commands According to https://learn.microsoft.com/en-us/microsoftteams/platform/resources/schema/manifest-schema#composeextensionscommands, there is a limit on the size of description in composeExtensions.commands. Is there a workaround for that?
Also, on adding multiple commands, the popup shows a "2 more" option,
is there any way to customize this, i want to show just 2 main commands in popup and other commands
to open when user clicks "More Filters".

I want something like ...

A:
There is a limit on the size of description in
composeExtensions.commands. Is there a workaround for that?

Is there any way to customize this, i want to show just 2 main
commands in popup

These are not customizable fields. This is by design.
Please feel free to post feature suggestions on Microsoft Teams feedback portal on UserVoice.


text:
Q: Python add digits on either side of ' : ' ie. 22:11 + 22:22 = 44:33 22:11  +  22:22  =  44:33
varible_A = ('22:11')
varible_B = ('22:11')

the numbers on the left(22) are minutes
the numbers on the right(11) are seconds
I'm trying to add the two numbers to get
total = 44:22

This is a Bonus but would really help me out*
is it possible to treat the digits like time for instance...
varible_A = ('22:50')
varible_B = ('22:30')

I would like to get 45:20
instead of
44:80

A: Use datetime.timedelta() to model time durations:
from datetime import timedelta

def to_delta(value):
    minutes, seconds = map(int, value.split(':'))
    return timedelta(minutes=minutes, seconds=seconds)

var_a = to_delta('22:50')
var_b = to_delta('22:30')

var_a + var_b

You can then turn a timedelta() object back to a minutes + seconds representation:
def to_minutes_seconds(delta):
    return '{:02.0f}:{:02.0f}'.format(*divmod(delta.total_seconds(), 60))

Demo:
>>> var_a = to_delta('22:50')
>>> var_b = to_delta('22:30')
>>> var_a + var_b
datetime.timedelta(0, 2720)
>>> to_minutes_seconds(var_a + var_b)
'45:20'

Alternatively, the str() result of a timedelta is formatted as HH:MM:SS:
>>> str(var_a + var_b)
'00:45:20'

and may suit your needs too. Note that for deltas that present more than one hour, there is a difference between str() and to_minutes_seconds(); the former shows you hours, minutes and seconds, the latter just shows minutes, where the minutes value can be over 60. Deltas representing more than 24 hours gain an extra prefix for the number of days:
>>> str(timedelta(minutes=65, seconds=10))
'1:05:10'
>>> to_minutes_seconds(timedelta(minutes=65, seconds=10))
'65:10'
>>> str(timedelta(minutes=(60*24)+1, seconds=10))
'1 day, 0:01:10'

A: I think these should be represented by objects, rather than one line comprehensions etc... As such my suggestion is to use a class like follows:
class Time(object):
    def __init__(self,minutes,seconds):
        self.minutes = minutes
        self.seconds = seconds
    def __add__(self,other):
        return Time(self.minutes+other.minutes,self.seconds+other.seconds)
    def __str__(self):
        return "{0}:{1}".format(self.minutes,self.seconds)

A = Time(22,11)
B = Time(22,22)
print(A+B)

Produces
>>>
44:33

A: You can Use similar function
def add_with_column(*args):
    res = (0,0)
    for data in args:
        nums = map(int, data.split(':'))
        res = [i + j for i,j in zip(res, nums)]
    return ':'.join([str(res[0] + res[1]/60), str(res[1] % 60)])

>>> add_with_column('22:50', '22:30')
'45:20'

A: Something like this:
>>> def add_time(t1,t2):
    h1,s1 = map(int,t1.split(":"))
    h2,s2 = map(int,t2.split(":"))
    q,r = divmod(s1+s2, 60)
    return "{0}:{1:02d}".format( h1+h2+q, r)
...
>>> add_time('22:30','22:50')
'45:20'
>>> add_time('22:30','22:30')
'45:00'

A: A simple way to do this without importing any external machinery would be:
def add(time1,time2):
    t1 = map(int,time1.split(':')) # t1[0] is minutes, t1[1] is seconds
    t2 = map(int,time2.split(':')) # map will apply int() to both elements of the array
    m = t1[0]+t2[0]+(t1[1]+t2[1])/60 # New minutes; recall that 70/60=1 for integer division
    s = (t1[1]+t2[1]) % 60 #new seconds
    return str(m)+":"+str(s)
add('22:30','22:50') # prints '45:20'

Of course, you can always import from datetime (which is probably better for practical applications), but if you want to implement time operations by yourself, this is how you can do so.

A: a = '22:50'
b = '22:30'

def add_time(a, b):
    a = map(int, a.split(':'))
    b = map(int, b.split(':'))
    a[1] += b[1]
    a[0] += b[0] + a[1]//60
    a[1] %= 60
    return '{}:{}'.format(*a)

print a, b, add_time(a,b)

A: You want to split the times into their components
def split_time(time):
    return time.split(':')

and add them
def add_times(time1, time2):
    minutes = time1[0] + time2[0]
    seconds = time1[1] + time2[1]
    return minutes, seconds

and do modular arithmetic to "carry the minute" when appropriate
def carry_the_minute(minutes, seconds):
    minutes += seconds / 60
    seconds %= 60
    return minutes, seconds

and create a representation of the result
def represent_time(minutes, seconds):
    """Specifies two-character-wide seconds with leading 0."""
    return "{0}:{1:02d}".format(minutes, seconds)

Putting it all together will look something like this:
def add_times(time1, time2):
    time1 = split_time(time1)
    time2 = split_time(time2)
    minutes, seconds = add_times(time1, time2)
    minutes, seconds = carry_the_minute(minutes, seconds)
    print represent_time(minutes, seconds)


text:
Q: Understanding various types of motion In classical statistical mechanics, given a system of particles, one often goes about classifying various dynamics (or types of motion) the system may exhibit on different time scales, but studying the time dependence of the average displacement vector squared. For example if the dependence is quadratic in time, we say the system is ballistic, and similarly if it is linear in time, we say it is diffusive. In other words

*

*$\langle \lvert \mathbf{r}(t)\rvert^2\rangle \propto t^2 \Rightarrow$ ballistic motion

*$\langle \lvert \mathbf{r}(t)\rvert^2\rangle \propto t \Rightarrow$ diffusive motion

Questions:

*

*Mathematically I understand the classification is given by the power of $t$ (this goes on, e.g. we can have subdiffusive motions etc), but purely from a physical point of view, how do the two aforementioned types of motion differ? For example, by diffusive motion, in contrast to ballistic, do we mean there are random forces involved? (e.g. particles in solvent)

*What does it mean that on different time scales, the system may follow different types of motion? e.g. in short times ballistic, and the longer term behaviour diffusive.

*Finally, why is the average squared displacement $\langle \lvert \mathbf{r}(t)\rvert^2\rangle$ a sufficient measure for qualifying the types of motion?


text:
Q: Changed DB engine to MySQL. Now Django does not create tables I have a Django app with a standard sqlite3 DB. Now I want to use MySQL. So I changed my DATABASES in settings.py, and it works well, but I can't run server because it says
django.db.utils.InternalError: (1049, "Unknown database 'django'")

So I created this DB in the client, and now it says
django.db.utils.ProgrammingError: (1146, "Table 'django.Cat' doesn't exist")

Seems like I have to create all tables by myself, which is the worst variant I can do.
#settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/db.conf',
        },
    }
}

and
#conf.db
[client]
database = django
host = localhost
user = DjangoUser
password = password_you_cant_guess
default-character-set = utf8

How to make Django create all tables I have?
I even can't run python3 manage.py with any command because it gives my this exception.
Traceback:
Traceback (most recent call last):
  File "/path/to/project/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/path/to/project/venv/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 74, in execute
    return self.cursor.execute(query, args)
  File "/path/to/project/venv/lib/python3.6/site-packages/MySQLdb/cursors.py", line 209, in execute
    res = self._query(query)
  File "/path/to/project/venv/lib/python3.6/site-packages/MySQLdb/cursors.py", line 315, in _query
    db.query(q)
  File "/path/to/project/venv/lib/python3.6/site-packages/MySQLdb/connections.py", line 239, in query
    _mysql.connection.query(self, query)
MySQLdb._exceptions.ProgrammingError: (1146, "Table 'django.Cat' doesn't exist")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/path/to/project/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/path/to/project/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute
    django.setup()
  File "/path/to/project/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/path/to/project/venv/lib/python3.6/site-packages/django/apps/registry.py", line 122, in populate
    app_config.ready()
  File "/path/to/project/External/apps.py", line 13, in ready
    active_cats = list(Cat.objects.filter(active_cat=True).all())
  File "/path/to/project/venv/lib/python3.6/site-packages/django/db/models/query.py", line 276, in __iter__
    self._fetch_all()
  File "/path/to/project/venv/lib/python3.6/site-packages/django/db/models/query.py", line 1261, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/path/to/project/venv/lib/python3.6/site-packages/django/db/models/query.py", line 57, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/path/to/project/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1151, in execute_sql
    cursor.execute(sql, params)
  File "/path/to/project/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
    return super().execute(sql, params)
  File "/path/to/project/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/path/to/project/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/path/to/project/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/path/to/project/venv/lib/python3.6/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/path/to/project/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/path/to/project/venv/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 74, in execute
    return self.cursor.execute(query, args)
  File "/path/to/project/venv/lib/python3.6/site-packages/MySQLdb/cursors.py", line 209, in execute
    res = self._query(query)
  File "/path/to/project/venv/lib/python3.6/site-packages/MySQLdb/cursors.py", line 315, in _query
    db.query(q)
  File "/path/to/project/venv/lib/python3.6/site-packages/MySQLdb/connections.py", line 239, in query
    _mysql.connection.query(self, query)
django.db.utils.ProgrammingError: (1146, "Table 'django.Cat' doesn't exist")

A: Your issue is here:
File "/path/to/project/External/apps.py", line 13, in ready
    active_cats = list(Cat.objects.filter(active_cat=True).all())

This code is executed as part of the initialization process. This is what prevents you from executing any management command. Note that this is documented with a very clear warning:

Warning
Although you can access model classes as described above, avoid
  interacting with the database in your ready() implementation. This
  includes model methods that execute queries (save(), delete(), manager
  methods etc.), and also raw SQL queries via django.db.connection. Your
  ready() method will run during startup of every management command.
  For example, even though the test database configuration is separate
  from the production settings, manage.py test would still execute some
  queries against your production database!


text:
Q: Prove this result relating to the sign of a permutation Suppose that $\phi \in S_n$ is a permutation.
Suppose also that $\psi = \phi \circ (i,j),$ where $1 \leq i, j \leq n.$
Why does it follow that sign$(\phi) = $ $-$sign$(\psi)$?

A: With the definition of sign in terms of transpositions, this is a one line proof. Namely, if $\phi$ is a product of an odd number of transpositions, then $\psi$ is the product of an even number of transpositions, and vice versa. Hence they have opposite signs.
Less trivial is with the definition in terms of inversions (odd number of inversions means sign $-1$, even number sign $1$). Suppose $\phi$ has $n$ inversions. Define
$a$= the number of indices $k$ with $i<k<j$ such that $\phi(i)>\phi(k)$
$b$= the number of indices $k$ with $i<k<j$ such that $\phi(i)<\phi(k)$
$c$= the number of indices $k$ with $i<k<j$ such that $\phi(j)>\phi(k)$
$d$= the number of indices $k$ with $i<k<j$ such that $\phi(j)<\phi(k)$
Then the number of inversions of $\psi$ is
$$n-a+b+c-d+1$$
But $a+b=c+d=j-i-1$, because they are both equal to the number of indices between $i$ and $j$, so $-a+b+c-d$, which has the same parity as $a+b+c+d$, is even, hence the number of inversions of $\psi$ has the opposite parity of the number of inversions of $\phi$ (from the $+1$ summand) hence they have opposite signs.


text:
Q: Delphi: How to avoid duplication (OneDrive) in Document Folder setting? Trying to store user settings & default saved data location in a less confusing way.
On PC1,
Label1.Caption := TPath.GetDocumentsPath;

shows me C:\Users\Mike\Documents, on PC2 it shows C:\users\mike\OneDrive\Documents.
On PC2 I have two sets of \Documents files & folders which do not match each other, and finding a setting or document involves a search. I have had feedback from a user in Singapore who similarly reported struggling to find their data.
As my application by default stores user settings in a subfolder of \Documents and there are users all over the world with different implementations, I would like advice.
I assume I should accept whatever is supplied by TPath.GetDocumentsPath without trying to modify it?
I could raise a warning if my application can detect two \Documents folders.
Or should I set a default store somewhere else?

A: I use Local AppData folder to store settings that depends on the user and ProgramData to store the global settings (independent of user). Code extract:
var
    CommonPath   : array [0..MAX_PATH] of Char;
    LocalPath    : array [0..MAX_PATH] of Char;
    LangFileName : String;
begin
    SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, SHGFP_TYPE_CURRENT, @CommonPath[0]);
    SHGetFolderPath(0, CSIDL_LOCAL_APPDATA,  0, SHGFP_TYPE_CURRENT, @LocalPath[0]);
    FAppName        := ChangeFileExt(ExtractFileName(Application.ExeName), '');
    FCommonAppData  := IncludeTrailingPathDelimiter(CommonPath) +
                       CompanyFolder + '\' + FAppName + '\';
    FLocalAppData   := IncludeTrailingPathDelimiter(LocalPath) +
                       CompanyFolder + '\' + FAppName + '\';
    ForceDirectories(FCommonAppData);
    ForceDirectories(FLocalAppData);
end;

The variables are in the protected stion in form's class:
    FLocalAppData                 : String;
    FCommonAppData                : String;
    FAppName                      : String;

And CompanyName is a constant whose value is obviously my company name.


text:
Q: Confirmation Dialog to Run Trigger on a picklist. I have a pick-list on accounts that when a certain stage is selected and saved, all oops are cancelled (via trigger). Is there a way to add a confirmation after selecting the stage from the pick-list and selecting save, so that If the user Selects Yes within the dialog it will continue with the trigger otherwise, it will not make the change.

A: You can create a custom Checkbox field on the account and only have the trigger run on those accounts where it is set to true.  You will likely have to have a custom JS button that sets your account pick-list value so you can then invoke your confirmation.  If they confirm, then just set the new checkbox flag on the account to true, so the trigger will act on this account.


text:
Q: Want to Run a function without click any button when application start I have a function named 'func()'. I want to run this function when application start without clicking any button. just when application load I want to show a massage.that massage in that function. I just want to run that function when app start what will be the code.
public class TextViewActivity extends Activity {
  public static EditText etxt;
public final void func(){
    etxt.setText("Massage");
 }

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
     etxt= (EditText) findViewById(R.id.etxt2);
     }
}

A: Just put a call to the function on the onCreate
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    etxt= (EditText) findViewById(R.id.etxt2);
    func(); //A call to the function.
}

Hope that helps.

A: I don't recommend subclassing the Application in order to do this.  When the application starts it will go to the main activity.  So I would say just keep a SharedPreference boolean value if it has been set.  If not show the message.
So keep state of the application here: http://developer.android.com/reference/android/content/SharedPreferences.html, just set a boolean. Remember when you app gets called, the activity onCreate always gets called of the main activity, so its just a matter of not calling it again.

A: try using below code.. you need to call ur function after you initialize edittext etxt. so it can not cause you NPE
public final void func(){
    etxt.setText("Message");
 }

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
     etxt= (EditText) findViewById(R.id.etxt2);
    func();// here your function call.
     }

A: Try this:
public class TextViewActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.etxt2).setText("SMTH");
    }
}

In case you really need a function to be called, you can use this:
public class TextViewActivity extends Activity {

    public final void func() {
        findViewById(R.id.etxt2).setText("SMTH");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        func();
    }
}


text:
Q: default browser Some softwares are needed to open IE so that I can use their help/documentations.I set my default browser as google chrome.
 Currently when I click on help/Docs a page is automatically opened by google chrome but it doesn't show the information unless I copy & paste the path on IE again.
  How can I made that software using IE without changing my default Browser ,Any idea?

A: With the push of a button you can switch to an IE Tab inside Chrome.

A: You don't need a new program if it is a local file on your PC.  You can associate IE with html files and STILL have Chrome as your default browser.  Chrome will open links and IE will open files.  Just change your file association on .html files to IE.
Find a file, right click, open with, choose program, select IE and check the box for "Always use the selected program..."

A: Try BrowserMaster: http://browsermaster.codeplex.com/releases/view/34262
It gets set as the default browser and allows you to choose which browser you want opened when you click or try to open something. I recommend setting the timer to 10 seconds.

A: The software in question is almost certainly just opening an HTML help file without reference to a particular browser - the equivalent of double-clicking on the HTML file in Windows Explorer.  If that is in fact the case - unless the program has an option to change this behaviour - you're out of luck, since it would otherwise require changing the program.


text:
Q: PySerial Throwing 'NoneType' Exception During read() I am using PySerial to read incoming bytes from a serial port into a buffer.  Every time I call my read function this exception gets thrown.
Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Python27\lib\threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "gatewayTester.py", line 480, in mcuRead
    byteIn = mcuPort.read()
  File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 269, in read
    win32.ResetEvent(self._overlapped_read.hEvent)
AttributeError: 'NoneType' object has no attribute 'hEvent'

My application seems to work fine despite this exception being thrown.
However, I would like some clarity on the source of this issue.
Here is my serial read function.
def mcuRead(self, *args, **kwargs):

    global mcuPort
    global readVal
    global serialWriting
    global testRunning

    print("READING MCU")
    sys.stdout.flush()
    inBuffer = ""

    while testRunning:
        try:
            byteIn = ""
            if not mcuPort.is_open:
                mcuPort.open()

            #Read incoming byte
            if not serialWriting:
                byteIn = mcuPort.read()
                inBuffer += byteIn
                #Skip newlines to parse incoming commands
                if(byteIn == "\n"):
                    inBuffer = ""

                #Check if buffer contains a valid command
                for rxCmd in mcuRxCmds:

                    if inBuffer == rxCmd['Command']:

                        #store incoming command globally
                        readVal = rxCmd['Command']
                        #Clear buffer
                        inBuffer = ""
                        print("MCU IN "+str(readVal))

        except(OSError, serial.SerialException):
            print(OSError)

        sys.stdout.flush()

Serial port is created globally as follows.  Read function is run concurrently on a separate thread.
mcuPort = serial.Serial(port, 115200, timeout=0)

A: The problem was due to the asynchronous nature of how I was closing the port.  In my exit routine I closed the port before clearing 'testRunning'.  The loop would then go through one unstable iteration before completing.  Clearing the 'testRunning' lock before closing the port prevents this unstable iteration.
Before
def quitTest(self):

    global testRunning
    global mcuPort

    #Close all open ports
    if(mcuPort.is_open):
        mcuPort.close()

    testRunning = False

After
def quitTest(self):

    global testRunning
    global mcuPort

    testRunning = False

    #Close all open ports
    if(mcuPort.is_open):
        mcuPort.close()

A: The exception tells mcuPort._overlapped_read  is None!
win32.ResetEvent(self._overlapped_read.hEvent)
AttributeError: 'NoneType' object has no attribute 'hEvent'

This is set in def open
try:
        self._overlapped_read = win32.OVERLAPPED()
        self._overlapped_read.hEvent = win32.CreateEvent(None, 1, 0, None)

Check if  mcuPort._overlapped_read  is not None after mcuPort.open(...
Beside this check if you have the latest pySerial module
Relevant:  pywin32/bugs/search/?q=OVERLAPPED


text:
Q: ios requires reCAPCHA every time w/ firestore auth (Flutter) I am using phone verification in my flutter app. My goal is to have the following flow: 1. user enters phone number 2. user is sent verification code 3. user enters code and is signed in. On android, that is the flow I get. On ios, however, it goes 1. user enters phone number 2. reCAPCHA page opens to make sure I'm not a robot 3. user is sent verification code 4. user enters code and is signed in (this happens on ios emulator). I want to get rid of the reCAPCHA page. Some people recommended that I turn on "remote-notifications", so I tried to do this in Xcode by adding it as a "capability" to my runner, and now my Info.plist includes
<key>UIBackgroundModes</key>
    <array>
        <string>remote-notification</string>
    </array>

Which seems right. However, this did not fix the issue, and I am still faced with the capcha.
Version of firebase auth:
firebase_auth: 0.15.4

Output of flutter doctor
[✓] Flutter (Channel stable, v1.12.13+hotfix.5, on Mac OS X 10.15.2 19C57, locale en-US)
    • Flutter version 1.12.13+hotfix.5 at /Users/gollyzoom/development/flutter
    • Framework revision 27321ebbad (3 months ago), 2019-12-10 18:15:01 -0800
    • Engine revision 2994f7e1e6
    • Dart version 2.7.0

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/gollyzoom/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-29, build-tools 28.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.3)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.3, Build version 11C29
    • CocoaPods version 1.8.4

[✓] Android Studio (version 3.5)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 39.0.3
    • Dart plugin version 191.8423
    • Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)

[✓] IntelliJ IDEA Ultimate Edition (version 2019.1.4)
    • IntelliJ at /Applications/IntelliJ IDEA.app
    • Flutter plugin version 38.1.3
    • Dart plugin version 191.8593

[✓] Connected device (2 available)
    • Android SDK built for x86 • emulator-5554                        • android-x86 • Android 9 (API 28) (emulator)
    • iPhone 11 Pro Max         • B3536B50-C435-4442-9CF4-69D470B979CA • ios         •
      com.apple.CoreSimulator.SimRuntime.iOS-13-3 (simulator)

• No issues found!

I would really appreciate if anyone had some advice on this!

A: Here is the solution for my problem in Android https://github.com/FirebaseExtended/flutterfire/issues/4189#issuecomment-741711350
Steps made by @Omrankabalan
Go to https://console.cloud.google.com/
If you have a Firebase project you can open in from here

Then select All tab and choose your existing project

Then go to API & Services => Library
Search for 'Android Device Verification'

Enable it

In Firebase make sure to add SHA-256 In Project Settings

Test it on a real device

A: This happens to be in Android as well. I get the reCaptcha opened before I can enter my verification code.

A: You will need to setup Silent Push Notification for iOS.
Referencing this document: https://firebase.google.com/docs/auth/ios/phone-auth
You will see there are 2 strategies when authorizing Phone Numbers: reCaptcha (to verify you are not a robot) and Silent Push Notifications.
There are additional configurations but in summary:

*

*In Xcode, enable push notifications for your project.

*Upload your APNs authentication key to Firebase.

A: I had this same issue and was able to solve it by modifying the entitlements. I have added 'Push Notifications' and 'Background Modes'. The background mode is set with "Background fetch" and "Remote notifications" options.
my "Info.plist" looks as follows after the 'Background Modes' change:
<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
    <string>remote-notification</string>
</array>

Needless to say that you need to configure the push notifications from your developer account and to configure it from the firebase console for you iOS app.


text:
Q: Is it incorrect to say, "Why cannot....?" At any point in history was "Why cannot...?" used as frequently as "Why can't...?"  Is it even grammatically correct to say "Why cannot you do this?" I know it can be rearranged to be "Why can you not do this?," but I always presumed the contraction and the contracted phrase could be used equivalently, without changing the sentence structure. I think this pattern holds true with the other question words (e.g. how, when, etc.); however, I also know it is common to say "Who cannot do this?" In general, are there rules pertaining to the uses of contractions in questions?

A: Arnold M. Zwicky and Geoffrey K. Pullum have shown that -n't is not just a contraction of not. The two American linguists pointed out that you can say why don't you... but not *why do not you... because you can place one and only one auxiliary before the subject in an interrogative phrase. Don't is a single word while do not are two words. -n't is not a clitic but a negative inflectional suffix.
Cannot is the only negative form that contains not rather than -n't. Theoretically, since it is a single word, you can say why cannot you... without a problem. My theory is that modern English speakers don't want to put cannot before the subject because it contains not and sounds like can not. You definitely cannot say why can not you... with a separate not. On the contrary can't remains a single word, which is why they use it more and more often.

A: The transition point was about a century ago

Note that if we substitute a pronoun (I, he, they) for "why", the transition point comes much later (1980 for "I") – or hasn't even happened yet (all other pronouns). I can't explain why that is, except by pointing out that this very sentence is an increasingly typical usage. Maybe we all tend to be a bit less formal when introducing our own selves into the text.
It's only my opinion, but I think can't (similarly, let's) are examples of grammaticalisation. The contracted form has effectively taken on a "life of its own", leading to a situation where OP is prepared to accept that there may be contexts where can't is "grammatical", but "cannot" (or the equivalent "can not") wouldn't be valid.
Using cannot / can not might be a bit stilted in many contexts now we're so used to seeing the contracted form, but I don't think it's ever ungrammatical.

A: If you go to Open Library, a search will turn up 52,223 interrogatives (questions) that begin with "Why cannot" in published English literature and there are over 2 million examples of interrogatives that begin with "Why cannot" on the internet.
Looking at a specific example, "Why cannot we" turns up with 758,000 interrogatives (and 8,064 examples in published literature).
There are also many examples of "Why we cannot", but they are not interrogatives.
JForrest explains that 'cannot' is the negative form of 'can', and so 'cannot' should be placed in the same location as 'can' would be in a sentence.
Since we can say "Why can we grow taller?", "Why cannot we grow taller?" is a logical and properly written negative.
We don't say "Why we can grow taller?" so the construct should not be "Why we cannot grow taller?"
The reason is that auxiliaries should come before the subject to make an interrogative.
I argue that the "Why cannot" usage is acceptable because of that rule mentioned by Shinji, above, that "you can place one and only one auxiliary before the subject in an interrogative phrase".
Thus, "Why cannot" is acceptable though "Why can not" is not.
I admit that some people argue that the contraction "can't" should be used instead in this case. That option is quite popular - there are 16.6 million examples of can't on google and 90,470 in published literature. It is much easier to type can't, and easier to speak it as well. Contractions generally aren't considered ideal for formal writing, however.
Another alternative that is growing in popularity is the construction "Why can we not" which sees 1.2 million uses online, 9,900 in publication.


text:
Q: How can I copy STDOUT to a file without stopping it showing onscreen using Ruby I'm attempting to copy stdout to a file for logging purposes. I also want it to display in the Ruby console of the IDE I'm using.
I inserted this code into my script and it redirects $stdout to the my.log file:
$stdout.reopen("my.log", "w")

Does anyone know of a gem or technique to copy the contents of $stdout to a file and not redirect it to a file? Also, I am not using Rails just Ruby.

A: If you are using Linux or Mac OS, the tee command available in the OS makes it easy to do this. From its man page:
NAME
     tee -- pipe fitting

SYNOPSIS
     tee [-ai] [file ...]

DESCRIPTION
     The tee utility copies standard input to standard output, making a copy in zero or more files.  The output is unbuffered.

So something like:
echo '>foo bar' | tee tmp.out
>foo bar

echos the output to STDOUT and to the file. Catting the file gives me:
cat tmp.out
>foo bar

Otherwise, if you want to do it inside your code, it's a simple task:
def tee_output(logfile)
  log_output = File.open(logfile, 'w+')
  ->(o) {
    log_output.puts o
    puts o
  }
end

tee = tee_output('tmp.out')
tee.call('foo bar')

Running it:
>ruby test.rb
foo bar

And checking the output file:
>cat tmp.out
foo bar

I'd use "w+" for my file access to append to the output file, rather than over-write it.
CAVEAT: This opens the file and leaves it open during the life of the code after you've called the tee_output method. That bothers some people, but, personally, it doesn't bother me because Ruby will close the file when the script exits. In general we want to close files as soon as we're done with them, but in your code, it makes more sense to open it and leave it open, than to repeatedly open and close the output file, but your mileage might vary.

EDIT:
For Ruby 1.8.7, use lambda instead of the new -> syntax:
def tee_output(logfile)
  log_output = File.open(logfile, 'w+')
  lambda { |o|
    log_output.puts o
    puts o
  }
end

tee = tee_output('tmp.out')
tee.call('foo bar')

A: Something like this might help you:
class TeeIO < IO

  def initialize orig, file
    @orig = orig
    @file = file
  end

  def write string
    @file.write string
    @orig.write string
  end

end

Most of the methods in IO that do output ultimately use write, so you only have to override this one method. You can use it like this:
#setup
tee = TeeIO.new $stdout, File.new('out.txt', 'w')
$stdout = tee

# Now lots of example uses:
puts "Hello"
$stdout.puts "Extending IO allows us to expicitly use $stdout"
print "heres", :an, :example, "using", 'print', "\n"
48.upto(57) do |i|
  putc i
end
putc 10 #newline
printf "%s works as well - %d\n", "printf", 42
$stdout.write "Goodbye\n"

After this example, the following is written identically to both the console and to the file:
Hello
Extending IO allows us to expicitly use $stdout
heresanexampleusingprint
0123456789
printf works as well - 42
Goodbye

I won't claim this technique is fail proof, but it should work for simple uses of stdout. Test it for your use.
Note that you don't have to use reopen on $stdout unless you want to redirect output from a child process or an uncooperative extension. Simply assigning a different IO object to it will work for most uses.

RSpec
The RSpec command line takes a reference to $stdout before you can get any code to run to reassign it, so this doesn't work. reopen still works in this case as you're changing the actual object pointed to by both $stdout and the reference that RSpec has, but this doesn't give you output to both.
One solution is to monkey-patch $stdout like this:
$out_file = File.new('out.txt', 'w')

def $stdout.write string
  $out_file.write string
  super
end

This works, but as with all monkey patching, be careful. It would be safer to use your OS's tee command.

A: I know it's a old question, but I found myself in the same situation. I wrote a Multi-IO Class which extends File and overrode write puts and close methods, I also made sure its thread safe:
require 'singleton'

class MultiIO < File
  include Singleton
  @@targets = []
  @@mutex = Mutex.new

  def self.instance
    self.open('/dev/null','w+')
  end

  def puts(str)
    write "#{str}\n"
  end

  def write(str)
    @@mutex.synchronize do
      @@targets.each { |t| t.write str; flush }
    end
  end

  def setTargets(targets)
    raise 'setTargets is a one-off operation' unless @@targets.length < 1
    targets.each do |t|
       @@targets.push STDOUT.clone if t == STDOUT
       @@targets.push STDERR.clone if t == STDERR
       break if t == STDOUT or t == STDERR
       @@targets.push(File.open(t,'w+'))
    end
    self
  end

  def close
    @@targets.each {|t| f.close}
  end
end

STDOUT.reopen MultiIO.instance.setTargets(['/tmp/1.log',STDOUT,STDERR])
STDERR.reopen STDOUT

threads = []

5.times.each do |i|
  threads.push(
    Thread.new do
      10000.times.each do |j|
        STDOUT.puts "out#{i}:#{j}"
      end
    end
  )
end

5.times.each do |i|
  threads.push(
    Thread.new do
      10000.times.each do |j|
        STDERR.puts "err#{i}:#{j}"
      end
    end
  )
end

threads.each {|t| t.join}

A: Tiny improvement from matts answer:
class TeeIO < IO
  def initialize(ios)
    @ios = ios
  end

  def write(string)
    @ios.each { |io| io.write string }
  end
end


text:
Q: Docker volume mapping generates error : This command is not available when running the Angular CLI outside a workspace Docker version 20.10.21
docker run command without volume mapping works as expected. But when I try to share the source code using volume mapping it ends with This command is not available when running the Angular CLI outside a workspace error.
command works as expected:
docker run -p 4200:4200  angular-app

command that was not work
docker run -p 4200:4200 -v ${pwd}:/web-app/ -v /web-app/node_modules/ angular-app

A: I know what the problem is. There is no error with the command docker run -p 4200:4200 -v ${pwd}:/web-app/ -v /web-app/node_modules/ angular-app.
The problem was that I run this command outside of the project folder. So that means the project doesn't mounted correctly to the container.
But after I run the command inside the project folder the angular app is run without error.
${pwd} meaning:
The importance part of the command is ${pwd}. ${pwd} is an environment variable that puts path of the current working directory into that command. So if the current working directory is not the project folder it puts path of  other directory than the project.


text:
Q: How to get the console to "remember" a user input in Python? I am trying to figure out how I can get the console to "remember" what the user has inputted into the console for my hangman game. For example, if the word "tree" is picked from the hangman word string that I created, if a user inputs the letter "r", I want the console to remember that input and keep printing it to the console every time the user inputs a letter until the session ends. I want the console to re-print "- r - -" if the user inputs "r" while the user can find the other letters in the word. I wish for the same thing to happen if a user inputs the letter "t" or "e" as well: "- r e e". Thank you, sorry if I am asking for too much, I can't find the answer to this.
Here is my code:
#hangman mini-project

import random
import string
import time

letters = string.ascii_letters
lettertree = ['a', 'b', 'c', 'd', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 's', 'u', 'v', 'w', 'x', 'y', 'z']
hangmanwords = ['tree','sun']
sunchoices = ['s _ _', '_ u _', '_ _ n']
treechoices = ['t _ _ _', '_ r _ _', ' _ _ e _', '_ _ _ e']
lettercount = [0]
gameWinTree = False
gameWinSun = False
limbCount = 5

hangmanword = random.choice(hangmanwords)
correct = hangmanword
if hangmanword == "sun":
    print (random.choice(sunchoices))
if hangmanword == "tree":
    print (random.choice(treechoices))

    if letters == "r":
        print("Nice! You guessed one letter from the word")
        if letters == "e":
            print("Wow! You guessed two letters from the word, if you wish, you can guess the word")
while True:
    letters = input("Please enter a letter to guess the word")
    if letters == correct:
        input("Correct! The word was " + correct + ". Press enter to play again.")
        time.sleep(1)
        break
    if letters == correct:
        gameWinTree == true
        if gameWinTree == true:
            time.sleep(1)
        break
    print("The letter that you chose was " + letters)
    if letters == "r":
        print("Nice! You guessed one letter from the word!\n t r _ _")

    if letters == "e":
        print("Wow! You guessed two letters from the word!\n t _ e e")
    if letters == correct:
        print("Correct! The word was tree!")
    if letters == lettertree:
        print("Sorry, that's not a correct letter, feel free to try again.")
    limbCount -=1
    if limbCount == 0:
        print("Unfortunately, you are out of tries, better luck next time!")
        time.sleep(1)
        exit()

Sorry if my code seems sloppy, I'm just starting to learn Python after learning other programming languages.

A: Here's how I would construct the string you're looking for. When a player guesses a letter, I'd store it in a set, called guesses. If it's in the set of letters in the word, called correct, then I effectively add it to the intersection of these sets, called correct_guesses. Then, I iterate over the word, and print out each letter into the placeholder string, replaced with an underscore if that letter is not in correct_guesses. This is what it would look like in code:
word = 'tree'
guesses = set()
correct = set(list(word))
correct_guesses = set()

while correct_guesses != correct:
  # Get input
  guess = input("Guess: ")
  guesses.add(guess)
  correct_guesses = guesses.intersection(correct)

  # Print word status
  placeholder = ' '.join(['%s' for _ in word])
  print(placeholder % tuple([l if l in correct_guesses else '-' for l in word]))
  print("You've guessed: " + ", ".join(guesses))

Let me know if this code doesn't work for you or if it needs more explaining.


text:
Q: YouTube Data API: The request cannot be completed because you have exceeded your quota, INSUFFICIENT_TOKENS The problem occurred when I was using a Python program to upload videos to YouTube.  I did not use it to upload for many days before this happened so it should not exceed the quota.  I tried many times and it had the same error.
The following is the error:
[RequestError] Server response:
{
  "error": {
    "code": 403,
    "message": "The request cannot be completed because you have exceeded your \u003ca href=\"/youtube/v3/getting-started#quota\"\u003equota\u003c/a\u003e.",
    "errors": [
      {
        "message": "The request cannot be completed because you have exceeded your \u003ca href=\"/youtube/v3/getting-started#quota\"\u003equota\u003c/a\u003e.",
        "domain": "youtube.quota",
        "reason": "quotaExceeded",
        "debugInfo": "Code: 8; Description: ?metric=youtube.googleapis.com/default&limit=defaultPerDayPerProject&qs_error_code=INSUFFICIENT_TOKENS"
      }
    ]
  }
}

A: Taking into account the DTOS docs, it's very likely that you exceeded 90 days of inactivity w.r.t. your API credentials:

Inactivity
YouTube reserves the right to disable or curtail your access to, or use of, specific YouTube API Services if your API Project has been inactive for 90 consecutive days. For example, YouTube could revoke your API Credentials, or reduce (or eliminate) your API Project's quotas for specific YouTube API Services. If your API Client's quota is reduced or eliminated, you may reapply for quota or a quota extension, and YouTube will review that application based on YouTube's determination of your expected use of the YouTube API Services.

You may follow the official recommendations stated above by applying for a quota extension. For obtaining a quota extension you have to address Google directly. There's this form that you'll have to fill in. Than wait for response -- which, according to the experience of users of this forum, doesn't arrive shortly.
Other option would be to just discard (delete) the current app from Google's developers console and create a new one that will have assigned a new daily quota amount (of usually 10,000 units).


text:
Q: Why removing objects from a list with duplicate properties of types double in C# does not give consistent result using different methods? I am trying to find the quickest way to remove duplicate entries in a list.
My list contains objects which have properties X and Y which are both of type double.
I need to remove any objects which contain the same X and Y values.
My first attempt is very slow.
It will take a list that contains 81403 objects and spit out a new list with 25900 but it takes over a minute to run. Had this run quickly I would have compared the difference in order to add some rounding but it's too slow.
private List<DelaunayPoint> DeleteDuplicatesSlowWay(List<DelaunayPoint> points)
{
    List<DelaunayPoint> distinctPoints = new();
    int i = 0;
    foreach (DelaunayPoint p in points)
    {
        if (i == 0)
        {
            distinctPoints.Add(p);
        }
        else
        {
            if (distinctPoints.Any(pnt => pnt.X == p.X) == false ||
                distinctPoints.Any(pnt => pnt.Y == p.Y) == false)
            {
                distinctPoints.Add(p);
            }
        }
        i++;
    }
    return distinctPoints;
}

The following method will take the same list of 81403 objects but it will spit out a list containing 73385 objects, however, it takes less than a second to run.
private List<DelaunayPoint> DeleteDuplicatesFast(List<DelaunayPoint> points)
{
    return points
        .GroupBy(p => new { p.X, p.Y })
        .Select(output => output.First())
        .ToList();
}

Why do the above two methods give different results?
Assuming the difference is a rounding error between the two methods, how can I add rounding to the second DeleteDuplicatesFast method so I can compare the two?
I would need any rounding to not apply the rounding to the output list.

A: To answer the first part of your question: points are only equal if both their X and Y values are equal. You're testing for either X or Y being equal.
About the filtering of duplicates. The fastest way is to make your DelaunayPoint class implement IEquatable<DelaunayPoint> and then add the collection to a HashSet:
class DelaunayPoint : IEquatable<DelaunayPoint>
{
    public DelaunayPoint(double x, double y)
    {
        X = x;
        Y = y;
    }
    public double X { get;  }
    public double Y { get;  }

    public bool Equals(DelaunayPoint other)
    {
        return other != null && this.X == other.X && this.Y == other.Y;
    }

    public override int GetHashCode()
    {
        return System.HashCode.Combine(X,Y);
    }
}

var set = new HashSet<DelaunayPoint>(points);

Now set contains distinct points. I tested it to be approx. 7 times faster than GroupBy.


text:
Q: Получение ID чата по сообщению пользователя в нем Подскажите пожалуйста как сделать на библиотеке Telebot, python, так чтобы бот узнавал с какого чата приходит сообщение пользователя.

A: У сообщения есть свойство chat, а у него id:
message.chat.id


text:
Q: Trigger to insert/update fields with aggregate results on custom object Hi I need to calculate fields in a trigger depending on the parent Account record. For this, I created on the custom object Object__c, where the calculation needs to be done, the text field Parent_Account__c which copies the ParentId from Account to Object__c. Then I implement the trigger - it is just an excerpt as the trigger is more complicated. Please mind I do know to move the logic to a class, but for now I just want the trigger to be working.
trigger triggerUpdateObject on Object__c (before insert, before update) {

    public list <String> listParentIds = new list <String>();
    public list <Object__c> listObject = new list <Object__c>();

    //loop through new/updated records (I need this twice in the trigger due to other logic)
    for (Object__c cv: trigger.new){

        listParentIds.add(cv.Parent_Account__c);

    }

    public Map<Id,AggregateResult> mapAggAR = new Map<id,AggregateResult>([Select ParentId, Min(Field)minfield, Max(Field)maxfield from Account where Field <> null AND ParentId <> null AND ParentId IN :listParentIds group by ParentId]);

    //loop through records again
    for (Object__c cv: trigger.new){

        //loop through ParentIds from Aggregate Result Map and calculate field depending on ParentId
        for (Id mapId : mapAggAR.keyset()){

            AggregateResult ARObject = mapAggAR.get(mapId);
            Double ValueMax = Double.valueof(ARObject.get('maxfield'));
            Double ValueMin = Double.valueof(ARObject.get('minfield'));

            //calculate fields on the record where ParentId is the Account Parent Id
            if (cv.Parent_Account__c == mapId){
                cv.Max = ValueMax;
                cv.Min = ValueMin;
            }
        }

}

I get the error

Error: Invalid Data.  Review all error messages below to correct your
  data. Apex trigger triggerUpdateObject caused an unexpected exception,
  contact your administrator: triggerUpdateObject: execution of
  BeforeUpdate caused by: System.ListException: Row with null Id at
  index: 0: Trigger.triggerUpdateObject: line 25, column 1

That is the line where I generate the map mapAggAR. I have created accurate test records, so there should be Ids available. So what is wrong? Thanks for your help!


text: Q: Find a shoot angle looking at a photograph Is there a way to find which anlges a photograph is shoot from? Using a protractor or some other tool. At least for objects which we can say are staying at right angle. For example for an item on a store shelf.


text:
Q: I get the error message "Inconsistent accessibility" What is wrong?
I am getting the following error:

Inconsistent accessibility: return type 'List<Employee>' is less accessible than method 'Profile.GetEmployee(byte)'

A: Without seeing more of your code, it's hard to discern what the problem is.  Usually you get this error when you have inconsistent member availability.  My guess is that your Employee entity isn't public.
If you post your Profile and Employee classes, I may be able to provide more input.
You also might want to check here: Inconsistent Accessibility: Parameter type is less accessible than method


text:
Q: can't push upstream using EGit I use EGit in eclipse to pull and push.
my config is:
  [remote "origin"]
    fetch = refs/heads/*:refs/remotes/origin/*
    push = refs/heads/*:refs/remotes/origin/*

local branch is master
Remote Tracking branch is origin/master
when I do push, it comes out "origin/master:master[up to date]". Actually the remote branch is not up to date. I wander if I configure the wrong way.
Sometimes I change different configure, I will get either "create a new branch"(which is wrong, as I just push some commits) or "reject-no fast forward"(which is strange, as I am the only user of the remote repository and I have already fetch before push)

A: Check with Egit if you aren't in a detached HEAD mode:

If HEAD is "detached", i.e. is not pointing to the tip of a local branch but to a commit or tag, then none or several "checked-out" markers may appear in the tree, since any number of remote branch or tags may point to the currently checked out commit.
  The state you are in while your HEAD is detached is not recorded by any branch (which is natural --- you are not on any branch).

(See "Why did git detach my head?" for probable cause, and "Git: How can I reconcile detached HEAD with master/origin?" for reconciliation).
That is a common cause for an "up to date" message when pushing to a remote repo.

A:
After I push to upstream successfully, like version 0.3.9, I continue to change my codes locally and submit a version 0.5.0. This submit should based on version 0.3.9. I don't know why. That's why I have to do merge every time, and sometimes merge make my codes messy.


text:
Q: Django Template If does not work as expected i'm trying to create a HTML drop-down with Django that shows the numbers 1 - 250 in the template and always selects the last selection after reloading the page. For this i use a variable "clea" to get the value with "request.GET.get('clea')" from the url in my "views.py" to pass it as context.
To select the value in the drop-dwon I have the following syntax:
        # Context: {"VIEW": {"clea": "140"}

        <label style="color: white;">Amount</label>
        <select class="browser-default" id="clea">

        {% for _ in ''|center:250 %}

        <script>console.log("{{ forloop.counter }}" == "{{ data.VIEW.clea }}")</script>

        {% if "{{ forloop.counter }}" == "{{ data.VIEW.clea }}" %}

          <script>console.log("Worked")</script>
          <option value={{ forloop.counter }} selected> {{ forloop.counter }} </option>

        {% else %}

          <option value={{ forloop.counter }}> {{ forloop.counter }} </option>

        {% endif %}

        {% endfor %}

        <script>console.log("Finished")</script>

      </select>

Everything works except the If Statement from Django Template!
In the log you can see that it always logs false, except if forloop.counter and data.VIEW.clea are equal, then its true, as expected. But it will never log "Worked", although it logs "true" in the line above.
Does anyone know what this could be?

A: I would suspect the if statement contains things that you did not intend.
This:
{% if "{{ forloop.counter }}" == "{{ data.VIEW.clea }}" %}

just compares two hard-coded strings: "{{ forloop.counter }}" and "{{ data.VIEW.clea }}". And they are always different, so the clause is always false.
Try avoiding the quotes (see example of a similar usage):
{% if forloop.counter == data.VIEW.clea %}

Make sure data.VIEW.clea is an integer though.


text:
Q: Set image in image-tag using rails 3. I want to set one image in image tag using RoR. That image path is fetched from DB and it has to set inside image tag.I have done some coding but unable to display that image.It also showing the following error.
Error:
SyntaxError in Homes#home

Showing C:/Site/swargadwara_puri/app/views/homes/home.html.erb where line #209 raised:

C:/Site/swargadwara_puri/app/views/homes/home.html.erb:209: syntax error, unexpected $undefined
...",:height => "140",:border => \'0\',:class =>\'borderblackdi...
...                               ^
C:/Site/swargadwara_puri/app/views/homes/home.html.erb:223: syntax error, unexpected ')', expecting keyword_end
');     else
  ^
Extracted source (around line #209):

206:

207:

208:

209:
<% image_tag("<%= @hcsy.D_Photo %>",:height => "140",:border => '0',:class =>'borderblackdiv' ) %>

210:
Deceased Photo

211:

212:

Please check my below line.

<% image_tag("<%= @hcsy.D_Photo %>",:height => "140",:border => '0',:class =>'borderblackdiv' ) %>

Please help me to resolve this error and display this image successfully.

A: Try this,

<%= image_tag("#{@hcsy.D_Photo}",:height => "140",:border => '0',:class =>'borderblackdiv' ) %>

Changes are: <% image_tag... to <%= image_tag and "<%= @hcsy.D_Photo %>" to "#{@hcsy.D_Photo}"
Edited
change "<%= @hcsy.D_Photo %>" to "/#{@hcsy.D_Photo}"


text:
Q: Memcached error for apache httpd 2.4 I created an EC2 instance with Apache HTTPD 2.4 with mod_ssl version 2.4.34.  I've created a Memcached cluster on AWS ElastiCache version 1.6.17 with encryption in transit.
The goal is to have HTTPD use MemCached with TLS for the SSLSessionCache.  However, whenever a request is received, the server logs the following:
vhosts.conf
...
SSLSessionCache memcache:test-memcache.2dr943.cfg.use1.cache.amazonaws.com:11322
...

ssl_error_log
Could not find specified socket in poll list.: AH00790: scache_mc: error setting key 'mod_ssl-session:162534f25cf4152836459039d4c99263a346345e9366230f9a00394f593abcab' with 1447 bytes of data

I can verify the Memcached cluster is accessible and functional by using openssl s_client -connect test-memcache.2dr943.cfg.use1.cache.amazonaws.com:11322.
It seems HTTPD is unable to connect to the Memcache service with encryption in-transit.  Any ideas how to address the issue?


text:
Q: NSForegroundColorAttributeName doesn't change the Navigation Bar Button colors in MFMailComposeViewController. [[UINavigationBar appearance] setTitleTextAttributes: @{ NSForegroundColorAttributeName: navigationBarFontColor, NSFontAttributeName: navigationBarFont }];

I set all the button colors in my app via the above appearance proxy. It changes the color of the text for icons like "+" and back buttons like "< Home".
However, when I pop up a MFMailComposeViewController, the Cancel and Send button are in default iOS blue, and not in the color I've chosen like the rest of my application. Why is this?
        if ([MFMailComposeViewController canSendMail])
        {
            MFMailComposeViewController *mailController = [[MFMailComposeViewController alloc] init];
            mailController.mailComposeDelegate = self;

            [mailController setSubject:REPORTMISSING_SUBJECT];
            [mailController setToRecipients:[NSArray arrayWithObject:REPORTMISSING_RECEIPIENT]];

            [self presentViewController:mailController animated:YES completion:nil];
        }

A: As far as I know, the setTitleTextAttributes method can only change the title properties of the navigation bar and will not affect the buttons.
That said, if you still want to use this method to customize the title, try calling it right before creating your MFMailComposeViewController instance and it should work.
To change the cancel/send button colors you can use the tintColor property:
mailController.view.tintColor = navigationBarFontColor;

Or, you can use the appearance proxy for UIBarButtonItem. That should work too and will also let you change the font (again, you'll need to call it right before creating and presenting the mail composer):
[[UIBarButtonItem appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName: navigationBarFontColor, NSFontAttributeName: navigationBarFont } forState:UIControlStateNormal];


text:
Q: Creating a Single Argument Quicksort Function - Python I'm trying to learn how to create a standalone recursive quicksort function in Python but I'm having trouble. I'm tasked with accepting a single argument, the unsorted list, and partitioning the list for recursion within the same quicksort function.
def quicksort(copyLyst):
    low = len(copyLyst) - len(copyLyst)
    high = len(copyLyst) - 1

    # Base Case
    if high <= low:
        return

    center = low + (high - low) // 2
    pivot = copyLyst[center]

    first = low
    last = high

    # Partitioning
    done = False
    while not done:
        while copyLyst[first] < pivot:
            first = first + 1
        while pivot < copyLyst[last]:
            last = last - 1
        if first >= last:
            done = True
        else:
            swap = copyLyst[first]
            copyLyst[first] = copyLyst[last]
            copyLyst[last] = swap
            first = first + 1
            last = last - 1

    leftCopy = copyLyst[low:last + 1]
    quicksort(leftCopy)

    rightCopy = copyLyst[last + 1:high]
    quicksort(rightCopy)

I'm hoping to keep much of my original code as I can, because I'm still learning about data structures and I think that would help me the best conceptually.
I've tried adjusting the range on the left and right recursive calls, I tried rewriting the entire function in new variables, I've double checked that the index locations don't conflict.
I've gone through everything compared to my textbook. I don't know what I did wrong.

A: Your code has major flaws and you have some unnecessary steps and complications in your implementations. Let's look at what's wrong first.
Your low is always 0, so you don't need to compute it or include it in the center computation.
The second, and the most important part, is that you're keeping the pivot in its original place, but you are not accounting for that. So at some point, either your first or last index will point to the pivot, and your code treats it as the rest of the numbers. Take a look at the example below to better understand this:
copyLyst = [5, 3, 7, 4, 1]
pivot = 7
first = 5
last = 1

first(5) < pivot(7): # 5 stays, first points to the next element(3)
[5, 3, 7, 4, 1]
first(3) < pivot(7): # 3 stays, first points to the next element(7)
[5, 3, 7, 4, 1]
## now we are at the pivot, but the code doesn't know that
first(7) not < pivot(7): #we now look at the right side starting from last
[5, 3, 7, 4, 1]
last(1) < pivot(7): # 1 needs to move, based on your code, we swap it with the first, and what's the first here? It's the pivot. The list now looks like this:
[5, 3, 1, 4, 7]
# the last index now points at 4 and the first points at 1, and since 1 is before 4,
# your while loop terminates, but the list is not partitioned correctly

Your code structure is problematic, and I suspect that you're trying to follow some pseudocode that you have quite literally. So it might not be possible to preserve much of your current code while keeping it clean and simple.

*

*You can expand the base case. The high is never less than low since low is always zero. And you can base it on the length of the list:

if len(copyLyst) <= 1:
        return

*You should probably keep the pivot out of your way when you're performing the partitioning part. The easiest way is to place it at the very end, such as:

pivot = copyLyst[center]
# swap the pivot with the last element
copyLyst[center] = copyLyst[high]
copyLyst[high] = pivot
# move the last element pointer to the left (since it's pointing at the pivot)
high = high - 1

And then when you're done with the partitioning, you place it into its correct position (between the highest of the smaller-than-pivot number and the lowest of the larger-than-pivot number).

*The while loops that you have can cause you a lot of headaches to deal with, so instead of having two while loops that approach each other from different ends, you can iterate once and place any number smaller than the pivot at the beginning of the list (look at the example here https://www.geeksforgeeks.org/python-program-for-quicksort/).

I think you now have enough feedback to work with on solving your problem. Good luck.


text:
Q: JPanels one above the other I want to design a jFrame where there are three jButtons and a set of three jpanels one above the other. When we call a jPanel from the respective jButton , that pane will be displayed. It would appear to the user as if the same portion of the jFrame is displaying the content to be shown on clicking each jButton.But when i am trying to set the jPanels one above the other, they are being shown side by side thus elongating the jFrame horizontally. What should i do to put one jPanel over the other? Any other idea than jPanel which should do the work i intend to do would also be help !!

A: Your behavior sounds like you are using a FlowLayout. This will not "layer" anything. Instead us a CardLayout, which does exactly what you are trying to accomplish. You call method like show, next, and previous to navigate the panels. See How to Use CardLayout for more details.
Also there are probably hundreds of other examples here on so. Go through the cardlayout questions.
[Tip: navigate the different tabs like "votes" and "frequent" to filter to some of the better posts]
Here's one that uses the show() method to switch between two panels by name.


text:
Q: Adding an image as accessory view in UITableViewCell is not showing i am trying to add some labels and images as accessory view in UITableViewCell.
But it is not showing in table cell my code is
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit;
NSDateComponents* parts = [[NSCalendar currentCalendar] components:flags fromDate:[NSDate date]];

UILabel *lbTime = [[UILabel alloc]initWithFrame:CGRectMake(-80, -21, 99, 20)];
[lbTime setBackgroundColor:[UIColor clearColor]];
[lbTime setTextColor:[UIColor grayColor]];
[lbTime setFont:[UIFont systemFontOfSize:13]];
int hour = parts.hour;
NSString *amPm = @"Am";
if (hour>12) {
    hour = hour -12;
    amPm = @"Pm";
}
lbTime.text = [NSString stringWithFormat:@"%.02d:%.02d %@",hour,parts.minute,amPm];

UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 15, 15)];
imgView.image = [UIImage imageNamed:@"imgWhiteAero.png"];
cell.accessoryView = imgView;

UIView *view = [[UIView alloc]init];
[view addSubview:lbTime];
[view addSubview:imgView];
cell.accessoryView = view;
[view release];
[imgView release];

label is showing successfully but image is not
when i add only image as accessory view it becomes visible
    cell.accessoryView = imgView;
but when i add it in a UIView like above mentioned code it is not showing


text:
Q: Texture units and vertex arrays in OpenGL I'm trying to draw one cube with different textures for each face. I've come across many tutorials which state that in the display() routines, you need to enable all texture units before calling glDrawElements(). I do this my calling:
gl.glClientActiveTexture(GL.GL_TEXTURE0);
gl.glBindTexture(GL.GL_TEXTURE_2D, textureId);
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, getTexCoordBufferObject());
gl.glTexCoordPointer(2, GL.GL_FLOAT, 0, 0);

gl.glClientActiveTexture(GL.GL_TEXTURE1);
gl.glBindTexture(GL.GL_TEXTURE_2D, textureId+1);
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, getTexCoordBufferObject());
gl.glTexCoordPointer(2, GL.GL_FLOAT, 0, 0);

...

gl.glClientActiveTexture(GL.GL_TEXTURE5);
gl.glBindTexture(GL.GL_TEXTURE_2D, textureId+5);
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, getTexCoordBufferObject());
gl.glTexCoordPointer(2, GL.GL_FLOAT, 0, 0);

This all makes sense to me. What doesn't however is how I determine which texture I am referring to when I populate the buffers (e.g. when I load my model data).
Thanks
Chris

A: What you are looking for is a cube map. In OpenGL, you can define six textures at once (representing the size sides of a cube) and map them using 3D texture coordinates instead of the common 2D texture coordinates. For a simple cube, the texture coordinates would be the same as the vertices' respective normals. (If you will only be texturing plane cubes in this manner, you can consolidate normals and texture coordinates in your vertex shader, too!) Cube maps are much simpler than trying to bind six distinct textures simultaneously the way you are doing right now.
GLuint mHandle;
glGenTextures(1, &mHandle); // create your texture normally

// Note the target being used instead of GL_TEXTURE_2D!
glTextParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTextParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTextParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTextParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

glBindTexture(GL_TEXTURE_CUBE_MAP, mHandle);

// Now, load in your six distinct images. They need to be the same dimensions!
// Notice the targets being specified: the six sides of the cube map.
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGBA, width, height, 0,
    format, GL_UNSIGNED_BYTE, data1);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GL_RGBA, width, height, 0,
    format, GL_UNSIGNED_BYTE, data2);
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GL_RGBA, width, height, 0,
    format, GL_UNSIGNED_BYTE, data3);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GL_RGBA, width, height, 0,
    format, GL_UNSIGNED_BYTE, data4);
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GL_RGBA, width, height, 0,
    format, GL_UNSIGNED_BYTE, data5);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GL_RGBA, width, height, 0,
    format, GL_UNSIGNED_BYTE, data6);

glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
glTextParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

// And of course, after you are all done using the textures...
glDeleteTextures(1, &mHandle);

Now, when doing your shaders, you need the vertex shader to accept and/or pass 3D coordinates (vec3) instead of 2D coordinates (vec2).
// old GLSL style
attribute vec3 inTextureCoordinate;
varying vec3 vTextureCoordinate;

// more recent GLSL
in vec3 inTextureCoordinate;
out vec3 vTextureCoordinate;

In this example, your vertex shader would simply assign vTextureCoordinate = inTextureCoordinate. Your fragment shader then needs to accept that texture coordinate and sample the cube map uniform.
uniform samplerCube cubeMap;
...
gl_FragColor = textureCube(cubeMap, vTextureCoordinate);

Whew! That was a lot. Did I leave anything out?

A:
What doesn't however is how I determine which texture I am referring to when I populate the buffers (e.g. when I load my model data).

You are referring to whichever texture you last specified with the most recent ActiveTexture call -- that call doesn't actually do anything, it justs sets a hidden state which affects all subsequent calls that do anything with textures.

A: Selecting a texture on a per-face basis is usually hard on openGL (except for some recent cards that can index an array of textures, for instance with EXT_texture_array). The problem is usually avoided by packing all textures in one, like this.
In your very specific case, though, a cubemap is perfect - if you're really sure you'll just have cubes and nothing else.


text: Q: Android 2 cursors 1 listview I have an app that populates a listview from a cursor.  One of the items is gallons of water.  Recently I had a request to use liters as well so I wrote a settings page that lets people choose units.  I want to have the cursor still show the number of units of water in the listview but I also want to have a texview next to the number to say gallons or liters, whichever the second cursor pulls.  Is it possible to have one cursor put 10 items in a listview then another cursor put one item in that same listview?


text:
Q: Select a row by the value of one cell in jqxGrid I've got a little question about the use of jqxGrid from jqWidgets.
I'm trying to select a row of my table dynamically from another page. I explain myself:
My first page contains a list of users. I want that when I choose an user on this list, it opens a new page with, by exemple, the ID of my user returned in GET through PHP. And then, I want to generate a new grid, with less information, but with the user already selected.
I've found how to select a row by her index $('#grid').jqxGrid('selectrow', 10); but it's not working, because if one table is sorted or filtered, the index is changed...
So, is there any way to do this ?
Here's the code wich is called when selecting a row on first table:
$('#search_right').bind('rowselect', function(event){
    var iSocID = $('#search_right').jqxGrid('getcellvalue', event.args.rowindex, 'id');
    $("#soci_right").load('activites/soc.search.php?a=form&id='+iSocID);
    $('#content').jqxTabs('select', 3);
});

And here's the generation code of my second list:
var url = 'activites/soc.search.php';
    var source = {
        datatype: "json",
                datafields: [
                    { name: 'name', type: 'string'},
                    { name: 'id', type: 'int'},
                ],
                id: 'id',
                url: url,
                root: 'data'
    };

    dataSource = new $.jqx.dataAdapter(source);

    $("#soci_table").jqxGrid({
        source: dataSource,
        theme: jqxGlobalTheme,
        columnsresize: true,
        sortable: true,
        filterable: true,
        showfilterrow: true,
        columns: [
            { text: 'Name', dataField: 'name'},
            { text: 'ID', dataField: 'id',  hidden:true},
        ]
    });

A: After contacting the support of jqWidgets (who couldn't help me......) I've made a little snippet that does the tricks... But I think jqWidget should add this as a default functionnality of jqxGrid !
I paste you my code here, hope it'll help some of you !
    $('#search_right').bind('rowselect', function(event){
    var iSocID = $('#search_right').jqxGrid('getcellvalue', event.args.rowindex, 'id');

         // Create filter
        var filtergroup = new $.jqx.filter();
        var filtervalue = iSocID;
        var filtercondition = 'EQUAL';

        var filter1 = filtergroup.createfilter('stringfilter', filtervalue, filtercondition);

        var filter_or_operator = 1;
        filtergroup.addfilter(filter_or_operator, filter1);

        $("#soci_table").jqxGrid('addfilter', 'id', filtergroup);

        // Apply filter

        $("#soci_table").jqxGrid('applyfilters');

        // Select row

        $('#soci_table').jqxGrid('selectrow', 0);

        // Remove filter

        $("#soci_table").jqxGrid('clearfilters');
    });


text:
Q: Get all objects that belongs to a entity in a one-to-many relationship with core data I'm working on simple iPhone app and I'm trying to get core data working. I currently have two entities in my data model, it looks like this:

In my application I have a tableview that should display all pages that belongs to a certain note block. I currently use:
NoteblockAppController * appController = [NoteblockAppController sharedNoteblockAppController];
NSArray * list = [appController allInstancesOf:@"Page" orderBy:@"createdAt"];
noteblockPages = [list mutableCopy];

But this obviously doesn't work since it always shows the same pages. I assume that I have to fetch the result some other way, but I don't know how.
I'm quite stuck so any tips/tricks would be great.
Thanks.

A: Let CoreData do the work. You have an instance of the Noteblock, correct?
[yourNoteblock noteblockPages]

A: I like to add derived methods to access things like this.  I add these to the custom class but don't model them in the data model.
Once you get your accessor working correctly, it should return a mutable set.  Then:
- (NSArray *)noteblockPagesArray {
  NSMutableSet *pages = self.noteblockPages;
  NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:YES];

  NSArray *orderedPages = [pages sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
  return orderedPages;
}

Modify to cache value as appropriate/needed.


text:
Q: req.body reveals password when I console.log it in Node I am working with NodeJs in the backend and I console.log(req.body) from a form which is to collect user's username and password.
I discover that it reveals the username and password from that form.
Does this mean my code is vulnerable? Or is that how it ought to be?
Though the user's password is hashed and stored in a database.

A: Yes, req.body will contain any and all data passed to it, including the password.
Just don't send it to the console in your production environment.
Instead you use those values to validate the user, save in a DB or do whatever other logic you need to do.
If req.body didn't have the password then how would you be able to validate the user trying to log in?

A: Any form's data that you are sending to the server will necessarily be visible at the server.  This is normal.  This is how the client sends data to the server.
It is only insecure if you are running it over http (instead of https) such that connection points in the middle could see the password or such that your server's DNS could be hijaacked or if you do something insecure with it on the server (store it improperly, log it to log files, etc...).
If you are running over properly secured https and you hash the password on the server and store only a hash and have proper security measures for the security of your database, then you would be doing what most sites do.

A: If the printing is necessary in your code, you can use a environment flag, commonly I set an attribute in config.js, for example, "devMode":true, then I use this attribute for printing, for example:
const { devMode } = require('./config.js');
...
if(devMode) console.log('Hello World');
when You make a deploy for production, You only need to change devMode to false


text:
Q: How to use is_countable to count if there is a row in the tbl that would equal to it? I'm following a tutorial that will display the entire record of a person to input text boxes from table rows upon hitting the button and every thing seems okay and working however the if (count($result)==1) is showing Warning: count(): Parameter must be an array or an object that implements Countable tho it's working
Upon searching I've read that this count() already been an issue before with php 7.2 version but with php 7.3 they it was fixed by coming up with the is_countable. However as I tried putting is_countable the code isn't working.
with count() it is working but showing an error
with is_countable it is not working
The version of my php is 7.3.3
How to use is_countable properly in php 7.3.3?
count() it is working returning tbl row values on textboxes but showing an error - Warning: count(): Parameter must be an array or an object that implements Countable
if (count($result)==1) {
   #code
 }

is_countable it is not working totally
if (is_countable($result)==1) {
  #code
 }

I expect to see the values of rows from tbl to input textboxes
like the
$rlname = $row['lname'];

to show to
<input type = "text" name = "lname" value = "<?php echo $rlname ?>">

A: Thank you very much hemnath mouli, Nick and Mr Shunz it is now working after changing the
if (is_countable($result)==1) {
  $row = $result->fetch_array();
 }

to
if (mysqli_num_rows($result)==1) {
    $row = $result->fetch_array();


text:
Q: Custom column type with column options implied I've got a large number of Slick tables with an ID column defined as
def id = column[Int]("ID", O.PrimaryKey, O.AutoInc, O DBType "INT UNSIGNED")

and I'm wondering if there is a way to create a custom IDPK type that would somehow "imply" the usage of the various options shown above, e.g.
case class IDPK(id: Int) extends AnyVal

def id = column[IDPK]("ID")
  // O.PrimaryKey, O.AutoInc, O DBType "INT UNSIGNED" are all implied

I realize I could make a convenience function along the lines of def makeIDPK = column[Int]("ID", .....) but my question is about whether or not a type can be made to imply certain column options.
I've noticed that if I run show create table <tablename> there are options that I did not explicitly state, e.g. NOT NULL for non-Option columns, or DEFAULT NULL for Option columns. Because of this, I have hope for a "yes" answer, but I was unable to find something like this while looking through the Slick documentation.

A: you could define a function that receives type and creates a column.  Something like:
def makeColumn[T](name: String): Column[Int] =
  column[Int](name, O.PrimaryKey, O.AutoInc, O DBType "INT UNSIGNED")

def id = makeColumn("id")


text:
Q: Pandas min() of selected row and columns I am trying to create a column which contains only the minimum of the one row and a few columns, for example:
    A0      A1      A2      B0      B1      B2      C0      C1
0   0.84    0.47    0.55    0.46    0.76    0.42    0.24    0.75
1   0.43    0.47    0.93    0.39    0.58    0.83    0.35    0.39
2   0.12    0.17    0.35    0.00    0.19    0.22    0.93    0.73
3   0.95    0.56    0.84    0.74    0.52    0.51    0.28    0.03
4   0.73    0.19    0.88    0.51    0.73    0.69    0.74    0.61
5   0.18    0.46    0.62    0.84    0.68    0.17    0.02    0.53
6   0.38    0.55    0.80    0.87    0.01    0.88    0.56    0.72

Here I am trying to create a column which contains the minimum for each row of columns B0, B1, B2.
The output would look like this:
    A0      A1      A2      B0      B1      B2      C0      C1      Minimum
0   0.84    0.47    0.55    0.46    0.76    0.42    0.24    0.75    0.42
1   0.43    0.47    0.93    0.39    0.58    0.83    0.35    0.39    0.39
2   0.12    0.17    0.35    0.00    0.19    0.22    0.93    0.73    0.00
3   0.95    0.56    0.84    0.74    0.52    0.51    0.28    0.03    0.51
4   0.73    0.19    0.88    0.51    0.73    0.69    0.74    0.61    0.51
5   0.18    0.46    0.62    0.84    0.68    0.17    0.02    0.53    0.17
6   0.38    0.55    0.80    0.87    0.01    0.88    0.56    0.72    0.01

Here is part of the code, but it is not doing what I want it to do:
for i in range(0,2):
    df['Minimum'] = df.loc[0,'B'+str(i)].min()

A: This is a one-liner, you just need to use the axis argument for min to tell it to work across the columns rather than down:
df['Minimum'] = df.loc[:, ['B0', 'B1', 'B2']].min(axis=1)

If you need to use this solution for different numbers of columns, you can use a for loop or list comprehension to construct the list of columns:
n_columns = 2
cols_to_use = ['B' + str(i) for i in range(n_columns)]
df['Minimum'] = df.loc[:, cols_to_use].min(axis=1)

A: For my tasks a universal and flexible approach is the following example:
df['Minimum'] = df[['B0', 'B1', 'B2']].apply(lambda x: min(x[0],x[1],x[2]), axis=1)

The target column 'Minimum' is assigned the result of the lambda function based on the selected DF columns['B0', 'B1', 'B2']. Access elements in a function through the function alias and his new Index(if count of elements is more then one). Be sure to specify axis=1, which indicates line-by-line calculations.
This is very convenient when you need to make complex calculations.
However, I assume that such a solution may be inferior in speed.
As for the selection of columns, in addition to the 'for' method, I can suggest using a filter like this:
calls_to_use = list(filter(lambda f:'B' in f, df.columns))

literally, a filter is applied to the list of DF columns through a lambda function that checks for the occurrence of the letter 'B'.
after that the first example can be written as follows:
calls_to_use = list(filter(lambda f:'B' in f, df.columns))
df['Minimum'] = df[calls_to_use].apply(lambda x: min(x), axis=1)

although after pre-selecting the columns, it would be preferable:
df['Minimum'] = df[calls_to_use].min(axis=1)


text:
Q: How to boot load the kernel using EFI stub (efistub) loader? I have Ubuntu 14.04 running in UEFI mode as only operating system, no dual-boot here. The kernel version is 3.13.0-24-generic. There is an EFI partition. In this case the EFI partition is not at the default /dev/sda1 but at /dev/sda3 because I did actually convert BIOS mode to EFI mode. I have used the grub-efi-amd64 package, though that actually loads GRUB boot menu from UEFI firmware boot menu (UEFI boot loads \EFI\ubuntu\grubx64.efi).
I want to skip that double boot menu loading step, and boot faster, directly from UEFI into the kernel. The Ubuntu kernels since 12.10 have "Kernel EFI stub loader" feature.
I know I do need to copy the Ubuntu kernel to the EFI partition (possibly rename) and create an entry in UEFI boot menu (for instance using efibootmgr). Which exact terminal commands are necessary to do this?

A: According to the Debian wiki, this can be done in a few simple steps that will survive a kernel update.
Note: this assumes that you have an EFI partition mounted at /boot/efi.

*

*Create /etc/kernel/postinst.d/zz-update-efistub with the following contents:
#!/bin/sh
cp /vmlinuz /initrd.img /boot/efi/EFI/ubuntu/

This is a hook that will be ran on kernel update to copy the latest kernel image and initrd to the appropriate location. Then make it executable and run it:
sudo chmod +x /etc/kernel/postinst.d/zz-update-efistub
sudo /etc/kernel/postinst.d/zz-update-efistub

*Add the boot entry:
sudo efibootmgr -c -d /dev/sdb -p 1 -L "Ubuntu (efistub)" -l /EFI/ubuntu/vmlinuz -u "root=/dev/sdb2 rw initrd=/EFI/ubuntu/initrd.img quiet splash"

Don't forget to change the -d and -p arguments depending on where your EFI system partition is. In my case, it is /dev/sdb1, but this is likely to be different for you. You will probably also have to change the root= value in the kernel cmdline to your root partition.
(You can change the label to anything you want by changing the -L parameter.)
The boot entry you just added will become the default entry. And it won't break after a kernel update, since the hook will make sure vmlinuz and initrd.img are always updated.

A: The commands below are more generic then for kernel version 3.13.0-35 only.
1. Mount the efi partition and copy the kernel files there

$ mount /dev/sda3 /boot/efi
$ mkdir -pv /boot/efi/EFI/ubuntu/
$ cp -uv /boot/vmlinuz-* /boot/initrd.img-* /boot/efi/EFI/ubuntu/
'/boot/vmlinuz-3.13.0-35-generic' -> '/boot/efi/EFI/ubuntu/vmlinuz-3.13.0-35-generic'
'/boot/initrd.img-3.13.0-35-generic' -> '/boot/efi/EFI/ubuntu/initrd.img-3.13.0-35-generic'

2. Change the kernel file name
Shorten the kernel file name by removing -generic because there seems to be a 39 character length path limit and Rename kernel file(s) to end in .efi, this ensures compatibility with most systems

$ for f in /boot/efi/EFI/ubuntu/vmlinuz-*-generic; do mv -uv -- "$f" "${f//-generic/}.efi"; done
'/boot/efi/EFI/ubuntu/vmlinuz-3.13.0-35-generic' -> '/boot/efi/EFI/ubuntu/vmlinuz-3.13.0-35-generic.efi'`

The above name kernel file name shortening is not enough for a dpkg installed mainline kernel, because for example /EFI/ubuntu/vmlinuz-3.16.0-031600rc6.efi without -generic is still 40 characters long.
3. Add new entry to EFI boot menu
Replace 3.13.0-35 in this example with your specific kernel version

$ kv=3.13.0-35;efibootmgr -c -p 3 -L $kv -l \EFI\ubuntu\vmlinuz-$kv.efi -u root=/dev/sda1 initrd=\\EFI\\ubuntu\\initrd.img-$kv-generic ro rootfstype=ext4 debug ignore_loglevel libata.force=dump_id crashkernel=384M-:128M

This new boot menu entry will become your default new boot choice.
You might not need the extra debugging parameters debug, ignore_loglevel, libata.force=dump_id and crashkernel=384M-:128M. Initrd must be present, otherwise boot hangs at "Switched to clocksource tsc." because the root device sda1 cannot be opened.


text:
Q: How to save a string temporary variable in assembly x86-64 Im new to assembly and I've to write the memmove function in assembly x86-64, and it said :

The memmove() function copies n bytes from memory area src to memory area dest. The memory areas may overlap: copying takes place as though the bytes in src are first copied into a temporary array that does not overlap src or dest, and the bytes are then copied from the temporary array to dest.

Nevertheless, I don't find a way to save a temporary string in assembly, and that's why I am posting this.
I tried to put in rax register, but I got a segmentation fault :
mov r8b, byte [rsi + rcx] ; rsi is source string
mov byte [rax + rcx], r8b

By the way, I'm using nasm -f elf64 memmove.asm on my build
Thank you.

A: Machine instruction MOVSB
will be your friend in copying memory areas. It copies one byte from memory addressed by RSI
to the memory addressed by RDI and then modifies both registers to the next element (byte).
SECTION .data
Memory   DB '0123456789'
Src1st   EQU Memory+0
SrcLast  EQU Memory+4
Dest1st  EQU Memory+3
DestLast EQU Memory+7
SECTION .text
   LEA RSI,[Src1st]
   LEA RDI,[Dest1st]
   CLD

We can visualize memory layout before MOVSB this way
  RSI   RDI
   |     |
   0 1 2 3 4 5 6 7 8 9
   _________        Src
         _________  Dest

After MOVSB
    RSI   RDI
     |     |
   0 1 2 0 4 5 6 7 8 9

With instruction prefix REP it is repeated RCX times.
After
MOV RCX,DestLast-Dest1st+1
REP MOVSB
                RSI   RDI
                 |     |
       0 1 2 0 1 2 0 1 8 9

This doesn't work as expected when Src and Dest areas overlap - instead of 0120123489 we've got 0120120189.
When the destination field is above the source (RDI>RSI), we must copy backward (set Direction Flag)
and start with registers pointing at the end of fields.
   LEA RSI,[SrcLast]
   LEA RDI,[DestLast]
   MOV RCX,DestLast-Dest1st+1

          RSI   RDI
           |     |
   0 1 2 3 4 5 6 7 8 9

After
   STD
   REP MOVSB

RSI   RDI
 |     |
   0 1 2 0 1 2 3 4 8 9

Source field is copied verbatim to the destination without temporary array, not wasting memory and clocks. The direction flag should be reset to its default state after backward copy, which is expected by interface of most operational systems and library functions.


text:
Q: Data Structure for Spatial Agent Based Modeling What are some good data structures for keeping track of agents in a two-dimensional, spatial simulation?
I've seen some references to quadtrees (which I understand) and kd-trees (which I don't understand very well).
I'm looking for something through which an agent can efficiently say, "I know my location, and I would like to know which agents are near me (within a certain radius of myself)."
Examples (pseudo-code is fine) would be greatly appreciated.
I'm working in Java.

A: Well, I'm not sure exactly how it is implemented, but the MASON toolkit uses a discretization algorithm that places agents that are close to one another in the same "bucket" of a hash table. It makes for very fast lookups, as only a few of these buckets have to be checked for each query.
The best thing for you is probably to take a look at the source code here:
http://code.google.com/p/mason/source/browse/trunk/mason/sim/field/continuous/Continuous2D.java?r=529

A: I have found something called a Bucket PR Quadtree.


text:
Q: Understanding parts of this BLDC driver schematic I have a couple of question on ST's STSPIN32F0A 3-phase BLDC driver and I was hoping someone can help me figure out some parts of the schematic. The schematic shows the STSPIN32F0A (pg. 1) connected to the onboard ST-LINK debugger via the SWD pins (SWD_IO and SWD_CLK, pins PA13 and PA14 respectively) and also via the UART lines (pins PB6 and PB7).
The SWD lines are for programming the STSPIN32F0A correct? What role is the UART playing here? THere doesn't seem to be any specific firmware for the onboard ST-LINK on the product page. Does this mean it has some custom firmware that isn't public?

A: I will do my best to answer that.
STM designs their development board so that there is a possibility to communicate with a PC using uart trough the onboard ST Link.
This is called virtual COM port (VCP)

A: SWD is for programming the firmware into the STM32F031 microcontroller embedded inside the STSPIN32F0A, as well as debugging the running code through an ST-LINK programmer/debugger. As @Alex Fedoseev mentions, the UART can be used as a serial port (again through an ST-LINK if it's embedded in the demo board, which seems to be the case) for bidirectional communication. It should also be usable to load a firmware through the embedded bootloader.


text:
Q: Reverting to a git branch I'm using TortoiseGit, and I want to go back to the end of a branch last committed three days ago. I've hard reset a couple of times but since I'm unfamiliar with git I risk doing something foolish and would appreciate help.
Looking at the image here:

'master' is currently set at the version made at 17:40:56 on 10 Jan. This is where I'd like the latest version to be both locally and remotely. (Some text redacted in this image).
However, I see that origin/HEAD and origin/master are at the version made at 11:04:01 on 13 Jan (today).
So for clarity, I want to revert to the end of the green branch, and make that version the master version. What must I do to get there?
Please say if I need to provide more information...

A: You should be able to right click on that commit referenced by master, select push, and select the "force" option in order to push --force your master onto the remote.
("Force Overwrite Existing Branch (May discard changes)")
Make sure to communicate that to other using that same remote repo, because you would be changing an history that others might already have pulled from.

A: I have partial answer to your question. I don't know tortoisegit so what are the black and red lines in the graph? I imagine the green is master branch. Is this image for local repo? What is your current branch name?
Using git on commandline/terminal window you can do following.
You can move HEAD to any commit. For brevity, lets say the SHA of Jan 10th 17:40:56 commit is c. If this is your commit history/log.
a----b----c----d----e <-- master branch
                    ^
                    HEAD

So, doing git checkout c should set the HEAD where you want leaving the later commits in place.
a----b----c----d----e <-- master branch
          ^
          HEAD

This is called detached state. If you do git branch, it says so. You can continue to do new commits from this point, but since they are not referenced by any branch, git can garbage collect them.
Alternately, if you want to delete commits d and e and move HEAD to c, do git reset --hard c. If you want to leave d and e changes in there but move HEAD and master branch to c, do git reset --soft c. You'll see the d and e as changes to be committed in git status.