text:
Q: Alsa virtual rawmidi port will only receive first and last midi byte of any message I have been experimenting with the following code:
alsarawmidiin.c
The alsa rawmidi states that you can create a virtual rawmidi port by naming the input port "virtual"
So I compiled the code and started it with the command:

alsarawmidiin virtual

This works and I can connect other midi ports using aconnect.
The problem is that the midi data that os being displayed only shows the first and last byte of the midi message. Most midi messages are three bytes, but when using the virtual driver only two are displayed.
Connecting straight to a rawmidi device (not virtual) does work. But I want to connect several midi devices to the same rawmidi port. Is this an error in the alsa rawmidi library?

A: This is a bug in the virtual plugin.
It appears that the code for handling a buffer smaller than a MIDI message was never tested.
This will be fixed in alsa-lib 1.1.4; until that package reaches your distribution, you can apply the patch by hand, or work around this by using a larger buffer.


text:
Q: addPoint with HIGHCHARTS (xAxis dateTime) I based this tutorial to create a chart in real time.
http://www.highcharts.com/docs/working-with-data/live-data
Then as I work with nodejs and socket I MODIFY code but suddenly the graph does not update ..
Here's the code :
Code client :
var chart;
var series = Array();
socket.on('ping', function(data){
    console.log(data);
      socket.emit('pong', {beat: 1})
    //console.log(i);
requestData(data);

    });
        function requestData(point) {
        if(point !== null){

                    //console.log('if'+point);
                    var series = chart.series[0],
                        shift = series.data.length > 60; // shift if the series is longer than 20
                    //alert(point);
                    chart.series[0].addPoint(point, true, shift);

                    //setTimeout(requestData, 5000);
        }
}

        $(document).ready(function() {
            chart = new Highcharts.Chart({
                chart: {
                    renderTo: 'container',
                    defaultSeriesType: 'spline',
                            zoomType: 'x',
                    backgroundColor: "#333333"
                },
                        load: function(){
                    chart = this;
                    requestData();
                },
                title: {
                    text: 'Bitcoin price'
                },
                xAxis: {
                    type: 'datetime',
                    tickPixelInterval: 150,
                    maxZoom: 20 * 1000
                },
                yAxis: {
                    minPadding: 0.2,
                    maxPadding: 0.2,
                    title: {
                        text: 'Value',
                        margin: 80
                    }
                },
                series: [{
                    name: 'Bitcoin Price (Spot)',
                    data: []
                }]
            });
        });

Code server :
var amount;
var dateN;
function updateChart(){
    setTimeout(updateChart, 5000);
    dateN =(Math.floor(new Date().getTime() /1000)*1000); // equal to time() in php
  client.getSpotPrice({'currency': 'USD'}, function(err, obj) {
        amount = obj.data.amount;
        });
    var info = [dateN,amount+phpjs.rand(01,99)];
    var pointd = JSON.stringify(info);
    console.log(pointd);
    //console.log(amount);
    pointd = phpjs.str_replace('"','',pointd);
    io.sockets.emit('ping', pointd);
}

io.sockets.on('connection', function (socket) {
    socket.on('pong', function(data){
        console.log("Pong received from client");
    });
});

When I look at the log console I get well [1446218389000,323.3578] for example.
Exactly what I receive at the base with the script in php .
But not update the graph ..
If you have an idea ?
Thank you :)

A: Shift takes Boolean value , in your case the condition
shift = series.data.length > 60;

returning false ,as you may getting point data which may not >60. so instead use
chart.series[0].addPoint(point, true, true); //true in place of shift.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to accomplish audio effect processing on iOS? First of all, we used an AudioUnit(SubType_VoiceProcessingIO) to record the sound captured by device's microphone(iPhone or iPad). The problem is that when we spoke loudly and got too close to the microphone, due to the build-in AGC, the volume of the sound would decrease very quickly. And if we turned off the build-in AGC, the sound would crack. We just want the volume to be normal and stable. But we had not found any way to change the parameter of the build-in AGC. This is troubling us for a long time because there is no such phenomenon on Android device.
Then we discover that we can use AUGraph to accomplish audio effect processing and maybe solve this problem. So we tried this way. Due to the specific format required by DynamicsProcessor(an AudioUnit subType, belong to the main type of kAudioUnitType_Effect), we use an AudioUnit(SubType_VoiceProcessingIO) for sound recording, two AudioUnits(SubType_AUConverter) for format convertion, an AudioUnit(SubType_DynamicsProcessor) for volume control. At last, we use AUGraph to connect all these AudioUnits.
The data flows like this:
AudioUnit instance1(VoiceProcessingIO) -> AudioUnit instance2(AUConverter) -> AudioUnit instance3(DynamicsProcessor) -> AudioUnit instance4(AUConverter).
But the result is that we could not get the data processed by the AudioUnit instance4(AUConverter) through its callback function, the function was never called.
Here are some questions
1.Are there any easier ways to solve this problem ?
2.How to get the data processed by the last AudioUnit instance4(AUConverter) ? We need to write the data into a localFile for analysis.
3.Are there some implicit things that we should know about kAudioUnitSubType_AUConverter or kAudioUnitType_FormatConverter ?
Latest Code
#import "ViewController.h"

#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

#define OUTPUT_ELEMENT 0
#define INPUT_ELEMENT 1

FILE *g_recordFileHandle1;
FILE *g_resultFileHandle1;

static inline void CheckError(OSStatus status, NSString *functionDescription, NSString *errorMessage);

static OSStatus ConvertUnitRenderCallBack(void *inRefCon,
                                          AudioUnitRenderActionFlags *ioActionFlags,
                                          const AudioTimeStamp *inTimeStamp,
                                          UInt32 inBusNumber,
                                          UInt32 inNumberFrames,
                                          AudioBufferList *ioData);

@interface ViewController ()

@property (nonatomic, strong) UIButton *beginButton;
@property (nonatomic, strong) UIButton *endButton;

@end

@implementation ViewController
{
    AUGraph m_pAudioGraph;

    AUNode m_nRecordNode;
    @public AudioUnit m_pRecordUnit;
    @public AudioBufferList *m_pRecordBufferList;
    AudioStreamBasicDescription m_stRecordFormat;

    AUNode m_nConvertNode1;
    @public AudioUnit m_pConvertUnit1;

    AUNode m_nDPNode;
    @public AudioUnit m_pDPUnit;
    AudioStreamBasicDescription m_stDPInputFormat;
    AudioStreamBasicDescription m_stDPOutputFormat;

    AUNode m_nConvertNode2;
    @public AudioUnit m_pConvertUnit2;
}

#pragma mark - Life Cycle

- (void)dealloc {
    if (g_recordFileHandle1) {
        fclose(g_recordFileHandle1);
        g_recordFileHandle1 = NULL;
    }

    if (g_resultFileHandle1) {
        fclose(g_resultFileHandle1);
        g_resultFileHandle1 = NULL;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"方案1";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.beginButton];
    [self.view addSubview:self.endButton];

    NSString *recordFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"recordData1.pcm"];
    g_recordFileHandle1 = fopen([recordFilePath UTF8String], "wb");
    NSString *resultFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"resultData1.pcm"];
    g_resultFileHandle1 = fopen([resultFilePath UTF8String], "wb");

    [self configureAudioGraph];
}

#pragma mark - Private Methods

- (void)configureAudioGraph {
    memset(&m_stRecordFormat, 0, sizeof(AudioStreamBasicDescription));
    m_stRecordFormat.mSampleRate = 16000.0f;
    m_stRecordFormat.mFormatID = kAudioFormatLinearPCM;
    m_stRecordFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked | kAudioFormatFlagIsNonInterleaved;
    m_stRecordFormat.mBitsPerChannel = 16;
    m_stRecordFormat.mChannelsPerFrame = 1;
    m_stRecordFormat.mBytesPerFrame = m_stRecordFormat.mBitsPerChannel * m_stRecordFormat.mChannelsPerFrame / 8;
    m_stRecordFormat.mFramesPerPacket = 1;
    m_stRecordFormat.mBytesPerPacket = m_stRecordFormat.mBytesPerFrame * m_stRecordFormat.mFramesPerPacket;

    m_pAudioGraph = NULL;
    CheckError(NewAUGraph(&m_pAudioGraph), @"NewAUGraph", @"fail");

    // RecordNode
    AudioComponentDescription recordDescription;
    recordDescription.componentType = kAudioUnitType_Output;
    recordDescription.componentSubType = kAudioUnitSubType_VoiceProcessingIO;
    recordDescription.componentManufacturer = kAudioUnitManufacturer_Apple;
    recordDescription.componentFlags = 0;
    recordDescription.componentFlagsMask = 0;
    CheckError(AUGraphAddNode(m_pAudioGraph, &recordDescription, &m_nRecordNode), @"AUGraphAddNode recordNode", @"fail");
    // ConvertNode1
    AudioComponentDescription convertDescription1;
    convertDescription1.componentType = kAudioUnitType_FormatConverter;
    convertDescription1.componentSubType = kAudioUnitSubType_AUConverter;
    convertDescription1.componentManufacturer = kAudioUnitManufacturer_Apple;
    convertDescription1.componentFlags = 0;
    convertDescription1.componentFlagsMask = 0;
    CheckError(AUGraphAddNode(m_pAudioGraph, &convertDescription1, &m_nConvertNode1), @"AUGraphAddNode convertNode1", @"fail");
    // DynamicsProcessor
    AudioComponentDescription dpDescription;
    dpDescription.componentType = kAudioUnitType_Effect;
    dpDescription.componentSubType = kAudioUnitSubType_DynamicsProcessor;
    dpDescription.componentManufacturer = kAudioUnitManufacturer_Apple;
    dpDescription.componentFlags = 0;
    dpDescription.componentFlagsMask = 0;
    CheckError(AUGraphAddNode(m_pAudioGraph, &dpDescription, &m_nDPNode), @"AUGraphAddNode dpNode", @"fail");
    // ConvertNode2
    AudioComponentDescription convertDescription2;
    convertDescription2.componentType = kAudioUnitType_FormatConverter;
    convertDescription2.componentSubType = kAudioUnitSubType_AUConverter;
    convertDescription2.componentManufacturer = kAudioUnitManufacturer_Apple;
    convertDescription2.componentFlags = 0;
    convertDescription2.componentFlagsMask = 0;
    CheckError(AUGraphAddNode(m_pAudioGraph, &convertDescription2, &m_nConvertNode2), @"AUGraphAddNode convertNode2", @"fail");

    CheckError(AUGraphOpen(m_pAudioGraph), @"AUGraphOpen", @"fail");

    [self setupRecordUnit];

    [self setupDynamicsProcessorUnit];

    [self setupConvertUnit1];
    [self setupConvertUnit2];

    CheckError(AUGraphConnectNodeInput(m_pAudioGraph, m_nRecordNode, INPUT_ELEMENT, m_nConvertNode1, OUTPUT_ELEMENT), @"AUGraphConnectNodeInput m_nRecordNode->m_nConvertNode1", @"fail");
    CheckError(AUGraphConnectNodeInput(m_pAudioGraph, m_nConvertNode1, OUTPUT_ELEMENT, m_nDPNode, OUTPUT_ELEMENT), @"AUGraphConnectNodeInput m_nConvertNode1->m_nDPNode", @"fail");
    CheckError(AUGraphConnectNodeInput(m_pAudioGraph, m_nDPNode, OUTPUT_ELEMENT, m_nConvertNode2, OUTPUT_ELEMENT), @"AUGraphConnectNodeInput m_nDPNode->m_nConvertNode2", @"fail");

    CheckError(AUGraphInitialize(m_pAudioGraph), @"AUGraphInitialize", @"fail");
    CheckError(AUGraphUpdate(m_pAudioGraph, NULL), @"AUGraphUpdate", @"fail");
    CAShow(m_pAudioGraph);
}

