text:
Q: Body onLoad not working if a script tab is included inside body Summary:
Following body onload works when a link to another script using <script> is included in the head tag but not while the same <script> is included just before the end of body
<body onload="console.log('body loaded');">

To Reproduce:
Load Complete code in Fiddle
When we set the Javascript Loadtype to No Wrap - In <head>, we see the following logs in the console:
DOM Loaded
window loaded
body loaded

But when we set it to No Wrap - In <body>, we see the following logs in the console:
DOM Loaded
window loaded

Why the difference?

A: Setting it in body tag needs to wait for all the resources to be rendered in page such as images, styles, scripts etc.
When you put it inside head tag, no need to wait for the resources to be rendered.
It's like between window.on('load') and document.ready in jquery.


text:
Q: NRPE: Unable to read output #!/usr/bin/env bash

DEFAULT_WARN_SECONDS=60
DEFAULT_CRIT_SECONDS=120

while getopts  'hp:c:w:' option; do
    case $option in
        h) help=1;;
        p) path=$OPTARG;;
        c) crit=$OPTARG;;
        w) warn=$OPTARG;;
    esac
done

if [ -n "$help" ] || [ -z "$path" ]; then
    echo "usage: $0 -p [path (required)] -w [warning threshhold seconds] -c [critical threshhold seconds]" 1>&2
    exit 4
elif ! [ -e "$path" ]; then
    echo "fatal: invalid or unreadable file path provided: $path" 1>&2
    exit 3
fi

if [ -z "$warn" ]; then
    warn=$DEFAULT_WARN_SECONDS
fi
if [ -z "$crit" ]; then
    crit=$DEFAULT_CRIT_SECONDS
fi

seconds=$(($(date +'%s') - $(stat --format='%Y' $path)))

if [ $seconds -gt $crit ]; then
    echo "CRITICAL: $path was last modified $seconds seconds ago"
    exit 1
elif [ $seconds -gt $warn ]; then
    echo "WARNING: $path was last modified $seconds seconds ago"
    exit 2
else
    echo "OK: $path was last modified $seconds seconds ago"
    exit 0
fi

When I run the script in localhost it is working :
./check_last -p /root/Ratify/apache-tomcat-ratify/target/ratify.log -w 30 -c 40
**output:**
OK: /root/Ratify/apache-tomcat-ratify/target/ratify.log was last modified 24 seconds ago

When I run the script from remote server it is not working :
./check_nrpe -H 00.00.0.00 -c check_ratify
NRPE: Unable to read output

Please suggest solution.

A: This is usually a permissions issue. If the nrpe or nagios user can't access the path you are trying to stat, you'll get that. And I see your example is trying to access a file under the /root directory, which is only readable by the superuser.
So, I guess you're running your local example as root, but the remote check is run as nrpe or nagios. If you really need to access that path, you have to configure permissions accordingly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create database table from CSV I am working on a module that requires access to some tabular data provided from an external source. It's only two columns but has roughly 40000 rows.
Currently, my module is just parsing the CSV in entirety when necessary. This works well, but since the file is about 450Kb, this will eat up server resources once deployed to a production site.
I'd like to move this data to a Magento table and am having trouble.
I'm using the RDBMS methods in my setup script, ala:
$installer = $this;
$installer->startSetup();

$table = $installer->getConnection()
    ->newTable($installer->getTable('my_table'))
    ->addColumn('column_a', Varien_Db_Ddl_Table::TYPE_TEXT, 5, array(
        'nullable' => false,
        ), 'Column A')
    ->addColumn('column_b', Varien_Db_Ddl_Table::TYPE_TEXT, 3, array(
        'nullable' => false,
        ), 'Column B');

$installer->getConnection()->createTable($table);

$installer->endSetup();

This works just fine to create my table, but actually getting my data in is wracking my head (I'm still a noob when it comes to database management).
Ideally, I would just parse my CSV file and insert values into the table without having to deal with a bunch of copy/paste.
Are there any built-in methods for handling arbitrary CSV data, or are they all built to handle just what they need to? What would be the best approach to get my data into Magento?

A: Never done this. Let's play!
After the createTable() call, or in a subsequent script:
/* @var $installer Mage_Core_Model_Resource_Setup */
$installer = $this;
$installer->startSetup();

//Extract data from CSV file
$csv = new Varien_File_Csv;
$data = $csv->getData('path/to/file.csv');

$resultNum = $installer->getConnection()->insertArray(
    $installer->getTable({TABLE NAME}),
    array({COL 1},{COL 2}),    //column names
    $data
);

//EDIT: if this is done using a data setup script, can even log the results:
Mage::log(
    __FILE__." added $resultNum records to $installer->getTable({TABLE NAME})",
    Zend_Log::INFO,
    "setup.log",
    true
);

$installer->endSetup();


text:
Q: Running Excel macros from R through RDCOMClient, error -2147418111 The objective is to add data to an existing excel file with OpenXLSX, then run macros in the same Excel file using RDCOMClient, saving it along the way, from an R script.
The Excel macros make changes to the pivot table filters and collapse points that must occur after the data is loaded.
This small, reproduction of the problem works without issue:
library(openxlsx)
library(RDCOMClient)

ds <- cars
tmpl <- './templates/templatetest.xlsm'
datatab <- 'data'
datarng <- 'pdata'
fn <- paste0("./WAR/", "test1.xlsm")

wb <- loadWorkbook(tmpl)
writeData(wb, datatab, ds)
saveWorkbook(wb, fn, overwrite = TRUE)
rm(wb)

# note this doesn't reveal the full actual UNC path
fn <- paste0("./WAR/",
             "test1.xlsm")

xlApp <- COMCreate("Excel.Application")
xlWbk <- xlApp$Workbooks()$Open(fn)

# run macros
xlApp$Run("clear_pt_filters")
xlApp$Run("CollapsePivotFields")
xlApp$Run("toggle_alcItems")

# Close the workbook and quit the app:
xlWbk$Close(TRUE)
xlApp$Quit()

# Release resources:
rm(xlWks, xlWbk, xlApp)
gc()

However, when running in production, I get an error at the first macro line:
xlApp$Run("clear_pt_filters")

Error in .COM(x, name, ...) :    Cannot locate 0 name(s) Run in COM
  object (status = -2147418111)

I am suspicious that it is due to the time of loading the 1-2 MB file while R is proceeding without a signal that RDCOMClient is ready for the macro run request.
I manually resolve this by simply running the script again, starting from the same macro line. In the end, the error just prevents full automation, the spreadsheets turn out exactly as expected.
Edit: If I step through the 'production' version line by line, there is no error.
The questions that I have are 1) what is the the cause of the error, and 2) what can I do to resolve the issue in automation?
Thanks.

A: The simplest solution found that I'm using is to insert a single second pause using Sys.sleep().
Sys.sleep(1)

So, it looks like this, from above, edited:
xlApp <- COMCreate("Excel.Application")
xlWbk <- xlApp$Workbooks()$Open(fn)

# run macros
Sys.sleep(1)
xlApp$Run("clear_pt_filters")
xlApp$Run("CollapsePivotFields")
xlApp$Run("toggle_alcItems")

# Close the workbook and quit the app:
xlWbk$Close(TRUE)
xlApp$Quit()

# Release resources:
rm(xlWbk, xlApp)
gc()

Credit to Is there a "pause" function in R?

A: I would imagine the issue is that the saveWorkbook() function is meant to save in xlsx format and probably not retaining the macro information in the workbook. What may work better, is to process this entirely with RDCOMClient. Possibly by a method such as this.
library(openxlsx)
library(RDCOMClient)

ds <- cars
tmpl <- './templates/templatetest.xlsm'
newfile <- './templates/templatetestNEW.xlsm'

# Create Excel instance
xlApp <- COMCreate("Excel.Application")

# Open workbook template
xlWB <- xlApp$Workbooks()$Open(tmpl)

# Select the "data" Sheet
xlSheet <- xlWB$Sheets("data")

# Create a dataframe from headers
headers <- t(as.data.frame(colnames(ds)))
# Set range for headers
rng <- xlSheet$Range(xlSheet$Cells(1, 1),xlSheet$Cells(1, ncol(headers)))
# Insert headers
rng[["Value"]] <- asCOMArray(headers)

# Set range for data values
rng <- xlSheet$Range(xlSheet$Cells(2, 1),xlSheet$Cells(nrow(ds)+1, ncol(ds)))

# Add data to Excel sheet
rng[["Value"]] <- asCOMArray(ds)

# Save Workbook
xlWB$SaveAs(gsub("/","\\\\",newfile))

# run macros
xlApp$Run("clear_pt_filters")
xlApp$Run("CollapsePivotFields")
xlApp$Run("toggle_alcItems")

# Close the workbook and quit the app:
xlWbk$Close(TRUE)
xlApp$Quit()

# Release resources:
rm(xlWks, xlWbk, xlApp)
gc()


text:
Q: Remove whole sections of strings I'm trying to remove a part of a string meaning only a small section would be left, but with the ability to change the desired remaining part depending on user input. I have tried df_abil.columns.str.removeprefix("{'name':") but it didn't work.
Hard to explain, sorry, but here's an example:
import requests
import pandas as pd

temp='chandelure' #User input added later
r2 = requests.get('https://pokeapi.co/api/v2/pokemon/' + temp)
type(r2)
data2 = r2.json()
df_abil = pd.DataFrame()
df_abil = pd.DataFrame(data2['abilities'])
df_abil['ability'] = df_abil['ability'].astype(str)

Current Output:

ability
is_hidden
slot

