text:
Q: Webpack, "hot-reload" or "live-reload" sass? Is there a way to get webpack to "recompile" sass and reload your page on the fly?
I've been searching around but have not found an example.
Here is what I've got:
My folder structure
-app
---public
------dist
---------index.html
---------sass
------------webpack.scss

It seems like my sass only recompiles when I run webpack but it doesn't recompile when I am running the webpack-dev-server
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpack = require('webpack');

module.exports = {
  entry: {
    app: './app/main.js',
    //All 3rd party source
    vendor: ['react', 'redux', 'lodash']
  },
  output: {
    path: path.join(__dirname, 'app', 'public', 'dist'),
    publicPath: '/app/public/dist/',
    filename: 'app.js'
  },
  module: {
    loaders: [
      { test: /\.js$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ },
      { test: /.jsx?$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.css/, loader: ExtractTextPlugin.extract('css') },
      { test: /\.scss$/, loader: ExtractTextPlugin.extract('!css!sass?sourceMap') }
    ]
  },
  sassLoader: {
    includePaths: [ path.resolve(__dirname, './app/public/sass/')]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js", Infinity),
    new ExtractTextPlugin('./css/style.css',{
            allChunks: true
        })
  ],
  debug: true,
  //watch: true
};


text:
Q: Optimize search on a database table having more than 3,500,000 rows I have an Access Database with a table having around 3,500,000 rows. One of its column is a 10-digit 'Phone_No'. Performing a search on such a huge table would take too long. So i decided to split that one table into multiple tables based on first 5 digits of the 'Phone_No'.
For example, if I have a 'Phone_No' value as 1234500000 then I will create a new table named 12345 and insert into it all rows which have 'Phone_No' starting with 12345 i.e. values like 1234500001, 1234500002, etc.
This way if I have to search for a 'Phone_No' I just need to do a 'SELECT * FROM 12345 WHERE Phone_No = 1234500000'. This would narrow down my search to a very small dataset comparatively.
The sample code is as shown below
        int iRow = 0;
        int iRowCount;

        string strIndex;
        string strOutputTableName;

        DataTable dtOutput;

        DataRow dr;

        try
        {
            // Get staging row count
            iRowCount = dtStaging.Rows.Count;
            dsOutput = new DataSet();

            // Iterate each row for splitting
            while (dtStaging.Rows.Count > 0)
            {
                // Increment row count
                iRow++;

                // Get current Datarow
                dr = dtStaging.Rows[0];

                // Get column to be indexed by splitting
                strIndex = dr["Phone_No"].ToString();

                // Set output table name
                strOutputTableName = strIndex.Substring(0, 5);

                try
                {
                    // Create new datatable
                    dtOutput = new DataTable(strOutputTableName);

                    // Add columns
                    dtOutput.Columns.Add("Phone_No", typeof(string));
                    dtOutput.Columns.Add("Subscriber_Name", typeof(string));
                    dtOutput.Columns.Add("Address_Line1", typeof(string));
                    dtOutput.Columns.Add("Address_Line2", typeof(string));
                    dtOutput.Columns.Add("Address_Line3", typeof(string));
                    dtOutput.Columns.Add("City", typeof(string));
                    dtOutput.Columns.Add("Pin_Code", typeof(string));
                    dtOutput.Columns.Add("SIM_Activation_Date", typeof(DateTime));

                    // Add datatable to dataset
                    dsOutput.Tables.Add(dtOutput);
                }
                // catch table already exists error and proceed
                catch
                {

                }

                // Import current datarow from staging to output table
                dsOutput.Tables[strOutputTableName].ImportRow(dr);

                // Report progress
                bwSplit.ReportProgress((iRow * 100) / iRowCount);

                // Remove current datarow to release some memory
                dtStaging.Rows.RemoveAt(0);
            }
        }
        catch
        {
            throw;
        }
        finally
        {
            dtStaging = null;
        }

Once my Dataset dsOutput is prepared, I insert it into another Access Database file. The problem is this splitting process takes ages. I am looking for an optimized version of the above code. Or any different approach which would make the splitting process faster.

A: As stated in several comments to the question, indexing is the first thing to look at when performance is an issue.
I just ran a test with a 170MB .accdb on a network share. The file contained a table with 3.5 million rows whose primary key was the 10-digit phone number (Text(10)). Performing a SELECT to retrieve the row containing a specific phone number, e.g.,
SELECT CompanyName FROM PhoneNumbers WHERE PhoneNumber='4036854444'

consistently took less than 0.1 seconds. To me, that does not seem slow enough to warrant any sort of scheme to segment the data into multiple tables.
For more information on performance considerations for applications using an Access database, see
C# program querying an Access database in a network folder takes longer than querying a local copy

redpajama_set_name: RedPajamaStackExchange


text:
Q: как сделать музыкального бота discord по названию песни на python? Я начал изучать дискорд ботов на питоне и захотел сделать музыкального бота. Смог сделать только по ссылке с ютуба, а хотелось бы как у vexera(вводишь название песни и бот сам находит ее в ютубе и начинает проигрывание).
P.s. При попытке ввести название песни выводится ошибка,но не знаю как это использовать, нигде не нашел..

ERROR: 'gta5soundtrack' is not a valid URL. Set --default-search "ytsearch" (or run  youtube-dl "ytsearch:gta5soundtrack" ) to search YouTube


text:
Q: Macbook keyboard's ] n } keys are cap locking I have replaced my MacBook keyboard twice and I continue to have the same issue. When I press the ] n } key it just turns on Caps Lock. I really need these keys to code.
Can anyone help me with this?
Thanks

A: You should install PCKeyboardHack and change the keycode of the capslock key to 30 (keycode of "]" button). Next you have to switch off caps lock in keyboard settings.

A: The problem I find with a MacBook keyboard is that I can hit the caps lock key when I'm typing fast or carelessly (usually instead of the A key, sometimes instead of the left shift key).  Could your trouble be that with the '}' key, you hit the  caps lock instead of the shift key just below it?  That doesn't explain the problem with the ']' key.
What is your language and keyboard settings set to?  Have you accidentally done something with the keyboard shortcuts from 'System Preferences' / 'Keyboard and Mouse'?


text:
Q: How do I make mutter use my nouveau GPU I am using a laptop which has a discrete nvidia GPU along with the Intel GPU.
$ inxi -G
Graphics:  Device-1: Intel HD Graphics 530 driver: i915 v: kernel
           Device-2: NVIDIA GM107M [GeForce GTX 960M] driver: nouveau v: kernel
           Display: x11 server: X.Org 1.20.8 driver: intel,nouveau resolution: 1920x1080~60Hz, 2560x1440~60Hz
           OpenGL: renderer: NV117 v: 4.3 Mesa 20.1.7 - kisak-mesa PPA

with hybrid-graphics service active
$ sudo systemctl status switcheroo-control.service
● switcheroo-control.service - Switcheroo Control Proxy service
     Loaded: loaded (/lib/systemd/system/switcheroo-control.service; enabled; vendor preset: enabled)
     Active: active (running) since Fri 2020-09-11 19:28:59 PDT; 20h ago
   Main PID: 1267 (switcheroo-cont)
      Tasks: 3 (limit: 18985)
     Memory: 1.5M
     CGroup: /system.slice/switcheroo-control.service
             └─1267 /usr/libexec/switcheroo-control

And I believe the default opengl render is already set to my nvidia.
$ glxinfo | grep "OpenGL renderer"
OpenGL renderer string: NV117

When I run glxgears and/or go to a webgl website,  the nvidia gpu is active.
My question is:  does it mean that the default gnome windows manager / compositor, mutter, uses my nvidia gpu whenever it can?  If not, is there a way to force mutter to use nvidia?
Thanks in advance


text:
Q: How can i create StateClient object in LoginController using service url or microsoft app credentials? I am working on bot framework technology, in one of my project I want to create the state client object using service Url or Microsoft credentials in my LoginController.cs
This is the code I wrote in LoginController.cs, it's working in bot emulator but after published my bot and added it to skype then it's not working.
 //[HttpGet, Route("api/{userid}/authorize")]
    [HttpGet, Route("api/{userid}/token")]
    public async System.Threading.Tasks.Task<HttpResponseMessage> Authorize(string userid, string code)
    {
        AuthenticationContext ac = new AuthenticationContext("https://login.windows.net/common/oauth2/token/");
        ClientCredential cc = new ClientCredential(Constants.Constants.ADClientId, Constants.Constants.ADClientSecret);
        AuthenticationResult ar = await ac.AcquireTokenByAuthorizationCodeAsync(code, new Uri(Constants.Constants.apiBasePath + userid + "/token"), cc, "https://api.office.com/discovery/");
        if (!String.IsNullOrEmpty(ar.AccessToken))
        {
           // var stateClient = new StateClient(new Uri("http://localhost:9000/"));
            // var stateClient = new StateClient(new Uri("http://skype.botframework.com/"));
            //var microsoftAppCredentials = new MicrosoftAppCredentials(appId: "ace15a7e-b7f6-4776-a6a3-a58c0314bd01", password: "X7BS9hJt0skSBu6z9kgW1FB");
            //var stateClient = new StateClient(new Uri("http://skype.botframework.com/"),microsoftAppCredentials,addJwtTokenRefresher:true);
            //var stateClient = new StateClient(microsoftAppCredentials);

            var stateClient = new StateClient(new Uri("https://apis.skype.com/"));
            //var stateClient = new StateClient(new Uri("https://api.slack.com/"));

            if (stateClient != null)
            {
                var userId = userid.Replace("-", ":");
                var getData = await stateClient.BotState.GetUserDataAsync(Constants.Constants.botId, userid);

                //var getData = await client.B.GetUserDataAsync(Constants.Constants.botId, userid);
                getData.Data = ar.Serialize();
                getData.ETag = "*";
                var foo = await stateClient.BotState.SetUserDataAsync(Constants.Constants.botId, userid, getData);

                //var foo = await client.Bots.SetUserDataAsync(Constants.Constants.botId, userid, getData);
            }
            //return Request.CreateResponse(foo);
            var response = Request.CreateResponse(HttpStatusCode.Moved);
            response.Headers.Location = new Uri("/loggedin.html", UriKind.Relative);
            return response;
        }
        else
            return Request.CreateResponse(HttpStatusCode.Unauthorized);

    }

Please tell how to resolve above problem.
-Pradeep

A: The url for the state client service is the following, independent of channel.
        this.BaseUri = new Uri("https://state.botframework.com");

A: Try using the helper method to create your stateclient:
StateClient stateClient = activity.GetStateClient();


text:
Q: machine specific config settings I have an application that gets deployed to a load balanced environment. This application is an asp.net mvc4 application.
I have settings (appsettings & httpheaders) in the web.config for each server. Rather than managing them during deployment, is there a way to set them on the machine and available in the application?

A: You can set your specific settings in the machine.config file on each server. You'll then be able to access those settings, as you would an app setting in the web.config:
string setting = ConfigurationManager.AppSettings["machine.somekey"];

See this post for the location of the machine.config file.


text:
Q: Set alignment for paragraphs in LyX (only for the editor) I am new to LyX. The default setting for the alignment for standard paragraph is 'Justified'. This gives me some inconvenience with long footnotes. For example,