- (void)setupRecordUnit {
    NSLog(@"");
    NSLog(@"---------------setupRecordUnit begin---------------");

    m_pRecordUnit = NULL;
    CheckError(AUGraphNodeInfo(m_pAudioGraph, m_nRecordNode, NULL, &m_pRecordUnit), @"AUGraphNodeInfo recordNode", @"fail");

    UInt32 inputFlag = 1;
    CheckError(AudioUnitSetProperty(m_pRecordUnit,
                                    kAudioOutputUnitProperty_EnableIO,
                                    kAudioUnitScope_Input,
                                    INPUT_ELEMENT,
                                    &inputFlag,
                                    sizeof(inputFlag)),
               @"AudioUnitSetProperty m_pRecordUnit kAudioOutputUnitProperty_EnableIO INPUT_ELEMENT kAudioUnitScope_Input",
               @"fail");

    UInt32 enableAGC = 1;
    CheckError(AudioUnitSetProperty(m_pRecordUnit,
                                    kAUVoiceIOProperty_VoiceProcessingEnableAGC,
                                    kAudioUnitScope_Global,
                                    INPUT_ELEMENT,
                                    &enableAGC,
                                    sizeof(enableAGC)),
               @"AudioUnitSetProperty m_pRecordUnit kAUVoiceIOProperty_VoiceProcessingEnableAGC INPUT_ELEMENT kAudioUnitScope_Global",
               @"fail");

    CheckError(AudioUnitSetProperty(m_pRecordUnit,
                                    kAudioUnitProperty_StreamFormat,
                                    kAudioUnitScope_Output,
                                    INPUT_ELEMENT,
                                    &m_stRecordFormat,
                                    sizeof(m_stRecordFormat)),
               @"AudioUnitSetProperty m_pRecordUnit kAudioUnitProperty_StreamFormat INPUT_ELEMENT kAudioUnitScope_Output",
               @"fail");

    NSLog(@"---------------setupRecordUnit end---------------");
    NSLog(@"");
}

- (void)setupDynamicsProcessorUnit {
    NSLog(@"");
    NSLog(@"---------------setupDynamicsProcessorUnit begin---------------");

    m_pDPUnit = NULL;
    CheckError(AUGraphNodeInfo(m_pAudioGraph, m_nDPNode, NULL, &m_pDPUnit), @"AUGraphNodeInfo dpNode", @"fail");

    UInt32 inputFormatSize = sizeof(m_stDPInputFormat);
    CheckError(AudioUnitGetProperty(m_pDPUnit,
                                    kAudioUnitProperty_StreamFormat,
                                    kAudioUnitScope_Input,
                                    OUTPUT_ELEMENT,
                                    &m_stDPInputFormat,
                                    &inputFormatSize),
               @"AudioUnitGetProperty m_pDPUnit kAudioUnitProperty_StreamFormat OUTPUT_ELEMENT kAudioUnitScope_Input",
               @"fail");

    UInt32 outputFormatSize = sizeof(m_stDPOutputFormat);
    CheckError(AudioUnitGetProperty(m_pDPUnit,
                                    kAudioUnitProperty_StreamFormat,
                                    kAudioUnitScope_Output,
                                    OUTPUT_ELEMENT,
                                    &m_stDPOutputFormat,
                                    &outputFormatSize),
               @"AudioUnitGetProperty m_pDPUnit kAudioUnitProperty_StreamFormat OUTPUT_ELEMENT kAudioUnitScope_Output",
               @"fail");

    NSLog(@"---------------setupDynamicsProcessorUnit end---------------");
    NSLog(@"");
}

- (void)setupConvertUnit1 {
    NSLog(@"");
    NSLog(@"---------------setupConvertUnit1 begin---------------");

    m_pConvertUnit1 = NULL;
    CheckError(AUGraphNodeInfo(m_pAudioGraph, m_nConvertNode1, NULL, &m_pConvertUnit1), @"AUGraphNodeInfo convertNode1", @"fail");

    CheckError(AudioUnitSetProperty(m_pConvertUnit1,
                                    kAudioUnitProperty_StreamFormat,
                                    kAudioUnitScope_Input,
                                    OUTPUT_ELEMENT,
                                    &m_stRecordFormat,
                                    sizeof(m_stRecordFormat)),
               @"AudioUnitSetProperty m_pConvertUnit1 kAudioUnitProperty_StreamFormat OUTPUT_ELEMENT kAudioUnitScope_Input",
               @"fail");

    CheckError(AudioUnitSetProperty(m_pConvertUnit1,
                                    kAudioUnitProperty_StreamFormat,
                                    kAudioUnitScope_Output,
                                    OUTPUT_ELEMENT,
                                    &m_stDPInputFormat,
                                    sizeof(m_stDPInputFormat)),
               @"AudioUnitSetProperty m_pConvertUnit1 kAudioUnitProperty_StreamFormat OUTPUT_ELEMENT kAudioUnitScope_Output",
               @"fail");

    NSLog(@"---------------setupConvertUnit1 end---------------");
    NSLog(@"");
}

- (void)setupConvertUnit2 {
    NSLog(@"");
    NSLog(@"---------------setupConvertUnit2 begin---------------");

    m_pConvertUnit2 = NULL;
    CheckError(AUGraphNodeInfo(m_pAudioGraph, m_nConvertNode2, NULL, &m_pConvertUnit2), @"AUGraphNodeInfo convertNode2", @"fail");

    CheckError(AudioUnitSetProperty(m_pConvertUnit2,
                                    kAudioUnitProperty_StreamFormat,
                                    kAudioUnitScope_Input,
                                    OUTPUT_ELEMENT,
                                    &m_stDPOutputFormat,
                                    sizeof(m_stDPOutputFormat)),
               @"AudioUnitSetProperty m_pConvertUnit2 kAudioUnitProperty_StreamFormat OUTPUT_ELEMENT kAudioUnitScope_Input",
               @"fail");

    CheckError(AudioUnitSetProperty(m_pConvertUnit2,
                                    kAudioUnitProperty_StreamFormat,
                                    kAudioUnitScope_Output,
                                    OUTPUT_ELEMENT,
                                    &m_stRecordFormat,
                                    sizeof(m_stRecordFormat)),
               @"AudioUnitSetProperty m_pConvertUnit2 kAudioUnitProperty_StreamFormat OUTPUT_ELEMENT kAudioUnitScope_Output",
               @"fail");

    CheckError(AudioUnitAddRenderNotify(m_pConvertUnit2,
                                        ConvertUnitRenderCallBack,
                                        (__bridge void *)self),
               @"AudioUnitAddRenderNotify m_pConvertUnit2",
               @"fail");

    NSLog(@"---------------setupConvertUnit2 end---------------");
    NSLog(@"");
}

#pragma mark - Action Methods

- (void)beginAudioCapture {
    CheckError(AUGraphStart(m_pAudioGraph), @"AUGraphStart", @"fail");
}

- (void)endAudioCapture {
    Boolean isRunning = false;
    OSStatus status = AUGraphIsRunning(m_pAudioGraph, &isRunning);
    if (isRunning) {
        status = AUGraphStop(m_pAudioGraph);
        CheckError(status, @"AUGraphStop", @"Could not stop AUGraph");
    }
}

#pragma mark - Getter