{'name': 'flash-fire', 'url': 'https  ://pokeapi...
False
1

{'name': 'flame-body', 'url': 'https  ://pokeapi...
False
2

{'name': 'infiltrator', 'url': 'https  ://pokeap...
True
3

Desired output:

ability
is_hidden
slot

'flash-fire'
False
1

'flame-body'
False
2

'infiltrator'
True
3

Any help would be greatly appreciated, thanks! <3


text:
Q: ¿Cómo ordeno un arreglo de objetos dependiendo la suma de sus atributos? Estoy desarrollando un aplicación de ventas. Tengo 2 arreglos de objetos, uno con los nombres de los vendedores y otro con las ventas realizadas del mes. Mi idea era ordenar el arreglo de nombres dependiendo del que hizo más ventas al que hizo menos usando la información del arreglo de ventas.
Intenté realizar un reduce sumando las ventas de cada vendedor, pero no se me ocurre cómo realizarlo para los 3 vendedores y luego de eso compararlos para ordenar el arreglo de objetos de nombres.
const vendedores = [{id:1,name: 'juan', age: 23},{id:2,name: 'adrian', age: 32},{id:3,name: 'apolo', age: 45}];

const ventas= [{equipo: 'frances', vendedorId: 2, cantidad: 234},{equipo: 'italiano', vendedorId: 3, cantidad: 24},{equipo: 'polaco', vendedorId: 1, cantidad: 534},{equipo: 'frances', vendedorId: 2, cantidad: 1234},{equipo: 'frances', vendedorId: 3, cantidad: 2342}];

const mejoresVendedores= () => {
//no se como hacerlo para los 3 vendedores y despues compararlos para ordenar el arreglo de nombres
 ventas.reduce((sum, value) => ( value.vendedorId == 1 ? sum + value.area : sum), 0);

}

A: Tal vez no es la mejor forma, pero creo que podrías resolver con esto:
const ordenar = vendedores.map((vendedor) => {
    vendedor.ventas = ventas.reduce((suma, vta) => {
                            suma += (vta.vendedorId === vendedor.id)?1:0;
                            return suma;
                        }, 0);
    return vendedor;
});

ordenar.sort((a, b) => b.ventas > a.ventas);

Hice un par de pruebas y al parecer funciona, me devuelve esto:
[ { id: 2, name: 'adrian', age: 32, ventas: 2 },
  { id: 3, name: 'apolo', age: 45, ventas: 2 },
  { id: 1, name: 'juan', age: 23, ventas: 1 } ]

Espero te ayude o te de un norte de lo que ocupas hacer.
Mi recomendación seria meter en el primer objeto la cantidad de ventas que cada vendedor ha hecho como arreglo, así puedes tener el numero de ventas por cada uno y ordenas basado en eso.
Saludos

A: Primero necesitas ordenar el arreglo ventas usando el campo cantidad de mayor a menor. Una vez ordenado el arreglo, necesitarías juntar los 2 arreglos por medio de su ID. Te dejo un ejemplo:

const vendedores = [
  {id:1,name: 'juan', age: 23},
  {id:2,name: 'adrian', age: 32},
  {id:3,name: 'apolo', age: 45}
];

const ventas = [
  {equipo: 'frances', vendedorId: 2, cantidad: 234},
  {equipo: 'italiano', vendedorId: 3, cantidad: 24},
  {equipo: 'polaco', vendedorId: 1, cantidad: 534},
  {equipo: 'frances', vendedorId: 2, cantidad: 1234},
  {equipo: 'frances', vendedorId: 3, cantidad: 2342}
];

function multiSort(array, sortObject = {}) {
    const sortKeys = Object.keys(sortObject);

    // Devuelve una matriz si no se proporciona ningún objeto de ordenación.
    if (!sortKeys.length) {
        return array;
    }

    // Cambie los valores de las claves sortObject a -1, 0 o 1.
    for (let key in sortObject) {
        sortObject[key] = sortObject[key] === 'desc' || sortObject[key] === -1 ? -1 : (sortObject[key] === 'skip' || sortObject[key] === 0 ? 0 : 1);
    }

    const keySort = (a, b, direction) => {
        direction = direction !== null ? direction : 1;

        if (a === b) { // Si los valores son los mismos, no cambie de posición.
            return 0;
        }

        // Si b > a, multiplique por -1 para obtener la dirección inversa.
        return a > b ? direction : -1 * direction;
    };

    return array.sort((a, b) => {
        let sorted = 0;
        let index = 0;

        // Ciclo while hasta que se clasifique (-1 o 1) o hasta que se hayan procesado las claves de clasificación.
        while (sorted === 0 && index < sortKeys.length) {
            const key = sortKeys[index];

            if (key) {
                const direction = sortObject[key];

                sorted = keySort(a[key], b[key], direction);
                index++;
            }
        }

        return sorted;
    });
}

// Juntamos los 2 arreglos por medio de su ID
const mergeArrays = (arr1 = [], arr2 = []) => {
   let res = [];
   res = arr1.map(obj => {
      const index = arr2.findIndex(el => el["id"] == obj["vendedorId"]);
      const { name } = index !== -1 ? arr2[index] : {};
      return {
         ...obj,
         name
      };
   });
   return res;
};

// En esta línea puedes cambiar el orden ya sea 'asc' o 'desc'
console.log(mergeArrays(multiSort(ventas, {cantidad: 'desc'}), vendedores));


text:
Q: Progress Dialog in Thread NullPointer Exception Hi i have a fragment and when i call it from my MainActivity i start a Thread to show somethings of BD
private ProgressDialog progressDialog;

@Override
    public void onStart()
    {
        super.onStart();

        Bundle args = getArguments();

        if ( args != )
        {
            progressDialog.show( getActivity(), "Query", "Please wait", true, false );
            // Here i call my thread
            mRutFechas( progressDialog );
        }
    }

my thread
private void mRutFechas( final ProgressDialog progressDialog )
{
        Thread nt = new Thread()
        {
            @Override
            public void run()
            {
                // Lot of BD Conecction work

                 // Display
                 getActivity().runOnUiThread( new Runnable()
                 {
                     @Override
                     public void run()
                     {
                         // Screen update
                     }
                 });
              progressDialog.dismiss();
            }
        };
        nt.start();
}

The popup show propertly but when its time to close to display throw
03-12 11:52:29.132  25504-25618/com.example.camilo.relojcontrol_navdraw E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-9962
    java.lang.NullPointerException
            at com.example.camilo.relojcontrol_navdraw.F_RelojMostrar$2.run(F_RelojMostrar.java:301)

EDIT: When i put in run UI Thread it gives me this error
03-12 12:20:09.652  27235-27235/com.example.camilo.relojcontrol_navdraw E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.example.camilo.relojcontrol_navdraw.F_RelojMostrar$2$1.run(F_RelojMostrar.java:300)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4963)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
            at dalvik.system.NativeStart.main(Native Method)

A: Your ProgressDialog progressDialog; is NULL in mRutFechas()
Because show() method will create a ProgresssDialog as a static.
Try to change it with
private ProgressDialog progressDialog;

@Override
 public void onStart()
 {
  super.onStart();
  Bundle args = getArguments();
  if ( args != )
   {
    progressDialog = new ProgressDialog(getActivity());
    progressDialog.setTitle("Query");
    progressDialog.setMessage("Please wait");
    progressDialog.setCancelable(true);
    progressDialog.show();

    // Here i call my thread
    mRutFechas(progressDialog);

Try this and let me know what happen..

A: Main Thread is also known as UI Thread. That means you cannot update any UI in any other thread but Main Thread. So you can't dismiss the ProgressDialog in background thread. Just put it in main thread and everything would be fine.
getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run()
    {
        progressDialog.dismiss();
    }
});

A: Please initialize your progress dialog:
private ProgressDialog progressDialog;

progressDialog = new ProgressDialog(Mainactivity.this);


text:
Q: Devise routes to only use custom sign in page I am trying to learn Devise and seem to have hit a problem that is nearly the same as many, many questions here on SO but just slightly different enough that I am not getting much traction following those questions' threads.
I have a very simple application. Users can sign in and sign out (and also the devise 'forgot password' stuff is enabled - I am not concerned about it at this time) and that is it. They can't register, they can't edit their profile other than to change their password, they can't do anything except sign in and sign out. (Account creation will, for now, be handled manually at the command line.)
I would vastly prefer that the only page that users can log in from was "/" (root_path). I already have it working where you can log in from "/", and that is great. The problem I am having is that if you type in your user/password combination incorrectly from the root_path login page, it automatically sends you to the Devise sign-in page to continue trying to sign in. How can I make Devise redirect to root_path on sign-in failure?
Here are my routes - they are probably not optimal or correctly configured and I would appreciate pointers on fixing them:
root to: "core_pages#splash"

devise_for :users, skip: [:sessions]
as :user do
  # get 'signin' => 'devise/sessions#new', as: :new_user_session
  post 'signin' => 'devise/sessions#create', as: :user_session
  delete 'signout' => 'devise/sessions#destroy', as: :destroy_user_session,
    via: Devise.mappings[:user].sign_out_via
end

match '/home' => 'core_pages#home'

Note the commented-out 'get signin' line. The system works without this line but, surprisingly (to me), "GET /signin" results in a HTTP 400 (OK) response and renders the Devise login template. I would prefer it return some sort of 'invalid request' or just silently redirect the user to root_path.
Running rake routes on these routes gives:
                root        /                              core_pages#splash
       user_password POST   /users/password(.:format)      devise/passwords#create
   new_user_password GET    /users/password/new(.:format)  devise/passwords#new
  edit_user_password GET    /users/password/edit(.:format) devise/passwords#edit
                     PUT    /users/password(.:format)      devise/passwords#update
        user_session POST   /signin(.:format)              devise/sessions#create
destroy_user_session DELETE /signout(.:format)             devise/sessions#destroy
                home        /home(.:format)                core_pages#home

Thanks!

A: You may point your root_path to Devise Sessions controller: "devise/sessions#new" (and move your home view to that page). Also, you may add this line you your routes.

get "/" => "devise/sessions#new", :as => :user_session

Doing this, when a sign in is unsuccessful, you'll be back to the home page (which now is on devise/sessions/new).


text:
Q: APEX - passing substitution string in PL/SQL I'm having some difficulty passing session substitution strings in APEX 5.
I have a process in my APEX application which will change the password of a user on a remote database.  The username is set from the local LDAP authentication so is held in the APEX substitution string :APP_USER
I'd like to pass this string to the remote database so that I can change the password of the currently logged in user  (hope that makes sense!)
I have this process which is executed when the "change password" button is pressed on the APEX page:
DECLARE
   cursor_handle          INTEGER;
   cursor_handle_tmp      INTEGER;
  BEGIN

   -- Open a Cursor on the REMOTE database
   cursor_handle := DBMS_SQL.OPEN_CURSOR@remote_db;

   -- Parse the "change password"
   DBMS_SQL.PARSE@remote_db(cursor_handle,'ALTER USER MYUSER IDENTIFIED BY mypassword',DBMS_SQL.NATIVE);

   -- Execute the cursor
   cursor_handle_tmp := DBMS_SQL.EXECUTE@remote_db(cursor_handle);

   -- Close the cursor
   DBMS_SQL.CLOSE_CURSOR@remote_db(cursor_handle);

END;

This executes fine as a proof of concept is both the user and password are hard-coded amd the password of the remote user is changed as expected.
However, if I then use the substitution strings :APP_USER   and  :P111_PASSWORD   I get the error message:
missing user or role name

Which implies that the string isn't being passed correctly to the remote DB.
If I use the v function V('APP_USER'),  my code will not validate correctly in the editor as APEX flags it with the followng error:
DBMS_SQL.PARSE@passman_bandev(cursor_handle,'ALTER USER v('APP_USER') IDENTIFIED BY P111_RE_PASSWORD',DBMS_SQL.NATIVE);

ORA-06550: line 11, column 63: PLS-00103: Encountered the symbol "APP_USER" when expecting one of the following: ) , * & = - + < / > at in is mod remainder not rem => <an exponent (**)> <> or != or ~= >= <= <> and or like like2 like4 likec between || multiset member submultiset The symbol ", was inserted before "APP_USER" to continue.

So it looks like I might not be escaping the necessary characters correctly?
However, I've tried many different possible combinations without success.

A: How about this? Prepare ALTER USER statement in a local variable, and then use it in DBMS_SQL.PARSE.
declare
  l_str         varchar2(100);
  l_my_password varchar2(30) := 'pwd';
begin
  l_str := 'alter user ' || :APP_USER || ' identified by ' || l_my_password;
  DBMS_SQL.PARSE@remote_db(cursor_handle, l_str, DBMS_SQL.NATIVE);
  ...
end;


text:
Q: Как сделать фон именно под текстом, не покрывая пространство между строк Как сделать фон именно под текстом, не покрывая пространство между строк?
Нужно сделать вот так:
но в итоге получается, что заливает весь фон,вот сам код собственно:
#block-for-slider ul li h2{
    position: absolute;
    left: 160px;
    top:140px;
    font-size: 4.375em;
    color: #000000;
    text-align: left;
    padding: 15px;
    background: #ffea00;
    line-height: 1.1;
    text-transform: uppercase;
}

Перерыл весь инет решения найти не могу буду премного благодарен.

Всё спасибо наконец-то дошло, просто видимо очень долго пытался и запутался в конец, всем спасибо.
Поставил span с бэкграундом, и line-height.

A:

.highlighted {
  color: white;
  font-size: 30px;
  background-color: gray;
  outline: gray solid 0.3em;
}
Пример построчно закрашенного
текста

