text:
Q: Multi-Threading Loop Through 4D Array C++ I have many functions that loop over data stored in a 4D array. We are using some OpenMP to help iterate over this data in locations where it makes most sense and we are not overwriting things.
For instance I have the following snippet of code:
void MaximumCombiner::createComplexData(double**** input, const int nX, const int nY,
                                        const int nZ, const int nA, std::complex<double>**** output,
                                        const double* beamData)
{
    for(int iX = 0; iX < nX; ++iX)
    {
        for(int iY = 0 ; iY < nY ; ++iY)
        {
            std::complex<double> complexArg(0.0, (beamData[iY] * M_PI / 180.0));
            std::complex<double> complexExp = std::exp(complexArg);

            for(int iZ = 0; iZ < nZ; ++iZ)
            {
                for(int iA = 0 ; iA < nA ; ++iA)
                {
                    output[iX][iY][iZ][iA] = input[iX][iY][iZ][iA] * complexExp;
                }
            }
        }
    }
}

Originally, I thought I should add a #pragma omp parallel for before each for-loop but now I am wondering if I am spending more time with overhead of creation/deletion of threads than actual work. I also have tried out using #pragma omp parallel above the first for-loop and stuck a #pragma omp for on one of the inner loops, but am not sure if this is best either. What should I look for when trying to decide where to place my OMP calls?

A: Generally the straightforward way is to put only one #pragma omp for on the most outer for-loop. This gives you smallest thread creation/deletion overhead.
However this overhead may not be the bottleneck. So you still need to profile you code to find out the best way, as suggested by the comments.


text:
Q: jQuery element show and slide down on button click So Im learning jQuery / JavaScript. I believe the title says it all trying to get a div section which is set to display: none show whilst slowly sliding down on button click
As per jQuery manual, W3schools and other few places where I've tried to read up, this is what I came up with. Needless to say it doesn't look pretty.
My logic here is that the code should get executed on button click hench I put the onclick event handler to the button element.

