text:
Q: Format STR_TO_DATE to a date Hi I have been able to extract a VARCHAR to a date using string_to_date, however whatever I try the date always echoes as e.g. 2009-05-25
Here is my code that works:
$query = "SELECT u.url_id, url, title, description, STR_TO_DATE( pub_date, '%d-%b-%Y')
    AS pub_date FROM urls AS u, url_associations AS ua WHERE u.url_id = ua.url_id AND
    ua.url_category_id=$type AND ua.approved = 'Y' ORDER BY pub_date DESC";
$result = mysql_query ($query);
echo "

{$row['pub_date']}

\n";

I have tried DATE_FORMAT and similar methods but I either receive 2009-05-25 or blank.
Can anyone help me solve this issue. I am looking and testing but I have decided to ask for help here as the assistance is welcomed and those who helped previously were very kind.
Thanks
Sean

A: The return type of STR_TO_DATE is DATE which is returned to PHP.
It's PHP that formats dates in your echo, not MySQL.
To do the formatting on MySQL side, use:
DATE_FORMAT(STR_TO_DATE( pub_date, '%d-%b-%Y'), '%Y.%m.%d')

or other format.
The inner format controls how your string is expected to be stored in the database, the outer format controls how will it be output.
To do the formatting on PHP side (which is better as you can honor culture specific formats for different users), use:
echo date('Y m d', strtotime($row['pub_date']))

A: From this reference site following are mysql command and output
mysql> SELECT DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y');
        -> 'Sunday October 2009'
mysql> SELECT DATE_FORMAT('2007-10-04 22:23:00', '%H:%i:%s');
        -> '22:23:00'
mysql> SELECT DATE_FORMAT('1900-10-04 22:23:00',
    ->                 '%D %y %a %d %m %b %j');
        -> '4th 00 Thu 04 10 Oct 277'
mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00',
    ->                 '%H %k %I %r %T %S %w');
        -> '22 22 10 10:23:00 PM 22:23:00 00 6'
mysql> SELECT DATE_FORMAT('1999-01-01', '%X %V');
        -> '1998 52'
mysql> SELECT DATE_FORMAT('2006-06-00', '%d');
        -> '00'


text:
Q: Replacing Day/Month format with Year on a Squarespace Template I'm using Squarespace's Foundry template and it displays dates in a "Mon Day" format. I'd like instead to display the year (and only the year) of publication. A member of this community helped someone else change the way the months displayed in the same template (Change date format on a template); I'm wondering if someone might be able to help me with this other, similar challenge, too.
If you're able to help me with this, would you also be able to let me know where in the template to inject the Javascript? (I actually have not had success getting the month-display code to work even as a test -- I tried it to see if I could play with it and change it myself, but it didn't work, and I wonder whether I'm inserting it in the wrong place?).
Thank you so much, regardless,
Maggie

A: The following Javascript, inserted via site code injection, ought to do the trick:

In the Home Menu, click Settings, click Advanced, and then click Code Injection.

Use the "Footer" injection area.
<script>
    (function() {
        var dates = document.getElementsByClassName("dt-published date-highlight");
        var date;
        var i,I;

        // Loop through all dates, replacing inner HTML with date from 'datetime' attribute.
        for (i=0, I=dates.length; i<I; i++) {
            date = dates[i];
            date.innerHTML = date.getAttribute("datetime").split("-")[0];
        }
    })();
</script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: I have a problem with an if-else statement Whenever I run the following code, it always runs the else statement, not the if. It works perfectly when I don't have the or operator, but I need to use it. I don't know what to do!
print('What is your favourite Pokemon?')
FavPokemon = input()
if FavPokemon == ('Pikachu' or 'pikachu'):
    print('Me too!')
else:
    print('Cool! ' + FavPokemon + ' is a good Pokemon. My favourite is Pikachu though!')

A: The statement isn't working because or doesn't do what you think it does.  The expression ('Pikachu' or 'pikachu') evaluates to a single string, 'Pikachu'.  The == then compares against that only.
What you probably want is:
if FavPokemon in ('Pikachu', 'pikachu'):

A: print('What is your favourite Pokemon?')
 FavPokemon = input()
 if FavPokemon == 'Pikachu' or FavPokemon == 'pikachu':
     print('Me too!')
 else:
     print('Cool! ' + FavPokemon + ' is a good Pokemon. My favourite is Pikachu though!')

Is what your code needs to be. Your if statement needs to be changed. The expression before, If x == (a or b) will always evaluate to true. You were not checking if the FavPokemon variable was actually Pikachu or pikachu, you were checking is the condition (a or b) is true, which in that syntax, it is always true.
See https://www.w3schools.com/python/python_conditions.asp

A: Programming languages are not natural languages and have different (and much stricter) grammars.
In natural languages, we all understand that "if a is equal to b or c" actually means "if a is equal to a or a is equal to b", but in programming language the formaly similar statement "if a == b or c" is parsed "if (expression) == (other expression)". Then each expression is evaluated (replaced with it's current final value) and only then the equality test is done. So
if a == b or c:

is really:
d = b or c
if a == d:

Now the expression b or c returns the first of b or c which has a true value. Since in Python a non-empty string as a true value, your code:
if FavPokemon == ('Pikachu' or 'pikachu'):

is really:
name = ('Pikachu' or 'pikachu')
if FavPokemon == name:

and since 'Pikachu' is a non empty strings, this ends up as:
name = 'Pikachu'
if FavPokemon == name:

or more simply:
if FavPokemon == 'Pikachu':

The general rule is that if you want to test against multiple conditions, you have to write it explicitely, ie:
if a == b or a == c:

or
if a == b and x != y:

etc
Now if you want to test whether one object (string or whatever) is part of a collection of objects (tuple, list, etc), you can use the in operator:
a = 5
if a in (4, 5, 6):
    # ...

But in your case, since what you want is to test against the capitalized or uncapitalized version of the same word, you could instead transform the user's input (FavPokemon) in a "normalized" version and test against the "normalized" version of your string, ie instead of:
if FavPokemon in ('Pikachu', 'pikachu'):

you could write:
 FavPokemon = FavPokemon.lower()
 if FavPokemon == 'pikachu':

Note that this will be a bit less strict than the in version as it will accept "pIkachU" or "PIKACHU" or just any combination of upper/lowercase - but for your use case that's usually what's expected.

A: Working Code:
print('What is your favourite Pokemon?')
FavPokemon = input()
if (FavPokemon == 'Pikachu' or FavPokemon == 'pikachu'):
    print('Me too!')
else:
    print('Cool! ' + FavPokemon + ' is a good Pokemon. My favourite is Pikachu though!')

Useful Links
python-or-operator/

A: EXPLANATION OF YOUR MISTAKE
You have done a little syntax mistake in writing the if statement. You have written
if FavPokemon == ('Pikachu' or 'pikachu'):
Here u have kept 'Pikachu' or 'pikachu' within parenthesis and checked FavPokemon outside that parenthesis with that == assignment operator sign.Doing these causes an error as it is unable to check with the condition.
CORRECT CODE
Correct code will be if you put the whole FavPokemon == 'Pikachu' or FavPokemon =='pikachu'into a parenthesis.This way it checks that whether FavPokemon is "Pikachu" or FavPokemon is "pikachu" and gives you the correct result.
The correct code will be:
print('What is your favourite Pokemon?')
FavPokemon = input()
if (FavPokemon == 'Pikachu' or FavPokemon =='pikachu'):
print('Me too!')
else:
print('Cool! ' + FavPokemon + ' is a good Pokemon. My favourite is Pikachu though!')


text:
Q: Wrong millimeter values for standard paper sizes at Wikipedia? On the Wikipedia page https://en.wikipedia.org/wiki/Paper_size there are tables for standard paper sizes. The table "ANSI and CAN paper sizes" has paper size values expressed in inches and millimeters. For example, the ANSI D paper size is expressed as "22 × 34 inches" or "559 × 864 mm". But when you calculate the conversion by multiplying the inches values with 25.4 to get the millimeter values you get:
22 * 25.4 = 558.8
and:
34 * 25.4 = 863.6
So, is my calculation wrong or are the millimeter values on the Wikipedia page wrong? Because there is no mention about rounding on the Wikipedia page. (Assuming the ANSI paper sizes were originally defined as inches and then converted into millimeters).

A: Having written a good part of said article, I can confirm that we are trying to enforce a sensible number of significant digits. This usually results in rounding to the nearest millimeter.
From time to time, a random user believes that conversions should be more (i.e. overly) precise and hence changes one table or the other. Such edits may go by unnoticed for a while, so the article may not always be 100% consistent. The rounding policy isn't stated in the article explicitly, because it follows from Wikipedia's Manual of Style
I'm not sure whether ANSI or any other American standardization body specifies tolerances for paper sizes, but in ISO 216 and DIN 476 they are at least 1 mm and up to 3 mm for longer sides. That means, millimeter precision in conversions from inch values is arguably even too correct. Canadian standards rounded Letter etc. dimensions to the closest half-centimeter which might more accurately reflect actual American paper sizes.
The most common inch-based paper sizes are specified with a precision of half an inch. For other sizes, it rarely goes beyond a quarter inch, i.e. about 6 mm. Even if we assume a precision of half that for the definitions, we are still very well on the safe side in rounding converted metric values to the nearest millimeter.


text:
Q: Adding JTextFields hard code free I am trying to write code for a program that will give users a hardcoded amount of JTextFields from top to bottom, with an option to add additional JTextFields. I have to retrieve user imported data from each JTextField afterwards. How do I do this?
All JTextFields are added to a JPanel.

A: Do something like this:
    ArrayList<JTextField> list = new ArrayList<JTextField>();
    //add all the hardcoded JTextFields to this list
    //b is a button which the user clicks to add extra TextFields
    b.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            JTextField a = new JTextField();
            panel.add(a);//panel is the existing panel
            list.add(a);
        }
    });
}

So with the help of 'list' you can later retrieve all the text fields


text:
Q: XBMC 13.2 linker error on Raspberry Pi: undefined references to COMXImage and g_OMXImage I have tried to compile XBMC 13.2 Gotham on my Raspberry Pi using DistCC to speed up compilation. When it comes to linking, I got the following error:
AR      xbmc/cores/paplayer/paplayer.a
LD      xbmc.bin
xbmc/linux/linux.a(RBP.o): In function `CRBP::Initialize()':
RBP.cpp:(.text+0x468): undefined reference to `COMXImage::Initialize()'
RBP.cpp:(.text+0x4d0): undefined reference to `g_OMXImage'
xbmc/linux/linux.a(RBP.o): In function `CRBP::Deinitialize()':
RBP.cpp:(.text+0x7cc): undefined reference to `COMXImage::Deinitialize()'
RBP.cpp:(.text+0x878): undefined reference to `g_OMXImage'
collect2: ld returned 1 exit status
distcc[24757] ERROR: compile (null) on localhost failed
distcc[24756] ERROR: compile (null) on localhost failed
Makefile:541: recipe for target 'xbmc.bin' failed
make: *** [xbmc.bin] Error 1

The COMXImage class is present in the source code of xbmc/cores/omxplayer.
For compile preparation I used the commands from RaspbianXBMC.
The source code has been checked out from the XBMC Github Repository using tag 13.2.
I have run ./boostrap and ./configure with the following options:
./configure --build=arm-linux-gnueabihf --with-platform=raspberry-pi \
--disable-gl --enable-gles --disable-x11 --disable-sdl --enable-ccache \
--enable-optimizations --enable-external-libraries --disable-goom \
--disable-hal --disable-pulse --disable-vaapi --disable-vdpau \
--disable-xrandr --disable-airplay --disable-alsa --enable-avahi \
--enable-libbluray --enable-dvdcss --disable-debug --disable-joystick \
--enable-mid --enable-nfs --disable-profiling --disable-projectm \
--enable-rsxs --enable-rtmp --enable-optical-drive --enable-libcec