Перенос строк внутри  поддерживается. Чтобы сделать видимость выделения "построчно", добавьте свойство line-height.

A: ну как вариант)

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: "Roboto", sans-serif;
  line-height: 1.2;
}

.container__inner {
  font-size: 4rem;
}

.container__text {
  background: #ffeb00;
  margin-bottom: 10px;
  width: max-content;
}

.container__text:last-of-type {
  margin-bottom: 0;
}

Lorem ipsum

Lorem ipsum dolor sit amet.

A: Поместите каждую строку Вашего текста в тег . Потом добавьте этому тегу css-свойство: background-color: yellow;

A: Всё что нужно, это использовать для текста display: inline, а расстояние полученных "блоков" подгонять при помощи line-height

h1 {
  display: inline;
  background: yellow;
  line-height: 1.25;
}

Lorem ipsum.
Consectetur adipiscing elit.


text:
Q: How to vertically center text in a table cell with multiple lines? I want to vertically center "Apple iPad".
Does someone here knows how to do that?

My code looks like this:
\begin{table}[H]
  \noindent
    \centering{}
      \begin{tabular}{cc}
      \hline
            \noalign{\vskip\doublerulesep}
      Modellname & Display-Auflösung \\ ~ & (in Pixel)
            \tabularnewline[\doublerulesep]
      \hline
      Samsung Galaxy SIII & 1280x720
            \tabularnewline[\doublerulesep]

      Samsung Galaxy SII & 800x480
            \tabularnewline[\doublerulesep]

      Apple iPad & 1024x768 (Standard)
      \\ ~ & 2048x1536 (Retina)
            \tabularnewline[\doublerulesep]

      Samsung Galaxy Tab 2 (7.0) & 1280x720
            \tabularnewline[\doublerulesep]

      Samsung Galaxy Y & 320x240
            \tabularnewline[\doublerulesep]

      Sony Ericsson Xperia Arc HD & 1280x720
            \tabularnewline[\doublerulesep]

      Amazon Kindle Fire & 1024x600
            \tabularnewline[\doublerulesep]

      Google Nexus 7 & 1280x800
            \tabularnewline[\doublerulesep]

      SamsungGalaxy Tab 2 (10.1) & 1280x720
            \tabularnewline[\doublerulesep]

      Motorola Droid Razr 4G & 960x540
            \tabularnewline[\doublerulesep]
      \hline
      \end{tabular}
\end{table}

A: One way would be to use the multirow package which allows you to create cells spanning multiple rows:

Notes:

*

*I also applied \multirow to the header of the first column.

*I also replaced the x with \times.

Code:
\documentclass{article}
\usepackage{multirow}

\begin{document}
\begin{table}[H]
  \noindent
    \centering{}
      \begin{tabular}{cc}
      \hline
            \noalign{\vskip\doublerulesep}
      \multirow{2}{*}{Modellname} & Display-Auflösung \\ ~ & (in Pixel)
            \tabularnewline[\doublerulesep]
      \hline
      Samsung Galaxy SIII & $1280 \times 720$
            \tabularnewline[\doublerulesep]

      Samsung Galaxy SII & $800 \times 480$
            \tabularnewline[\doublerulesep]

      \multirow{2}{*}{Apple iPad} & $1024 \times 768$ (Standard)
      \\ ~ & $2048 \times 1536$ (Retina)
            \tabularnewline[\doublerulesep]

      Samsung Galaxy Tab 2 (7.0) & $1280 \times 720$
            \tabularnewline[\doublerulesep]

      Samsung Galaxy Y & $320 \times 240$
            \tabularnewline[\doublerulesep]

      Sony Ericsson Xperia Arc HD & $1280 \times 720$
            \tabularnewline[\doublerulesep]

      Amazon Kindle Fire & $1024 \times 600$
            \tabularnewline[\doublerulesep]

      Google Nexus 7 & $1280 \times 800$
            \tabularnewline[\doublerulesep]

      SamsungGalaxy Tab 2 (10.1) & $1280 \times 720$
            \tabularnewline[\doublerulesep]

      Motorola Droid Razr 4G & $960 \times 540$
            \tabularnewline[\doublerulesep]
      \hline
      \end{tabular}
\end{table}
\end{document}


text:
Q: Laravel - Using controller function for two different eloquent models I am currently developing an application for an indy movie production company. The way I have the workflow right now, the user begins by creating a new movie object by entering the movie title and synopsis. From there the user can then add more details such as price, run-time, full-screen/wide-screen, etc. The movie basic (title, synopsis) are in one database table, and the details are in another. I have set up a one-to-one relationship between the two eloquent models. I have also set up a MovieController that allows me to very easily do CRUD operations on the movie basic model, and when I am displaying the movie object to the user, I can display both the basics and details.
What I was wondering was there some way to use the already existent functions in the movie controller to do CRUD operations on the movie details without having to create new functions in the controller? Also is it possible to reuse the views I've created for each corresponding CRUD operation? In other words can I would like
something.dev/cms/create
In one instance to match to creating a new movie (title, synopsis) and in another instance to match to creating the movie detail (price, run-time, full-screen/widescreen) etc. Is this possible? I have provide the code for the two models below:
Movie_basic.php
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Movie_basic extends Model {

    protected $fillable = ['movie_title', 'movie_synopsis'];

    protected $guarded = ['id'];

    public function details()
    {
        return $this->hasOne('App\Movie_detail', 'movie_id');
    }

    public function personnel()
    {
        return $this->hasMany('App\Movie_personnel', 'movie_id');
    }
}

Model_detail.php
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Movie_detail extends Model {

    protected $fillable = ['minutes', 'languages', 'viewer_discretion', 'screen_type', 'price'];

    protected $guarded = ['id', 'movie_id'];

    public function basics()
    {
        return $this->belongsTo('App\Movie_basic');
    }

}

A: If I understand you, this might be an answer. (Did not test the code.)
Please note that, that code has been written to show you an example. You will probably want to edit it to make it work and act as you wanted. Maybe you want to use a repository or automate the model instance creating (I did not create new instances), and saving processes. You can use interfaces instead of your models etc...
Here is the service to store the logic.
<?php
use Movie_basic; use Movie_detail;

Class MovieService {

    protected $movieBasic;
    protected $movieDetail;

    public function __construct(Movie_basic $movieBasic, Movie_detail $movieDetail) {

        $this->movieBasic = $movieBasic;
        $this->movieDetail = $movieDetail;

    }

    public function createMovie(array $attr) {

        // TODO: Move your business logic here.
        // E.g
        $movie = $this->movieBasic->fill($attr);
        $movie->save();
        return $movie;

    }

    public function createMovieDetail(array $movieAttr, array $attributes) {

        // TODO: Move your detail logic here.
        // E.g.
        $basic = $this->createMovie($movieAttr);
        $detail = $this->movieDetail->fill($attributes);
        $detail->basic()->associate($detail);
        $detail->save();
        return $detail;

    }

}

And here, the controller examples:
<?php

use MovieService;

class MovieController {

    public function __construct(MovieService $ms) {
        $this->ms = $ms;
    }

    public function store() {
        $this->ms->createMovie($attrToSave);
    }

}

<?php

use MovieService;

class MovieDetailController {

    public function __construct(MovieService $ms) {
        $this->ms = $ms;
    }

    public function store() {
         $this->ms->createMovieDetail($attrToSave);
    }

}


text:
Q: Working with PyQt and Qt designer ui files I'm new to PyQt and I'm trying to work with ui files directly from within my PyQt script. I have two ui files, mainwindow.ui and landing.ui. Clicking on a button 'pushButton' on the main window should open the landing window. However, clicking on the button does not work as I expected. Here is the code(I'm just trying to work stuff out so the code is pretty rough):
from PyQt4 import QtCore, uic
from PyQt4 import QtGui
import os

CURR = os.path.abspath(os.path.dirname('__file__'))

form_class = uic.loadUiType(os.path.join(CURR, "mainwindow.ui"))[0]
landing_class = uic.loadUiType(os.path.join(CURR, "landing.ui"))[0]

def loadUiWidget(uifilename, parent=None):
    uifile = QtCore.QFile(uifilename)
    uifile.open(QtCore.QFile.ReadOnly)
    ui = uic.loadUi(uifilename)
    uifile.close()
    return ui

@QtCore.pyqtSlot()
def clicked_slot():
    """this is called when login button is clicked"""
    LandingPage = loadUiWidget(os.path.join(CURR, "landing.ui"))
    center(LandingPage)
    icon(LandingPage)
    LandingPage.show()

class MyWindow(QtGui.QMainWindow, form_class):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(clicked_slot)

class LandingPage(QtGui.QMainWindow, landing_class):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)

def center(self):
    """ Function to center the application
    """
    qRect = self.frameGeometry()
    centerPoint = QtGui.QDesktopWidget().availableGeometry().center()
    qRect.moveCenter(centerPoint)
    self.move(qRect.topLeft())

def icon(self):
    """ Function to set window icon
    """
    appIcon = QtGui.QIcon("icon.png")
    self.setWindowIcon(appIcon)

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    pixmap = QtGui.QPixmap(os.path.join(CURR, "splash.png"))
    splash = QtGui.QSplashScreen(pixmap)
    splash.show()
    app.processEvents()
    MainWindow = MyWindow(None)
    center(MainWindow)
    icon(MainWindow)
    MainWindow.show()
    splash.finish(MainWindow)
    sys.exit(app.exec_())

What mistake I'm I making??

A: There are two main problems with your script: firstly, you are not constructing the path to the ui files correctly; and secondly, you are not keeping a reference to the landing-page window (and so it will get garbage-collected immediately after it is shown).
Here is how the part of the script that loads the ui files should be structured:
import os
from PyQt4 import QtCore, QtGui, uic

# get the directory of this script
path = os.path.dirname(os.path.abspath(__file__))

MainWindowUI, MainWindowBase = uic.loadUiType(
    os.path.join(path, 'mainwindow.ui'))

LandingPageUI, LandingPageBase = uic.loadUiType(
    os.path.join(path, 'landing.ui'))

class MainWindow(MainWindowBase, MainWindowUI):
    def __init__(self, parent=None):
        MainWindowBase.__init__(self, parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.handleButton)

    def handleButton(self):
        # keep a reference to the landing page
        self.landing = LandingPage()
        self.landing.show()

class LandingPage(LandingPageBase, LandingPageUI):
    def __init__(self, parent=None):
        LandingPageBase.__init__(self, parent)
        self.setupUi(self)


text:
Q: How to avoid high memory usage in Phaser game using Cordova? I have developed a Cordova Phaser game. It runs in Android and iOS devices.
The game has seven levels, with each level having a number of sprite (background, player) and groups (bullets, enemies).
In preload function, I have loaded all images and atlasJSONHash
function preload(){
    game.load.atlasJSONHash('anim', 'anim.png', 'anim.json');
    //and so on
}

function create(){
     var star = game.add.sprite(160, 32, 'level1bg');
     star.x = 0;
     star.y = 0;
     star.height = game.height;
     star.width = game.width;

     bullets = game.add.group();
     bullets.enableBody = true;
     bullets.physicsBodyType = Phaser.Physics.ARCADE;

     bullets.createMultiple(30, 'bullet');
     bullets.setAll('anchor.x', 0.5);
     bullets.setAll('anchor.y', 1);
     bullets.setAll('outOfBoundsKill', true);
     bullets.setAll('checkWorldBounds', true);
     //and so on
}
function startlevel(level)
{
     var star = game.add.sprite(160, 32, 'level1bg');
     star.x = 0;
     star.y = 0;
     star.height = game.height;
     star.width = game.width;

     bullets = game.add.group();
     bullets.enableBody = true;
     bullets.physicsBodyType = Phaser.Physics.ARCADE;

     bullets.createMultiple(30, 'bullet');
     bullets.setAll('anchor.x', 0.5);
     bullets.setAll('anchor.y', 1);
     bullets.setAll('outOfBoundsKill', true);
     bullets.setAll('checkWorldBounds', true);
     //and so on
}