function showPackages(){
  $('#submitBtn').on('click', function(){
    $('#showPackages').slideDown('slow', function(){
      $('#showPackages').css('display', 'inline');
    });
  });
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

        Collapsible Group 1

        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat.

        Collapsible Group 2

        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat.

Any help / advice appreciated.

A: First of all, you have to bind event handlers separated.
function showPackages(){
    $('#submitBtn').on('click', function(){
      $('#showPackages').slideDown('slow', function(){
        $('#showPackages').css('display', 'inline');
      });
    });
}

As you writed every time when you click the input it attached a click event handler to your submitBtn.
Change it to this:
function showPackages(){

}
$('#submitBtn').on('click', function(){

});
$('#showPackages').slideDown('slow', function(){
    $('#showPackages').css('display', 'inline');
});

But, if you want to trigger the event automatically, use .trigger() method.
function showPackages(){
    $('#submitBtn').trigger('click');
    $('#showPackages').trigger('slideDown');
}

A: Try this
show and hide can be done with different effects

*

*hide() and show()

*fadeIn(), fadeOut() and fadeToggle()

*slideUp(), slideDown() and slideToggle()

*In your case you want slide effect so just use slideToggle()

$('#submitBtn').on('click', function(){
//$('#dispPackages').slideToggle('slow')   this will set display:block
$('#dispPackages').slideToggle('slow').css("display","inline-block");
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button id="submitBtn">clickhere</button>

        Collapsible Group 1

        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat.

        Collapsible Group 2

        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to prevent cordova to hide the keyboard when the input loses the focus I'm making a chat application for android with phonegap but i'm facing a problem.
I have a text area field (where the users can write their messages) and a button to send the messages.
When the user clicks on the text area, the keyboard comes up. However, when the user clicks the button to send the message, the text area field loses the focus and the keyboard disappears. I'd like to keep to keyboard displayed and give back the focus to the text area.
I've tried to select the keyboard with
$('#text-area).focus()

But it didn't work out.
I have also added this line to my config.xml.
<preference name="KeyboardDisplayRequiresUserAction" value="false"/>

I've tried to use the plugin https://github.com/driftyco/ionic-plugins-keyboard. When the keyboard is going to hide, it fires an event but the only thing I can do is to open it again with
cordova.plugins.Keyboard.show();

The problem is that the keyboard hide/show and the animation is still triggered.
Any advices ?

A: I had the similar issue. You need to use focus directive for that  just use this link i think you get the point and some help :
Set element focus in angular way

A: i have done this like this:
<textarea id="NewTextBox" ng-model="newMsgModel.text" ng-click="add()"></textarea>

and in angularJS:
$scope.add = function () {
    /** add message to db ...*/

    /** keep Keyboard Open*/
    $('#NewTextBox').focus();
};


text:
Q: ArrayList> - How to tidy up best? A quick question in between: I have a simple WeakRunnableList.
Is this way ok to clean it up (removing dead references), or is there a more elegant and faster solution. Full source for my WeakRunnableList:
public class WeakRunnableList
{
    private ArrayList<WeakReference<Runnable>> _items = new ArrayList<WeakReference<Runnable>>();

    public void Add(Runnable r)
    {
        _items.add(new WeakReference<Runnable>(r));
    }

    public void Execute()
    {
        ArrayList<WeakReference<Runnable>> remove = new ArrayList<WeakReference<Runnable>>();
        for (WeakReference<Runnable> item : _items)
        {
            Runnable tempCheck = item.get();
            if (tempCheck  == null)
            {
                remove.add(item);
            }
            else
            {
                tempCheck.run();
            }
        }
        _items.removeAll(remove);
    }
}

A: Here is my take.
WeakHashMap removes autmatically, so this should suffice. Beware of hashCode/equals semantics of Runnable though.
See also
Are keySet entries of a WeakHashMap never null?
WeakHashMap iteration and garbage collection
import java.util.WeakHashMap;

public class WeakRunnableList
{
    private WeakHashMap<Runnable, Void> _items = new WeakHashMap<Runnable, Void>();

    public void Add(Runnable r)
    {
        _items.put(r, null);
    }

    public void Execute()
    {
        Iterator<Runnable> iterator = _items.keySet().iterator();
        while (iterator.hasNext()) {
            Runnable runnable = iterator.next();
            if (runnable != null) {
                runnable.run();
                iterator.remove();
            }
        }
    }
}

A: You have a race condition between calls to item.get().  I would place item.get() into a local variable and use that.


text:
Q: Mi primer programa en python no funciona como quisiera. Dónde está mi fallo? Soyunordenador.py
print("Hola, me llamo Bernat y soy un ordenador del 1532, ¿Cómo te llamas?")
Sunombre = input()
print("¿Cuántos años tienes?")
Suedad = input()
print("¿Sabías que tu nombre tiene", str(len(Sunombre)), "letras y yo soy", str(486-int(Lasevaedat)), "años mayor que tu?")
Sino = input ()
if (Sino ==("sí" or "si" or "Sí" or "Si" or "SÍ" or "SI")):
    print("Uauuuuuu!!....Eres un gran matemático, mucho gusto de conocerte, espero nos volvamos a ver")
if (Sino ==("NO" or "No" or "no")):
    print("No pasa nada, las mates se aprenden con el tiempo, hasta pronto")
print ("Gusto de conocerte")

A: Los condicionales están mal planteados. En if Sino ==("NO" or "No" or "no"): (y en el anterior condicional igual) primero se evalúa ("NO" or "No" or "no"), lo cual es siempre "NO" ya que una cadena no vacía siempre se evalúa como verdadera. Por lo tanto, si la entrada es "no", "No" o "nO" no se va a evaluar como cierta.
El condicional debe ser:
if Sino == "NO" or Sino == "No" or Sino == "no"

ó usando un contenedor y el operador in:
if Sino in ("NO", "No", "no")

Para no tener que comprobar todas las posibilidades de mayúsculas-minúsculas puedes usar str.lower para convertir todos los caracteres de la entrada en minúscula y simplificar la comparación:
if Sino.lower() == "no":

Además de esto, unas observaciones.

*

*input puede recibir una cadena a imprimir antes de esperar la entrada del usuario, lo cual puede simplificar el código al prescindir de muchos de los print.

*No uses dos if, si el primero se cumple no tiene sentido evaluar el segundo. En su lugar usa elif.

*Por convención, los nombres de las variables no debe empezar con mayúscula y debe separarse las palabras usando _. Son solo convenciones, pero ayudan a la legibilidad y estandarización del código.
Con todo esto, puedes hacer:
su_nombre = input("Hola, me llamo Bernat y soy un ordenador del 1532, "
                  "¿Cómo te llamas? ")
su_edad = input("\n¿Cuántos años tienes? ")
resp = input("¿Sabías que tu nombre tiene {} letras y yo soy {} años mayor que tu? "
             .format(len(su_nombre), 486-int(su_edad)))

if resp.lower() in ("sí", "si"):
    print("Uauuuuuu!!....Eres un gran matemático, mucho gusto de conocerte, "
          "espero nos volvamos a ver")
elif resp.lower() == "no":
    print("No pasa nada, las mates se aprenden con el tiempo, hasta pronto")
else:
     print("No he entendido tu respuesta...")

print ("Gusto de conocerte")

Puedes usar str.format para formatear la cadena en vez de concatenar (lo cual es muy ineficiente dado que las cadenas son inmutables). Si usas Python 3.6 en adelante son más eficeintes y simples los literales de cadena formateados.
resp = input(f"¿Sabías que tu nombre tiene {len(su_nombre)} letras y "
             f"yo soy {486-int(su_edad)} años mayor que tu? ")

A: La excelente respuesta de FJSevilla te explica sucintamente por qué no funciona y cómo arreglarlo.
Sólo quería añadir una explicación un poco más detallada de por qué:
if (Sino ==("NO" or "No" or "no")):

funcionaría cuando el usuario responda "NO", pero no funcionaría si responde "No" o "no".
Entiendo que pretendías que el if se ejecutara si la respuesta era cualquiera de las tres, pero no es eso lo que estás expresando. Lo que estás expresando es que se ejecute el if cuando la variable Sino sea igual al resultado de evaluar la expresión ("NO" or "No" or "no"). Hay que explicar por tanto cómo evalúa python una expresión así.
Cuando python se encuentra varias expresiones separadas por or, lo que hace es examinar el valor de verdad de la primera de ellas. Si es considerada verdad, ya no mira las restantes (pues en el or basta que una sea verdad para que la expresión completa lo sea). El resultado de la expresión completa es igual al valor de su primer expresión antes del or. Si la primera expresión antes del primer or fuera considerada falsa, entonces se miraría la siguiente, etc.
En definitiva, el resultado de una expresión como (A or B or C) es A si A se considera verdadera, o B si A se considera falsa pero B verdadera, o C si A y B se consideran falsas, pero C verdadera, o C si las tres se consideran falsas.
Ahora bien, si A es un booleano, está claro lo que significa que A sea verdadera o falsa. Pero si A es de otro tipo ¿qué se considera falso o verdadero? Depende del tipo:

*

*Si A es un entero (o un flotante), se considera falso si vale 0 (ó 0.0), y verdadero si es distinto de cero.

*Si A es una cadena, se considera falsa si es la cadena vacía "" y verdadera en caso contrario.

*Si A es una lista (o un contenedor) se considera falsa si está vacía  ([]) y verdadera en caso contrario.

*etc. Cada tipo tiene un caso en que se considera falso y otros en que se considera verdadero.

En tu ejemplo A sería la cadena "NO". Esa cadena no está vacía, por lo que se considera verdadera. Por tanto la expresión ("NO" or "No" or "no") se evalúa y su resultado es "NO". Por consiguente tu if equivale a:
if (Sino =="NO"):

y por eso no funciona como esperabas. Otro tanto ocurre con el if del "si".


text:
Q: Executing C programs from HDD or PenDrive So lately I've been in C programming. On trial and Error and Basis I tried Compiling(GCC) and Executing(./a.out) from my Windows' partition and Pen-drive i.e. precisely I tried executing on NTFS and FAT. I'm currently using Ubuntu 14.04(32bit) and executing via Terminal.

PROBLEM:- When I tried executing C program in Terminal (in Pendrive), It returns a following error

bash: ./a.out: Permission denied

Here's what I tried:
(1)WITHOUT ROOT-
tj@tj-HP-Pavilion-dv4-Notebook-PC:/media/tj/HP/TJbin$ gcc phil.c -pthread -o dine
tj@tj-HP-Pavilion-dv4-Notebook-PC:/media/tj/HP/TJbin$ ./dine
bash: ./dine: Permission denied

(2)WITH ROOT-
root@tj-HP-Pavilion-dv4-Notebook-PC:/media/tj/HP/TJbin# gcc phil.c -pthread -o dine
root@tj-HP-Pavilion-dv4-Notebook-PC:/media/tj/HP/TJbin# ./dine
bash: ./dine: Permission denied

Explanation-
Since without root, it returned an error "Permission denied"; I tried it with root, but no success.
Question-

*

*Is it necessary that an C program must reside on EXT partition?

*Is there any command that will grant the permission?

*Does it need .exe for NTFS or FAT and if so can it be executed in Terminal?


text:
Q: How to uninstall expired Kasperksky without required password? My colleage's PC has Kaspersky software that is expired. And he want to remove the software - I help him to uninstall it but the software requires some password that nether of us knows what it is.
A software should be able to be removed by the PC's administrator so I ask here to look for such workaround. My quick google search for this seems not helpful at all.
Please share if you know how to.

A: What you will need to do is run the Kaspersky Anti-Virus remover. Please follow the steps below.

*

*IMPORTANT: Please create a restore point on your system before using the tool by following these instructions:

*

*Windows 7 & Vista:
http://windows.microsoft.com/en-au/windows7/create-a-restore-point

*Windows 8/8.1:
On the Start screen type restore point -> Click 'Create a Restore Point' -> Click 'Create' -> name the restore point Before KAV Remover.

*Please use KAV remover to remove the Kaspersky product which was not removed with the steps above:
Download the Kaspersky removal tool from:
http://media.kaspersky.com/utilities/ConsumerUtilities/kavremvr.exe
Choose the option to 'Save' the file, do not choose Run.
Save it to a location that is easy for you to find; e.g.: your desktop.
Follow the opening process of KAV and select the Kaspersky product you have installed, type in the Captcha code and continue to uninstall the Kaspersky product.
(Tips of the trade when working for Kaspersky!)
Source: https://support.kaspersky.com/1464#block1

A: You could try the following:

*

*Reboot into Safe Mode (hit F8 at startup and select safe mode)

*Enter the Kaspersky Program Folder and locate the avp.exe

*rename the avp.exe to whatever you desire (i.e. temp.exe)

*double-click that exe - the Kaspersky icon should show up on the taskbar at the bottom right screen

*right-click that icon and select Settings

*Now find the passwort protection and turn it off

*Click ok to close the window and restart your computer

*Now take the usual steps to uninstall software (control panel -> uninstall programs -> kaspersky and follow the routine)

A: *

*Boot in Safe Mode

*open regedit

go to Windows 64-bit: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\KasperskyLab\AVP16.0.1\settings
change EnablePswrdProtect to 0

*restart in normal mode

*set a new password for Kasperky (require even if you want to uninstall)

*uninstall Kasperky

A: Use Revo Uninstaller Software. It will remove entire software from root including registry and log files.
URL: www.revouninstaller.com/revo_uninstaller_free_download.html

A: If you have forgotten your Kaspersky password here is the best way to change it under Windows 7.

*

*Visit this link https://support.kaspersky.com/us/11101. Download the KLAPR zip setup.

*Press Windows + R for the Run window and Type msconfig and click Ok.

*On the System Configuration Dialogue box click on "Boot option" under menu.

*Under Boot options select safe mode with minimal as the second selection.

*Click Ok. On the next dialogue box click Restart. (This will boot in safe mode)

*Under safe mode; visit the folder containing the KLAPR setup, Unzip and Double click. This will open a command dialogue box. Just press any key and it will show process successful. press any button again as instructed and restart.(The computer will restart in safe mode)

*Open Kaspersky and you will notice you can now change the password.

*Repeat step 2 while in safe mode but this time UNCHECK the safe mode option and restart your computer.

Good luck.

A: Download Kaspersky Removal Tool.

*

*Enter safe mode (msconfig → reboot into Safe Mode)

*Regedit → Ctrl+F → search for EnablePswrdProtect → change in 3 places for zero.

Still in safe mode, run Kaspersky Removal Tool.

A: The answer by Bento Fernandes works, but for me it was slight different:
I found the EnablePswrdProtect entry in:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\KasperskyLab\protected\KES10SP1\settings

And I didn't need to change the password to uninstall it.


text:
Q: Jquery adding image URLs from Firebase database into HTML table I am trying to insert images from a storage platform (Firebase in this case) in a HTML table. I am using a database which has links to each image (see snapshot at the end of the post) and so far, I have managed to insert only the text from the database in the table and one image, but not the rest, as one can see in this screenshot:

As you can see, the text is shown, while the images have that small icon instead. The code is shown below. It works very well in my browser, but for some reason, it doesn't show in SE platform. Can anyone help me figure out what am I doing wrong? How can I make the images appear in that table?

    <title>Evenimente locale</title>

    Image
    Categoria

The database looks like this:


text:
Q: Is it possible to have Windows Authentication and JWT in the same application in ASP.NET? I have a application working fine with Windows Authentication in IIS Server. Only some Active Directory users have access to the application. I want to have a option where a person without AD user can access the application with JWT and have HttpContext.User setted and roles too.
Example:

*

*Person without AD user open the application in a computer with autologin (sysexample).

*Application detect that the sysexample user it's not allowed in the application and redirect to the login page.

*User logs in with non-AD user and the HttpContext.User is changed to the logged and not sysexample.

Is something like that possible?


text:
Q: How to detect if someone broke a spruce log? I know it's possible to detect when players break certain blocks with the scoreboard criteria stat.mineBlock, but I was wondering how you detect if a player broke a block that has a data value, such as a particular type of wood?
I tried looking through the trusty tab key, but to no avail.

A: stat.mineBlock by itself is a criteria, but you can also use an argument with it. For your example, try stat.mineBlock.sapling. However, these criteria cannot check metadata, so it would not be able to differentiate mining a spruce sapling from an oak one.

A: Assuming SinglePlayer
When breaking a block, its pickUpDelay is 5. Test for items spawning with such pickUpDelay is enough.
testfor @e[type=Item,tag=!old] {Item:[...]}


text:
Q: android eclipse emulator sdcard permission denied I am getting the "open filed: EACCES (Permission denied)" error when trying to copy a file from assets to /sdcard from my unit test project. I spent the last two hours dredging through search and trying many variations. Probably missing some stupid little detail, hopefully someone will see it.
I am using ADT build v22.3.0-887826. Build target is Google APIs 2.2 platform. Tried 4.4.2 with same results. The AVD is 4.4.2.
The LogCat is:
MediaPlayerServiceTest(3324): copy test files
MediaPlayerServiceTest(3324): File copy testfile.mp3 exception. java.io.FileNotFoundException: /storage/sdcard/testfiles/testfile.mp3: open failed: EACCES (Permission denied)

I am testing a service that manages the media player so the class is
public class MediaPlayerServiceTest extends ServiceTestCase<MediaPlayerService>

The code is trivial. Note the canWrite() method must be returning true.
    Log.i(TAG,"copy test files");

    File sdcard = Environment.getExternalStorageDirectory();
    if (sdcard == null) {
        Log.i(TAG,"no sdcard");
    } else {
        if (sdcard.canWrite()) {
            Log.i(TAG,"cannot write to sdcard");
        } else {
            final String fileName = "BBPro_Confirm.mp3";
            final String dest = sdcard.getAbsolutePath() + "/testfiles/" + fileName;
            if (new File(dest).exists()){
                    Log.d(TAG, "No need to copy file " + fileName);
            } else {
                    try {
                        InputStream localInputStream = mTestAppContext.getAssets().open(fileName);
                        FileOutputStream outFile = new FileOutputStream(dest);
                    } catch (IOException localIOException) {
                        Log.d(TAG, "File copy " + fileName + " exception. " + localIOException.toString());
                }
            }
        }
    }

Tried the many variations on uses-permissions that are out there. Current manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="zookey.GPS.test"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="zookey.GPS" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <uses-library android:name="android.test.runner" />
    </application>

    <uses-permission   android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <uses-permission   android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
</manifest>

I can access the sdcard from adb and created a testfiles subdirectory to verify I can update it. Irrelevant when accessing /storage/sdcard/ but also tried remounting sdcard and using /sdcard/.
root@generic:/storage/sdcard # ls -l
ls -l
drwxrwx--- root     sdcard_r          2014-02-15 13:06 Alarms
drwxrwx--x root     sdcard_r          2014-02-15 13:07 Android
drwxrwx--- root     sdcard_r          2014-02-15 13:06 DCIM
drwxrwx--- root     sdcard_r          2014-02-15 13:06 Download
drwxrwx--- root     sdcard_r          2014-02-15 13:05 LOST.DIR
drwxrwx--- root     sdcard_r          2014-02-15 13:06 Movies
drwxrwx--- root     sdcard_r          2014-02-15 13:06 Music
drwxrwx--- root     sdcard_r          2014-02-15 13:06 Notifications
drwxrwx--- root     sdcard_r          2014-02-15 13:06 Pictures
drwxrwx--- root     sdcard_r          2014-02-15 13:06 Podcasts
drwxrwx--- root     sdcard_r          2014-02-15 13:06 Ringtones
drwxrwx--- root     sdcard_r          2014-02-15 13:24 testfiles
root@generic:/storage/sdcard #

I successfully pushed a file to /storage/sdcard:
C:\Users\Bruce\android-sdks\platform-tools>adb -s emulator-5554 push F:\BBPro_link.mp3 /storage/sdcard/testfiles
100 KB/s (5464 bytes in 0.053s)

Rebuilt the ADV several times.
Etc, etc, etc
Any suggestions would be very helpful.

A: Insert in your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

A: The solution was to create a small service in my main app to copy the files. Called this service from the unit test during setup. Used an if exists to prevent copying the files with each test setup.


text:
Q: Is it possible to make multiple separate operations queues (or something similar) with Alamofire? So I need to make like 300+ get api calls and I don't want to pass them all at once and strain the server. So I was thinking of maybe doing about 5 asynchronous calls at a time.
From what I have read here operation queues sound awesome and are very useful. From the answer from this question the asynchronous example makes an operation queue and passes it into the call. I am assuming if I did something like this I could just make 5 separate queues and funnel my calls into those 5 queues (I'm assuming, haven't actually tried it since I would like to use Alamofire). Is something similar possible with Alamofire?

A: Network requests are automatically managed by the underlying URL Loading System, so Alamofire should be able to handle whatever you throw at it. There are ways to schedule Alamofire requests on a queue, but it shouldn't be necessary. Always better to try and measure results rather than speculate.


text:
Q: How can i fix this error? I use Java Spring MVC thymeleaf How can I fix it this error, I use java Spring-mvc thymeleaf, I want to move page from login page to tambah akun(sign up)page? but shows error
this is my entity
@Entity
@Table(name= "tb_akun")
public class Akun {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}
public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}

}
This is my Controller
@Controller
@RequestMapping("/tambahakun/save")
public class TambahAkunController {

@Autowired
private TambahAkunRepository tambahAkunRepository;

@ModelAttribute("tambahakun")
private Akun getTambahAkun(@RequestParam(value="id",required = false)Long id )
{
    if(id==null)
        return new Akun();
    else
        return tambahAkunRepository.findById(id).orElse(null);
}

@RequestMapping(method = RequestMethod.GET)
public String form() {
    return "tambahakun";
}

@RequestMapping(method = RequestMethod.POST)
public String submit(@ModelAttribute("tambahakun") Akun tambahakun) {

    System.out.println(tambahakun.toString());
    tambahAkunRepository.save(tambahakun);

    return "redirect:/tambahakun";
}

}
This is My Html (tambahakun.html)
th:action="@{/tambahakun/save(id=${akun.id})}"method="post"th:object="${akun}">

This is my messages error

2019-07-17 11:49:33.409 ERROR 14064 --- [nio-8080-exec-4]
  o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for
  servlet [dispatcherServlet] in context with path [] threw exception
  [Request processing failed; nested exception is
  org.thymeleaf.exceptions.TemplateProcessingException: Exception
  evaluating SpringEL expression: "akun.id" (template: "tambahakun" -
  line 12, col 43)] with root cause
org.springframework.expression.spel.SpelEvaluationException: EL1007E:
  Property or field 'id' cannot be found on null


text:
Q: Apache Common Maths - Univariate Function Solver I am trying to solve the following mathematical equation for "V" using the apache-commons-math solver.
Equation :
V = log(X/ (V-1))
Following is the MWE;
import org.apache.commons.math3.analysis.UnivariateFunction;
import org.apache.commons.math3.analysis.solvers.*;

public class Test {
    public static void main(String[] args) {

        UnivariateFunction function = v ->  v - Math.log( (9/(v-1)) );
        UnivariateSolver solver = new BrentSolver();
        double c = solver.solve(100, function, -10.0, 10.0, 0);
        System.out.println(c);
    }
}

However, I get the following error;
Exception in thread "main" org.apache.commons.math3.exception.NoBracketingException: function values at endpoints do not have different signs, endpoints: [-10, 10], values: [�, 10]
I have looked around the internet to solve it but so far no success. I am looking for an MWE to solve "V", any help will be highly appreciated.

A: The BrentSolver only works with univariate functions over the real numbers.  The real number support for the function f(v) = v - log(c / (v - 1)) is (1, Infinity).  If v is less than or equal to 1, then the function evaluates to a complex number.
The solver is failing because it tries to evaluate the function at -10 and receives NaN at the value.  This causes the bracketing exception to occur because the sign of NaN is indeterminate.
So, in order for the solver to work you must provide an initial lower bound that is included in the real number support.  Something just greater than 1 should suffice.


text:
Q: Date picker localization in material-table(Material UI) Does anyone know how to do localization of date picker in material-table(Material UI)? In this example, date picker is used when filtering.
import React from 'react';
import MaterialTable from 'material-table';

function App() {
  return (
    <MaterialTable
      title="Simple Action Preview"
      columns={[
        { title: 'Birthday', field: 'birthDay', type: 'date'},
      ]}
      data={[
        { birthDay: "08-30-2020" },
      ]}
      options={{
        filtering: true
      }}
    />
  );
}

export default App;

A: Add the dateSetting in columns.
const columns = [
    {
      title: "Simple Action Preview",
      field: 'birthYear',
      type: "date",
      dateSetting: { locale: "ko-KR"}
      ....
    }
]

A: npx create-react-app datepicker
cd .\datepicker\
npm install material-table @material-ui/core --save

File App.js
import React from 'react';
import MaterialTable from 'material-table';
import idLocale from 'date-fns/locale/id';

function App() {
  return (
    <MaterialTable
      title="Simple Action Preview"
      columns={[
        { title: 'Birthday', field: 'birthDay', type: 'date'},
      ]}
      data={[
        { birthDay: "08-30-2020" },
      ]}
      options={{
        filtering: true
      }}
      localization={{
        body: {
          dateTimePickerLocalization: idLocale
        }
      }}
    />
  );
}

export default App;

A: Material-UI document of localization
import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles';
import { zhCN } from '@material-ui/core/locale';

const theme = createMuiTheme({
  palette: {
    primary: { main: '#1976d2' },
  },
}, zhCN);

<ThemeProvider theme={theme}>
  <App />
</ThemeProvider>


text:
Q: How much faster is Eigen for small fixed size matrices? I'm using Julia at the moment but I have a performance critical function which requires an enormous amount of repeated matrix operations on small fixed size matrices (3 dimensional or 4 dimensional). It seems that all the matrix operations in Julia are handled by a BLAS and LAPACK back end. It also appears theres a lot of memory allocation going on within some of these functions.
There is a julia library for small matrices which boasts impressive speedups for 3x3 matrices, but it has not been updated in 3 years. I am considering rewriting my performance critical function in Eigen
I know that Eigen claims to be really good for fixed size matrices, but I am still trying to judge whether I should rewrite this function in Eigen or not. The performance benchmarks are for dynamic sized matrices. Does anyone have any data to suggest how much performance one gets from the fixed size matrices? The types of operations I'm doing are matrix x matrix, matrix x vector, positive definite linear solves.

A: If you want fast operations for small matrices, I highly recommend StaticArrays. For example (NOTE: this was originally written before the BenchmarkTools package, which is now recommended):
using StaticArrays
using LinearAlgebra

function foo(A, b, n)
    s = 0.0
    for i = 1:n
        s += sum(A*b)
    end
    s
end

function foo2(A, b, n)
    c = A*b
    s = 0.0
    for i = 1:n
        mul!(c, A, b)
        s += sum(c)
    end
    s
end

A = rand(3,3)
b = rand(3)
Af = SMatrix{3,3}(A)
bf = SVector{3}(b)

foo(A, b, 1)
foo2(A, b, 1)
foo(Af, bf, 1)

@time foo(A, b, 10^6)
@time foo2(A, b, 10^6)
@time foo(Af, bf, 10^6)

Results:
julia> include("/tmp/foo.jl")
  0.080535 seconds (1.00 M allocations: 106.812 MiB, 14.86% gc time)
  0.064963 seconds (3 allocations: 144 bytes)
  0.001719 seconds (2 allocations: 32 bytes)

foo2 tries to be clever and avoid memory allocation, yet it's simply blown away by the naive implementation when using StaticArrays.


text:
Q: Combination of fixed size from a list of list I would like to find how many combinations of a fixed size $k$ exist into a list of list.
Where the list containing others is of size $n$.
Where size of inner lists are $s_1, s_2,..., s_n$
Each combination can only have one element of inner lists.
We suppose $k \le s_{min}$ where $s_{min}$ is the lowest cardinality of inner lists.
Example with $k=2$, $n=3$, $s_1=3$, $s_2=2$, $s_3=2$
list[list[a,b,c], list[1,2], list[$,€]]

Gives
(a,1), (a,2), (b,1), (b,2), (c,1), (c,2), (a,€), (a,$), (b,€), (b,$), (c,€), (c,$), (1,€), (1,$), (2,€), (2,$)

A: Lets assume that there are no identical members in any inner list, and no identical elements that are members of two different lists. Outer list has $n$ members (inner lists), $s_i$ is number of members of $i$-th inner list. Pick any (strictly) increasing sequence $1\le i_1<i_2<..<i_k\le n$ and assume these are indexes of  inner lists from which members will be drawn. Member of each lists is picked independently, so for fixed indexes $1\le i_1<i_2<..<i_k\le n$ the number of possible draws is $s_{i_1}*..*s_{i_k}$. This gives the sum:
$$ \sum_{1\le i_1<i_2<..<i_k\le n}s_{i_1}*..*s_{i_k}$$
over all possible sequences to be the answer. In your example $3*2+3*2+2*2$.
Special case: if $s_1=..=s_n$, then:
$$\sum_{1\le i_1<i_2<..<i_k\le n}s_{i_1}*..*s_{i_k}=\sum_{1\le i_1<i_2<..<i_k\le n} s_{1}^{\ k}=\binom{n}{k}s_1^{\ k}$$
because number of strictly increasing sequences of length $k$ with elements from {1,..,n} is $\binom{n}{k}$.

A: In your example all possible lists of all possible lengths (including $0$) may be viewed as a generating function
$$(1+\mathbf{a}+\mathbf{b}+\mathbf{c})(1+\mathbf{1}+\mathbf{2})(1+\mathbf{\$}+\mathbf{€})$$
Since all ordered lists will appear in the expanded polynomial. Note that list items are shown in bold.
As you only care about the length of the list (specifically in your example you have use length $2$) then we can call all symbols $x$ and let the index of $x$ enumerate the length of the list and the coefficient of $x^k$ enumerate the number of lists length $k$.
In your example we have
$$(1+x+x+x)(1+x+x)(1+x+x)=(1+3x)(1+2x)^2$$
and to count lists of length $2$ we want the coefficient of $x^2$ in this expansion
$$(1+3x)(1+2x)^2=12 \, x^{3} + 16 \, x^{2} + 7 \, x + 1$$
which is $16$.
In general for a set of $n$ lists with $s_1, s_2, \ldots, s_n$ items we can enumerate the number of lists length k by evaluating the $x^k$ coefficient of
$$\prod_{i=1}^{n}(1+s_ix)$$
we represent this with the "find coefficient of $x^k$" operator $\left[x^k\right]$
$$\text{lists of length $k$}=\left[x^k\right]\prod_{i=1}^{n}(1+s_ix)$$
Note that, although $x$ "looks like" a variable, it is in fact an indeterminate meaning that we use it purely for it's multiplicative and additive properties in order to determine coefficients, we never even consider the question of evaluating $x$.


text:
Q: How do I get WebStorm to recognize the React variable name? React is included in my project, but WebStorm is not recognizing the variable name React when I'm using it in code (gets a squiggly underline). The code still runs and executes just fine. What do I need to do?

A: Add the react-DefinitelyTyped library to you JavaScript Libraries in WebStorm's preferences. Use the Download... button to search for it and then download it.

A: Just put your cursor over where you are getting the src and hit alt-enter.  Webstorm will download it for you.


text:
Q: Aggregation on Latest Records Of same status in ElasticSearch I Have following data in ElasticSearch index some_index.
[ {
      "_index": "some_index",
        "_source": {
          "cart": {
            "cart_id": 1,
            "cart_status": "new",
            "grandTotal": 12,
            "event": "some_event",
            "timestamp": "2022-12-01T00:00:00.000Z"
          }
        }
      },
      {
        "_index": "some_index",
      "_source": {
        "cart": {
          "cart_id": 1,
          "cart_status": "paid",
          "grandTotal": 12,
          "event": "some_event",
          "timestamp": "2022-12-02T00:00:00.000Z"
        }
      }
    },
    {
      "_index": "some_index",
    "_source": {
      "cart": {
        "cart_id": 2,
        "cart_status": "new",
        "grandTotal": 23,
        "event": "some_event",
        "timestamp": "2022-12-01T00:00:00.000Z"
      }
    }
  },
  {
  "_index": "some_index",
  "_source": {
    "cart": {
      "cart_id": 2,
      "cart_status": "paid",
      "grandTotal": 23,
      "event": "some_event",
      "timestamp": "2022-12-04T00:00:00.000Z"
    }
  }
},
{
  "_index": "some_index",
"_source": {
  "cart": {
    "cart_id": 3,
    "cart_status": "new",
    "grandTotal": 17,
    "event": "some_event",
    "timestamp": "2022-12-01T00:00:00.000Z"
  }
}
},
{
  "_index": "some_index",
"_source": {
  "cart": {
    "cart_id": 3,
    "cart_status": "new",
    "grandTotal": 17,
    "event": "some_event",
    "timestamp": "2022-12-04T00:00:00.000Z"
  }
}
}
]

What I want to get is sum of the grandTotals by the latest cart_statuses of each cart within a given time range.
Having the example above, the result for timestamp >= 2022-12-01 00:00:00 and timestamp<= 2022-12-03 00:00:00 should be something like
cart_status:new, sum grandTotal: 40 because within that time range latest status new have cart_id 3 and 2.
and cart_status:paid, sum grandTotal: 12 and this one because paid is the latest status of only cart_id=1.
What I tried is to use sub-aggregation on top_result, top_hits but ElasticSearch complains that "Aggregator [top_result] of type [top_hits] cannot accept sub-aggregations"
Besides I tried with collapse as well to get the latest by status, but according to docs there is also no possibility to aggregate over the results of collapse.
Can someone please help me solving this, it seems like a common calculation but not very trivial in ElasticSearch.
In SQL this is quite easy with window functions.
I want to avoid persisting intermediate data into another index. Because I need the dynamic query, as the users may want to get their calculations for any time range.

A: you can try the following way. meanwhile, for card_status, sum value will be 52 as it includes card_id 1 that has "new" as card status along with 2 and 3 for given timestamp.
Mappings:
PUT some_index
{
  "mappings" : {
    "properties": {
      "timestamp" : {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss||strict_date_optional_time ||epoch_millis"
      },
      "cart_id" : {
        "type": "keyword"
      },
      "cart_status" : {
        "type": "keyword"
      },
      "grand_total" : {
        "type": "long"
      },
      "event":{
        "type": "keyword"
      }
    }
  }
}

Bulk Insert:
POST _bulk
{ "index" : { "_index" : "some_index", "_id" : "1" } }
{ "cart_id" : "1" , "grand_total":12, "cart_status" : "new","timestamp":"2022-12-01T00:00:00.000Z", "event" : "some_event"}
{ "index" : { "_index" : "some_index", "_id" : "2" } }
{ "cart_id" : "1" , "grand_total":12, "cart_status" : "paid","timestamp":"2022-12-02T00:00:00.000Z", "event" : "some_event"}
{ "index" : { "_index" : "some_index", "_id" : "3" } }
{ "cart_id" : "2" , "grand_total":23, "cart_status" : "new","timestamp":"2022-12-01T00:00:00.000Z", "event" : "some_event"}
{ "index" : { "_index" : "some_index", "_id" : "4" } }
{ "cart_id" : "2" , "grand_total":23, "cart_status" : "paid","timestamp":"2022-12-04T00:00:00.000Z", "event" : "some_event"}
{ "index" : { "_index" : "some_index", "_id" : "5" } }
{ "cart_id" : "3" , "grand_total":17, "cart_status" : "new","timestamp":"2022-12-01T00:00:00.000Z", "event" : "some_event"}
{ "index" : { "_index" : "some_index", "_id" : "6" } }
{ "cart_id" : "3" , "grand_total":17, "cart_status" : "new","timestamp":"2022-12-04T00:00:00.000Z", "event" : "some_event"}

Query:
GET some_index/_search
{
    "size":0,
    "query": {
        "bool": {
            "filter": [
                {
                    "range": {
                        "timestamp": {
                            "gte": "2022-12-01 00:00:00",
                            "lte": "2022-12-03 00:00:00"
                        }
                    }
                }
            ]
        }
    },
    "aggs": {
    "card_status": {
      "terms": {
        "field": "cart_status"
      },
      "aggs": {
        "grandTotal": {
          "sum": {
            "field": "grand_total"
          }
        }
      }
    }
  }
}

Output:
{
  "took": 86,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 4,
      "relation": "eq"
    },
    "max_score": null,
    "hits": []
  },
  "aggregations": {
    "card_status": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "new",
          "doc_count": 3,
          "grandTotal": {
            "value": 52
          }
        },
        {
          "key": "paid",
          "doc_count": 1,
          "grandTotal": {
            "value": 12
          }
        }
      ]
    }
  }
}