So, I change the alignment setting to 'Left'. But this makes the paragraph left aligned both in the LyX editor and in the resulting pdf file after typesetting. I am wondering if there is a way to change the alignment merely in the LyX editor without changing the alignment of the pdf file?
I would also appreciate if people have other solutions to my problem here.
P.S. = I noticed some discussion here: How to set the justification for all the standard paragraphs in a LyX document. But the solutions seem to make adjustments to both LyX editor and the resultant pdf file.

A: Go to Document > Settings > Text Layout and uncheck "Use justification in LyX work area".


text:
Q: How do I resize a WebDriverJS browser window? I am using WebDriverJS, the JavaScript bindings for WebDriver, to do some simple frontend testing (driven by nodejs).  However, I'm running into difficulties resizing the window, and the documentation is just a bit unclear to me.
var webdriver = require('selenium-wedriver');

driver = new webdriver.Builder()
           .withCapabilities(webdriver.Capabilities.chrome())
           .build();

driver.get("http://www.google.com")
.then(function() {
    driver.Window.setSize(400, 400);  // <-- should resize, does nothing
})
// more thenables...

Everything works normally and it gives no error, but the browser window does not resize.  Am I referencing this setSize method incorrectly?

A: After more than a week of confused searching through the api docs and google, the answer was actually lying inside  of the tests folder of the selenium-webdriver tests node module!!
driver.manage().window().setSize(x, y);

A: I don't know how selenium-webdriver works so I can't help you there but just in case you are interested, here is how it works with WebdriverJS:
var webdriverjs = require('webdriverjs');
var options = {
    desiredCapabilities: {
        browserName: 'chrome'
    }
};

webdriverjs
    .remote(options)
    .init()
    .windowHandleSize({width:1024,height:768})
    .url('http://www.google.com')
    .title(function(err, res) {
        console.log('Title was: ' + res.value);
    })
    .end();


text:
Q: How to parse syslog messages in a syslog4j syslog server I want to parse syslog messages coming to a syslog server implemented in syslog4J. It is possible to do that in syslog4J?
What I want to do is to be able to segregate out various fields in syslog messages like hostname, timestamp, message, severity level etc. and make a uniform syslog pattern for future analysis.
This king of functionality is available in rsyslog or syslogNG.
SyslogServerConfigIF config = new TCPNetSyslogServerConfig("0.0.0.0", 1455);
config.setUseStructuredData(true);

SyslogServerIF syslogserver = SyslogServer.getInstance("tcp");
syslogserver.initialize("tcp", config);
syslogserver.run();

A: Start with creating a new Event Handler class to handle the messages. Note that the parsing should be done in the event() method as that will be called for each syslog event.
public class SyslogMessageHandler implements SyslogServerSessionEventHandlerIF {

@Override
public void event(Object session, SyslogServerIF syslogServer,
                  SocketAddress socketAddress, SyslogServerEventIF event) {
    // Simple parsing for Strings in the message
    if (!event.getMessage().contains(" msg=\"")) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, event.getMessage());
    }

    // You can also build Objects and/or use Pattern/Matcher for parsing.
    MyHTTPLogInfo info = new MyHTTPLogInfo(event.getMessage());
    Pattern myPattern = Pattern.compile("^GET\\s+/([^\\s\\?]*)(\\?\\S*)?\\s+HTTP/1\\.\\d$");
    Matcher matcher = myPattern.matcher(info.getHttpRequest());
    if (matcher.matches()) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, info.getMyCustomLogOutput());
    }
}

@Override
public void exception(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, Exception exception) {
    Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, "exception()");
}

@Override
public Object sessionOpened(SyslogServerIF syslogServer, SocketAddress socketAddress) {
    Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, "sessionOpened()");
    return new Date();
}

@Override
public void sessionClosed(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, boolean timeout) {
    Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, "sessionClosed() {0}", session);
}

@Override
public void initialize(SyslogServerIF syslogServer) {
    Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, "initialize()");
}

@Override
public void destroy(SyslogServerIF syslogServer) {
    Logger.getLogger(getClass().getSimpleName()).log(Level.INFO, "destroy()");
}

Finally register that new class as an EventHandler in the syslog4j config:

eventHandler = new SyslogMessageHandler();
config.addEventHandler(eventHandler);

Then you are ready to start testing and debugging your various formats and patterns :)


text:
Q: Handle / Detect UIPanGestureRecognisor and UISwipeGestureRecognisor on same UIImageView I have a Image Gallery, If User Single Tap On a Picture, it appeares in full screen ImageView,
Now if user Uses UIPinchGesture Picture is zoom in / Out perfectly.
I want to acheive if picture is not zoomed UISwipeGesture Should work and on Swipe Gesture Next Image from gallery is called.
if Picture is zoomed then swipeGesture stop working and UIPanGesture should work.
what will be the best approach to acheive it,
i am doing it like this. but always mixing in PanGesture and SwipeGesture.
my Swipe Handling Method
- (void)handleSwipe:(UIGestureRecognizer *)sender
{
    if (stopSwipe == true) // bool iVar (stopSwipe)
    {
        return;
    }
    UISwipeGestureRecognizerDirection direction = [(UISwipeGestureRecognizer *) sender direction];
    switch (direction)
    {
        case UISwipeGestureRecognizerDirectionLeft:
            newIndexPath = [NSIndexPath indexPathForRow:myIndexPath.row+1 inSection:myIndexPath.section];
            [self ChangeImage];
            myIndexPath = [NSIndexPath indexPathForRow:myIndexPath.row+1 inSection:myIndexPath.section];
            break;
        case UISwipeGestureRecognizerDirectionRight:
            newIndexPath = [NSIndexPath indexPathForRow:myIndexPath.row-1 inSection:myIndexPath.section];
            [self ChangeImage];
            myIndexPath = [NSIndexPath indexPathForRow:myIndexPath.row-1 inSection:myIndexPath.section];
            break;
        default:
            break;
    }
}

my Pinch Handling Method
-(void)handlePinch:(UIPinchGestureRecognizer*)sender
{
static CGRect initialBounds;
if (sender.state == UIGestureRecognizerStateBegan)
{
    initialBounds = myLrgImageView.bounds;
}
CGFloat factor = [(UIPinchGestureRecognizer *)sender scale];

CGAffineTransform transform = CGAffineTransformScale(CGAffineTransformIdentity, factor, factor);
myLrgImageView.bounds = CGRectApplyAffineTransform(initialBounds, transform);
}

my Pan Handling Method
-(void)handlePan:(UIPanGestureRecognizer*)recognizer
{
    //after pinch 'myLrgImageView.frame' is changed.
    //imgActualBoundry is the normal size with out zooming.
    if ([NSValue valueWithCGRect:myLrgImageView.frame] > [NSValue valueWithCGRect:imgActualBoundry])
    {
        stopSwipe = true;
        CGPoint translation = [recognizer translationInView:self.myLrgImageView];
        recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                         recognizer.view.center.y + translation.y);
       [recognizer setTranslation:CGPointMake(0, 0) inView:self.myLrgImageView];

       if (recognizer.state == UIGestureRecognizerStateEnded)
       {
           CGPoint velocity = [recognizer velocityInView:self.myLrgImageView];
           CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
           CGFloat slideMult = magnitude / 200;
           NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);

           float slideFactor = 0.1 * slideMult; // Increase for more of a slide
           CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor),
                                         recognizer.view.center.y + (velocity.y * slideFactor));
           finalPoint.x = MIN(MAX(finalPoint.x, 0), self.myLrgImageView.bounds.size.width);
           finalPoint.y = MIN(MAX(finalPoint.y, 0), self.myLrgImageView.bounds.size.height);
        }
    }
    else
    {
        stopSwipe = false;
    }
}

i have tried with or without this method of simultanious usage of multi gestures, but didn't get success.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

A: What i figure out from your question is : you want to use Pan and Swipe gestures on same UIImageView but on specific conditions.
If i am saying being just a lazy person, simply take the actual size of image in an iVar at first Then Check on both delegate methods :
if size is changed then you will surely like to use Pan gesture on same Image.
&
if size is the same as actual image then Swipe.

I am just posting as an idea to proceed you on.
Sorry for posting not the code, actually facing electricity shortfall and laptop battery is about to dead. :P


text:
Q: MATLAB: String Manipulation and File Input/Output Ok so I have a data file similar to this one containing the names and weights of people:
Darby George          166.2
Helen Dee            143.5
Giovanni Lupa    192.4
Cat Donovan       215.1

Im supposed to read the script into strings one line at a time, save the weight into a vector, and print each person's name in the form 'last,first' followed by the weight:
George, Darby's weight is 166.20 lbs.
Dee, Helen's weight is 143.50 lbs.
Lupa, Giovanni's weight is 192.40 lbs.
Donovan, Cat's weight is 215.10 lbs.

This is my code:
fid = fopen('patwts.dat');
if fid == -1
    disp('File open not successful')
else
    while feof(fid) == 0
    % Read one line into a string variable
    aline = fgetl(fid);
    %Save vector and fprintf here
    strtok(aline,' ')=[first last num];
    fprintf('%s %s %3.2f',last,first,num)
    mat=['%3.2f %3.2f %3.2f %3.2f %3.2f %3.2f 3.2f %3.2f %3.2f %3.2f']
    end
    closeresult = fclose(fid);
    if closeresult == 0
        disp('File close successful')
    else
        disp('File close not successful')
    end
end
fprinf('The average weight is $sum(%3.2f)/2 lbs', num)

I'm having problems with the strtok function.
I don't know how to format the string to read 'last, first' weight.

A: [token, remain] = strtok(aline,' ') will return the first token "Darby" and the remain of the line. I don't think it is what you are looking for.
I would suggest to use strsplit(aline, ' '), it will return a cell containing all the tokens and you would need to get each "first, last, num" by doing a for loop (for example)

A: I wouldn't use strtok.  I would use strsplit instead and split it based on spaces.  Replace your strtok call with strsplit.  Also, declare an empty vector... call it mean_vec that will store the weights as you read them in.  Once you get to the end of the file, you can calculate the average weight after.
As such, try something like this:
fid = fopen('patwts.dat');
mean_vec = []; %// Add here to store weights per line
if fid == -1
    disp('File open not successful')
else
    while feof(fid) == 0
    % Read one line into a string variable
    aline = fgetl(fid);

    %// Change -  Split up string by spaces
    C = strsplit(aline, ' ');

    %// Change - Print out the information
    fprintf('%s, %s''s weight is %s lbs\n', C{2}, C{1}, C{3});

    %// Change - Save weight to vector
    mean_vec = [mean_vec; str2double(C{3})];
    end

    closeresult = fclose(fid);
    if closeresult == 0
        disp('File close successful')
    else
        disp('File close not successful')
    end
end
%// Change - Use mean, not sum
fprintf('The average weight is %f lbs\n', mean(mean_vec));

What's important is that every single part of the line is a string.  Therefore, if you want to get the actual number that's at the end of the line, you need to convert it to a number with str2double.  Once I ran the above code, including the fact that I made a file called patwts.dat and put in your example data in it, I get this:
George, Darby's weight is 166.2 lbs
Dee, Helen's weight is 143.5 lbs
Lupa, Giovanni's weight is 192.4 lbs
Donovan, Cat's weight is 215.1 lbs
File close successful
The average weight is 179.300000 lbs