When the level ends I call startlevel(2) and so on.
In browser it runs fine, but in mobile memory doubles for each level, with the app eventually crashing. How do I avoid this memory problem?

A: I hope this would help. Before assign a new group, to make sure old group is destroyed, I always call destroy on it and then re-assign a new group.
Move over i think you will want to create a new function for init your bullets group and re-use it.
function createBulletGroup(){

    if(bullets!=null)
    {
         bullets.destroy(true);
         bullets = null;
    }
    //.. The rest of add group
}

More over, since you use
var star = game.add.sprite(160, 32, 'level1bg');

Every time you startlevel, a new star will be placed on the old star, since their position are the same. When star is created, it will be assigned to world. And re-create star many time cause memory leak which can't be seen by eyes.
You can try to randomly place your star when you start new level too see if it overlapped others or set it alpha to 0.5;


text:
Q: How to sum nested array or variables from children and parent I have this array en php
array (
text=> '',
points=> 8,
children=> [
text=> '',
points=> 8,
children=>
],
[text=> '',
points=> 8,
children=> [text=> '',
points=> 8,
children=>]
)
how can I get the sum of all point from child and parent?
expected output
total = 32


text:
Q: htmlhelp.lib for Visual Studio 2012 MFC app? Anyone know of 3rd party or open source alternatives to MS' old htmlhelp.lib library?  It was compiled w/ an older version of Visual Studio and apparently is no longer supported.
I'm porting an old program to VS.2012.
Looks like the official way to do this is a bit hackish...you have to create a new app w/ HTML help using the MFC Wizard and then merge all your old code into it :-P
http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/045a2e45-01cb-4be3-afc5-f1473496760f/
EDIT: Note: my app is 64-bit..


text:
Q: How do I enable upload of large files in classic ASP on IIS 7? Recently I had to get an old ASP application working in IIS 7.5 on a W2K8 server. Almost everything works fine, except that I can't seem to get it to accept uploads larger than ~200kB. I did find a setting, that from what I can understand should to the trick, in the applicationHost.config, I set the max request size to 100 MB like this:
<location path="TheNameOfMySite">
    <system.webServer>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="104857600" />
            </requestFiltering>
        </security>
    </system.webServer>
</location>

Unfortunately, this seems to do nothing at all, it still refuses to accept any files larger than about 200 KB, and in the log file it gives this error message:

ASP_0104_:_80004005|Operation_not_Allowed

Googling that points to increasing the maxAllowedContentLength as I have done above. So I'm fresh out of ideas, but confident that the clever stackoverflow crowd can solve this in less time than it took for me to write this question.

A: On Windows 2008 - Go into Administrative tools - server Manager - expand Roles - expand Webserver -click on IIS - and look for the web instance, for which you want to change the file size limit and then go into option "ASP" expand "Limit properties" and property you need to change is 'Maximum Request Entity Body Limit'. File Size is always in bytes so use any online calculator to calculate the conversion of bytes to KB or MB.

A: First off @AnthonyWJones answer was very helpful but didn't solve my problem, in fact it's slightly inaccurate and for that reason I'm writing this.
Large uploads in IIS 6 was a doddle you had one configuration value to worry about

AspMaxRequestEntityAllowed

The AspMaxRequestEntityAllowed property specifies the maximum number of bytes allowed in the entity body of an ASP request. If a Content-Length header is present and specifies an amount of data greater than the value of AspMaxRequestEntityAllowed, IIS returns a 403 error response. This property is related in function to MaxRequestEntityAllowed, but is specific to ASP request. Whereas you might set the MaxRequestEntityAllowed property to 1 MB at the general World Wide Web Publishing Service (WWW Service) level, you may choose to set AspMaxRequestEntityAllowed to a lower value, if you know that your specific ASP applications handle a smaller amount of data.

With the introduction of IIS 7 and it's new hierarchical XML-based configuration system  that uses *.config files it all got a bit more complicated.
There are now two settings you need to configure correctly before Large File Uploading will work as you expect and they both live in different areas of the configuration.

maxRequestEntityAllowed
 <configuration>
   <system.webServer>
     <asp>
       <limits maxRequestEntityAllowed="200000" />
     </asp>
   <system.webServer>
 <configuration>

The maxRequestEntityAllowed attribute specifies the maximum number of bytes allowed in the entity body of an ASP request. If a Content-Length header is present and specifies an amount of data greater than the value of maxRequestEntityAllowed, IIS returns an HTTP 403 error response.

IMPORTANT:
Configuring the above setting will work up to a point as you will see from the default below but once you reach that default regardless of what maxRequestEntityAllowed is set to, the server will respond with HTTP 404 Not Found error response. This confused me at first because I thought it must be my code that was returning the 404 error response.

maxAllowedContentLength
 <configuration>
   <system.webServer>
     <security>
       <requestFiltering>
         <requestLimits maxAllowedContentLength="30000000" />
       </requestFiltering>
     </security>
   </system.webServer>
 </configuration>

Specifies the maximum length of content in a request, in bytes. The default value is 30000000, which is approximately 28.6MB.

This setting is extremely important as it defines the maximum number of bytes in an IIS Request (not an ASP Request like the previous configuration value) it has nothing to do with the content length of the response (as has previously been stated). Regardless of what maxRequestEntityAllowed (which is a asp-classic specific setting) is set to, if maxAllowedContentLength is not set or you try to upload more then the default of 28 MB (approx.) you will get a HTTP 404 error response.
Links

*

*ASP Limits <limits>

*Request Limits <requestLimits>

A: The maxAllowedContentLength controls how much data is allowed to be sent in a response.  However you want to control how much can be accepted in a request.  This is handled by the maxRequestEntityAllowed attribute of the limits element in the asp section of the config file.  An example might look like:-
<system.webServer>
  <asp>
     <cache diskTemplateCacheDirectory="%SystemDrive%\inetpub\temp\ASP Compiled Templates" />
     <limits scriptTimeout="00:02:00"
        queueConnectionTestTime="00:00:05"
        requestQueueMax="1000"
        maxRequestEntityAllowed="104857600"
        />
  </asp>

You can configure this in the IIS7 manager under the "Limit Properties" category in the property grid for the ASP feature.  Alternatively you can use a command line:-
appcmd set config /section:asp /limits.maxRequestEntityAllowed:104857600

Note that extending this value increase the window for DOS attack where the attacker sends large content to the server so don't be tempted to extend this beyond what you really need.

A: for those who cannot execute the appcmd command from CMD, you need to change path to C:\windows\system32\inetsrv since the command reside in that folder.

A: The solution accepted here didn't work for me.  First, there wasn't the element  specified in my config and I didn't want to screw up a config file.
I also tried @shoaib-suleman's solution and it didn't work either.  Finally, I ran across the solution shown here and it worked.

*

*Open IIS 7 SnapIn

*Select the website you want enable to accept large file uploads.

*In the main window double click 'Request filtering'

*Once the window is opened you may see on top a list of tabs eg: file name extensions, rules, hidden segments and so on...
Regardless the tab you select, in the main window,right-click to display a pop-up context menu.
Select "Edit Feature Settings" in the menu.

*On the form that pops up, modify the "Maximum allowed content length (bytes)"

A: Go in IIS, choose you site and expand it then click the ASP icon in right panel.
Open the Limits Properties icon, and change the value in the "Maximum Requesting Entity Body Limit" to a value larger than 200000 (200kb). 2000000 would be around 2mb, 20000000 would be 20mb. Set according to your need and apply.
That's it!
ENJOY..


text:
Q: Using variable in openrowset, result in syntax error I'm trying to declare connection as a variable and use it in a query:
DECLARE @connStr VARCHAR(MAX) = 'server=xxxxx'
DECLARE @table VARCHAR(MAX) = 'xxxxx'

BEGIN
DELETE FROM @table;
INSERT @table
SELECT * FROM OPENROWSET(
    'SQLNCLI',
    @connStr,
    'SELECT TOP 10 * from xxxx ORDER BY xxxx DESC'
);
END;

And it results in syntax error.
What's wrong with @connStr? I'm using SQLServer 2012


text:
Q: Dynamic content scrollbar error I have a problem with adding dynamic content to a webpage.
The javascript loads some html and swap the divholder's innerhtml. Basically is a
$("#mydiv").load("some.html");

My problem is that when you get a huge page, it created a huge scrollbar, then, after swaping the html for a smaller html, the scrollbars aren't being resized.
eg: http://jode.com.br/joe/scrollbarerror.png
Using firebug, you can see that the highlighted content is the window but the scrollheight is just a lot bigger than the contents of it
It is happening on firefox and ie, but not in chrome. Using chrome, hte scrollbars are updated to only scroll content
any help?

A: My solution right now is create a div that holds all the content. The div's scrollbar is being updated to the right size when the content changes.
THen I used the method:
html, body {
  height: 100%;
}
#MainContentHolder {
  height: 100%;
}

with this, the maincontentholder got the right scrollbars and is being updated correctly.
many thanks who tried to help!
Jonathan

A: I guess the bug is because of your height:100% on the body tag.
Why do you need it ? You shouldn't do that :) Try removing it and tell us if the bug's still here.


text:
Q: C++ function overload resolution - bool vs string I've found some unexpected behavior using the VC++2010 compiler with function overloading:
struct A {
  A();
  void O(const bool in);       //(1)
  void O(const std::string in);//(2)
}

Some of the following calls do not resolve like I would think:
A a;
a.O(true);//calls (1)
a.O("what?");//calls (1)
a.O(std::string("better..."));//calls (2)

Can someone explain to me why the second call resolves to the boolean function and what the motivation behind resolving in that way is?

A: The type of "what?" is char const[6], which after decaying to char const* while being passed into the function, is implicitly convertible to bool. The standard conversion takes precedence over user-defined implicit conversions, like the case of converting char const* to std::string.


