text:
Q: Is it possible to intercept all method class on any UIViewController subclass Let's say I wanted to be able to intercept any method calls to a UIViewController subclass.
First of all, I swizzle the +(instancetype)alloc method and I check if the current instance isKindOfClass:[UIViewController class]. If it is I go ahead and instantiate my proxy with the target.
///swizzled Alloc
+ (instancetype)monitoredAlloc {
     id obj = [self monitoredAlloc];
     if([obj isKindOfClass:[UIViewController class]]) {
        id proxy = [PMGProxy proxyWithObject:obj];
        return proxy;
     }
    return [self monitoredAlloc];
}
 ---------------------------------------
/// Proxy class
@implementation PMGProxy

+ (instancetype)proxyWithObject:(id)obj {
    PMGProxy *proxy = [self alloc];
    proxy.obj = obj;
    return proxy;
}

- (void)forwardInvocation:(NSInvocation *)invocation
{
    [invocation setTarget:_obj];
    [invocation invoke];
}

-(NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    return [self.obj methodSignatureForSelector:sel];
}

- (Class)class {
    return [self.obj class];
}

The problem is that I get crashes, so I would expect the implementation of my Proxy is wrong... What am I doing wrong?
Here is the exception:
*** Terminating app due to uncaught exception 'NSGenericException', reason: 'This coder requires that replaced objects be returned from initWithCoder:'

A: From the error it seems that the coder is only happy to accept a different class returned from initCoder: rather than earlier in the process at the alloc stage.
Might be worth looking up NSSecureCoding for more detail on the whole process.
While you're at it, take a look at the stack track that resulted in your exception, it will give you a bit more perspective on just how deep this rabbit hole goes.


text:
Q: unable to call anchor tag in html? The Search Button below does not take the control to the div tag with id resultLogBus when clicked ?
Search

<fieldset class="ui-field-contain" data-role="controlgroup">

   View Post

Bus time will be displayed here real time once you select the above filters and click search

</fieldset>

A: You need to add  before the element.  So your code will look like

Bus time will be displayed here real time once you select the above filters and click search

Here is a demo

redpajama_set_name: RedPajamaStackExchange


text:
Q: Grouping together multiple control value changes autocomplete functionality to trigger a filter function for each form control respectively.
Is there a way to group the statements instead of individually using multiple observables and separately writing them down as I did below?
this.filteredTypesCodes = this.assetTypeCodeControl.valueChanges
      .pipe(
        startWith(''),
        map(value => value.length >= 2 ? this._filter(value) : [])
      );

    this.filteredSubTypesCodes = this.assetSubTypeCodeControl.valueChanges
      .pipe(
        startWith(''),
        map(value => value.length >= 2 ? this._filter(value) : [])
      );

    this.filteredMakesCodes = this.assetMakeCodeControl.valueChanges
      .pipe(
        startWith(''),
        map(value => value.length >= 2 ? this._filter(value) : [])
      );

A: You have merge from Rxjs to merge multiple observables into one, but I don't think it will work for you, because you need each observable separately, what you can do instead, to stop repeating yourself is you can put the repeated code in a separate function, like so:
createFilter(formControl) {
      return formControl.valueChanges
      .pipe(
        startWith(''),
        map(value => value.length >= 2 ? this._filter(value) : [])
      );
}

Then you can use it to create your filters:
this.filteredTypesCodes = this.createFilter(this.assetTypeCodeControl)
this.filteredSubTypesCodes = this.createFilter(this.assetSubTypeCodeControl)
this.filteredMakesCodes = this.createFilter(this.assetMakeCodeControl)


text:
Q: Android Camera2 API Cropping Video I'm trying to record a video using Android Camera2 API. I'm trying to crop video as a square by setting the SCALER_CROP_REGION in the request builder. I'm using the following code but it doesn't seem to work
mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {

    @Override
    public void onConfigured( CameraCaptureSession cameraCaptureSession) {
        mCaptureSession = cameraCaptureSession;
        try {
            mIsRecording = true;

            /////****** this where i'm setting the coping
            mZoom = getZoomRect();
            mPreviewRequestBuilder.set(CaptureRequest.SCALER_CROP_REGION, mZoom);
            /////////******************
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
            HandlerThread thread = new HandlerThread("CameraPreview");
            thread.start();
            mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onConfigureFailed( CameraCaptureSession cameraCaptureSession) {
        Log.d(TAG, "onConfigureFailed");
    }}, mBackgroundHandler);

this is the code that should get the region to crop
public int zoom_level = 1;
public Rect mZoom = null;

public Rect getZoomRect(){
    try {
        CameraManager manager = (CameraManager) getApplicationContext().getSystemService(Context.CAMERA_SERVICE);
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraId);
        float maxzoom = (characteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM))*10;
        Rect m = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);

        int minW = (int) (m.width() / maxzoom);
        int minH = (int) (m.height() / maxzoom);
        int difW = m.width() - minW;
        int difH = m.height() - minH;
        int cropW = difW /100 *(int)zoom_level;
        int cropH = difH /100 *(int)zoom_level;
        cropW -= cropW & 3;
        cropH -= cropH & 3;
        mZoom = new Rect(cropW, cropH, m.width() - cropW, m.height() - cropH);
        ///// if recording video make it square
        if (mIsRecording) {
            mZoom = new Rect(cropW, cropH, m.width() - cropW, m.width() - cropW);
        }

    } catch (CameraAccessException e) {
        Log.e(TAG, "can not access camera",e);
        throw new RuntimeException("can not access camera.", e);
    } catch (NullPointerException ex) {
        Log.e(TAG, "touch logic",ex);
    }

    return mZoom;
}

A: Assuming zoom_level=1, and SCALER_AVAILABLE_MAX_DIGITAL_ZOOM is 4, then you end up with
minW = m.width/40
minH = m.height/40
difW = m.width*39/40
difH = m.height*39/40
cropW = m.width*39/40/100 * 1
cropH = m.height*39/40/100 * 1
(floor cropW/cropH down to nearest multiple of 4)

if m.width = 3000, m.width=2000, then cropW = 28, cropH = 16.
so mZoom for recording is
Rect(28, 16, 2972, 2972).

Which isn't centered, and many devices only support center-zoom. But it is a square region at least.
The real issue is that you can't change the aspect ratio of an output by cropping - the aspect ratio is fixed by the resolution of the output Surface when you create a capture session. See these diagrams for how the cropping works.


text:
Q: Working with moodle excellib Can anyone provide me with a working example of moodle excellib library. Currently I am unable to use it since it writes the xls file with all the html tags of current page instead of what I really want to write in it. I need to create custom tables using this library. Currently I created an experiment page in /local just to play with it. But had no luck. The code is as follows:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

 //The number of lines in front of config file determine the // hierarchy of files.
  require_once(dirname(dirname(__FILE__)).'/config.php');

  $PAGE->set_context(context_system::instance());
  $PAGE->set_pagelayout('admin');
  $PAGE->set_title("Experiment Page");
  $PAGE->set_heading("Blank page");
  $PAGE->set_url($CFG->wwwroot.'/blank_page.php');

  echo $OUTPUT->header();

  $filename = 'report_'.(time());

  $downloadfilename = clean_filename($filename);
  /// Creating a workbook
  $workbook = new MoodleExcelWorkbook("-");
  /// Sending HTTP headers
  $workbook->send($downloadfilename);
  /// Adding the worksheet
  $myxls = $workbook->add_worksheet($filename);

  $workbook->close();
  exit;

  echo $OUTPUT->footer();

A: The problem is that you are outputting the page header back to the user's browser, then starting to generate the Excel file. Remove all the $PAGE lines and (most importantly) the echo $OUTPUT->header(); line and it will work much better.


text:
Q: How to add a custom Gulp Task and a Directive in Ionic Framework I've been asked to work on a fix for our Ionic Project. I have to replace all pixel units with Rem units but I didn't want to go file by file to replace them, instead I found this wich looks like quite a solution but I have almost no idea where I should write this task and Directive
Gulp Task:
gulp.task('build:rem', ['build:sass'], function() {
    function replaceWith(match, p1, offset, string) {
        return p1 / 16 + 'rem';
    }

    return gulp.src('./www/index.html')
        .pipe(assets({js: false, css: true}))
        .pipe(tap(function(file) {
            file.contents = new Buffer(file.contents.toString().replace(/([\d.]+)\s*px/g, replaceWith));
        }))
        .pipe(gulp.dest('./www'));
});

Directive and its extension:
(function() {
    'use strict';
    angular.module('App.core')
    .directive('style', StyleDirective);

    StyleDirective.$inject = ['$timeout'];

    function StyleDirective($timeout) {
    function pxToRem(el, at) {
        if (el.attr('style')) {
        at.$set('style', el.attr('style').replace(/([\d.]+)\s*px/g, function(match, p1, offset, value) {
            return p1 / 16 + 'rem';
        }));
        }
    }

    return {
        restrict: 'A',
        compile: function(element, attr) {
            pxToRem(element, attr);
        }
    };
    }
})();

(function() {
    'use strict';
    angular.module('App.core')
    .directive('collectionRepeat', CollectionRepeatDirective);

    CollectionRepeatDirective.$inject = ['$timeout'];

    function CollectionRepeatDirective($timeout) {
    function pxToRem(el, at) {
        if (el.attr('style')) {
            $timeout(function() {
                at.$set('style', el.attr('style').replace(/([\d.]+)\s*px/g, function(match, p1, offset, value) {
                    return p1 / 16 + 'rem';
                }));
            });
        }
    }

    return {
        restrict: 'A',
        multielement: true,
        link: {
            post: function(scope, element, attr) {
                pxToRem(element, attr);
            }
        }
    };
    }
})();

So that's my question: How do you add a custom Gulp task to your Ionic Enviroment and how to add a directive and its extension.
I'm sorry if my question sounds too lame but I really haven't found an actual way how to do it
Many thanks for your time in advance

A: I am addressing the root issue of your problem i.e. you need to change the PX to rem so this can be done using the gulp-pxtorem , and at the time of building the application you can add this task and as these changes will be in css only so no need to be using of the Directive.
Sample Task
var pxtorem = require('gulp-pxtorem');