text:
Q: JqGrid Form Edit Validate all fields on Submit and Show error on each invalid field I am using jqGrid form Edit with templating from the link in
 Here
I have updated the template to look like below sothat I show invalid error below each field if any error.
            template = "

 Customer ID *:

 {CustomerID}
";
            template += "
 Company Name:

{CompanyName}
";
            template += "
 Phone:

{Phone}
";
            template += "";
            template += "
 Postal Code:

{PostalCode}
";
            template += "";
            template += "
 City:

 {City}
";
            template += "";
            template += "
";
            template += "
 {sData} {cData}

";

Now I have added validation to some of my fields using
jqgrid Edit Rules
Lets say I have
editrules : { required: true} in Phone
editrules : { integer: true} in PostalCode
editrules: { custom: true, custom_func: myCustomCheck } in Country

Where my custom check is
  myCustomCheck = function (value, colname) {
        if (colname === "County") {
            var label = $("label[for='" + colname + "']");

            if (value.indexOf("foobar") > -1) {
                invalidDesc = true;
                $("#FrmGrid_mygrid").find('#' + colname).addClass("ui-state-error");

                label.html("Country cant be contain foobar");
                label.removeClass('hidden');
                return [false];
            }
            else
            {
                label.addClass('hidden');
                return [true];
            }

        }
        return [true];
    };

The issue with here is it marks one input at a time when I click submit and there is no way to show my custom error label, on those edit rules predefined by jqgrid(like the integer/required). It only shows the error at the top of the form.
What I would want is when the user clicks submit I validate all the inputs and show the error message on all the invalid ones instead of showing one click submit then show another...etc

A: As a solution to my problem I have added a hidden error label below each input in the form template as follows
            template = "

 Customer ID *:

 {CustomerID}
";
            template += "
 Company Name:

{CompanyName}
";
             template +=
            template += "
 Phone:

{Phone}
";
            template +=
            template += "
 Postal Code:

{PostalCode}
";
            template +=
            template += "
 City:

 {City}
";
            template += "";
            template += "
";
            template += "
 {sData} {cData}

";

Changed the rules to be all custom
editrules: { custom: true, custom_func: emptyCheck } in Phone
editrules : { custom: true, custom_func: numberCheck } in PostalCode
editrules: { custom: true, custom_func: myCustomCheck } in Country

WHERE the custom functions are defined as follows. All that happens in the custom checks is check if something is valid and display the error label if it is not valid and return true regardless. Returning false in the custom check was the main problem of the validation not able to continue to the next field.
   // Add a global field invalid which would summarize the validation result
    var invalid = false;
 emptyCheck = function (value, colname) {

var label = $("label[for='" + colname + "']");
var input = $("#FrmGrid_grdEquipment").find('#' + colname);
    if (value) {
        label.addClass('hidden');
        input.removeClass("ui-state-error");
    }
    else {
        input.addClass("ui-state-error");
        label.html(colname+"is required");
        label.removeClass('hidden');
        invalid = true;
        // return [false, " Please correct the errors"];
    }

    return [true];

};
numberCheck = function (value, colname) {
    var label = $("label[for='" + colname + "']");
    var input = $("#FrmGrid_grdEquipment").find('#' + colname);
    if (!isNaN(parseFloat(value)) && isFinite(value)) {
        label.addClass('hidden');
        input.removeClass("ui-state-error");
    }
    else {
        input.addClass("ui-state-error");
        label.html(colname + "should be number");
        label.removeClass('hidden');
        invalid = true;
        // return [false, " Please correct the errors"];
      }

    return [true];
};

myCustomCheck = function (value, colname)
{
    // check validation display the error label if not valid
    return [true];
};