text:
Q: Access denied in RenameFile after FileExists I´m regularly importing files from a path into an application with Delphi 10.2. After each successful import I want to move the current file to a new path(SuccessPath). It´s possible to have file names that already exist in the SuccessPath. That´s why I first check if the file name exists. If thats the case I append an index to the filename (e.g. test.txt changes to test_2.txt).
In some cases RenameFile returns false and GetLastError returns Access denied. It´s probably an unclosed file handle. Do I need to close a handle after calling FileExists? How would I do so?
Here´s my example code:
procedure TDemo.Execute;
begin
  MoveFileWithRenameDuplicates('C:\temp\test.txt', 'C:\temp\new\');
end;

procedure TDemo.MoveFileWithRenameDuplicates(oldFile, newPath: string);
var
  lNewFile: string;
  i: integer;

begin
  lNewFile := newPath + TPath.GetFileName(oldFile);
  i := 0;
  repeat
    if FileExists(lNewFile) then
    begin
      i := i + 1;
      lNewFile := newPath + TPath.GetFileNameWithoutExtension(oldFile) + '_' + IntToStr(i) + TPath.GetExtension(oldFile);
    end;
  until not FileExists(lNewFile);
  WriteLn('lNewFile=' + lNewFile);

  if not RenameFile(oldFile, lNewFile) then
    WriteLn(SysErrorMessage(GetLastError));
end;

A: I changed my loop like Remy suggested. I also realized that the appended index didn´t actually increment so I changed that aswell:
procedure TDemo.MoveFileWithRenameDuplicates(oldFile, newPath: string);
var
  lNewFile: string;
  i: integer;

begin
    lNewFile := newPath + TPath.GetFileName(oldFile);
    i := 0;
    while not RenameFile(oldFile, lNewFile) do
    begin
        if FileExists(lNewFile) then
        begin
          lNewFile := newPath
            + TRegEx.Match(TPath.GetFileNameWithoutExtension(oldFile), '/^(?''name''[^_]*)_\d*$', [roIgnoreCase]).Groups['name'].Value
            + '_' + IntToStr(i) + TPath.GetExtension(oldFile);
        end
    else
        begin
          WriteLn(SysErrorMessage(GetLastError));
          break;
        end;
    end;
end;

This seems to have fixed my problem.


text:
Q: Current through an inductor Assume we have an inductor with the following values:
$$B=B_0 \cdot sin(2\cdot \pi \cdot f \cdot t)$$
$$N=10$$
$$r=5cm$$
$$B_0 = 2mT$$
$$f=50Hz$$
$$R=5 \Omega $$
How much current runs through the inductor as function of time?
Well I don't know the inductance, so I tried this:
$$U=-\frac{d \phi}{dt}$$
$$\phi = B \cdot A = 2mT \cdot sin(\pi \cdot 100 \cdot t) \cdot \pi \cdot (2\cdot10^{-2})$$
$$U = -\frac{d}{dt} 2mT \cdot sin(\pi \cdot 100 \cdot t) \cdot \pi \cdot (2\cdot10^{-2})^2 $$
$$U = -\frac{d}{dt} 8 \cdot \pi \cdot 10^{-7}T \cdot sin(\pi \cdot 100 \cdot t) $$
$$U = -8 \cdot \pi \cdot 10^{-7}T \cdot \frac{d}{dt} sin(\pi \cdot 100 \cdot t) $$
$$U = -8 \cdot \pi \cdot 10^{-7}T \cdot 100\cdot \pi \cdot cos(\pi\cdot 100\cdot t) $$
$$U = -800 \cdot \pi^2 \cdot 10^{-7}T \cdot cos(\pi\cdot 100\cdot t) $$
$$I=\frac{U}{R}= - \frac{800 \cdot \pi^2 \cdot 10^{-7}T \cdot cos(\pi\cdot 100\cdot t)}{5\Omega} = -1.579\cdot 10^{-4}\cdot cos(\pi\cdot 100\cdot t)A$$
I never saw something like that anywhere else so I'm a bit unconfident if this approach was really correct. Is this correct? Is there maybe another (easier) approach?
Additional information:
After reading the comments I should add some more information.
As you may have thought, this is an exercise. Here is the full text:
A coil with N turns is brought into a magnetic field. The area of the coil is perpendicular to the field. The coil has a radius r and the field changes after [see B above]. The coil has a resistance of R.
Biot-Savart was discussed but is explicitly not necessary.
Solivng this task should be pretty easy, so I get the feeling that this task either lacks some values or I misunderstood it.


text:
Q: Rails server error - railties After finishing the official getting started guide for RoR I played with it so much that I ruined the blog so I decided just to scrap everything and start again.
Now that I'm trying to run the rails server I get this error
 /home/nadia/.gem/ruby/2.0.0/gems/bundler-1.5.2/lib/bundler/vendor/thor/actions.rb:109:in `expand_path': No such file or directory - getcwd (Errno::ENOENT)
    from /home/nadia/.gem/ruby/2.0.0/gems/bundler-1.5.2/lib/bundler/vendor/thor/actions.rb:109:in `destination_root='
    from /home/nadia/.gem/ruby/2.0.0/gems/bundler-1.5.2/lib/bundler/vendor/thor/actions.rb:85:in `initialize'
    from /home/nadia/.gem/ruby/2.0.0/gems/bundler-1.5.2/lib/bundler/cli.rb:17:in `initialize'
    from /home/nadia/.gem/ruby/2.0.0/gems/bundler-1.5.2/lib/bundler/vendor/thor.rb:359:in `new'
    from /home/nadia/.gem/ruby/2.0.0/gems/bundler-1.5.2/lib/bundler/vendor/thor.rb:359:in `dispatch'
    from /home/nadia/.gem/ruby/2.0.0/gems/bundler-1.5.2/lib/bundler/vendor/thor/base.rb:440:in `start'
    from /home/nadia/.gem/ruby/2.0.0/gems/bundler-1.5.2/lib/bundler/cli.rb:10:in `start'
    from /home/nadia/.gem/ruby/2.0.0/gems/bundler-1.5.2/bin/bundle:20:in `block in <top (required)>'
    from /home/nadia/.gem/ruby/2.0.0/gems/bundler-1.5.2/lib/bundler/friendly_errors.rb:5:in `with_friendly_errors'
    from /home/nadia/.gem/ruby/2.0.0/gems/bundler-1.5.2/bin/bundle:20:in `<top (required)>'
    from /home/nadia/.gem/ruby/2.0.0/bin/bundle:23:in `load'
    from /home/nadia/.gem/ruby/2.0.0/bin/bundle:23:in `<main>'

in the gemfile I have added
   gem 'railties', '~>4.0.2'

then
$ bundle install

to try and resolve the issue. However it still hasn't work. I'm fairly new so I'm not actually sure what the error is.
Any thoughts would be appreciated.
I'm also running rails v4.0.2 if that helps

A: This is a pretty weird thing to see:

No such file or directory - getcwd (Errno::ENOENT)

Are you trying to run this application from a directory you maybe moved, or even deleted?  That error implies that it can't determine the current directory.

A: Define rails in gem file like this
gem 'rails', '4.0.2'

And then bundle install.

A: Whoops. I derped. All sorted now. I was simply trying to run it from the wrong directory.
Should have seen it earlier.


text:
Q: Passing arrays with values returned from another user defined function I have 2 functions in question:
' Starting from first row, navigate through headers (rows) in lookup_range and return cell value at row_index if we reach a single column Range at the end of navigation; N/A otherwise.
Public Function HLOOKUPRANGE(headers() As Variant, lookup_range As range, row_index As Integer) As Variant
' returns the minimum value in search range that is greater than or equal to target.
Public Function MINGE(search As range, target As Variant) As Variant

In my excel worksheet, the HLOOKUPRANGE works like this:
=HLOOKUPRANGE({"Color", "Red", "Alpha", 50}, A1:Z30, SELECTED_INDEX)
=HLOOKUPRANGE({"Color", "Blue", "Alpha", 100}, A1:Z30, SELECTED_INDEX)

But how can I make it work with another function, like this?:
=HLOOKUPRANGE({"Color", "Red", "Alpha", MINGE(A4:Z4, INPUT_ALPHA_VALUE)}, A1:Z:30, SELECTED_INDEX)

Excel is not letting me put MINGE between {} and I think the problem is with passing arrays in this manner. What can I do to pass the result of MINGE into HLOOKUPRANGE?
Tip: MINGE is "MINimum Greater than or Equal"

A: Two ways that I can think of...
WAY 1
Write a 3rd function which will unite the Array with the MINGE value. I have created a sample since I don't know what HLOOKUPRANGE and MINGE does but the concept is the same.
The SID() imitates HLOOKUPRANGE in this example. But all it does at the moment is it sums the values
So if you enter
=SID({1,2,3,4,5})

it will give you the sum 15. Now lets say we wanted the sum of
=SID({1,2,3,4,5,MINGE()})

where the value of MINGE() is 6. This is how we would do it
=SID(Unite({1,2,3,4,5},6))

Which will give you 21. This code goes in a module
Option Explicit

Dim TempAr() As Variant

Public Function Sid(headers() As Variant) As Variant
    Dim temp As Long, i As Long
    For i = LBound(headers) To UBound(headers)
        temp = temp + headers(i)
    Next i
    Sid = temp
End Function

Public Function Unite(MyArray() As Variant, Vl As Variant) As Variant
    Dim n As Long, i As Long

    n = UBound(MyArray)

    ReDim Preserve TempAr(n + 1)

    For i = LBound(MyArray) To UBound(MyArray)
        TempAr(i) = MyArray(i)
    Next i

    TempAr(n + 1) = Vl
    Unite = TempAr
End Function

If I were to apply the same to your functions then it would look something like this
=HLOOKUPRANGE(UNITE({"Color", "Red", "Alpha"},MINGE(A4:Z4, INPUT_ALPHA_VALUE)), A1:Z30, SELECTED_INDEX)

WAY 2
You could change HLOOKUPRANGE function slightly to accept optional values. For example the formula
=SUM({1,2,3,4,5},{6}) does the same thing as above in a worksheet.
So you could change your HLOOKUPRANGE() to
Public Function HLOOKUPRANGE(headers() As Variant, lookup_range As Range, _
row_index As Integer, Optional HeadersItem1 As Variant, _
Optional HeadersItem2 As Variant) As Variant
    '~~> In the code add HeadersItem1 and HeadersItem2 to headers()
    '~~> If they are not blank
End Function

USAGE would be like this
=HLOOKUPRANGE({"Color", "Red", "Alpha"}, A1:Z30, SELECTED_INDEX,MINGE(A4:Z4, INPUT_ALPHA_VALUE)))

or
=HLOOKUPRANGE({"Color", "Red"}, A1:Z30, SELECTED_INDEX,MINGE(A4:Z4, INPUT_ALPHA_VALUE)),SELECTED_INDEX,MINGE(B4:B4, INPUT_ALPHA_VALUE)))


text:
Q: Why can't the following function template code compile? I wrote a function template f which takes a vector iterator as a parameter:
#include<vector>
using namespace std;

template <typename T>
void f(vector<T>::iterator it)
{

}

int main()
{
    vector<int> v;
    f(v.begin());
}

Compiling it with gcc failed, the error message is very hard to understand:

What's the cause of the compilation error and how can I fix it?


text:
Q: python code to internationalize my application depending on a variable I'm trying to internationalize my python application but I have a small problem : The messages to print are in english by default (in my python code they are in engilsh) and I generated the french translation in a file fr.mo situated in : myAppName/src/locale/fr_Fr/LC_Messages/fr.mo and now I don't know which code to insert in my files .py to traduce to french my messages only when my variable langVar='fr' and not when the system default Language is french that means when the user chooses english ==> lanVAr='en' I want my application to print the messages in my code without any traduction ..
Is it possible ?
my python code :
main_app.py:
import logging
import app
import i18n
_ = i18n.language.ugettext

def my_function(langVar):
     logger = logging.getLogger()
     logger.setLevel(logging.DEBUG)
     ch = logging.StreamHandler()
     ch.setLevel(logging.DEBUG)
     logger.addHandler(ch)
     logging.info(_("Start My application "))
     app.my_app_function()
     #...
     logging.info(_("End My application"))

if __name__ == '__main__':
    langVar = input("Enter your language : ")
    my_function(langVar)

app.py:
import logging
import i18n
_ = i18n.language.ugettext

def my_app_function():
     logging.info(_("start my_app_function"))
     #...
     logging.error("Unexpected error !!")
     #...
     logging.info(_("end my_app_function"))

i18n.py:
import os, sys
import locale
import gettext

LOCALE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'locale')
lc, encoding = locale.getdefaultlocale()
if lc:
     languages = [lc]
mo_location = LOCALE_DIR

gettext.install(True, localedir=None, unicode=1)
gettext.find("fr", mo_location)
gettext.textdomain ("fr")
gettext.bind_textdomain_codeset("fr", "UTF-8")
language = gettext.translation("fr", mo_location, languages , fallback=True)

the problem is with this code I wrote the traduction is done when the system default language is french I want it to be done when the user enter "fr"
Does anyone have any idea how to do this?
Thanks

A: To handle units ect: locale.setlocale(locale.LC_ALL, 'fr_FR')
This shows how to switch language:
import gettext

lang1 = gettext.translation('myapplication', languages=['en'])
lang2 = gettext.translation('myapplication', languages=['fr'])
lang3 = gettext.translation('myapplication', languages=['de'])

# start by using language1
lang1.install()

# ... time goes by, user selects language 2
lang2.install()

# ... more time goes by, user selects language 3
lang3.install()


text:
Q: Amazon S3 images cache-control not being applied I searched all over and found a method to cache images on Amazon S3. Whenever I upload an image, I add a meta element of cache-control and then set max-age=86400. However, on any sort of speed test site it says that my images do not have a cache applied to them.
I am not sure if it matters, but I have CloudFront linked to this S3 bucket. Sorry, but completely new to AWS.
Anyone know why my images may not be caching?

A:
on any sort of speed test site it says that my images do not have a cache applied to them.

That isn't what this says.  The screenshot says they have a short freshness lifetime, and longer than 1 week is recommended.
Your setting of max-age=86400 is only 24 hours.

A: I recently had this issue (as of 4 Mar 23) after setting my bucket storage cache-control and I used a CDN on my bucket resources. I noticed the bucket items (images) were not displaying any cache-control. In further research I am posting this is anyone stumbles upon this question in searching the same error. I had to go to my CloudFront distributions and select my CDN for the S3 bucket. Select the tab Behaviors, select the default behavior check box and then that will allow you to select EDIT. In the settings scroll down and find Cache key and origin requests and select the check box for Cache policy and origin request policy (recommended) and at the bottom of the form click SAVE. I am not sure if I accepted defaults when I created the CDN bucket or if the default was 'Legacy cache settings' <-- in my case that is what was selected. Once I changed the setting to Cache policy and origin request policy (recommended) my images where now showing the cache-control I had set in my S3 Bucket. I hope this helps anyone else. Happy coding. NOTE: As the accepted answer above mentions the max-age duration <-- I had nothing showing up at all. My max-age was set to 1 year.


text:
Q: Angular scope and bindToController use cases Angular lets you specify scope for your directive like so:
            var directive = {
                restrict: 'EA',
                scope: {},
                bindToController: {
                    text: '='
                },
                controller: DirectiveController,
                controllerAs: 'vm',
                templateUrl: 'directive.partial.html',
                link: DirectiveLink
            };

I understand that bindToControllers sets a namespace within scope.
In this directive template I can data bind text like so:
            {{vm.text}}

If I did not use bindToController and used scope instead I can data bind text like so:
            {{text}}

Everybody seems to be suggesting that bindToController is the way to go, but I want to know why.
So my question is when should I use scope and when should I use bindToController?
Are there any use cases when I should just use scope?
Thanks.


text:
Q: How to delete Many-To-Many Attribute from DB I Have in DB Many-To-Many relation between 2 tables. And I'm using EF Code first from Db.
Table Genres:
public partial class Genres

    {
        public Genres()
        {
            Post = new HashSet<Post>();
        }

        public int GenresID { get; set; }

        [StringLength(90)]
        public string GenresName { get; set; }

        [StringLength(128)]
        public string GenresSlug { get; set; }

        [StringLength(200)]
        public string GenresDescription { get; set; }

        public virtual ICollection<Post> Post { get; set; }
    }

Table Post:
public partial class Post
    {

        public Post()
        {
            Genres = new HashSet<Genres>();
        }

        public int PostID { get; set; }

        [Display(Name = "Title")]
        [Required]
        [StringLength(150)]
        public string Name { get; set; }

        [AllowHtml]
        [Display(Name = "Description")]
        [Column(TypeName = "text")]
        public string Description { get; set; }

        [Display(Name = "Publish Date")]
        public DateTime PublishDate { get; set; }

        [Display(Name = "Genres")]
        [Required]
        [StringLength(200)]
        public string GenresList { get; set; }

        public virtual ICollection<Genres> Genres { get; set; }
    }

Now I have Actually Two Questions :
1- How to Delete The Values From Table GenresPost which is created from this relation ? Only from the GenresPost I don't Want to Delete My Post Or Make It Affect from this.
2-In my Genres Table When I add a new Post I got the Genres from text field like this :

Drama,Romance,Shoujo

and then i split them and add them, but they keep repeating in database and i need them to be unique , so when i add for example Drama there and add it again in other post , i want to check if it exists so i don't need to add it again .. and here is my code for this but it's not worked from me :

post.GenresList contain the genres like this (Drama,Romance,Shoujo)

if (post.GenresList != null)
            {
                Collection<Genres> GenresPost = new Collection<Genres>();
                var s = post.GenresList.ToString();
                string[] newGenres = s.Split(',');

                foreach (var val in newGenres)
                {
                    var iTag = db.Genres.FirstOrDefault(t => t.GenresName == val);

                        if (iTag == null && val.Length > 1)
                        {

                            iTag = new Genres
                            {
                                GenresName = val.Trim(),
                                GenresSlug = val.MakeUrlFriendly2(),

                            };
                            db.Genres.Add(iTag);
                        }

                    GenresPost.Add(iTag);

                }
                post.Genres = GenresPost;
            }


text:
Q: crontab : yesterday's date not showing up I need a cron job to work on a file named like this:
20160307_20160308_xxx_yyy.csv
(yesterday_today_xxx_yyy.csv)

And my cron job looks like this:
53 11 * * * /path/to/python /path/to/python/script /path/to/file/$(date -d "yesterday" +"\%Y\%m\%d")_$(date +"\%Y\%m\%d")_xxx_yyy.csv >> /path/to/logfile/cron.log 2>&1

Today's date is getting calculated properly but I am unable to get yesterday's date working. The error is:
IOError: [Errno 2] No such file or directory: 'tmp/_20160308_xxx_yyy.csv'

Please help!

A: I found the answer to my own question.
I needed to use this to get yesterday's date:
53 11 * * * /path/to/python /path/to/python/script /path/to/file/$(date -v-1d +"\%Y\%m\%d")_$(date +"\%Y\%m\%d")_xxx_yyy.csv >> /path/to/logfile/cron.log 2>&1

Hope it helps somebody!

A: This version worked for me. Maybe it can be helpful for someone:
53 11 * * * /path/to/python /path/to/python/script /path/to/file/$(date --date '-1 day' +"\%Y\%m\%d")_$(date +"\%Y\%m\%d")_xxx_yyy.csv >> /path/to/logfile/cron.log 2>&1


text:
Q: Bigint class operator Please check out this code and tell me why is the operator += only works if the numbers have the same size when i tried x += z; i got 345678.
I think the problem is int for (i = 0; i <= len - 1; i++) loop. I tried to fix it but I wasn't successful. Any solutions?
Header file.
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Mint {
public:

    Mint();
    Mint(int);
    Mint (const char  *s);
    string afficher();
    Mint operator+=(const Mint &rhs); //returns mint + rhs
    Mint operator+(const Mint &rhs);
private:
    vector<char> num;
};

Source file.
#include "Mint.h"
#include <string.h>

Mint::Mint()
{
    num.push_back(0);
}
Mint::Mint(int n)
{
    while(n!=0)
    {
        num.push_back(n%10);
        n = n/10;
    }
}
Mint::Mint(const char* s)
{
    int i = 0 ;
    for(i=strlen(s)-1;i>=0;i--)
    num.push_back(s[i] - '0');
}
string Mint::afficher(){
    string s="";
    int i;
    for(i=num.size()-1;i>=0;i--)
        s += char('0'+num[i]);
    return s;
}
Mint Mint::operator+=(const Mint &rhs) {
    unsigned int len = num.size();
    char carry = 0;

    if (len > rhs.num.size())
        len = rhs.num.size();

    unsigned int i;
    for (i = 0; i <= len - 1; i++)
    {
        char result = num[i] + rhs.num[i] + carry;
        num[i] = result % 10;
        carry = result / 10;
    }

    while (carry)
    {
        if (i < num.size())
        {
            num[i] += carry;
            if (num[i] >= 10)
            {
                num[i] -= 10;
                i++;
            }
            else
                carry = 0;
        }
        else {
            num.push_back(carry);
            carry = 0;
        }
    }
    return *this;
}
Mint Mint::operator+(const Mint &rhs){
    Mint result;
    result = *this;
    return result+=rhs;
}

main file.
#include "Mint.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{
    Mint x="123456",z="22222222222222222222",f;
    Mint a = "655478461469974272005572";
    Mint b = 8;
    x += z;
    f = x + z;
    cout << x.afficher()<<endl;

}

A: I've now written big integer packages three times. One thing that helps me a great deal is to picture doing arithmetic by hand. Try it!
In the case of += here, the problem occurs for something like 123 += 4567. The code looks at the length of both arrays, sees that the larger one is 4, and walks off the end of the first one, which only has three elements. So don't adjust len to rhs.num.size().
Instead, add another loop in operator+=, between the two that are there: while there's a carry and i is less than rhs.size(), add rhs[i] and carry and push the sum into *this. Once the code has handled all of rhs, it should fall through to the final loop to handle any remaining carries.


text:
Q: BigQuery randomnly fails with /bigquery/v2/projects//queries/>jobID-HEX 404 not found I am getting random failures from the Big Query API when I send it some SQL to fetch data over the REST API.
the REST point I am using is
https://www.googleapis.com/bigquery/v2/projects/${project}/queries
Sometimes I get results and sometimes not.
I found a similar issue on the web where the error was caused by the location parameter being defaulted to 'US', so I tried 'EU' and a couple of my queries worked but some still failed.
The queries do take a while to run, (5 minutes) .
I am able to run it okay in the console.
Any help with where to look would be much appreciated
The error I get looks like this (PS: I did not create that job id returned in the error
Query failed: <!DOCTYPE html>

  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
  <title>Error 404 (Not Found)!!1</title>

404. That's an error.

The requested URL /bigquery/v2/projects/$project/queries/job_F6t2Lvufj01Eo1PyuUZuyUiIUwZA was not found on this server.  That's all we know.

I have tried with no location and also changing the location from US to EU with no luck. I'm based in the UK and the dataset I am querying has the location set to US
below is the perl code that runs the query.
sub query {
my ( $self, $sql, %params ) = @_;

my $url
    = "https://www.googleapis.com/bigquery/v2/projects/$self->{project}/queries";

my $res
    = %params
    ? $self->request( $url,
    { query => $sql, useLegacySql => \0, %params } )
    : $self->request( $url, { query => $sql, useLegacySql => \0 } );

croak "Query failed: $res->{content}" unless $res->{success};

my $job_id = $res->{content}{jobReference}{jobId};

my $attempts;

# If the result set takes longer to build than the default BigQuery
# timeout (10 seconds), we need to poll an endpoint to gather the results.
# We attempt this up to n times before giving up.
until ( $res->{content}{jobComplete} ) {
    $res
        = %params
        ? $self->request( "$url/$job_id", \%params )
        : $self->request("$url/$job_id");

    croak "Query failed: $res->{content}" unless $res->{success};

    croak 'Query failed: result set took too long to return'
        if ++$attempts > MAX_ATTEMPTS;
}

my @fields = map $_->{name}, @{ $res->{content}{schema}{fields} };

sub {
    my @rows;

    for ( @{ delete $res->{content}{rows} // [] } ) {
        push @rows, \my %row;

        @row{@fields} = map $_->{v}, @{ $_->{f} };
    }

    if ( $res->{content}{pageToken} ) {
        my $url = "$url/$job_id?";

        $url .= HTTP::Tiny->www_form_urlencode(
            { pageToken => $res->{content}{pageToken} } );

        $res
            = %params
            ? $self->request( $url, \%params )
            : $self->request($url);

        croak "Query failed: $res->{content}" unless $res->{success};
    }

    @rows;
};

}
I expect the rows that are pulled returned when I run the same SQL in the console to be returned over the API in a consistent way.
Actual result is, sometimes the REST point fails with 404 job id not found

A: The default timeout when calling the API endpoint is 10 seconds, this is for the request not for the query.
The query timeout for BigQuery itself is six hours


text:
Q: CodeIgniter3: Why would $_SERVER['CI_ENV'] ever be set in the first place? I see that in their default installation, their index.php has this:
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');

Why would CI_ENV ever already be set within the $_SERVER array?

A: As Oliver described; it's a special-use case for multiple environments. Splitting out the development, testing & production by means of .htaccess before it even gets to the code. To configure this:
Development (Localhost)
<IfModule mod_env.c>
    SetEnv CI_ENV development
</IfModule>

Testing (Your Local Server)
<IfModule mod_env.c>
    SetEnv CI_ENV testing
</IfModule>

Production (Remote Server)
<IfModule mod_env.c>
    SetEnv CI_ENV production
</IfModule>

You're right in thinking it won't ever change unless there's some manual intervention. There's not much documentation in regards to this:

"This server variable can be set in your .htaccess file, or Apache config using SetEnv. Alternative methods are available for nginx and other servers, or you can remove this logic entirely and set the constant based on the server's IP address."

Source: Using the Environment Constant

A: Just in case you are using nginx, here is the configuration you have to add
inside vhosts configuration:
  server {

        location ~ \.php$ {
            fastcgi_param CI_ENV production;
        }

save and run nginx syntax check (just to avoid you from cursing me):
nginx -t

if you having issues or you cant find the parameter, you can follow the answer below:
Nginx variables similar to SetEnv in Apache?

A: It is a convention used by codeigniter. It helps the framework function 'out of the box'.


text:
Q: Firing radio buttins shows and hides textbox in JS Very simple but no idea why it doesn't fire.
I want a text box to open up when the user clicks on "yes" and for it to hide when the user clicks on "no" and when nothing is selected.
I looked it up and I found some code that should be working but it isn't.
This is my HTML:
     <form name="form2" onsubmit="return validateForm()" method="post">
        <fieldset id= "fieldset2">
        <legend>Step 2</legend>
            Would you like your company name on your badges?

            <input type="radio" id="companyYes" name="company">Yes<input type="radio" id="companyNo" name="company">No

            <input type="text" id="companyText">

        Will anyone in your group require special accommodations?

       (if yes) Please explain below:

        <input type="radio" name="special" id="specialYes" value="Yes">Yes<input type="radio" id="specialNo" name="special" value="No">No

        <input type="text" id="specialText">

        </fieldset>
    </form>

This is my JS:
$("#companyYes").on("click", function() {
    $("#companyText").show();
});
$("#companyNo").on("click", function() {
    $("#companyText").hide();
});
$("#specialYes").on("click", function() {
    $("#specialText").show();
});
$("#specialNo").on("click", function() {
    $("#specialText").hide();
});
$(Document).on("click",function(){

}
$( document ).ready(function() {
    $("#check").hide();
    $("#specialText").hide();
    $("#companyText").hide();
});

A: You have an error in the console:

Uncaught SyntaxError: missing ) after argument list

You are missing a ); in
$(Document).on("click",function(){

}

Working JSFiddle:
Side Note:

*

*Better to put the click events inside document.ready() too

*Instead of hiding the objects at page load with jQuery use pure css (display: none;) so they will not flicker when the page first loads


text:
Q: Many sprites need to load on mobile devices in unity3D My 2D game has 3 characters which each character has 7 types of animation that is contained to many frames. Those are around 1050 frames (sprites) for all 3 characters animations. I make atlas by these sprites but right now it is around 60 2048x2048 atlases with compressed format.
So on some devices which I've tested, The game is not loaded but on some other devices it is. I think it's because of too many atlases which they can't load on these mobile devices RAM.
I've tried to make these frames as small as possible and put them in atlas but as I said before the number of atlases is 60 and I can't reduce number of frames or size of them more than this.
What do you think guys and what can I do ?

A: There is a limitation in mobile devices for how many images can load in ram. This is a bad idea to import your sprite with 2048*2048 dimension and then compress them to something like 512*512. You have to reduce the size of those sprite in an image editor program and then you can join 16 512*512 images and make a 2048*2048 sprite. Now you just load 1 image in mobile ram instead of 16 images.


text:
Q: Cannot read property 'state' of undefined I'm trying to get the values from the input in the button click but when I click the error appears: Cannot read property 'state' of undefined.
This my code, in authentication function this.state returns: Cannot read property 'state' of undefined.
constructor(props) {
  super(props);
  this.state = {
    email: '',
    pass: ''
  }
}

handleChange (event) {
  this.setState({
    [event.target.name]: event.target.value
  })
}

authentication() {
 console.log(this.state);
}

render() {
        return (
            <Fragment>
                <LoginStyles />

Login

                            Nome:
                            <input type="text" name="email" onChange={event => this.handleChange(event)} />

                            Senha:
                            <input type="password" name="pass" onChange={event => this.handleChange(event)} />

                            <button className="btn-default" onClick={this.authentication}>Acessar</button>

            </Fragment>
        )
    }

A: You should bind your authentication function as well as handleChange function. To do that you can either use bind method in constructor or use ES6 arrow operator as below-
handleChange = (event) => {
  this.setState({
    [event.target.name]: event.target.value
  })
}

authentication = () => {
 console.log(this.state);
}

A: As someone already mentioned, you have to bind the method in the constructor or in the onClick as he did
Here is a link to Handling Events in React


text:
Q: How to Validate appid of the Azure AD Access We have a .NET Core application which performs JWT token authentication. This application is registered in Azure AD with a client Id of abcde and an API scope of api://abcde. Our tenant has other applications registered, one of which has a client id of fghij. What I noticed is that if I use this client Id with its secret and API scope api://abcde I was able to generate an access token and access the APIs under this scope.
services.AddAuthentication(options =>
{
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.Authority = $"{ Configuration.GetValue<string>("AzureAD:Instance") }/{ Configuration.GetValue<string>("AzureAD:TenantId") }/";
    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        ValidAudience = Configuration.GetValue<string>("AzureAD:Audience"),
        ValidIssuer = $"https://sts.windows.net/{ Configuration.GetValue<string>("AzureAD:TenantId") }"
    };
});

The solution I have in mind is to validate the appid field in the access token. How can I achieve this? Basically I want to make sure that only client Id abcde can request for an access token for scope api://abcde.
"aio": "abcde=",
"appid": "abcde", //client id of the application in Azure AD
"appidacr": "1",

A: You can get ClaimsPrincipal first and then use
ClaimsPrincipal.Current.FindFirst("appid").Value

to get the value of appid field. Then judge if the value equal to your specified app id.

A: You can change the default Authorization policy to validate appid claim.
Out of the box, the default policy is:
new AuthorizationPolicyBuilder()
    .RequireAuthenticatedUser()
    .Build();

You can change it to:
    builder.Services.AddAuthorization(options =>
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .RequireClaim("appid", "allowedApp1", "allowedApp2")
            .Build();
    });

Please see for reference Setting global authorization policies using the DefaultPolicy and the FallbackPolicy in ASP.NET Core 3.x


text:
Q: How to apply something like --space-prototype-paren=0 but for signatures with perltidy We have the following code:
sub some_method($self, %args) {
    #code here
}

When I run it trough perltidy it gets formatted like this:
sub some_method ($self, %args) {
    #code here
}

How to make perltidy to not add the space between the subroutine name and the starting parenthesis for the signature?
I looked at the perltidy documentation but the closest I found was --space-prototype-paren=0 which seemingly does not work for signatures.


text:
Q: SQL select rows given they were included in TOP in a given year I'm trying to select previous years' data for the top-selling products from this year to see how they've done over time.
I currently have something like:
SELECT TOP 10 *
WHERE Table.Year = 2016
ORDER BY Table.Transactions DESC

which gets me the data for the current year, but I'm not sure how to pull data for that same top 10 in previous years, given that this year's top 10 likely differs from previous years' top 10.
I was wondering if there was a way to do something along the lines of:
SELECT *
WHERE Table.Year = 2015
AND (order ID was in Top 10 in 2016)
ORDER BY Table.Transactions DESC

Except clearly I have no idea what to put in place of the bracketed condition.
Any suggestions would be greatly appreciated. Thanks!

A: do you want this:
SELECT *
From Table
WHERE Table.Year = 2015
AND ID IN (
    SELECT TOP 10 ID
    FROM Table
    WHERE Table.Year = 2016
    ORDER BY Table.Transactions DESC
)
ORDER BY Table.Transactions DESC

A: Use window functions:
select t.*
from (select t.*,
             row_number() over (partition by year order by transactions desc) as seqnum
      from t
     ) t
where seqnum <=  10;

Another fun way is to use cross apply:
select t.*
from (select 2015 as yyyy union all select 2016) y cross apply
     (select top 10 t.*
      from t
      where t.year = y.yyyy
      order by transactions desc
     ) t;

Instead of listing out the years explicitly, you can use a subquery (select distinct year from t) y.

A: Note ID should be some unique value like a PK
SELECT *
FROM YourTable
WHERE YourTable.Year = 2015
AND ID IN
(SELECT TOP 10 ID
WHERE Table.Year = 2016
ORDER BY Table.Transactions DESC)

A: select      *

from       (select      t.*
                       ,dense_rank () over (partition by t.year order by t.transactions desc)   as dr

            from        t
            ) t

where       t.dr <= 10

order by    t.year
           ,t.dr
;


text:
Q: How do I use syntax highlighting in PHP within a markdown github gist? I want to include code in a markdown gist on github, and cannot work out how to do syntax highlighting.
github flavoured markdown - e.g.
```php
    Class::function($param);
```

would highlight the syntax as php in an issue, for instance, but it seems not in a gist.

A: Fenced code blocks do work in Markdown Gists, and in fact your code is being rendered that way. If you inspect the blocks you'll see that they are contained in divs with class="highlight highlight-PHP".
The problem is that PHP code is only recognized for highlighting by GFM if it includes the <?php delimiter (much like PHP code only runs inside a <?php block). Add this to the top of each PHP code block and you should be good to go, e.g.:
...

```php
<?php
class GO_Example_Model_Thing extends GO_Base_Db_ActiveRecord {
    ...

A: Use this HTML comment tag before the block:

<!-- language: php -->

then your block of code and the rest of que answer/question:

    Class::function($param);
    // more code...

Important rules:

*

*Don't indent the HTML comment.

*Enter a new empty line after the comment.

*If don't work insert a new empty line before the comment and the indented code too.

You can check the Stack Overflow's Markdown help and a more elaborated meta's answer.


text:
Q: SharePoint 2010 Organization Browser limit active/enabled AD accounts users We are just starting to use the Organization browser webpart in our local intranet. While working with it we've noticed that disabled AD accounts are showing up in the list. Is there a way to filter the webpart to only bring back AD accounts that are enabled?

A: Yes, you could go to your user profile synchronization service to remove disabled accounts from the synchronization process.  Here is where I found the solution.

*

*Go to your central administration website

*Click on "Application Management"

*Click on "Manage Service Applications" under "Service Applications"

*Click on the "User Profile Synchronization Service"

*Click on "Configure Synchronization Connections" under "Synchronization"

*Click on your connection and select "Edit Connection Filters" in the context menu

*In the "Exclusion Filter for Users" section fill in "userAccountControl" for Attribute

*Fill in "Bit on equals" for operator

*Fill in "2" for filter

*Click the "Add" button

*Click the "OK" button at the bottom of the page


text:
Q: How to customize UIRefreshControl with different image and position? I have been looking around but couldn't find anything good about this.
I would like to customize the default UIRefeshControl with different loader, etc. So far I can only change tintColor & attributedTitle properties and most code I found are just basically creating a new "pulltorefresh" effect but what I want is to just use the UIRefreshControl and customize it a bit.
Is this possible?

A: You can't add different loader without accessing private APIs, but you can add background image:
UIImageView *rcImageView =
    [[UIImageView alloc] initWithImage:
        [UIImage imageNamed: @"refreshControl.png"]];
[self.refreshControl insertSubview:rcImageView atIndex:0];

assuming self is an instance of UITableViewController subclass.
Image size you need is 320x43px (@2x 640x86px), the middle area (approximately 35px) will be covered by the loader animation.
I show application logo there...


text:
Q: Suppress an MSI error code I get error 2803: dialog view did not find a record for the dialog. Its because I have explicitly removed the FilesInUse dialog from my installer. This is a dialog that is sometimes requested for presentation by msiexec when there are file locks. My installer logic does not explicitly ever try to show this dialog. My installer has custom actions to kill processes that are locking files, so there is never a problem with ignoring this message and then doing an installation (but for this process termination I need permissions, and thus a deferred custom action which must run after the dialog is requested). This dialog is essentially useless for all my intents and purposes. Instead of showing a fatal error dialog when this error code presents itself, how can I suppress this error code? Does anyone know if there any way to do that in WiX, perhaps through the form of a C# custom action or something? Any way to trap and handle error codes?

A: I don't think you can suppress that error, unless you are prepared to use your own UI and ignore FilesInUse dialog requests. Or modify the WiX code, if that's allowed. Basically you'd be receiving the messages and reacting (or not) to them:
https://msdn.microsoft.com/en-us/library/aa370573(v=vs.85).aspx
You'd return the ignore response instead of showing a dialog.
Can you use a bootstrapper that elevates when it starts and which runs the MSI? In that case the entire install is elevated and your CAs are elevated when they run before InstallFinalize, even if they are immediate.
If they are your apps, then another solution would be to integrate them with Restart Manager so that they are told to shut down, with the added feature that they can save state and restore it if necessary. You wouldn't need your CAs.


text:
Q: Difference between polynomial and linear combination $$
P=a_0+a_1x+a_2x^2+\cdots+a_nx^n\\
V=a_1v_1+a_2v_2+a_3v_3+\cdots+a_nv_n
$$
Why is Polynomial infinite dimensional here, but the linear combination is not?
Or are there any difference between these two expressions based on both have the similar form.
Thanks

A: The reason that the space of polynomials is considered infinite dimensional is that while a single polynomial can only have finitely many terms, each of finite degree, there is no bound on how many terms it can have, or which degree those terms can have.
In your example, you've stopped the polynomial at degree $n$, and if we can only use up to and including degree $n$, then polynomials become a finite-dimensional vector space (of dimension $n+1$, to be specific). But without any such restriction, the infinitely many polynomials $1, x, x^2, x^3, \ldots$ are all linearly independent, and as such the vector space is infinite dimensional.
There is nothing stopping you from doing the same thing with "regular" vectors, i.e. lists of numbers. You can allow addition of two vectors with different number of entries by padding the shortest one with $0$'s on the right until they have the same length, and then add them together the usual way. Also, we may requirre that any trailing zeroes on the right side of a vector are cut (except the final zero if all entries are zero). So, for instance
$$
(1, 2, 3) + (1, 0, 0, 1, 2) = (1, 2, 3, 0, 0) + (1, 0, 0, 1, 2) = (2, 2, 3, 1, 2)\\
(1, 2, 3) + (5, 4, -3) = (6, 6, 0) = (6, 6)
$$
(scaling is done the normal way). This will make a vector space that is entirely analoguous to the space of polynomials, only expressed the way you are used to seeing vectors. It also has the geometric interpretation of including $\Bbb R$ as the $x$-axis in $\Bbb R^2$, including $\Bbb R^2$ as the $xy$-plane in $\Bbb R^3$, and so on all the way up through the dimensions, and looking at the final union of all these vector spaces as a single vector space.
This is, in some sense, the smallest infinite-dimensional vector space you can make. Unlike many other, "larger" infinite-dimensional vector spaces, this one actually has a basis even without invoking Zorn's lemma. That means we can actually know what the elements of the basis are.


text:
Q: Powershell: Capture output from cmd at run time is it possible to capture the Output from a commandline while a cmd is running? I´ve a small exe, which displays various Messages that should be processed with a script and displays the user some informations while the script is running.
My script starts the program (the exe) with some Parameters und checks if the process is still running. While the program is running i want to capture all messages to a variable to process it. I can´t find any solution, some tests with "run.exe 2>&1" etc... fails.
Any ideas?

A: $oInfo = New-Object System.Diagnostics.ProcessStartInfo
$oInfo.FileName  = "ping"
$oInfo.Arguments = "localhost"
$oInfo.UseShellExecute = $False
$oInfo.RedirectStandardOutput = $True

$oProcess = New-Object System.Diagnostics.Process
$oProcess.StartInfo = $oInfo

[Void]$oProcess.Start()

$bDone = $False

while (!$bDone)
{
    $char = $oProcess.StandardOutput.Read()

    if ($char -eq -1)
    {
        if ($oProcess.HasExited)
        {
            $bDone = $True
        }
        else
        {
            Wait-Event 1
        }
    }
    else
    {
        Write-Host -NoNewline "".PadLeft(1, $char)
    }
}


text:
Q: Encryption in PHP leaves unwanted characters I have made an encryption function which encrypts a simple value and stores it in the database. Here is the code to encrypt and decrypt:
public function encrypt($string){
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $value = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key256, $string, MCRYPT_MODE_ECB, $iv);
    $value = base64_encode($value);
    return $value;
}

public function decrypt($string){
    $value = base64_decode($string);
    $value = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key256, $value, MCRYPT_MODE_ECB);
    return $value;
}