text:
Q: How to estimate SQL query timing? I'm trying to get an rough (order-of-magnitude) estimate of how long time the following query could take:
mysql> EXPLAIN SELECT t1.col1, t1_col4 FROM t1 LEFT JOIN t2 ON t1.col1=t2.col1 WHERE col2=0 AND col3 IS NULL;
+----+-------------+--------------------+------+---------------+------------+---------+-----------------------------+---------+--------------------------+
| id | select_type | table              | type | possible_keys | key        | key_len | ref                         | rows    | Extra                    |
+----+-------------+--------------------+------+---------------+------------+---------+-----------------------------+---------+--------------------------+
|  1 | SIMPLE      | t1                 | ref  | foobar        | foobar     | 4       | const                       | 9715129 |                          |
|  1 | SIMPLE      | t2                 | ref  | col1          | col1       | 4       | db2.t1.col1                 |   42318 | Using where; Using index |
+----+-------------+--------------------+------+---------------+------------+---------+-----------------------------+---------+--------------------------+
2 rows in set (0.00 sec)

mysql>

A: This can be done when using SHOW PROFILES syntax.
When you open a MySQL session, you could set the variable "profiling" to 1 or ON.
mysql> SET profiling = 1;

So all the statements sent to the server will be profiled and stored in a historical and shown later by typing the command:
mysql> SHOW PROFILES;