Before complete compilation i fetched and successfully built TAGLIB and libcec from their own git repositories using the latest version.
I could provide the output of ./configure if this might help.
Thanks for your help!

A: open RBP.cpp file
and remove lines containing
g_OMXImage.Initialize()
and
if (m_omx_image_init)
   g_OMXImage.Deinitialize();
and then try to re-compile


text:
Q: Find process id when Process.Start returns null? If I try to open an image file, or video, or website by calling Process.Start(filepath) directly, then it will typically succeed. However, the return value of Process.Start will sometimes be null. (As discussed here)
I need to know the associated process's id so that I can retrieve it later and close it if necessary. (Use case: User opens an image file using my program, and would like to close it using my program) However, it's kind of hard to retrieve the process id of a process that returns null :P
Any suggestions on how I should go about this, other than maybe specifying directly which program to use for each type of file we may encounter?

A: You have to specify directly which program to use to get the id of the process.  I can imagine you can ask the os what program to use for each extensions as the os has a list of those.


text:
Q: How to pass variable from one html to a php file login.html file contains :
<A HREF="welcome.php?name=Kevin"> Hi, I'm Kevin! </A>

welcome.php file contains :
<?php
$name = $_GET['name'];
echo( "Welcome to our Web site, $name!" );
?>

While I run login.html it redirect to welcome.php but gives following error:
Notice: Undefined variable: name in C:\xampp\htdocs\train\welcome.php on line 2
Welcome to our Web site, !


text:
Q: input file for Webpack Encore I'm on Symfony 3.4
I want to use Webpack Encore
I Have followed these instructions:
https://symfony.com/doc/3.4/frontend/encore/simple-example.html
I had to follow these steps https://stackoverflow.com/a/53231113/4277724
I must be clause but now in my generated html I have:
<link href="/build/app.css?2" rel="stylesheet" />

Whereas it must be something like:
<link href="/my-app/web/app_dev.php/build/app.css" rel="stylesheet"/>

What am I missing ?

A: Ok I just add that in my webpack.json
.setPublicPath('/my-app/web/build')


text:
Q: Is there a single word for people/ consultants who partner with our health? We made a card for hospitals which introduces the doctors to its patients.
We named the card Meet Your Healers, but we need a new word to replace Healers now.

A: Well, healer does have that meaning, but alas it is more often use of non-medical approaches.
"Health care professionals" and "health care practitioners" are both commonly used expressions, with the former in particular often used in such contexts.


text:
Q: Ignore header in join command (outdated coreutils) I have two CSV files to be joined on a column, I am using unix join command, I want to ignore the header while joining, I was using --header option in GNU core utils v8.21, but my product machine has core utils v8.4, --header is not available in GNU core utils 8.4, I cannot upgrade the core utils in production machine. Is there a way to skip the header(first line and join the files)
join --header -t, -1 3 -2 2 <File1> <File2> -o 2.1,1.2,2.2,2.3,2.4,2.5,2.6,2.7

A: If you can't use --header, help yourself out with tail
join <(tail -n+2 file1) <(tail -n+2 file2)


text:
Q: Excel VBA - Ignore continuous blank lines while save as a file I am having some content in Sheet1 and I am doing some manipulations and writing them in Sheet2.
The objective is to write the Sheet2 into a .txt file. The range is always going to be A1:A2320 from Sheet2. So I loop and print them in the output file.
The problem I face is post manipulation there are a set of blank lines getting into the output file and it is always having 2321 lines (This is expected as per my code). I need to remove all subsequent blank lines in the range A1:A2320 before printing, only if there is more than one continuous blank.
For Example if this is the sheet Temp after manipulation
A
B

C

D

E

.

This should be written as
A
B

C

D
E
.

This is what I made so far
Private Sub Make_Click()

Dim numFields As Integer
Dim numRows As Integer
Dim curField As Integer
Dim curRow As Integer
Dim tmpText As String
Dim outputFile As Variant

numFields = 1
numRows = 2320
curField = 1
curRow = 1

outputFile = Application.GetSaveAsFilename(InitialFileName:=ActiveWorkbook.Path _
            & "\", filefilter:="Text Files (*.txt), *.txt", _
            Title:="Output file name (will overwrite)")
If outputFile = False Then
    Exit Sub
End If
On Error GoTo failed
Open outputFile For Output As #1

For curRow = 1 To numRows
  For curField = 1 To numFields
    tmpText = ActiveWorkbook.Sheets("Temp").Cells(curRow, curField).Value
    Print #1, tmpText;
    If curField < numFields Then
      Print #1, vbTab;
    End If
  Next curField
  Print #1, vbLf;
Next curRow
Close #1

MsgBox "File " & outputFile & " written. " & numFields & " fields, " & numRows & " rows."

Exit Sub

failed:
On Error Resume Next
Close #1
MsgBox "Couldn't create/overwrite file."

End Sub

A: If you are only dealing with one column of data, then checking for blanks is trivial. And if you are always only dealing with column A, why are you stepping through columns? You could use a counter to keep track of how many blank lines you have in a row...
Dim counter As Integer
counter = 0
...
For curRow = 1 To numRows
    tmpText = ActiveWorkbook.Sheets("Temp").Cells(curRow, 1).Value
    If Len(tmpText) > 0 Then
        If counter = 1 Then
            Print #1, vbLf
        End If
        Print #1, tmpText
        Print #1, vbLf
        counter = 0
    Else
        counter = counter + 1
    End If
Next curRow

We just delay printing the single blank line until we find the next non-blank. Now if you want to keep a single blank when it occurs on the last row, you will need to stick an if statement on the end of this code.


text:
Q: Some ReactiveCocoa Design Pattern Questions Sorry for the multi-question post, but they're all somewhat related. I apologize if some of this is obvious, I'm still trying to wrap my head around ReactiveCocoa.
I have a UIViewController that's being passed a RACSignal whose values it needs to display. This signal will either emit a model object immediately if it already exists on the device, or if the model needs to be fetched, when the fetch finishes; so, basically the signal is a promise. This allows me to remove all knowledge of network from the view controller.

*

*if the user dismisses the view controller, I no longer need whatever the signal will emit. Is this a normal thing to do in the view controller?
- (void) dealloc
{
    [_modelSignalDisposable dispose] ; // Dispose of the subscription to the signal
}

*Let's say that the device loses its connection while a model fetch is occurring, and this causes the signal to emit an error. In this case I may display something like a reload button to let the user try again. When the user taps the reload button, can I just resubscribe to the same signal even though it's completed? If not, how do I "reset" the signal? Remember, the view controller can't really re-create the signal from scratch since it has no knowledge of how it was created to begin with.

*The signal in question is actually a subclass of RACSubject called a Command (has nothing to do with a RACCommand). The idea behind it is that the Command starts network fetching on subscribe and thus overrides -subscribe: to start a network operation. If the view controller goes out of scope due to user interaction I'd like for the subscription disposal to cancel any related fetch operations. Is this the right pattern?
- (RACDisposable *) subscribe:(id<RACSubscriber>)subscriber
{
    RACDisposable *rd = [super subscribe:subscriber] ;
    [self.remoteService startFetching] ;
    @weakify(self);
    return [RACDisposable disposableWithBlock:^
        {
            @strongify(self) ;
            [self.remoteService cancelFetching] ;
            [rd dispose] ;
        }] ;
}

A:
if the user dismisses the view controller, I no longer need whatever the signal will emit. Is this a normal thing to do in the view controller?

Yep, that's totally reasonable. Though I'd use -takeUntil:self.rac_willDeallocSignal instead, so that I don't have to bother with keeping the disposable around.

Let's say that the device loses its connection while a model fetch is occurring, and this causes the signal to emit an error. In this case I may display something like a reload button to let the user try again. When the user taps the reload button, can I just resubscribe to the same signal even though it's completed? If not, how do I "reset" the signal? Remember, the view controller can't really re-create the signal from scratch since it has no knowledge of how it was created to begin with.

You can simply re-subscribe if the signal is a cold signal. That is, if the signal does something on subscription. Usually this means you created the signal with +[RACSignal createSignal:].

The signal in question is actually a subclass of RACSubject called a Command (has nothing to do with a RACCommand). The idea behind it is that the Command starts network fetching on subscribe and thus overrides -subscribe: to start a network operation. If the view controller goes out of scope due to user interaction I'd like for the subscription disposal to cancel any related fetch operations. Is this the right pattern?

You have the right idea, but you can just use +[RACSignal createSignal:] instead of subclassing RACSubject.


text:
Q: Сортировка списка файлов по размеру с помощью Python задача банальная для людей разбирающихся в программировании.
В организации есть сетевой диск объемом 1 Тб с различными типами файлов, из-за ограниченности объема его приходится постоянно чистить вручную. Идея такая - с помощью Python проходить по всему диску, на выходе получать имя файла(Полный путь) и размер, в html документе чтобы строка с результатом  была ссылкой к файлу.

A: import os, time

def _get_files(path: str):
    """проходить по всему диску, на выходе получать имя файла(Полный путь)"""
    for (root, dirs, files) in os.walk(path):
        for file in files:  # файлы
            full_name = os.path.join(root, file)
            yield full_name
        for folder in dirs:  # поддиректории
            p = os.path.join(root, folder)
            normpath = os.path.normpath(p)
            yield from _get_files(normpath)  # рекурсия

def get_files(path: str):
    for file in _get_files(path):
        size = os.path.getsize(file)  # размер
        time_create = time.strftime('%H:%M:%S %m.%d.%y', time.gmtime(os.path.getmtime(file)))
        yield size, file, time_create  # порядок сортировки, размер идет первым

if __name__ == '__main__':
    it = get_files('c:\\SCR\\STAND\\')
    files = sorted(it)  # Сортировка списка файлов по размеру

    with open('_test.html', 'w') as f:  # в html документе
        f.write('')
        for (size, file, time_create) in files:  # чтобы строка с результатом была ссылкой к файлу.
            lk = '{f}
{t}
{s}

'.format(f=file, s=size, t=time_create)
            f.write(lk)
        f.write('')

A: Предложу этот вариант генерации:
import os
from os.path import join
import time

def get_files_info(dir_name):
    for root, dirs, files in os.walk(dir_name):
        for file_name in files:
            abs_file_name = join(root, file_name)

            yield abs_file_name, os.stat(abs_file_name)

def sizeof_fmt(num):
    for x in ['bytes', 'KB', 'MB', 'GB']:
        if num < 1024.0:
            return "%3.1f %s" % (num, x)

        num /= 1024.0

    return "%3.1f %s" % (num, 'TB')

def get_date_as_string(dt):
    return time.strftime('%H:%M:%S %m.%d.%y', time.gmtime(dt))