When I encrypt a simple value such as 'Michael' and decrypt again, I get the value:
Michael���������

Is there a reason I get all those question marks or a way to get rid of them?

A: In my experience, those extra character are NULL-bytes used for padding, that has been preserved after decryption.
You should try changing your decrypt() function to:
public function decrypt($string){
    $value = base64_decode($string);
    $value = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key256, $value, MCRYPT_MODE_ECB);
    return trim($value, "\0");
}

A: use bin2hex() instead of bas64_encode() and you can use the hex2bin() before decryption instead of base64_decode()
protected function hex2bin($hexdata)
{
 $bindata = '';
 for ($i = 0; $i < strlen($hexdata); $i += 2) {
 $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
     }

  return $bindata;
}

Ofcourse you can use hex2bin() in PHP., this custom code  is for compatibility with Java like platforms.
I do it this way. May be you can give a try.
Thanks


text:
Q: Skip programmatic changes in valueChanges of Angular 2 control I'm subscribing to the valueChanges observable of an Angular 2 (2.2.1) control. It's defined in AbstractControl in @angular\forms\src\model.d.ts and it's doc string states that it will yiald changes from the UI as well as programmatic ones:
/**
 * Emits an event every time the value of the control changes, in
 * the UI or programmatically.
 */
valueChanges: Observable<any>;