gulp.task('css', function() {
    gulp.src('css/**/*.css')
        .pipe(pxtorem())
        .pipe(gulp.dest('css'));
});


text:
Q: Using log4j logging in weblogic 9/10 In weblogic I can configure in the console for the Serverlog to use log4j instead of default JDK logging.
However the serverlog is not using a log4j.properties file, but seems to use the configuration in config.xml
Even if the log4j.properties file is in the classpath and I set these properties:
set JAVA_OPTIONS=%JAVA_OPTIONS% -Dlog4j.configuration=file:<path>/log4j.properties
set JAVA_OPTIONS=%JAVA_OPTIONS% -Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
set JAVA_OPTIONS=%JAVA_OPTIONS% -Dweblogic.log.Log4jLoggingEnabled=true

Is it possible to use log4j.properties configuration for Weblogic Server Logging, or can I only change the log4j configuration with java code?

A: I don't know anything about WebLogic in particular, but adding -Dlog4j.debug will cause log4j to tell you where it's looking for its configuration.  I've found that to be invaluable when tracking down logging issues in tomcat previously.
Check out the docs for PropertyConfigurator and DOMConfigurator for details on the log4j configuration process.

A: If you put the log4j.xml in your classpath, WebLogic will pick it up.  I use Apache Commons logging with log4j in WebLogic, and it's an easy thing to do.  No need for those Java options.

A: Where are you setting the above options? Try putting the -Dlog4j option in the Server Start options for each managed server that will use log4j

A: To specify logging to a Log4j Logger instead of the default Java Logging:
* When you start the Administration Server, include the following Java option in the weblogic.Server command:

  -Dweblogic.log.Log4jLoggingEnabled=true

From:  http://edocs.bea.com/wls/docs103/logging/config_logs.html#wp1014610

A: I never got this working as I intented.
What I eventually did was create some kind of work-around.
I register a Handler that listens to the Weblogic serverlog.
From this handler I do my own logging to log4j. That logging can be redirected to do anything I want.
create a custom logHandler:
public class CustomLogHandler extends Handler {
..

    public CustomLogHandler () throws SecurityException, IOException,
            NamingException {

        String log4jConfig = LogFilterConfiguration.getLog4jDirectory();
        classlogger.info("log4j configured for file"+ log4jConfig );
        PropertyConfigurator.configure(log4jConfig);
        logFilterConfiguration = new LogFilterConfiguration();
    }

    public void publish(LogRecord record) {
        WLLogRecord rec = (WLLogRecord) record;
        if (!isLoggable(rec))
            return;
        if (getLoggerName().. is something i want to log) {
                        // do my own log4j logging
                  }

then create an ApplicationLifecycleListener.
with a postStart method:
public void postStart(ApplicationLifecycleEvent evt) {
    Logger logger = LoggingHelper.getServerLogger();
    Handler oldHandler = null;
    Handler[] currentHandlers = logger.getHandlers();

              .. code to remove an old custom handler if exists...
    with something like logger.removeHandler(oldHandler);

    // add custom handler to serverlogger.
    CustomLogHandler h = null;
    try {
        h = new CustomLogHandler ();
        // If handler was removed we can add a new version.
        if (!(unRemovedHandlerClasses.contains(h.getClass()))){
            logger.addHandler(h);
            registerMBean(h) ;
        }
    } catch (Exception nmex) {
    classLogger.error("Error adding CustomLogHandler to serverlogger "
                + nmex.getMessage());
        logger.removeHandler(h);
    }

}


text:
Q: PHP - Check if element exists in this Array I'm retrieving a database record which is stored in a variable $record. If I do a:
echo '

'.print_r($record).'

';

I get the following:
    FileMaker_Record Object
(
    [_impl] => FileMaker_Record_Implementation Object
        (
            [_fields] => Array
                (
                    [Title] => Array
                        (
                            [0] => Alaska 24/7
                        )

                    [Status] => Array
                        (
                            [0] => Popular
                        )

                    [Author] => Array
                        (
                            [0] => Rick Smolan and David Elliot Cohen
                        )

                    [Publisher] => Array
                        (
                            [0] => DK Publishing
                        )

                    [Cover Photo Credit] => Array
                        (
                            [0] => Evan R. Steinhauser, Anchorage Daily News
                        )

                    [Description] => Array
                        (
                            [0] => The remarkable photographs showcased in Alaska 24/7 are the result of an epic project, America 24/7, which harnessed the talents of more than 25,000 photographers.
                        )

                    [Quantity in Stock] => Array
                        (
                            [0] => 50
                        )

                    [Number of Pages] => Array
                        (
                            [0] => 192
                        )

                    [Cover Image] => Array
                        (
                            [0] => /fmi/xml/cnt/AK-cover.jpg?-db=FMPHP_Sample&-lay=Form%20View&-recid=1&-field=Cover%20Image(1)
                        )

                )

            [V5e7ec2d5] => Array
                (
                )

            [_recordId] => 1
            [_modificationId] => 2
            [_layout] => FileMaker_Layout Object
                (
                    [_impl] => FileMaker_Layout_Implementation Object
                        (
                            [_fm] => FileMaker_Implementation Object
                                (
                                    [V73ee434e] => Array
                                        (
                                            [charset] => UTF-8
                                            [locale] => en
                                            [logLevel] => 3
                                            [hostspec] => 127.0.01
                                            [recordClass] => FileMaker_Record
                                            [prevalidate] =>
                                            [database] => FMPHP_Sample
                                            [username] => admin
                                            [password] => testing123
                                        )

                                    [Vea4b3413] =>
                                    [V9a3dcbce] =>
                                )

                            [_name] => Form View
                            [_fields] => Array
                                (
                                    [Title] => FileMaker_Field Object
                                        (
                                            [_impl] => FileMaker_Field_Implementation Object
                                                (
                                                    [_layout] => FileMaker_Layout Object
 *RECURSION*
                                                    [_name] => Title
                                                    [_autoEntered] =>
                                                    [_global] =>
                                                    [_maxRepeat] => 1
                                                    [_validationMask] => 0
                                                    [_validationRules] => Array
                                                        (
                                                        )

                                                    [_result] => text
                                                    [_type] => normal
                                                    [_valueList] =>
                                                    [_styleType] =>
                                                    [_maxCharacters] => 0
                                                )

                                        )

                                    [Status] => FileMaker_Field Object
                                        (
                                            [_impl] => FileMaker_Field_Implementation Object
                                                (
                                                    [_layout] => FileMaker_Layout Object
 *RECURSION*
                                                    [_name] => Status
                                                    [_autoEntered] =>
                                                    [_global] =>
                                                    [_maxRepeat] => 1
                                                    [_validationMask] => 0
                                                    [_validationRules] => Array
                                                        (
                                                        )

                                                    [_result] => text
                                                    [_type] => normal
                                                    [_valueList] =>
                                                    [_styleType] =>
                                                    [_maxCharacters] => 0
                                                )

                                        )

                                    [Author] => FileMaker_Field Object
                                        (
                                            [_impl] => FileMaker_Field_Implementation Object
                                                (
                                                    [_layout] => FileMaker_Layout Object
 *RECURSION*
                                                    [_name] => Author
                                                    [_autoEntered] =>
                                                    [_global] =>
                                                    [_maxRepeat] => 1
                                                    [_validationMask] => 0
                                                    [_validationRules] => Array
                                                        (
                                                        )

                                                    [_result] => text
                                                    [_type] => normal
                                                    [_valueList] =>
                                                    [_styleType] =>
                                                    [_maxCharacters] => 0
                                                )

                                        )

                                    [Publisher] => FileMaker_Field Object
                                        (
                                            [_impl] => FileMaker_Field_Implementation Object
                                                (
                                                    [_layout] => FileMaker_Layout Object
 *RECURSION*
                                                    [_name] => Publisher
                                                    [_autoEntered] =>
                                                    [_global] =>
                                                    [_maxRepeat] => 1
                                                    [_validationMask] => 0
                                                    [_validationRules] => Array
                                                        (
                                                        )

                                                    [_result] => text
                                                    [_type] => normal
                                                    [_valueList] =>
                                                    [_styleType] =>
                                                    [_maxCharacters] => 0
                                                )

                                        )

                                    [Cover Photo Credit] => FileMaker_Field Object
                                        (
                                            [_impl] => FileMaker_Field_Implementation Object
                                                (
                                                    [_layout] => FileMaker_Layout Object
 *RECURSION*
                                                    [_name] => Cover Photo Credit
                                                    [_autoEntered] =>
                                                    [_global] =>
                                                    [_maxRepeat] => 1
                                                    [_validationMask] => 0
                                                    [_validationRules] => Array
                                                        (
                                                        )

                                                    [_result] => text
                                                    [_type] => normal
                                                    [_valueList] =>
                                                    [_styleType] =>
                                                    [_maxCharacters] => 0
                                                )

                                        )

                                    [Description] => FileMaker_Field Object
                                        (
                                            [_impl] => FileMaker_Field_Implementation Object
                                                (
                                                    [_layout] => FileMaker_Layout Object
 *RECURSION*
                                                    [_name] => Description
                                                    [_autoEntered] =>
                                                    [_global] =>
                                                    [_maxRepeat] => 1
                                                    [_validationMask] => 0
                                                    [_validationRules] => Array
                                                        (
                                                        )

                                                    [_result] => text
                                                    [_type] => normal
                                                    [_valueList] =>
                                                    [_styleType] =>
                                                    [_maxCharacters] => 0
                                                )

                                        )

                                    [Quantity in Stock] => FileMaker_Field Object
                                        (
                                            [_impl] => FileMaker_Field_Implementation Object
                                                (
                                                    [_layout] => FileMaker_Layout Object
 *RECURSION*
                                                    [_name] => Quantity in Stock
                                                    [_autoEntered] =>
                                                    [_global] =>
                                                    [_maxRepeat] => 1
                                                    [_validationMask] => 0
                                                    [_validationRules] => Array
                                                        (
                                                        )

                                                    [_result] => number
                                                    [_type] => normal
                                                    [_valueList] =>
                                                    [_styleType] =>
                                                    [_maxCharacters] => 0
                                                )

                                        )

                                    [Number of Pages] => FileMaker_Field Object
                                        (
                                            [_impl] => FileMaker_Field_Implementation Object
                                                (
                                                    [_layout] => FileMaker_Layout Object
 *RECURSION*
                                                    [_name] => Number of Pages
                                                    [_autoEntered] =>
                                                    [_global] =>
                                                    [_maxRepeat] => 1
                                                    [_validationMask] => 0
                                                    [_validationRules] => Array
                                                        (
                                                        )

                                                    [_result] => number
                                                    [_type] => normal
                                                    [_valueList] =>
                                                    [_styleType] =>
                                                    [_maxCharacters] => 0
                                                )

                                        )

                                    [Cover Image] => FileMaker_Field Object
                                        (
                                            [_impl] => FileMaker_Field_Implementation Object
                                                (
                                                    [_layout] => FileMaker_Layout Object
 *RECURSION*
                                                    [_name] => Cover Image
                                                    [_autoEntered] =>
                                                    [_global] =>
                                                    [_maxRepeat] => 1
                                                    [_validationMask] => 0
                                                    [_validationRules] => Array
                                                        (
                                                        )

                                                    [_result] => container
                                                    [_type] => normal
                                                    [_valueList] =>
                                                    [_styleType] =>
                                                    [_maxCharacters] => 0
                                                )

                                        )

                                )

                            [_relatedSets] => Array
                                (
                                )

                            [_valueLists] => Array
                                (
                                )

                            [Vab234ad8] => Array
                                (
                                )

                            [_database] => FMPHP_Sample
                            [_extended] =>
                        )

                )

            [_fm] => FileMaker_Implementation Object
                (
                    [V73ee434e] => Array
                        (
                            [charset] => UTF-8
                            [locale] => en
                            [logLevel] => 3
                            [hostspec] => 127.0.0.1
                            [recordClass] => FileMaker_Record
                            [prevalidate] =>
                            [database] => FMPHP_Sample
                            [username] => admin
                            [password] => testing123
                        )

                    [Vea4b3413] =>
                    [V9a3dcbce] =>
                )

            [_relatedSets] => Array
                (
                )

            [_parent] =>
        )

)

I need to do some checking to see if the field I'm after exists in the list of fields returned with the $record object. For example I would like to see if the field 'Status' is contained within the  [_fields] => Array list of fields (would be true in this example).
I'm assuming I can use something like this:
if (in_array('Status', _fields)) {

but not sure of the exact syntax here and haven't been able to get this to work so far.

A: Seems like you have an embedded object called FileMaker_Record_Implementation Object. Might be worth seeing if you have access to the source code of this Class as it may provide getters/setters for the attributes within.
Or you could try directly accessing the property like this:
if(!isset($record->_impl->_fields['Status'])){
    // Status doesn't exist
}

A: You can use isset() or array_key_exists() functions for checking,
but they both are not the same.
array_key_exists() only checks if key exists even if the value is NULL.
isset() always return false if key exist and value is NULL.


text:
Q: how to pass list parameter in IN clause using jdbcTemplate I want to pass list values in IN clause using jdbcTemplate in mysql query. Like below,
 List<Long> listId= new ArrayList<>();
 listId.add(1234L);
 listId.add(1235L);
 listId.add(1236L);

 String type ="A";
 List<BojoClass> result = new ArrayList<>();
 String sql="select column1,column2  from table where columName in(?)"
 result = jdbcTemplate.query(sql, new Object[]{listId}, new BeanPropertyRowMapper<BojoClass>(BojoClass.class));

How to achieve this in best way?

A: NamedParameterJdbcTemplate may help for you.
For your sample, try this please:)
NamedParameterJdbcTemplate jdbcTemplate = ...

List<Long> listId= new ArrayList<>();
listId.add(1234L);
listId.add(1235L);
listId.add(1236L);

String sql="select column1,column2  from table where columName in(:ids)";
List<BojoClass> result = new ArrayList<>();
Map idsMap = Collections.singletonMap("ids", listId);
result = jdbcTemplate.query(sql, idsMap, ParameterizedBeanPropertyRowMapper.newInstance(BojoClass.class));

Edited:
If you can get DataSource, you can just init a NamedParameterJdbcTemplate object by its constructor like:
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource());

A: You can join your list with StringUtils.join(paramListForInClause, ","); to generate the string you need


text:
Q: Scaladoc tag for HTTP request body? I am using Play2 with Scala and I would like to write information about the body of the request in the endpoint Scaladoc.
/**
  * Replaces images for a given user.
  *
  * @param id The user id
  * @body a multipart HTTP body with the image files   <-- NO GOOD
  * @return
  */
def replaceImages(id: String) = Action.async(parse.multipartFormData) {
    ...
}

I couldn't find an appropriate tag in the Scaladoc's documentation. What would be the appropriate tag?


text:
Q: How to Convert Sql to Linq with Distinct(id) select count(distinct  LicencePlate) from MT_Vehicle where IsDeleted=0 and CreatedBy = 1

A: You can write that as:
var count = db.MT_Vehicle
    .Where( v => v.IsDeleted == 0 && v.CreatedBy == 1 )
    .Select(v => v.LicencePlate)
    .Distinct()
    .Count();

A: var count = MT_Vehicle.Where(x => x.IsDeleted==0 && x.CreatedBy == 1)
                      .Select(x => x.LicencePlate)
                      .Distinct()
                      .Count();


text:
Q: parse number as currency in opencart php first off, using Opencart 1.5.1.3
with my array of products, i've had the need to create a MAP (manufacturers advertised pricing) pricing field as well as a regular pricing field. Some manufacturers only allow me to display a minimum price they set, even if my price is lower, they must add to cart.
In order to make this work i used the "location" field in the database and just uploaded the map price to there...
by using $product['location'] (a number value) and stripping out $product['price'] to display as number value then use a series of if statements to determine what price to show.
i believe i've traced my issue to being this: since $product['location'] isn't a price, it's not being told by opencart to process the exchange rate (when switching currencies) and therefore my $product['location'] value is not changing.
i think this can be resolved by editing the following lines in category.php but i'm not sure what to put...
if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
               $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
            } else {
               $price = false;
            }