- (UIButton *)beginButton {
    if (!_beginButton) {
        CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
        CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
        _beginButton = [[UIButton alloc] initWithFrame:CGRectMake((screenWidth - 80)/2, screenHeight - 300, 80, 50)];
        [_beginButton setTitle:@"开始录制" forState:UIControlStateNormal];
        [_beginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_beginButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        [_beginButton addTarget:self action:@selector(beginAudioCapture) forControlEvents:UIControlEventTouchUpInside];
    }

    return _beginButton;
}

- (UIButton *)endButton {
    if (!_endButton) {
        CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
        CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
        _endButton = [[UIButton alloc] initWithFrame:CGRectMake((screenWidth - 80)/2, screenHeight - 200, 80, 50)];
        [_endButton setTitle:@"结束录制" forState:UIControlStateNormal];
        [_endButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_endButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        [_endButton addTarget:self action:@selector(endAudioCapture) forControlEvents:UIControlEventTouchUpInside];
    }

    return _endButton;
}

@end

#pragma mark - Functions

static void CheckError(OSStatus status, NSString *functionDescription, NSString *errorMessage)
{
    if (status != noErr)
    {
        char fourCC[16];
        *(UInt32 *)fourCC = CFSwapInt32HostToBig(status);
        fourCC[4] = '\0';
        if (isprint(fourCC[0]) && isprint(fourCC[1]) && isprint(fourCC[2]) && isprint(fourCC[3]))
        {
            NSLog(@"%@ - %@: %s", functionDescription, errorMessage, fourCC);
        }
        else
        {
            NSLog(@"%@ - %@: %d", functionDescription, errorMessage, (int)status);
        }
    }
    else
    {
        NSLog(@"%@ succeed", functionDescription);
    }
}

static OSStatus ConvertUnitRenderCallBack(void *inRefCon,
                                          AudioUnitRenderActionFlags *ioActionFlags,
                                          const AudioTimeStamp *inTimeStamp,
                                          UInt32 inBusNumber,
                                          UInt32 inNumberFrames,
                                          AudioBufferList *ioData)
{
    if (*ioActionFlags == kAudioUnitRenderAction_PreRender)
    {
        NSLog(@"ConvertUnitRenderCallBack flag = kAudioUnitRenderAction_PreRender");
    }
    if (*ioActionFlags == (kAudioUnitRenderAction_PostRender | kAudioUnitRenderAction_OutputIsSilence | kAudioUnitRenderAction_PostRenderError))
    {
        NSLog(@"ConvertUnitRenderCallBack flag = kAudioUnitRenderAction_PostRenderError");
    }
    if (*ioActionFlags == kAudioUnitRenderAction_PostRender)
    {
        NSLog(@"ConvertUnitRenderCallBack flag = kAudioUnitRenderAction_PostRender");
        NSLog(@"ConvertUnitRenderCallBack dataLength = %lu", (unsigned long)ioData->mBuffers[0].mDataByteSize);
        if (ioData->mBuffers[0].mData)
        {
            if (g_resultFileHandle1)
            {
                fwrite(ioData->mBuffers[0].mData, 1, ioData->mBuffers[0].mDataByteSize, g_resultFileHandle1);
            }
        }
    }

    if (ioData->mBuffers[0].mData)
    {
        memset(ioData->mBuffers[0].mData, 0, ioData->mBuffers[0].mDataByteSize);
    }

    return noErr;
}


text:
Q: How to understand python data frames better Being a beginner in Python, I often face this problem - Let's say I am working with a data frame and want to execute an operation on one of the column. It can be just removing the decimal point from the value or maybe I want to take out the month from the date column. But often the solutions I would find online - it is generally shown with a single value or a data point like this:
a = 11.0
int(a)
11

Now, the same solution can't be applied if I have a data frame or a column. Again If I want to add time with date
d = date.today()
d
datetime.date(2018, 3, 30)

datetime.combine(d, datetime.min.time())
datetime.datetime(2018, 3, 30, 0, 0)

In the same manner, this solution can not be used for a data frame. That will throw an error. Obviously I have a lacking in knowledge here, I am not being able to make it work in terms of data frames. Can you please point me towards the topic which might help me understand these problems in terms of data frames ? or maybe show an example how its done ?

A: You should have a look at pandas library to manipulate dataframes : https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html
This is an exemple to apply a function for each value of a given column:
import pandas as pd

def myFunction(a_string):
   return a_string.upper()

data = pd.read_csv('data.csv')

print(data)
data['City'] = data['City'].apply(myFunction)
print(data)

Data at beginning :
 Name     City    Age
 Robert   Paris   32
 Max      Dallas  24
 Raj      Delhi   27

Data after:
 Name     City    Age
 Robert   PARIS   32
 Max      DALLAS  24
 Raj      DELHI   27

Here myFunction uppercase the string but could be used the same way for other kind of operations.
Hope that helps.


text:
Q: MS Access using function on onclick event of button I have below function on form:
Function StringsHaveAMatchingCharacter(String1 As Variant, String2 As Variant) As Boolean

     ' Return True if the two strings have at least one character in common;
     ' otherwise return False.

     Dim lngX As Long

     If IsNull(String1) Or IsNull(String2) Then
         ' No point checking for a match.
     Else
         For lngX = 1 To Len(String1)
             If InStr(String2, Mid$(String1, lngX, 1)) <> 0 Then
                 StringsHaveAMatchingCharacter = True
                 Exit Function
             End If
         Next lngX
     End If

     StringsHaveAMatchingCharacter = False

 End Function

I can call this function with commandbutton on form. But how to use specify on my event if function returns "false" or "true" as I want new dialog form to be open if function returns "True" else I want msgbox and cancel opening dialog form.

A: Not sure I understand the problem. You simply call the function and use its return value.
Private Sub cmdOpenDialog_Click()

    Dim isMatch As Boolean

    isMatch = StringsHaveAMatchingCharacter(Me!Text1.Value, Me!Text2.Value)

    If isMatch Then
        DoCmd.OpenForm "myDialog"
    Else
        MsgBox "Nope."
    End If

End Sub


text:
Q: Subdomain on GCP for split domain routing How can I make a subdomain on google cloud platform for split domain routing? I already have an email provider on my domain so I want to do SDR to connect another email provider. My domain is registered from GoDaddy and then pointed to GCP where is hosted by Bitnami WordPress.

A: I understand that you want to create a Split Domain Routing using GCP but you should know that Google Cloud is blocking the outbound connections on ports 25, 465, and 587.
So if you want to create an SDN you have to  set up your own email server on an instance using a non-standard ports and create the MX records in your DNS.


text:
Q: interpreting my own data (negative confidence interval in epidemiology) Im trying to measure the absolute change between two means of systolic bloodpressure, and used a simple method for calculating the confidence interval between to means.
My goal is to estimate the absolute change for the TREND between 1980-2000. So to accomplish this im comparing the first and last year (i.e 1980 and 2000, which i already have an point estimate and 95%Cl for, achieved with proc STDRATE in SAS 9.4, using a backgroundpopulation of holland).
Now to the problem ->
For the year 1980 i have a point estimate with 95%cl for systolic bloodpressure at 94.9(73.1 to 120.8)
For the year 2000 i have a point estimate with 95%cl for systolic bloodpressure at 80.3(70.1 to 96.8)
So the absolute change is -14,6, this means that the asbolute decline is 14.6 with the calculated confidence interval of +/- 22,7 (normal distribution).
Here's the thing-> i cant make any sense of how to interpret an absolute decline of 14.6 (-8.1 to 37.3).
Since im trying to describe trends and already know that systolic hypertension have a decline with 14,6 estimates then how can i describe a lower limit of minus (-)8.1 if its already a decrease.
Hope that this makes any sense, its probably a more epidemiological question then a mathematical or programming one.
In desperate need of help :)!

A: You're thinking too hard! A "negative decrease" is just an increase. Your CI says "with 95% confidence, systolic pressure changed between -37.3 and 8.1"


text:
Q: How to pass an external variable to an Angular Iframe? I have created a simple Angular application and have it in production.
From another project I have invoked it through an iframe.
The iframe is displayed correctly, but I don't know how to pass a variable to the application that is inside the iframe.
I have tried this:
Parent App
<iframe src="https://{myBusinessUri}.amazonaws.com/index.html?id=12345"></iframe>

Iframe App > App.Module
ngOnInit(): void {
    this.getQueryParam();
  }

  getQueryParam() {
    this.activatedRoute.queryParams.subscribe(params => {
      const id = params['id'];
      console.log(id);
    });
  }

If I add the id to the iframe an error occurs.
Error: Cannot match any routes. URL Segment: 'index.html'

I also tried to put the query param id, in the path of the parent application but without success.


text:
Q: Having GROUP BY multiple values giving me all possible combinations Imagine the following table:
type cond
A    good
A    good
A    bad
B    good
B    bad
C    good
C    bad
D    good
D    bad
E    worse

If I count and group by both type and cond I'll get this:
count type cond
2     A    good
1     A    bad
1     B    good
1     B    bad
1     C    good
1     C    bad
1     D    good
1     D    bad
1     E    worse

But for better summarizing the data into a table I'd rather like a result like this:
count type cond
2     A    good
1     A    bad
0     A    worse
1     B    good
1     B    bad
0     B    worse
1     C    good
1     C    bad
0     C    worse
1     D    good
1     D    bad
0     D    worse
0     E    good
0     E    bad
1     E    worse

I already managed to cross join all existing types with all existing conds but then I can't count anymore.
I also tried to left join the result against all existing types or conds but that didn't work either.
The SUM-CASE-WHEN strategy doesn't work here as I want to have it dynamic, i.e. I don't know how many types or conds there will be.
Is there a simple (or even a complicated) solution to generate a linear matrix of the grouped data? (Bonus: …or even transpose it, i.e. 2D matrix, to have one group as table headers?)

A: Try this:
SELECT
  COUNT(c.type) as `count`, a.type, b.cond
FROM (
    SELECT DISTINCT type
    FROM table_name
  ) a
  CROSS JOIN (
    SELECT DISTINCT cond
    FROM table_name
  ) b
  LEFT JOIN
    table_name c ON c.type = a.type AND c.cond = b.cond
GROUP BY a.type, b.cond
ORDER BY a.type, b.cond

Test it: SQL Fiddle
EDIT:
To show results in 2D matrix with one group as table headers, you must known group names before running query. Query can be:
SELECT
  a.type,
  COUNT(CASE WHEN b.cond = 'good'  THEN c.type ELSE NULL END) as good,
  COUNT(CASE WHEN b.cond = 'bad'   THEN c.type ELSE NULL END) as bad,
  COUNT(CASE WHEN b.cond = 'worse' THEN c.type ELSE NULL END) as worse
FROM (
    SELECT DISTINCT type
    FROM table_name
  ) a
  CROSS JOIN (
    SELECT DISTINCT cond
    FROM table_name
  ) b
  LEFT JOIN
    table_name c ON c.type = a.type AND c.cond = b.cond
GROUP BY a.type
ORDER BY a.type

Test it: SQL Fiddle

A: For better data structure you must have a table with cond anagraph but...
You can build your cartesian product with two subqueries, one for all types and one for all conds, so, you have a subquery on SELECT fields where you can count the elements of these couples.
Try this:
CREATE TABLE app(type char, cond varchar(10));

INSERT INTO app values
('A', 'good'),
('A', 'good'),
('A', 'bad'),
('B', 'good'),
('B', 'bad'),
('C', 'good'),
('C', 'bad'),
('D', 'good'),
('D', 'bad'),
('E', 'worse')

select t1.cond, t2.type, (select count(*) from app a3 where a3.cond = t1.cond
and (a3.type = t2.type)) as total
from
    (select distinct cond
    from app a1) as t1
cross join
    (select distinct type
    from app a2) as t2
order by t2.type, t1.cond

Show SqlFiddle

A: select
    A.type,
    A.cond,
    case
        when B.cnt is null then 0
        else B.cnt
    end
from
    (select
        type, cond
    from
        (SELECT distinct
        cond
    from
        package)
    cross join (select distinct
        type
    from
        package)) A
        left join
    (select
        type, cond, count(*) as cnt
    from
        package
    group by type , cond) B ON A.cond = B.cond and A.type = B.type
order by type


text:
Q: How do I migrate Sqlite3 database into Firebase? I have developed an App with Sqlite3 database , now I am planing to migrate into Firebase.

A: Try to use hibernate ,read data from sqllite3 and write into firebase


text:
Q: change resolution and size of image with cocoa/osx/swift (no mobile apps) I try to change the size and the resolution of an image programmatically, afterwards I save this image.
The imagesize in the imageView is changing, but when I look at my file "file3.png" it always has the original resolution of 640x1142.
I googled around but can't find a solution. I try to redraw the image. But maybe it's the wrong strategy.
thanks
@IBAction func pickOneImageBtn(sender: AnyObject) {

    //load image from path
    pickedImage.image = loadImageFromPath(fileInDocumentsDirectory("Angebote.png"))

    let newSize = NSSize(width: 10, height: 10)

    if let image = pickedImage.image {

        print("found image")

        //cast to CGImage
        var imageRect:CGRect = CGRectMake(0, 0, image.size.width, image.size.height)
        let imageRef = image.CGImageForProposedRect(&imageRect, context: nil, hints: nil)

        if let imageRefExists = imageRef {
            print("Cast to CGImage worked \(imageRefExists)")
        }

        //redraw to NSImage with new size
        let imageWithNewSize = NSImage(CGImage: imageRef!, size: newSize)

        //save on disk
        let imgData: NSData! = imageWithNewSize.TIFFRepresentation!
        let bitmap: NSBitmapImageRep! = NSBitmapImageRep(data: imgData!)
        if let pngCoverImage = bitmap!.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [:]) {
            pngCoverImage.writeToFile("/...correctpath.../imageSourceForResize/file3.png", atomically: false)
            print("saved new image")
        }

       //the size is smaller
       pickedImage.image = imageWithNewSize
    }

}

A: Change
let imgData: NSData! = pickedImage.image!.TIFFRepresentation!

to
let imgData: NSData! = imageWithNewSize.TIFFRepresentation!