How can I filter this down to give me only the changes from the UI and not the programmatic ones?
I think that the boolean props (pristine, dirty, touched, etc.) won't help me, because even after a control is marked dirty - indicating a change from the UI, which I would like to capture - there might be further programmatic changes, which I would like to ignore.

A: You can use
control.setValue(123, {emitEvent: false})

See also

*

*https://angular.io/docs/ts/latest/api/forms/index/AbstractControl-class.html#!#setValue-anchor

*https://github.com/angular/angular/blob/e9f307f9488e44879dc027e5f4436fb6bc046fa4/modules/%40angular/forms/src/model.ts#L669

A: Well, you want to ignore changes made by programatically, that means changes made by you (the programmer, not the end user).
When you make a programatic change, you may set a property in a shared service. When you subscribe the valueChanges observable, simply consult the shared service every time.


text:
Q: Java / Scala math library with elliptic integrals and bessel functions? I am looking for a math library for scientific computing to use in Java / Scala. Especially I need complete elliptic integrals und modified Bessel functions. I would be nice if it is open source, but I guess I will have to take whatever is out there. A scipy (python lib for scientific computing) replacment would be great :-)

A: As far as I'm aware, the most widely used Java math libraries are:

*

*The Apache Commons Math library, and

*The Colt project (developed by CERN)