Finally add this to the  options for the Edit Dialog
onclickSubmit: function ((params, posdata) {
if (invalid)
    {
        invalid = false;
        return;
    }
      // Else save row and do other stuff
}


text:
Q: Equality Constrained Non Negative Linear Least Squares (Unit Simplex Constraint) I have the following constrained linear least-squares problem:
$$\min_{x \in \mathbb{R}^n} \frac{1}{2}||Ax-b||_2^2,$$
$$\text{subject to } \sum_{i=1}^n x_i = 1 \text{ and } x_i \geq 0, \text{ for } i=1,...,n.$$
If we discard the equality constraint, we have a standard non-negative least-squares (NNLS) problem, which can be solved by any NNLS solver.
On the other hand, if we discard the non-negativity constraints, we have a least-squares problem with an equality constraint, which can be solved in closed form (up to a matrix inverse calculation) by using Lagrange multipliers, for instance.
However, considering both constraints, I do not see any method that is particularly suitable for the problem. Of course, I could use the projected gradient descent method, but this one is pretty generic and does not exploit the linear least-squares nature of the problem.
My questions are:
1- Is there any numerical optimization algorithm that is particularly suitable for this problem?
2- Or can I reformulate the problem in a less constrained form so that can it be solved by a standard NNLS solver?
My attempt:
The Lagrangian is:
$$L(x,\lambda,\mu) = \frac{1}{2}||Ax-b||_2^2 + \lambda (\mathbf{1}^Tx - 1) - \mu^T x,$$
where $\lambda$ is a scalar, $\mu$ is $n$-dimensional and $\mathbf{1}$ is an $n$-dimensional vector of ones.
Thus, writing the KKT conditions, we get:
$$\begin{pmatrix}
A^TA & \mathbf{1} & -I \\
\mathbf{1}^T & 0 & \mathbf{0}^T \end{pmatrix}\begin{pmatrix} x \\ \lambda \\ \mu\end{pmatrix} = \begin{pmatrix}
A^Tb \\
1 \end{pmatrix}, \text{ } \mu_i \geq 0, \text{ and } \mu_i x_i = 0, \text{ for } i=1,...,n.$$
I don't know how to proceed from here, due to the complementary slackness constraints...

A: Your problem can be formulated as convex quadratic programming problem with a linear equality constraint and nonnegativity constraints on $x$.
$\min \frac{1}{2}\left( x^{T}(A^{T}A)x - 2(b^{T}A)x + b^{T}b \right)$
subject to
$\sum_{i=1}^{n} x_{i}=1$
$x \geq 0$.
As a practical matter, you're probably best off using a well-written library routine for linearly constrained quadratic programming.  There are many of them available in a variety of programming languages.  If you need to implement this yourself, then implementing an active set QP solver is relatively straight forward.


text:
Q: Mirroring Docker Traffic to Different Port in Same Container I am using docker containers on CentOS to simulate devices on the network and have two tools that are to run inside each of those containers to simulate communication with actual network devices.  Individually, either tool works inside the docker containers and can communicate with the outside world via one port we'll call 8000 here, but due to both attempting to use 8000, they are unable to run simultaneously.  To resolve this, I am looking to mirror traffic on 8000 to another port we'll call 8001 here so that one tool can run on 8000 while the other receives its packets on 8001.  In my Dockerfile, I EXPOSE both of these (though do not publish them in the run command).
Poking around the internet, I found this.  Attempting to adapt it to my purposes, I ended up with the below, which I execute from within docker exec -it <container> bash.  By my primitive understanding, it should copy the message to a different localhost IP's port 8000 while letting the original message through, then pass the duplicate packet back to 127.0.0.1:8001.
iptables -t mangle -A PREROUTING -p UDP --dport 8000 -j TEE --gateway 127.0.0.2
iptables -t nat -A PREROUTING -d 127.0.0.2 -p UDP --dport 8000 -j DNAT --to 127.0.0.1:8001

This does not appear to be working.  Running a tool on 8001 caused it to miss all packets I threw at 8000 from the outside world.
Similarly, I found this one, and tried adapting it to the below, but it doesn't seem to work either, and trying to get netcat running properly in a container has proven to be quite the headache.
iptables -A PREROUTING -t mangle -p tcp ! -s 127.0.0.1 --dport 8000 -j TEE --gateway 127.0.0.1
iptables -A OUTPUT -t nat -p tcp -s 127.0.0.1/32 --dport 8000 -j DNAT --to 127.0.0.1:8001

I am new to both docker and iptables, so any explanation of the underlying mechanisms of what is going wrong here would be greatly appreciated.

A: After a great deal of effort, the following solution was discovered that needs to run inside the container:
sysctl -w net.ipv4.conf.eth0.route_localnet=1
iptables -t mangle -A PREROUTING -i eth0 -p UDP --dport 8000 -j TEE --gateway 127.0.0.1
iptables -t nat -A PREROUTING -p UDP --dport 8000 -j DNAT --to-destination 127.0.0.1:8001

The key thing missing was the sysctl command to be run inside the container to allow things in the first place.  Then, it needed to be eth0 instead of the previous solutions as otherwise you would end up with infinite loops.


text:
Q: Redirect root to subdirectory apache I have an apache server with a WordPress website set up at root and a WordPress website in a subdirectory. I would like for the website in the subdirectory to be the default website. For example, when someone goes to www.example.com I would like for them to see the website that is actually located at www.example.com/newsite but the URL needs to stay the same, www.example.com.
Is doing something like that possible with say a 301 redirect or some other method?

A: check this out, you just need some htaccess changes:
https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory

A: You can simply move/copy the files to the root folder in case you are having root access.

cp -pR /path/to/rootfolder/subdirectory(wordpress)/* /path/to/rootfolder/

Thats it. Don't complicate by putting redirects.
In case you are having a control panel like cPanel, Its easy to put redirects. But as far as I concern moving/copying the files are more reliable.


text:
Q: You tried to call count_params on ..., but the layer isn't built. TensorFlow 2.0 I receive the following error in in Pyhotn 3 and TF 2.0.
"ValueError: You tried to call count_params on digits, but the layer isn't built. You can build it manually via: digits.build(batch_input_shape)." at line new_model.summary().
what is the problem and how to solve it?
inputs = keras.Input(shape=(784,), name='digits')
x = layers.Dense(64, activation='relu', name='dense_1')(inputs)
x = layers.Dense(64, activation='relu', name='dense_2')(x)
outputs = layers.Dense(10, activation='softmax', name='predictions')(x)

model = keras.Model(inputs=inputs, outputs=outputs, name='3_layer_mlp')
model.summary()

(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(60000, 784).astype('float32') / 255
x_test = x_test.reshape(10000, 784).astype('float32') / 255

model.compile(loss='sparse_categorical_crossentropy',
              optimizer=keras.optimizers.RMSprop(),
              metrics=['accuracy'])
history = model.fit(x_train, y_train,
                    batch_size=64,
                    epochs=2)

model.save('saved_model', save_format='tf')
new_model = keras.models.load_model('saved_model')
new_model.summary()

A: For 2.0 version Model can be saved in .h5 format, please use model.save('my_model.h5') while saving.
Please find the link of working gist.
Also issue seems to be resolved in the Latest TF-nightly version,as going forward 2.1 will be official version try using pip install tf-nightly
Find the link of working gist here.

A: I met the same error, and it solved after upgraded tf2.0 to tf2.1.

A: I had the same problem, I was using tensorflow==2.0.0. I tried running the same code using tensorflows nightly build (in my case pip install tf-nightly==2.1.0.dev20191003).
It worked on the nightly build but you may have to save the model again using the nightly build.

A: you can use the model properly if there is not the last line of you codes, that is to say you just can not use summary here.


text:
Q: How can I move elements from one array to another pseudo-randomly using a hash? Picture two different arrays:
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let newArr = [];

What I'm trying to achieve is moving elements from arr to newArr via a pseudo-random loop, that attempts to mimic the functionality of Math.random(), except that the only randomness should go against a fixed, hash number.
I was trying something like this, but no luck so far:
const madeUpHash = "827354819373"
const floatIndex = "0."
const f = parseFloat(floatIndex + madeUpHash);

let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let newArr = [];

for (let i = 0; i < arr.length; i++) {
  let ranNum = (f/i); // this points towards 0, meaning the next Math.Floor will eventually always retrieve index 0
    let rand = Math.floor(ranNum * arr.length);
    newArr.push(...arr.splice(rand, 1))
}

Not only does this not work, it's also pretty horrible.
Is there any reliable way to achieve this?
My other idea would be to loop through the individual digits of the hash (after transforming them into an array) and create a random number such as ranNum = i/madeUpHash[i] but that would break as soon as i >= madeUpHash[i] since it would return a positive integer bigger than one.
Any ideas? Thank you.

A: I'm not sure about how people are implementing Math.random in javascript, but I know it in C.
Basically, the idea is, you got a hash function hash, and a seed s, you apply hash(s) to get your X_0, and for X_(n+1), you do X_(n+1) = hash(X_n).
As long as you choose a good hash function with the certain distribution you want for your randomness, it's very easy and consistent if the seed is the same.
For C, they are doing Linear Congruential Generator
X_(n+1) = (a * X_n + b) % m

So you can use your hash number as a seed and generate a series of pseudo-random numbers. Basically, you need a place to store your seed and replace it when you call the random generator (and don't forget to apply the hash function).
The randomness totally comes from your choice of hash function and it's not easy to prove you get a good hash function to generate random numbers (like we want a uniform distribution hash function in most cases, and the performance matters too). But I believe there is literature to do those proofs for you.

A: Why do you divide ranNum by i?
let rand = Math.floor(f * arr.length);

Should be ok, because you decreasearr.length in each iteration. Also I'm not sure about incrementing i and removing an element from array, which affects the loop condition at the same time. Maybe just use the while loop.


text:
Q: How can I get missing values recorded as NULL when importing from csv I have multiple, large, csv files, each of which has missing values in many places. When I import the csv file into SQLite, I would like to have the missing values recorded as NULL for the reason that another application expects missing data to be indicated by NULL. My current method does not produce the desired result.
An example CSV file (test.csv) is:
12|gamma|17|delta
67||19|zeta
96|eta||theta
98|iota|29|

The first line is complete; each of the other lines has (or is meant to show!) a single missing item. When I import using:
.headers on
.mode column
.nullvalue NULL
CREATE TABLE t (
  id1     INTEGER  PRIMARY KEY,
  a1      TEXT,
  n1      INTEGER,
  a2      TEXT
);
.import test.csv t
SELECT
  id1, typeof(id1),
  a1,  typeof(a1),
  n1,  typeof(n1),
  a2,  typeof(a2)
FROM t;

the result is
id1   typeof(id1)  a1      typeof(a1)  n1  typeof(n1)  a2      typeof(a2)
----  -----------  ------  ----------  --  ----------  ------  ----------
12    integer      gamma     text      17  integer     delta   text
67    integer                text      19  integer     zeta    text
96    integer      eta       text          text        theta   text
98    integer      iota      text      29  integer             text

so the missing values have become text. I would appreciate some guidance on how to ensure that all missing values become NULL.

A: sqlite3 imports values as text and there does not seem to be a way to make it treat empty values as nulls.
However, you can update the tables yourself after import, setting empty strings to nulls, like
UPDATE t SET a1=NULL WHERE a1='';

Repeat for each column.
You can also create a trigger for such updates:
CREATE TRIGGER trig_a1 AFTER INSERT ON t WHEN new.a1='' BEGIN
  UPDATE t SET a1=NULL WHERE rowid=new.rowid;
END;

A: For the cases where you cannot update after import because the import will fail when the empty string (text columns) or 0 (integer columns) is inserted instead of NULL, see my answer to this other stackoverflow question


text:
Q: Django Action Stream error No Module named 'actstreamdjango' I am building a Django app, and wrote in the code as it exists on the documentation to use Action Streams.
This means:
'actstream' is in my INSTALLED_APPS
I copied ('^activity/', include('actstream.urls')) into my urlpatterns
and I copied the text in the Settings documentation to settings.py
and I get the error: No Module named 'actstreamdjango'
There is nothing else in the Get Started guide... what am I missing?


text:
Q: MySQL data not in correct order with PHP I have a messaging system on my site and I'm trying to group the messages into conversations, similar to how Facebook does. The following is the PHP code I'm using:
                    <form name="myform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
   New Message  <input type="submit" name="deleteBtn" class="btn btn-danger pull-right" id="deleteBtn" value="Delete Selected" />

    <?php
///////////End take away///////////////////////
// SQL to gather their entire PM list
$sql = mysqli_query($db_conx,"SELECT * FROM (SELECT * FROM private_messages WHERE to_id='$my_id' AND recipientDelete='0' ORDER BY time_sent DESC) AS tmp_table GROUP BY LOWER(from_id)");

while($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)){

    $item_date = $row["time_sent"];
    $convertedTime = ($myObject -> convert_datetime($item_date));
    $date = ($myObject -> makeAgo($convertedTime));
    //$date = strftime("%b %d, %Y",strtotime($row['time_sent']));
    if($row['opened'] == "0"){
            $textWeight = 'msgDefault';
    } else {
            $textWeight = 'msgRead';
    }
    $fr_id = $row['from_id'];
    // SQL - Collect username for sender inside loop
    $ret = mysqli_query($db_conx,"SELECT id, username, firstname, lastname FROM bs_mem_base389 WHERE id='$fr_id' LIMIT 1");
    while($raw = mysqli_fetch_array($ret, MYSQLI_ASSOC)){ $Sid = $raw['id']; $Sname = $raw['username']; $Sfirst = $raw['firstname']; $Slast = $raw['lastname'];
     if ($Sfirst != "") {$Sname = "$Sfirst $Slast";} } //}

?>

<a href="message.php?id=<?php echo $fr_id; ?>" class="<?php echo $textWeight; ?>">

<?php echo $date; ?> <input type="checkbox" name="cb<?php echo $row['id']; ?>" id="cb" value="<?php echo $row['id']; ?>" />

<?php echo $Sname; ?>

<?php echo stripslashes(wordwrap(nl2br($row['message']), 54, "\n", true)); ?>

<?php
}// Close Main while loop
?></form>

It's grouped them all together just fine, but they are not in the correct order. They're all jumbled. Any idea on how to order them so that the convo with the most recent message is first?

A: change this:
$sql = mysqli_query($db_conx,"SELECT * FROM (SELECT * FROM private_messages WHERE to_id='$my_id' AND recipientDelete='0' ORDER BY time_sent DESC) AS tmp_table GROUP BY LOWER(from_id)");

to this:
$sql = mysqli_query($db_conx,"SELECT * FROM (SELECT * FROM private_messages WHERE to_id='$my_id' AND recipientDelete='0' ORDER BY time_sent DESC) AS tmp_table GROUP BY LOWER(from_id) order by time_sent desc");

A: In MySQL, the GROUP BY performs an implicit ORDER BY. Sometimes, we can improve performance by suppressing the automatic sort, by adding an ORDER BY NULL.
But, if you need the rows returned in a specific sequence, then add an ORDER BY to the query.
Also note, due to way MySQL processes inline views, the resultset for the inline view gets materialized as a temporary MyISAM table (MySQL calls it a "derived table").
I don't believe your query is returning the resultset you are expecting.
I'm going to assume that one side of a "convo" is identified by the tuple (to_id,from_id), and the corresponding side of the convo is also identified by inverse tuple (from_id,to_id).
I'm also going to assume that you want to return all the private messages, and that by "grouped by" you mean that you want each convo to appear sorted together, with the convo with the latest private message listed first.
We can first get the latest "time_sent" of messages sent to us from each "from_id", with a query like this:
   SELECT n.from_id
        , n.to_id
        , MAX(n.time_sent) AS latest_time_sent
     FROM private_messages n
    WHERE n.to_id = '$my_id'
      AND n.recipientDelete='0'
    GROUP BY n.from_id, n.to_id
    ORDER BY MAX(n.time_sent) DESC, n.from_id DESC

If you are looking at this, and thinking, hey, we don't really need to return the to_id column, because it's always going to be the same value, you are right. As long as we can insure that $my_id doesn't contain some clever string, such as:
$my_id = "14' OR 'a'='a";

Of course, $my_id could contain even more nefarious SQL text, which we would probably really want to avoid including in our statement. But we'll set the SQL Injection issue aside, and focus on the question you asked.
Note that if we also wanted to consider messages "from" us, in terms of the latest_time_sent for the convo, (the inverse side, this query could be modified to do that. But, for now, we're assuming that we're looking only at the latest time a message was sent to us.
If we want to get just the latest message sent to us in each convo, the "trick" is to join the resultset from that previous query with the messages table, something like this:
SELECT p.*
  FROM private_messages p
  JOIN ( SELECT n.from_id
              , n.to_id
              , MAX(n.time_sent) AS latest_time_sent
           FROM private_messages n
          WHERE n.to_id = '$my_id'
            AND n.recipientDelete='0'
          GROUP BY n.from_id, n.to_id
          ORDER BY MAX(n.time_sent) DESC
       ) o
    ON o.from_id = p.from_id
   AND o.to_id = p.to_id
   AND o.time_sent = p.latest_time_sent
 WHERE p.recipientDelete='0'
 ORDER BY o.latest_time_sent DESC, o.from_id DESC

If we wanted to get all the messages in those convo, the trick is to match the rows in the message table with convo from the inline view, so that each row from messages gets "tagged" with the "latest_time_sent" for the convo.
Something like this:
SELECT p.*
  FROM private_messages p
  JOIN ( SELECT n.from_id
              , n.to_id
              , MAX(n.time_sent) AS latest_time_sent
           FROM private_messages n
          WHERE n.to_id = '$my_id'
            AND n.recipientDelete='0'
          GROUP BY n.from_id, n.to_id
          ORDER BY MAX(n.time_sent) DESC
       ) o
    ON ( o.from_id = p.from_id AND o.to_id = p.to_id )
    OR ( o.from_id = p.to_id AND o.to_id = p.from_id )
 WHERE p.recipientDelete='0'
 ORDER BY o.latest_time_sent DESC, o.from_id DESC, p.time_sent DESC

(Note that we are repeating the predicate on the recipientDelete column; and we are "matching" the rows from message to the rows from the inline view on the (from_id,to_id) tuple, as well as the inverse, so we get both sides of the convo.
Then, when we go to sort the rows, we do it first based on the latest_time_sent. Next, we order based on the identifier of the convo, that (from_id,to_id) tuple.  (Now it should be more clear the real reason we included the to_id from the inline view. (The other option would be reference $my_id again, in the join predicates.)
Finally, once the rows are ordered by convo, with the one with latest_time_sent first, we also order by time_sent.


text:
Q: Apigility Resource class methods I am using the Apigility to create Rest Web Services except that I have a doubt. Can I add methods in the class Resource? If so, how can I make a call to the method with php?
Thanks

A: Yes, you can add methods to you Resource, but they wont be called via API, in any way.
If you want to call them with PHP, then load resource by factory and call function.


text:
Q: Select if different from string sql I have a web app where users can fill forms and results are registered into a MySQL DB.
Here is the DB : USERS(id,name,email,extras)
If users use form #1, id, name and email are filled in DB.
If users use form #2, id and extras are filled in DB.
So I have a table like :
1 | John      | john@john.com     |

2 | Johnny    | johnny@johnny.com |

3 | undefined | undefined         | "name: Dumbo, email: dumbo@dumbo.fr"

I'd like to extract name and email from all rows where extras is empty : this query is okay.
I'd like to extract extras from rows where name and email are undefined. And combine these queries.
How can I do that?
Thanks.

A: SELECT * FROM USERS
WHERE COALESCE(extras) = '' OR
(name = 'undefined' AND email = 'undefined');


text: Q: What Lie supergroup does the super-Poincare algebra generate? Every Lie supergroup has an associated Lie superalgebra of generators (in general, some of which are bosonic and some fermionic).  Which Lie supergroup(s) are generated by the Super-Poincare algebra for $d$ spacetime dimensions and $N$ spinor generators (or, if $d \equiv 2 \text{ mod } 4$, $M$ left-handed and $N$ right-handed spinor generators)?


text:
Q: Calling function from other form textbox doesn't change I'm trying to call a method from a different form on buttonclick.
If I debug it it does go to the method that I'm trying to call, but as soon as I try to change a textbox inside this function it doesn't work.
Here is my function
public void addedtram(string tramno, string rail, string lineno, string sect)
    {
        String tbx = "tbx_sect" + 1 +"L"+ 2;
        TextBox tb = (TextBox)this.FindControl(tbx) as TextBox;
        if (tb != null)
        {
            tb.Text = tramno;
            tbx_sect10L1.Text = tramno;
        }
    }

I just put this in as a test, because I'm sure that the tbx exists but and with the debug it does say tb.Text = "1234"(example) but it doesn't show on my form.
Does anyone have a clue what the problem could be here?

A: If I understand you correctly, you should expose the contents of the textbox using a property:
class Form1 {
  public string txtbox {
    get { return textBox1.Text; }
  }
}

Then in Form2 do this:
var frm = new Form1();
textBox1.Text = frm1.txtbox;

You can make frm a class var of Form2 and call .Show() in the constructor of Form2.


text:
Q: Retrieve ACL of specific file with Google Cloud Storage Client Library for Java I currently have the following problem:
I would like to check the access control list of an object in my bucket on Google Cloud Storage from my App Engine App. I know I can set the ACL with the GcsFileOptions.Builder, but I want to read it from a specific file before passing it to the user.
I am not able to find a method with which this is possible. Am I missing something here or is the Google Cloud Storage REST API the only way to do this? (https://cloud.google.com/storage/docs/xml-api/get-object-acls). In that case: can anyone explain why this method is not available in the client library?

A: Maybe I am also missing something, but isn't it through the getAcl method of the GcsFileOptions class?
https://cloud.google.com/appengine/docs/java/googlecloudstorageclient/javadoc/com/google/appengine/tools/cloudstorage/GcsFileOptions.html#getAcl--
You first get the file metadata through getMetadata() on the gcs service and then get the GcsFileOptions via metadata.getOptions()


text:
Q: Condition on join tables - Rails My models:
class Review < ActiveRecord::Base
  belongs_to :business

class Business < ActiveRecord::Base
  has_many :reviews
  has_and_belongs_to_many :categories

I want to get the Reviews for businesses under a certain category:
Review.joins(:business => :categories).where(:business => {:categories => [1,2,3,4]})

The resulting query:
SELECT "reviews".* FROM "reviews" INNER JOIN
"businesses" ON "businesses"."id" = "reviews"."business_id" INNER JOIN
"businesses_categories" ON "businesses_categories"."business_id" = "businesses"."id"
INNER JOIN "categories" ON "categories"."id" = "businesses_categories"."category_id"
WHERE "business"."categories" IN (1, 2, 3, 4)

However, I am getting the following error:
ActiveRecord::StatementInvalid: PG::Error: ERROR:  missing FROM-clause entry
for table "business"
LINE 1: ...id" = "businesses_categories"."category_id" WHERE "business"...

A: Use this:
Review.joins(:business => :categories).where( :categories => { :id => [1,2,3,4] } )


text:
Q: key in charge -- how do you understand that? Please, take a listen: audio clip
Transcript:

Today it's really difficult for us to evaluate whether a particular fossil species is the ancestor of another one. You're always looking for the right anatomical features to link something up. In recent years, Meave Leakey, Richard's wife, has been running the Turkana field site. And today their daughter Louise is key in charge. And in 2001, Meave found a fossil skull on the west side of Lake Turkana. A fossil skull that was the same age as Australopithecus afarensis.

I'm not sure how I should understand that. Sure, to be in charge of something means to be in control of it—such as an enterprise or project. That's simple. But what I'm having real trouble with here is how the adjective key is used in conjunction with the expression in charge. If I said, "Who's key in charge here?", what would that possibly mean?

A: I think it's a simple error. They may have initially written *

is the key person

*, then changed it to *

in charge

*

*and overlooked deleting the word key.

The phrase key in charge sounds odd and like a bit of a duplication.


text:
Q: How to respond to HTTP GET with .net and XML How to respond to HTTP GET with c#/.net and XML
What I am trying to is when another service call posts to a get with say 5 parameters. This service would respond with an appropriate xml file.
Is WCF the way to go?
Any good examples out there?
Is this way easier/faster on some other platform?

A: One very easy option is to simply host an ASP.NET MVC web application ... you can have an action method that maps to the URL you are interested in which would take the parameters and return the XML:
http://asp.net/mvc

A: Pretty easy with .NET.
A good blog post on it here.
http://msmvps.com/blogs/omar/archive/2008/10/03/create-rest-api-using-asp-net-mvc-that-speaks-both-json-and-plain-xml.aspx

A: If you havve just one service method to support, then I'd say yes, use ASPNET: it's simple and easy.
If you are building a REST infrastructure and you want logging, multi-protocol capability, a variety of REST documents and verbs, and so on, then  I'd recommend WCF.


text:
Q: SQL Statement With 'Totals' as Final Column I'm trying to run an SQL query with the first column being 'month'. Each column will have a number value (or the month number) and the final column will say 'Totals'. The issue is that when I try to have them order, it gives me errors every time it reaches the Totals column because it is looking for an INT value. So, for example, I have this query:
SELECT CY.Month, CY.PaymentAmount_ThisYear, LY.PaymentAmount_LastYear FROM
(SELECT DATEPART(MM, Orders.OrderDate) AS Month, SUM(Orders.PaymentAmount) as PaymentAmount_ThisYear
    FROM Orders WHERE DATEPART(YY, Orders.OrderDate) = DATEPART(YY, DATEADD(MM, -1, CURRENT_TIMESTAMP))
    GROUP BY DATEPART(MM, Orders.OrderDate)
) CY
INNER JOIN
(SELECT DATEPART(MM, Orders.OrderDate) AS Month, SUM(Orders.PaymentAmount) as PaymentAmount_LastYear
    FROM Orders WHERE DATEPART(YY, Orders.OrderDate) = DATEPART(YY, DATEADD(MM, -13, CURRENT_TIMESTAMP))
    GROUP BY DATEPART(MM, Orders.OrderDate)
) LY
ON CY.Month = LY.Month
UNION
SELECT 'Totals' AS Month, CY.PaymentAmount_ThisYear, LY.PaymentAmount_LastYear FROM
(SELECT SUM(Orders.PaymentAmount) AS PaymentAmount_ThisYear
    FROM Orders WHERE DATEPART(YY, Orders.OrderDate) = DATEPART(YY, DATEADD(MM, -1, CURRENT_TIMESTAMP))
) CY,
(SELECT SUM(Orders.PaymentAmount) AS PaymentAmount_LastYear
    FROM Orders WHERE DATEPART(YY, Orders.OrderDate) = DATEPART(YY, DATEADD(MM, -13, CURRENT_TIMESTAMP))
) LY

If I changed 'Totals' to 13, it works and puts the totals at the bottom but the row says '13' instead of 'Totals'.

So what I then tried was at the very beginning of the query I changed this:
SELECT CY.Month

To
SELECT CAST(CY.Month AS VARCHAR(10)) AS Month

But when I do that it orders them wrong it goes:
1
10
11
5

Because it's recognizing them as varchar values. I'm basically looking for this to order the months numerically but then have the last column say 'Totals'.
I also tried to do an
ORDER BY
CASE ISNUMERIC(Month)
WHEN 1 THEN CAST(Month AS INT)
ELSE Month
END
But that was giving me an 'Ambiguous column name 'Month'.' error.
I'm sort of stuck, any ideas? Thank you!

A: I think you can simplify your query considerably and use the ROLLUP option of GROUP BY to do your totals, e.g.:
SELECT
      CASE
        WHEN GROUPING(MONTH(orders.orderdate)) = 1
        THEN 'Totals'
        ELSE CONVERT(CHAR(2), MONTH(orders.orderdate))
      END AS [Month]
    , SUM(
        CASE
            WHEN YEAR(orders.orderdate) = Datepart(yy, Dateadd(mm, -1, CURRENT_TIMESTAMP))
            THEN orders.paymentamount
            ELSE 0.00
        END
        )   AS PaymentAmount_ThisYear
    , SUM(
        CASE
            WHEN YEAR(orders.orderdate) = Datepart(yy, Dateadd(mm, -13, CURRENT_TIMESTAMP))
            THEN orders.paymentamount
            ELSE 0.00
        END
        )   AS PaymentAmount_LastYear
FROM
    orders
GROUP BY
    MONTH(orders.orderdate)
WITH ROLLUP

A: You could try putting the current query in an inline view and then ordering afterwards
SELECT Month, PaymentAmount_ThisYear, PaymentAmount_LastYear
FROM (
    SELECT CAST(CY.Month AS VARCHAR(10)) AS Month, CY.PaymentAmount_ThisYear, LY.PaymentAmount_LastYear FROM
        (SELECT DATEPART(MM, Orders.OrderDate) AS Month, SUM(Orders.PaymentAmount) as PaymentAmount_ThisYear
            FROM Orders WHERE DATEPART(YY, Orders.OrderDate) = DATEPART(YY, DATEADD(MM, -1, CURRENT_TIMESTAMP))
            GROUP BY DATEPART(MM, Orders.OrderDate)
        ) CY
    INNER JOIN
        (SELECT DATEPART(MM, Orders.OrderDate) AS Month, SUM(Orders.PaymentAmount) as PaymentAmount_LastYear
            FROM Orders WHERE DATEPART(YY, Orders.OrderDate) = DATEPART(YY, DATEADD(MM, -13, CURRENT_TIMESTAMP))
            GROUP BY DATEPART(MM, Orders.OrderDate)
        ) LY
    ON CY.Month = LY.Month
    UNION
    SELECT 'Totals' AS Month, CY.PaymentAmount_ThisYear, LY.PaymentAmount_LastYear FROM
        (SELECT SUM(Orders.PaymentAmount) AS PaymentAmount_ThisYear
            FROM Orders WHERE DATEPART(YY, Orders.OrderDate) = DATEPART(YY, DATEADD(MM, -1, CURRENT_TIMESTAMP))
        ) CY,
        (SELECT SUM(Orders.PaymentAmount) AS PaymentAmount_LastYear
            FROM Orders WHERE DATEPART(YY, Orders.OrderDate) = DATEPART(YY, DATEADD(MM, -13, CURRENT_TIMESTAMP))
        ) LY) T
ORDER BY CASE WHEN ISNUMERIC(Month) = 1 THEN 0 ELSE 1 END, Month


text:
Q: Fade effect with .hide() .show() in JQuery I found a nice method to split large post, on blogger, into multiple pages here: http://blogtimenow.com/blogging/splitting-long-blog-post-blogger/
I'm trying to add a fade effect when switching pages, but i don't know how to do this, i have no experience when it comes to jquery...
I managed so far to make the page scroll back to the top, and added some animations using time values, but it's not looking quite right.
jQuery(document).ready(function(){
jQuery('.page1').click(function(){
jQuery("html, body").animate({ scrollTop: 0 }, "slow");
jQuery('.content1').show(2000);
jQuery('.content2').hide(1000);
jQuery('.content3').hide(1000);
jQuery('.content4').hide(1000);
jQuery('.content5').hide(1000);

So basically what i want is the current "page" to fade out and the next "page" to fade in...

A: Use below code
below javascript will add effect fadeIn-fadeOut on page while switching the pages.
<script type="text/javascript">
            $(document).ready(function() {
                $("body").fadeIn(800);
                $("a").not(".no-fade").click(function(event){
                    event.preventDefault();
                    linkLocation = this.href;
                    $("body").fadeOut(400, redirectPage);
                });
                // Redirects page
                function redirectPage() {
                   window.location = linkLocation;
                }
            });
    </script>

*

*Put above code into <head> tag in your Html page

A: Add this code
jQuery(document).ready(function(){
jQuery('.page1').click(function(){
jQuery("html, body").animate({ scrollTop: 0 }, "slow");
jQuery('.content1').fadeIn(2000);
jQuery('.content2').fadeOut(1000);
jQuery('.content3').fadeOut(1000);
jQuery('.content4').fadeOut(1000);
jQuery('.content5').fadeOut(1000);


text:
Q: Why biopython built-in calculated proteins molecular weight is different from the one calculated by my code? mw = 0
n=0 # number of amino acid in each protein
Total=0 # total molecular weight after elimination of one molecule of water
for y,z in proteins[i].items():
    n+=z
    mw += ((weights[y]*z))
    Total=(mw-(18.015*(n-1)))

for sequence in SeqIO.parse("H:\\yeast.fasta","fasta"):
    analysed_seq = ProteinAnalysis(str(sequence.seq))
    print(sequence.id, sequence.seq, 'Mw : ', analysed_seq.molecular_weight())

First code gave me result 6760.
Second code gave me 7560.
What may be the difference for?

A: not sure but could be related to :
see here https://biopython.org/docs/1.76/api/Bio.SeqUtils.ProtParam.html
class Bio.SeqUtils.ProtParam.ProteinAnalysis(prot_sequence, monoisotopic=False)

Bases: object Class containing methods for protein analysis.
The constructor takes two arguments. The first is the protein sequence as a string, which is then converted to a sequence object using the Bio.Seq module. This is done just to make sure the sequence is a protein sequence and not anything else.
The second argument is optional. If set to True, the weight of the amino acids will be calculated using their monoisotopic mass (the weight of the most abundant isotopes for each element), instead of the average molecular mass (the averaged weight of all stable isotopes for each element). If set to false (the default value) or left out, the IUPAC average molecular mass will be used for the calculation.
try using both:
analysed_seq = ProteinAnalysis(str(sequence.seq, monoisotopic=False))

and :
analysed_seq = ProteinAnalysis(str(sequence.seq, monoisotopic=True))

but can't tell for sure unless you tell us how your weights function does calculate Mw
More on Biopython have a look at aa Mws in IUPACData.py
from (https://github.com/biopython/biopython/blob/c560c95b6575686b4e84637111d4a4bf070053ae/Bio/Data/IUPACData.py
starting at line 219 https://github.com/biopython/biopython/blob/c560c95b6575686b4e84637111d4a4bf070053ae/Bio/Data/IUPACData.py#L219

A: or if you are using second answers from here:  I need help to create a program that calculate molecular weight of each protein sequence in FASTA file of many sequences
that were borrowed from here : The Sum of molecular weight of proteins in python
you need to amend code :
weight = sum(weights[p] for p in seq)

in
weight = sum(weight_table[x] for x in seq) - (len(seq) - 1) * water

with  water = 18.0153  ( monoisotopic water = 18.010565)
see https://github.com/biopython/biopython/blob/c560c95b6575686b4e84637111d4a4bf070053ae/Bio/SeqUtils/init.py#L485
if the peptide is circular --> weight -= water
Take home lesson: never trust an SO unaccepted answer, test every bit of code, dont forget your biochemistry studies:
Amino acids bind to each other to make polypeptide chains via a condensation reaction, which involves the elimination of a water molecule for each bond formed.

A: mw = 0
n=0 # number of amino acid in each protein
Total=0 # total molecular weight after elemination of one molecule of   warter
for y,z in proteins[i].items():
    n+=z
    mw += ((weights[y]*z))
    Total=(mw-(18.015*(n-1)))

replace indentation last line :
mw = 0
n=0 # number of amino acid in each protein
Total=0 # total molecular weight after elemination of one molecule of   warter
for y,z in proteins[i].items():
    n+=z
    mw += ((weights[y]*z))

Total=(mw-(18.015*(n-1)))


text:
Q: Convert IP list to minimal CIDR representation I have a list of IP addresses that looks like this:
10.10.0.0
10.10.0.1
10.10.0.2
...
10.10.0.255
172.171.0.5
...
172.171.0.67

Is there a tool that can take such a list and compute the minimal CIDR representation for these IP addresses?
For instance, for the above example I would like to get the following output:
10.10.0.0/24
172.171.0.5/32
172.171.0.6/31
172.171.0.8/29
172.171.0.16/28
172.171.0.32/27
172.171.0.64/30

Edit: for clarification, the "minimal CIDR representation" would be the smallest set of CIDR IP addresses that contains all the IP addresses of my input file.

A: Using the builtin python module ipaddress suggested by @A.B in comment suggesting this post.
Either summarize_address_range (with start, end) or collapse_addresses (with a list) can be used.
For this case, the latter is more convenient.
import sys
import ipaddress

data = open(sys.argv[1],'r').read().splitlines()
ips = [ipaddress.IPv4Address(line) for line in data]
print('\n'.join([ip.with_prefixlen for ip in ipaddress.collapse_addresses(ips)]))

Usage and output:
$ python3 cidr.py file
10.10.0.0/24
172.171.0.5/32
172.171.0.6/31
172.171.0.8/29
172.171.0.16/28
172.171.0.32/27
172.171.0.64/30


text:
Q: Google-maps for Business Authentication Issue with Python-Requests I am having issues incorporating my new Business credentials into the Python-Requests module I had previously been using with the free user API key to create requests.
I have been following the authentication directions given by Google - (1) parsing the base URL into its path and query parts (2) decoding the private key to binary (3) creating a signature using this private key and the URL-encoded string using HMAC SHA1 (4) encoding the binary signature using base64
My code is as follows -
import requests
import csv
import json
import urlparse
import hashlib
import base64
import hmac
from pprint import pprint

url_raw = 'https://maps.googleapis.com/maps/api/directions/json&client=REMOVED'
Private_Key = 'REMOVED'

with open('./Origins.csv', 'rU') as csvfile:
    reader = csv.DictReader(csvfile)
    origincoords = ['{Y},{X}'.format(**row) for row in reader]

with open('./Destinations.csv', 'rU') as csvfile:
    reader = csv.DictReader(csvfile)
    destinationcoords = ['{Y},{X}'.format(**row) for row in reader]

results=[]

url = urlparse.urlparse('url_raw')

url_to_sign = url.path + '?' + url.query

decodedKey = base64.urlsafe_b64decode(Private_Key)

signature = hmac.new(decodedKey, url_to_sign, hashlib.sha1)

encodedSignature = base64.urlsafe_b64encode(signature.digest())

originalUrl = url.scheme + "://" + url.netloc + url.path + '?' + url.query

Full_URL = originalUrl + "&signature=" + encodedSignature

for i in range(0,(len(origincoords))):
    params ={'origin': origincoords[i],
          'destination': destinationcoords[i],
          'encodedSignature': encodedSignature}

    directions = requests.get(Full_URL, params=params).json()
    results.append(directions)

At this point I parse the results of the relevant information for my research. Thanks to @fredtantini for the help here previously.
The error message I am currently getting relates to a requests.exception, stating that I am not using a valid schema. However, in my code I have included the url.scheme in the originalUrl variable, which makes up part of the Full_URL which is used in the requests generation.

A: You are not parsing the value of url_raw. You are parsing the string with the contents 'url_raw':
url = urlparse.urlparse('url_raw')

Remove the quotes around url_raw, you want to parse the value associated with the variable, not a string that just happens to contain text that is equal to the variable name.
Demo:
>>> import urlparse
>>> url_raw = 'https://maps.googleapis.com/maps/api/directions/json&client=REMOVED'
>>> urlparse.urlparse('url_raw')
ParseResult(scheme='', netloc='', path='url_raw', params='', query='', fragment='')
>>> urlparse.urlparse(url_raw)
ParseResult(scheme='https', netloc='maps.googleapis.com', path='/maps/api/directions/json&client=REMOVED', params='', query='', fragment='')

Note how in the first case scheme is an empty string, while when parsing the actual URL the scheme is set to 'https' instead.
Next, you to produce the signature for the query string as a whole, not just the path plus client id.
You can best do that by creating a prepared request, after attaching the query parameters:
session = requests.Session()

for origin, destination in zip(origincoords, destinationcoords):
    params ={'origin': origin, 'destination': destination}
    request = requests.Request('GET', Full_URL, params=params).prepare()
    parsed_url = urlparse.urlparse(request.url)
    signature = hmac.new(decodedKey, '{}?{}'.format(parsed_url.path, parsed_url.query),
                         hashlib.sha1).digest()
    request.prepare_url(request.url, {'signature': base64.urlsafe_b64encode(signature)})
    response = session.send(request)
    directions = response.json()

    results.append(directions)

This uses a PreparedRequest object to produce the URL for us, so we can parse that again for ease of signing. The PreparedRequest.prepare_url() method then lets us add the signature to the URL of that object, after which we can easily send it with a session object.


text:
Q: Find formula structure for a complex function I am looking to find the function formula structure of a repeating function like the one in the image linked below....
Something that repeats indefinitely (like a sine wave) on the X-axis.  Anybody can help me.
http://i57.tinypic.com/29nbb15.jpg

A: Edit: the last answer didn't work for it was symmetrical
$$f(x) = \begin{cases}g(x)^2 & \text{ if } g(x)>0\\
                     \frac{g(x)^2}{9}& \text{ if } g(x) \leq 0\end{cases}$$ where $g(x) =2( x-[x])-1,5$


text:
Q: Django pre-save I'm working on my first project with Django ,it's a personal blog
the story model has 'beginning' filed that is first 100 characters of the story itself
I want to create beginning with pre_save but I got error always : in admin section when I add a story and leave the beginning blank ,Django say 'this field is required'!!
this works very good in another file
here is the code :
from django.db import models
from django.db.models.signals import pre_save

from my_blog_tags.models import Tag

# Create your models here.

class Story(models.Model):
    title = models.CharField(max_length=75)
    story = models.TextField()
    beginning = models.CharField(max_length=100)
    tags = models.ManyToManyField(Tag, blank=True)
    active = models.BooleanField(default=True)
    views = models.IntegerField(default=0)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = "story"
        verbose_name_plural = "stories"

def story_pre_save(sender, instance: Story, *args, **kwargs):
    if not instance.beginning:
        story = str(instance.story)
        instance.beginning = story[:100]

pre_save.connect(story_pre_save, sender=Story)

Screenshot from admin section:

A: The error you get originates from the fact that beginning is a required field. You can allow a form item to be blank with blank=True in the corresponding model field:
class Story(models.Model):
    # …
    beginning = models.CharField(max_length=100, blank=True)
I would also advise not to use a signals to set the beginning field if it is left blank. Signals are an antipattern. They are useful if you have models in another application, but if you have control over the model, it is not a good idea to work with signals.
A more elegant way to solve this might be the one advised by @schwobaseggl, where you have a property that either takes the beginning or slices the story, so:
class Story(models.Model):

    def get_beginning(self):
        return self.beginning or self.story[:100]
You can use this in a template with {{ mystory.get_beginning }}. If you do not specify a .beginning yourself, and you later update the .story, then the get_beginning will automatically return an updated sliced version.

A: There is not need to use singles you can override save method. To do this for you.
you just have to do something like this
    class Story(models.Model):
        beginning = models.CharField(max_length=100, blank=True, null=True)

    def save(self, *args, **kwargs):
        self.beginning = self.story[0:100]
        return super().save(*args, **kwargs)

It will automatically save the first 100 characters of your story.


text:
Q: Get the part of string after the delimiter The string format is
Executed: variable_name

What is the simplest way to get the *variable_name* sub-string?

A: foo="Executed: variable_name"
echo ${foo##* }     # Strip everything up to and including the rightmost space.

or
set -- $foo
echo $2

Unlike other solutions using awk, sed, and whatnot, these don't fork other programs and save thousands of CPU cycles since they execute completely in your shell. They are also more portable (unlike ${i/* /} which is a bashism).

A: With sed:
echo "Executed: variable_name" | sed 's/[^:]*: //'

A: Using awk:
echo 'Executed: variable_name' | awk -F' *: *' '{print $2}'
variable_name

A: If you have the string in a variable:
$ i="Executed: variable_name"
$ echo ${i/* /}
variable_name

If you have the string as output of a command
$ cmd
Executed: variable_name
$ cmd | awk '{print $NF}'
variable_name

Note that 'NF' means "number of fields", so $NF is always the last field on the line. Fields are assumed to be separated by spaces (unless -F is specified)
If your variable_name could have spaces in it, the
-F' *: *'
mentioned previously ensures that only the ": " is used as a field separator.  However, this will preserve spaces at the end of the line if there are any.
If the line is mixed in with other output, you might need to filter.
Either grep..
$ cmd | grep '^Executed: ' | awk '{print $NF}'

or more clever awk..
$ cmd | awk '/^Executed: /{print $NF}'


text:
Q: valgrind help required My application is causing 10m of memory leak in one scenario. But when i debugged with valgrind, the following is the leak summary.
812 ==18074== LEAK SUMMARY:
813 ==18074==    definitely lost: 0 bytes in 0 blocks.
814 ==18074==      possibly lost: 3,424 bytes in 20 blocks.
815 ==18074==    still reachable: 10,422 bytes in 47 blocks.
816 ==18074==         suppressed: 0 bytes in 0 blocks.

what could i derive from this summary? can i say that there is no problem with application?
can somebody explain the following also? what could be the issue in creating thread? I am not even passing something dynamically allocated as thread argument.
795 ==18074== 2,448 bytes in 17 blocks are possibly lost in loss record 32 of 33
796 ==18074==    at 0x40056BF: calloc (vg_replace_malloc.c:279)
797 ==18074==    by 0xC0D71A: _dl_allocate_tls (in /lib/ld-2.3.4.so)
798 ==18074==    by 0xD8A91E: pthread_create@@GLIBC_2.1 (in /lib/tls/libpthread-2.3.4.so)
799 ==18074==    by 0x8056A28: Server::intithreads() (ServerProcess.cpp:899)
800 ==18074==    by 0x8054E39: main (ServerProcess.h:85)

A: I wouldn't worry much about the "still reachable" blocks. Since all blocks are freed upon program exit, it isn't necessary to specifically free each block. To better the situation, you can try freeing blocks at intermediate stages in your program, beyond which you don't require them. On the other hand, "possibly lost" blocks are of slightly more serious nature.
In any case, from the Valgrind manual:

"Still reachable". This covers cases
  for the BBB blocks shown below. A
  start-pointer or chain of
  start-pointers to the block is found.
  Since the block is still pointed at,
  the programmer could, at least in
  principle, have freed it before
  program exit. Because these are very
  common and arguably not a problem,
  Memcheck won't report such blocks
  individually unless
  --show-reachable=yes is specified.

Pointer chain
-------------
RRR ------------> BBB
RRR ---> AAA ---> BBB

"Possibly lost". This covers cases for
  the BBB blocks shown below. This means
  that a chain of one or more pointers
  to the block has been found, but at
  least one of the pointers is an
  interior-pointer. This could just be a
  random value in memory that happens to
  point into a block, and so you
  shouldn't consider this ok unless you
  know you have interior-pointers.

Pointer chain
-------------
RRR ------?-----> BBB
RRR ---> AAA -?-> BBB
RRR -?-> AAA ---> BBB
RRR -?-> AAA -?-> BBB

A: There may be problems with your application according to the memory leak report.
If any of "definitely lost", "possibly lost" or "still reachable" are greater than 0, then you have a memory leak.
"Definitely lost" means that there was unfreed memory, and no variables pointing to it existed at program termination, because for example the variables went out of scope. This means that the leak will be difficult to fix, because you will need to find where you discarded them.
"Possibly lost" indicates that there was unfreed memory, and you did have variables pointing to it at program termination, but they were probably not usable to free the memory, because they were internal pointers, rather than pointers to the beginning of the block, which you need to pass to free.
"Still reachable" indicates that there was unfreed memory, but it was directly pointed to by variables at program termination. This means that although there is a leak, it is not one that can grow and so is not so serious.


text:
Q: How would I go about comparing a vector with itself, and removing elements according to a comparison function? I have a vector v, which I want to compare each, with every other element. For the sake of simplicity, in my example, the vector comprises of integers, and the comparison function is simply if (el1 == el2). As such, std::unique will not work, as my real list contains some data structure.
Below is an example of what I have tried so far, but it does not remove all duplicate elements as expected.
#include <iostream>
#include <vector>
#include <algorithm>

bool CompareElements(int el1, int el2)
{
    if (el1 == el2) { // Just as an example
        return true;
    } else {
        return false;
    }
}

int main()
{
    std::vector<int> v = {4, 1, 3, 2, 2, 3, 6, 2, 3, 1, 4, 3, 2, 3, 5, 6, 5};

    // Should remove el1 if CompareElements() returns true.
    v.erase(
        std::remove_if(v.begin(), v.end(), [&](int el1)
        {
            bool result = false;
            std::for_each(v.begin(), v.end(), [&](int el2)
            {
                result = CompareElements(el1, el2);
            });
            return result;
        }),
        v.end()
    );

    // Print the contents of v
    std::cout << "v = {";
    for (auto el : v)
       std::cout << el << ", ";
    std::cout << "}\n";

    return 0;
}

To reiterate, std::unique or any variation thereof would not work here, as I am trying to get this to work with a vector of custom data structures, and a simply duplicate remover will not work in my actual program, hence the use of the user-defined comparitor. The ordering of removal does not matter, I am just aiming to get one of the compared elements to removed from v so that that specific element is not compared with anything else.
What I would expect is something like
v = {1, 4, 2, 3, 6, 5}

But instead, I get
v = {4, 1, 3, 2, 2, 3, 6, 2, 3, 1, 4, 3, 2, 3, 6, }

Any help or pointers (get it?) would be greatly appreciated!

A: std::unique accepts a custom binary predicate. So, std::unique would work if you provided it with the custom function you already made.
#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> v = {4, 1, 3, 2, 2, 3, 6, 2, 3, 1, 4, 3, 2, 3, 5, 6, 5};
    v.erase(std::unique(v.begin(), v.end(), [](const int a, const int b)
        {
            return a == b;
        }), v.end());

    // Print the contents of v
    std::cout << "v = {";
    for (auto el : v)
       std::cout << el << ", ";
    std::cout << "}\n";

    return 0;
}

It also works if the type you provided has an implemented operator==.
struct Data
{
    Data(int _param)
        : m_Data{_param}
    {}

    int m_Data{};

    bool operator==(const Data& other) const
    {
        return m_Data == other.m_Data;
    }
};

int main()
{
    std::vector<Data> a{ 0,1,1,1,2,3,4,5 };

    a.erase(std::unique(a.begin(), a.end()), a.end());

    for (auto i : a)
        std::cout << i.m_Data << ", ";

    return 0;
}

A: If time complexity is not a huge deal for you, you can convert your vector to a set, then back to vector. The set will remove duplicates and you should be left with unique values.
v=vector<struct>(set<struct>(v.begin(), v.end()));
I believe the syntax is so or quite similar.
EDIT: There was a comment about this being wrong. Set can be replaced with unordered_set to remove sorting effect, although I'm not certainly sure about vector->set->vector conversion, that needs to be checked. But still, you can loop through the set and construct vector by yourself if the conversion is not supported.
In summary, you should be able to do this:
set<struct> st=set<struct>(v.begin(), v.end());
vector<struct> uniqvec=vector<struct>(st.begin(), st.end())

If ordering matters, changing set<struct> to unordered_set<struct> shall work as far as I know.


text:
Q: python calling classes dynamically I want to call python classes dynamically,
These are the classes that I want to call
class AutosoukModelMakeFuzzyComparisonModule:
    def __init__(self,configurationLoader=None, moduleConfigurationFile=None, settings=None):
        pass

and
class DefaultFuzzyComparisonModule:
    def __init__(self,configurationLoader, moduleConfigurationFile, settings = None):
        pass

and these too classes located in fuzzymodules folder
and I call them from ** FuzzyComparisonPipeline.py** which is in the same directory as fuzzymodules like this:
for module in FuzzyComparisonPipeline.fuzzyModules:
        name = module['name']
        configurationLoader = module['configurationLoader']
        moduleConfigurationFile = module['moduleConfigurationFile']
        settings = module['settings']
        module_to_import = __import__('fuzzymodules.'+name)
        instanceOfModule = getattr(module_to_import, name).__init__(configurationLoader, moduleConfigurationFile, settings)
        #instanceOfModule(configurationLoader, moduleConfigurationFile, settings)
    return item

I got this error:
   Traceback (most recent call last):
  File "path to my FuzzyComparisonPipeline.py", line 9, in process_item
    instanceOfModule = getattr(module_to_import, name).__init__(configurationLoader, moduleConfigurationFile, settings)
TypeError: module.__init__() takes at most 2 arguments (3 given)

and my question is how the init() takes 2 arguments, as you see, in both classes the init takes three arguments
Could you help please
i can't give you the whole code, because it is so complicated, everything else is working fine, i am sure of that, my problem is in calling that function.
the values of the for loop coming from this xml
<FuzzyComparison>
    <Modules>
        <Module>
            <name>AutosoukModelMakeFuzzyComparisonModule</name>
            <configurationLoader>DefaultLoader</configurationLoader>
            <configurationFile>MakesModels.conf</configurationFile>
            <settings></settings>
        </Module>
        <Module>
            <name>DefaultFuzzyComparisonModule</name>
            <configurationLoader>DefaultLoader</configurationLoader>
            <configurationFile>Buildings.conf</configurationFile>
            <settings>
                <attribute>building</attribute>
                <second>2222duxk fuck fuck</second>
            </settings>
        </Module>
    </Modules>
    </FuzzyComparison>

A: You are retrieving a module, not the class in the module; the __import__() function returns the top-level package, not the nested module itself.
You really want to use importlib.import_module() instead here, it behaves as you expect.
Next, you want to call the class object thus retrieved, not the __init__ method directly. Let Python call that for you, it'll do so to initialise the instance you create by calling the class:
from importlib import import_module

for module in FuzzyComparisonPipeline.fuzzyModules:
    name = module['name']
    configurationLoader = module['configurationLoader']
    moduleConfigurationFile = module['moduleConfigurationFile']
    settings = module['settings']
    module_to_import = import_module('fuzzymodules.' + name)
    instance = getattr(module_to_import, name)(configurationLoader, moduleConfigurationFile, settings)

A: From the documentation of __import__() -

__import__(name[, globals[, locals[, fromlist[, level]]]])
When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.

(Emphasis mine)
So in your case, the module - fuzzymodules is being returned - not the module containing your class.
You should specify the fromlist argument as name . Example -
module_to_import = __import__('fuzzymodules.'+name, fromlist=name)

Also , another issue is that you should not directly call the __init__() function of the class to create an object for it, instead call it directly, Example -
instanceOfModule = getattr(module_to_import, name)(configurationLoader, moduleConfigurationFile, settings)

__init__() function is called for initialization after the object has been created.


text:
Q: How do I get records in a Redis stream by position instead of ID? With XREAD, I can get count from a specific ID (or first or last). With XRANGE, I can get a range from key to key (or from first - or to last +). Same in reverse with XREVRANGE.
How do I get by position? E.g. "give me the last 10 records in order"? XREVRANGE can do it with XREVRANGE stream + - COUNT 10, although it will be backwards in order, and XRANGE will give me the first 10 with XRANGE stream - + COUNT 10, but how do I:

*

*get the last X in order?

*get an arbitrary X in the middle, e.g. the 10 from position 100-109 (inclusive), when the stream has 5000 records in it?

A: Redis Streams currently (v6.0) do not provide an API for accessing their records via position/offset. The Stream's main data structure (a radix tree) can't provide this type of functionality efficiently.
This is doable with an additional index, for example a Sorted Set of the ids. A similar discussion is at https://groups.google.com/g/redis-db/c/bT00XGMq4DM/m/lWDzFa3zBQAJ
The real question is, as @sonus21 had asked, what's the use case.

A:
It is an existing API that allows users to retrieve records from index
x to index y. It has a memory backend (just an array of records) and a
file one, want to put Redis in it as well.

We can just use Redis List to get the items randomly and at any offset using LRANGE
Attaching consumers to Redis LIST is easy but it does not come with an ack mechanism like a stream, you can build an ack mechanism in your code but that could be tricky. There could be many ways to build an ack mechanism in Redis, see one of them here Rqueue.
Ack mechanism is not always required but if you just want to consume from the LIST, you can use BLPOP/LPOP commands to consume elements from the list, that could be your simple consumer, but using BLPOP/LPOP commands would remove entries from the LIST so your offset would be dynamic, it will not always start from the 0. Instead of using BLPOP/LPOP, if you use LRANGE and track the offset in a simple key like my-consumer-offset, using this offset you can build your consumer that would always get the next element from the list based on the current offset.
Using LIST and STREAM to get random offset and streaming feature. Most important part would be you should use Consumer group so that streams are not trimmed. During push operation you should add element to STREAM as well as LIST. Once elements are inserted your consumer can work without any issue in a consumer group, for random offset you use LIST to get elements. Stream can grow as it'd be in append only mode, so you would need to periodically trim stream.  See my other answer for deleting older entries


text:
Q: Does Google Maps API provide statistical tools or even raster to vector conversion? I am working with a web developer who is working with Google maps API, trying to determine what pre-processing steps I should perform (e.g. in R and GRASS), and what can be done within the google maps API. This leads me to the following questions:

*

*Is there a way to convert raster to vector data in the google maps API?

*Are there any statistical tools associated with the API?

A: 1.- Nope, only the other way around.
2.- Not directly, but you can use Google Fusion Tables to do some basic queries, avg, max, min and some basic mathematical operations.

A: 1 - I don't know well the Gmap API but I don't think you can't vectorize data.
2 - Regarding statistic tool, it could be worth to use a JS stat library like Jstat before sending data to google. You can eventually use a server side library. Depending on your needs and the language you're using you will find something.
A global answer would be you need more than Gmap API.

A: Im no gmap expert, but i would say no to the former, and for the latter, you can calculate area and length (using libraries=geometry)  but not much more.

A: Typically I write runtime functionality like this using other libraries like ArcGIS Server or GDAL and expose this functionality to the client via web services (ArcGIS Server REST, ASP.NET, Java Web Services, PHP, etc), returning links to results, links to a new tile cache or geospatial data in KML or geoJSON.
There are certain operations, especially raster processing that just are not well supported in client side web programming yet.


text:
Q: Using withTaskCancellationHandler in MainActor-isolated context raises warnings In swift-concurrency, we will get a warning from Xcode when we use withTaskCancellationHandler in main-actor-isolated context as the attached screenshot.
How we can solve this warning? in case of using in main-actor context.

I think I can understand this warning means. Jumping into closure can't guarantee it runs on same context. Which is why closure sometimes needs to have Sendable.
But how about what if the closure is isolated in main-context(using @MainActor)?
I did some experiments - creating mostly same signatured method
func my_withTaskCancellationHandler<T>(operation: @MainActor () async throws -> T, onCancel handler: @MainActor @Sendable () -> Void) async rethrows -> T {
  fatalError()
}

Using Actor attributes is difference.
If we use this method in main-actor context, I suspect it no needs to have sendable. but it does not work as I expected. the same warning's raised.


text:
Q: impossible to pass js variable to php code i have this code

 function getPackage(id) {
     console.log(id)
     }
<button onClick="getPackage('.$rRow["id"].')" type="button" data-bs-toggle="modal" data-bs-target="#exampleModalScrollable" data-bs-placement="top" onClick="myFunction();" title="Download Playlist" class="btn btn-light waves-effect waves-light btn-xs" ><i class="mdi mdi-video-switch"></i></button>

so when i clic on button i pass the value of id to a function getPackage()
and i can see the value in console.log(id)
now i have a php code :
 <?php $rUser = getUser("61"); ?>

my question is how i can pass the value of js variable console.log(id) to my php code ?? i need to change the number "61" by the js variable id , for exemple like this :
<?php $rUser = getUser("id"); ?>

any one have idea ? thank you

A: By writing PHP code and JS in the same file as you did is to dynamic generate client's side HTML/JS code using PHP, the direction is [server->client], so using this method will never able to send information from client to server.
You've two solutions:

*

*Form submit [client->server] communication (involve page navigation or open new tab)

*AJAX (run in background, no page navigation involved)

You may try JQuery to ease up using JS
For option no.2
If you're using pure JS, then use this:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        // Typical action to be performed when the document is ready:
        document.getElementById("demo").innerHTML = xhttp.responseText;
    }
};
xhttp.open("GET", "your link", true);
xhttp.send();

If you're going to use JQuery, then use this:
$.ajax({
  url: "test.html",
  data: "param1=value1&param2=value2",
  method: "POST" // OR GET
}).done(function() {
  // X: Code here will only run after server responded
});

// Y: Code here will run first before X


text:
Q: Execute a function when the page is loaded angular I have this function selectHotel() which executes when the select box is clicked and I have used GET method to call data and display it on my view.
I have two options on my select area and it fetches different data for both of them. I want the data of my first option to be displayed when the page is loaded and not when I click the select box.

                <select ng-click="selectHotel()" class="form-control" ng-options='item as item.hotel_name for item in hotels.data' ng-model='current_Hotel'></select>
                Check In:<input type="date">
                Check Out:<input type="date">

{{current_Hotel.hotel_name}}

{{current_Hotel.hotel_description}}

            <btn class="btn btn-primary">Book a room </btn>

{{x.room_type}}Room Details

{{x.rack_price}}
Per room per night

            Adult: <select>
                <option>1</option>
                <option selected="selected">{{x.max_people}}</option>
            </select>
            Child: <select>
                <option>{{x.max_child}}</option>
            </select>

Here is the controller
var app = angular.module('myApp', []);
app.controller('ctrl1', function ($scope, $http) {
     $scope.current_Hotel = {
        hotel_id: "",
        hotel_name: "",
        hotel_description: "",
        exterior_image: "",
        image_url: ""
    };

    $http({
        url: '',
        method: "POST",
        data: 'postData',
        headers: {
            'Authorization': ''
        }
    }).then(function (response) {
                $scope.hotels = response.data;
                $scope.current_Hotel = $scope.hotels.data[0];
            });

    $scope.selectHotel = function () {
        $http({
            method: 'GET',
            url: '&image_id=' + $scope.current_Hotel.exterior_image
        }).then(function (response) {

                var imgdata = response.data;
                var imgdata1 = imgdata.data.image_name;
                $scope.current_Hotel.image_url = "" + imgdata1;
            });

         $http({
            method:'GET',
            url: '&hotel_id=' +$scope.current_Hotel.hotel_id
        }).then(function(response){
            $scope.roomdata = response.data;
        });

    };
});

A: Change your HTMl to invoke a changeHotel when different option is selected.
Invoke changeHotel after all the hotels are loaded passing the first item in the hotel list. This will load the data for the first hotel as per your necessity.
HTML:
<select ng-options="hotel as hotel.name for hotel in hotels"
        ng-model="currentHotel"
        ng-change="changeHotel(currentHotel)">
</select>

{{disp}}

JavaScript:
$http.get('API_URL')
  .then(function(res) {

    $scope.hotels = res.data;
    $scope.currentHotel = res.data[0];

    $scope.changeHotel($scope.currentHotel);

  });

$scope.changeHotel = function(hotel) {
  $scope.currentHotel = hotel;
  $scope.disp = "This is data for current hotel : " + $scope.currentHotel.name;
  // stuffs ...
};

Check this CodePen Demo