any help would be appreciated.
link: https://arkmarine.ca/instruments/autopilots

A: You will need to set the value as a float, then pass it to the $this->currency->format method. You can set the float type using the (float) typecasting before the value
$this->currency->format( (float) $variable);


text:
Q: How to add glassfish 2.x to Netbeans 7.0.1 on mac os x I have been trying to install glashfish 2.x into netbeans 7.0.1 for three days now. Needless to say, I have tried many, many things. Presently I am here: According to Netbeans.org, glassfish 2.x should be in the list of available plugins. But it's not there.
Will anyone please share their success with me? I am using mac os x.
Thanks

A: Tell me about it.  Been fighting this off and on now for a week.  Keep having to go back to 7.0.0 prior to adding the 'fixes' to plugins.  Utterly frustrating!

A: Did you guys check what you had in your netbeans update center ? I have heard people mentioning that they had URLs for 6.9 and plugins (such as GF2.0) will not show up until you modify that URL for 7.0


text:
Q: how to pass the dynamic filename in csv data set config in jmeter while the dynamic names are generated to save data of previous request? I have one http request whose response comes in nested json and using groovy i am saving that data in different csv file on the basis of conditions.
the name of csv file is generated dynamically and saved in a variable
using vars.put() function
vars.put("_cFileName",cFileName.toString());
when try to use this variable in csv data set config
enter image description here
getting error message
2022-01-19 16:58:39,370 ERROR o.a.j.t.JMeterThread: Test failed!
java.lang.IllegalArgumentException: File ${_cFileName} must exist and be readable
it is not converting the name to actual file name
But in case if file name is not dynaamic and the variable is defined under user defined variable in test plan it will able to convert to actual file name?
is there any way we can use the dynamic name created in an previos request post processor?

A: You cannot, as per JMeter Test Elements Execution Order Configuration Elements are executed before everything else, CSV Data Set Config is a Configuration Element hence it's being initialized before any JMeter Variables are being set.
The solution would be moving to __CSVRead() function, JMeter Functions are evaluated at the time they're being called so it's possible to provide dynamic file name there, see How to Pick Different CSV Files at JMeter Runtime guide for more details if needed.


text:
Q: How can i compress the MultipartFie[] size in spring boot when i deploy the spring boot project in aws elastic beanstalk.? In this service class where can i write the file compression code and am saving the file as "Base64" format in database. The single file is uploaded in s3 bucket but when i upload the MultipartFile[] using postman in aws s3 bucket am getting the "413 Request Entity Too Large" error.How can i solve this error.
This is my service class
@Component
public class TeacherGalleryService {
    @Autowired
    TeacherGalleryRepository galleryRepo;

    private AmazonS3 amazonS3;

    @Value("${aws.access.key.id}")
    private String accessKey;

    @Value("${aws.access.key.secret}")
    private String secretKey;

    @Value("${aws.region}")
    private String region;

    @Value("${aws.s3.audio.bucket}")
    private String s3Bucket;

    @Value("${aws.endpointUrl}")
    private String endpointUrl;

    @SuppressWarnings("deprecation")
    @PostConstruct
    private void initializeAmazon() {
        System.out.println(accessKey);
        AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
        this.amazonS3 = new AmazonS3Client(credentials);
    }

    public String uploadFile(MultipartFile file) {
        String fileUrl = "";
        try {
            File myFile = convertMultiPartToFile(file);
            String fileName = generateFileName(file);
            fileUrl = endpointUrl + "/" + s3Bucket + "/" + fileName;
            uploadFileTos3bucket(fileName, myFile);
            myFile.delete();
        } catch (Exception e) {
           e.printStackTrace();
        }
        return fileUrl;
    }

    private File convertMultiPartToFile(MultipartFile file) throws IOException {
        File convFile = new File(file.getOriginalFilename());
        FileOutputStream fos = new FileOutputStream(convFile);
        fos.write(file.getBytes());
        fos.close();
        return convFile;
    }

    private String generateFileName(MultipartFile multiPart) {
        return  multiPart.getOriginalFilename().replace(" ", "_");
    }