See, from MySQL manual:
mysql> SET profiling = 1;
Query OK, 0 rows affected (0.00 sec)

mysql> DROP TABLE IF EXISTS t1;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> CREATE TABLE T1 (id INT);
Query OK, 0 rows affected (0.01 sec)

mysql> SHOW PROFILES;
+----------+----------+--------------------------+
| Query_ID | Duration | Query                    |
+----------+----------+--------------------------+
|        0 | 0.000088 | SET PROFILING = 1        |
|        1 | 0.000136 | DROP TABLE IF EXISTS t1  |
|        2 | 0.011947 | CREATE TABLE t1 (id INT) |
+----------+----------+--------------------------+
3 rows in set (0.00 sec)

mysql> SHOW PROFILE;
+----------------------+----------+
| Status               | Duration |
+----------------------+----------+
| checking permissions | 0.000040 |
| creating table       | 0.000056 |
| After create         | 0.011363 |
| query end            | 0.000375 |
| freeing items        | 0.000089 |
| logging slow query   | 0.000019 |
| cleaning up          | 0.000005 |
+----------------------+----------+
7 rows in set (0.00 sec)

mysql> SHOW PROFILE FOR QUERY 1;
+--------------------+----------+
| Status             | Duration |
+--------------------+----------+
| query end          | 0.000107 |
| freeing items      | 0.000008 |
| logging slow query | 0.000015 |
| cleaning up        | 0.000006 |
+--------------------+----------+
4 rows in set (0.00 sec)

mysql> SHOW PROFILE CPU FOR QUERY 2;
+----------------------+----------+----------+------------+
| Status               | Duration | CPU_user | CPU_system |
+----------------------+----------+----------+------------+
| checking permissions | 0.000040 | 0.000038 |   0.000002 |
| creating table       | 0.000056 | 0.000028 |   0.000028 |
| After create         | 0.011363 | 0.000217 |   0.001571 |
| query end            | 0.000375 | 0.000013 |   0.000028 |
| freeing items        | 0.000089 | 0.000010 |   0.000014 |
| logging slow query   | 0.000019 | 0.000009 |   0.000010 |
| cleaning up          | 0.000005 | 0.000003 |   0.000002 |
+----------------------+----------+----------+------------+

References (updated at: 2014-09-04):

 - SHOW PROFILE Syntax
 - The INFORMATION_SCHEMA PROFILING Table
 - How To Use MySQL Query Profiling (The Digital Ocean recently published a great article concerning this issue.)


text:
Q: How to identify seasonal time series? I am having sales volume data for 100 stock-keeping units (SKUs). Is there a statistical way of identifying seasonal time series?

