Q: Pandas Dataframe sum row based on column header I have the following dataframe and want to create two columns, one will show the amount MTD and the other will show the cumulative YTD based on a date parameter for each Account Name. This is easily achievable in Excel using a =SUMIFS formula and want to know the Python equivalent.
+---------------+------------+------------+------------+------------+
| Account Names | 31/01/2022 | 28/02/2022 | 31/03/2022 | 30/04/2022 |
+---------------+------------+------------+------------+------------+
| Cash At Bank  |        100 |        150 |        100 |        150 |
| Debtors       |         50 |         50 |         50 |        100 |
| Inventory     |        250 |        250 |        350 |        100 |
| PAYG Withheld |         50 |         50 |         10 |        150 |
+---------------+------------+------------+------------+------------+

Ideally, I'd want this to be as efficient as possible i.e. doesn't require loops. I went the route of trying to do this using np.select as I've read this is one of the fastest methods, but had no luck. I get the following error:

ValueError: shape mismatch: objects cannot be broadcast to a single shape

EndDate = '31/03/2022'
Budget_Assets["MTD_Amount"] = np.select(condlist=[Budget_Assets.columns == EndDate],choicelist=[Budget_Assets[EndDate]],default=0)

For example, the value in the MTD_Amount column for Cash At Bank should be 100 and the YTD_Column will be 350 (sum of numbers from '31/01/2022' to '31/03/2022')

A: You can try sum(axis=1) by slicing the datetime like columns to calculate YTD and just use loc to get MTD
EndDate = '31/03/2022'
date_cols = df.filter(regex='\d{2}/\d{2}/\d{4}')
date_cols.columns = pd.to_datetime(date_cols.columns, dayfirst=True)

df['YTD_Column'] = date_cols.loc[:, :pd.to_datetime(EndDate, dayfirst=True)].sum(axis=1)
df['MTD_Column'] = df[EndDate]

   Account Names  31/01/2022  28/02/2022  31/03/2022  30/04/2022  YTD_Column  MTD_Column
0   Cash At Bank         100         150         100         150         350         100
1        Debtors          50          50          50         100         150          50
2      Inventory         250         250         350         100         850         350
3  PAYG Withheld          50          50          10         150         110          10


Q: Firefox Password Field is not empty I'm new here on stackoverflow.
I'm writing a Form to add a Album to a gallery, but now I discovered a problem in Firefox which I've never had. The password field is already set. I never filled out the form.
Does somebody knows, why Firefox fills text in?

A: If it is a saved password, you will be able to find it in the security and password settings (see link for more information).  If you've saved a password on a different portion of the site (say you have a form on www.site.com/login.html and www.site.com/admin.html for example), it could be pulling it from there.


Q: Can you use "first class" concept on Python methods/attributes? Can the "first-class" concept be applied to Python methods/attributes like it can functions?
>>>a=sum
>>>a([1,2,3])
6

I would like to do something like:
>>>case='lower'
>>>'UPPERCASE'.case()

To produce the string object 'uppercase'. Otherwise, would I just have to use eval?

A: You can do it this way:
case = str.lower # Take the lower() method of the str class.
case('UPPERCASE') # pass your string as the first argument, which is self.

In this case, Python being explicit about self being the first argument to methods makes this a lot clearer to understand.


Q: Botão "Gostei/Like" Quero fazer um botão no meu site com um contador ao lado e gostaria que a cada clique o contador aumentasse 1 número. Mas eu queria que ficasse salvo esse número de cliques num ficheiro .txt no servidor, e que todos pudessem clicar e ver esse contador.
Um botão Like, que só poderia ser clicado 1 vez por computador. Entendem?
Quero que os usuários avaliem o conteúdo do meu site com esse botão.

A: Serão utilizado tres arquivos:
1 - principal.php, que exibirá o link para download e o numero de downloads
2 - download_arquivo.php - Este aumentará o contador em 1, fará o download do arquivo e redirecionará para o principal.php
3 - contador_arquivo.txt - Armazenará o numero de downloads
ARQUIVO 1 - PRINCIPAL.PHP:

DOWNLOAD AQUI

N. de Downloads: <? include "contador_arquivo.txt"; ?>

ARQUIVO 2 - DOWNLOAD_ARQUIVO.PHP

">Voltar
<?php
//Abre o contador de downloads e acrescenrta em 1
$fp = fopen("contador_arquivo.txt","r");
$visitas = fgets($fp,255);
$visitas++;
fclose($fp);
$fp = fopen("contador_arquivo.txt","w+");
fwrite($fp, $visitas);
fclose($fp);
?>

ARQUIVO 3 - CONTADOR_ARQUIVO.TXT
(escreva o numero 0 e salve o arquivo)

Fonte: Contador Clicks


Q: How to Reduce 3G data consumption using Google Map API for Android I am developing an android application that requires to display the current location of a user and to load KMZ file (with poly lines) on Google Map (use of google map api).
My application opens the google map, loads the KMZ file and diplays current position fast, when having wi-fi and 3G enabled to mobile.The problem I face is that having 3G the data consumption is too big. I checked that after 5 clicks/zoom in-out on a single map the data consumption on mobile become 100MB..
Are there any ways to reduce the 3G data consumption? Should I use another map source?
Thanks


Q: How to remap the copy-paste keyboard shortcuts in MATLAB on Ubuntu? The default keys are alt-w for copying and ctrl-y for pasting. Is there any way to remap this to ctrl-c for copying and ctrl-v for pasting?

A: Yes. Go to Preferences -> Keyboard.
There you will find "Command Window keybindings" and "Editor/Debugger" keybindings.
These are most likely set to "Emacs" style for you -- you should change them to "Windows" style to copy and paste with Ctrl-C and Ctrl-V, respectively.
Source: http://blogs.mathworks.com/community/2007/05/11/setting-up-keybindings-for-the-command-window-and-editor/

A: In Matlab version R2020a, you can change the keyboard shortcuts by following these steps:

*

*Go to Home > Preferences > Keyboard > Shortcuts

*Change the Active Settings to Windows Default Set

*Apply the changes by clicking on Apply and then Ok
It will look like this screenshot.

Now you can use ctrl-C / ctrl-V to copy / paste as usual.


Q: Google breakpad crashes when run under a debugger We have a problem where initializing the Google Breakpad exception handler errors out when the program is run under lldb, but not when run normally from the shell.
The system is MacOS 13 (Ventura) and the IDE is Visual Studio Code.
The code below fails on a call to init():
namespace crashhandler {
    static std::unique_ptr<google_breakpad::ExceptionHandler> pExceptionHandler;

    namespace {
        bool DumpCallback(const char* dump_dir, const char* minidump_id, void*, bool success) {
            if (success)
                printf("Application crashed. Breakpad Crash Handler created a dump at location %s/%s.dmp\n",
                       dump_dir, minidump_id);
            else
                printf("Application crashed. Breakpad Crash Handler failed to create a dump");

            fflush(stdout);
            return success;
        }
    } // namespace

    void init(const std::string& reportPath) // <-- crash happens when calling this function
    {
        if (pExceptionHandler)
            return;
        pExceptionHandler.reset(
            new google_breakpad::ExceptionHandler(reportPath, nullptr, DumpCallback, nullptr, true, nullptr));
    }
} // namespace crashhandler

The debug console shows:
=================================================================
==5060==ERROR: AddressSanitizer: stack-buffer-underflow on address 0x00016fdfee00 at pc 0x000100ac9030 bp 0x00016ff11540 sp 0x00016ff10d08
READ of size 4608 at 0x00016fdfee00 thread T2
    #0 0x100ac902c in wrap_write+0x15c (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x1902c)
    #1 0x100109f08 in google_breakpad::UntypedMDRVA::Copy(unsigned int, void const*, unsigned long)+0x54 (my_server:arm64+0x100109f08)
    #2 0x10010ce14 in google_breakpad::MinidumpGenerator::WriteStackFromStartAddress(unsigned long long, MDMemoryDescriptor*)+0xf8 (my_server:arm64+0x10010ce14)
    #3 0x10010d244 in google_breakpad::MinidumpGenerator::WriteThreadStream(unsigned int, MDRawThread*)+0x100 (my_server:arm64+0x10010d244)
    #4 0x10010c04c in google_breakpad::MinidumpGenerator::WriteThreadListStream(MDRawDirectory*)+0xfc (my_server:arm64+0x10010c04c)
    #5 0x10010bd20 in google_breakpad::MinidumpGenerator::Write(char const*)+0xc8 (my_server:arm64+0x10010bd20)
    #6 0x10010adc0 in google_breakpad::ExceptionHandler::WriteMinidumpWithException(int, int, int, __darwin_ucontext64*, unsigned int, bool, bool)+0x160 (my_server:arm64+0x10010adc0)
    #7 0x10010af1c in google_breakpad::ExceptionHandler::WaitForMessage(void*)+0x104 (my_server:arm64+0x10010af1c)
    #8 0x1a330a068 in _pthread_start+0x90 (libsystem_pthread.dylib:arm64e+0x7068)
    #9 0x1a3304e28 in thread_start+0x4 (libsystem_pthread.dylib:arm64e+0x1e28)

Address 0x00016fdfee00 is located in stack of thread T0 at offset 0 in frame
    #0 0x1000034cc in main main.cpp:36

  This frame has 10 object(s):
    [32, 56) 'reportPath' (line 39) <== Memory access at offset 0 partially underflows this variable
    [96, 120) 'ref.tmp' (line 40) <== Memory access at offset 0 partially underflows this variable
    [160, 208) 'parser' (line 43) <== Memory access at offset 0 partially underflows this variable
    [240, 264) 'configPath' (line 45) <== Memory access at offset 0 partially underflows this variable
    [304, 320) 'ref.tmp12' (line 46) <== Memory access at offset 0 partially underflows this variable
    [336, 360) 'agg.tmp' <== Memory access at offset 0 partially underflows this variable
    [400, 416) 'ref.tmp30' (line 57) <== Memory access at offset 0 partially underflows this variable
    [432, 456) 'agg.tmp42' <== Memory access at offset 0 partially underflows this variable
    [496, 520) 'agg.tmp80' <== Memory access at offset 0 partially underflows this variable
    [560, 568) 'ref.tmp86' (line 74) <== Memory access at offset 0 partially underflows this variable
HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork
      (longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-buffer-underflow (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x1902c) in wrap_write+0x15c
Shadow bytes around the buggy address:
  0x00702dfdfd70: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x00702dfdfd80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x00702dfdfd90: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x00702dfdfda0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x00702dfdfdb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x00702dfdfdc0:[f1]f1 f1 f1 00 00 00 f2 f2 f2 f2 f2 f8 f8 f8 f2
  0x00702dfdfdd0: f2 f2 f2 f2 f8 f8 f8 f8 f8 f8 f2 f2 f2 f2 f8 f8
  0x00702dfdfde0: f8 f2 f2 f2 f2 f2 f8 f8 f2 f2 00 00 00 f2 f2 f2
  0x00702dfdfdf0: f2 f2 f8 f8 f2 f2 00 00 00 f2 f2 f2 f2 f2 00 00
  0x00702dfdfe00: 00 f2 f2 f2 f2 f2 f8 f3 f3 f3 f3 f3 00 00 00 00
  0x00702dfdfe10: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
Thread T2 created by T0 here:
    #0 0x100ae8c5c in wrap_pthread_create+0x54 (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x38c5c)
    #1 0x10010a360 in google_breakpad::ExceptionHandler::Setup(bool)+0xd0 (my_server:arm64+0x10010a360)
    #2 0x10010a1c4 in google_breakpad::ExceptionHandler::ExceptionHandler(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, bool (*)(void*), bool (*)(char const*, char const*, void*, bool), void*, bool, char const*)+0x110 (my_server:arm64+0x10010a1c4)
    #3 0x1001132b4 in crashhandler::init(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)+0x58 (my_server:arm64+0x1001132b4)
    #4 0x10000367c in main main.cpp:41
    #5 0x1a2fdfe4c  (<unknown module>)

==5060==ABORTING

To reiterate, if I run the program outside of the debugger, it proceeds normally.
What can cause this?

A: Breakpad is inserting a right into the process's "task exception port" - which is where you listen for crashes and the like either from within the process or externally - i.e. when you are a debugger.  But in Mach the exception ports only have a single owner.  So when you run under the debugger, Breakpad and the debugger fight for control of the exception port.  For example, if you got your port right set up before the debugger attached, you will end up with a bad port right after the attach, because lldb now owns the port.
Debugging programs that use task exception port handlers is not well supported, because (a) it would be tricky to get that right and (b) there aren't enough programs that need to do this to motivate the effort (at least on the debugger side).  Most people turn off their exception handling for their debug builds since their exception catcher and the debugger are pretty much doing the same job, and it's more convenient to trap in the debugger than the internal exception handler.  And the core part of the exception handler is usually simple enough that you can do printf debugging if you really need to debug that part.


Q: Symfony 2 - Form collection for one entity without parent entity I have problem with form collection. I want to show one form with all values from one entity and I want to be able to add or remove some record(line) from this entity on one page. I have the following solutions, which is ok.
CurrencyController
class CurrencyController extends Controller {
/**
 * @Template()
 */
public function testAction() {
    $em = $this->getDoctrine()->getManager();

    $currencies = $em->getRepository('MyWebBundle:Currency')->findAll();

    $arr = array('currencies' => $currencies);
    $form = $this->createFormBuilder($arr)
    ->add('currencies', 'collection', array(
    'type' => new CurrencyType(),
                'allow_add'    => true,
                'allow_delete'    => true,
                'by_reference' => false,
    ))
    ->add('submit', 'button', array('label' => 'Odeslat'))
    ->getForm();

    return array(
        'form' => $form->createView(),
    );
}
}

CurrencyType
class CurrencyType extends AbstractType {

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder
            ->add('abbreviation', 'text')
            ->add('rate', 'number')
    ;
}

/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver) {
    $resolver->setDefaults(array(
        'data_class' => 'My\WebBundle\Entity\Currency'
    ));
}

/**
 * @return string
 */
public function getName() {
    return 'currency';
}
}

Twig
{% extends '::base.html.twig' %}

{% block body -%}

Test

{{ form(form) }}

{% endblock %}

If I use form class for CurrenciesType, then Symfony throws exception
Notice: Object of class My\WebBundle\Entity\Currency could not be converted to int in
....\web\vendor\symfony\symfony\src\Symfony\Component\
Form\Extension\Core\ChoiceList\ChoiceList.php line 462

Code for this is below.
CurrencyController
class CurrencyController extends Controller {
/**
 * @Template()
 */
public function testAction() {
    $em = $this->getDoctrine()->getManager();

    $currencies = $em->getRepository('MyWebBundle:Currency')->findAll();

    $arr = array('currencies' => $currencies);
    $form = $this->createForm(new CurrenciesType(), $arr);

    return array(
        'form' => $form->createView(),
    );
}
}

CurrenciesType
class CurrenciesType extends AbstractType {

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder
            ->add('currencies', 'collection', array(
                'type' => new CurrencyType(),
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
            ))
            ->add('submit', 'button', array('label' => 'Send'))
    ;
}

/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver) {
    $resolver->setDefaults(array(
        'data_class' => null
    ));
}

/**
 * @return string
 */
public function getName() {
    return 'my_webbundle_currencies';
}
}

CurrencyType and Twig are same as above.
I found solution these solution #1 solution #2, but my symfony still throws exception as above and I don't see different in my solution and these solutions. Please help with this problem. Thank you all :)


Q: How to set the color of margins in a QGridLayout? How to set the color of margins in a QGridLayout? I want to show the different columns and rows separately by placing lines between various rows and columns.
In other words, how to display items in grid-layout such that they are in a table.

A: QGridLayout doesn't draw anything, it just calculates the layout. So the QGridLayout itself cannot draw gridlines for you.
The easiest way is to put a QFrame to each of your QGridLayout's cell and move your content to these QFrames. In WinXP, setting QFrame's frameShape to Box and frameShadow to Plain, you get simple boxes.
You could also create a new widget that draws the gridlines according to the layout that the QGridLayout calculates. By using QGridLayout::itemAtPosition you can get a QLayoutItem for each cell.


Q: MySQL table with a lot of text So I have this database (Size 3.1Gb total), but this is due to one specific table I've got, containing A LOT of console output text, from some test runs. The table itself is 2.7Gb, and I was wondering if there could be another solution for this table, so the database would get a lot smaller? It's getting a bit anoying to backup the database or even make a copy of the database to a playground, because it's so big this table.
The Table is this one