You'll have to investigate their respective APIs though to determine if they provide exactly the functionality you require.

A: I know that the GNU Scientific Library contains both elliptic integrals and Bessel functions of many kinds.  Unfortunately, good mathematics libraries are hard to come by; your best bet may be to wrap the GSL using JNI (or JNA if you can get it to work).
If you really must have pure Java/Scala functions, I guess you could translate the portions of the library you need.  It would be a lot of work, but it is GPLed code at least.


text:
Q: How can i update a value in mysql database with php when a checkbox is checked? In database i am updating the height of an image and after the checkbox is checked i want to see the image with that height.Any idea what should i be using to achieve this ? An example would be appreciated.

A: Okay, what you need to do is implement ajax for async call to database for updating image's height in database and vanilla JavaScript (or jQuery) to resize image after the request is successful.
For Example:
HTML
<input type="checkbox" name="your_checkbox" value="50" onclick="changeHeight(this);">

<img src="image/url/here.jpg" alt="foo" class="your-class" id="img">

JavaScript
let changeHeight = checkbox => {
    if(checkbox.checked){
        $.ajax({
            url: 'your/path/to/updating/file.php',
            type: 'POST',
            data: {img_height: checkbox.value}
            success: res => {
                $('#img').css({height: checkbox.value+'px'});
            },
            error: err => {
                console.error(err);
            }
        });
    }
}

PHP
$height = $_POST['img_height'];

// query to update height in the database...


text:
Q: Angular 4.0.0 documentation I am looking for a way to see the documentation URL for previous releases of angular like Angular 4.0.0 or Angular 4.2.0. Angular.io only has documentation of 4.4.4 which is latest version as of today. I want use little older version of angular to get support for relatively older version of google chrome. I also checked github but could not find old version documentation.

A: Please look into Angular Change Log
Angular Document cannot update according to what the current build is that is the reason they have a changelog file which describes all the versions that they are working on presently . As of today Angular v5 RC 0 is released and the stable is 4.4.4. You can Find docs for all the beta versions the PR for each breaking change and added concepts.


text:
Q: Gaussian distribution with mean zero and variance $\sigma^2$ For a Gaussian distribution with mean zero and variance $\sigma^2$, let $X \sim N(0, \sigma^2)$. Is it integral
$$P(X>0)=\frac{1}{2}?$$

A: For any random variable with a continuous symmetric distribution this is true. $N(0,\sigma^{2})$ has  these properties.
[ $P(X=0)=0$ and $P(X>0)=P(X<0)$. Hence $P(X>0)=P(X<0)=\frac 1  2$].