A: Seasonality is a periodic signal in the data.  The most basic tool for detecting periodic signals is to transform your data into the frequency domain using a Discrete Fourier Transform (DFT).  In the frequency domain, periodic signals show up as frequency 'spikes' (usually with harmonics at multiples of that frequency), which are generally easy to see unless there is too much noise.
If you are looking to progress further to statistical modelling of the signal, you can add a seasonal component (a number of sine waves) to your time-series model and use your model-fitting to estimate the parameters of the signal (number of sine waves, amplitude, frequency, phase-shift).  If you do this you will automatically have a non-seasonal model built in, which is the special case when the number of signals is zero.  You can use this fact to do a hypothesis test to see whether there are signals in the data.
If you would like a specific example of a test for seasonal components in a time-series, you can have a look at the permutation-spectrum test in O'Neill (2020) and the accompanying function spectrum.text in the ts.extend package in R.  This test uses the maximum Fourier intensity as its test statistic and it tests this against its simulated null distribution computed by permuting the elements of the input time-series vector.  The test can detect periodic signals in noise with reasonable power and it does not require any assumption for the distribution of the noise part of the input.  The linked paper explains the test and shows how to implement it.

A: One possibility would be to fit both a nonseasonal and a seasonal exponential smoothing model to each SKU's time series. Note each model's AICc. SKUs where the seasonal model yields a lower AICc are "more seasonal".
The absolute difference in AICc measures the strength of the evidence (to a degree). As a rule of thumb, Burnham & Anderson suggest that a difference in AICc of about 2 constitutes weak evidence, a difference of 5 constitutes clear evidence and a difference of 10 constitutes strong evidence that the model with the lower AICc describes the data better.
Alternatively, use a holdout sample for each time series. Fit seasonal and nonseasonal models to the initial data, forecast into the holdout sample and check whether a seasonal or a nonseasonal model provides better forecasts. If you need a statistical test as to whether the forecast improvement is significant, you can use the diebold-mariano test.
Look at ets in the forecast package for R. While you are there, look at the seasonplot command to visualize seasonality.


text:
Q: SQL Query with Regular Expression in LIKE function I have a requirement where in I want to filter all rows in a table, which have a keyword 'Risk' in the description but not 'F Risk'. For example, in the following test data, the query should select rows 1,5,6 and 7.

However, when I am using the below query, it is eliminating id 1 (as it meets the second half of the condition) and just returning 5,6 and 7.
SELECT *
FROM TestDesc
WHERE ([desc] LIKE '%Risk%' AND [desc] NOT LIKE '%F Risk%')

I believe I would have to use regular expressions to achieve the desired result, but I am not very familiar with regular expression.
Any help/suggestion would be appreciated. Thanks!

A: I think you need to tweak the search for "F Risk":
SELECT *
FROM TestDesc
WHERE [desc] LIKE '%Risk%' AND [desc] NOT LIKE '%[ (]F Risk%'


text:
Q: Blow-up of a surface at a point living inside a curve Let $C$ be a curve lying on a smooth surface $X$ in $\mathbb P^3$. Let $P$ be a singular point of $C$ and $m$ is the multiplicity of $C$ at  $p$. If we consider the blow - up $\pi : B  \to X$ of $X$ at $p$ and denote $ C'$ to be the strict transform  of $C$ by $\pi $ and $E$ to be the exceptional divisor, then is the following true : $ \pi ^*C = C' + m E$ ?
Can anyone give me any reference on this.
Any help from anyone is welcome

A: This is a community wiki post consisting of the answer from the comments, in order to remove this question from the unanswered queue.

Prop 3.6 of chapter V of Hartshorne – peter a g

Here is the statement of the proposition (with some clarifying language on the assumptions):

Proposition 3.6. Let $X$ be a smooth surface. Let $C$ be an effective divisor on $X$, let $P$ be a point of multiplicity $r$ on $C$, and let $\pi:\widetilde{X}\to X$ be the monoidal transformation with center $P$ (the blowup of $X$ at $P$). Then $$ \pi^*C = \widetilde{C} + rE$$ where $\widetilde{C}$ is the strict transform of $C$.


text:
Q: Efficient way to bypass Error C2248 "cannot access protected member declared in class" I'm implementing a c++ app and among others I also use Poco libraries. Specifically I 'm trying to use the poco logging framework. I have created a class that uses the following code from one of poco examples in order to create a logging mechanism:
 AutoPtr<PatternFormatter> pPatternFormatter(new PatternFormatter());
 AutoPtr<FormattingChannel>pFormattingChannel(new
 FormattingChannel(pPatternFormatter));

 pPatternFormatter->setProperty("pattern", "%s: %p : %t");

 AutoPtr<ConsoleChannel> pConsoleChannel(new ConsoleChannel());
 pFormattingChannel->setChannel(pConsoleChannel);

However when I tried to replace the poco AutoPtr with poco SharedPtr pointer
I get the following build error:
Error C2248   'Poco::FileChannel::~FileChannel': cannot access protected member declared in class 'Poco::FileChannel'
I have searched and found that the FileChannel class has its destructor protected which I assume is used in order to prevent the deletion of the object via a pointer to its base.
Is it efficient to make my class derived from FileChannel with public or protected access specifier for the SharedPtr to work or it there another way?

A: Out of curiosity, I thought about: What if the derived class makes the destructor simply public? Actually, it sounds too easy but I believe it should work.
Sample test-prot-dtor.cc:
#include <iostream>

class Base {

  public:
    Base() { std::cout << "Base::Base()" << std::endl; }
  protected:
    virtual ~Base() { std::cout << "Base::~Base()" << std::endl; }
};

class Derived: public Base {

  public:
    Derived() { std::cout << "Derived::Derived()" << std::endl; }
    virtual ~Derived() { std::cout << "Derived::~Derived()" << std::endl; }
};

int main()
{
#if 0 // Does not work!
  Base *pBase = new Derived;
  delete pBase;
  /* here:
   * error: 'virtual Base::~Base()' is protected
   */
#endif // 0
  Derived *pDerived = new Derived;
  delete pDerived;
  // done
  return 0;
}

Tested with VisualStudio 2013 (Express) and gcc in cygwin on Windows 10 (64 bit). Below a sample session with the latter:
$ g++ --version
g++ (GCC) 5.4.0

$ g++ -std=c++11 -c test-prot-dtor.cc

$ ./test-prot-dtor
Base::Base()
Derived::Derived()
Derived::~Derived()
Base::~Base()

$

About your idea (making SharedPtr a friend of your derived class) I'm not sure. It depends on implementation details of SharedPtr i.e. whether it "does the work itself" or delegates it to another (eventually even hidden) class/method or function...


text:
Q: Detecting and assigning NA values in an R vector when using C I'm using R's .Call interface to C to pass and return real-valued vectors (REALSXP) which may include NA values. For vectors being passed into C, I need to detect the existence of NA values, and in vectors which I return from C I need to assign the NA value.
Suppose vec is a SEXP object that has been set equal to a vector containing REALSXP objects. For instance, if allocating this in C, the code might be
SEXP vec;
PROTECT(vec = allocVector(REALSXP, 10));

With respect to detecting an NA value, I know the following will work:
isnan(vec[index])

where isnan() is defined in math.h. Is this the preferred way for detecting NA values?
I do not know how to assign NA values. I know that I can do something like the following,
vec[index] = 0.0/0.0;

to assign an NaN. I'm not sure exactly what the difference is between NaN and NA in R, but I would prefer to assign NA instead of NaN.
EDIT
Found the answer. Functions ISNA() and ISNAN() are defined in R_ext/Arith.h and so is the symbol R_NaReal which can be used to assign an NA value.

A: Found the answer to my question. Functions ISNA() and ISNAN() are defined in R_ext/Arith.h and so is the symbol R_NaReal which can be used to assign an NA value.


text:
Q: server-server receipt validation vs online validation from device to apple for subscriptions I am researching what's the best way to do a subscription validation without making users login.
I read
Apple doesn't recommend Online validation because of security reasons: HTTPS request can be intercepted via man-in-the-middle attack. (Source - https://blog.apphud.com/receipt-validation/)
This has me thoroughly confused. Does apple not force HSTS so the receipt validation is open to man-in-the-middle attacks?
What's the best way to do a no-login receipt validation on iPhone apps for subscriptions?  If I do server-server without login, then won't sending my back-end be susceptible to hackers just spoofing a userId?


text:
Q: Can not match 2 descriptor opencv android I try to do like this theard Error matching with ORB in Android
But when i use matcher.match(descriptors1,descriptors2,matches); My app is exit and say "Unfortumatively, Car_Traking_1 has stopped"
This is my code when i not use matcher.match(descriptors1,descriptors2,matches); It's run and i can see data of descriptor1,descriptor1 in logcat
This is my code:
 public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
    mImageRGBA = inputFrame.rgba();
    Utils.bitmapToMat(icon, img_object);
    Imgproc.cvtColor(mImageRGBA,img_scene,Imgproc.COLOR_RGBA2GRAY);

    FeatureDetector detector = FeatureDetector.create(FeatureDetector.ORB);
    DescriptorExtractor descriptor = DescriptorExtractor.create(DescriptorExtractor.ORB);;
    DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);

    //first image
    Mat img1 = img_object;
    Mat descriptors1 = new Mat();
    MatOfKeyPoint keypoints1 = new MatOfKeyPoint();

    detector.detect(img1, keypoints1);
    descriptor.compute(img1, keypoints1, descriptors1);

    //second image
    Mat img2 = img_scene;
    Mat descriptors2 = new Mat();
    MatOfKeyPoint keypoints2 = new MatOfKeyPoint();

    detector.detect(img2, keypoints2);
    descriptor.compute(img2, keypoints2, descriptors2);

    //matcher should include 2 different image's descriptors
    Log.i("aaa1", descriptors1.dump());
    Log.i("aaa2",descriptors2.dump());
    Log.i("aaa3",String.valueOf(descriptors1.cols()));
    Log.i("aaa4",String.valueOf(descriptors1.rows()));
    Log.i("aaa5",String.valueOf(descriptors2.cols()));
    Log.i("aaa6",String.valueOf(descriptors2.rows()));

    return mImageRGBA;
}

I see descriptor1 and descriptor2 have data, size of descriptor1 is 32x104 and size of descriptor1 is 32x219
But now when i add 2 line
        MatOfDMatch matches = new MatOfDMatch();
    matcher.match(descriptors1,descriptors2,matches);

So my code will like
 public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
    mImageRGBA = inputFrame.rgba();
    Utils.bitmapToMat(icon, img_object);
    Imgproc.cvtColor(mImageRGBA,img_scene,Imgproc.COLOR_RGBA2GRAY);

    FeatureDetector detector = FeatureDetector.create(FeatureDetector.ORB);
    DescriptorExtractor descriptor = DescriptorExtractor.create(DescriptorExtractor.ORB);;
    DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);

    //first image
    Mat img1 = img_object;
    Mat descriptors1 = new Mat();
    MatOfKeyPoint keypoints1 = new MatOfKeyPoint();

    detector.detect(img1, keypoints1);
    descriptor.compute(img1, keypoints1, descriptors1);

    //second image
    Mat img2 = img_scene;
    Mat descriptors2 = new Mat();
    MatOfKeyPoint keypoints2 = new MatOfKeyPoint();

    detector.detect(img2, keypoints2);
    descriptor.compute(img2, keypoints2, descriptors2);

    //matcher should include 2 different image's descriptors
    MatOfDMatch matches = new MatOfDMatch();
    matcher.match(descriptors1, descriptors2, matches);

    return mImageRGBA;
}