A: I tried to change the size of a NSImage for Mac application and here is the working function to resize an image written in swift.
    func resize(image: NSImage, w: Int, h: Int) -> NSImage
    {

      let destSize = NSMakeSize(CGFloat(w), CGFloat(h))
      let newImage = NSImage(size: destSize)
      newImage.lockFocus()
      image.drawInRect(NSMakeRect(0, 0, destSize.width, destSize.height),  fromRect: NSZeroRect, operation: NSCompositingOperation.CompositeCopy, fraction: 1.0)

      newImage.unlockFocus()
      newImage.size = destSize
      return NSImage(data: newImage.TIFFRepresentation!)!
   }

You need to pass 3 parameters to call this function i.e NSImage, width, height and this function will return resized image.
    targetimage = resize(source, w: Int(targetwidth), h: Int(targetheight))


text:
Q: Create a Hyperlink using String resources I try to make a TextView as hyperlink. This one worked as expected :
content.text = "Content".fromHtml()

But I get a lint warning regarding using string resources. But this one does now show TextView as hyperlink:
content.text = getString(R.string.content, args.article.url).fromHtml()

And this is String resource :
<string name="content">Content</string>

Is there any solution to fix it using String resource?
@Suppress("DEPRECATION")
fun String.fromHtml() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    Html.fromHtml(this, Html.FROM_HTML_MODE_COMPACT)
} else {
    Html.fromHtml(this)
}

A: This is how to set text in TextView :
content.text = TextUtils.expandTemplate(getText(R.string.content), args.article.url).toString().fromHtml()

And this is how to set String resources :
<string name="content"><![CDATA[ Content]]></string>


text:
Q: truested but still error The security certificate presented by this website was issued for a different website's address we have an intranet website. it is self-signed. i added the certificate to trusted zone. add the site to trusted site and intranet site, but still get this error.
The security certificate presented by this website was issued for a different website's address.
Security certificate problems may indicate an attempt to fool you or intercept any data you send to the server.

A: the problem is users connect to server by ip and not the address.bcs site signed by previous admin i didn't know which address the certificate was issued for. so checked the cert address
start>certmgr.msc
found the certificate
in detail tab, found subject property, in the attributes, the CN is showing the address of website:

so i added the address of website into the dns and everything get fine.so users will need to connect to the website by "http:///" not "http://"
**(if the certificate issued for contoso.com but users access to the site by ip this error will be shown)


text:
Q: OpenCV matchTemplate finds same shapen multiple times - Python My questions is an extention of a question that I asked here.
I'm using matchTemplate to find circles on a page. This is the result:

I want to find the locations of the mid-points of these rectangles, which I can do with the coordinates of the corners of the rectangles. I put a list inside the four loop, so the code could catch the coordinates of the rectangles. This it the result:
[...,
 [(144, 187), (539, 571)],
 [(145, 187), (540, 571)],
 [(146, 187), (541, 571)],
 [(147, 187), (542, 571)],
 [(148, 187), (543, 571)],
 [(149, 187), (544, 571)],
 [(150, 187), (545, 571)],
 [(151, 187), (546, 571)],
 [(152, 187), (547, 571)],
 [(133, 188), (528, 572)],
 [(134, 188), (529, 572)],
 [(135, 188), (530, 572)],
 [(136, 188), (531, 572)],
 [(137, 188), (532, 572)],
 [(138, 188), (533, 572)],
 [(139, 188), (534, 572)],
 [(140, 188), (535, 572)],
 [(141, 188), (536, 572)],
 [(142, 188), (537, 572)],
 [(143, 188), (538, 572)],
 [(144, 188), (539, 572)],
 [(145, 188), (540, 572)],
 [(146, 188), (541, 572)],
 [(147, 188), (542, 572)],
 [(148, 188), (543, 572)],
 [(149, 188), (544, 572)],
 ...]

This is just a snippet: there are hundreds of lines like this which gives me the info that matchTemplate finds the same circle over and over again. I was expecting only five sets of corner-values.
First I started to remove all double values in the list, but since there are many values remaining after that I still have the same problem.
Does anyone have a way to find only one set of corner-values for each circle (which is most certainly correct) so that I can use that value?
I hope my question is clear and someone can help.
Regards,
Ganesh

EDIT: my question is still unclear, so I hope this edit will give some clarity.
First, I want my code to be able to find the circles on the image, using OpenCV matchingTemplate. I have the code, the image and the template here:
import cv2
import numpy as np

#load image into variable
img_rgb = cv2.imread('example_scan.jpg')

#load template
template = cv2.imread('example_template.jpg')

List = []

#read height and width of template image
w, h = template.shape[0], template.shape[1]