    private void uploadFileTos3bucket(String fileName, File file) {
        amazonS3.putObject(new PutObjectRequest(s3Bucket, fileName, file)
                .withCannedAcl(CannedAccessControlList.PublicRead));
    }

    public TeacherGallery storeFile(TeacherGallery teacherGallery, MultipartFile file) {
        String fileNames = StringUtils.cleanPath(file.getOriginalFilename());
        String fileUrls = endpointUrl + "/" + s3Bucket + "/" + fileNames;
        byte[] images = null;
        try {
            images = Base64.encodeBase64(file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        teacherGallery = new TeacherGallery(images, fileNames, fileUrls, teacherGallery.getTitle());
        return galleryRepo.save(teacherGallery)
}
}

A: This does seem to be low size configured in Spring's servlet container. Take a look at Web properties for your Spring Boot:
You want to look into these properties
spring.servlet.multipart.max-file-size (default 1MB)
spring.servlet.multipart.max-request-size (default 10 MB)


text: Q: Вызов метода в программе из dll Скажите пожалуйста как вызвать метод с параметрами из dll? Ну вот например : в программе есть public void writestr(string instring) который просто присваивает Label.content принятую строку instring, так вот есть dll при инициализации которого нужно сделать что-то похожее на writestr("hello from dll").


text:
Q: NLTK 3 POS_TAG throws UnicodeDecodeError Hi I am trying to learn NLTK. I am new to Python as well. I am trying the following.
>>import nltk
>>nltk.pos_tag(nltk.word_tokenize("John lived in China"))

I get the following error message

Traceback (most recent call last):   File "", line 1, in

      nltk.pos_tag(nltk.word_tokenize("John lived in California"))   File "C:\Python34\lib\site-packages\nltk\tag__init__.py", line 100,
  in pos_tag
      tagger = load(_POS_TAGGER)   File "C:\Python34\lib\site-packages\nltk\data.py", line 779, in load
      resource_val = pickle.load(opened_resource) UnicodeDecodeError: 'ascii' codec can't decode byte 0xcb in position 0: ordinal not in
  range(128)

I have downloaded all models available (including the maxent_treebank_pos_tagger)
The default system encoding is UTF-8
>>sys.getdefaultencoding()

I opened up the data.py file and this is the content available.
774# Load the resource.
775    opened_resource = _open(resource_url)
776if format == 'raw':
777            resource_val = opened_resource.read()
778        elif format == 'pickle':
779            resource_val = pickle.load(opened_resource)
780        elif format == 'json':
781            import json

What am I doing wrong here?

A: The fundamental problem is that NLTK 2.x is not supported for Python 3, and NLTK 3 is an on-going effort to release a fully Python 3-compatible version.
The simple workaround is to download the latest NLTK 3.x and use that instead.
If you want to participate in finishing the port to Python 3, you probably need a deeper understanding of the differences between Python 2 and Python 3; in particular, for this case, how the fundamental string type in Python 3 is a Unicode string (u'...'), not a byte string (Python 3 b'...') like in Python 2.  See also http://nedbatchelder.com/text/unipain.html
FWIW, see also https://github.com/nltk/nltk/issues/169#issuecomment-12778108 for a fix identical to yours. The bug you linked to has already been fixed in NLTK 3.0 (presumably by a fix to the actual data files instead; I think in 3.0a3).

A: I'm coming to this late, but in case it helps someone else who comes across this, what worked for me was to decode the text before putting it into word_tokenize, i.e.:
raw_text = "John lived in China"
to_tokenize = raw_text.decode('utf-8')
tokenized = nltk.word_tokenize(to_tokenize)
output = nltk.pos_tag(tokenized)

Maybe that'll work for someone else!

A: OK, I found the solution to it. Looks like a problem in the source itself. Check here
I opened up data.py and modified line 779 as below
resource_val = pickle.load(opened_resource) #old
resource_val = pickle.load(opened_resource, encoding='iso-8859-1') #new

A: Using Python 3.4 and NLTK 3 you can fix this by doing:
f = open('myClassifier_or_X_trained_model',mode='rb')
whereIuseTheModel = pickle.load(f,encoding='UTF-8')

Note that the mode to open is rb and encoding='uft-8'. This solution doesn't require to edit data.py.

A: I tried all the answers but nothing worked, so followed the following 2 links and then
https://github.com/nltk/nltk/issues/169
https://github.com/nltk/nltk_data/tree/gh-pages/packages/taggers

*

*downloaded the maxent_treebank_pos_tagger.zip file.

*unzipped it and copied the english.pickle file and replaced the
english.pickle files already present in my nltk_data tags folder
--> C:\nltk_data\taggers\maxent_treebank_pos_tagger with the new one.

*I also replaced the one in the folder
C:\nltk_data\taggers\maxent_treebank_pos_tagger\PY3 with the new one.

PS: I do not know what else might be affected but for now I'm ok.


text:
Q: Help with java regular expression "^[\\s]*DISPLAY.*?(\".*?\").*?\\."

I have the above regular expression. However i have a problem with it.
DISPLAY AC-YEAR LINE 2 POSITION 68 REVERSE.

This string isn't captured as it should.
DISPLAY "EATING.FOOD" LINE 13 POSITION 31 REVERSE.

This is captured successfully.
I cant figure how I should write the regular expression.
"^[\\s]*DISPLAY.*?(\".*?\")  *,?,??       .*?\\.

Putting quantifiers after the ) doesn't work. It doesn't even capture the group.

A: The regex needs a pair of quotes (") present after the DISPLAY word. That's why the first one doesn't work.
If you want the first non white space word after the DISPLAY (everything between DISPLAY and LINE this should work:
^[\\s]*DISPLAY\\s*?(\".*?\"|.*?)\\s*?LINE.*?\\.

A: The first string did not match the regex because (\".*?\") matches anything between start quot and end quot, whicxh is not in your string. I suggest you test your regex here http://www.regexplanet.com/simple/index.html

A: This should work to capture AC-YEAR and "EATING.FOOD", while matching the entire line:
^\\s*DISPLAY\\s(.*?)\\s.*\\.$

Note that the $ matches the end of the line, so the literal dot \\. will only be matched at the end.
If you want to capture everything after DISPLAY, this should do it:
^\\s*DISPLAY\\s(.*?)\\.$


text:
Q: Cannot start a neo4j cluster with 3 instances on different machines I am trying to start a neo4j cluster with 3 instances on 3 diffenrent machines, but the 3rd instance never  get started. And it works well in single instance mode.
version: neo4j-enterprise-2.2.0-M01
environment:JDK7,linux-redhat-2.6.18,64bit
The configuration is as below:
instance 1:
neo4j-server.properties:
org.neo4j.server.webserver.address=<ip:1>
org.neo4j.server.database.mode=HA
...

neo4j.properties:
online_backup_server==<ip:1>:6362
ha.initial_hosts=<ip:1>:5001,<ip:2>:5001,<ip:3>:5001
ha.cluster_server=<ip:1>:5001
ha.server=<ip:1>:6001
...

instance 2:
neo4j-server.properties:
org.neo4j.server.webserver.address=<ip:2>
org.neo4j.server.database.mode=HA
...

neo4j.properties:
online_backup_server==<ip:2>:6362
ha.initial_hosts=<ip:1>:5001,<ip:2>:5001,<ip:3>:5001
ha.cluster_server=<ip:2>:5001
ha.server=<ip:2>:6001
...

instance 3:
neo4j-server.properties:
org.neo4j.server.webserver.address=<ip:3>
org.neo4j.server.database.mode=HA
...

neo4j.properties:
online_backup_server==<ip:3>:6362
ha.initial_hosts=<ip:1>:5001,<ip:2>:5001,<ip:3>:5001
ha.cluster_server=<ip:3>:5001
ha.server=<ip:3>:6001
...

And when I started these 3 instance one by one, I got  log as below:
--------------terminal------------
WARNING: Max 8196 open files allowed, minimum of 40 000 recommended. See the Neo4j manual.
Using additional JVM arguments:  -server -XX:+DisableExplicitGC -            Dorg.neo4j.server.properties=conf/neo4j-server.properties -  Djava.util.logging.config.file=conf/logging.properties -  Dlog4j.configuration=file:conf/log4j.properties -XX:+UseConcMarkSweepGC -  XX:+CMSClassUnloadingEnabled -XX:MaxDirectMemorySize=2G -XX:-OmitStackTraceInFastThrow
Starting Neo4j Server...WARNING: not changing user
 HA instance started in process [16030]. Will be operational once connected to peers.     See /sbclocal/apps/f35/neo4j/neo4j-enterprise-2.2.0-M01/data/log/console.log for current status.

----------------console.log---------------------
2014-12-12 05:53:17.994+0000 INFO  [Cluster] Write transactions to database disabled
2014-12-12 05:53:19.399+0000 INFO  [Cluster] Attempting to join cluster of [<ip:1>:5001, <ip:2>:5001, <ip:3>:5001]

----------------neo4j.0.0.log--------------------
Dec 11, 2014 7:21:48 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.18.1 02/19/2014 03:28 AM'

For the 3rd instance, the console log just stucks at "Write transactions to database disabled", and then after 1 or 2 minutes, the instance just become down, without errors or exceptions.
And I cannot access the server by ip:7474 UI.
Could anyone give me some infomation about this please? Did I do something wrong?
Any answer is appriciated

A: Problem solved.
I found a log file in data/graph.db/message.log, and there is Port already in use exception
I really didnt know there is a message.log , I didnt find it in the neo4j documentation, I have to complain about the documentation, it is so confusing and not organized.....


text:
Q: How to loop through JSON GET result? I am laravel developer and i have no experience with jquery , i want to show editable images on dropbox file uploader please help me how can i dynamic ? thank u.
Jquery Scripts
<script>
$(document).ready(function(){

    var data = @json($roomdetails);

    var   file ="{{Config('wfh.file')}}";

    $.each(data, function(i, item) {

        {id: 1, src: 'https://picsum.photos/500/500?random=1'},
    }),

     let preloaded = [
                {id: 1, src: 'https://picsum.photos/500/500?random=1'},
                {id: 2, src: 'https://picsum.photos/500/500?random=2'},
                {id: 3, src: 'https://picsum.photos/500/500?random=3'},
                {id: 4, src: 'https://picsum.photos/500/500?random=4'},
                {id: 5, src: 'https://picsum.photos/500/500?random=5'},
                {id: 6, src: 'https://picsum.photos/500/500?random=6'},
       ];

    $('.input-images').imageUploader({
        preloaded: preloaded,
        imagesInputName: 'images',
        preloadedInputName: 'old'
    });
});
</script>

This is static images and i want to like this.
 let preloaded = [
                    {id: 1, src: 'https://picsum.photos/500/500?random=1'},
                    {id: 2, src: 'https://picsum.photos/500/500?random=2'},
                    {id: 3, src: 'https://picsum.photos/500/500?random=3'},
                    {id: 4, src: 'https://picsum.photos/500/500?random=4'},
                    {id: 5, src: 'https://picsum.photos/500/500?random=5'},
                    {id: 6, src: 'https://picsum.photos/500/500?random=6'},
           ];

A: Your question is very unclear. No way to know what you are asking. When I look at your code, I might suggest the following.
<script>
$(function(){
  var data = @json($roomdetails);
  var file ="{{Config('wfh.file')}}";
  var preload = [];

  $.each(data, function(i, item) {
    preload.push({id: item.id, src: item.src});
  });

  $('.input-images').imageUploader({
    preloaded: preloaded,
    imagesInputName: 'images',
    preloadedInputName: 'old'
  });
});
</script>

As you did not provide an example of data, I havce no way to know if this is suitable.


text:
Q: Rearranging a matrix I would like to convert a matrix which has a structure like this:
{{"A", 10, "D", 1},{"B", 3, "A", 2},{"C", 7, "B", 3},{"D", 6, "C", 4}}//MatrixForm//Print;

into one that looks like this:
{{"A", 10, "A", 2},{"B", 3, "B", 3},{"C", 7, "C", 4},{"D", 6, "D", 1}}//MatrixForm//Print;

Is there a way to do this that still works even if column 1 is not in alphabetical order?

A: Despite saying

Coloumn 3 should look like coloumn 1

it seems your rearrangement from your first list to the second is much more than that because you are moving both the third and fourth elements. In other words you are not simply making column 3 the same as column 1. So therefore you need to rearrange while keeping the 3rd and 4th elements grouped together:
list = {{"A", 10, "D", 1}, {"B", 3, "A", 2}, {"C", 7, "B", 3}, {"D",
   6, "C", 4}};
list[[All, {3, 4}]] = SortBy[list[[All, {3, 4}]], First];
list

(* {{"A", 10, "A", 2}, {"B", 3, "B", 3}, {"C", 7, "C", 4}, {"D", 6, "D",
  1}} *)

Edit
Okay let's consider a case in which column 1 is not in alphabetical order.
list = {{"D", 10, "C", 1}, {"B", 3, "A", 2}, {"C", 7, "B", 3}, {"A",
    6, "D", 4}};

Based on your example the transformed list should be
{{"D", 10, "D", 4}, {"B", 3, "B", 3}, {"C", 7, "C", 1}, {"A", 6, "A",
  2}}

...right?
In this case you collect the order of your first column and use that later:
order = Ordering[list[[All, 1]]]
(*  {4, 2, 3, 1}  *)

Then proceed as above by sorting the grouped columns 3 and 4 and then arrange that sorted list according to the order of column 1.
list[[All, {3, 4}]] = SortBy[list[[All, {3, 4}]], First][[order]];
list

(* {{"D", 10, "D", 4}, {"B", 3, "B", 3}, {"C", 7, "C", 1}, {"A", 6, "A",
  2}} *)

Alternatively the final step could be written as
list[[order, {3, 4}]] = SortBy[list[[All, {3, 4}]], First];
list

A: Starting with:
in = {{"A", 10, "D", 1}, {"B", 3, "A", 2}, {"C", 7, "B", 3}, {"D", 6, "C", 4}};

A method using GatherBy:
Join @@@ GatherBy[Join @@ Partition[in, {4, 2}][[1]], First]

{{"A", 10, "A", 2}, {"B", 3, "B", 3}, {"C", 7, "C", 4}, {"D", 6, "D", 1}}

And a method using the new-in-10 Association functionality:
Merge[{# -> #2, #3 -> #4} & @@@ in\[Transpose], # &]

Join @@@ Thread /@ List @@@ Normal[%]

<|"A" -> {10, 2}, "B" -> {3, 3}, "C" -> {7, 4}, "D" -> {6, 1}|>

{{"A", 10, "A", 2}, {"B", 3, "B", 3}, {"C", 7, "C", 4}, {"D", 6, "D", 1}}


text:
Q: mysql_fetch_array with conditions I am making a soccer site. I have the following table structure:
season1 (name of the table)
id | player1 | player2 | score

I want to put the scores into a html table. This table is only for player called nickname1 vs every other player. I have this:
$query = mysql_query("SELECT * FROM season1 WHERE player1='nickname1'") or die(mysql_error());

while($row = mysql_fetch_array( $query )) {
    echo "
";
    echo "";
    echo "	";
    echo $row['score2'];
    echo "	";
    echo $row['score3'];
    echo "	";
    echo $row['score4'];
    echo "	";
    echo $row['score5'];
    echo "
";
}
echo "

";

*

*Instead of $row['score2'] I need the score between nickname1 vs
nickname2

*Instead of $row['score3'] I need the score between    nickname1 vs
nickname3

*Instead of $row['score4'] I need the score    between nickname1 vs
nickname4

*Instead of $row['score5'] I need the    score between nickname1 vs
nickname5

I tried SELECT * FROM season1 WHERE player1='nickname1' AND player2='nickname2' but then it will show only player1 vs player2 in the table. I want to show all 4 players vs player1 in the same table.

A: You need to focus your loop only on making one row:
echo "

";
while($row = mysql_fetch_array( $query )) {
    echo "{$row['score']}	";
}
echo "

";

This will ONLY output the scores of the players. You can modify it to have nickname headers and so forth.
Take note that the $row array resembles your table structure. $row['score'] will give you the scores of the players where as since score1 is not a column in the table, it does not exist in $row.
Possible design:
echo "

Player 1	Player 2	Score

";
while($row = mysql_fetch_array( $query )) {
    echo "{$row['player1']}	";
    echo "{$row['player2']}	";
    echo "{$row['score']}	";
}
echo "

";

will output (depending on ID's in database)
Player 1  |  Player 2 |  Score
   p1           p2         0
   p1           p3         0

NOTICE: MySQL_* has been deprecated in PHP 5.5. Use MySQLi or PDO instead

A: Assuming score1 it's player 1 score:
$query = mysql_query("SELECT * FROM season1 WHERE player1='nickname1'") or die(mysql_error());

while($row = mysql_fetch_array( $query )) {
echo "
";
echo "";
echo "	";
echo $row['player1']." vs ".$row['player2'].", with a score of: ".$row['score'];
echo "
";
}
echo "

";

I hope it helps.
Saludos ;)


text:
Q: How to convert the UTC time into the device time in android when using GPS? Hi All please any one can tell how to convert the UTC time into the android device current time....
Actually when we are using the GPS service in mobile I am displaying lat,lon,altitude and  time
Here the time is coming in format of UTC milliseconds I want to convert that time into the device current time

A: Try this code
String dat = new SimpleDateFormat("ddMMyy").format(location.getTime())

A: Date d = new Date(System.currentTimeMillis());
d.toLocaleString(); //to phone's locale
d.toGMTString(); //in GMT


text:
Q: Display current time globally with Ruby on Rails I want to display the current time (of the server) with Time.now on all sites (different controllers).
Since the global displaying of headers/navigation bars and so on can be done within layout>application.html.erb I changed it to the following:
<!DOCTYPE html>

  <title>Depot</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>

<body class='<%= controller.controller_name %>'>

  <%= link_to 'Store', controller: 'store', action:'index' %>
  <%= link_to 'Products', controller: 'products', action: 'index' %>
  Current time: <%= @time %>

<%= yield %>

Now I further hoped to possibly add the code to get the current time within the application_controller.rb.
Here's the code I have in there
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  @time = Time.now
end

Unfortunately that's not working and I have to add the @time = Time.now - code within the controller (and method) I am using. This means I'd have to fill the code in several times and isn't that against the rails - idea?
I'd appreciate any help :)

A: In application controller
before_action :set_time

def set_time
  @time = Time.now
end

Now you have @time available everywhere and always.


text:
Q: Transfer learning for regression problems I have trained a regression model with 7 features for a given problem.
Now, I have another regression problem (quite similar to the previous one) where I have only 6 samples in hand, but with 3 more features than the first model (7+3). The correlation between the target value and these 3 additional features is very high.
So I would like to use transfer learning method to create a new model based on the old model; but I can not find a way to integrate the additional features into the model, since the old one was trained only on X features. On the other hand I must employ the 3 additional features in the new model which means that I cannot just remove or ignore them.
Thanks.

A: One way: Use your old model's prediction as a new feature and combine with the additional three you have, i.e. a four-length feature vector for each sample. Then, train with these new features. So, the old model will act like a static feature generator for you. Of course, you may have challenges with that low number of samples.


text:
Q: How do I add a missing word to a pretrained embedding? I have a pretrained word embedding and want to add missing words to it. How exactly should I do that?
I think to just randomly initialize the vector is not a good idea.
I heard something about calculating the average - but how do I exactly do that? The average of what exactly?

A: You might consider "a la carte" word embeddings. Essentially, the word vector of any new word  can be derived from the average vector of the other words appearing alongside it, as you suggest. However, note that the "derived" word vector is not simply the average, but rather a linear transformation of the average.
That is, if the embedding for the new word is $v_{w}$ and the average is
$$ u_{w} = \alpha \sum_{\mathrm{sentences \ s \ containing \ w} \\ \mathrm{words \ w' \ in \ s}} v_{w'}$$
with $\alpha$ the appropriate normalizing constant, then we have
$$ v_{w} = A u_{w}$$
where $A$ is a matrix that is determined uniquely by the corpus itself. In particular, $A$ can be determined by linear regression (we have known pairs $v_{w}$, $u_{w}$ for all of the words already in the embedding).
To be clear, I have not used "a la carte" embeddings before, so I don't know how well it works in practice.
Fun fact: the official publication date of the linked paper is roughly one week before this question was posted.


text:
Q: Laravel Eloquent How to apply condition on "with" datas on the output? here my code :
$prestations = Prestation::with(
            [
            'service' => function($service) use($searchService) {
                $service->select(['id','name'])->where('name', 'regexp', "/$searchService/i");
            },
            'facility' => function($facility) use($searchPartenaire) {
                $facility->select(['id','name'])->where('name', 'regexp', "/$searchPartenaire/i");
            }
            ]
        )
            ->where('name', 'regexp', "/$search/i")
            ->orderBy($orderBy, $orderDirection)
            ->simplePaginate(50);

        $res = [
            'results' => $prestations,
            'total' => Prestation::all()->count(),
        ];

The problem is that in the output of all datas where "service" and "facility" names are not equal on the $searchService and $searchPartenaire the values are replaced by "null".
So i don't want to have values in the output where the search variables are not equals.
Thank you.

A: you can try like this
 $prestations = Prestation::with('service','facility');

        $prestations->whereHas('service', function ($query) use ($searchPartenaire) {
            $query->Where('name', 'like', '%' . $searchPartenaire . '%');
        });

        $prestations->whereHas('facility', function ($query) use ($searchPartenaire) {
            $query->Where('name', 'like', '%' . $searchPartenaire . '%');
        });

        $prestations->where('name', 'like', '%'.$search.'%')
            ->orderBy($orderBy, $orderDirection)
            ->simplePaginate(50);

        return $res = [
            'results' => $prestations,
            'total' => Prestation::all()->count(),
        ];

1st create instances of Prestation $prestations = Prestation::with('service','facility')
then apply the condtion this is good approach in seach

A: Here my code after Kamlesh Paul suggestion :
$prestations = Prestation::with('service','facility');

        $prestations->whereHas('service', function ($query) use ($searchService) {
            $query->where('name', 'regexp', "/$searchService/i");
        });

        $prestations->whereHas('facility', function ($query) use ($searchPartenaire) {
            $query->where('name', 'regexp', "/$searchPartenaire/i");
        });

        $prestations->where('name', 'regexp', "/$search/i")
            ->orderBy($orderBy, $orderDirection)
            ->simplePaginate(50);

        $res = [
            'results' => $prestations,
            'total' => Prestation::all()->count(),
        ];

        return $res;

But there is an infinite calls of http request, i think that the problem is when the where don't find an equal name, anyone have a suggest ?
Thank's.

A: I finnaly found a solution very similar :
$prestations = Prestation::with('service','facility')
            ->whereHas('service', function ($query) use ($searchService) {
            $query->where('name', 'regexp', "/$searchService/i");
            })
            ->whereHas('facility', function ($query) use ($searchPartenaire) {
                $query->where('name', 'regexp', "/$searchPartenaire/i");
            })
                ->where('name', 'regexp', "/$search/i")
                ->orderBy($orderBy, $orderDirection)
                ->simplePaginate(50);

        $res = [
            'results' => $prestations,
            'total' => Prestation::all()->count(),
        ];

Thank's for your help.


text:
Q: Java Shut the Box Im writing a program similar to a game called shut the box. The game asks the player to roll 2 die, and then the player chooses to cover both numbers individually (in the boolean array), or the total of the two.
I'm having difficulty returning two values of the int method roll() which is supposed to roll two die.
Heres my code for the main class:
public class clacker {

    private int play;
    private int die1;
    private int die2;
    private boolean[] table;
    private final int high = 6;
    private final int low = 1;
    private int range;

    public clacker()
    {
        range = high-low+1;
        table = new boolean[13];
        play = 0;
    }

    public void roll()
    {
        die1 = (int)(Math.random()*range+low);
        die2 = (int)(Math.random()*range+low);

    }

    public void value(char ch)
    {
        if(ch == 'i' || ch == 'I')
        {
            table[die1] = true;
            table[die2] = true;
            displayBoard();
        }
        else if(ch == 'T' || ch == 't')
        {
            table[die1+die2] = true;
            displayBoard();

        }
        else
        {
            roll();
        }
    }

    public void displayBoard()
    {
        for(int i = 1; i<table.length; i++)
        {
            if(table[i] == false)
            {
                System.out.print("   " + i + "   ");
            }
            else
            {
                System.out.print("   /   ");
            }
        }
    }
}

and for the test class:
public class clackerTest {

    public static void main(String[] args) {
        clacker oo = new clacker();

        EasyReader kboard = new EasyReader();
        System.out.println("Press anything to roll the dice. ");
        char roll= kboard.readChar();

        int dice1 = oo.roll();
        int dice2 = oo.roll();
        System.out.println("You rolled " + dice1 + " and a " + dice2 + "!");

        System.out.println("Cover Individual or Total: (enter i or t)");
        char roll2 = kboard.readChar();
    }
}

A: Why don't you just roll() twice? Modify roll() to return one int.
public int roll() {
  return (int)(Math.random()*range+low);
}

And now, from within clackerTest (java conventions dictates you name this ClackerTest):
int dice1 = oo.roll();
int dice2 = oo.roll();


text:
Q: flutter firebase_admob integration - how to use it along with app flavors I have my flutter app setup to use flavors for different releases e.g. development, production and etc. The essential part of this lays into app/build.gradle file and looks like that:
    flavorDimensions "flutter-flavours"

    productFlavors {
        development {
            dimension "flutter-flavours"
            applicationIdSuffix ".dev"
        }
        staging {
            dimension "flutter-flavours"
            applicationIdSuffix ".stg"
        }
        production {
            dimension "flutter-flavours"
        }

As a result, when I build let's say development release, I have got it with following appId - com.example.myapp.dev, while my production release is com.example.myapp. So far so good.
Now, I decided to add a firebase_admob plugin to the app. To do so, I made Firebase app into my Firebase account and downloaded corresponding google-services.json file required for authentication. Then, I have to put this file into an android/app folder of my app.
And this is where I found a bummer - basically, I can create json file for each of the app flavor, i.e. I can have one json for production and one for development, but I cannot figure out how to put these both into the folder and how gradle will figure out which one to take according to the release flavor.
Any thoughts, hints would be greatly appreciated!

A: I use google_mobile_ads plugin with flavors. Here's how I set up for different flavors:
in my android/app/build.gradle, I simply add resValue named ads_id
    productFlavors{
    ss {
        dimension "flavor-type"
        applicationId "com.company.ss"
        resValue "string", "app_name", "ss"
        resValue "string", "ads_id", "ca-app-pub-xxx~yy"
        versionNameSuffix "-ss"
        signingConfig signingConfigs.ss
    }
    rk {
        dimension "flavor-type"
        applicationId "com.company.rk"
        resValue "string", "app_name", "rk"
        resValue "string", "ads_id", "ca-app-pub-xxx~yy"
        versionNameSuffix "-rk"
        signingConfig signingConfigs.rk
    }
    ns {
        dimension "flavor-type"
        applicationId "com.company.ns"
        resValue "string", "app_name", "ns"
        resValue "string", "ads_id", "ca-app-pub-xxxx~yyy"
        versionNameSuffix "-ns"
        signingConfig signingConfigs.ns
    }
}

and then grab this value inside AndroidManifest.xml
 <application
    android:name="io.flutter.app.FlutterApplication"
    android:label="@string/app_name"
    android:usesCleartextTraffic="true"
    android:icon="@mipmap/launcher_icon">
    <meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="@string/ads_id"/>
    <activity
..


text:
Q: Interaction between xml file and python script in Ansible Currently, I have a playbook that creates an .xml file and a python script which takes in the .xml file and processes it. I intend to use use j2 templating to create the file in the form of {{ ansible_date_time.iso8601_basic_short }}.xml so that I can keep track of the new files. However right now the playbook is really static as the path is hard coded in the shell command and the python script.
Any suggestions?
---
- name: testing
  hosts: localhost
  tasks:
    - name: execute some shell command that produces an xml output file in current dir
      shell: XXX

    - name: Takes in xml output file produced earlier and passes into script.py
      script: python_script.py

A: If I understand what you're asking, Why not using a shell script that prints on the stdout the XML content, so that you can register it in a variable and use it after with variable.stdout?
Like:
- name: generate xml
  shell:
    echo '<xml></xml>'
  register: myxml

- name: create xml file
  copy:
    content: "{{ myxml.stdout }}"
    dest: "{{ ansible_date_time.iso8601_basic_short }}.xml"


text:
Q: Preventing the Words while Chatter Post Can you find me an alternative Appexchange APP for Chatter Blacklist. I got the issue while installing in Production.
FYI, I have installed Chatter Blacklist. but it was failed. I just want to prevent the words while posting in Chatter post.

A: It can be possible and I have the custom package. Are you interested?


text:
Q: Basic SQL Server Administration We just recently moved an internal database from access to SQL Server Express 2008.  Other then taking backups and applying patches are there basic administration tasks that I should be doing?

A: *

*Keep an eye on disk space.

*Related - don't have your data and log files on the same partition as each other or the OS.

*If you're running in Recovery Mode = Full, you also need to do transaction log backups.

*There's a lot of performance analysis that you can do, if you need to. You might not need to.

A: google "sql server administration for beginners"
also, have a look here for books to read BrentO

A: The pdfs from redgate are pretty good - lots of things you can look at.
Your three main things to look after are...
1.Backups
2.Recovery
3.Security
Test a backup to another database name and make sure it works for you.  Make sure you are notified when the backups fail.
You'll want to do periodic maintenance on the indexes too.  I prefer this script -  http://ola.hallengren.com/
This type of stuff is a bit of a pain in sql express since there is no agent to run jobs.  You'll need to use the windows task scheduler or another tool to schedule .bat's to run.


text:
Q: What should a Socket Thread class do public class SOCKET_SERVER {

    private JmailHelp JmailHELPER = new JmailHelp();
    static int PORT = 444;

    public static void main(String[] args) throws Exception {

        SOCKET_SERVER SERVER = new SOCKET_SERVER();
        SERVER.JmailHELPER.resetONN();
        ServerSocket SRVSOCK = new ServerSocket(PORT);
        //ArrayList<SocketStatus> OnlineUsers = new ArrayList<SocketStatus>();

        Socket SOCK = SRVSOCK.accept();
        //new ServerThread(SOCK).start();
        SocketStatus a = new SocketStatus(SOCK, false);
        //OnlineUsers.add(a);
        //String action = "";
        SERVER.ServerActionsHandler(SERVER, SRVSOCK, SOCK, a);

    }//
}

forgive me if what i am giving is not enough don't hesitate to ask more if you can and want to try to help me
Well,
this is my socket server class ServerActionHandler is a method i created that takes as "input"(by BufferedReader) from the client a string and calls the right methods to serve the client.
for example he wants to login:

*

*he(client) sends the string "login"

*then server takes it as an "input" by the ServerActionHandler in a string called action, then recognise the the "login" and then calls the Acceptlogin method from the server class

*Meanwhile client who send the "logi message" is calling the Dologin method from the client class
4.a loop of the ServerActionsHandler ends
5.A new loop starts asking the new action from the Client
my project works for A server and One client
I want to make it working for many clients
also something more I use JmailHELPER object
in almost all the methods of SOCKET_SERVER class(eg. login_accept,register_accept...)
in order to call some methods of it's class.
And SocketStatus keeps one variable if the certain socket which uses the Server is logged in or not
from what I know i have to make a ServerThreads class that extends Threads to handle more than one users.
What is the constructor and the run of that classmethod supposed to do
for example of A SocketThread I have this http://www.cdk5.net/ipc/programCode/TCPServer.java
thanks.

A: ok,
I know its funny but after a break of two hours I tried to find the solution for 3 minutes and i solved it(thats what i believe for now :P )
At least it is working on my pc for two clients so I will check it tommorow in more than one pc
Anyway I am posting the answer to my problem so that you can see it if you have a common problem
public static void main(String[] args) throws Exception {
    SOCKET_SERVER SERVER = new SOCKET_SERVER();
    SERVER.JmailHELPER.resetONN();
    ServerSocket SRVSOCK = new ServerSocket(PORT);

    while (true) {
        Socket SOCK = SRVSOCK.accept();
        SocketStatus a = new SocketStatus(SOCK, false);
        new Thread() {
            public void run() {
                try {
                    SERVER.ServerActionsHandler(SERVER, SRVSOCK, SOCK, a);
                } catch (Exception ex) {
                    Logger.getLogger(SOCKET_SERVER.class.getName()).log(Level.SEVERE, null, ex);
                };
            }
        }.start();
    }
}


text:
Q: No downtime upgrade Elasticache from Redis 2.6 to 2.8 I'm trying to determine whether updating my Elasticache cluster to use Redis 2.8 instead of 2.6 will cause Elasticache downtime. Ideally the upgrade would occur during the cluster's scheduled downtime, but I can't seem to find any documentation on what will happen when I tell the cluster to upgrade.
Has anyone gone through this yet?

A: Yes, we have done an upgrade to our redis elasticache. We made a snapshot of the current cache then spawned a new instance from the created snapshot. We pointed the servers to use the new cache then proceeded with the upgrade on the old cache. It did not take some time and the data was still intact but I cannot guarantee it because it was stated in the prompt before the upgrade that the data might be lost during the upgrade.


text:
Q: Action Cable issue: messages occasionally not delivering or occasionally sent to the wrong channel I'm using Action Cable for a chat application with many different channels.  Everything is set up with Redis and Postgresql (to save messages) on Heroku and 95% of the time works great in development and production.
Occasionally though, messages sent do not show up.  The message is sent, it is saved in the database, but then it never shows up on the front end unless I refresh.  Or, the message shows up in another channel for which it is not directed.  Again, everything is properly saved in the Postgres database.  It just gets wonky on the front end.  Somewhere the ActionCable seems to get confused.
This issue happens so rarely for me, that it is very difficult to replicate to debug properly.  But I have a bunch of users that are regularly reporting the issue and I'm struggling to figure out how to track it down.
Here is some of my code:
javascripts/channels/channels.js
class PodsChannel < ApplicationCable::Channel
  def subscribed
    stream_from "pods_channel_#{params['pod_slug']}"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

  def speak(data)
    #after_create_commit callback fires to create a job to broadcast message
    pod_message = PodMessage.create! pod_slug: data['pod_slug'], message_body: data['message'], user_id: data['user_id'], message_type: data['msg_type']
  end
end

channels/pods_channel.rb
$(document).on("ready",function(){
  var pod_slug = $("#pod_slug_value").val();

  // hack to prevent double posting of messages
  if (!App.pods || JSON.parse(App.pods.identifier).pod_slug != pod_slug){
    App.pods = App.cable.subscriptions.create(
      { channel: 'PodsChannel', pod_slug: pod_slug },
      {
      received: function(data) {
        if ( ($(".chat-stream").length) && data.pod_slug == pod_slug ){ // hack to prevent msgs going accross pods
          //#CLEAN: this is a super hackish way of preventing double messages
          if(!$("#msg_" + data.msg_id).length){
            $(data.message).appendTo($(".chat-stream")).find('.msg-text a').attr('target', '_blank');
            $("#msg_" + data.msg_id + " .msg-text").html(Autolinker.link($("#msg_" + data.msg_id + " .msg-text").html(), { mention: "sutra" }));
            $(".chat-stream").scrollTop($(".chat-stream")[0].scrollHeight);
          }
        }
      },

      speak: function(message, pod_slug, user_id, msg_type) {
        return this.perform('speak',{
          message: message,
          pod_slug: pod_slug,
          user_id: user_id,
          msg_type: msg_type,
        });
      }
    });
  };

  if ( $(".chat-stream").length ) {
    $(".chat-stream").scrollTop($(".chat-stream")[0].scrollHeight);
  };

  captureMessage();
});

function captureMessage(){

  $(document).on('click', "#btn-submit-msg", {}, function(){
    var raw_text = $("#msg-input-text").val();
    if (raw_text != ""){
      submitMessage(raw_text, "pod_message");
    }
  });

  $(document).on('keydown', '#msg-input-text', {}, function(event) {
    if (event.which == 13 && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
        event.preventDefault();
        event.stopPropagation();
        if (event.target.value != "") {
          submitMessage(event.target.value, "pod_message")
        }
    }
    });
}

function submitMessage(raw_text, msg_type){
  var message = raw_text;
  var pod_slug = $("#pod_slug_value").val();
  var user_id = $("#current_user_id_value").val();
  var msg_type = msg_type;
  if (App.pods.consumer.connection.disconnected == false) {
    App.pods.speak(message, pod_slug, user_id, msg_type);
    if (msg_type != "attachment") {
      $("#msg-input-text").val("");
    }
  }
}

models/pod_message.rb
class PodMessage < ApplicationRecord
    after_create_commit { MessageBroadcastJob.perform_now self }
end

jobs/message_broadcast_job.rb
class MessageBroadcastJob < ApplicationJob
  queue_as :default

  def perform(pod_message)
    stream_id = "pods_channel_#{pod_message.pod_slug}"
    ActionCable.server.broadcast stream_id, message: render_message(pod_message), msg_id: pod_message.id, pod_slug: pod_message.pod_slug
  end

  private
    def render_message(pod_message)
      renderer = ApplicationController.renderer.new
      renderer.render(partial: 'pod_messages/pod_message', locals: { pod_message: pod_message })
    end
end


text:
Q: Serverless offline - Migration on local dynamoDb is not working I'm working in a Serverless project and I'm having issues to run locally my application with dynamodb. It is not creating a data table thus not executing correctly the seed. What is wrong with my configurations?
start command: $ sls offline start --stage dev
error message:
Serverless: Bundling with Webpack...
Serverless: Watching for changes...
Dynamodb Local Started, Visit: http://localhost:8000/shell

  Resource Not Found Exception ---------------------------

  ResourceNotFoundException: Cannot do operations on a non-existent table
      at Request.extractError (/home/mauricio/dev/project/covid-favor-api/node_modules/aws-sdk/lib/protocol/json.js:51:27)
      at Request.callListeners (/home/mauricio/dev/project/covid-favor-api/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
      at Request.emit (/home/mauricio/dev/project/covid-favor-api/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
      at Request.emit (/home/mauricio/dev/project/covid-favor-api/node_modules/aws-sdk/lib/request.js:683:14)
      at endReadableNT (_stream_readable.js:1183:12)
      at processTicksAndRejections (internal/process/task_queues.js:80:21)

     For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.

  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
     Issues:        forum.serverless.com

  Your Environment Information ---------------------------
     Operating System:          linux
     Node Version:              12.13.0
     Framework Version:         1.64.0
     Plugin Version:            3.4.0
     SDK Version:               2.3.0
     Components Core Version:   1.1.2
     Components CLI Version:    1.4.0

Serverless file:
org: mauriciocoder
app: covid-favor
# We are using JEST for testing: https://jestjs.io/docs/en/getting-started.html - npm test
service: covid-favor-app-api

# Create an optimized package for our functions
package:
  individually: true

# Create our resources with separate CloudFormation templates
resources:
  # API Gateway Handler
  - ${file(resources/api-gateway-handler.yml)}
  # DynamoDb Handler
  - ${file(resources/dynamodb-handler.yml)}

plugins:
  - serverless-bundle # Package our functions with Webpack
  - serverless-dynamodb-local
  - serverless-offline
  - serverless-dotenv-plugin # Load .env as environment variables

custom:
  authorizer:
    dev:
    prod: aws_iam
  dynamodb:
    stages: dev
    start:
      port: 8000 # always se port 8000, otherwise serverless-dynamodb-client will not find
      migrate: true # creates tables from serverless config
      seed: true # determines which data to onload
    seed:
      domain:
        sources:
          - table: userAccount
            sources: [./resources/migrations/v0.json]

provider:
  name: aws
  runtime: nodejs10.x
  stage: ${opt:stage, 'dev'}
  region: us-east-1

  # These environment variables are made available to our functions
  # under process.env.
  environment:
    helpTableName: help
    userAccountTableName: userAccount

  # 'iamRoleStatements' defines the permission policy for the Lambda function.
  # In this case Lambda functions are granted with permissions to access DynamoDB.
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:DescribeTable
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:us-east-1:*:*"

  # These are the usage plan for throttling
  usagePlan:
    throttle:
        burstLimit: 2
        rateLimit: 1

functions: ...

dynamodb-handler file:
userAccount:
  Type: AWS::DynamoDB::Table
  DeletionPolicy : Retain
  Properties:
    TableName: userAccount
    AttributeDefinitions:
      - AttributeName: userId
        AttributeType: S
    KeySchema:
      - AttributeName: userId
        KeyType: HASH
    ProvisionedThroughput:
      ReadCapacityUnits: 1
      WriteCapacityUnits: 1

seed file v0.json:
{
    "Table": {
        "TableName": "userAccount",
        "KeySchema": [
            {
                "AttributeName": "userId",
                "KeyType": "S"
            }
        ],
        "LocalSecondaryIndexes": [
            {
                "IndexName": "local_index_1",
                "KeySchema": [
                    {
                        "AttributeName": "userId",
                        "KeyType": "HASH"
                    }
                ]
            }
        ],
        "ProvisionedThroughput": {
            "ReadCapacityUnits": 1,
            "WriteCapacityUnits": 1
        }
    }
}

package.json
{
  "name": "notes-app-api",
  "version": "1.1.0",
  "description": "A Node.js starter for the Serverless Framework with async/await and unit test support",
  "main": "handler.js",
  "scripts": {
    "test": "serverless-bundle test"
  },
  "author": "",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "https://github.com/AnomalyInnovations/serverless-nodejs-starter.git"
  },
  "devDependencies": {
    "aws-sdk": "^2.622.0",
    "jest": "^25.1.0",
    "serverless-bundle": "^1.2.5",
    "serverless-dotenv-plugin": "^2.1.1",
    "serverless-offline": "^5.3.3"
  },
  "dependencies": {
    "serverless-dynamodb-client": "0.0.2",
    "serverless-dynamodb-local": "^0.2.35",
    "stripe": "^8.20.0",
    "uuid": "^3.4.0"
  }
}

A: I think you are missing the migration block, where you specify your migration file. put this under your dynamodb: key
migration:
  dir: resources/migrations/v0.json

A: The error message is explaining where your issue is - the dynamodb-handler.yml file is missing the key, Resources. In the serverless-dynamodb-local docs, you can see the redundant resources & Resources keys. So your dynamodb-handler.yml should begin like this:
Resources:
  userAccount:
    Type: AWS::DynamoDB::Table

Note that all other external resources must begin with the same key, i.e. api-gateway-handler.yml in your example.
Additionally, if you're having difficulty creating the table when starting serverless offline, or you're using a persistent docker dynamodb instead, migrate with the following command:
npx serverless dynamodb migrate


text:
Q: Yarn global install of private module I am trying to install a module globally with yarn.
I typed the following command:
yarn global add react-native-rename

and then I find it in the yarn global directory, and I am able to call it directly since the directory is included in the path.
But if I try to do the same thing with the same cloned repository hosted on my gitlab:
yarn global add git+ssh://git@git.company.info:mobile/react-native-rename.git

the installation goes fine but the binary is not present into the folder.
yarn global list

shows the binaries as installed but I am unable to find it, neither looking for it using which react-native-rename.
Any idea?

A: Could you try adding this to your .bashrc or .zshrc?
export PATH="$(yarn global bin):$PATH"

Yarn Global docs
https://classic.yarnpkg.com/en/docs/cli/global/
FYI: Locations on my mac

*

*Executable: /usr/local/bin

*Location of downloaded code: ~/.config/yarn/global/node_modules
Could you check these two directories?


text:
Q: How to choose contour for rational approximation Let $f$ be an analytic function on $\Omega \subset \mathbb{C}$. The Hermite formula for interpolation at the points $a_k$, $k=1,\ldots,n$, using a rational function $r_n$ with poles at $b_k$, $k=1,\ldots,n$,
$$
        f(z) - r_n(z)
        =
        \frac{1}{2\pi i} \oint_{\partial \Omega} \frac{\ell_n(z)}{\ell_n(w)} \, \frac{f(w)}{w-z} \, dw
, \qquad
\ell_n(z) = \frac{\prod_{k = 1}^n (z-a_k)}{\prod_{k=1}^n (z-b_k)}
,
$$
allows to estimate the interpolation error on a compact set $A\subset\Omega$ by
$$
        \|f - r_n\|_{\infty,A}
        \leq
        \|f\|_{\infty,A} \, \frac{\sup_{z \in A} |\ell_n(z)|}{\inf_{w \in \partial\Omega} |\ell_n(w)|}
.
$$
We can then use logarithmic potential theory to find $a_k$ and $b_k$ which asymptotically minimise this expression, see e.g. chapter VIII in Saff & Totik "Logarithmic Potentials with External Fields". Thus, there is a complete theory on how to do asymptotically optimal rational interpolation except that I have to a-priori choose the domain of analyticity $\Omega$ or equivalently the contour $\partial \Omega$. Are there any guidelines/theory on how to do this?

A: If the points $\{a_{k}\}_{k=1}^{n}\subset A$ and $\{b_{k}\}_{k=1}^{n}\subset\mathbb C\setminus\Omega$ are chosen as rational Fekete points (see p.396 of the reference mentioned by the OP), then it can be proved (see p.397) that
$$\limsup_{n\infty}\left(\frac{\sup_{z\in A}|l(z)|}{\inf_{z\in\mathbb C\setminus\Omega}|l(z)|}\right)^{1/n}\leq e^{-1/\text{cap}(A,\mathbb C\setminus\Omega)},$$
where $\text{cap}(A,\mathbb C\setminus\Omega)$ denotes the capacity of the condenser made of the two plates $A$ and $\mathbb C\setminus\Omega$, which is defined as the inverse of
$$\inf_{\mu_{1},\mu_{2}}\iint\log\frac{1}{|z-t|}d(\mu_{1}-\mu_{2})(z)d(\mu_{1}-\mu_{2})(t),$$
where $\mu_{1}$ and $\mu_{2}$ are probability measures supported on $A$ and
$\mathbb C\setminus\Omega$ respectively. Note that if one of the sets becomes smaller, the infimum increases and the capacity decreases.
In order to optimize the rate of approximation, one thus has to minimize the capacity, or equivalently to choose $\Omega$ as large as possible. Hence the best rate of approximation is achieved when choosing $\Omega$ as the (maximal) domain of analyticity of the function $f$ and the contour as the boundary of this domain.

To answer the question in the comment about rational approximation to the function $1/(1+\exp(x))$ on the interval $[-1,1]$, here are the plots of the error functions of best (minimax) rational approximants of degrees 3 and 5, as computed by the Remez command of the Chebfun package.


text:
Q: Could not open JDBC Connection for transaction in Spring Junits Spring junits are getting failed during the maven build. If I run each test case individually it is working fine. If I run in bulk then only I am getting the below error. Spring version is 4.3.0 and Junit version is 4.12
Exception:
    WARNING: Caught exception while allowing TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener@21f5a665] to process 'before' execution of test method [public void com.ikea.rix.range.model.RetailItemSalesLocationAreaHibernateMappingTest.testSimpleMapping()] for test instance [com.ikea.rix.range.model.RetailItemSalesLocationAreaHibernateMappingTest@9226883]
    org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLException: Listener refused the connection with the following error:
    ORA-12520, TNS:listener could not find available handler for requested type of server

    at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:245)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    at org.springframework.test.context.transaction.TransactionContext.startTransaction(TransactionContext.java:98)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener.beforeTestMethod(TransactionalTestExecutionListener.java:203)
    at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:269)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:367)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121)

Caused by: java.sql.SQLException: Listener refused the connection with the following error:
ORA-12520, TNS:listener could not find available handler for requested type of server


text:
Q: What is the radius of convergence of the series $p(x)=\sum b_nx^n$ Suppose that the series $\sum b_n$ is conditionally convergent but not absolutely convergent.
What is the radius of convergence of the series $p(x)=\sum b_nx^n$?
My try:
Since the series $\sum b_n$ is conditionally convergent so $b_n\to 0\implies |b_n|\to 0$.
Since $b_n\to 0$ so $|b_n|<1$ for $n\ge m$.
If we take $|x|<1$ then $ \sum|b_n||x_n|^n<\sum|x|^n\to 0$ as $|x|<1$.
Thus $p(x)$ is convergent for $|x|<1$.
If $x=1$ then $p(1)=\sum b_n$ which is convergent.
I am unable to proceed for $|x|>1$ .Will you please give some hints to proceed here?

A: Suppose $R$ is the radius of convergence of $\sum b_n x^n.$ Then $\sum b_n x^n$ converges absolutely for $|x|<R.$ If $R>1,$ this includes $x=1.$ But $\sum |b_n 1^n| = \sum |b_n| = \infty.$ Thus $R\le 1,$ and since you've shown $R\ge 1,$ we have $R=1.$


text:
Q: How to kill a zombie process which always initiated whenever geany does I am using Geany for editing a large text data in Ubuntu (600MB or so). But after a while, a zombie process starts whenever I start Geany and it couldn't load the file so that I edit the content. It took 100% of my CPU while Geany runs. I try to kill the zombie process with the following:
    kill -HUP `ps -A -ostat,ppid,pid,cmd | grep -e '^[Zz]' | awk '{print $2}'`

But once I start the application again, the zombie process starts automatically. Also tried logout.
What can I do to kill the zombie process once and for all? Thanks!

A: You can't kill a zombie process since it's already dead.

On Unix and Unix-like computer operating systems, a zombie process or
  defunct process is a process that has completed execution (via the
  exit system call) but still has an entry in the process table: it is a
  process in the "Terminated state".

(from Wikipedia)
It's simply an entry in the process table with no associated process. It exists because the spawning (parent) process has yet to collect the return status (via wait()). Other than that it will consume no resources.
So I suspect the parent process is either busy or not working properly. I would first of all try to identify that process (via the PPID column in ps, for example)
EDIT: I note there's a geany issue raised/resolved around this