When i run it, it run and exit and say "Unfortumatively, Car_Traking_1 has stopped"
I don't know what problem with it, or descriptor1 and descriptor2 had to same size. How can i fix it.

A: Did you convert your OBJECT image to gray? You converted scene photo with this code on the start of onCameraFrame:
mImageRGBA = inputFrame.rgba();
Utils.bitmapToMat(icon, img_object);
Imgproc.cvtColor(mImageRGBA,img_scene,Imgproc.COLOR_RGBA2GRAY);
but where did you converted object image to the same format?
Before calculating descriptor and keypoints of object image you should convert it to gray:
Imgproc.cvtColor(OBJECT_IMAGE,img_object,Imgproc.COLOR_RGBA2GRAY);

Just be careful to convert object image to Mat() before using this above. If its bitmap you can convert it on the same way as you did with scene image.


text:
Q: Error proofing data Is it possible to encode data is such a way that it can self-recover from corruptions? (corruptions - for example, hard drive or usb drive with bad sectors)
I'm not looking for solutions involving backups, raid, or file system repair. I'm looking for solutions that employ some kind of self-healing process on raw data.
I'm also aware that I can checksum my data ahead of time and that this will help me know (in most cases) if corruption has occurred. For me this is only half the battle, I need the system to not only know that something has changed but be able to restore from the change itself.
I am aware of ZFS and its capabilities:

ZFS can heal the data if the storage pool has redundancy via ZFS
  mirroring or RAID. If the storage pool consists of a single disk, it
  is possible to provide such redundancy by specifying "copies=2" (or
  "copies=3"), which means that data will be stored twice (thrice) on
  the disk, effectively halving (or, for "copies=3", reducing to one
  third) the storage capacity of the disk.

But I am looking for somewhat different solutions/tools, for example something that allows me to protect data on a usb flash drive that is formatted FAT,FAT32, exFAT. Does such a thing exist?

A: No such tool exists to magically recover corrupted data unless you have sufficient parity/backup copies of the data in question.  @grawity indicates tools like PAR2, QuickPar, and WinRAR can do what you want.  To work properly those tools will build parity data into the archive so recovery will (hopefully) be possible if some data is corrupt.  I am a long time WinRAR/7z user but I have never explored this functionality so I cannot comment on its effectiveness.
Most file systems have some measure of "self healing" like NTFS check disk, which is just as likely to corrupt your data as it is to fix it.
ZFS is not the only file system with what I would consider "true" self healing capabilities, but it is the most mature.  Btrfs and ReFS also have "true" self healing capabilities.  Even file systems with "true" self healing require parity data to heal.
I would avoid putting data you really care about on a flash drive if at all possible, not because it is flash, but because even if you have parity data it will still only be contained on one physical device.  If you must use a flash drive make sure it uses high quality memory and avoid cosmic ray storms.  Experiment with some of the tools @grawity mentioned, I know I will :)

A: Thanks to an old slashdot post, I have found a solution/tools that will protect data on flash drives.
Shielding your files with Reed-Solomon codes
Looks like it uses data parity to heal corrupted/damaged sectors.

What follows is a simple description of a way I use to additionally
  "shield" my important files, so that even if some sectors hosting them
  are lost, I still end up salvaging everything.
The idea behind this process is error correcting codes, like for
  example the ubiquitous Reed-Solomon. With Reed-Solomon, parity bytes
  are used to protect a block of data from a specified maximum number of
  errors per block. In the tools described below, a block of 223 bytes
  is shielded with 32 bytes of parity. The original 223 bytes are then
  morphed into 255 "shielded" ones, and can be recovered even if 16
  bytes from inside the "shielded" block turn to noise...

The "freeze" and "melt" scripts can be used to create files that can be deployed to a USB flash drive (or any medium for that matter).

We "shield" a file with the freeze.sh script, which is part of my
  package; we then melt.sh the frozen file, and verify (through md5sum)
  that the new generated file is exactly the same as the original one.
  We then proceed to deliberately destroy 64KB of the shielded file
  (that's a lot of consecutive sectors!), using dd to overwrite 127
  sectors with zeros. We invoke melt.sh again, and we see that the new
  generated file (data3) has the same MD5 sum as the original one - it
  was recovered perfectly.

Fantastic!!!


text:
Q: How to ignore JSON field in response alone in java I want to exclude name and age from my response, but When I receive the JSON payload request I need name and age field - after my business logic, I want to send status and message as part of JSON response. name and age should exclude from that.  How can I achieve this in java?
public class Sample {

    private String name;
    private String age;
    private String status;
    private String message;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

My Controller class:
@PostMapping(path = "/testApp", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> test(@RequestBody Sample sample) {
    Sample response = myService.calculate(sample);
    return new ResponseEntity<Object>(response, HttpStatus.OK);
}

My Request
{
    "name": "Mark",
    "age": "48"
}

My Response
{
    "status": "200",
    "message": "success"
}

A: Using Jackson for Java/JSON serialization and deserialization provides a number of ways to control the JSON that is produced and accepted.
Since you want to omit fields in certain cases, the most straightforward way to do this is with the @JsonIgnore annotation.
@JsonIgnore can be used on fields, getters, and setters (and more) to always ignore the field, ignore on output to JSON, or ignore on JSON->Java deserialization.
Your basic Sample class could ignore message all the time (both when serializing and deserializing) by annotating the field:
public class Sample {
    private String name;
    private String age;
    private String status;
    @JsonIgnore private String message;
}

When you want to omit a field when serializing Java -> JSON you can annotate the getter, when you want to ignore a field when deserializing JSON -> Java you annotate the setter.
So if you want to omit name and age when your Sample object is producing JSON, you'd annotate both those fields
public class Sample {

    private String name;
    private String age;
    private String status;
    private String message;

    @JsonIgnore        // Added Annotation
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @JsonIgnore        // Added Annotation
    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

With those annotations, name and age will be set in the object when you deserialize from JSON, but they will not be output when serializing to JSON, and you need only one class, not separate classes for the request and the response.

A: I think you should create a separate class for request and response, you can't include two different functionalities in the same class, let's suppose in future in you need to include something in request or response, then again you need to change whole lot of code and if you keep segregation then it will be not a problem.

A: You can't do it without some tricky hacks.  Response and Request don't even share a single field, and from OOP perspective they are different objects, so why mashing them up together?
If you are just experimenting with (de)serialization, then you can try @JsonIgnore on specific setters and getters to manipulate serialization and deserialization. Check this question Ignoring property when deserializing
If you are actually trying to solve the problem writing a clean code then split them into two separate classes.

A: You should have a Sample class with the name and age fields and a SampleResponse class with only the fields you want to include in the response.


text:
Q: EAR archive inside another EAR using Maven? Can you put an ear archive inside another ear archive? I have tried adding an ear dependency to an ear module specifying artifact type as<type>ear</type>with maven 3.3.3 but I getFailed to initialize ear modules: Unknown artifact type[ear]If I don't specify an artifact type then maven looks for a jar artifact and fails to find it.
Is there a way to do it? If not, is there a reason to prohibit inner ear archives?

A: An EAR archive can only contain WAR, JAR and RAR (Resource Archive) modules.
If you have an EAR project in Maven, you should add your EJB dependencies like this one:
<dependency>
    <type>ejb</type>
    <groupId>...</groupId>
    <artifactId>...</artifactId>
    <version>...</version>
</dependency>

and configure the maven-ear-plugin similarly
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-ear-plugin</artifactId>
    <configuration>
        ...
        <modules>
            <ejbModule>
                <groupId>...</groupId>
                <artifactId>...</artifactId>
            </ejbModule>
        </modules>
    </configuration>
</plugin>

For WAR dependencies you need to use <type>war</type> and <webModule> instead.


text:
Q: gRPC comunication error stream terminated by RST_STREAM with error code: PROTOCOL_ERROR and SSL Wrong Version Number Im trying to check gRPC service status from a grpcurl call, but got "SSL handshake failed due to WRONG_VERSION_NUMBER"
Logs from the Pod:
"E0725 11:18:36.532479482      62 ssl_transport_security.cc:1455] Handshake failed with fatal error SSL_ERROR_SSL: error:100000f7:SSL routines:OPENSSL_internal:WRONG_VERSION_NUMBER.
"
Im using an nginx ingress controler with a valid cert on this ingress
I0725 11:18:29.248298       7 controller.go:166] "Configuration changes detected, backend reload required"
I0725 11:18:29.322648       7 controller.go:183] "Backend successfully reloaded"
I0725 11:18:29.322834       7 event.go:285] Event(v1.ObjectReference{Kind:"Pod", Namespace:"ingress", Name:"nginx-ingress-microk8s-controller-xdlxz", UID:"4ad5159c-c2b7-4d0a-9a75-724f29f0d69c", APIVersion:"v1", ResourceVersion:"13020298", FieldPath:""}): type: 'Normal' reason: 'RELOAD' NGINX reload triggered due to a change in configuration
when send the grpcurl got this error
"stream terminated by RST_STREAM with error code: PROTOCOL_ERROR"
Not sure if the WRONG_VERSION_NUMBER is related to the fact I sending TLSv1.3 and the gRPC server does not support that or the certificate although it is valid, has some mistmach...
in case that helps, open ssl with show cert verification
No client certificate CA names sent
Peer signing digest: SHA256
Peer signature type: RSA-PSS
Server Temp Key: X25519, 253 bits
---
SSL handshake has read 3277 bytes and written 440 bytes
Verification: OK
---
New, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384
Server public key is 2048 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)
---
---
Post-Handshake New Session Ticket arrived:
SSL-Session:
    Protocol  : TLSv1.3
    Cipher    : TLS_AES_256_GCM_SHA384


text:
Q: 1 large json file to many individual markdown files This was a long post with context, but the gist of it was that I have one 2000 item json file with multiple fields , and I need to make them all become their own markdown files, converting every internal field but the definition item into frontmatter. If I could delete the content item as well, that would be a bonus.
How do I go about this? I've been bashing my head against the wall for three days now.
{
"3350" : {
    "askedHistPercent1" : "98",
    "askedHistYear1" : "2009",
    "author" : " Name ",
    "categories" : [ "Generic Category" ],
    "content" : "

\n
\n
\n
\n
\n
Keyword history
\n
\n
\n
\n Percentage correct\n	\n 98%\n
\n
\n Year asked\n	\n 2009\n

\n
\n
\n
\n
Suggest a change[edit]
\n
\n
Suggest a change for this keyword\n
\n
\n

\n
\n\n\n\n\n",
    "date" : "2013-05-30 02:23:04",
    "definition" : "
Very long definition section;
",
    "excerpt" : "Keyword history Percentage correct 98% Year asked 2009 Suggest a change[edit] Suggest a change for this keyword",
    "id" : 3356,
    "permalink" : "",
    "sourceLink1" : "Source",
    "title" : "Title item name"
  },
 "3351" : {
    "askedHistPercent1" : "98",
    "askedHistYear1" : "2009",
    "author" : " Name ",
    "categories" : [ "Generic Category" ],
    "content" : "

\n
\n
\n
\n
\n
Keyword history
\n
\n
\n
\n Percentage correct\n	\n 98%\n
\n
\n Year asked\n	\n 2009\n

\n
\n
\n
\n
Suggest a change[edit]
\n
\n
Suggest a change for this keyword\n
\n
\n

\n
\n\n\n\n\n",
    "date" : "2013-05-30 02:23:04",
    "definition" : "
Very long definition section;
",
    "excerpt" : "Keyword history Percentage correct 98% Year asked 2009 Suggest a change[edit] Suggest a change for this keyword",
    "id" : 3356,
    "permalink" : "",
    "sourceLink1" : "Source",
    "title" : "Title item name"
  },
  "3356" : {
    "askedHistPercent1" : "98",
    "askedHistYear1" : "2009",
    "author" : " Name ",
    "categories" : [ "Generic Category" ],
    "content" : "

\n
\n
\n
\n
\n
Keyword history
\n
\n
\n
\n Percentage correct\n	\n 98%\n
\n
\n Year asked\n	\n 2009\n

\n
\n
\n
\n
Suggest a change[edit]
\n
\n
Suggest a change for this keyword\n
\n
\n

\n
\n\n\n\n\n",
    "date" : "2013-05-30 02:23:04",
    "definition" : "
Very long definition section;
",
    "excerpt" : "Keyword history Percentage correct 98% Year asked 2009 Suggest a change[edit] Suggest a change for this keyword",
    "id" : 3356,
    "permalink" : "",
    "sourceLink1" : "Source",
    "title" : "Title item name"
  },
}

Current direction. It's hideous, but this is getting me the frontmatter I need. Next I need to figure out how to append only the description part of the data.
const fs = require("fs");
const YAML = require("yamljs");
// const json2md = require("./json2md.js");
const bigObject = require("./data1.json");

// var showdown = require("showdown"),
//   converter = new showdown.Converter(),
//   text = "# hello, markdown!",
//   html = converter.makeHtml(text);

Object.entries(bigObject).forEach(([name, data]) => {
  fs.writeFile(`${name}.yaml`, "---\r\n", err => {
    fs.appendFile(`${name}.yaml`, YAML.stringify(data), err => {
      fs.appendFile(`${name}.yaml`, "---\r\n", err => {
        if (err) throw err;
        console.log(`${name}.yaml has been saved!`);
      });
    });
  });
});

Output of one file that I did by hand after converting using a website to markdown. It usually consists of everything being hidden in the frontmatter, while the definition tab is displayed inside of the main body
3350.md

---
title: ATitleNameHere
categories: Category1
property: 3350
id: 3350
date: 2013-05-30
author: Author Name
description: Category1
askedHistPercent1: 75
askedHistPercent2: 76
askedHistYear1: 2012
askedHistYear2: 2009
assocMediaLink1: Optional section here
assocMediaCaption1: Second Optional section here
---

Definition item here. Usually quite long.

A: const fs = require("fs");
const YAML = require("yamljs");
const bigObject = require("./1111data.json.js");
var _ = require("lodash");

Object.entries(bigObject).forEach(([name, data]) => {
  fs.writeFile(`${_.kebabCase(data.title)}.md`, "---\r\n", err => {
    fs.appendFile(
      `${_.kebabCase(data.title)}.md`,
      YAML.stringify(data),
      err => {
        fs.appendFile(`${_.kebabCase(data.title)}.md`, "\r\n---\r\n", err => {
          // fs.appendFile(`${_.kebabCase(data.title)}.md`, YAML.stringify(data.definition), err => {
          if (err) throw err;
          console.log(`${_.kebabCase(data.title)}.md has been saved!`);
          // });
        });
      }
    );
  });
});


text:
Q: In python I need to remove 1st letter I have a large dataframe as below:
df1 (sample data)
a      name       keywords
1      ramesh     rrahul,rapple
2      venkat     rtemple
3      rajesh     rcake,rphone,rmaths
4      lamda      rcon
5      feast      rcamera,rtab

I want to remove letter r which occurs at the beginning of each word in strings which consist of comma-separated words. The output should be as below:
a      name       keywords
1      ramesh     rahul,apple
2      venkat     temple
3      rajesh     cake,phone,maths
4      lamda      con
5      feast      camera,tab

A: Use nested list comprehension with join and split:
Notice:
Assuming no null/ NaNs values.
df['keywords'] = [','.join(y[1:] for y in x.split(',')) for x in df['keywords']]
print (df)
   a    name          keywords
0  1  ramesh       rahul,apple
1  2  venkat            temple
2  3  rajesh  cake,phone,maths
3  4   lamda               con
4  5   feast        camera,tab

If possible sometimes not exist first letter with r is possible a bit change solution with if-else:
print (df)
   a    name             keywords
0  1  ramesh            aa,rapple
1  2  venkat              rtemple
2  3  rajesh  rcake,rphone,rmaths
3  4   lamda                 rcon
4  5   feast         rcamera,rtab

df['keywords'] = [','.join(y[1:] if y[0] == 'r'
                                 else y
                                 for y in x.split(',')) for x in df['keywords']]
print (df)
   a    name          keywords
0  1  ramesh          aa,apple
1  2  venkat            temple
2  3  rajesh  cake,phone,maths
3  4   lamda               con
4  5   feast        camera,tab

A: Use str.replace with regex pattern as:
import re
pat = re.compile(r'^r|(?<=,)[r]')
df['keywords'] = df.keywords.str.replace(pat,'')

Or:
df['keywords'] = df.keywords.str.replace(r'^r|(?<=,)[r]','')

print(df)
   a    name          keywords
0  1  ramesh       rahul,apple
1  2  venkat            temple
2  3  rajesh  cake,phone,maths
3  4   lamda               con
4  5   feast        camera,tab

Explanation to regex :

*

*^r checks whether there is r at the start of string.

*(?<=,)[r] check whether there is r after every ,
The list comprehension method by jezrael is faster than str.replace, whereas if you have null/ NaN values then str.replace can take care of those with out hustle.

A: df["keywords"] = df["keywords"].apply(lambda x: ",".join([w[1:] if w[0] == "r" else w for w in x.split(",")]) )
df

a   name    keywords
1   ramesh  rahul,apple
2   venkat  temple
3   rajesh  cake,phone,maths
4   lamda   con
5   feast   camera,tab


text:
Q: Database table with just 1 or 2 optional fields... split into multiple tables? In a DB I'm designing, there's one fairly central table representing something that's been sold or is for sale. It distinguishes between personal sales (like eBay) and sales from a proper company. This means there is literally 1 or two fields which are not equally appropiate to both cases... for instance one field is only used in one case, another field is optional in one case but mandatory in the other.
If there were more specialty it would be sensible to have a core table and then two tables with the fields relevant to the specific cases. But here, creating two tables just to contain like one field plus the reference to the core table seems both aesthetically bad, and painful to the query designer and DB software.
What do you think? Is it ok to bend the rules slightly by having a single table with weakened constraints - meaning the DB cannot 100% prevent inconsistent data being added (in a very limited way) - or do I suck it up and create dumb-looking 1-field tables?

A: What you're describing with one table for common columns and dependent tables for subtype-specific columns is called Class Table Inheritance.  It's a perfectly good thing to do.
What @Scott Ferguson seems to be describing (two distinct tables for the two types of sales) is called Concrete Table Inheritance.  It can also be a good solution depending on your needs, but more often it just makes it harder to write query across both subtypes.
If all you need is one or two columns that apply only to a given subtype, I agree it seems like overkill to create dependent tables.  Remember that most brands of SQL database support CHECK constraints or triggers, so you can design data integrity rules into the metadata.
CREATE TABLE Sales (
 sale_id SERIAL,
 is_business INT NOT NULL, -- 1 for corporate, 0 for personal
 sku VARCHAR(20),          -- only for corporate
 paypal_id VARCHAR(20),    -- mandatory but only for personal
 CONSTRAINT CHECK (is_business = 0 AND paypal_id IS NOT NULL)
);

A: I think the choice of having these fields is not going to hurt you today and would be the choice I would go for. just remember that as your database evolves you may need to make the decision to refactor to 2 separate tables, (if you need more fields)

A: There are some who insist that inapplicable fields should never be allowed, but I think this is one of those rules that someone wrote in a book and now we're all supposed to follow it without questioning why. In the case you're describing, a single table sounds like the simple, intelligent solution.
I would certainly not create two tables. Then all the common fields would be duplicated, and all your queries would have to join or union two tables. So the real question is, One table or three. But you seem to realize that.
You didn't clarify what the additional fields are. If the presence or absence of one field implies the record type, then I sometimes use that fact as the record type indicator rather than creating a redundant type. Like, if the only difference between a "personal sale" and a "business sale" is that a business sale has a foreign key for a company filled in, then you could simply state that you define a business sale as one with a company filled in, and no ambiguity is possible. But if the situation gets even slightly more complicated, this can be a trap: I've seen applications that say if a is null and b=c d / 7 = then it's record type A, else if b is null and etc etc. If you can't do it with one test on one field, forget it and put in a record type field.
You can always enforce consistency with code or constraints.
I worry a lot more about redundant data creating consistency problems then inapplicable fields. Redundant data creates all sorts of problems. Data inapplicable to a record type? In the worst case, just ignore it. If it's a "personal sale" and somehow a company got filled in, ignore it or null it out on sight. Problem solved.

A: If there are two distinct entities, "Personal Sales" and "Company Sales", then perhaps you ought to have two tables to represent those entities?

A: News flash: the DB cannot prevent 100% of corrupt data now matter which way you cut it. So far you have only considered what I call level 1 corruption (level 0 corruption is essentially what would happen if you wrote garbage over your database with a hex editor).
I have yet to see a database that could prevent level 2 corruption (syntactically correct records but when taken as a whole mean something perverse).

A: The PRO for keeping all fields in one table is that you get rid of JOIN's which makes your queries faster.
The CONTRA is that your table grows larger which makes your queries slower.
Which one impacts you more, totally depends on your data distribution and which queries you issue most often.
In general, splitting is better for OLTP systems, joining is better for data analysis (that tends to scan the tables).
Let's imagine 2 scenarios:

*

*Split fields. There are 1,000,000 rows, the average row size is 20 bytes, the split field is filled once per 50 rows (i. e. 20,000 records in the split table).
We want to query like this:
SELECT  SUM(mainfield + COALESCE(splitfield, 0))
FROM    maintable
LEFT JOIN
        splittable
ON      splitid = mainid

This will require scanning 20,000,000 bytes and nested loops (or hash lookups) to find 10,000 records.
Each hash lookup is roughly equivalent to scanning 10 rows, so the total time will be equivalent of scanning 20,000,000 + 10 * 20,000 * 20 = 24,000,000 bytes