res = cv2.matchTemplate(img_rgb,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.95
loc = np.where( res >= threshold)

for i in zip(*loc[::-1]):
    location = (i[0] + w, i[1] + h)
    List.append([i, location])

    cv2.rectangle(img_rgb, i, location, (0,255,0), 20)

img_rgb = cv2.resize(img_rgb,(800,600))
cv2.imshow("result",img_rgb)
cv2.waitKey(10000)

Normally I use a threshold of 0.8, but for this example I use 0.95 for more clearity. This is then the result:

This shows that the code does indeed work. Now, here is the issue.
I want to determine the centerpoint of the reactangle that is shown. This can be determined using a simple code which uses the corners of the rectangle:
xCenter = (i[0] + i[0] + w)/2
yCenter = (i[1] + i[1] + w)/2

I can use this code inside the for-loop, which gives me the center xy-coordinate of each ractangle that is found.
When I print this xy-coordinate (and also the List) I would expect one xy-coordinate, but instead I can see a whole list of coordinates which only differ a little bit from each other:
#Locations of the center xy-coordinates:
(1527.5, 770.5)
(1525.5, 771.5)
(1526.5, 771.5)
(1527.5, 771.5)
(1528.5, 771.5)
(1529.5, 771.5)
(1525.5, 772.5)
(1526.5, 772.5)
(1527.5, 772.5)
(1528.5, 772.5)
(1529.5, 772.5)
(1524.5, 773.5)
(1525.5, 773.5)
(1526.5, 773.5)
(1527.5, 773.5)
(1528.5, 773.5)
(1529.5, 773.5)
(1530.5, 773.5)
(1525.5, 774.5)
(1526.5, 774.5)
(1527.5, 774.5)
(1528.5, 774.5)
(1529.5, 774.5)
(1525.5, 775.5)
(1526.5, 775.5)
(1527.5, 775.5)
(1528.5, 775.5)
(1529.5, 775.5)
(1527.5, 776.5)

So what happens is that the template is found multiple times on the same spot, with only a small difference in coordinates (around 5px).
What I want is that the code returns only one center xy-coordinate, for which I need only one rectangle. My question is: how can this be done? Is there a code that is able for example to recognize the small difference and would be able to filter them out?
I hope the question is much clearer now.
Regards,
Ganesh


text:
Q: "Lost password" page triggers 404 I have a WP 4.5.3 with Wiz theme and two other plugins (other than the ones bundled with Wiz): WP Customer Area and WP-Members.
https://www.ukulele.it/wp-login.php
Try clicking "Lost password", you get a 404. I've googled for the problem, and the results suggest a plugin conflict. I've tried disabling both of the user-management related plugins, but the 404 error is still there.
How do I reset the "change password" page to the WP default one?
EDIT AFTER birgire's ANSWER:
I've added the suggested code to discover the resposible plugin, e.g.:
add_action( 'login_footer', function() use ( &$wp_filter )
{
    if( isset( $wp_filter['lostpassword_url'] ) )
        printf( '<!--%s-->', print_r( $wp_filter['lostpassword_url'], 1 ) );
});

In the login page source now I get:
<!--Array
(
    [10] => Array
        (
            [wc_lostpassword_url] => Array
                (
                    [function] => wc_lostpassword_url
                    [accepted_args] => 1
                )
        )
)-->

That means that in my case WooCommerce is to blame (or myself for a broken WooCommerce configuration).

A: Your theme or plugins are most likely modifying the "Lost password" link on your wp-login.php via the lostpassword_url filter.

How do I reset the "change password" page to the WP default one?

One would need to remove those filters callbacks.
Here's one (untested) suggestion:
add_filter( 'lostpassword_url', function( $url, $redirect )
{
    remove_all_filters( 'lostpassword_url' );

    return wp_lostpassword_url( $redirect );
}, PHP_INT_MAX, 2 );

Otherwise one could search the install for add_filter( 'lostpassword_url' or peek into the $wp_filter global array. Here's an example:
add_action( 'login_footer', function() use ( &$wp_filter )
{
    if( isset( $wp_filter['lostpassword_url'] ) )
        printf( '<!--%s-->', print_r( $wp_filter['lostpassword_url'], 1 ) );
});

that should print out the information as an HTML comment on the login page.


text:
Q: What's faster/more efficient: Continuous Deleting OR Continuous Updating + Intermittent Deleting? I have a cron that runs through many rows, deleting the "bad" ones (according to my criteria). I'm just wondering what would be the best to optimize the script. I can do one of the following:

*

*Have the same cron instantly delete the "bad" rows upon finding them.

*Have the same cron instantly update the "bad" rows to status "1", meaning bad. Then, I can set up another cron that runs onces an hour deleting all rows with status "1". To make it faster, I guess I'd have an index on "status", but that might also ruin performance.
Any suggestions?

A: An index on a field with two possible values is not as useful as you might think, particularly if you're continually changing the field that you're indexing.  As an example, let's say you have a table with 100,000 rows of data, and initially 'status' is set to 0 for each row (after a delete cycle, and before an update cycle).  At that point in time, using that index is equivalent to doing a sequential search of the table.  If you update 1,000 rows, marking their status as 1, then your index will need to be updated (and possibly rebalanced) 1,000 times.  Finally when you delete all the rows with status == 1, then you'll be able to take advantage of the index (you only look at 1% of the rows), but you'll need to update the index 1,000 times (in addition to deleting the rows).
IMO, you're better off selecting the 'bad' rows directly and deleting them immediately -- you eliminate the overhead of an index you're not using well, and the overhead of a second query.
Note: depending upon your database, deletes may be a very fast operation, or remarkably slow.  Ultimately, deleting a row involves marking a row as unused, and then returning the space occupied by that row to the table so that new rows can be inserted.  This is complicated by variable-length rows (as a result of variable-length datatypes), and by the internal implementation details.  As an example, PostgresQL merely marks a row as deleted, and then uses a separate manually-invoked process (vacuum) to return the space used by the deleted rows to the table for use for new rows.  I believe that PostegresQL still treats row updates as a delete, followed by an insert.  MySQL and Oracle and SQL Server all have different methods of achieving the same end result, each with more complicated side-effects on system performance.
You'll need to study your documentation and any performance guides to decide what would be best for your system.

A: I am not experienced in mySQL but on other DBMS I worked on an update and then delete does not help. Just try with huge amounts of data and measure the time on the delete versus update+delete. It helps if the columns that act as a criteria for the "bad" ones have an index.

A: IF you are thinking of updating a row as bad and then later deleting it, you are putting extra pressure on the server.
Deleting them directly is the better option.
If you think there are going to be huge amount of bad rows, make a cron in such a way that it does not delete more than 100 rows at a time. That should limit the server load to some extend.


text:
Q: Стоить ли учить perl 5? Стоить ли учить perl 5?
A: Думаю однозначно стоит, т.к. это современный язык, который активно развивается, для веб-разработки можете посмотреть в сторону Plack/PSGI, Mojolicious, Dancer/Dancer2, Kelp.
На русском языке развивается журнал о современном Perl: http://pragmaticperl.com/
Еще несколько ссылок на русском:

*

*http://perltrap.com/ru/

*http://ru.perlmaven.com/

*https://perljobs.ru/

*http://perldancer.ru/home

*http://dev-lab.info/

*http://alpha6.ru/

*http://dev.perltuts.com/

*https://github.com/timurn/modern_perl_book/tree/russian_translation/translation/ru/sections

A: Ну учить можно стихотворения. А понимать можно начинать.
Но опять же, смотря для чего он вам. Если вы живете в nix* то он вам как родной станет, если в сторону веб-программинга - тут надо думать.
Язык лишь средство, смотря в какой области применять будете.
A: Дубль.
Возможности и назначение языка Perl
ЗЫ. Однозначно стоит, но без опыта трудно куда-нибудь устроиться.

A: Тут не столько важна "цифра", сколько само название технологии - "Perl". Если говорить кратко, то нет, не стоит учить Perl сейчас( ни первый, ни пятый, ни десятый ). Эта технология начала умирать на 8 лет раньше PHP, а PHP сейчас хоть и является самым распространенным языком для разработки веб приложений, но все же это ему особо не помогает не умирать.
Также важно то, где вы собираетесь использовать технологию. Если для разработки "инновационных" решений, то, определенно, учить его, опять же, нет смысла. Если же для себя( в качестве экзотики, например, как сейчас становится "модно" разбираться в древних вещах типа ADA или вещах без смысла, как BrainFuck  ), то, пожалуйста : многому можно научиться и многое понять, изучая Perl. Например, разобраться в том, как в общем работают скриптовые языки.
Сейчас хоть и есть сообщества Perl-программистов и даже готовится Perl 6. Но это вовсе не делает его "мейнстримовым" и передовым языком. Лучше потратить время на что-то более серьёзное вроде Java, Python или на тот же PHP.
A: Цифра в вопросе как бы намекает, что вы выбираете между Perl 5 и Perl 6.
Если это так, то для работы, выполнения реальных задач, все же стоит пока учить Perl 5.
Perl 6 можно учить потому, что в нем очень много новых фишек - многие задачи можно решить более удобными методами, чем на других языках (том же Perl 5), и эти методы встроены напрямую в язык. Изучение самого этого языка способно поднять ваш общий уровень как программиста.
Хотя если вам в компании разрешают применять подобные инновации, можете попробовать Perl 6 и для реальных небольших проектов в продакшене. Однако имейте в виду, что по быстродействию Perl 6 пока не на высоте, хотя и постоянно улучшается в этом плане, как и в других (за последний год, кстати, сильно вырос - и по фишкам тоже).
Уже через неделю Ларри объявит, что язык готов для использования в продакшене: https://fosdem.org/2015/schedule/event/get_ready_to_party/


text:
Q: How to change/swap a div's background image with a click? I'm attempting to create a mute button (it already has an onclick function) on a site using a div with a background image. I would like to be able to change the displayed image after clicking on it (mute), but I also need to change it back after a second click (unmute). How can this be done?
The site already uses jquery.
Thank you!

A: Have a look at toggleClass(). You just need two CSS classes, one with each background image e.g.:
.mute {
  background-image:url('mute.png');
}

.unmute {
  background-image:url('unmute.png');
}

Then the jQuery would be (assuming you have a div named "button", with class "unmute"):
$('#button').click(function() {
    $(this).toggleClass('mute');
});

A: You want jQuery's .toggle() which takes multiple function arguments and calls each in turn after each click event.
$("#mutebutton").toggle(
    function() {
        $(this).css("background-image","url('on.jpg')");
        mySoundOn();
    },
    function() {
        $(this).css("background-image","url('off.jpg')");
        mySoundOff();
    }
);

A: Use .removeAttr() if the background image is the only think applied inline. If not, then use .css() and change the path to the original background image.

$(this).toggle(function() {
   $(this).removeAttr('style');
},
function() {
   $(this).css("backgroundImage", "url(mute_img_path)");
});

A: its easy
<div id="img-swap" />

where xxxxxx_Off is you image for mute
$(function(){
  $("#img-swap").on('click', function() {
    if ($(this).attr("class") == "img-swap") {
      $(this).css("background-image","on.jpg");
    } else {
      $(this).css("background-image","off.jpg");
    }
    $(this).toggleClass("on");
  });
});

this will switch image on click from off to on. you must use a pattern for images that will contain _off and _on suffix


text:
Q: Firebase facebook auth error I am getting a problem with the cordova facebook authentication plugin when using it to login using Firebase Auth.
Here is my error:

Here is my code:
if (window.facebookConnectPlugin && (window.cordova && device.platform == 'iOS') || (window.cordova && device.platform == 'Android')) {
        console.log("using the plugin");
        facebookConnectPlugin.login(['public_profile'], function(result) {
          provider = firebase.auth.FacebookAuthProvider.credential(result.authResponse.accessToken);
          provider.addScope('public_profile');
          provider.addScope('email');
          Auth.firebaseAuth.$signInWithCredential(provider).then(function(authData) {
            // User successfully logged in
            console.debug(authData);
            console.log("logged in ionic");
          }).catch(errFn);
        }, errFn);
      }

A: Found the problem. I needed to add an Android app over here, then generate a key hash and input that using this command:
keytool -exportcert -alias <alias> -keystore <path to app keystore> | openssl sha1 -binary | openssl base64


text:
Q: Data Binding not refresh when "clear" ObservableCollection of strings I have a Windows which contains two Listboxes and one button.
Those two List Box Data Bind to List of Class "ObjectList" and include ObservableCollection in it.
The First ListBox (we will call it "ObjectLists") contain text box in it.
The Second  ListBox (we will call it "ObjectListsSelected") contain Listbox in it.
I use those top Listboxes to get dynamic UI.
The Button executea a command which use to split the text in the first listbox (follow \r\n chars), add them to the second list box and clear the Text Box in first listbox.
I'm having a problem with Data Binding for "ObjectLists".
The Clean option doen't reflect in the UI although the property get this update.
When Debugging this scenario i found out that the Clear action doesn't go to the set of the property.
of course i Used Property Change, but nothing work.
Main Windows
<Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Window.Resources>
    <local:ListToTextConverter x:Key="converter1"></local:ListToTextConverter>
</Window.Resources>
<Grid Name="ObjPanel">
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Label Content="Object" Height="30"/>
    <ListBox Name="ObjectLists" Grid.Row="1" Grid.Column="0" ItemsSource="{Binding OB1,Mode=TwoWay}" BorderThickness="0" Background="Transparent" Width="200" HorizontalAlignment="Center">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel></StackPanel>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBox Name="ObjectList" Text="{Binding content,Mode=TwoWay,Converter={StaticResource converter1}}"  Margin="0,0,30,0" Height="225" Width="200" HorizontalAlignment="Center"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <Button Name="AddButton" Command="{Binding AddCommand}" Grid.Row="1" Grid.Column="1" Height="50" Width="150" HorizontalAlignment="Center" Margin="0,0,10,0">Add</Button>
    <Label Content="ObjectSelect" Height="30" Grid.Column="2"/>
    <!--<ListBox Name="ObjectListSelectedBox1" ItemsSource="{Binding ObjSelected}" Grid.Row="1" Grid.Column="3" Width="200" Height="225" HorizontalAlignment="Center"/>-->
    <ListBox Name="ObjectListsSelected" Grid.Row="1" Grid.Column="2" ItemsSource="{Binding OB2,Mode=TwoWay}" BorderThickness="0" Background="Transparent" Width="200" HorizontalAlignment="Center">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel></StackPanel>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <ListBox Name="ObjectListSelected" ItemsSource="{Binding content,Mode=TwoWay}"  Margin="0,0,30,0" Height="225" Width="200" HorizontalAlignment="Center"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

class ObjectList
class ObjectList
{
    public string header { get; set; }

    private ObservableCollection<string> _content;

    public ObservableCollection<string> content
    {
        get { return _content; }
        set
        {
            _content = value;
        }
    }

    public ObjectList()
    {
        content=new ObservableCollection<string>();
    }

}

Main View Model
class MainVM : INotifyPropertyChanged
    {
        public RelayCommand AddCommand { get; set; }
    public List<ObjectList> OB2 { get; set; }

    private List<ObjectList> ob1;

    public List<ObjectList> OB1
    {
        get { return ob1; }
        set {
            ob1 = value;
            OnPropertyChanged(nameof(ob1));
            }
    }

    public MainVM()
    {
        this.AddCommand = new RelayCommand(Add);
        OB1 = new List<ObjectList>()
        {
            new ObjectList()
        };
        OB2 = new List<ObjectList>()
        {
            new ObjectList()
        };

    }

    public void Add()
    {
        foreach (var s in OB1[0].content)
        {
            OB2[0].content.Add(s);
        }

        OB1[0].content.Clear();
        OnPropertyChanged(nameof(OB1));

    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

}

Covertors
public class ListToTextConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        StringBuilder sb = new StringBuilder();
        Type TEST = value.GetType();
        foreach (string s in (ObservableCollection<string>)value) sb.AppendLine(s);
        string str = sb.ToString();
        return str;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string[] lines = Regex.Split((string)value, "\r\n");
        ObservableCollection<string> OC = new ObservableCollection<string>(lines);
        return (OC);
    }
}


text:
Q: If $AB$ contains a neighborhood of $x$, does $m(A \cap x B^{-1})>0$? This is a converse to a step in Steinhaus theorem for topological groups, where it is shown that $m(A \cap xB^{-1})>0$ implies $AB$ contains a neighborhood of $x$.
Suppose $m(A),m(B)>0$ on some locally compact topological group with left Haar measure $m$. Suppose $AB$ contains a neighborhood of $x$. (By Steinhaus theorem, there is always such an $x$). Can one conclude that $m(A\cap xB^{-1})>0$?

A: Consider the case of $\mathbb R$.  Let $A = B = E \cup [10,11]$ where $E$ is the Cantor set.  As is well known, $E + E = [0,2]$ so we can take $x = 1$.  But $A \cap (1 - B) = E$ has measure $0$.


text:
Q: A question related to the mean value theorem Let $f$ be continuous on $[a,b]$ and differentiable on $(a,b)$. It it true that for every $c\in[a,b]$, there exists some $(a_0, b_0)$ such that
$$f'(c) = \frac{f(b_0)-f(a_0)}{b_0 - a_0}\,? $$

A: No, not necessarily. Consider for example $f(x)=x^3$. Then $f'(0)=0$, but there are no $a$ and $b$ such that
$$\frac{a^3-b^3}{a-b}=0$$
without having $a=b$.


text:
Q: Why print() in Swift does not log the time stamp as NSLog in objective C From background of Objective C when I use NSLog() it prefixes the text with the date time stamp, but when I use print() on Swift it only prints the text
So it there is a way to make it print the time stamp as well, or am I doing some thing wrong?

A: Here is a suggested function you can use instead of print()
func printLog(log: AnyObject?) {
    let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS "
    print(formatter.stringFromDate(NSDate()), terminator: "")
    if log == nil {
        print("nil")
    }
    else {
        print(log!)
    }
}

A: Because print is not NSLog. It is as simple as that.
NSLog is a logging tool in Foundation that writes to the Apple System Log facility which appears on the console.
print(…) is a print function in the Swift Standard Library that writes to standard out, which appears on the console in debug sessions.
You could add Date() to your print parameter to print the current time and date. (Or Date().description(with: Locale.current) to get it in your local time zone.)
Or you could just use NSLog which is available in Swift too (if you import Foundation).

A: Swift:
NSLog("this will print with dates")

A: You can use the Logging os module to do that in Swift: https://developer.apple.com/documentation/os/logging
Specifically os_log: https://developer.apple.com/documentation/os/2320718-os_log
import os.log
os_log("Message %d", type: .info, value)

A: Make your own class function for print, eg printWithDate() and prepend the date to the output. Then you can use this everywhere without needing to add the date each time you want to print.

A: This one just outputs a simple timestamp, but can be easily modified to include additional text if you want.
Additionally, it relies on a lazy DateFormatter to avoid expensive initializations.
import Foundation

class Timestamp {
    lazy var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS "
        return formatter
    }()

    func printTimestamp() {
        print(dateFormatter.string(from: Date()))
    }
}

let timestamp = Timestamp()
timestamp.printTimestamp() // 2018-07-05 12:57:08.725
timestamp.printTimestamp() // 2018-07-05 12:57:08.727 (uses the same formatter)


text:
Q: Hi, I am using android studio and I'm am getting this error about duplicated dependencies but I'm not sure where to look to be able to fix the issue here is a print out of the error.
Duplicate class com.google.android.gms.auth.api.zza found in modules classes.jar (com.google.android.gms:play-services-auth-base:16.0.0) and classes.jar (com.google.android.gms:play-services-auth:12.0.1)
Duplicate class com.google.android.gms.measurement.AppMeasurement found in modules classes.jar (com.google.android.gms:play-services-measurement-impl:16.4.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.android.gms.measurement.AppMeasurement$ConditionalUserProperty found in modules classes.jar (com.google.android.gms:play-services-measurement-impl:16.4.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.android.gms.measurement.AppMeasurement$Event found in modules classes.jar (com.google.android.gms:play-services-measurement-impl:16.4.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.android.gms.measurement.AppMeasurement$EventInterceptor found in modules classes.jar (com.google.android.gms:play-services-measurement-impl:16.4.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.android.gms.measurement.AppMeasurement$OnEventListener found in modules classes.jar (com.google.android.gms:play-services-measurement-impl:16.4.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.android.gms.measurement.AppMeasurement$Param found in modules classes.jar (com.google.android.gms:play-services-measurement-impl:16.4.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.android.gms.measurement.AppMeasurement$UserProperty found in modules classes.jar (com.google.android.gms:play-services-measurement-impl:16.4.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.firebase.analytics.FirebaseAnalytics found in modules classes.jar (com.google.android.gms:play-services-measurement-api:16.4.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.firebase.analytics.FirebaseAnalytics$Event found in modules classes.jar (com.google.android.gms:play-services-measurement-api:16.4.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.firebase.analytics.FirebaseAnalytics$Param found in modules classes.jar (com.google.android.gms:play-services-measurement-api:16.4.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.firebase.analytics.FirebaseAnalytics$UserProperty found in modules classes.jar (com.google.android.gms:play-services-measurement-api:16.4.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Go to the documentation to learn how to Fix dependency resolution errors.

A: Add this line in your gradle
multiDexEnabled true


text:
Q: Flutter Get object from Navigator. push. hangs   //***************** main *************
 Future  callCobrac( BuildContext context)   async {
        final ConfigTrajet configTrajet  =
           await    (Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => MapCobrac()),
              ));
        }

//**********.   MapCobrac.
   IconButton(
            icon: const Icon(Icons.save),
            onPressed: () {
            Navigator.pop(context, configTrajet);
            },
//----
   class ConfigTrajet {
          int code = 0;
          double centerLatitude;
          double centerLongitude;
          List<int> tripSelected = [];
          ConfigTrajet(this.code , this.centerLatitude, this.centerLongitude,
              this.tripSelected);
        }

//I  received always  following message

Error: Expected a value of type 'ConfigTrajet' (in   package:mapcobrac/main.dart), but got one of type 'ConfigTrajet' (in  package:mapcobrac/mapcobrac.dart`
NB
I have defined the class   ConfigTrajet . in main.dart  & mapcobrac.dart
I dont understands. Thanks for some help


text:
Q: JS: Resizing canvas + redrawing elements on canvas My question: What's the best way to resize the canvas with all its drawn elements?
I have 2 examples where I tried to archieve this.
The first one works, but lacks functionality because if I would add many more elements to be drawn it would get very messy. In my second example I tried to put everything into an array and loop through it but it doesn't resize correctly anymore because it doesn't recalculate the x,y width and height anymore. Basically I wish to know a way to not have to call a function which calculates the elements x,y,width and height again before drawing. I want to to put the math into the array and when it's getting drawn,
it recalculates so I just have to make sure the canvas.width/height is updated, how do I do that?
1st example

class Canvas {
    constructor() {
        this.canvas = document.createElement('canvas');
        this.canvas.width = window.innerWidth;
        this.canvas.height = window.innerHeight;
        this.ctx = this.canvas.getContext('2d');
        document.body.appendChild(this.canvas);
        this.resize();
    }

    initAreas() {
        this.firstArea = { "x": 0, "y": 0, "w": this.canvas.width, "h": this.canvas.height / 2 }
        this.secondArea = { "x": 0, "y": this.firstArea.h, "w": this.canvas.width, "h": this.canvas.height / 2 }
    }

    resize() {
        this.canvas.width = window.innerWidth;
        this.canvas.height = window.innerHeight;
        this.initAreas();
        this.ctx.fillStyle = "green";
        this.ctx.fillRect(this.firstArea.x, this.firstArea.y, this.firstArea.w, this.firstArea.h);
        this.ctx.fillStyle = "red";
        this.ctx.fillRect(this.secondArea.x, this.secondArea.y, this.secondArea.w, this.secondArea.h);
    }

}

const canvas = new Canvas();

window.onresize = function() { canvas.resize(); }
body {
    padding: 0;
    margin: 0;
}

canvas {
    display: block;
}
<!DOCTYPE html>

<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <script src="script.js"></script>
</body>
</html>

2nd example
class Canvas {
constructor() {
    this.canvas = document.createElement('canvas');
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
    this.ctx = this.canvas.getContext('2d');
    document.body.appendChild(this.canvas);
    this.areasToDraw = [];
    this.initAreas();
    this.resize();
}

initAreas() {
    this.firstArea = { "x": 0, "y": 0, "w": this.canvas.width, "h": this.canvas.height / 2, "color": "green" }
    this.areasToDraw.push(this.firstArea);
    this.secondArea = { "x": 0, "y": this.firstArea.h, "w": this.canvas.width, "h": this.canvas.height / 2, "color": "red" }
    this.areasToDraw.push(this.secondArea);
}

resize() {
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
    for(this.areas in this.areasToDraw) {
        this.ctx.fillStyle = this.areasToDraw[this.areas].color;
        this.ctx.fillRect(this.areasToDraw[this.areas].x, this.areasToDraw[this.areas].y, this.areasToDraw[this.areas].w, this.areasToDraw[this.areas].h);
    }
}

A: Observation 1: "Since resize events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as DOM modifications. Instead, it is recommended to throttle the event using requestAnimationFrame, setTimeout or customEvent"
This is from MDN resize
Observation 2: on resize you need to bind the canvas, otherwise you will get canvas undefined.
Observation 3: when you resize the canvas, you need to empty the array of elements: this.areasToDraw in this case, and repopulate the array with new elements.
This is how I would do it:

class Canvas {
constructor() {
    this.canvas = document.createElement('canvas');
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
    this.ctx = this.canvas.getContext('2d');
    document.body.appendChild(this.canvas);
    this.areasToDraw = [];
    //this.initAreas();
    //this.resize();

}

initAreas() {
    this.firstArea = { "x": 0, "y": 0, "w": this.canvas.width, "h": this.canvas.height / 2, "color": "green" }
    this.areasToDraw.push(this.firstArea);
    this.secondArea = { "x": 0, "y": this.firstArea.h, "w": this.canvas.width, "h": this.canvas.height / 2, "color": "red" }
    this.areasToDraw.push(this.secondArea);
}

resize() {
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
    // empty the array
    this.areasToDraw.length = 0;
    // repopulate the array
    this.initAreas();
    for(this.areas in this.areasToDraw) {
        this.ctx.fillStyle = this.areasToDraw[this.areas].color;
        this.ctx.fillRect(this.areasToDraw[this.areas].x, this.areasToDraw[this.areas].y, this.areasToDraw[this.areas].w, this.areasToDraw[this.areas].h);
    }
}

}

let canvas = new Canvas()

setTimeout(function() {
  canvas.resize()
  addEventListener('resize', canvas.resize.bind(canvas), false);
}, 15);
body {
 padding: 0;
 margin: 0;
}

canvas {
 display: block;
}


text:
Q: Unity InputSystem value constantly outputs 0 unless its read from a perform event So I am trying to create a new first-person movement system with the new input system in order to make gamepad support so much easier and I am experiencing a problem when I try to read the value of the Vector2 in a FixedUpdate loop, it only outputs (0,0) but if I read it in an InputAction.performed event it works. However, I cannot use the event as it doesn't repeat on keyboard input and it isn't smooth. I've seen a tutorial linked here and at the end it does demonstrate you can pull information from outside events. Now my question is did I miss something or is there a different way to do it, my code is found below
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Assertions;

public class MovementEngine : MonoBehaviour
{

public InputMaster Input; // My input device here

public float currentSpeed = 2f;

public float walkingSpeed = 2f;
public float runningSpeed = 4f;

public Transform cameraTransform;
public CharacterController controller;

public InputAction Movement;

// Start is called before the first frame update
void Awake()
{
    Input = new InputMaster(); // Creates new instance
}

void OnEnable()
{
    Movement = Input.Player.Movement;
    Movement.Enable(); // it is enabled

    Input.Player.Interaction.performed += Interact;
    Input.Player.Interaction.Enable();
}
private void Interact(InputAction.CallbackContext context)
{
    Debug.Log("Interact");
}
void OnDisable()
{
    Movement.Disable();
    Input.Player.Interaction.Disable();
}

// Update is called once per frame
void FixedUpdate(){
    Debug.Log("Movement: " + Input.Player.Movement.ReadValue<Vector2>()); // doesn't work
}
}

A: Store the value (retrieved in the performed event) in a variable, and use that variable in fixed update.
Make sure to reset the variable from the cancelled event (otherwise the variable will hold the last retrieved value from performed event).
You can read the input value directly into a class variable, as shown below.
// Value read from user input
//
private Vector2 movement;

private void Start()
{
    SubscribeEvents();
}

private void SubscribeEvents()
{
    // Read the value directly into our movement variable
    //
    Input.Player.Movement.performed += ctx => movement = ctx.ReadValue<Vector2>();

    // Reset the movement variable in cancelled since we are no longer interacting
    //
    Input.Player.Movement.cancelled += ctx => movement = Vector2.zero;
}

private void FixedUpdate()
{
    Debug.Log("Movement: " + movement);
}

A: I fixed this a while ago but StackOverflow never posted my answer
I fixed it by downgrading to Unity InputSystem v1.0.0 as v1.1.1 seemed to not like the InputAction.ReadValue<>() function.


text:
Q: How to limit the character count in CSS I am creating a multilingual website where the plugin in I am using only provides the option to show the language name entirely. I want to limit the character count to only 3 characters. Example: If the language is English I only want to display it as ENG, When it's Vietnamese it will be VIE.
I already tried

span {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 50px;
  display: inline-block;
  text-transform: uppercase;
  font-size: 15px;
}

  English

  Vietnamese

I don't want the ... appear with the first three letters and setting a width or max-width is not effective to show only 3 characters in some languages as you see in the above snippet. Is there are any alternative approaches there? Let me know, please.

A: that ? with font-family:monospace;

span {
  font-size      : 30px;
  display        : inline-block;
  width          : 3ch;
  font-family    : monospace;
  overflow       : hidden;
  text-transform : uppercase;
}

  English

  Vietnamese


text:
Q: Pentaho - charts not displaying in CDE dashboards I installed Pentaho 5.3 community version on Windows.
My problem is that when displaying a CDE dashboard, text is displaying just fine but charts do not display at all.
I got this issue with both sample CDE dashboard and my own dashboards.
I see nothing into pentago log that could explain that problem.
I gotr the problem with both Firefox and Chrom latest versions.
Any idea ?
Thank you


text:
Q: stop for loop in java I have written code that computes the simple steepest descent algorithm, and there is an iteration of a for loop.
When the values of x1,x2 is the same as the minimizer, it should stop looping. But in my code it doesn't, instead it prints again and again the minimizer value.
Here is my code:
for (int i = 0 ; i < MAX ; i++) {
    // ∇ƒ(x) =
    //     | 2(x1 - a) - c(x2 - b) |
    //     | 2(x2 - b) - c(x1 - a) |
    //
    // Apply x to ∇ƒ(x)
    double d1f1 = 2 * (x1 - a) - c * (x2 - b);
    double d1f2 = 2 * (x2 - b) - c * (x1 - a);

    // ∇²ƒ(x) =
    //     | 2    -c |
    //     | -c   2  |
    double d2f1 =  2.0;
    double d2f2 = -c;

    //we reach to the minimizer
    if (d1f1 == 0 && d1f2 == 0)
    {
        break;
    }

    // α = |d1f1 d1f2| * | d2f1 d2f2 | * | d1f1 |
    //                   | d2f2 d2f1 |   | d1f2 |
    alpha = (d1f1 * d1f1 + d1f2 * d1f2) /
        (d1f1 * (d1f1 * d2f1 + d1f2 * d2f2) +
         d1f2 * (d1f1 * d2f2 + d1f2 * d2f1));

    // x1 = |x1| - α * | d1f1 |
    // x2 = |x2| - α * | d1f2 |
    x1 = x1 - alpha * d1f1;
    x2 = x2 - alpha * d1f2;

    // Debug
    System.out.println("");
    System.out.printf("alpha  = %.2f\n", alpha);
    System.out.printf("x1     = %.2f\n", x1);
    System.out.printf("x2     = %.2f\n", x2);
}

and the result:
a  = 5.00
x1 = 1.00
x2 = 4.00

alpha  = 0.28
x1     = 4.11
x2     = 1.11

alpha  = 2.47
x1     = 4.96
x2     = 2.02

alpha  = 0.28
x1     = 4.99
x2     = 1.99

alpha  = 2.47
x1     = 5.00
x2     = 2.00

alpha  = 0.28
x1     = 5.00
x2     = 2.00

alpha  = 2.47
x1     = 5.00
x2     = 2.00

alpha  = 0.28
x1     = 5.00
x2     = 2.00

alpha  = 2.47
x1     = 5.00
x2     = 2.00

alpha  = 0.28
x1     = 5.00
x2     = 2.00

alpha  = 2.47
x1     = 5.00
x2     = 2.00

alpha  = 0.28
x1     = 5.00
x2     = 2.00

alpha  = 2.47
x1     = 5.00
x2     = 2.00

alpha  = 0.28
x1     = 5.00
x2     = 2.00

alpha  = 2.47
x1     = 5.00
x2     = 2.00

alpha  = 0.28
x1     = 5.00
x2     = 2.00

alpha  = 2.17
x1     = 5.00
x2     = 2.00

alpha  = 0.28
x1     = 5.00
x2     = 2.00

alpha  = 2.50
x1     = 5.00
x2     = 2.00
final result
x1     = 5.00
x2     = 2.00

A: I don't know if it's the real problem, but you should never check exact equality using doubles. That is because operations like multiplication or division using double are most likely not exact. Better choose some small number epsilon>0 and check if the absolute value of your double is smaller than epsilon.


text:
Q: Extjs6 association between grids I'm trying to make associations work in grid panel: when the user click on a record in the "users" table the corresponding address should appear in the "addresses" table. I've created a fiddle for this. I want to use reference and bind using selection.
I've looked at their example but I was not able to resolve my case(The below snippet is from their example):
 xtype: 'grid',
 bind: '{customerGrid.selection.orders}',

As I understood, in their example, the data is served using SimManager which may add different behavior then reading directly from json file(as I tried in the fiddle).
Also, in this post (the post is about extjs5 but I think the principle is the same), the author says something about the presence of association and inverse association between models. In my local example, when debugging, I cannot see these associations.
How to properly use association between two grids?

A: I know two ways to get user's addresses store.
First way is a using addresses store with filter by property ts_user_id.
viewModel: {
    stores: {
        users: {
            type: 'users'
        },
        addresses: {
            type: 'addresses',
            filters: [{
                property: 'ts_user_id',
                exactMatch: true,
                value: '{usersGrid.selection.ts_id}'
            }]
        }
    }
},

items: [{
    title: 'Home',
    layout: 'fit',
    items:[{
        xtype: 'panel',
        layout: {
            type: 'vbox',
            align: 'stretch'
        },
        items: [{
            xtype: 'tabGrid',
            margin: '10 0 0 0',
            reference: 'usersGrid',
            bind: '{users}',
        },{
            xtype: 'addressGrid',
            margin: '10 0 0 0',
            bind: '{addresses}'
        }]
    }]
}]

Second way is a using hasMany in User model. But this way needs change users.json and doesn't use addresses.json at all.
users.json must contains field addresses with array of Address model
{
    "ts_id": 1,
    "ts_name": "john smith",
    "ts_email": "js@email.com",
    "addresses": [{
        "ts_id": 1,
        "ts_address": "Street A, no 24",
        "ts_user_id": 1
    }, {
        "ts_id": 2,
        "ts_address": "Street B, no 44",
        "ts_user_id": 1
    }]
}

And now you can use addresses field of User model
viewModel: {
    stores: {
        users: {
            type: 'users'
        }
    }
},

items: [{
    title: 'Home',
    layout: 'fit',
    items:[{
        xtype: 'panel',
        layout: {
            type: 'vbox',
            align: 'stretch'
        },
        items: [{
            xtype: 'tabGrid',
            margin: '10 0 0 0',
            reference: 'usersGrid',
            bind: '{users}',
        },{
            xtype: 'addressGrid',
            margin: '10 0 0 0',
            bind: '{usersGrid.selection.addresses}'
        }]
    }]
}]

First example
Second example


text:
Q: Setting elements in a big vector in R I'm working with vectors in R, storing bigz objects (GMP package). It works fine when the vector is not too big (up to 200 elems), but when the vector grows, the performance decrease dramatically.
Trying to get where the bottleneck is, I execute my programm with the profvis library, and I get that the problem is the next piece of code:
res <- as.bigz(rep(0, length(resT))) #resT is a list of bigz of length 600
res[[1]] <- sum.bigz(a_bigz_elem, another_bigz_elem)
i <- 1
while (i <= length(resT) - 1) {
    res[[i + 1]] <- sum.bigz(resT[[i + 1]], resE[[i + 1]])
    i <- i + 1
}

and more specifically, in the 5th line (the elem assignment in the list).
I know this solution is better than a growing vector, i.e. res <- c(res, sum.bigz(resT[[i + 1]], resE[[i + 1]])), but I'm pretty sure there is a more efficient way to do the assignment.
I've read related post in SO and the Advanced R reference documentation, but nothing improves my performance. Any idea how can it be improved?

A: With
res <- as.bigz(rep(0, length(resT))) #resT is a list of bigz of length 600

you are not creating a list. When you change it to:
res <- as.list(as.bigz(rep(0, length(resT))))

you create a list and the execution time should be reduced.
A reproducible example would look like:
library(gmp)

resT  <- as.list(urand.bigz(600, seed=0))
resE  <- as.list(urand.bigz(600, seed=1))
a_bigz_elem  <- resT[[1]]
another_bigz_elem  <- resE[[1]]

res <- as.list(as.bigz(rep(0, length(resT))))
res[[1]] <- sum.bigz(a_bigz_elem, another_bigz_elem)
i <- 1
while (i <= length(resT) - 1) {
  res[[i + 1]] <- sum.bigz(resT[[i + 1]], resE[[i + 1]])
  i <- i + 1
}

A: Here is a concise way, a bit more efficient than @GKi's solution:
mapply(sum.bigz, resT, resE, SIMPLIFY = FALSE)

Benchmarks:
library(gmp)

resT_list  <- as.list(urand.bigz(1000, seed=0))
resE_list  <- as.list(urand.bigz(1000, seed=1))

f1 <- function(){
  a_bigz_elem  <- resT_list[[1]]
  another_bigz_elem  <- resE_list[[1]]
  res <- as.list(as.bigz(rep(0, length(resT_list))))
  res[[1]] <- sum.bigz(a_bigz_elem, another_bigz_elem)
  i <- 1
  while (i <= length(resT_list) - 1) {
    res[[i + 1]] <- sum.bigz(resT_list[[i + 1]], resE_list[[i + 1]])
    i <- i + 1
  }
  res
}

f2 <- function(){
  mapply(sum.bigz, resT_list, resE_list, SIMPLIFY = FALSE)
}

library(microbenchmark)
microbenchmark(
  f1 = f1(),
  f2 = f2(),
  times = 10
)
# Unit: milliseconds
# expr      min       lq     mean   median       uq      max neval cld
#   f1 15.27488 16.48450 19.84019 17.51613 25.25338 28.10120    10   b
#   f2 11.83838 12.21875 13.30705 12.87080 14.37143 15.75504    10  a


text:
Q: Can I change gitlab-ci.yml file mid execution? This is our simplified gitlab-ci.yml
stages:
    - build
    - deploy

# fetch home repo that'll run the pipeline processes
before_script:
    - git clone git@git.org:home_repo/home_repo.git
    - cd home_repo

build:
  stage: build
  needs: []
  resource_group: $CI_PROJECT_NAME'_build'
  script:
    - ./pipeline.sh build

deploy_environment1:
  stage: deploy
  needs: [build]
  resource_group: deploy_environment1
  script:
    - ./pipeline.sh deploy env1

deploy_environment2:
  stage: deploy
  needs: [build]
  resource_group: deploy_environment2
  script:
    - ./pipeline.sh deploy env2

Adding 5-10 environments would blow up the size by a lot. How can we handle that?
Possible solution 1:
Have one job that will create a list of all environments available and deploy to them. However, we won't have a good pipeline view of how each deployment went.
deploy_environments:
  stage: deploy
  needs: [build]
  resource_group: deploy_environments
  script:
    - ./pipeline.sh deploy to_all

Possible solution 2:
before_script fetches a list of all environments and inserts as many deploy_environment job definitions as needed. But we don't know how to do that. Hence the question in the title.

A:
Can I change gitlab-ci.yml file mid execution?

No, not really. The closest thing to that would be using dynamic child pipelines where the YAML for a child pipeline is generated dynamically by another job in the parent pipeline.
That would allow you to achieve the effect you want.

Adding 5-10 environments would blow up the size by a lot. How can we handle that?

Alternative to (or even in combination with) using dynamic child pipelines, you could use a parallel matrix for concise definitions.
Something like this:
deploy:
  stage: deploy
  script:
    - ./pipeline.sh deploy $ENV_NAME
  parallel:
    matrix:
      - ENV_NAME: [env1, env2]


text:
Q: Webpack 5 - Asset Module - Missing feature of url-loader - postTransformPublicPath I wanted to switch to the webpack 5 asset module as recommended. Unfortunately I miss the function "postTransformPublicPath: (path: any) => any" of webpack url-loader.
Due to the structure in our application, the public and private areas of the assets are divided there. With the url loader I could then use the following:
      {
        test: /\.(png|jp(e*)g|gif|svg)$/,
        use: [{
          loader: 'url-loader',
          options: {
            limit: 10 * 1024, // Convert images < 10kb to base64 strings
            name: 'private/img/[name].[ext]',
            postTransformPublicPath: (path) => path.replace('private/', ''),
          },
        }],
      },

As a result, the urls in the css were set to the path without private, but placed in the private folder in the folder structure. This private folder was then made available as static after Auth.
Is there a possibility to somehow use this behavior with the asset module?
      {
        test: /\.(png|jp(e*)g|gif|svg)$/,
        type: 'asset',
        generator: {
          filename: 'private/img/[base][query]',
        },
      },


text:
Q: Codeigniter Image doesn't display I'm having a big problem that I can't see or access my image
it says

403 forbidden

here is my code
<img src="http://127.0.0.1/shop/grandes_img/<? $big_pic ?>">

I tried to change the htaccess file inside my project it did not work
I'm stuck here
please help
Edit:
When I add a directory from phpstorm I don't find it inside the project directory why?

A: Add this.
$config['base_url'] = "http://127.0.0.1/shop/";

then change your image source as below
<img src="<?php echo base_url(); ?>grandes_img/<?php echo $big_pic ?>" >

Hope this can help you.


text:
Q: Error accessing an array's value by it's index? Trying to sum up all the numbers in an array. Example 10 + 20 + 30 should be 60.
def sum *arr
  i=0
  total=0
  while i <= arr.count
    total += arr[i]
    i+=1
  end
  total
end

puts sum(10,20,30)

Why am I getting this error. This code looks like it should work to me. What am I doing wrong? Why wont it let me access the array value by it's index?
p8.rb:23:in `+': nil can't be coerced into Fixnum (TypeError)
        from p8.rb:23:in `sum'
        from p8.rb:29:in `<main>'

A: Change
while i <= arr.count

to
while i < arr.count

arr[arr.count] is always out of bounds.

Fyi a shorter way to write sum is:
def sum *arr
  arr.inject(:+)
end

A: Matt's answer gives you the canonical Ruby way to sum, using inject. But if you're not ready to learn inject, at least save yourself the trouble of manually keeping track of array indexes (where your actual problem lies!) by using #each to iterate through the array like so:
def sum *arr
  total = 0
  arr.each do |x|
    total += x
  end
  total
end

puts sum(10,20,30) # => 60

A: Matt's answer is both slick and correct, but you hit the error because ruby zero indexes arrays.  So if you changed the count condition

while i <= arr.count - 1

your error would go away


text:
Q: Right multi object dependance design I need some help with a correct design.
I have a class called BufferManager. The push() method of this class reads data from a source and pushes it to a buffer repeatedly until there is no more data left in the source.
There are also consumer threads that read data from this buffer, as soon as new data arrives.
There is an option to sort the data before it comes to buffer. What I do right now is that BufferManager, instead of pushing data to the buffer, pushes it to another "sorting" buffer and starts a sorting thread. SorterManager class reads the data, sorts it in files and push()es the sorted data into the buffer.
There will be a bottleneck (I use merge sort with files) but this is something I can't avoid.
This is a bad design, because both BufferManager and SorterManager push data to a buffer (that consumers read from).  I think only BufferManager should do it.
How can I design it?

A: A lot of design problems go away when you use composition instead of inheritance.
For clarity, let's say the source you're reading from is a socket.
You can create an abstract Reader with read() method that reads a single string.
It will have 2 subclasses - SocketReader and FileReader.
Add a Reader data member to BufferManager initialized in the c'tor.
To create a 'regular' BufferManager, create a BufferManager and pass it a SocketReader instance in the c'tor.
Instead of creating a SorterManager, create a BufferManager and pass it a FileReader instance in the c'tor.
The push() method should be implemented as follows:

while (!mReader.eof()) {
  String s = mReader.read();
  writeToBuffer(s);
}

For summary - you will have a single BufferManager class which will work with sockets or sorted files depending on the Reader you initialize it with.

A: Let's start from what we have?

*

*A source of list exists somewhere.

*The items of this list should be sorted.

*There is a destination buffer which is consumed by others.

'It is a must's:

*

*Sort process must precede source extraction.

*Destination buffer flush must precede sort process.

*All work must done asynchronously.

*But steps of process must be preserved.

Process steps:

*

*Get source list.

*Sort it.

*Write to buffer.

Design Steps:

*

*SourceManager

*SortingManager

*BufferManager

Eventually here is your solution from my point of view:

*

*When SourceManager finishes its work; it passes list to SortingManager

*SortingManager sorts the list taken asynchronously.

*When SortingManager finishes its work; it passes sorted list it produced to BufferManager.

*BufferManager behaves like a data server to all other consumer threads by its buffer.

Warnings:

*

*Do not give two responsibilities to a single class. All monads of a program must serve for only and only one responsibility.

*While programming asynchronous tasks; make distinction between tasks which must not start unless another task finishes and task which
  starts and runs independently relying on none of other tasks.

A: Rambling answer follows :-)

*

*I'm nit picking here, but your push() method should probably split out the reading of data from a source into another method, i.e. Follow the Single Responsibility Principle (SRP)

*What sort of buffer do you have? I'm curious since you state that you have multiple consumers. I assume you're using a java.util.concurrent (j.u.c) data structure?

*Depending on your buffer data structure, you might be able to push to the buffer in a sorted manner (whatever sorted means to you)

*I think your design problem comes from higher up in the method call stack.  I think you're trying to model this:
BufferManager manager = new BufferManager();
manager.getDataFromSource();
if (sortData) {
    manager.sortData();
}

manager.push();

Above is very much a strawman as the BufferManager methods could easily be static (depending on your mutability traits) and it depends on how you're reading in the data (bulk read or firehose style).
Hope that helps a little! And apologies for the non styling of the code block, not sure what's going on there, couldn't get the usual tool to work.


text:
Q: Could there be massive gravitons and in our spacetime? My question is: Could there in principle be sub-groups of gravitons (if they existed) that has mass (and in our spacetime dimensions) such as those affected by electric or by strong force or other forces which could be above the energy threshold of our current particle accelerators. (Perhaps they could be created, say, near pulsars due to high-energy collisions)?

A: This is a speculative question and can only have the answer that mathematically it is conceivable that the theory of everything ( TOE) may contain higher mass gravitons.
After all in the electroweak interactions the photon, the Z and the W are all to start with zero mass carriers of the electroweak force, and then symmetry breaking makes the photon massless and the Z and W ( weak force carriers) massive.
So their might be higher mass graviton-like particles  in some theories .


text:
Q: ValueError: Unknown label type: I am just Starting this naive Bayes Theoram and Getting stuck by this please tell me what to do,
this is my code ::
import sklearn
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split

from sklearn import metrics
from sklearn.metrics import accuracy_score

df = (pd.read_csv("C:\\Users\\dhana\\Downloads\\Mechanics\\train.csv"))

X = []
Y = []
for i in df.Age:
    X.append(str(i))

for j in df.Fare:
    Y.append(j)

X_train, X_test, y_train, y_test = train_test_split(X,Y,test_size=0.3,random_state= 17)

model = GaussianNB()
model.fit(X_train,y_train)
print(model)

y_expect = y_test
y_pred = model.predict(X_test)

print(accuracy_score(y_expect,y_pred))```


text:
Q: How to SELECT last 50 entries except latest 5 from a table? I have a table with around 1000 entries.
I want to SELECT the latest 50 of these entries except the most recent 5 ones. I know how to do this using nested query, but is there a simple way or some special keyword to do something like this.

A: select * from your_table
order by some_column desc
limit 5, 45


text:
Q: Open new file with pre-written text in Code::Blocks IDE Every time I create a new empty file in Code::Blocks, I want below code to be there in the file.
#include<bits/stdc++.h>

using namespace std;

int main(){

    return 0;
}

Is it possible?


text:
Q: Issues in printing time series graph from pandas dataframe I have a DataFrame object with a datetime as index:
In [210]:
f
f.plot(legend=True)

Out[210]:
                         user_time  sys_time  wait_io_time
date_time
2012-11-01 08:59:27          3         1             0
2012-11-01 08:59:32          0         0             0
2012-11-01 08:59:37         20         2             1
2012-11-01 08:59:42          0         0             0
2012-11-01 08:59:47          0         0             0

f.plot() causes this error:
-> 1367     plot_obj.generate()
--> 674         self._make_plot()
-> 1000             self._make_ts_plot(data, **self.kwds)
---> 81     left, right = _get_xlim(ax.get_lines())
--> 220         left = min(x[0].ordinal, left)
AttributeError: 'numpy.int64' object has no attribute 'ordinal'

I do see one line graph, displaying values from the user_time data, so suspecting that the data values from sys_time may be causing the issue. Following suggestion from https://github.com/pydata/pandas/issues/1737, I installed a newer version of matplotlib (1.1.1) but no luck, and plotting fails on the data from the bug url as well.

A: This seems to work with latest matplotlib library installed. I forgot to restart the ipython notebook process or reload the matplotlib after I upgraded it.