Would it be better to delete this table and make all the LogTextData <- LongText, be stored in a PDF, instead of the database? (Then I can't backup this data tho...)
Do anyone have an idea on how to make this table smaller, or another solution? I'm open for suggestions, to make this table smaller.
The way this console log data gets imported to the database is by Python scipts, so I have fully access to other python solutions, if there is any.

A: You could try enabling either the Storage-Engine Independent Column Compression or InnoDB page compression. Both provides ways to have a smaller on-disk database which is especially useful for the large text fields.
Since there's only one table with one particular field that's taking up space, trying out individual column compression seems like the easiest first step.

A: According to me you should just store the path of log files instead of the complete logs in the database. By using those paths you can access the files anytime you want.
It will decrease the size of database too.
Your new table would look like this,
LogID, BuildID, JenkinsJobName,LogTextData.


Q: Comparar campo data com data atual no datagridviwer Tenho um campo no meu datagridiviwer que se chama "PROGRAMAÇÃO" este campo recebe uma data, que vem do banco como varchar ou string, preciso comparar a data que esta neste campo com a data atual, se for maior que a data atual a linha do data datagridiviwer muda de cor. Fiz o comando abaixo mas não estou conseguindo o resultado que espero, esta trocando a cor de todas as linhas.
segue meu código
else if (row.Cells["PROGRAMAÇÃO"].Value.ToString() != Convert.ToString(DateTime.Now))
{
    row.DefaultCellStyle.BackColor = Color.Bisque;
}

A: Eu faria algo mais ou menos assim:
if (row.Cells["PROGRAMAÇÃO"].Value != null)
{
    DateTime dataProgramacao = DateTime.Parse(row.Cells["PROGRAMAÇÃO"].Value.ToString();
    DateTime dataAtual = DateTime.Now;
    int resultado = DateTime.Compare(dataProgramacao, dataAtual);

    if (resultado < 0)
    //dataProgramacao é menor que a dataAtual
    else if (resultado == 0)
     //datas iguais
    else
    //dataProgramacao é maior que a dataAtual
    //row.DefaultCellStyle.BackColor = Color.Bisque;
}

Creio que atende o que deseja.

A: Converta o valor da célula para DateTime, e depois faça a comparação:
else if (DateTime.Parse(row.Cells["PROGRAMAÇÃO"].Value.ToString()) > DateTime.Now)
{
    row.DefaultCellStyle.BackColor = Color.Bisque;
}

Obs. Se a célula estiver em branco, nula, ou com um formato incorreto, irá acontecer erro no Parse. Talvez seja necessário tratar esse problema.
Edit: Tratando possíveis erros.
if (...)
{
    ...
}
else if (row.Cells["PROGRAMAÇÃO"].Value != null)
{
    DateTime programacao; //variavel auxiliar
    if (DateTime.TryParse(row.Cells["PROGRAMAÇÃO"].Value.ToString(), out programacao))
    {
        if (programacao > DateTime.Now)
            row.DefaultCellStyle.BackColor = Color.Bisque;
    }
}


Q: DLL module can't be found after updating to latest Windows 10, version 2004 I recently updated my Windows 10 Pro to version 2004.  Since then I've had clunky experiences, having to shutdown the computer to get out of trouble.  I am getting a notification saying:

Unable to load DLL iaStorAfserviceApi.dll. The specified module could not be found. (Exception from HRESULT:0x8).

The computer is still functional, and I do not want to "reset" because that would require a complete reinstallation of my other software.  I tried restore point without any results. I don't have a recovery disc.

A: Apparently the Intel Optane software was installed in error during the auto-update
installation of the Intel Storage Drivers.
This usually gives the error of:

Click on Start and run "Add or remove programs".
In the list, click on "Intel Optane Pinning Explorer Extensions"
and then click "Uninstall". Preferably reboot afterward.

A:
I recently updated my Windows 10 Pro to version 2004. Since then I've had clunky experiences, having to shut down the computer to get out of trouble

There are known issues with Intel Optane™ Memory Pinning with Windows 10 version 2004.  In order to resolve properly, you must repair the installation of Intel Optane Pinning Explorer Extensions, then uninstall Intel® Pinning Shell Extensions from within Device Manager.

*

*Run appwiz.cpl

*Locate and highlight Intel Optane Pinning Explorer Extensions.

*Click Repair.

You must now remove the old pinning package in order to prevent error the next time Windows reboots.

*

*Open Device Manager

*Expand the Software components field.

*Right-click the Intel® Pinning Shell Extensions field and select Uninstall Device.

*Check the box that states Delete the driver software for this device. and click Uninstall.

*Reboot

Source: How to Resolve Intel® Optane™ Memory Pinning Error: 'Unable to load DLL ‘iaStorAfsServiceApi.dll'' Encountered


Q: How to set dashed axes on a box plot I would like to figure out if it is possible using pyplot setting a dashed box (I mean the axes of plot contours) of the plot.
I know that could sound strange and horrible. but I would like to try using it.

A: The axes "box" consists of 4 "spines", which are accessible via ax.spines. You may set a linestyle to those as shown below.
import matplotlib.pyplot as plt

fig, axes = plt.subplots(2,2)

linestyles = ["--","-.",":", (0,(5,2,1,4))]

for ax, ls in zip(axes.flat, linestyles):
    for spine in ax.spines.values():
        spine.set_linestyle(ls)
        spine.set_linewidth(2)
    ax.set_title("linestyle: {}".format(ls))

plt.tight_layout()
plt.show()


Q: Having issues with fetching an environment variable In the root of my React project, I have this .env file containing the following.
DS_API_URL=[http://url.com](http:url.com/)

In another file of the project, an axios call utilizes this to return some stuff.
const url = 'http://url.com/graph/tech-stack-by-role' will return what I need.
const url = `${DS_API_URL}/graph/tech-stack-by-role`; returns an error.
How do I fetch the link from the env file and assign it to a var?

A: To use environment variable in react you need to prefix the variable name with process.env.REACT_APP_. Documentation
So in your .env file you have:
REACT_APP_DS_API_URL=[http://url.com](http:url.com/)

Then to use:
const url = `${process.env.REACT_APP_DS_API_URL}/graph/tech-stack-by-role`

Update to answer question:
update your start script to use the .env file you want. in this case it is .env.localhost. You will also need to npm install or yarn install env-cmd:
"start": "env-cmd -f ./.env.localhost react-scripts start",


Q: Capture 2nd entry from database I'm quite new to the programming world and have become stuck with querying a database in C#.
I am trying to return a date and an Int32 from the second entry in a database using the code below:
OleDbCommand com101 = new OleDbCommand("SELECT TOP 2 [Flight_Date], [No_Launches] FROM Flights WHERE [Claimed_By_ID] = ? ORDER BY [Flight_Date] DESC LIMIT 1,1", Program.DB_CONNECTION);
com101.Parameters.Add(new OleDbParameter("", 451));
OleDbDataReader dr101 = com101.ExecuteReader();

when I run the code I get an error saying there is a problem with the Syntax error in ORDER BY clause.
Can anyone spot what I am missing?
Cheers

A: This is your query:
SELECT TOP 2 [Flight_Date], [No_Launches]
FROM Flights
WHERE [Claimed_By_ID] = ?
ORDER BY [Flight_Date] DESC
LIMIT 1,1;

You need to decide which database you are using.  Some support TOP; some support LIMIT.  Based on your error and the use of the square braces, I would guess that you are using SQL Server/Sybase and should remove the LIMIT clause:
SELECT TOP 2 [Flight_Date], [No_Launches]
FROM Flights
WHERE [Claimed_By_ID] = ?
ORDER BY [Flight_Date] DESC;

If this is true, you should change the tag on the question from "mysql" to "sql-server".
EDIT:
To get the second entry, I think you can use a subquery:
SELECT TOP 1 *
FROM (SELECT TOP 2 [Flight_Date], [No_Launches]
      FROM Flights
      WHERE [Claimed_By_ID] = ?
      ORDER BY [Flight_Date] DESC
     ) as t
ORDER BY Flight_Date ASC


Q: Creating an if/elif statement with regex error in python So recently I started learning python through an online education platform and currently I hit a wall.
So the problem is:
Create an if statement that takes an age value. This if statement should print the word “child” if age is 12 or less, “teenager” if age is between 13 and 19 inclusive, and “adult” if age is greater than 19.
and my code is:
age = 16

if age < 13:
    print("child")

elif (age >= 13) and (age < 20):
    print("teenager")

else:
    print("adult")

So according to the website, the part I did for child and adult is correct but the teenager part of it is wrong and is showing this regex message:
Searched your code for a specific pattern:

^elif (13\s*<=\s*age|12\s*<\s*age)?\s*(or|\|)?\s*(age)?(\s*<\s*20|\s*<=\s*19):$\s*print\(('|")teenager('|")\)

So I basically tried learning regex to understand what I did wrong and what I could understand from it is basically but I'm sure that I'm reading it wrong:
elif (13 <= age 12 < age) or (age < 20 <= 19):
    print("teenager")

So what am I missing? Any help would be very much appreciated thanks! :)


Q: java.util.NoSuchElementException: No line found* I keep getting this error
java.util.NoSuchElementException No line found
when I use this method
public boolean hasMoreCommands() {
    if (input.hasNextLine()) {
        return true;
    } else {
        //input.close();
        return false;
    }
}

public void advance() {
    String str;
    if(hasMoreCommands() == true){
        do {
            str = input.nextLine().trim();

            // Strip out any comments
            if (str.contains("//")) {
                str = (str.substring(0, str.indexOf("//"))).trim();
            }
        } while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
        command = str;
  }
}

I have main code here:
public class Ptest
{
  public Ptest(String fileName)
  {
    String line = null;
    String nName = fileName.replace(".vm", ".asm");
    Parser p = new Parser();

    try{
        File neF = new File(nName);
        if(!neF.exists()){
            neF.createNewFile();
        }
        File tempFile = new File("temp.txt");
        if(!tempFile.exists()){
            tempFile.createNewFile();
        }

        FileReader fr = new FileReader(fileName);
        BufferedReader br = new BufferedReader(fr);
        FileWriter fw = new FileWriter(nName);
        BufferedWriter bw = new BufferedWriter(fw);
        FileWriter writR = new FileWriter(tempFile);
        BufferedWriter buffR = new BufferedWriter(writR);
        while((line = br.readLine()) != null) {
            buffR.write(line+ "\n");
            //System.out.println(line);
        }
        buffR.flush();
        buffR.close();
        p.insertTitle(tempFile);
        String ctype = p.commandType();
        int len = ctype.length();
        int spaces = 13 - len;
        String sp = " ";
        String asp = " ";
        String a1 = null;
        int a2;
        int alen;
        boolean t = false;
        while(p.hasMoreCommands()){
            for(int i= 0; i < spaces; i++){
                sp += " ";
            }
            t = p.hasMoreCommands();
            a1 = p.arg1();
            alen = (10 - a1.length());
            for(int i= 0; i < alen; i++){
                asp += " ";
            }
            //a2 = p.arg2();
            if (ctype == "C_PUSH" || ctype == "C_POP" || ctype == "C_FUNCTION" || ctype == "C_CALL") {
                a2 = p.arg2();
                bw.write(ctype + sp + a1 + asp + a2);
            }
            else {
                bw.write(ctype + sp + a1);
            }
            p.advance();
            ctype = p.commandType();
            len = ctype.length();
            spaces = 13 - len;
        }

        bw.flush();
        bw.close();
    }
    catch(FileNotFoundException ex){
        System.out.println("File not found!");
    }
    catch(IOException ex){
        System.out.println("Error reading file '"  + fileName + "'");
    }
  }
}

I went through debugger and it literally goes the entire file then gives me an error when its finished.

A: Like @hfontanez I think your problem is in this code:
if(hasMoreCommands() == true){
    do {
        str = input.nextLine().trim();

        // Strip out any comments
        if (str.contains("//")) {
            str = (str.substring(0, str.indexOf("//"))).trim();
        }
    } while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
    command = str;
}

However, my solution is to change the while clause to while (str.isEmpty() && hasMoreCommands());
I'm assuming that "advance" ought to return the next non-comment / blank line.
If the string from the previous pass is empty (after stripping any comment) it will go round the loop again provided that wasn't the last line. But, if that was the last line or str still has something in it, then it will exit the loop. Comments should have been stripped so don't need tested for in the while.
I think if you just test for hasNextLine within the loop then it will never exit the loop if the last line was comment / blank.

A: My guess is that your problem is here:
if(hasMoreCommands() == true){
    do {
        str = input.nextLine().trim();

        // Strip out any comments
        if (str.contains("//")) {
            str = (str.substring(0, str.indexOf("//"))).trim();
        }
    } while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
    command = str;
}

The exception you encountered (NoSuchElementException) typically occurs when someone tries to iterate though something (String tokens, a map, etc) without checking first if there are any more elements to get.  The first time the code above is executed, it checks to see if it has more commands, THEN it gets in a loop.  The first time it should work fine, however, if the test done by the while() succeeds, the next iteration will blow up when it tries to do input.nextLine().  You have to check is there is a next line to be got before calling this method.  Surround this line with an if(input.hasNextLine()) and I think you should be fine.


Q: Negativity of contraction Let $f:X\to Y$ be a birational morphism, $X, Y$ projective, $X$ smooth (threefold if this helps). Let $Exc(f)\subseteq X$ be the exceptional locus of $f$ and let $E\subseteq Exc(f)$ be an irreducible divisor. Is it true that for any curve $C\subseteq E$ contracted by $f$ one has $C\cdot E<0$? I can see this is true if $C$ is not contained in any other divisor sitting in $Exc(f)$, but what if it is?

A: Dear Carlos, the statement is false in general. For example let $Y$ be $\mathbb{C}^3$, let $f_1 : X_1 \rightarrow Y$ be the blowup of a point on $Y$, and $f_2 : X \rightarrow X_1$ the blowup of a point on the exceptional divisor of $f_1$. Let $f : X \rightarrow Y$ be the composition. The exceptional locus of $f$ has two components: a copy $F$ of $\mathbb{P}^2$ (the exceptional divisor of $f_2$) and a copy $E$ of the blowup of $\mathbb{P}^2$ in one point (the strict transform of the exceptional divisor of $f_1$). The intersection $C = E \cap F$ is a copy of $\mathbb{P}^1$, it is a line on $F$ and the $f_2$-exceptional curve on $E$. Now $E \cdot C$ equals $C^2$ computed on $F$ (because $C=E \cap F$),
so $E \cdot C = +1$.


Q: Page layout with value of calendar control I've got a custom page layout in SP 2010 that will need an ASP.NET calendar control for editors to select a date. Then we want to show the selected date (or a default date if none selected) to the end users (not the calendar control).
The Article Date field won't work because we need editors to be able to select a date. How do you accomplish this? Thanks.

A: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.datetimecontrol.aspx
Would this do?
A better explanation of how it works:
http://karinebosch.wordpress.com/sharepoint-controls/datetimecontrol-control/


Q: Generalization of a class of sets In topological space, we start with open set, which serves as fundamental set. We know that union of finite disjoint open sets is the smallest set amongst any kind of unions of open sets, so we have a least upper bound (or LUB) in the form of a set. Then from this LUB, we define compact set. Compact set is obviously a very important class of sets.
In measurable space, we start with elementary set, which serves as fundamental set. We know that Lebesgue outer measure is the smallest measure amongst other outer measures (e.g. Jordan), so we have a LUB in the form of a measure. Then from this LUB, we define measurable set. Again, measurable set is obviously a very important class of sets.
By fundamental set, I mean every more advanced concepts are defined based on this set, for example: connected, compact, complete, etc in topological space, or integrable, measurable in measurable space.
My questions are:
1) Is there any formal generalized framework for this:
In a certain space, we have fundamental set. In this space, we try to cover a set by another set which satisfies a certain condition in the form of LUB which is formed from this fundamental set. Then from this LUB, we have an important class of sets.
2) Other than measurable and topological space, are there any other examples?


Q: "in back (of)" in American English Some dictionaries say "in back of" means "behind" in American English, as in "there is a garage in back of the house."
There are also dictionaries that say "in back" means "at or in the back", as in "there are three kids sitting in back", presumably in reference to a vehicle.
I'm wondering whether "in back" without "of" can mean "behind", as in "can you see the garage in back?".
I'd appreciate your help.

A: Yes, you can say "can you see the garage in back?" or "the garage is in back."
It's generally clear from context whether you mean 'behind' or 'in the rear portion' - but not always.  In your example there could be confusion between an attached garage on the back portion of the house vs. a detached garage that is some distance behind the house.

A: Regarding "in back", I have the sense that it's more a shortened version of "in the back" – the two are interchangeable.


Q: How can I manage (delete) emails suggested via the autocomplete feature in Outlook 2011 for Mac? I recently switched to using Mac with Outlook 2011 for Mac. For some reasons many of the email addresses the program suggests are wrong and the worths part is that they don't have the "X" next to them so I could delete them from the auto-complete list. They say "other"

How can I remove the "other" emails form being suggested or even better manage (add/remove) that list?
Thank you

A: Undocumented tip: Use the keyboard to delete unwanted recent addresses
The above link contains a tip that gm2 suggested in the comments, but also has an AppleScript snippet that could be worth a try.
tell application "Microsoft Outlook"
    clear recent recipients
end tell

Copy and paste the above three lines into a new window in the AppleScript Editor application found in /Application/Utilities and click the Run button to clear recent addresses. To keep this script readily available select File menu –> Save As… –> Clear Recent Recipients.scpt and save this into your Outlook Script Menu Items folder found in your Home folder (where ” ~ ” denotes your Home folder):
~/Documents/Microsoft User Data/Outlook Script Menu Items
To run the script at any time select it from the AppleScript menu just to the right of the Help menu in Outlook.

Fixing “Recent Address” autofill problems in Outlook 2011
This other post remarks on a feature removed (or moved?) from Entourage that might have been useful and also provides some alternative possibilities.

Non-destructive (recommended):
When composing a message, a number of addresses are popping up. To clear the ones you don’t want from the Recent Addresses database, click the little gray “X” at the end of the line.
For any that don’t have an “X” in the name, here’s how to check the “Me” contact that may be storing those addresses and remove any that aren’t needed:

*

*Click on Contacts in the lower-left corner of the Outlook window.

*In Contacts, click the Organize tab

*Click the button called Me.
The Me contact stores information about the Outlook’s default main user. If it has different information than your name, email, etc, these fields can be updated with your information.
Possibly destructive (not recommended):
There is another way to clear the whole Recent Address cache file, but it could cause data loss so I don’t recommend doing it. It will definitely trigger a database rebuild, which will take some time to run.

*

*Quit Outlook

*Locate this folder in your home folder:
~/Documents/Microsoft User Data/Office 2011 Identities/Main Identity/Data Records/Recent Addresses

*Follow the sub-folders down until you come to a single file (should be named something similar to “x19_36260.olk14Recent”.) Move the file to the Trash.

*Launch Outlook.
When you open Outlook, it will tell you that there’s a problem with the database and will tell you that a rebuild is needed. Select to rebuild the database.
Why I don’t recommend this: I tested both methods, and the rebuild of the database did not work. It finished successfully, but then Outlook would open, display an error then shut back down again. However, it does clear out everything in one shot so I’m including it. Maybe you’ll have better luck than me.

A: Try this:

*

*Copy or remember the Autocomplete email that you want to delete

*Click on People in the lower left area of the Outlook window

*Search for the email you want to delete from Autocomplete

*Delete the entry found


Q: Axios + Typescript: how to pass a param of type "ResponseType"? Axios defines ResponseType as
export type ResponseType =
  | 'arraybuffer'
  | 'blob'
  | 'document'
  | 'json'
  | 'text'
  | 'stream'

I'm trying to pass a configuration to axios.post
const config = {
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Host': HOST_HEADER,
        },
        responseType: 'json'
 }

 const data_to_post = { .... omitted ... }

 return axios.post(HOST, data_to_post, config)

Problem: typescript linter warn me saying the type string cannot be assigned to type ResponseType.
Also tried: Of course I cannot use the syntax
 responseType: ResponseType.json

How can I fix this?

A: The problem is that Typescript will infer config to be of type
{
    headers: {
        'X-Requested-With': string;
        'Content-Type': string;
        'Host-Header': string;
    };
    responseType: string;
}

Typescript does not know that you are trying to create a config object for Axios. You can explicitly type the entire object as AxiosRequestConfig, or you could explicitly type responseType: 'json' to be of type ResponseType.
const config: AxiosRequestConfig = {
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Host-Header': 'dsa',
  },
  responseType: 'json'
};

A: Fixed using explicit casting
responseType: <ResponseType> 'json'


Q: Get source branch name in commit-msg hook of merge commit In the commit-msg hook for a merge commit, how can I get the branch name of the immediate source branch for the merge?  I can get the target branch with something like
git rev-parse --abbrev-ref HEAD

But HEAD and HEAD^ both refer to the target branch.  Is there a way to programmatically determine the source?  I'm using a bash script for the hook.
The default merge commit message contains this text:

Merge branch 'source-branch' into target-branch

So the commit-msg hook could grab the name right out of the message, but there's no guarantee that the user hasn't edited it.  If there's a more foolproof method, I would prefer it.
Edit: ah, unfortunately I also didn't realize that commit-msg doesn't actually even run on merge commits!  So I'll have to find a different way to do what I want anyway.

A: This will give you the commit being merged:
git rev-parse MERGE_HEAD

I do not think that there is a way to find the branch name other than guessing with a command like:
git for-each-ref | grep ^$(git rev-parse MERGE_HEAD)

(which finds all branches pointing to the commit you are merging)
Note that the commit being merged does not have to be a branch, one can also merge a commit directly like git merge deadbeef.
In the case of octopus merge, there is more than one commit being merged at the same time, and MERGE_HEAD is not present.
If you are to extract it from the merge message, then using .git/MERGE_MSG is safer than .git/COMMIT_EDITMSG, since it is less likely to be hand-edited.
The message is generated by git merge, hence has access to the branch name from git merge's arguments, but this does not seem to be stored on disk.

A:
but there's no guarantee that the user hasn't edited it

imvho you should use the merge commit summary line, after the user has had a chance to edit it.
I've edited subject lines for good reason.  All branch names are repo-local. Sometimes you're pulling from a coworker, sometimes you realize you typo'd during branch creation, or you're publishing from a wip that turned out well, there's lots more ways to get there.
If you're worried about inbound commits not meeting your standards for one of your own repositories, vet the inbound commits in its pre-receive.  No dvcs can be sure without doing that anyway.
#!/bin/sh
rc=0
existing=$(git for-each-ref --format='%(object)' refs/heads refs/tags);
validmergesubject='Merge (branch|tag) '\''[^ ]*'\'' (of|into) .*'
while read old new ref; do
    while read commit Subject; do
        if [[ ! $Subject =~ $validmergesubject ]]; then
            echo Merge $commit in $ref history has invalid summary line \"$Subject\"
            rc=1;
        fi;
    done  >&2 <<EOD
$(git log --merges --pretty='%H %s' $new --not $existing)
EOD
done
exit $rc


Q: How to get a range of elements from an array in Redisjson? I have a simple array as such :
[1,2,3,4,5]

and I wish to get a range for example from index 2 to index 4.
I can get the last element of the array by :
json.get key .[-1]

However I cannot find anyway to return a specific results without trimming the array.
Is there anyway I can get a range of elements from a Redis json array?

A: The answer is :
await Client.json.get("key" , {path : '$.[1:3]'})

which gets index 1 to 3.


Q: How to hide url in the popup window opened using window.open I am using below code to open a popup window in my page:
window.open("myPopupWindow.html", "_blank", "height=400, width=550, status=yes, toolbar=no, menubar=no, location=no, addressbar=no, top=200, left=300");

Although the url is disabled but even then it can be seen and copied. I have already set addressbar to no. How can I hide url in popup window?

A: Are you just trying to mask the address, to make it look nicer or hide the fact that you're linking to to another website, or is it that you don't want people to know they can access that page without using your popup?
If it's the former, then what you could do is make the page you open in window.open an iframe, and point the iframe to your actual page.  They user could still access the target page, but only via your nicer looking url.
The other option is to use something like a colorbox with an iframe instead of window.open, which will mask the address. Have a look at the Outside Webpage (iframe) example on this page.
Of course whichever option you choose, someone smart can still track down the target url via the source code and go there directly.

A: window.open('http://mysite/proxy.html')

and in proxy.html :
  <html>
       <body>
          <iframe src="/realPage.html"></iframe>
       </body>

  </html>

A: Simple solution open new tab after that add url to location.href.
window.open('','_blank').location.href = "url"


Q: Germain Primes and Solutions of $x^p+ y^p+ z^p =0$ I am taking a second course on number theory which is primarily of algebraic number theory. So, in the course , professor gave an exercise related to Germain primes and it's application to Fermat's Last Theorem. I think I will need help on this.
Question : Let $p\geq 3$ be a prime and 2p+1 also be prime , then prove that for every (x,y,z) which is solution of $x^p+y^p+z^p=0$,  the congruence $xyz\equiv 0$(mod p) holds.
( Note that my question is not following :Let p be a Germain prime with q = 2p + 1, and suppose that $x^p + y^p = z^p$ (mod q). Then at least one of x, y, z is divisible by q. This result was found by me on a website of a university when I googled my question.) I also know that atleast I didn't knew where to use the fact that 2p+1 is also prime with mu question statement. But , I have checked statement in notes atleast 3 times and so prove or supply a contradiction using my statement of the question only.
Attempt: I have to show that  p divides xyz. But p is prime so p must divide either one of x or y or z atleast.  Now , I thought of using Fermat's Little theorem to equation $x^p+y^p+z^p=0$ but I am not sure that either (x,p)=1 or (y,p)=1 or (z,p)=1. I also can see that $x^p+ y^p +z^p\equiv 0 $( mod p) but again I need a hint or two on how to move foreward.
Kindly help me!

A: Only the sketch of a proof (found on the internet on https://www.math.uni-kiel.de/ in German):
W.l.o.g. we assume that $x,y,z$ are pairwise coprime. Then we consider
\begin{align*}
–x^p &=\underbrace{ (y + z)}_{=:a_1}\underbrace{ (y^{p–1} – y^{p–2}z + y^{p–3}z^2 – ⋅⋅⋅ + z^{p–1})}_{=:a_2}\\
–y^p &=\underbrace{ (z + x)}_{=:b_1} \underbrace{(z^{p–1} – z^{p–2}x + z^{p–3}x^2 – ⋅⋅⋅ + x^{p–1})}_{=:b_2}\\
–z^p &= \underbrace{(x + y)}_{=:c_1}\underbrace{ (x^{p–1} – x^{p–2}y + x^{p–3}y^2 – ⋅⋅⋅ + y^{p–1})}_{=:c_2}
\end{align*}
Next, if one of the pairs $(a_1,a_2),(b_1,b_2),(c_1,c_2)$ has a common divisor, then it can be shown that it is $\pm p$ and thus that $p\mid xyz.$
If otherwise all pairs $(a_1,a_2),(b_1,b_2),(c_1,c_2)$ are coprime, then all numbers $a_1,a_2,b_1,b_2,c_1,c_2$ are powers of $p.$ Then we have to deduce a contradiction by using Fermat's little theorem, which is used to prove:
Let $p$ be a Sophie-Germain prime and $a,x,y,z\in \mathbb{Z}\backslash \{0\}.$ Then $a^{p}=\pm 1 \pmod{(2p+1)}$ or $a^p=0\pmod{2p+1}.$ Thus $x^p+y^p+z^p=0$ implies $2p+1\mid xyz.$
I admit that there is still significant work to do, but it is at least a road map.


Q: A example sentence in the dictionary for the word counterpart The Finnish organization was very different from that of its counterparts in the rest of the Nordic region.
The sentence above is an example sentence I came across, I'd like to know why it has 'that of' before its counterpart because from the viewpoint of understanding, only its counterparts is already able to express the meaning of this sentence clearly, adding the that of make the sentence more confusing.

A: It is possible that "counterparts" refers to "Finland", and "that of" refers to "organization".
"The Finnish organization was very different from the corresponding organizations in the other nations of the Nordic region"
but it sounds as though the writer was trying for increased formality and an "official" sounding statement, and made a mistake.


Q: QFileDialog::getOpenFileName doesn't set the initial directory on Mac OS 10.8 Mountain Lion I can not change the current directory with QFileDialog with Qt 4.8. The same code works fine on Windows and Mac OS 10.6 Snow Leopard. It also works fine if I don't use the native Mac OS X dialog.
This works:
fn=QFileDialog::getOpenFileName(this,"Select File","/Users/myuser/Desktop",QString(),0,QFileDialog::DontUseNativeDialog);

This doesn't work:
fn=QFileDialog::getOpenFileName(this,"Select File","/Users/myuser/Desktop");

It looks like if most of the time it opens the last path of the last call to getOpenFileName.

A: Got the same issue with Qt5.2.0 on Mavericks...
I found a work around: append a dummy file name to the directory you want to select.
However, be sure not to do this on Windows because the user will see it.
QString dir = "/Users/myuser/Desktop";
#if defined(__APPLE__)
dir += "/MyFile.txt";
#endif
fn = QFileDialog::getOpenFileName(this, "Select File", dir);

Also, for those like me that instantiate a file dialog because they need more options you can also do:
QFileDialog fileDialog(this, "Select File");
#if defined(__APPLE__)
fileDialog.selectFile(dir + "/MyFile.txt");
#else
fileDialog.setDirectory(dir);
#endif
...

A: This is a bug in Qt that is reportedly fixed in Qt 5.0.1 and Qt 4.8.4 (though it seems that it still reproducible in 4.8.4 by people (myself included)).
This bug has been reported in JIRA as QTBUG-20771, QTBUG-28161 and finally QTBUG-35779 (which appears to have finally fully resolved the issue in Qt 5.2.1). Here is a link to the patch in Gerrit.


Q: Navigator.getUserMedia and Navigator.webkitGetUserMedia undefined after updating to Chrome 74 After updating from Chrome 73 to 74 navigator.getUserMedia and navigator.webkitGetUserMedia return undefined.
Here https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getUserMedia I see that getUserMedia is actually deprecated in favor of navigator.mediaDevices.getUserMedia(), but in my case navigator.mediaDevices too is undefined so I cannot use it.
Anyone knows if it's a bug in the latest release of Chrome or if I need to use something else?

A: I tried a small setting on chrome and it turned out to work for me.
I enabled: chrome://flags/#unsafely-treat-insecure-origin-as-secure
and provided my HTTP server link along with the port.
It worked for me.
You could refer to the following:
1. https://stackoverflow.com/a/61472984/12906501
2. https://medium.com/@Carmichaelize/enabling-the-microphone-camera-in-chrome-for-local-unsecure-origins-9c90c3149339
Hope it helps!! Thanks.

A: Since version 74 of Chrome navigator.getUserMedia, navigator.webkitGetUserMedia and navigator.mediaDevices can be used only in secure context (https), otherwise they are undefined.
I've understood what the problem was while writing the question, as usual...

A: In my case HTTP was the cause of undefined for navigator.mediaDevices
with HTTPS works as expected


Q: ng-file-upload issue on IE9 - after uploading one file receiving error var prevFiles = ((ngModel && ngModel.$modelValue) || attr.$$ngfPrevFiles || []).slice(0);

I am getting an error that the result of this statement does not have a slice method.

A: Without knowing too much about the module I have a theory:
The first evaluation (ngModel && ngModel.$modelValue), when true, returns a Boolean which does not have a slice method.

A: There was an issue filed in Github about this https://github.com/danialfarid/ng-file-upload/issues/1139
Reportedly fixed in release 10.0.3.


Q: How can the code being allowed to continue from one question to another question even though the input answer had wrong for 3 attempts?

import time
import random
#declare variables and constant
guessingelement = ["Hydrogen", "Magnesium", "Cobalt", "Mercury", "Aluminium", "Uranium", "Antimony"]
nicephrases = ["Nice job", "Marvellous", "Wonderful", "Bingo", "Dynamite"]
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
guess_no = 0
score = 0

#set the maximum number of questions for looping and random pick an element from the list before deleting it
for i in range(7):
    randomelement = random.choice(guessingelement)
    guessingelement.remove(randomelement)
    time.sleep(2)

#tips of the element
if randomelement == "Hydrogen" and not out_of_guesses:
    print("Tip 1: It is the most flammable of all the known substances.")
    print("Tip 2: It reacts with oxides and chlorides of many metals, like copper, lead, mercury, to produce free metals.")
    print("Tip 3: It reacts with oxygen to form water.")

    #test the number of tries so that it doesn't exceed 3 times if answer is wrong
    while guess != randomelement and not(out_of_guesses):
        if guess_count < guess_limit:
            guess = input("Enter guess: ")
            guess_count += 1
        else:
            out_of_guesses = True

    #add score, praise when answer is correct and encourage when answer is wrong for 3 times
    if out_of_guesses:
        print("Out of Guesses, NICE EFFORT!")
    else:
        print(random.choice(nicephrases), ", YOU GET IT!")
        score = score + 1

#tips of the element
    if randomelement == "Magnesium" and not out_of_guesses:
        print("Tip 1: It has the atomic number of 12.")
        print("Tip 2: It's oxide can be extracted into free metal through electrolysis.")
        print("Tip 3: It is a type of metal.")

Same as first questions' code..
and so on....

In the progress of changing:`
#tips of the element
    if randomelement == "Hydrogen":
        print("Tip 1: It is the most flammable of all the known substances.")
        print("Tip 2: It reacts with oxides and chlorides of many metals, like copper, lead, mercury, to produce free metals.")
        print("Tip 3: It reacts with oxygen to form water.")

    #test the number of tries so that it doesn't exceed 3 times if answer is wrong

        while guess != randomelement:
            if guess_count < guess_limit:
                guess = input("Enter guess: ")
                guess_count += 1
            else:
                print(random.choice(wronganswers))

        #add score, praise when answer is correct and encourage when answer is wrong for 3 times
        else:
            print(random.choice(nicephrases), ", YOU GET IT!")
            score = score + 1

However, after 3 times of attempts, it keeps printing the elements from the wronganswers list non-stop,
and can't proceed to the next question.
The output I expected is that it will show an element from the list when the input answer is wrong and
proceed to the next question.

A: I hope this helps. I wrote this code for myself in a new way. I have used recursion to keep the guess happening and simple used a while loop that will break when max attempts go beyond 3.
import random

elements = ["hydrogen", "magnesium", "cobalt", "mercury", "aluminium", "uranium", "antimony"]
nice_phrases = ["Nice job", "Marvellous", "Wonderful", "Bingo", "Dynamite"]

# I went ahead and created a dictionary of lists for storing the Hints
hints = {
    'hydrogen':
        [
            "Tip 1: It is the most flammable of all the known substances.",
            "Tip 2: It reacts with oxides and chlorides of many metals, "
            "like copper, lead, mercury, to produce free metals.",
            "Tip 3: It reacts with oxygen to form water."
        ],
    'magnesium':
        [
            "Tip 1: It has the atomic number of 12.",
            "Tip 2: It's oxide can be extracted into free metal through electrolysis.",
            "Tip 3: It is a type of metal."
        ],
}

score = 0

def guess_again():
    global score
    random_element = random.choice(elements)
    max_attempts = 3

    # this will remove the element from occurring again
    for x in elements:
        if x == random_element:
            elements.remove(x)

    while max_attempts > 0:
        user_guess = input("Take a Guess").lower()

        if user_guess == random_element:
            print(f"{random.choice(nice_phrases)}, you got it!")
            score += 1
            # If the answer is right calling the function again will continue the game
            guess_again()
        else:
            max_attempts -= 1
            print("That was a wrong guess. Here is a Hint")
            if random_element in hints:
                print(hints[random_element])
            else:
                print("Sorry no hints available at the moment")
        if max_attempts == 0:
            print("Sorry your out of guesses")
            print(f"{random.choice} was the element")

guess_again()

If the Answer is right it will select the next element and the game continues until all the elements in the list are finished. I have coded it to give 3 attempts for each elements. If you want the maximum 3 attempts for the entire duration of the game just declare max_attempts outside the function and give it global scope like done for score


Q: if_attribute on declarative authorization I have a many-to-many relationship like this:
A user has_many organizations through affiliations and vice-versa.
I'm using declarative organizations and I only want a user to edit a particular organization if he is affiliated and the affiliationtype attribute of affiliation is a particular value.
So affiliations has 3 columns , user_id, organization_id and affiliationtype_id
I can do:
o = Organization.find(:first)
o.affiliatons[0].user and get the user

now I wish to do this:
has_permission_on [:organizations], :to => :edit do
  if_attribute (...)
end

That if_attribute should see if the current user is the organization.affiliation[?].user and if the organization.affiliation[?].affiliationtype_id = "3"
I hope this is syntax issue ... I really need to get this working.

A: EDIT:
You can restrict the type of affiliation with intersects_with(&block) :
  has_permission_on [:organizations], :to => :edit do
    if_attribute :affiliations => intersects_with {
      user.affiliations.with_type_3
    }
  end

Why not create a named_scope to find affiliations whose affiliationtype_id = 3?

From declarative_authorization documentation:
To reduce redundancy in has_permission_on blocks, a rule may depend on permissions on associated objects:
authorization do
  role :branch_admin do
    has_permission_on :branches, :to => :manage do
      if_attribute :managers => contains {user}
    end

    has_permission_on :employees, :to => :manage do
      if_permitted_to :manage, :branch
      # instead of
      #if_attribute :branch => {:managers => contains {user}}
    end
  end
end


Q: "a ... city, one that": why is there "one" in the apposition? "The first pillar is the concept of Dubai as a global and multicultural city, one that doesn't discriminate about whom to welcome." Dubai: The Making of a Megapolis by Pranay Gupte
Why do we have to add "one" in the appositive clause?
Is "The first pillar is the concept of Dubai as a global and multicultural city that doesn't discriminate..." correct English?
I have the impression one must add "one" but why?
Is the original a relative clause? If yes, shouldn't we have "one which" in an appositional relative clause?
Thanks.

A: "one" is needed in the apposition because appositions are, by definition, nominal (i.e. they have to contain a noun head).
As "one" refers to "a global and multicultural city," it can take a relative clause starting with that or which. If "one" were not there, instead of an apposition we'd have a non-restrictive or non-defining relative clause, and only "which" would be allowed.
I agree with Clare's comment that using a relative clause or an apposition containing a relative clause is only a matter of style. What is clear is that, with the relative clause being restrictive or defining in both cases, the meaning seems to be -- according to grammar rules -- that not all global and multicultural cities don't discriminate about whom to welcome -- Dubai is one that does not, but there might be others that do.
However, in practice the meaning is closer to:

*

*The first pillar is the concept of Dubai as a city that, being global and multicultural, does not discriminate about whom to welcome.


Q: The size of a particular subset of $\mathcal{O}_K$ Let $\mathcal{O}_K$ be the ringer of integers of a number filed $K$ of degree $n$ over $\mathbb{Q}$, with integral basis $\{\omega_1, \ldots, \omega_n\}$. Let $\mathfrak{a}$ be an integral ideal of $\mathcal{O}_K$. It is stated in Murdy and Esmonde's book Problems in Algebraic Number Theory that the set
$$
S = \left\{s \in \mathcal{O}_K \mid s = \sum_{i = 1}^n m_i\omega_i, \quad m_i \in \mathbb{Z}, \quad 0 \le m_i < (N(\mathfrak{a}))^{1/n}+1 \right\}
$$
contains at least $N(\mathfrak{a})+1$ elements. I am having a hard time seeing this. I feel like there should be some geometric intuition behind this claim (viewing $N(\mathfrak{a})$ as the volume of a parallelepiped) but I'm not sure why we're taking the $n$-th root here.

A: The number of $m_i$ is $\lfloor N(\mathfrak{a})^{\frac{1}{n}}\rfloor +1$ multiplying all together we get
$$(\lfloor N(\mathfrak{a})^{\frac{1}{n}}\rfloor +1)^n \leq |S|$$
Now
$$N(\mathfrak{a})=( N(\mathfrak{a})^{\frac{1}{n}} )^n<(\lfloor N(\mathfrak{a})^{\frac{1}{n}}\rfloor +1)^n$$
Note the strict inequality: this gives you the extra $+1$.


Q: Print "hello world" every X seconds Lately I've been using loops with large numbers to print out Hello World:
int counter = 0;

while(true) {
    //loop for ~5 seconds
    for(int i = 0; i < 2147483647 ; i++) {
        //another loop because it's 2012 and PCs have gotten considerably faster :)
        for(int j = 0; j < 2147483647 ; j++){ ... }
    }
    System.out.println(counter + ". Hello World!");
    counter++;
}

I understand that this is a very silly way to do it, but I've never used any timer libraries in Java yet. How would one modify the above to print every say 3 seconds?

A: You can use Thread.sleep(3000) inside for loop.
Note: This will require a try/catch block.

A: public class HelloWorld extends TimerTask{

    public void run() {

        System.out.println("Hello World");
    }
}

public class PrintHelloWorld {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new HelloWorld(), 0, 5000);

        while (true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                System.out.println("InterruptedException Exception" + e.getMessage());
            }
        }
    }
}

infinite loop is created ad scheduler task is configured.

A: The easiest way would be to set the main thread to sleep for 3000 milliseconds (3 seconds):
for(int i = 0; i< 10; i++) {
    try {
        //sending the actual Thread of execution to sleep X milliseconds
        Thread.sleep(3000);
    } catch(InterruptedException ie) {}
    System.out.println("Hello world!");
}

This will stop the thread at least X milliseconds. The thread could be sleeping more time, but that's up to the JVM. The only thing guaranteed is that the thread will sleep at least those milliseconds. Take a look at the Thread#sleep doc:

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

A: Try doing this:
Timer t = new Timer();
t.schedule(new TimerTask() {
    @Override
    public void run() {
       System.out.println("Hello World");
    }
}, 0, 5000);

This code will run print to console Hello World every 5000 milliseconds (5 seconds).
For more info, read https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html

A: Use java.util.Timer and Timer#schedule(TimerTask,delay,period) method will help you.
public class RemindTask extends TimerTask {
    public void run() {
      System.out.println(" Hello World!");
    }
    public static void main(String[] args){
       Timer timer = new Timer();
       timer.schedule(new RemindTask(), 3000,3000);
    }
  }

A: If you want to do a periodic task, use a ScheduledExecutorService. Specifically ScheduledExecutorService.scheduleAtFixedRate
The code:
Runnable helloRunnable = new Runnable() {
    public void run() {
        System.out.println("Hello world");
    }
};

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(helloRunnable, 0, 3, TimeUnit.SECONDS);

A: You can also take a look at Timer and TimerTask classes which you can use to schedule your task to run every n seconds.
You need a class that extends TimerTask and override the public void run() method, which will be executed everytime you pass an instance of that class to timer.schedule() method..
Here's an example, which prints Hello World every 5 seconds: -
class SayHello extends TimerTask {
    public void run() {
       System.out.println("Hello World!");
    }
}

// And From your main() method or any other method
Timer timer = new Timer();
timer.schedule(new SayHello(), 0, 5000);

A: This is the simple way to use thread in java:
for(int i = 0; i< 10; i++) {
    try {
        //sending the actual Thread of execution to sleep X milliseconds
        Thread.sleep(3000);
    } catch(Exception e) {
        System.out.println("Exception : "+e.getMessage());
    }
    System.out.println("Hello world!");
}

A: I figure it out with a timer, hope it helps. I have used a timer from java.util.Timer and TimerTask from the same package. See below:
TimerTask task = new TimerTask() {

    @Override
    public void run() {
        System.out.println("Hello World");
    }
};

Timer timer = new Timer();
timer.schedule(task, new Date(), 3000);

A: What he said. You can handle the exceptions however you like, but
    Thread.sleep(miliseconds);
is the best route to take.
public static void main(String[] args) throws InterruptedException {

A: Here's another simple way using Runnable interface in Thread Constructor
public class Demo {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                for(int i = 0; i < 5; i++){
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("Thread T1 : "+i);
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                for(int i = 0; i < 5; i++) {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("Thread T2 : "+i);
                }
            }
        });

        Thread t3 = new Thread(new Runnable() {

            @Override
            public void run() {
                for(int i = 0; i < 5; i++){
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("Thread T3 : "+i);
                }
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}

A: Add Thread.sleep
try {
        Thread.sleep(3000);
    } catch(InterruptedException ie) {}

A: For small applications it is fine to use Timer and TimerTask as Rohit mentioned but in web applications I would use Quartz Scheduler to schedule jobs and to perform such periodic jobs.
See tutorials for Quartz scheduling.

A: public class TimeDelay{
  public static void main(String args[]) {
    try {
      while (true) {
        System.out.println(new String("Hello world"));
        Thread.sleep(3 * 1000); // every 3 seconds
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}


Q: Why do electrons couple in atoms? In describing electron states in hydrogen, we have a very "simple" picture, at least in intro-quantum. But this only has one electron! As we permit more electrons, we also have things like the exclusion principle, which comes from the spin-statistics theorem, but that relies on the electrons having some kind of coupled wave functions, right? Why do electrons always come in pairs?

A: A potential well in the Schrodinger equation will produce energy levels similar to the energy levels of the hydrogen atom
A nucleus with two protons to be neutral will need two electrons. These will be accommodated in the lowest two energy levels: because of the spin statistics of electrons they cannot occupy the exact same energy level. A nucleus with three protons (Z=3) will need three electrons occupying the lowest three energy levels etc. The electrons may thermally or by photon interactions be kicked up to higher energy levels giving the characteristic spectral lines of the specific atom when returning to the ground state.
Electrons do not come in pairs. The fill up the levels so that the atoms are neutral.


Q: if $A$ and $B$ are open and $A \cap B = \emptyset$, then $A \cap \overline{B} = \overline{A} \cap B = \emptyset$ if $A$ and $B$ are open and $A \cap B = \emptyset$, then  $A \cap \overline{B} =  \overline{A} \cap B = \emptyset$
Assume $A$ and $B$ are open and $A \cap B = \emptyset$. Suppose $\overline{A} \cap B \not= \emptyset$. Then there exists some $x$ such that $x \in \overline{A}$ and $x \in B$. If $x \in \overline{A}$ then any epsilon-ball $B_\epsilon (x)$ will contain points in $A$. Since B is open, $B_\epsilon (x) \subseteq B$. This means that there are points in that are in both $A$ and $B$, which contradicts the assumption that $A \cap B = \emptyset$. Then you can do the same then for the case where $A \cap \overline{B} \not= \emptyset$
Would this be an ok proof of this? If not, what can I improve?

A: Based on your comments, you're dealing with $\mathbb{R}^n$, but you really need to make sure you're defining the space you're working with, either in the theorem or the proof. Your proof is generally correct, but it's sloppy. You should be saying, "Since $B$ is open, there exists $\varepsilon>0$ such that $B_\varepsilon(x)\subseteq B$, and this will contain points in $A$." Also, this is mostly a style thing, but I would recommend saying at the end that the argument for $A\cap \overline{B}\neq 0$ is identical.
Since it seems you're working with analysis, I should point out that this is true for any metric space, not just $(\mathbb{R}^n,d)$, where $d$ is the standard metric (distance formula), and your proof highlights this clearly. I would recommend looking into metric spaces, when you get a chance; this will make a lot more sense then.

A: Your proof is nearly correct and has right the right idea. The one problem is when you use the arbitrary epsilon ball as the ball that will be contained in B. It would be better to start like this: "Suppose x $\in \bar{A}$ and $x \in B$. Then since $B$ is open, there is an $\epsilon > 0$ such that $B_{\epsilon}(x) \subset B$..." Now use the fact that $x$ is in the closure of $A$ to proceed to the contradiction.

A: Getting down into the details, like you did in your proof, is a great way to get used to the concepts, but I will point out that there's an almost trivial proof if you use some basic properties of sets and topology:
Since $A \cap B = \emptyset$, we know that $B \subset A^C$ (where $A ^ C$ is the complement of $A$).  Now there's a general rule that if $D$ and $E$ are arbitrary sets then
$$ D \subset E \implies \overline D \subset \overline E,$$
so
$$ \overline B \subset \overline{A^C} = A^C,$$
because $A$ being open means that $A^C$ is closed. But this implies that $A \cap \overline B = \emptyset$.

A: In any space $X,$ if $B\subset X$ and $a\in X$ we have:
$a\not \in \overline B$ iff there exists an open set $U_a \subset X$ which contains $a$ and is disjoint from $B.$
Now if $A$ is open and disjoint from $B$ then for any $a\in A$ we can take $U_a=A,$ and conclude that no $a\in A$ belongs to $\overline B.$
Similarly with $A,B$ interchanged.


Q: how to create a single webapplication as a sub domain for many companies i am working on a project that you can subscribe with your company name and you can use all features of site specificly to your company.
for example company abcd can get its own url from our website like
www.test.com/abcd/productlist.aspx
company efgh can also login with its own url and see its product list.
www.test.com/efgh/productlist.aspx
can any one help me how can i implement this with my site with best approaches
I am thinking on the approach that will use Global.ascx file to distinguish companies,
i will write code to extract company name from url in global.ascx for every valid request and in all the pages i will put this.form.action = request.rawurl.
is there any other approaches?
if anybody implemented this type of feature, please let me know your approaches.
Thanks

A: If you're working with ASP.NET 3.5 SP1 then you should investigate the new routing engine that has been introduced from the MVC project. It will make for a clean solution.

A: We are using the DLL from http://urlrewriting.net and rules similar to the following:
<urlrewritingnet xmlns="http://www.urlrewriting.net/schemas/config/2006/07">
  <rewrites>
    <add name="Customer" virtualUrl="^~/([^/]+)/([^/]+).aspx" destinationUrl="~/$2.aspx?customer=$1"/>
    <add name="CustomerStart" virtualUrl="^~/([^/]+)/$" destinationUrl="~/Default.aspx?customer=$1"/>
    <add name="CustomerStartAddSlash" virtualUrl="^http\://([^/]+)/([a-zA-Z0-9_-]+)$"
                                      destinationUrl="http://www.example.com/$2/"
                                      redirect="Domain" redirectMode="Permanent" />
  </rewrites>
</urlrewritingnet>

Those rules do the following mappings. These are rewrites, so the user always sees the left-hand URL in his browser:
Rule 1: http://www.example.com/customerA/something.aspx => http://www.example.com/something.aspx?customer=customerA
Rule 2: http://www.example.com/customerA/ => http://www.example.com/Default.aspx?customer=customerA

The third rule is a redirect rather than a rewrite, i.e., it ensures that the trailing slash is added in the user's browser (makes sure that relative paths work correctly):
Rule 3: http://www.example.com/customerA => http://www.example.com/customerA/

A: Take a look at these questions.
Your approach has a name. It's called Multitenancy.

A: I did not found any solution that fully suites my requirement , I have written my own logic for this , which uses Global.ascx's BeginRequest, Login page, Base page and common classes created for Response.Redirect. I am no longer directly using Asp.Net's Response.Redirect, Paths and Session variables, instead I have created wrappers over them to add companyName from url to the Paths.
Let me know if you need more information on my code
Other answers are welcome.
Thanks


Q: Slow insert query I am currently investigating some really slow queries on my MySQL InnoDB DB.
Inserting around 30 records into different tables results in a response time of 13s and I am suspecting that something might be wrong with my indices etc.
This is an example of one of the tables:
CREATE TABLE `record_descriptions60 ` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `record_id` int(10) unsigned NOT NULL,
  `description` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL,
  `status` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `api_name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `comment` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `locale` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `record_descriptions60_record_id_locale_unique` (`record_id`,`locale`),
  CONSTRAINT `record_descriptions60_record_id_foreign` FOREIGN KEY (`record_id`) REFERENCES `records` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

I am trying to do a basic insert as per the log:
array:1 [
  0 => array:3 [
    "query" => "insert into `record_descriptions60` (`description`, `status`, `source`, `api_name`, `comment`, `locale`, `record_id`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
    "bindings" => array:10 [
      0 => "Some desc"
      1 => "approved"
      2 => "api"
      3 => "Some API"
      4 => "A comment."
      5 => "ENG"
      7 => 99
      8 => "2018-07-11 10:26:11"
      9 => "2018-07-11 10:26:11"
    ]
    "time" => 12.45
  ]
]

Any feedback on its structure? Any issues that you can notice?

A: 12.45 milliseconds to INSERT one row is reasonable.  Here are some of the issues:

*

*All UNIQUE keys must be checked for this insert being a duplicate.

*InnoDB is crash-safe; this involves doing at least one disk write to assure it.  (This is one per "transaction"; by default each statement is a transaction.)

*Rule of Thumb:  10ms to do one disk I/O on a spinning (HDD) drive.

*So, 12.45ms elapsed time is realistic.

There are multiple ways to speed that up, and not take 0.5s for 30 inserts:

*

*"Batch" the inserts -- a single INSERT statement with many rows.

*LOAD DATA

*Put several INSERTs in a single transaction (BEGIN...COMMIT) so that that mandatory disk write is done only once for the batch.

*Turn off the write that I am talking about (trade speed vs security).

*Use multiple connections.

*SSDs are faster.

*Consider chucking the AUTO_INCREMENT and promoting the UNIQUE to PRIMARY.

With some combination of those, it is 'easy' to average 1ms per row.  Still, the elapsed time for one write (of several rows) is likely to continue to be more than 10ms.  That is, the response time, as opposed to the throughput, is not likely to get below 10ms.
Also, keep in mind that MySQL can be doing lots of other things (via other connections) at the same time.


Q: How to send a Whatsapp message to a specific user using third party apps in iPhone? Let my app be A and the app user is called A1
I have a completely different person with his mobile mobile number - N1
Now I want achieve the following in my app A - When the user A1 clicks on a button, Whatsapp is opened(if present) with a compose message to the number N1, whether or not he is in his contact list.
I am pretty sure that this is possible on Android as I my self have done it but in iOS, I am not able to find any solution. What ever solutions are out there don't achieve what I want as they open Whatsapp in general, and show me all the users out there. Please, do not redirect to the Whatsapp.com support URL as it is pretty useless.


Q: Ember : sortBy or Ember.computed.sort I saw an example of Ember sortBy somewhere which goes like:
model.sortBy("time").reverse().sortBy("place")

It was working, but am not sure if this is a good way to do that. Would the below a better fit for this. If yes, why.
sortOptions: ['time:desc','place']
Ember.computed.sort('model',sortOptions)

A: model.sortBy("time").reverse().sortBy("place")

Will sort the array model one time.
Ember.computed.sort('model',sortOptions)

Will recompute its value every time model or its properties change.
So what you should use depends on what you need. I don't think there's a significant difference in performance of the sort itself.


Q: PHP extension conflict with Ioncube extension The problem is with the IonCube obfuscation library being used to encode/obfuscate their PHP application.
This IonCube library which is a zend extension, is interfering with PHP extension.
When IonCube is enabled, for all encoded/obfuscated PHP pages monitored, PHP extensions’ “myextensionfunc” method is being skipped because of which I am having problem in my extension code and some transaction related values are missing.
“myextensionfunc i.e. (zend_execute)” function is used by my PHP extension to identify the some transaction related values and to monitor php app methods.
Problem here is that - Is there any workaround(apart from disabling ioncube) so that ioncube doesn't interfere with my php extension?
Please provide some thoughts on this, thanks.


Q: How to convert the standard error of the log odds ratio to the odds ratio standard error I am using the log odds ratio (and its standard error) for meta-analysis. I want to convert back to odds ratio to write up the results... maybe i'm putting in the wrong search terms but can't find info on how to do this.
Obviously the Ln(OR) can be converted by using the exponent, I don't think i can do the same for the standard error of ln(OR)?

A: With an estimate of the log odds ratio $\hat\omega$ & its standard error $\hat\sigma_{\hat\omega}$ you can use the delta method to get an approximation to the standard error of the odds ratio estimate $\newcommand{\e}{\mathrm{e}}\e^\hat\omega$:
$$\newcommand{\Var}{\operatorname{Var}}
\newcommand{\dif}{\mathrm{d}}
\begin{align}
\sqrt{\Var \e^{\hat\omega}} & \approx \sqrt{\left(\left.\frac{\dif \e^x}{\dif x}\right|_\hat\omega\right)^2 \Var \hat\omega }\\
& = \e^{\hat\omega} \hat\sigma_{\hat\omega}
\end{align}$$
(That's assuming your estimate of the log odds ratio is consistent—i.e. it would tend to the true (population) value as sample size increased.)


Q: can't get href from beautifulsoup from 'a class' I'm trying to extract the href from this web site,
but I can't find the way to do that, I tried using this:
busqueda = requests.get('https://autos.mercadolibre.com.ar/vento/_DisplayType_LF')
auto_cont = BeautifulSoup(busqueda.content)
auto_cont.find_all('a',{'class':'item__info-title'}, href = True)

But there is a '< span>' content and I can't overcome that.

A: find_all has been explained. However, your selector is going to produce duplicates as it will pull the same urls from title and price. Instead, I would use a child combinator and a different class for parent and add a child a tag to get the unique list. I prefer select over find_all. select applies css selectors in order to match on elements. All these a tags have an href so no need to add a test.
from bs4 import BeautifulSoup as bs
import requests

r = requests.get('https://autos.mercadolibre.com.ar/volkswagen/vento/_DisplayType_LF')
soup = bs(r.content, 'lxml')
links = [item['href'] for item in soup.select('.list-view-item-title > a')]

Child combinator:

The child combinator (>) is placed between two CSS selectors. It
  matches only those elements matched by the second selector that are
  the children of elements matched by the first.

Ref:

*

*https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.html?highlight=select_one#css-selectors

A: Since you are using Beautiful Soup, it is important to understand that the find_all method will return a list of tags that match your requirements. Your issue is that you want the href attribute of those tags. To do that, you can use the notation tag['attr'] on each tag. To do that we will iterate through the returned tags.
from bs4 import BeautifulSoup
import requests

busqueda = requests.get('https://autos.mercadolibre.com.ar/vento/_DisplayType_LF')
auto_cont = BeautifulSoup(busqueda.content)
print([tag['href'] for tag in auto_cont.find_all('a',{'class':'item__info-title'}, href = True)])

A: Try this:
>>> import requests
>>> s = requests.Session()
>>> resp = s.get("https://autos.mercadolibre.com.ar/vento/_DisplayType_LF")
>>> from lxml import html
>>> doc = html.fromstring(resp.text)
>>> doc.xpath("//a[@class='item__info-title']")
[<Element a at 0x11c005688>, <Element a at 0x11c0059a8>, <Element a at 0x11c007e58>, <Element a at 0x11c007ea8>, <Element a at 0x11c007ef8>, <Element a at 0x11c007c78>, <Element a at 0x11c007db8>, <Element a at 0x11c007e08>, <Element a at 0x11c007d68>, <Element a at 0x11c007cc8>, <Element a at 0x11c007d18>, <Element a at 0x11c007bd8>, <Element a at 0x11c007c28>, <Element a at 0x11c007228>, <Element a at 0x11c003318>, <Element a at 0x11c003408>, <Element a at 0x11c0034f8>, <Element a at 0x11c003688>, <Element a at 0x11c0035e8>, <Element a at 0x11c003228>, <Element a at 0x11c003598>, <Element a at 0x11c003458>, <Element a at 0x11c003278>, <Element a at 0x11c003548>, <Element a at 0x11c0034a8>, <Element a at 0x11c003368>, <Element a at 0x11c0033b8>, <Element a at 0x11c0032c8>, <Element a at 0x11c0031d8>, <Element a at 0x11c003188>, <Element a at 0x11c003098>, <Element a at 0x11c003138>, <Element a at 0x11c0030e8>, <Element a at 0x11c003048>, <Element a at 0x11c0036d8>, <Element a at 0x11c003728>, <Element a at 0x11c003778>, <Element a at 0x11c0037c8>, <Element a at 0x11c003818>, <Element a at 0x11c003868>, <Element a at 0x11c0038b8>, <Element a at 0x11c003908>, <Element a at 0x11c003958>, <Element a at 0x11c0039a8>, <Element a at 0x11c0039f8>, <Element a at 0x11c003a48>, <Element a at 0x11c003a98>, <Element a at 0x11c003ae8>, <Element a at 0x11c003b38>, <Element a at 0x11c003b88>, <Element a at 0x11c003bd8>, <Element a at 0x11c003c28>, <Element a at 0x11c003c78>, <Element a at 0x11c003cc8>, <Element a at 0x11c003d18>, <Element a at 0x11c003d68>, <Element a at 0x11c003db8>, <Element a at 0x11c003e08>, <Element a at 0x11c003e58>, <Element a at 0x11c003ea8>, <Element a at 0x11c003ef8>, <Element a at 0x11c003f48>, <Element a at 0x11c003f98>, <Element a at 0x11c006048>, <Element a at 0x11c006098>, <Element a at 0x11c0060e8>, <Element a at 0x11c006138>, <Element a at 0x11c006188>, <Element a at 0x11c0061d8>, <Element a at 0x11c006228>, <Element a at 0x11c006278>, <Element a at 0x11c0062c8>, <Element a at 0x11c006318>, <Element a at 0x11c006368>, <Element a at 0x11c0063b8>, <Element a at 0x11c006408>, <Element a at 0x11c006458>, <Element a at 0x11c0064a8>, <Element a at 0x11c0064f8>, <Element a at 0x11c006548>, <Element a at 0x11c006598>, <Element a at 0x11c0065e8>, <Element a at 0x11c006638>, <Element a at 0x11c006688>, <Element a at 0x11c0066d8>, <Element a at 0x11c006728>, <Element a at 0x11c006778>, <Element a at 0x11c0067c8>, <Element a at 0x11c006818>, <Element a at 0x11c006868>, <Element a at 0x11c0068b8>, <Element a at 0x11c006908>, <Element a at 0x11c006958>, <Element a at 0x11c0069a8>, <Element a at 0x11c0069f8>, <Element a at 0x11c006a48>, <Element a at 0x11c006a98>, <Element a at 0x11c006ae8>, <Element a at 0x11c006b38>, <Element a at 0x11c006b88>]
>>> doc.xpath("//a[@class='item__info-title']/@href")
['https://auto.mercadolibre.com.ar/MLA-793135798-volkswagen-vento-20t-sportline-2007-4p-dh-aa-san-blas-auto-_JM', 'https://auto.mercadolibre.com.ar/MLA-793135798-volkswagen-vento-20t-sportline-2007-4p-dh-aa-san-blas-auto-_JM', 'https://auto.mercadolibre.com.ar/MLA-788603493-volkswagen-vento-25-advance-plus-manual-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-788603493-volkswagen-vento-25-advance-plus-manual-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-774423219-vento-comfortline-0km-2019-volkswagen-linea-nueva-vw-2018-_JM', 'https://auto.mercadolibre.com.ar/MLA-774423219-vento-comfortline-0km-2019-volkswagen-linea-nueva-vw-2018-_JM', 'https://auto.mercadolibre.com.ar/MLA-795714156-volksvagen-vento-advance-plus-25-anticipo-290000-y-ctas-_JM', 'https://auto.mercadolibre.com.ar/MLA-795714156-volksvagen-vento-advance-plus-25-anticipo-290000-y-ctas-_JM', 'https://auto.mercadolibre.com.ar/MLA-792330462-volkswagen-vento-25-luxury-wood-tiptronic-2009-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-792330462-volkswagen-vento-25-luxury-wood-tiptronic-2009-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-763941297-vento-highline-0km-automatico-auto-nuevos-volkswagen-vw-2019-_JM', 'https://auto.mercadolibre.com.ar/MLA-763941297-vento-highline-0km-automatico-auto-nuevos-volkswagen-vw-2019-_JM', 'https://auto.mercadolibre.com.ar/MLA-791000164-volkswagen-vento-20-advance-115cv-2015-_JM', 'https://auto.mercadolibre.com.ar/MLA-791000164-volkswagen-vento-20-advance-115cv-2015-_JM', 'https://auto.mercadolibre.com.ar/MLA-788125558-volkswagen-vento-14-tsi-highline-150cv-at-2017-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-788125558-volkswagen-vento-14-tsi-highline-150cv-at-2017-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-777140113-volkswagen-vento-gli-dsg-nav-my-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-777140113-volkswagen-vento-gli-dsg-nav-my-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-795016462-volkswagen-vento-25-luxury-tiptronic-2011-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-795016462-volkswagen-vento-25-luxury-tiptronic-2011-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-792487602-volkswagen-25-luxury-170cv-tiptronic-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-792487602-volkswagen-25-luxury-170cv-tiptronic-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-789645020-volkswagen-vento-20-advance-115cv-summer-package-371-_JM', 'https://auto.mercadolibre.com.ar/MLA-789645020-volkswagen-vento-20-advance-115cv-summer-package-371-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185003-vw-0km-volkswagen-vento-14-comfortline-highline-financiado-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185003-vw-0km-volkswagen-vento-14-comfortline-highline-financiado-_JM', 'https://auto.mercadolibre.com.ar/MLA-774502893-volkswagen-vento-14-comfortline-150cv-at-dsg-0km-2019-vw-_JM', 'https://auto.mercadolibre.com.ar/MLA-774502893-volkswagen-vento-14-comfortline-150cv-at-dsg-0km-2019-vw-_JM', 'https://auto.mercadolibre.com.ar/MLA-795734858-volkswagen-vento-25-luxury-tiptronic-2009-_JM', 'https://auto.mercadolibre.com.ar/MLA-795734858-volkswagen-vento-25-luxury-tiptronic-2009-_JM', 'https://auto.mercadolibre.com.ar/MLA-795501655-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-795501655-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-792476554-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792476554-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-790622152-volkswagen-vento-14-tsi-comfortline-dsg-como-nuevo-_JM', 'https://auto.mercadolibre.com.ar/MLA-790622152-volkswagen-vento-14-tsi-comfortline-dsg-como-nuevo-_JM', 'https://auto.mercadolibre.com.ar/MLA-741867064-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-741867064-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-770677950-volkswagen-vento-20-sportline-tsi-200cv-dgs-_JM', 'https://auto.mercadolibre.com.ar/MLA-770677950-volkswagen-vento-20-sportline-tsi-200cv-dgs-_JM', 'https://auto.mercadolibre.com.ar/MLA-756888148-volkswagen-vento-14-highline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-756888148-volkswagen-vento-14-highline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792470321-volkswagen-vento-highline-14-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792470321-volkswagen-vento-highline-14-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-780443475-volkswagen-vento-20-sportline-tsi-200cv-bi-xenon-_JM', 'https://auto.mercadolibre.com.ar/MLA-780443475-volkswagen-vento-20-sportline-tsi-200cv-bi-xenon-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185107-vw-0km-volkswagen-vento-14-comfortline-highline-financio-ya-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185107-vw-0km-volkswagen-vento-14-comfortline-highline-financio-ya-_JM', 'https://auto.mercadolibre.com.ar/MLA-763006237-volkswagen-nuevo-vento-comfortline-14-tsi-150cv-autotag-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-763006237-volkswagen-nuevo-vento-comfortline-14-tsi-150cv-autotag-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-792344363-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792344363-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-789195021-volkswagen-vento-comfortline-motor-14-at-tiptronic-_JM', 'https://auto.mercadolibre.com.ar/MLA-789195021-volkswagen-vento-comfortline-motor-14-at-tiptronic-_JM', 'https://auto.mercadolibre.com.ar/MLA-787103884-volkswagen-vento-comfortline-14-150-cv-dsg-_JM', 'https://auto.mercadolibre.com.ar/MLA-787103884-volkswagen-vento-comfortline-14-150-cv-dsg-_JM', 'https://auto.mercadolibre.com.ar/MLA-795438039-volkswagen-vento-14-highline-150cv-at-financio-leasing-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-795438039-volkswagen-vento-14-highline-150cv-at-financio-leasing-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-785080712-vento-25-advance-manual-permutofinancio-_JM', 'https://auto.mercadolibre.com.ar/MLA-785080712-vento-25-advance-manual-permutofinancio-_JM', 'https://auto.mercadolibre.com.ar/MLA-739533930-volkswagen-vento-20-tsi-i-2017-i-permuto-i-financio-_JM', 'https://auto.mercadolibre.com.ar/MLA-739533930-volkswagen-vento-20-tsi-i-2017-i-permuto-i-financio-_JM', 'https://auto.mercadolibre.com.ar/MLA-787212749-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-787212749-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-785738851-volkswagen-vento-advance-summer-package-20-unico-dueno--_JM', 'https://auto.mercadolibre.com.ar/MLA-785738851-volkswagen-vento-advance-summer-package-20-unico-dueno--_JM', 'https://auto.mercadolibre.com.ar/MLA-788508924-volkswagen-vento-25-advance-tiptronic-2007-_JM', 'https://auto.mercadolibre.com.ar/MLA-788508924-volkswagen-vento-25-advance-tiptronic-2007-_JM', 'https://auto.mercadolibre.com.ar/MLA-790696083-volkswagen-vento-14-highline-150cv-at-0km-tiptronic-nuevo-1-_JM', 'https://auto.mercadolibre.com.ar/MLA-790696083-volkswagen-vento-14-highline-150cv-at-0km-tiptronic-nuevo-1-_JM', 'https://auto.mercadolibre.com.ar/MLA-788446116-volkswagen-vento-20-sportline-tsi-200-2013-luxury-tdi-bora-_JM', 'https://auto.mercadolibre.com.ar/MLA-788446116-volkswagen-vento-20-sportline-tsi-200-2013-luxury-tdi-bora-_JM', 'https://auto.mercadolibre.com.ar/MLA-752087027-volkswagen-nuevo-vento-14-highline-0-km-2019-autotag-cb-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-752087027-volkswagen-nuevo-vento-14-highline-0-km-2019-autotag-cb-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-781505508-nuevo-vento-entrega-inmediata-tomo-usado-moto-auto-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-781505508-nuevo-vento-entrega-inmediata-tomo-usado-moto-auto-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-742485511-volkswagen-vento-14-highline-150cv-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-742485511-volkswagen-vento-14-highline-150cv-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-769182377-vw-volkswagen-vento-gli-230-cv-preventa-2019-0-km-_JM', 'https://auto.mercadolibre.com.ar/MLA-769182377-vw-volkswagen-vento-gli-230-cv-preventa-2019-0-km-_JM', 'https://auto.mercadolibre.com.ar/MLA-790609996-volkswagen-vento-20-luxury-i-140cv-dsg-automatico-diesel-_JM', 'https://auto.mercadolibre.com.ar/MLA-790609996-volkswagen-vento-20-luxury-i-140cv-dsg-automatico-diesel-_JM', 'https://auto.mercadolibre.com.ar/MLA-790664862-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-790664862-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-784454164-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-784454164-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-769868579-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-d-_JM', 'https://auto.mercadolibre.com.ar/MLA-769868579-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-d-_JM', 'https://auto.mercadolibre.com.ar/MLA-787564006-volkswagen-vento-20t-sportline-automatico-dsg-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-787564006-volkswagen-vento-20t-sportline-automatico-dsg-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-788080154-volkswagen-vento-20-sportline-tsi-200cv-dgs-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-788080154-volkswagen-vento-20-sportline-tsi-200cv-dgs-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-771885864-volkswagen-vento-14-comfortline-150cv-aut-sf-_JM', 'https://auto.mercadolibre.com.ar/MLA-771885864-volkswagen-vento-14-comfortline-150cv-aut-sf-_JM', 'https://auto.mercadolibre.com.ar/MLA-795273990-vento-25-manual-unico-dueno-80000-km-motor-cadenero-_JM', 'https://auto.mercadolibre.com.ar/MLA-795273990-vento-25-manual-unico-dueno-80000-km-motor-cadenero-_JM', 'https://auto.mercadolibre.com.ar/MLA-769870550-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-f-_JM', 'https://auto.mercadolibre.com.ar/MLA-769870550-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-f-_JM', 'https://auto.mercadolibre.com.ar/MLA-790653682-volkswagen-vento-25-triptronic-170-cv-cuero-carhaus-_JM', 'https://auto.mercadolibre.com.ar/MLA-790653682-volkswagen-vento-25-triptronic-170-cv-cuero-carhaus-_JM']


Q: Upload csv files from ftp into SF via Apex (without insertFile Tag) I want to automatically upload csv files into Salesforce on a regular basis, doing a scheduled job. I want to have this job centralized so that everybody has access to the code and the process. I want to do proper error handling so that the users get notified in case an upload fails. Due to company policies, we cannot access the database directly, only the csv on a ftp server. Can the upload be done without middleware?