*Joined fields. There are 1,000,000 rows, the average row size is 24 bytes, so the query will scan 24,000,000 bytes.
As you can see, the times tie.
However, if either parameter changes (field is filled more often or more rarely, the row size is more or less, etc), one or another solution will become better.


text:
Q: ProducerTemplate is there supposed to be only one instance We are using Spring and Camel in our web application.  In one of our controllers we are using the ProducerTemplate to send a message on a route and now I want to add another controller that will send a message down a separate route.  I an trying to understand if we are only suppose to have one ProducerTemplate for the whole application?
I ask this because I got a little confused after reading this.

A: Quoted from the link you gave:

You are not meant to create a ProducerTemplate for each message invocation; you are meant to create a single instance on startup and keep it around.
Also when you have finished using the ProducerTemplate you should call the stop() method to close down all the resources it has been using.

So, in a typical Web application you would not create a ProducerTemplate for every request like:
ProducerTemplate template = camelContext.createProducerTemplate();

This is considered a bad practice, for obvious reasons.
Instead the endpoint should be injected, e.g. by using the @EndpointInject annotation
@EndpointInject(uri = "file:{{file.inbox}}")
private ProducerTemplate inbox;

as described here.

A: In general, make sure you don't create a new ProducerTemplate for each message being processed.  That being said, creating a few of them in different routes/beans/processors is fine as well...just cache them for subsequent message requests.


text:
Q: Spotfire ironPython script change values in table rows Do you have any idea how can I change values in one column using ironPython script?
I would like to take values from one column in one table (which is easy doable by cursor current value), then 'paste' those values into column in different table. Any ideas?:)


text:
Q: Changing the image in UIImageView, other XCode issues I'm really new to XCode(swift), and I'm trying to make a UIImageView randomly show one of three images, but when I switch to the second viewController in the simulator, nothing happens and XCode highlights the end of the ViewDidLoad function saying Thread 1: breakpoint 1.1.
If there's a better or more reliable way to get UIImageView to switch images, I would definitely like to know.
My current code:
import UIKit

let imageInitialIdentity = arc4random_uniform(3)

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if(imageInitialIdentity == 0){
            imageGuess.image = UIImage(named: "0ps.pngs")
            imageGuess.frame = CGRect(x: 51, y: 47, width: 500, height: 340)
        }
        if(imageInitialIdentity == 1){
            imageGuess.image = UIImage(named: "250ps.png")
            imageGuess.frame = CGRect(x: 51, y: 47, width: 500, height: 340)
        }
        if(imageInitialIdentity == 2){
            imageGuess.image = UIImage(named: "500ps.png")
            imageGuess.frame = CGRect(x: 51, y: 47, width: 500, height: 340)
        }
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.

    }

    @IBOutlet weak var imageGuess: UIImageView!

    var imageIdentity = imageInitialIdentity
    var score = 0
    let imageZero = UIImage.init(named: "0ps")
    let image250 = UIImage.init(named: "250ps")
    let image500 = UIImage.init(named: "500ps")

    @IBAction func guessZero(sender: UIButton) {

        //if zero matches the picture 0, add a point
        if imageIdentity == 0{
            score++
        }
        else{
            //print incorrect, corect answer is 0
        }

            //randomizes another picture
            let rand1 = arc4random_uniform(3)
            if rand1 == 0 {
                imageGuess.image = UIImage(named: "0ps.png")
                imageGuess.frame = CGRect(x: 51, y: 47, width: 500, height: 340)
                imageIdentity = 0
            }
            else if rand1 == 1{
                imageGuess.image = UIImage(named:"250ps.png")
                imageGuess.frame = CGRect(x: 51, y: 47, width: 500, height: 340)
                imageIdentity = 1
            }
            else if rand1 == 2{
                imageGuess.image = UIImage(named:"500ps.png")
                imageGuess.frame = CGRect(x: 51, y: 47, width: 500, height: 340)
                imageIdentity = 2
            }

    }

    @IBAction func guess250(sender: UIButton) {
        // if 150 matches the picture of 250, return true
        //randomizes another picture
        //adds one to score?
        if imageIdentity == 1{
            score++
        }

        let rand2 = arc4random_uniform(3)
        if rand2 == 0 {
            imageGuess.image = UIImage(named:"0ps.png")
            imageGuess.frame = CGRect(x: 51, y: 47, width: 500, height: 340)
            imageIdentity = 0
        }
        else if rand2 == 1{
            imageGuess.image = UIImage(named:"250ps.png")
            imageGuess.frame = CGRect(x: 51, y: 47, width: 500, height: 340)
            imageIdentity = 1

        }
        else if rand2 == 2{
            imageGuess.image = UIImage(named:"500ps.png")
            imageGuess.frame = CGRect(x: 51, y: 47, width: 500, height: 340)
            imageIdentity = 2
        }
    }

    @IBAction func guess500(sender: UIButton) {
        //if 500 matches the picture of 500, return true
        //randomizes another picture
        if imageIdentity == 2{
            score++
        }

        let rand3 = arc4random_uniform(3)
        if rand3 == 0 {
            imageGuess.image = UIImage(named:"0ps.png")
            imageGuess.frame = CGRect(x: 51, y: 47, width: 500, height: 340)
            imageIdentity = 0
        }
        else if rand3 == 1{
            imageGuess.image = UIImage(named:"250ps.png")
            imageGuess.frame = CGRect(x: 51, y: 47, width: 500, height: 340)
            imageIdentity = 1

        }
        else if rand3 == 2{
            imageGuess.image = UIImage(named:"500ps.png")
            imageGuess.frame = CGRect(x: 51, y: 47, width: 500, height: 340)
            imageIdentity = 2
        }
    }

}

A: It looks like you've set a breakpoint. Usually caused by accident when clicking to view errors. If you click the blue arrow like button it will deactivate the break point:

A: If the code is running from one ViewController to this SecondViewController, and program breaks at viewDidLoad, you might want to check how does the code finish up with its previous class and what makes it run SecondViewController class. Once you are done checking that, you might want to move your random methods out of viewDidLoad to figure out what exactly is causing the crash. something like:
override func viewDidLoad()
{
    super.viewDidLoad()
    randomMethod()
}
func randomMethod() // put a break point here if viewDidLoad passes
{
     if(imageInitialIdentity == 0){
     ..... your code ....
    }
}

A: To answer your question, "If there's a better or more reliable way to get UIImageView to switch images".
Short answer, no, that's the way it's done.
One thing you should watch out is that you have to set the image on the main thread to see change. The viewDidLoad method is certainly running on the main thread so no worries here.
If you decide to update the imageview's image at a later time, you can use GCD to properly update your UI.
dispatch_async(dispatch_get_main_queue(), ^{
    // update your UI here
});

If you need to quickly switch between two images in an imageview, you can use the highlightedImage property.
You set this property same as you did for the image property (with a different image of course).
Then, all you need to do is set the highlighted property to YES or NO.
UIImageView *iv = [UIImageView new];
UIImage *firstImage = [UIImage imageNamed:@"first_image.png"];
iv.image = firstImage;
iv.highlightedImage = [UIImage imageNamed:@"second_image.png"];
// Call below code whenever you want to switch the image, by setting the boolean.
dispatch_async(dispatch_get_main_queue(), ^{
    iv.highlighted = YES;
});

One thing that I would recommend is using the image size property for the imageview's frame.
iv.frame = CGRectMake(0, 0, firstImage.size.width, firstImage.size.height);


text:
Q: Question on category theory So I have an introductory knowledge of category theory but there is one concept I can't get my head around and would like some help:
When my class had categories defined we said a category $\mathcal{A}$ is a collection of objects (not necessarily a set) and for every two objects $A, B$ there is a set Hom($A$,$B$) that are all the morphisms (arrows) between the two objects.
I was getting along fine with this until my professor mentioned that we cannot have a category of categories. He said we could certainly look at the collection of all categories but given two categories the functors between them may not form a set thus violating our definition. So this is where my confusion is. I understand that not all collections can be sets, i.e. under general set theory we cannot have a set of all sets that don't contain themselves (Russell's Paradox). But I don't quite see what is wrong with having a set of all functors between categories.
I'm well aware that there are things called Higher categories that allow my Hom space be a category on its own right and this would allow me to form a higher category of categories or some such (I'm not very familiar with this area, but it's also not quite what I'm asking at the moment).
So if possible I would love an example (or an explanation of) two categories where the collection of functors between them cannot be a set. I spoke to my professor about it but he pretty much just said it can lead to paradoxes, but I don't see how.
Any help is appreciated, Thanks

A: The class of functors from the one object category to the category of sets (which is determined by the image of the single object) is not a set because there is no 'set of all sets'.

A: It's only possible to say that there is no 'set of sets' if you believe that Russell's paradox rules it out.
Russell's paradox disappears if you accept dialetheias. If the idea of a 'large category' being one that contains things such as a 'set of all sets' there is no real problem because the 'set of all sets' is perfectly coherent if you omit the otiose axiom of non-contradiction.
If this is what is being meant - and I'm really not sure that it is - then I'd be interested to know the implications of dialetheism for category theory.


text:
Q: In TSQL, How do I add a count column that counts the number of rows in my query? This can be done a number of ways, which I will explain at the end. For now, I have been given a work assignment that includes the following (simplified):
"Create a record each week to track the current status that has the following: account numbers (unique within each report), a random number (provided), their status (Green, Orange, or Blue), and make sure the record also has a column which tells me how many records their are this week."
I do not need code to generate a random number.
Columns: Account, RanNum, Status, NumberOfRowsThisWeek
How do I handle adding a column that determines the number of rows in my query and produces that number, static, within each row of that column?
I may try to tweak the request and apply a rising number. How would I go about doing it in this case?
Edit: SQL Server 2014

A: You are not telling us which database you are using.
In SQL Server, the newer versions at least, you have windowing function or analytical functions available, and they are also available in most other popular RDBMS
You could do what you want in SQL Server by adding this to your select
,count(*) over (partition by 1) as [NrOfRows]

An analytical function does the "standard" query, and then performs the windowing function on the result set.
The count above, counts the rows in the result set, partitioned by the constant 1, which is of course stable across all rows, so it gives the full rowcount.
It is perhaps not standard in all databases to allow a constant in that way, perhaps this would give a better result in some, I know it works in SQL Server:
,count(*) over (partition by (select 1 n)) as [NrOfRows]

A: it sounds like you want to do some kind of simple count() / group by query
select Account, RanNum, Status, count(*) as NumberOfRowsThisWeek
from tablename
group by Account, RanNum, Status

you my need to do
select Account, RanNum, Status, NumberOfRowsThisWeek
from (
   select Account, Status, count(*) as NumberOfRowsThisWeek
   from tablename
   group by Account, Status
)

because the random number will confuse the group by by making every row unique.