if __name__ == '__main__':
    dir_name = r"D:\Program Files (x86)\Microsoft Office"

    # Сортировка по размеру
    files_sorted_by_size = sorted(get_files_info(dir_name), reverse=True, key=lambda x: x[1].st_size)

    # # Без сортировки
    # files_sorted_by_size = get_files_info(dir_name)

    # Сохраняем в HTML файл
    with open('result.html', 'w', encoding='utf-8') as f:
        f.write('''

                <meta content='text/html; charset=UTF-8' http-equiv='Content-Type'/>

        ''')

        f.write('<capture>{}</capture>'.format(dir_name))

        f.write('
{}	{}	{}
'.format('FILE NAME', 'SIZE', 'LAST MODIFICATION'))

        for file_name, file_stat in files_sorted_by_size:
            f.write('
')

            f.write('{}	{}	{}	'.format(
                '{f}'.format(f=file_name),
                sizeof_fmt(file_stat.st_size),
                get_date_as_string(file_stat.st_mtime)
            ))

            f.write('
')

        f.write('''

        ''')

Скриншот (размер 80%):

PS. как видно по коду, генерации HTML может код несколько усложнить, поэтому для упрощения можно использовать шаблонизатор для генерации текста – jinja.


text:
Q: SQL 2012 code that spatially polyline fine (join file) to a point file (target) and provides Distance Field I am currently working in ArcMap 10.2.2 but would like the SQL code to create the same output as that provided by the Spatial Join tool.
Target feature = point, Join Feature = polyline, Option CLOSEST and a Distance field generated and shown in new shapefile.
I have been struggling with the STDistance function but this is only for "a" distance between a single pair of geometries.

A: Here's a link to MSDN on Nearest Neighbour queries.  Luckily you are using 2012 so the indexes will be used.
A query like his should be close to what you want.
SELECT pl.ID polyID, pt.ID pointID, pt.Distance
FROM Polygon pl
    CROSS APPLY (
        SELECT TOP 1 p.ID, p.SHAPE.STDistance(pl.SHAPE) Distance
        FROM Point p
        WHERE p.SHAPE is not null
        ORDER BY p.SHAPE.STDistance(pl.SHAPE)
        ) pt;

This query will find the closest point to each polygon

A: Many thanks for the quick reply - I have however been able to reconcile the distance values between the two methods (ArcMap/SQL spatial tool/Cross Apply).  I apologize for the distraction and appreciate the code and link.   I know I am squarely on my way.


text:
Q: php - array not outputting all values I have a small issue i can't seem to work around. i have some data i'm pulling from the database and before i display the data, i want to manipulate some values in there. here's my function handling these:
public function getPageContent($id)
{
    $menutopic_model = new Menu_Topic();
    $content = $menutopic_model->getAllContent($id);

    //var_dump($content);

    $data = array();

    foreach ($content as $value)
    {
         $title = explode(',', $value->title);
         $filename = explode(',', $value->filename);

         $data['topicname'] = $value->topicname;
         $data['title'] = $title;
         $data['filename'] = $filename;

    }

   //var_dump($data);

}

Now, when i dump var_dump($content);, i get the entire array of data as it should be:
array(2) {
    [0]=>
    object(stdClass)#346 (3) {
      ["topicname"]=>
      string(19) "Signs giving orders"
      ["title"]=>
      string(42) "Stop,No entry,No cycling,No motor vehicles"
      ["filename"]=>
      string(179) "DQP0GVcUA2dG8ZfqeVYLO68YodgYnJMOjJw2o2iC.png,vWUcHGX3VVKPT08JXh9mAqZ40pT0vfDJ78Yoqovz.png,bplX8bbwHzHKX9n6SvvQiYNhkWwKxi2bhsrQ94U2.png,8KAEovxQn3EgzHoZg1euSgNYTFupnLdKusJ4SIEP.png"
    }
    [1]=>
    object(stdClass)#345 (3) {
      ["topicname"]=>
      string(13) "Warning Signs"
      ["title"]=>
      string(111) "Road narrows ahead both sides,Road narrows on right (left if symbol reversed),Crossroads,Junction on bend ahead"
      ["filename"]=>
      string(179) "uZ7fnDjlYfKU3pdSQ7wAq4siFryA6jSEitmRyPhp.png,4pslo6cC0I2E606DscWxiDD3sCBW7ZGaESQES4r0.png,xdVBMpV6PTLtX48M67kfWOqy59rsYMDZMuWbqDwl.png,hLtIGikARgARqmSqit4mqNXRFJthipH6O5vqxlbN.png"
    }
  }

but after passing the data through the foreach, this var_dump($data); only returns the last item in the array:
array(3) {
  ["topicname"]=>
  string(13) "Warning Signs"
  ["title"]=>
  array(4) {
    [0]=>
    string(29) "Road narrows ahead both sides"
    [1]=>
    string(47) "Road narrows on right (left if symbol reversed)"
    [2]=>
    string(10) "Crossroads"
    [3]=>
    string(22) "Junction on bend ahead"
  }
  ["filename"]=>
  array(4) {
    [0]=>
    string(44) "uZ7fnDjlYfKU3pdSQ7wAq4siFryA6jSEitmRyPhp.png"
    [1]=>
    string(44) "4pslo6cC0I2E606DscWxiDD3sCBW7ZGaESQES4r0.png"
    [2]=>
    string(44) "xdVBMpV6PTLtX48M67kfWOqy59rsYMDZMuWbqDwl.png"
    [3]=>
    string(44) "hLtIGikARgARqmSqit4mqNXRFJthipH6O5vqxlbN.png"
  }
}

what should i change in the above to get the correct result?

A: You were getting only last value just because you were over-writing values in array with the below code, which you were using.
$data['topicname'] = $value->topicname;
$data['title'] = $title;
$data['filename'] = $filename;

Changed code:
public function getPageContent($id)
{
    $menutopic_model = new Menu_Topic();
    $content = $menutopic_model->getAllContent($id);

    $data = array();

    foreach ($content as $value)
    {
         $title = explode(',', $value->title);
         $filename = explode(',', $value->filename);

         $data[]=array(
             'topicname'=>$value->topicname,
             'title'=>$title,
             'filename'=>$filename);
    }

     //var_dump($data);

 }

A: You are reusing the same array occurance each time round the loop. So create your array and then add it asa new occurance to the real array
public function getPageContent($id)
{
    $menutopic_model = new Menu_Topic();
    $content = $menutopic_model->getAllContent($id);

    //var_dump($content);

    foreach ($content as $value)
    {
        $title = explode(',', $value->title);
        $filename = explode(',', $value->filename);

        $d = array();
        $d['topicname'] = $value->topicname;
        $d['title'] = $title;
        $d['filename'] = $filename;

        $data[] = $d;
    }

   //var_dump($data);

}


text:
Q: Изменение размера виджета пользователем Можно ли каким-либо способом сделать изменение размера QWidget пользователем. То есть с помощью растягивания мышью.
Update:  изменение размера QWidget нужно сделать со всех сторон.
main.py
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class DragButton(QPushButton):

    def mousePressEvent(self, event):
        self.__mousePressPos = None
        self.__mouseMovePos = None
        if event.button() == Qt.LeftButton:
            self.__mousePressPos = event.globalPos()
            self.__mouseMovePos = event.globalPos()

        super(DragButton, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            currPos = self.mapToGlobal(self.pos())
            globalPos = event.globalPos()
            diff = globalPos - self.__mouseMovePos
            newPos = self.mapFromGlobal(currPos + diff)
            self.move(newPos)

            self.__mouseMovePos = globalPos

        super(DragButton, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if self.__mousePressPos is not None:
            moved = event.globalPos() - self.__mousePressPos
            if moved.manhattanLength() > 3:
                event.ignore()
                return

        super(DragButton, self).mouseReleaseEvent(event)

if __name__ == "__main__":
    app = QApplication([])
    w = QWidget()
    w.resize(800,600)

    button = DragButton("Drag", w)

    w.show()
    app.exec_()

И как суда изменение размера вставить?

A: Я обновил свой ответ Есть ли виджеты в PyQt5, размер которых может изменять пользователь? с учетом ваших пожеланий, попробуйте.
from PyQt5 import QtCore, QtGui, QtWidgets

class SizeGrip(QtWidgets.QSizeGrip):
    def __init__(self, location_angle, parent):
        super().__init__(parent)

        parent.installEventFilter(self)
        self.setFixedSize(30, 30)
        self.location_angle = location_angle

        if self.location_angle == 'left_top':
            self.polygon = QtGui.QPolygon([
                QtCore.QPoint(10, 20),
                QtCore.QPoint(20, 10),
                QtCore.QPoint(10, 10),
            ])
        elif self.location_angle == 'right_top':
            self.polygon = QtGui.QPolygon([
                QtCore.QPoint(20, 10),
                QtCore.QPoint(20, 20),
                QtCore.QPoint(10, 10),
            ])
        elif self.location_angle == 'left_bottom':
            self.polygon = QtGui.QPolygon([
                QtCore.QPoint(10, 20),
                QtCore.QPoint(20, 20),
                QtCore.QPoint(10, 10),
            ])
        elif self.location_angle == 'right_bottom':
            self.polygon = QtGui.QPolygon([
                QtCore.QPoint(10, 20),
                QtCore.QPoint(20, 10),
                QtCore.QPoint(20, 20),
            ])

    def eventFilter(self, source, event):
        if event.type() == QtCore.QEvent.Resize:
            if self.location_angle == 'left_top':
                geo = QtCore.QRect(0, 0, 30, 30)
                self.setGeometry(geo)
            elif self.location_angle == 'right_top':
                _geo = self.rect()
                _geo.moveBottomRight(source.rect().bottomRight())
                x = _geo.x()
                geo = QtCore.QRect(x, 0, 30, 30)
                self.setGeometry(geo)
            elif self.location_angle == 'left_bottom':
                _geo = self.rect()
                _geo.moveBottomRight(source.rect().bottomRight())
                y = _geo.y()
                geo = QtCore.QRect(0, y, 30, 30)
                self.setGeometry(geo)
            elif self.location_angle == 'right_bottom':
                geo = self.rect()
                geo.moveBottomRight(source.rect().bottomRight())
                self.setGeometry(geo)
        return super().eventFilter(source, event)

    def paintEvent(self, event):
        qp = QtGui.QPainter(self)
        qp.setPen(QtCore.Qt.white)
        qp.setBrush(QtCore.Qt.red)
        qp.drawPolygon(self.polygon)

class Container(QtWidgets.QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.sizeGrip1 = SizeGrip('left_top', self)
        self.sizeGrip2 = SizeGrip('right_top', self)
        self.sizeGrip3 = SizeGrip('left_bottom', self)
        self.sizeGrip4 = SizeGrip('right_bottom', self)

        self.startPos = None
        layout = QtWidgets.QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        self.setStyleSheet('''
            Container {
                background: lightblue;
                border: 0px;
                border-radius: 4px;
            }
        ''')

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.startPos = event.pos()

    def mouseMoveEvent(self, event):
        if self.startPos:
            self.move(self.pos() + (event.pos() - self.startPos))

    def mouseReleaseEvent(self, event):
        self.startPos = None

class GraphicsRoundedFrame(QtWidgets.QGraphicsProxyWidget):
    def __init__(self):
        super().__init__()

        self.container = Container()
        self.setWidget(self.container)

    def addWidget(self, widget):
        self.container.layout().addWidget(widget)

    def paint(self, qp, opt, widget):
        qp.save()
        p = QtGui.QPainterPath()
        p.addRoundedRect(self.boundingRect().adjusted(0, 0, -.5, -.5), 4, 4)
        qp.setClipPath(p)
        super().paint(qp, opt, widget)
        qp.restore()

class View(QtWidgets.QGraphicsView):
    def __init__(self):
        super().__init__()

        scene = QtWidgets.QGraphicsScene()
        self.setScene(scene)
        self.setRenderHints(QtGui.QPainter.Antialiasing)
        scene.setSceneRect(0, 0, 1024, 768)

        texture = QtGui.QImage(30, 30, QtGui.QImage.Format_ARGB32)
        qp = QtGui.QPainter(texture)
        qp.setBrush(QtCore.Qt.white)
        qp.setPen(QtGui.QPen(QtGui.QColor(189, 190, 191), 2))
        qp.drawRect(texture.rect())
        qp.end()
        scene.setBackgroundBrush(QtGui.QBrush(texture))

        testFrame = GraphicsRoundedFrame()
        scene.addItem(testFrame)
        testFrame.container.layout().addStretch(1)

        self.label_2 = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
        self.label_2.setPixmap(QtGui.QPixmap("lena.jpg").scaled(100, 100))
        testFrame.addWidget(self.label_2)
        testFrame.addWidget(QtWidgets.QLabel(
            'lena.jpg', alignment=QtCore.Qt.AlignCenter))
        testFrame.container.layout().addStretch(1)

        testFrame.addWidget(QtWidgets.QPushButton('I am a button'))

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = View()
    w.show()
    sys.exit(app.exec_())


text:
Q: How to keep dropdown item list on top I have a dropdown menu, that looks like this:

Location

Dubai

Sharjah

Ras Al Khema

This is the css I use to style it:
body {
font-family: 'Lato', 'Arial', sans-serif;
background: #ddd url(../images/bg.jpg);
font-weight: 300;
font-size: 15px;
color: #333;
-webkit-font-smoothing: antialiased;
overflow-y: scroll;
overflow-x: hidden;
}

a {
color: #555;
text-decoration: none;
}

.container {
width: 100%;
position: relative;
}

.clr {
clear: both;
padding: 0;
height: 0;
margin: 0;
}

.main {
width: 90%;
margin: 0 auto;
position: relative;
height:400px;
}

.container > header {
margin: 10px;
padding: 20px 10px 10px 10px;
position: relative;
display: block;
text-shadow: 1px 1px 1px rgba(0,0,0,0.2);
text-align: center;
}

.container > header h1 {
font-size: 30px;
line-height: 38px;
margin: 0;
position: relative;
font-weight: 300;
color: #666;
text-shadow: 1px 1px 1px rgba(255,255,255,0.7);
}

.container > header h2 {
font-size: 14px;
font-weight: 300;
margin: 0;
padding: 15px 0 5px 0;
color: #888;
font-family: Cambria, Georgia, serif;
font-style: italic;
text-shadow: 1px 1px 1px rgba(255,255,255,0.9);
}
@import url('demo.css');
@import url('font-awesome.css');

/* GLOBALS */

*,
*:after,
*:before {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 0;
margin: 0;
}

::selection {
background: transparent;
}

::-moz-selection {
background: transparent;
}

.wrapper-demo {
margin: 60px 0 0 0;
*zoom: 1;
font-weight: 400;
}

.wrapper-demo:after {
clear: both;
content: "";
display: table;
}

.wrapper-dropdown-3 {
/* Size and position */
position: relative;
width: 200px;
margin: 0 auto;
padding: 10px;

/* Styles */
background: #fff;
border-radius: 7px;
border: 1px solid rgba(0,0,0,0.15);
box-shadow: 0 1px 1px rgba(50,50,50,0.1);
cursor: pointer;
outline: none;

/* Font settings */
font-weight: bold;
color: #8AA8BD;
}

.wrapper-dropdown-3:after {
content: "";
width: 0;
height: 0;
position: absolute;
right: 15px;
top: 50%;
margin-top: -3px;
border-width: 6px 6px 0 6px;
border-style: solid;
border-color: #8aa8bd transparent;
}

.wrapper-dropdown-3 .dropdown {
/* Size & position */
position: absolute;
top: 140%;
left: 0;
right: 0;

/* Styles */
background: white;
border-radius: inherit;
border: 1px solid rgba(0,0,0,0.17);
box-shadow: 0 0 5px rgba(0,0,0,0.1);
font-weight: normal;
-webkit-transition: all 0.5s ease-in;
-moz-transition: all 0.5s ease-in;
-ms-transition: all 0.5s ease-in;
-o-transition: all 0.5s ease-in;
transition: all 0.5s ease-in;
list-style: none;

/* Hiding */
opacity: 0;
pointer-events: none;
}

.wrapper-dropdown-3 .dropdown:after {
content: "";
width: 0;
height: 0;
position: absolute;
bottom: 100%;
right: 15px;
border-width: 0 6px 6px 6px;
border-style: solid;
border-color: #fff transparent;
}

.wrapper-dropdown-3 .dropdown:before {
content: "";
width: 0;
height: 0;
position: absolute;
bottom: 100%;
right: 13px;
border-width: 0 8px 8px 8px;
border-style: solid;
border-color: rgba(0,0,0,0.1) transparent;
}

.wrapper-dropdown-3 .dropdown li a {
display: block;
padding: 10px;
text-decoration: none;
color: #8aa8bd;
border-bottom: 1px solid #e6e8ea;
box-shadow: inset 0 1px 0 rgba(255,255,255,1);
-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-ms-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;
}

.wrapper-dropdown-3 .dropdown li i {
float: right;
color: inherit;
}

.wrapper-dropdown-3 .dropdown li:first-of-type a {
border-radius: 7px 7px 0 0;
}

.wrapper-dropdown-3 .dropdown li:last-of-type a {
border: none;
border-radius: 0 0 7px 7px;
}

/* Hover state */

.wrapper-dropdown-3 .dropdown li:hover a {
background: #f3f8f8;
}

/* Active state */

.wrapper-dropdown-3.active .dropdown {
opacity: 1;
pointer-events: auto;
}

/* No CSS3 support */

.no-opacity       .wrapper-dropdown-3 .dropdown,
.no-pointerevents .wrapper-dropdown-3 .dropdown {
display: none;
opacity: 1; /* If opacity support but no pointer-events support */
pointer-events: auto; /* If pointer-events support but no pointer-events support */
}

.no-opacity       .wrapper-dropdown-3.active .dropdown,
.no-pointerevents .wrapper-dropdown-3.active .dropdown {
display: block;
}

Here's an image of this problem to explain it.

A: You need to use z-index to 'push' the active item to the 'front'.
You would set a lower z-index on your 'inactive' menu item and a higher z-index on your 'active' state of the menu items. Something like:
.wrapper-dropdown-3 .dropdown {
 z-index: 1;
}

/* Active state */

    .wrapper-dropdown-3.active .dropdown {
    opacity: 1;
    pointer-events: auto;
    z-index: 2;
    }

Here's a very useful article on z-index:
http://philipwalton.com/articles/what-no-one-told-you-about-z-index/


text:
Q: Syntax error preventing CREATE EVENT CREATE EVENT demo
    ON SCHEDULE
      EVERY 2 SECOND
    DO BEGIN

      update alarm set is_on=1;

    END

Error
SQL query:
CREATE EVENT demo
    ON SCHEDULE
      EVERY 2 SECOND
    DO
      BEGIN
      update alarm set is_on=1;

MySQL said: Documentation

1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near '' at line 6

A: You need to change the delimiter when you run DDL statements like this. MySQL is interpreting your semicolon as the end of your CREATE EVENT query, not as a delimiter within it.
Try this:
DELIMITER $$
CREATE EVENT demo
    ON SCHEDULE
      EVERY 2 SECOND
    DO BEGIN

      update alarm set is_on=1;

    END $$
DELIMITER ;


text:
Q: Major problems after trying to install Spotify I wanted to get the Spotify Linux app but I must have stuffed up the relatively simple instructions as now I can't update anything and I keep getting notifications telling me a major error has occurred.
Can someone help me either to remove this or repair it please? I'm somewhat new to Ubuntu, still a bit of a newbie but know basic stuff so please be detailed with any help :)
I'm on 14.04 running dual boot
C:~$ sudo apt-get purge spotify

E: Type 'sudo' is not known on line 2 in source list /etc/apt/sources.list.d/spotify.list E: The list of sources could not be read.
E: Type 'sudo' is not known on line 2 in source list /etc/apt/sources.list.d/spotify.list
E: The list of sources could not be read

A: I don't know how this happened (perhaps someone can enlighten me) but the solution is simple.
Open /etc/apt/sources.list.d/spotify.list as root
gksu gedit /etc/apt/sources.list.d/spotify.list

Remove all information from the file and replace it with
deb http://repository.spotify.com stable non-free

Save the file and update the sources
sudo apt-get update

Now you can install spotify
sudo apt-get install spotify-client


text:
Q: How do I make this code output a specific fibonacci term in ARM assembly? So, in this code I take user input for a specific term in the fibonacci series. And I want to output the number. I made a forloop and attempted to print the result. However the error it gives is "collect2: error: ld returned 1 exit status". Does not execute. Also there are little resources for this assembly syntax, so I can't really learn it well.
Code:
.cpu cortex-a53
.fpu neon-fp-armv8

.data

string: .asciz "Enter a Fibonacci term: "
scan: .asciz "%d"
result: .asciz "The %dth Fibonacci number is: %d\n"

.text
.align 2
.global main
.type main, %function

main:

push {fp, lr} @pushes on to stack
add fp, sp, #4 @adds the bytes to the stack

ldr r0, =string @loads string prompt into r0
bl printf @prints the string
sub sp, sp, #4 @allocates memory for sp
ldr r0, =scan @loads scan into r0
mov r1, sp @sp is moved to r1
bl scanf @branches to scanf

add sp, sp, #4 @creates bytes on stack

forloop:

cmp r0, #0 @compares user input to 0
bgt myexit @closes program if input is 0
mov r2, #0 @stores first term of fib
mov r3, #1 @stores second term of fib
add r2, r2, r3 @adds r2 & r3 then overwrites r2
bl forloop

ldr r6, =result
bl printf


text:
Q: Mobile First 8 application does not reconnect after time in background Technologies:

*

*IBM Mobile First 8

*Ionic v1.x

Problem description:
I use the application... then, I put it in background some time, but when I try to use it after that time passes, the application cannot connect to MFP server; therefore, I have to close the app to use it again.
I tried to solve this issue putting the next line on the onResume event: WLAuthorizationManager.obtainAccessToken().then(), but it does not work.
Thanks!


text:
Q: Functions with cyclic derivatives
Possible Duplicate:
Functions that are their Own nth Derivatives for Real n

Popular function like sine, cos, Sinh, exp, etc. Have the property where for some fixed natural number k and all natural n
$y^{(nk)}=y$
Is the family limited in some sense? Is there a general solution to this whole set of differential equations?

A: These are all of the form $e^{ax}$ for $a$ being an $n^{\text{th}}$ root of $1$ or linear combinations of them.  For example, $\sin(x)=\frac{e^{ix}-e^{-ix}}{2i}$ and $i$ is a $4^{\text{th}}$ root of $1$


text:
Q: JSP thinks my conditional is a block statement This is a snippet code for a little JSP servlet I'm writing to manage a PostgreSQL, which JSP claims is invalid.
<% if (request.getParameter("student-id") != null &&
    request.getParameter("sname") != null &&
    request.getParameter("date-of-birth") != null &&
    request.getParameter("email") != null &&
    request.getParameter("level") != null) {
        String update = "UPDATE students SET name = '" + request.getParameter("sname") + "', " +
        "date_of_birth = '" + request.getParameter("date-of-birth") + "', " +
        "email = '" + request.getParameter("email") + "', " +
        "level = '" + request.getParameter("level") + "' " +
        "WHERE student_id = " request.getParameter("student-id");
        statement.executeUpdate(update);
} %>

For some reason, this throws a nasty error at me complaining about a lack of a semicolon:
An error occurred at line: 65 in the jsp file: /students.jsp
Generated servlet error:
Syntax error, insert ";" to complete BlockStatements

Line 65 is where I open the <%

A: in this line you forget to put plus sign
"WHERE student_id = " request.getParameter("student-id");

and may I suggest String.format() as a better, clearer way to build the sql statement

A: there is a missing '+' after where student_id="    at this place
<% if (request.getParameter("student-id") != null && request.getParameter("sname") != null && request.getParameter("date-of-birth") != null && request.getParameter("email") != null && request.getParameter("level") != null) { String update = "UPDATE students SET name = '" + request.getParameter("sname") + "', " + "date_of_birth = '" + request.getParameter("date-of-birth") + "', " + "email = '" + request.getParameter("email") + "', " + "level = '" + request.getParameter("level") + "' " + "WHERE student_id = "+ request.getParameter("student-id"); statement.executeUpdate(update); } %>


text:
Q: GraphQL Strapi - how to query with where clause using array of IDs? I'm using Strapi GraphQL as a backend for my Nuxt app, and am trying to perform a query where I find images using an array of IDs. Right now, supplying an empty array returns all images when instead I need the query to return an empty array of Images.
images.gql:
query($ids:[ID]) {
  images(where:{id:$ids}) {
    id
    name
    slug
    src {
      url
      formats
    }
  }
}

query variables:
{
  "ids": [] <-------- returns all images; need to return empty array of Images
}
{
  "ids": [6] <--------- returns image with ID of 6 correctly
}

Looking at the Strapi documentation I've also tried other filters such as [field]_in but that is still returning all Images instead of an empty array.
Does anyone have a suggestion? Thanks!


text:
Q: included MySQLStore.h but HAVE_MYSQL not defined error (quickfix VS2015 c++) i using quickfix c++
when i want store data to mysql db and using MySQLStoreFactory class(include with mysqlstore.h) it show top error
i also included mysql include path and libs but didn't change
so any Idea??

A: SOLVED!!
i downloaded new MYSQL server LIB
put library address additional library directory dependency for tradeclient project

change name of libmysql.lib to libMySQL.lib in mysql server folder

add libMySQ.lib  name in linker ->input->additioanl dependency

put mysql include in C/C++ include directory

put "libmysql.dll" in release folder
build and run in cmd

and all Done !


text:
Q: Setting Up Prebid and Receiving CORB Error We're setting up prebid in our local environment with four ad networks; we aren't able to see ads.
I think it's possible that we haven't seen ads because of our local environment, but we're also seeing the ad below.

Cross-Origin Read Blocking (CORB) blocked cross-origin response https://securepubads.g.doubleclick.net/pagead/adview?ai=CzJ-9F0shW-7gKMj0-QP47YOQA97b-JFS5vHE8psHwI23ARABINGH0iBgyd74hsij6BmgAezprP8CyAEC4AIAqAMByAOZBKoEygFP0NBysRA0tLgwsgOml3PLPkm7yeGllYSfrEI4KYzuge5CkRTMSG_L2x2PRFevb3-01ht38BRruNB8m4zFcB2gbarxmwFcfohrQPX_mTsRwKpfrcuhQctY7FJ4L2v98E5JjqHXbgIC0GiGA6ok-cyq5AmUs4nTyXrPEi_SyQSO0jwdm2W_flNYF6SfN7nE3eBmxyuFg1YFwN-mOj_rw4_MIlUCOgi5XJ4Ci2gZV2FPOGVOINdWRgt9gBIq-u6u7XqBfhtfrP4UrtwMwASm1OKb4AHgBAGSBQQIBBgBkgUECAUYBKAGAoAH_7LRgAGoB47OG6gHjc0bqAfVyRuoB9nLG6gHz8wbqAemvhuoB5jOG6gH6c0b2AcB8gcEEKu0NtIIBwiAYRABGAHyCBthZHgtc3Vic3luLTI3NDYxMjc1MjcwMjgxNTaACgPYEww&sigh=TQAyHYAsHSo&dpt=1 with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.

Any help would be much appreciated!


text:
Q: How can I get rid of offset on head-rule? My headrule is offset throught my thesis. It looks like this:

I found a MWE that displays the same behaviour:
\documentclass{article}
\usepackage{titleps}% http://ctan.org/pkg/titleps

\expandafter\def\expandafter\normalsize\expandafter{%

    \setlength\abovedisplayskip{20pt}
    \setlength\belowdisplayskip{20pt}
    \setlength\abovedisplayshortskip{5pt}
    \setlength\belowdisplayshortskip{20pt}
}

\newpagestyle{main}{
\setheadrule{.4pt}% Header rule
\sethead{\thesubsection\ \subsectiontitle}% left
        {}%                                 center
        {\thesection\ \sectiontitle}%       right
}

\pagestyle{main}

\begin{document}

This is the introduction. This is the introduction. This is the introduction. This is the introduction. This is the introduction. This is the introduction. This is the introduction. This is the introduction.
\section{A section}

This is the introduction. This is the introduction. This is the introduction. This is the introduction. This is the introduction. This is the introduction.

\subsection{A subsection}
dsd
\subsubsection{A subsubsection}
\end{document}

I realized that the issue is caused by the command \expandafter\def\expandafter\normalsize\expandafter. If I remove it the issue disappears. However I cannot remove it as I need it for spacing equations.
What should I do?
Thanks

A: I think you've lost a bit of the code you're copying:
\documentclass{article}
\usepackage{titleps}

\expandafter\def\expandafter\normalsize\expandafter{%
  \normalsize
  \setlength\abovedisplayskip{20pt}%
  \setlength\belowdisplayskip{20pt}%
  \setlength\abovedisplayshortskip{5pt}%
  \setlength\belowdisplayshortskip{20pt}%
}

\newpagestyle{main}{%
  \setheadrule{.4pt}% Header rule
  \sethead{\thesubsection\ \subsectiontitle}% left
          {}%                                 center
          {\thesection\ \sectiontitle}%       right
}

\pagestyle{main}

\begin{document}

This is the introduction. This is the introduction.
This is the introduction. This is the introduction.
This is the introduction. This is the introduction.
This is the introduction. This is the introduction.

\section{A section}

This is the introduction. This is the introduction.
This is the introduction. This is the introduction.
This is the introduction. This is the introduction.

\subsection{A subsection}
dsd
\subsubsection{A subsubsection}

\end{document}

A \normalsize (that's expanded at redefinition time) was missing (and also some % were).

A simpler strategy would be
\documentclass{article}
\usepackage{titleps}
\usepackage{etoolbox}

\appto\normalsize{%
  \setlength\abovedisplayskip{20pt}%
  \setlength\belowdisplayskip{20pt}%
  \setlength\abovedisplayshortskip{5pt}%
  \setlength\belowdisplayshortskip{20pt}%
}

and the rest is the same.

A: I suggest that you replace
\expandafter\def\expandafter\normalsize\expandafter{%

with
\AtBeginDcoument{%

A full MWE (minimum working example):
\documentclass{article}
\usepackage{titleps}

\AtBeginDocument{%
    \setlength\abovedisplayskip{20pt}
    \setlength\belowdisplayskip{20pt}
    \setlength\abovedisplayshortskip{5pt}
    \setlength\belowdisplayshortskip{20pt}
}

\newpagestyle{main}{%
\setheadrule{.4pt}% Header rule
\sethead{\thesubsection\ \subsectiontitle}% left
        {}%                                 center
        {\thesection\ \sectiontitle}%       right
}
\pagestyle{main}

\begin{document}
\noindent
This is the introduction. This is the introduction.
This is the introduction. This is the introduction.
This is the introduction. This is the introduction.
This is the introduction. This is the introduction.

\section{A section}
This is the introduction. This is the introduction.
This is the introduction. This is the introduction.
This is the introduction. This is the introduction.

\subsection{A subsection}
dsd

\subsubsection{A subsubsection}
\end{document}


text:
Q: Order of accessing and Initializing Static Fields Java Consider the following example:
class Super{
   static String ID = "1234";
}
class Sub extends Super{
  static{ System.out.println("In Sub");
}

public static void main(String ...args){
  System.out.println(Sub.ID);
}

The way I understand this: if this was new Sub() in main, it would call super() constructor of Super class, obviously first executing static initializers if any then static initializers in Sub, then non-static init blocks and constructors in this particular order.
Having said this, this program prints "1234", How so if Sub doesn't inherit static fields, Shouldn't this be a compile error?

A: You're allowed to access (accessible) static members of a type through an expression of a subtype of that type. At compile time, it is resolved as an access through the declaring type, Super in this case.


text:
Q: Simulate kafka broker failures in multi node kafka cluster and what operations and tools to use to mitigate data loss issues Is there any tools or operation to use to mitigate data loss issues when kafka broker fail in multi node kafka cluster.

A: well, replication is an important features of Kafka and a key element to avoid data loss. In particular, should one of your broker go down, the replica on other brokers will be used by the consumers just as nothing happened (from the business side). Of course, this has consequences on the connections, band width etc.
However, a message must have been properly produced to be replicated.
So basically, if you have a replication set at higher than 1, this should be safe, as long as your producers don't go down.
The default.replication.factor is 1, so set replication (at the topic or general level) to 2 or 3. Of course you need 2 or 3 brokers.
http://kafka.apache.org/documentation.html#basic_ops_increase_replication_factor


text:
Q: SQL transaction not working when initiated via PHP I have the following query which does not work when it is initiated by my PHP code:
$sql = 'START TRANSACTION;
        DELETE FROM task_actions
            WHERE task_id='.$id.';
        DELETE FROM tasks
            WHERE id='.$id.';
        COMMIT;
       ';

When I echo $sql and put the output directly into phpMyAdmin, it works without a problem; and when I had it done in two steps instead of one transaction, it worked from my PHP code, too.
I first thought MySQL might not allow transactions, but stackoverflow.com/questions/2050310 and stackoverflow.com/questions/2960012 showed that was wrong.
I found I could disable autocommit, do both queries and reactivate autocommit (stackoverflow.com/a/17607619 & stackoverflow.com/a/12092151), but I would prefer not to.
Any ideas why it does not work?

A: $sql = 'START TRANSACTION';
// run this query
$sql = 'DELETE FROM task_actions WHERE task_id=?';
// run this query
$sql = 'DELETE FROM tasks WHERE id=?';
// run this query
$sql = 'COMMIT';
// finally run this one


text:
Q: Create PayPal Payment to account through email in order form Currently, I'm using the paypal-rest-api for node.js and am using paypal.payment.create(). However, for this, it's required that the seller have a business account as you need to enter a token and Id from an application on the developer's page.
I've seen in other methods that a seller uses their email for customers to pay through in an order/payment method - instead of using the token and Ids.

To elaborate further, currently I have to use
var paypal = require('paypal-rest-sdk');
paypal.configure({
    'mode': 'live', //sandbox or live
    'client_id': 'CLIENT_ID',
    'client_secret': 'CLIENT_SECRET'
});

However, in the json object that used is there a way to have an account email to pay to. For example
var create_payment_json = {
    "intent": "sale",
    "business": "myemail@gmail.com",
    "payer": {
        "payment_method": "paypal"
    },
    "redirect_urls": {
        "return_url": `return`,
        "cancel_url": `cancel`
    },
    "transactions": [{
        "item_list": {
            "items": itemsList
        },
        "amount": {
            "currency": "USD",
            "total": total.toFixed(2),
            "details": {
                "subtotal": subPrice.toFixed(2).toString(),
                "tax": "0.00",
                "shipping": "0.00",
                "discount": sortedDiscount.toFixed(2),
            }
        },
        "description": `Store payment.`
    }]
};

Thanks in advance.

A: Use your own credentials and specify a payee in the request, as documented here: https://developer.paypal.com/docs/checkout/integration-features/pay-another-account/
Since you are using the deprecated PayPal-Node-SDK and the deprecated v1/payments API, the parameter name will be transactions[0]->payee, as seen in the API reference: https://developer.paypal.com/docs/api/payments/v1/#definition-transaction
(For new integrations, you should be using the current Checkout-NodeJS-SDK and v2/checkout/orders API instead)


text:
Q: Bokeh: Limit Plot Pan and Zoom for list of strings Tried following : Limit bokeh plot pan to defined range, and it limits the range for the x axis, How do I do it for the y axis where the y axis is a list of strings?
Code:
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource,DataRange1d,Range1d
from bokeh.palettes import GnBu3, OrRd3
from bokeh.plotting import figure

output_file("bar_stacked_split.html")

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ["2015", "2016", "2017"]

exports = {'fruits' : fruits,
           '2015'   : [2, 1, 4, 3, 2, 4],
           '2016'   : [5, 3, 4, 2, 4, 6],
           '2017'   : [3, 2, 4, 4, 5, 3]}
imports = {'fruits' : fruits,
           '2015'   : [-1, 0, -1, -3, -2, -1],
           '2016'   : [-2, -1, -3, -1, -2, -2],
           '2017'   : [-1, -2, -1, 0, -2, -2]}

p = figure(y_range=fruits, plot_height=800, plot_width=800, x_range=DataRange1d(bounds=(-16,16)), title="Fruit import/export, by year",
           toolbar_location='below')

p.hbar_stack(years, y='fruits', height=0.9, color=GnBu3, source=ColumnDataSource(exports),
             legend=["%s exports" % x for x in years])

p.hbar_stack(years, y='fruits', height=0.9, color=OrRd3, source=ColumnDataSource(imports),
             legend=["%s imports" % x for x in years])

p.y_range.range_padding = 0.1
p.ygrid.grid_line_color = None
p.legend.location = "top_left"
p.axis.minor_tick_line_color = None
p.outline_line_color = None

show(p)

A: Figured it out:
Use FactorRange and set bounds to auto as:
from bokeh.models import FactorRange

p = figure(y_range=FactorRange(factors=fruits,bounds='auto'), plot_height=800, plot_width=1600, x_range=DataRange1d(bounds=(-16,16)), title="Fruit import/export, by year",
       toolbar_location='below')


text:
Q: Cannot read property of 'get' $http inside a nested function I get the following error

angular.js:13550 TypeError: Cannot read property 'get' of undefined
      at Object.DataService.getDataFromAPI

Here is the where I am messing up the $HTTP.get. Any idea of what I am doing wrong or how to fix it? I think the problem is passing the $HTTP into the nested function.
(function (module) {
    'use strict';
DataService.$inject = ['$http', '$q'];
function DataService($http, $q) {

var getDataFromAPI = function ($http) {

        $http.get("http://localhost:34183/myAPI")
        .then(function (response) {
            console.log(response);
            console.log(response.data);
            return response.data;
        });

    };
}
 return {
            getDataFromAPI: getDataFromAPI
};
}

    module.factory('DataService', DataService);

})(angular.module('ClassAPP'));

Here is my code showing the method works if i just embed the json directly in there which works fine.
 DataService.$inject = ['$http', '$q'];
 function DataService($http, $q) {

 var getDataFromAPI = function ($http) {
        return [{
                  "Grade": "A+",
                  "Class": {
                      "Subject": "Select Topics in Basket Weaving",
                      "Professor": "DJ Khaled"
                  }
               }];
    };
return {
            getDataFromAPI: getDataFromAPI
};
}
module.factory('DataService', DataService);

})(angular.module('ClassAPP'));

A: you need return object inside factory
function DataService($http, $q) {

    var getDataFromAPI = function () {

      return $http.get("http://localhost:34183/myAPI")
            .then(function (response) {
                console.log(response);
                console.log(response.data);
                return response.data;
            });

        };

      return {
           getDataFromAPI : getDataFromAPI
       }
    }

A: Can you write it like this?
app.factory("DataService", ["$http", function($http){
    return {
        getDataFromApi: function(url) {
            return $http.get(url);
        }
    };
}]);

Usage
getDataFromApi.getDataFromApi('/path/to/api/');


text:
Q: DatePicker postback return original value I have a calendar like this:image
Controller:
  protected void Page_Load(object sender, EventArgs e)
        {

 fecha_fin.Text = DateTime.Today.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
                    Thread.CurrentThread.CurrentCulture = new CultureInfo("es-MX");

 }

  protected void DateChange(object sender, EventArgs e)
        {
            fecha_fin.Text = Calendar1.SelectedDate.ToString("yyyy/MM/dd");
        }

View:
  <td>
                <asp:TextBox ID="fecha_fin" ClientIDMode="Static" runat="server"></asp:TextBox>
                <asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="DateChange" DayNameFormat="FirstLetter" Font-Names="Tahoma" Font-Size="11px" NextMonthText="." PrevMonthText="." SelectMonthText="»" SelectWeekText="›" CssClass="myCalendar" CellPadding="0">
                    <OtherMonthDayStyle ForeColor="#b0b0b0" />
                    <DayStyle CssClass="myCalendarDay" ForeColor="#2d3338" />
                    <DayHeaderStyle CssClass="myCalendarDayHeader" ForeColor="#2d3338" />
                    <SelectedDayStyle Font-Bold="True" Font-Size="12px" CssClass="myCalendarSelector" />
                    <TodayDayStyle CssClass="myCalendarToday" />
                    <SelectorStyle CssClass="myCalendarSelector" />
                    <NextPrevStyle CssClass="myCalendarNextPrev" />
                    <TitleStyle CssClass="myCalendarTitle" />
                </asp:Calendar>

            </td>

For default it have today date picked, problem start when I pick another day, it change date correctly with "DateChange" method, problem starts when I pick some other thing in my page, it return post today date again
For example image here I have 31-October selected but text return 12-December again. Why page reload postback as original one (when page load)? Regards

A: protected void Page_Load(object sender, EventArgs e) {
    if (!IsPostBack) {
        fecha_fin.Text = DateTime.Today.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
        Thread.CurrentThread.CurrentCulture = new CultureInfo("es-MX");
    }

}

On page load Check if its not page load .. This will not change values on post back ...
if (!IsPostBack) <-- This checks if its post back call or page refresh call..


text:
Q: How do I solve this using recursion in java? The rules are that I have to return the largest number, so pretty much the user wants to find the biggest number. Split the array in half or close to it and find the biggest value from the array in the lower half and find the biggest value in the high half. I just started learning recursion and this problem is giving me nightmares.
public static double getBiggest(double[] a, int low, int high)
{
    int mid = (low+high)/2;
    double one = 0;
    double two = 0;
    if(a == null || a.length == 0 || low > high)
        throw new IllegalArgumentException();

    //How do I loop to find the biggest?
    //A way to narrow down a big number of array values into a single one

    one = getBiggest(a,low,mid);
    two = getBiggest(a,mid,high);

    if(one >= two)
        return one;
    else
        return two;

  return -1;
}

A: Your code is already pretty close, but since getBiggest  always calls getBiggest(), it will never stop.
Before the recursive call, do something like this
if (low >= high)
{
    return a[low];
}

That still leaves a little problem:  When high == low+1, mid == low, so getBiggest(a,mid,high) will be the same size as the call you're in.  Recursing with the same arguments again means that it will never stop.
Your recursive calls should be like:
one = getBiggest(a,low,mid);
two = getBiggest(a,mid+1,high);

That way both of the recursive calls are guaranteed to be smaller.
Finally, the conditional part at the end works, but the return a[mid] never happens.  You should rewrite it like:
if(one >= two)
    return one;
else
    return two;

In English, the algorithm works like this:

*

*If there's only one element, return it.  Otherwise;

*Get the biggest element in the first half (the first recursive call), then

*Get the biggest element in the second half (the second recursive call), then

*return whichever is bigger.

A recursive solution to a problem is made from solutions to smaller versions of the same problem.

A: Any recursive algorithm must ALWAYS have a base case - if the problem is small enough that it can be solved trivially then that must be done instead. The function must not invariably call itself recursively, otherwise you are guaranteed to get infinite recursion, which in Java means a StackOverflowException. In this case you always call getBiggest as long as the arguments are valid so that is your problem. You wrote "If the low to high section is 3 or bigger" but there is no such if statement in your code. Adding one will allow you to avoid recursion when low and high meet.

A: Your implementation has two problems:

*

*It is not doing the arguments checking correctly - the check needs to happen at the top, and

*You are missing the base case. Any recursive program must specify what to do when you are down to one or two items; your program is not doing it.

You need to add a condition at the top to see if high minus low is two or less. If it is one, return the number at the low end; if there are two numbers, pick the max and return it.


text:
Q: $http Response always keep last response first, I would like to thank all the contributors of this site. They saved thousands of hours of my time :)
Then, I have now a problem that I cannot solve myself. However, I have searched in the site since this morning without any success.
Let me explain.
I'm using AngularJS and make an $http request this way :
var req = {
            method: 'POST',
            url: myurl/*an asmx file*/,
            headers: {
                      "Cache-Control" : "no-cache",
                      "Authorization": "Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==",
                      "Accept": "application/json;odata=verbose"
        },
        data: JSON.stringify(dataToPost)
    };
    $http(req).then(function successCallback(response) {
        console.log(response.data);
    }, function errorCallback(response) {
        return response.data;
    });

The query is well executed and the object response.data returns me something. If I execute the query once there is no problem BUT if I execute it a second time the query, the response.data object will have the result of the query just perform (the second execution) AND the result of the first execution. Is there something like a cache in the response ?
What do I do wrong ?
EDIT (as requested by JB Nizet): Here are the two responses :
First, the query returns me something -> OK
{"d":"{\"recordset\":[{\"ColA\":\"TEST\",\"ColA\":\"XXXXXX\",\"ColA\":\"ZZZZZZ\",\"ColA\":\"OOOOOO\",\"ColA\":\"LLLLLLL\",\"ColA\":\"\",\"ColA\":\"\",\"ColA\":\"\"}]}"}

Second, it keeps returning me the same results whereas thsi second execution should return no result (so empty response I guess):
{"d":"{\"recordset\":[{\"ColA\":\"TEST\",\"ColA\":\"XXXXXX\",\"ColA\":\"ZZZZZZ\",\"ColA\":\"OOOOOO\",\"ColA\":\"LLLLLLL\",\"ColA\":\"\",\"ColA\":\"\",\"ColA\":\"\"}]}"}

Thanks in advance for your answers.
Jérémie.

A: that's ok, I just missed the "static" on my class that built my JSON... -> Noob !


text:
Q: Retrieve value that is stored in db and display in select box using angularjs and laravel I am trying to retrieve a value that was stored in my MySQL database and display the selected value from the database along with the other select box items so that they can be updated. The problem that I am having is that the select box is not displaying the selected value that is stored in the database, instead it defaults to the empty first option. I am using angularjs to retrieve the values from laravel:
laravel
public function getEmployeeshifts() {
    $employeeShift = DB::table('shift')
                       ->select('shiftId', 'title')
                       ->get();

    return Response::json($employeeShift);
}

angularjs
$http.get('/schedule/employeeshifts').success(function(shiftdata) {
    $scope.employeeshifts = shiftdata;
});

html
<select class="form-control input-sm" name="employeeshift"
                                      ng-model="time.employeeshift"
                                      ng-init="time.employeeshift='{{$schedules[0]->title}}'"
                                      ng-options="employeeshift.title for employeeshift in employeeshifts track by employeeshift.shiftId" required>
        <option value="">Select</option>
</select>

desired output
<option value="101">Shift A</option>
<option value="102">Shift B</option>
<option value="103">Shift C</option>

Based on the above desired output what i actually want to store in the database is the value but I need to show the words to the user. I am not sure what I am doing wrong, therefore I am asking for assistance to this problem.

A: AngularJS automatically resolves which item is selected based on the value of ng-model. It appears that you are setting the value of time.employeeshift to a title value and not a shiftId value. Try changing your ng-init attribute to time.employeeshift='{{$schedules[0]->id}}' or it's equivalent.

A: You have to set your model to the desired selected item. In your case, you are not setting it correctly in your ng-init. You should use employeeshift as your model.
<select ng-model="employeeshift"
        ng-init="employeeshift = employeeshifts[0]"
        ng-options="employeeshift.title for employeeshift in employeeshifts">
        <option value="">Select</option>
</select>

This will bind the selected shift object to the $scope.employeeshift variable, and set the default value to the first object in your employeeshifts array.


text: Q: Randomly Sample Raster Pixels With a Minimum Distance in QGIS Is there a way I can sample random raster pixels from a satellite image with QGIS or QGIS plugin?   I also need each randomly-chosen pixel to have a pre-defined minimum distance from the other raster pixels. I need this pre-defined minimum distance in order to minimize spatial autocorrelation.


text:
Q: Python turtle | Display won't show I was working on fixing up some code to make it look better and when I finished copying the code over and finishing fixing it, I ran it and nothing happened. Two things loaded then everything clears. I can't find the problem.
Original code works
import turtle
from random import randint
import time
"""-------------"""
t=turtle.Turtle()
s=turtle.Screen()
cube=turtle.Turtle()
title=turtle.Turtle()
"""--------------"""
WIDTH, HEIGHT=300, 300
LENGTH=(5)
"""--------------"""
x1 = randint(cube.xcor()/2 - WIDTH/2, WIDTH/2 - cube.xcor()/2)
y1 = randint(cube.ycor()/2 - HEIGHT/2, HEIGHT/2 - cube.ycor()/2)
"""------------"""
s.setup(WIDTH,HEIGHT)
"""------------"""
t.width(1)
s.bgcolor("dark green")
"""-----------------"""
#Title
title.color("Red")
title.hideturtle()
title.penup()
title.goto(0,130)
title.pendown()
title.write("SNAK3",align="center", font=("Lobster", 20, "Bold"))
"""-------------"""
class Food():
    def block():
        cube.hideturtle()
        cube.color("red")
        cube.penup()
        cube.goto(x1,y1)
        cube.speed(0)
        cube.begin_fill()
        for i in range(4):
            cube.pendown()
            cube.forward(10)
            cube.right(90)
        cube.end_fill()
"""---------------"""
t.shape("square")
class Player():
    def move_up():
        player=False
        while player==False:
            for i in range(10):
                t.forward(LENGTH)
                t.delay(25)
            t.clear()
            x, y = t.position()
            if not -WIDTH / 2 < x < WIDTH / 2 or not -HEIGHT / 2 < y < HEIGHT / 2:
                player=True
                t.hideturtle()
                cube.clear()
                title.clear()
                title.penup()
                title.goto(0,0)
                title.pendown()
                title.write("GAMEOVER", align="center", font=("lobster", 18, "bold"))
    def move_left():
        t.speed(0)
        t.left(90)
        t.speed(3)
    def move_right():
        t.speed(0)
        t.right(90)
        t.speed(3)
"""------------"""
food=Food.block()
player1=Player()
"""----------------"""
s.onkey(Player.move_up,"up")
s.onkey(Player.move_left,"left")
s.onkey(Player.move_right,"right")
s.listen()
"""--------------"""
collision=Collision_check.check()
"""--------------------"""
t1=t.xcor(),t.ycor()
cube1=cube.xcor(),cube.ycor()
class Collision_check():
    def check():
        crash=True
        if t1.xcor()>=cube.xcor() and t1.xcor()<=cube.xcor()+10 and t1.ycor>=cube.ycor() and t1.ycor()<=cube.ycor+10:
            cube.clear()
            cube.goto(x1,y1)
            LENGTH=+1
        elif t1!=cube1:
            crash=False
        return crash

Fixed code with slight changes
import turtle
from random import randint

t=turtle.Turtle()
s=turtle.Screen()
cube=turtle.Turtle()
title=turtle.Turtle()

t.width(1)
s.bgcolor("dark green")

#Title
title.color("red")
title.hideturtle()
title.penup()
title.goto(0,130)
title.write("SNAK3",align="center",font=("lobster",20,"Bold"))

WIDTH, HEIGHT=300, 300
LENGTH=[5]

s.setup(WIDTH,HEIGHT)

#Random cords
x1=randint(cube.xcor()/2-WIDTH/2, WIDTH/2-cube.xcor()/2)
y1=randint(cube.ycor()/2-HEIGHT/2, HEIGHT/2-cube.ycor()/2)

class Food():
    def block():
        cube.hideturtle()
        cube.color("red")
        cube.penup()
        cube.goto(x1,y1)
        cube.speed(0)
        cube.begin_fill()
        cube.pendown()
        for i in range(4):
            cube.forward(10)
            cube.right(90)
        cube.end_fill()

t.shape("square")
class Player():
    def forward():
        player=False
        while player==False:
            for i in range(10):
                t.forward(LENGTH)
                t.delay(25)
            t.clear
            x, y=t.position()
            if not -WIDTH / 2 < x < WIDTH / 2 or not -HEIGHT / 2 < y < HEIGHT/2:
                player=True
                cube.clear()
                t.hideturtle()
                title.clear()
                title.penup()
                title.goto(0,0)
                title.pendown()
                title.write("GAMEOVER", align="center", font=("lobster",18,"bold"))
def left():
        t.speed(0)
        t.left(90)
        t.speed(3)
    def right():
        t.speed(0)
        t.right(90)
        t.speed(3)

food=Food.block()
player1=Player()

s.onkey(player1.forward,("up"))
s.onkey(player1.left,("left"))
s.onkey(player1.left,("right"))

class Collision_check():
    def check():
        crash=True
        if t.xcor()>=cube.xcor() and t.xcor()<=cube.xcor()+10 and t.ycor()>=cube.ycor() and t.ycor()<=cube.ycor()+10:
            cube.clear()
            cube.goto(x1,y1)
            LENGTH+=1
            if cube.xcor()>=t.xcor() and cube.xcor()<=t.xcor()+10 and cube.ycor()>=t.ycor() and cube.ycor()<=t.ycor()+10:
            cube.clear()
            cube.goto(x1,y1)
            LENGTH+=1
        else:
            crash=False
        return crash
collision=Collision_check.check()

Everything in the code above is nearly exactly the same as the original. Ive gone over the code several times and can not find the problem.
I've ruled out that the collision_check is not the problem, all the classes are in order and aligned. The only other thing I could think of is that i have spelled something wrong.

A: Let's first address some basic facts:

*

*Neither version of this code works

*The slight changes to make it look better don't make it look better
and aren't slight, there are significant differences

*Neither version of the code uses Python classes correctly

*repl.it provides its own implementation of turtle which is generally
a subset of the original
A program is like a story, you first explain the background of events and then you proceed to tell the story in an order that makes logical sense.
Here's my rework of your code to try to tell a better story, but it still doesn't work completely as there are parts of the story missing:
from turtle import Turtle, Screen
from random import randint

WIDTH, HEIGHT = 300, 300

class Food():
    def block():
        cube.penup()
        cube.goto(x1, y1)
        cube.pendown()

        cube.begin_fill()
        for _ in range(4):
            cube.forward(10)
            cube.right(90)
        cube.end_fill()

class Player():
    def forward():

        for _ in range(10):
            t.forward(LENGTH)
            # t.delay(25)  # no such turtle method, perhaps repl.it addition
        t.clear()

        x, y = t.position()

        if not -WIDTH / 2 < x < WIDTH / 2 or not -HEIGHT / 2 < y < HEIGHT/2:
            cube.clear()
            t.hideturtle()
            title.clear()
            title.penup()
            title.goto(0, 0)
            title.pendown()
            title.write("GAMEOVER", align='center', font=('lobster', 18, 'bold'))

    def left():
        t.speed(0)
        t.left(90)
        t.speed(3)

    def right():
        t.speed(0)
        t.right(90)
        t.speed(3)

class Collision_check():
    def check():
        global LENGTH
        crash = True

        if t.xcor() >= cube.xcor() and t.xcor() <= cube.xcor() + 10 and t.ycor() >= cube.ycor() and t.ycor() <= cube.ycor() + 10:
            cube.clear()
            cube.goto(x1, y1)
            LENGTH += 1
            if cube.xcor() >= t.xcor() and cube.xcor() <= t.xcor()+10 and cube.ycor() >= t.ycor() and cube.ycor() <= t.ycor()+10:
                cube.clear()
                cube.goto(x1, y1)
                LENGTH += 1
        else:
            crash = False

        return crash

s = Screen()
s.setup(WIDTH, HEIGHT)
s.bgcolor('dark green')

t = Turtle()
t.shape('square')
t.width(1)

cube = Turtle()
cube.hideturtle()
cube.color('red')
cube.speed('fastest')

# Title
title = Turtle()
title.hideturtle()
title.color('red')
title.penup()
title.goto(0, 130)
title.write("SNAK3", align='center', font=('lobster', 20, 'bold'))

LENGTH = 5

# Random cords
x1 = randint(cube.xcor()/2 - WIDTH/2, WIDTH/2 - cube.xcor()/2)
y1 = randint(cube.ycor()/2 - HEIGHT/2, HEIGHT/2 - cube.ycor()/2)

food = Food.block()
player1 = Player()

s.onkey(Player.forward, 'Up')
s.onkey(Player.left, 'Left')
s.onkey(Player.right, 'Right')
s.listen()

# this makes no sense here, needs to happen on a regular basis after moves
collision = Collision_check.check()

s.mainloop()


text:
Q: How to fetch the Excel file path connection dynamically through a variable in the Excel Source? How to fetch the Excel file path connection dynamically through a variable in the Excel Source?
Inside my Foreach Loop Container, I have Excel Source which has Excel Connection String.
I am using the variable to map the Incoming folder path. I set DelayValidation to True.
Folder Path : c:\IncomingPath\
However, I am getting an error as

The connection is not found.

We put the excel files by extracting the zip file. Steps are done through SSIS Package.

A: In the Foreach Loop make sure it's using the Foreach File Enumerator type if it's not already.  Then on the Variable Mappings page, set a string variable to Index 0, this will hold the file name for each iteration of the loop.  Then go to the Excel Connection Manager, click on the ellipsis next to the Expressions property (highlight the connection manager and press F4 to view the Properties window) and set the same string variable that was set at Index 0 in the loop as the expression for the ExcelFilePath, not ConnectionString, property.  This will set the Excel Source component to use the current file from each iteration of the Foreach Loop.


text:
Q: Smooth Edges In Segmentation I am working on project in which i have to do segmentation masking. Now problem is that exported masked image should have 2 things.
NOTE: Please download both images for better understanding my problem

*

*Only 2 Colors.

*No Jagged Edges.

Tools Used:

*

*Cvat

*Photopea ( for Reducing Colors )

*Pixspy ( for checking how many colors image have )

If i achieve 1 ( means if i reduce color ) than for sure jagged edges will appear. because mask is png and if you remove colors from jagged edges than it is obvious that all shades which given illusion of image smoothing will disappear. and if i go with no jagged edges than i will get thousands of colors in image.
Image with Smooth edges but many colors around 12k

Image with Jagged edges but limited colors only 2

How can i achieve both of the things on same time for my mask.


text:
Q: Is it safe to repair and optimize mysql tables? I use mysqltuner to tune the mysql server. It recommends to "Run OPTIMIZE TABLE to defragment tables for better performance". I had done this on a single database before and I don't see any problem. Now, I have several client's databases on this server, I am hesitate to use optimize and repair on all databases. Is it safe to do this? Should I optimize their databases or ask them to do it? Thanks.

A: I'd rather leave it to customers if only for the reason OPTIMIZE TABLE locks the table for the duration of the operation.

A: I've never had a problem with it.  I'd say it's about as safe as anything else in MySQL.

A: I'd definitely schedule this for a quiet/off-peak time, and do a database dump beforehand and immediately after, and compare if possible.
of course, you might want to consider whether there's a reason the DB performance is dropping off and look at the mysql slow query log to see if a new table layout would prevent problems happening.


text:
Q: How to Nested dicts, lists & OrderedDicts to DataFrame How can I parse the following data structure:
data = {0: None,
     1: [OrderedDict([('N', '1192'),
                   ('Date', '2009-10-08T00:00:00'),
                   ('Rule', '0'),
                   ('N_Dip', '0'),
                   ('Leg',
                    OrderedDict([('Id', '33'),
                                 ('Name', 'Ports'),
                                 ('Type',
                                  OrderedDict([('Id', '2'),
                                               ('Name', 'Dip')]))])),
                   ('Id', '69')]),
      OrderedDict([('N', '382'),
                   ('Date', '2012-11-23T00:00:00'),
                   ('Rule', '0'),
                   ('N_Dip', '0'),
                   ('Leg',
                    OrderedDict([('Id', '33'),
                                 ('Name', 'Ports'),
                                 ('Type',
                                  OrderedDict([('Id', '2'),
                                               ('Name', 'Dip')]))])),
                   ('Id', '70')])],
     2: None,
     3: None,
     4: None,
     5: OrderedDict([('N', '5º'),
                  ('Article', '36º'),
                  ('Date', '0001-01-01T00:00:00'),
                  ('Rule', '0'),
                  ('N_Dip', '0'),
                  ('Leg',
                   OrderedDict([('Id', '7'),
                                ('Name', 'DEVA'),
                                ('Type',
                                 OrderedDict([('Id', '1'),
                                              ('Name', 'Code')]))])),
                  ('Id', '127')]),
     6: None,
     7: None}

into a pandas DataFrame with the columns (not necessarily in this order):
N | Date | Rule | N_Dip | Leg_Id | Leg_Name | Leg_Type | Leg_Type_Id | Leg_Type_Name | Leg_Type_Name | Id | Article

and where each dict key (each number) becomes a row?
Example desired output:

*

*I'm not seeing how to solve this without the use of multilevel indexing, but if you have another idea, feel free.

*I don't care about the order of the columns.
Thanks in advance,
EDITS:

*

*corrected "Nome" to "Name" (18/06/2021);

*added desired output (18/06/2021).

A: If data is your dictionary:
df = pd.DataFrame(
    [l for v in data.values() for l in (v if isinstance(v, list) else [v]) if v]
)
x = df.pop("Leg").apply(pd.Series).add_prefix("Leg_")
y = x.pop("Leg_Type").apply(pd.Series).add_prefix("Leg_Type_")

out = pd.concat([df, x, y], axis=1)
print(out)

Prints:
      N                 Date Rule N_Dip   Id Article Leg_Id Leg_Name Leg_Nome Leg_Type_Id Leg_Type_Nome Leg_Type_Name
0  1192  2009-10-08T00:00:00    0     0   69     NaN     33    Ports      NaN           2           Dip           NaN
1   382  2012-11-23T00:00:00    0     0   70     NaN     33      NaN    Ports           2           NaN           Dip
2    5º  0001-01-01T00:00:00    0     0  127     36º      7     DEVA      NaN           1           NaN          Code

A: After leveraging @andrej-kesely's great list comprehension, I might use json_normalize() to do the work for me. Note that in my test I assumed that there is a typo between "Name" and "Nome" and I made them both "Name".
import pandas
data = [l for v in data.values() for l in (v if isinstance(v, list) else [v]) if v]
print(pandas.json_normalize(data, sep="_"))

Gives:
      N                 Date Rule N_Dip   Id Leg_Id Leg_Name Leg_Type_Id Leg_Type_Name Article
0  1192  2009-10-08T00:00:00    0     0   69     33    Ports           2           Dip     NaN
1   382  2012-11-23T00:00:00    0     0   70     33    Ports           2           Dip     NaN
2    5º  0001-01-01T00:00:00    0     0  127      7     DEVA           1          Code     36º


text:
Q: Really occasional malfunction of the Schmitt-trigger input I'm using some Schmitt-trigger inputs for debouncing the interrupt problems.

Referring to above circuit, the circuit has a RC circuit and the output of the RC circuit goes to the Schmitt-trigger IC(74HC14).
Also, I soldered like this circuit and the look is like as below picture.

Well, the picture is not good I apologize for the view. (18k : R1, 2k : R2, 0.1u : C1)
Anyway, I'm convinced of the equality of the circuit picture and the real one.
However there is a very small issue.
The output of the Schmitt-trigger IC is connected to the MCU interrupt pin. So, if the Schmitt-trigger output goes to low(I use falling-edge-triggered interrupt), the MCU will run some ISR. Suppose I "bring(NOT push the button)" my hand to control the device on my own. At most, the device not malfunction. However, very occasionally the device goes to interrupt mode(ISR).
The schmitt-trigger goes to MCU(ATmega2560, STM32F411RE, and so forth) and the MCU has some attached interrupts that can respond for the some schmitt-trigger inputs. And if the problem occurs, MCU just execute some ISRs. I thought the problem is occurred by the ESD so I used some TVSs and collected all the GNDs as near as the SMPS input, but the issue is not entirely solved. The problem hardly happens(probably just one time of a day) so this wouldn't be important one, but what could be the cause of this situation? Could I get some intuitions for the issue and the solutions?

A: Your awareness of stray ISR resets, tells me you have an EMI problem.
It can be caused by stray E-fields, modulated by your hand that acts as an antenna and variable capacitor to couple line E fields near a floating supply voltage used on MCU.
Although 0.1uF seems low impedance, the thin wires also raise ground impedance, so the distance to MCU can be important and RF broadcast signals can also combine with this interference.  Often Common MOde (CM) noise converts to Dff. Mode (DM) noise by unbalanced impedance of signal and reference. (supply)
To reduce stray E-fields; typically, ground planes, shielding , ferrite beads, twisted pair wires, using tighter/smaller layouts to reduce loop area are some methods used and use lower impedance sensors.

A: As @Sunyskyguy says, you have an EMI problem. Very likely due to your perforated board construction and the distance between components. Enough of a stray field can be induced into those long wires to cause some problems.
Without a proper PCB it could be hard to avoid, but here are a couple of things that you can do to reduce the likelihood of the problem:

*

*Make sure to have a low inductance connection between the ground of the 74HC14 and the MCU. Place these as close as possible, with as thick a wire as possible.

*Make sure to have a ~100nF decoupling capacitor for the 74HC14 power supply. Directly on its pins.

*Place the debouncing capacitor as close to the 74HC14 as possible. This will serve to filter any EMI coupled into the wiring.

*Optionally, add a zener or TVS before the capacitor. This will serve to dissipate any ESD energy before it hits the ICs.

A: I would avoid this whole problem by doing the debouncing in software.  There are several subroutines for this on https://playground.arduino.cc/Main/LibraryList#IO_buttons
That, to me, is the correct way to solve the problem.  Requires no external components beyond the switch.  You can set INPUT_PULLUP for the pin to eliminate the pullup resistor.
"The cheapest and most reliable parts are those which are not there." - Gordon Bell (designer of the PDP-11)


text:
Q: how to give @media query to my inline style? i am making a responsive site and using media query for that but, i stuck with one problem where i had given inline style. and now i want to change that style for different size of screen. how it can be done? here is my code.

in style i had given width=500px; i want it 700px for
@media only screen and (max-width: 1920px) {
}

1920px size screen.please give solution for it or give other way to do this thing.i am using edu_table class many places...and i want width=700px; for screen size 1920px and for particular place.

A:

remove inline style
 .edu_table{
         width:500px;
         margin-right:400px;
         margin-bottom:30px;
    }
@media only screen and (max-width: 1920px) {
    .edu_table{
         width:700px;
    }
}

if you can not remove your inline style then use Important
@media only screen and (max-width: 1920px) {
        .edu_table{
             width:700px !important;
        }
    }

A: Here is what you want, put this in a css file or at be bottom of the . Though the width should always be at 700px because you set them max-width. At the moment it is everything to a max-width of 1920px, everything above will get the 500px.
.edu_table{
     width: 500px;
}

@media only screen and (max-width: 1920px) {
    .edu_table{
         width: 700px;
         margin-right: 400px;
         margin-bottom: 30px;
    }
}

A: It is not possible to put media queries in style attributes.
target the class with the css:
.edu-table {
    width: 500px;
    /* styles */
}

Then over-ride them when the screen is 1920px or wider:
@media only screen and (min-width: 1920px) {
    .edu-table {
        width: 700px;
        /* any other styles for 1920px and above */
    }
}

Using min-width in the media query will ensure the styles only apply to screens wider than 1920px.
Also, remove the inline styles as they will over-ride the css. You could use !important but only if you have no other conceivable option, as it is a nightmare to over-ride and can make a real mess of stylesheets.


text:
Q: Mysql query with group by and having clause I am constructing query to get the maximum price for same product.
I have table as
-----------------------------------------
|   prod_id  |   price   |    user_id   |
-----------------------------------------
|     4      |   25      |       1      |
|     4      |   38      |       2      |
|     4      |   41      |       3      |
|     7      |   100     |       1      |
|     7      |   95      |       2      |
-----------------------------------------

I am trying to get following output:
-----------------------------------------
|     4      |   41      |       3      |
-----------------------------------------
|     7      |   100     |       1      |
-----------------------------------------

I have constructed following query which is not right.
select * from user_bid group by prod_id having max(price);

Can someone guide me to get the query for desired results.

A: Here is an option using a join:
SELECT p1.*
FROM prod_id
INNER JOIN
(
    SELECT prod_id, MAX(price) AS price    -- this inner subquery finds the maximum
    FROM user_bid                          -- price for each product group
    GROUP BY prod_id
) p2
    ON p1.prod_id = p2.prod_id AND         -- and this join condition retains
       p1.price   = p2.price               -- only records which have this maximum
                                           -- price for each product group

And here is an option which uses a subquery:
SELECT p1.*
FROM prod_id p1
WHERE price = (SELECT MAX(p2.price) FROM prod_id p2 WHERE p1.prod_id = p2.prod_id)

A: SELECT *
FROM user_bid
WHERE (prodid, price) IN
(
    SELECT prodid, MAX(price)
    FROM user_bid
    GROUP BY prod_id
)

A: For SQL Server
;WITH cte AS

(
SELECT prod_id,price,user_id,
       ROW_NUMBER() OVER(PARTITION BY prod_id ORDER BY price desc) as rank
FROM table Name
)

SELECT prod_id,price,user_id
FROM cte
WHERE rank=1

A: Use the below query:
SELECT * FROM (SELECT * FROM user_bid  ORDER BY price DESC) AS Temp
GROUP BY prod_id

Output: