text:
Q: Ruby regex: "capture string unless it is followed by..." My regex captures quoted phrases:
"([^"]*)"

I want to improve it, by ignoring quotes, which are followed by ', -' (a comma, a space and a dash in this particular order).
How do I do this?
The test: http://rubular.com/r/xls6vN1w92

A: This should do it, using a Negative Lookahead:
"(?!, -)([^"]*)"(?!, -)

A little icky, but it works. You want to make sure either quote isn't followed by your string, or else the match will start at the closing quotes.
http://rubular.com/r/yFMyUKJOHL

A: Regex
"(.*?)"(?!, -)
Working Example
http://rubular.com/r/9kOmZLxLfy

A: This is unparsable in your context, its open ended. The only way to parse it is to consume the not's as well as the want's, but its still an invalid premise.
/"([^"]*?)"(?!, -)|"[^"]*?"(?=, -)/
Then check for capture group 1 on each match, something like this:
$rx = qr/"([^"]*?)"(?!, -)|"[^"]*?"(?=, -)/;
while (' "ingnore me", - "but not me" ' =~ /$rx/g) {
  print "'$1'\n" if defined $1
}

A: Add (?!...) at the end of the regex:
"([^"\n]*)"(?!, -)


text:
Q: Create custom home page with Jekyll I would like to create a custom "home" page using Jekyll's standard theme "Minima". By default it is set to a list of recent blog posts:
---
layout: default
---

Posts

  {{ content }}

    {% for post in site.posts %}

        {{ post.date | date: "%b %-d, %Y" }}

          {{ post.title | escape }}

    {% endfor %}

subscribe via RSS

This setup is controlled in a file _layouts/home.html. I have created my custom "home" page using Markdown. It is saved in my local directory and called "aboutme.md":
---
layout: page
title: About Me
permalink: /aboutme/
order: 1
---

This is a custom about me page.

I would like to override the default list of recent posts and replace it with my custom "aboutme" page. How can I achieve this in an elegant way? One way is to rewrite the "aboutme.md" in HTML and save it into "home.hml". However, it is doubling the work. I'm sure there must be a way to "include" an "aboutme.md" page in "home.html" with a simple Liquid command. I would also like to have the "About me" page displayed in the site menu.

A: You should rename your 'aboutme.md' file to 'index.md', remove the permalink statement and save it in the root of your website directory (and optionally rename the old index.md to blog.md).
Like this: (index.md)
---
layout: page
title: About Me
order: 1
---

This is now the homepage.

A: To customize home page, locate where your minima gem files are located in your system and copy _layouts/home.html to your Jekyll instance maintaining the directory structure .
/_layouts/home.html

There you can edit it as you wish, replacing the blog posts list with a link to an about me page or including an about me section.

*

*update

To include the contents of the "about me" page as a section of the home page, you can add the following code in your /index.md:
{% assign about = site.pages | where: 'name','about.md' %}
{{about}}

It looks for the filename called about.md and include its contents where you put that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swift 5.1 & Alamofire 5.1 : GET method ERROR when passing header and params: Alamofire.AFError.URLRequestValidationFailureReason.bodyDataInGETRequest(0 bytes)
 AF.request(urlString,method:.get, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { response in

              print(response)

 }

A: As of Apple's 2019 OS versions, trying to make a GET request with body data will fail with an error. The value must be nil. Alamofire provides it's own error here in order to provide a consistent experience for Alamofire users, regardless of which OS their code is running on.


text:
Q: Cannot route with logic to my Views from Backbone Router I try to make my router decide to show a login only home view, otherwise the login view or registerview.
my app is at initially localhost:8080/indexapp.
I load it at the data-main file. but the route tied to action that makes this decision is not triggered I think.
Is it possible to have a router with a route to be triggered on the page loaded.
Also, I have a commented one line that says this.loginModel.fetch(); which causes undefined is not a function error.
    define([
    'jquery',
    'ratchet',
    'underscore',
    'backbone',

    'login/loginview',
    'login/loginmodel',
    'register/registerview',

    'home/homeview',
    ],
    function($, Ratchet, _, Backbone, LoginModel, LoginView, RegisterView, HomeView){
        var MainRouter = Backbone.Router.extend({
            routes: {
                "": "showHome",
                //"/": "showHome",

                "login": "showLogin",
                "register": "showRegister"
            },
            initialize: function(){
                Backbone.history.navigate("home", {trigger:true})
            },
            showHome: function(){
                //var self = this, loginModel = new LoginModel();
                this.loginModel = new LoginModel();
                //this.loginModel.fetch();

                if(this.loginModel.get('loginp') == true ){
                    this.homeView = new HomeView();
                    this.homeView.render();
                }
                else {
                    Backbone.history.navigate("/login", {trigger:true})
                }
                /*
                this.loginModel.fetch({
                    success: function(model){
                        if( model.get('loginp') == true ){ //show you app view for logged in users!
                            this.homeView = new HomeView();
                            this.homeView.render();
                        }
                        else { //not logged in!
                            Backbone.history.navigate("/login", {trigger:true})
                        }
                    },
                });
                */
            },
            showLogin: function(){ //display your login view
                this.loginView = new LoginView;
                //this.loginView.fetch();
                this.loginView.render();

            },
            showRegister: function(){ //display your register view
                this.registerView = new RegisterView;
                //this.registerView.fetch();

                this.registerView.render();
            },
        });

        return MainRouter;
});

loginmodel:
    define([
    'underscore',
    'backbone',
    ],
    function(_, Backbone) {
        var LoginModel = Backbone.Model.extend({

            urlRoot: '/login',
            initialize: function(){
                this.fetch();
            },
            defaults: {
                username: null,
            },

        });

        return LoginModel;
});

loginview:
define([
    'jquery',
    'ratchet',
    'underscore',
    'backbone',

    'login/loginmodel',
    'text!login/logintemplate.html',

    ],
    function($, Ratchet, _, Backbone, LoginModel, LoginTemplate){
        var LoginView = Backbone.View.extend({

            el: $('body'),

            model: new LoginModel,
            /*
            initialize: function(){
                this.model = new LoginModel;
            },
            */
            template: _.template( LoginTemplate ),

            render: function(){ //display your login view
                this.$el.html( template( this.model.attributes ) );
            },

        });

        return LoginView;
});

A: Glad to see you're following my idea! ;)
The only thing you're missing is to start up routing using Backbone.history.start() on $(document).ready.
http://backbonejs.org/#Router
It works this way: you need to instantiate your router(s) before calling Backbone.history.start().
So in your main app file, require your MainRouter, create one instance and start history.
$(document).ready(function(){
  new MainRouter();
  Backbone.history.start();
});


text:
Q: pretrained object detection models in keras There are pretrained object recognition models in keras.applications library. But as far as I know, there is no pretrained object detection model available.
Does anyone know why it is the case? Object detection is a big part of problems when dealing with visual problems.

A: That is because vanilla Keras does not include implementation of methods/models for object detection.
There are many approaches to object detection with deep learning (see Object Detection with Deep Learning: A Review for a survey), but none of them are implemented as a part of Keras library, so no official models as well. I have a feeling that François Chollet tries to keep it simple and minimalistic, so bloating the code with something like TensorFlow models will be against its philosophy.
However, Keras is easily extendable, so there are plenty of unofficial implementations (e.g. SSD or Mask R-CNN) supplied with the trained models though. See Keras model zoo for more.

A: Though applications module has no object detection models included, the repo provides links to some of the community implementations. https://github.com/keras-team/keras-applications#reference-implementations-from-the-community


text:
Q: Pass the names of the selected files from "Send To" menu to powershell script I have a script that I wrote that is added to the "Send To" menu already, and it asks for a search string and then searches every .log and .txt file in that directory for the string.
But what I need it to do is look at the file I am right clicking on and collect the name so I can use it as the only file to search in.
So if you can help me grab the name of the file I am right clicking on, and then "send to" my PowerShell script.
Thanks

A: Create a shortcut in your "SendTo" folder:

*

*Press Win+R, enter shell:sendto

*Create a shortcut with this target:

*

*for Windows PowerShell:
"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -File "FullPathToYourScript.ps1"

*for PowerShell 7+:
"%ProgramFiles%\PowerShell\7\pwsh.exe" -File "FullPathToYourScript.ps1"

When the "Send to" menu item is invoked, the system appends the full paths of the selected files to the commandline. In your PowerShell script, use the automatic $args array variable to get the file paths from the commandline arguments.
This demo shows how you can get the number of selected files and loop over the paths:
"Received $($args.Count) files:"

foreach( $path in $args ) {
    "Processing file: $path"
}


text:
Q: How did -ing become a suffix for both present participles and nouns derived from verbs? In non-modern and non-Middle-English Germanic languages, present participles and nouns derived from verbs look and sound very different:

*

*English: wend - wending - wending

*Middle English: wenden - wendynge/wendende - wending/wendyng

*Old English: wendan - wendende - wending

*German: wenden - wendend - Wendung

*Dutch: wenden - wendend - wending

*Danish: vende - vendende - vending

*Icelandic: venda - vendandi - vending

*Swedish: vända - vändande - vändning

(In order from left to right, infinitive verb - present participle - noun)
Notice how only in modern English are the verbal present participle and noun identical in form.
Both the Wikipedia article and Wiktionary entries for -ing say it's a fusion of the Middle English present participle suffix -ynge and the nominalizing suffix -ing/-yng. The participial suffix was altered from the Old English -ende, which remained a variant in Middle English. This means if the distinction between these two suffixes remained, we would be saying something like "They are *buildend that building", rather than "They are building that building". Neither of those wikis, however, elaborates on why there was such a fusion.
The Online Etymology Dictionary has an interesting claim, albeit very brief and vague:

The vowel weakened in late Old English and the spelling with -g began 13c.-14c. among Anglo-Norman scribes who naturally confused it with -ing (1)

If I'm reading this correctly, it was the French who caused the fusion, because of their own confusion. This French fusion and confusion simply solidified sometime during the Middle English period. I've contacted the author of the Online Etymology Dictionary and am waiting to hear back.
In the meantime, though, I have one hypothesis. It does make sense that the French elite could've confused the participial suffix -ende and the nominal suffix -ing. From my understanding, Latin and its daughter French do love to make verbal nouns precisely from present participles. So even though the Germanic suffixes are not related, their French counterparts are. This Latin and French method left its mark all over English:

*

*Latin: ignōrāre - ignōrantem - ignōrantiam

*French: ignorer - ignorant - ignorance

*Middle English: ignoren - ignorant - ignora(u)nce

*English: ignore - ignorant - ignorance

*

*Latin: vacāre - vacantem - vacantiam

*French: vaquer - vacant - vacance

*English: n/a - vacant - vacancy

*

*Latin: condolēre - condolentem - condolentiam

*French: condouloir - condoléant - condoléance

*English: condole - condolent - condolence

*

*Latin: dēpendēre - dēpendentem - dēpendentiam

*French: dépendre - dépendent - dépendence

*English: depend - dependent - dependence/dependency
(In order from left to right, infinitive verb - accusative present participle - accusative noun)
So because it was the norm for them to make nouns out of present participles, the French probably ended up applying their French mindset to treating the English suffixes, confused them and eventually altered them and fused them.
This is just my educated hypothesis. It's not very easy to do research on this, Googling hasn't proven fruitful. Anyone who could confirm with a source would be greatly appreciated.


text:
Q: Python Default Confusion Upon running python in any dir in my amazon EC2 instance, I get the following printout on first line: Python 2.6.9 (unknown, todays_date). Upon going to /usr/bin and running python27, I get this printout on first line: Python 2.7.9 (default, todays_date).
This is a problem because the code that I have only works with Python 2.6.9, and it seems as though my default is Python 2.7.9. I have tried the following things to set default to 2.6:
1) Editing ~/.bashrc and creating an alias for python to point to 2.6
2) Editing ~/.bashrc and exporting the python path
3) Hopelessly scrolling through the /etc folder looking for any kind of file that can reset the default python
What the hell is going on?!?! This might be EC2 specific, but I think my main problem is that upon running /usr/bin/python27 I see that it is default on that first line.
Even upon running python -V, I get Python 2.6. And upon running which python I get /usr/bin/python, but that is not the default that the EC2 instance runs when it attempts to execute my code. I know this because the EC2 prints out Python/2.7.9 in the error log before showing my errors.

A: Creating an alias in your ~/bashrc is a good approach.
It sounds like you have not run source ~/.bashrc after you have edited it. Make sure to run this command.
Also keep it mind that when you run sudo python your_script.py it will not use your alias (because you are running as the root, not at the ec2-user).
Make sure to not change your default python, it could break several programs in your linux distributions (again, using an alias in your ~/bashrc is good).


text:
Q: jQuery is not working in webpage? I am using jQuery but its not working in my webpage.
jquery-1.10.2.min.js is used for TAB and jquery.lightbox-0.5.js" is used for Photo gallery with jquery.js scripting file.
Now though it shows the tab buttons and the thumbnails of the gallery, when I click on the tabs the tab doesn't work and photo gallery doesn't work too.

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

        <link rel="stylesheet" type="text/css" href="css/jquery.lightbox-0.5.css" media="screen" />


text:
Q: How to display the name of a supervisor for a certain worker MYSQL Display the name of McLester's supervisor.
Using standard syntax
select sup.lastname "Supervisor's Name"
from staff e, staff sup
where e.supervisorno = sup.staffno and lastname = 'McLester';

Here is the table
I think I need to connect staffno and supervisorno. But it does not seem to work. Any Ideas why?
Here is a screenshot to the table https://prnt.sc/on3er7

ERROR 1052 (23000): Column 'lastname' in where clause is ambiguous

To replicate the problem:
Drop Table Staff;

Create Table Staff
 (StaffNo  varchar(6) Primary Key,
  Lastname  varchar(30),
  Firstname varchar(25),
  Hire_date  date,
  Location  varchar(30),
  SupervisorNo  varchar(6),
  Salary  numeric(8,2),
  Commission  numeric(4,2));

-- Populate Staff Table ------------------------------------------

Insert Into Staff
Values('000001','Zambini','Rick',Date('1980-2-15'),'LOS ANGELES','000000',6000.00,5.00);
Insert Into Staff
Values('000003','Vidoni','Cheryl',Date('1980-3-6'),'NEW YORK','000000',5780.00,5.00);
Insert Into Staff
Values('000004','Coudray','Sandy',Date('1980-6-6'),'LOS ANGELES','000001',6237.00,5.00);
Insert Into Staff
Values('000006','Thomas','Pat',Date('1991-1-8'),'NEW YORK','000003',5875.00,5.00);
Insert Into Staff
Values('000008','McLester','Debbie',Date('1981-4-12'),'LOS ANGELES','000001',4792.00,5.00);
Insert Into Staff
Values('000011','Michaels','Delores',Date('1982-5-5'),'CHICAGO','000012',4927.00,7.00);
Insert Into Staff
Values('000012','Charles','Ted',Date('1983-2-2'),'CHICAGO','000000',5945.00,5.00);
Insert Into Staff
Values('000013','Marin','Mark',Date('1983-6-5'),'LOS ANGELES','000001',4802.00,11.00);
Insert Into Staff
Values('000015','Roddick','Mary',Date('1984-2-13'),'NEW YORK','000003',5493.00,8.00);
Insert Into Staff
Values('000016','Long','Nicole',Date('1984-8-18'),'NEW YORK','000003',5190.00,7.00);
Insert Into Staff
Values('000019','Rolfes','Chuck',Date('1984-9-9'),'LOS ANGELES','000001',4586.00,6.00);
Insert Into Staff
Values('000020','Sanders','Kathy',Date('1985-3-23'),'CHICAGO','000012',3783.00,5.00);

COMMIT;

A: Just use proper joins and column aliases:
select sup.lastname "Supervisor's Name"
from Staff e inner join Staff sup
on e.supervisorno = sup.staffno
where e.lastname = 'McLester';

See the demo.
Result:
| Supervisor's Name |
| ----------------- |
| Zambini           |


text:
Q: How do I use JavaScript/jQuery to populate multiple divs dynamically? I apologise in advance, I'm not allowed to post images until I have 10 reputation. So, I hope that my description would be enough to get across the idea I have.
So, say I have three columns; a, b, and c. And when there's too much content to be hosted in just a, b, and c, I'd want new off-screen columns to be made, d, e, and f. - This goes on until all the content is used.
So, my current setup has the "hidden-text" div play host to all the content, and then I'd have a JavaScript function, or jQuery function to dynamically populate each of the divs, and create divs where needed along with buttons to then get to the new divs it creates.
The way it determines which to populate is simply grabbing the content and putting it into column a. Column a is full when the content reaches the bottom of the screen. Then it grabs the rest of the content and puts it in b, until b is full and so on until all the content available is used.
I really hope I'm being clear enough, I have no idea if anyone is going to even remotely understand what I'm trying to say... Any help at all is much appreciated!
Here's a code snippet of how the HTML is structured, maybe it'll help someone understand what I mean... Thanks again, everyone!

   This is the content I would like to have displayed across the three divs above.

Here is some JS that I have so far and I'm rather stuck on where to go from here:
function Populate(){
//paragraph is equal to all of the content in the hidden-text div
var paragraph = document.getElementById('hidden-text').innerHTML;
var newParagraph = "";

//the variable div would play host to the names of each of the divs in the HTML
var div = "";
//words stores each character of paragraph and passes them into the new paragraph
var words = "";

for (words in paragraph)
{
    newParagraph += paragraph[words];
}
//the column with the name equal to the value of the div variable gets populated by the value of newParagraph
document.getElementByClassName(div).innerHTML = newParagraph;}

A: I think it should be something like this:
var divs = ['a', 'b', 'c'];
var word_limit = 50;
var paragraph_words = paragraph.split(' ');
for (var i = 0, div_index = 0; i < paragraph_words.length && div_index < divs.length; i++) {
    newParagraph += ' ' + paragraph_words[i];
    if (i > 0 && i % word_limit == 0) {
        document.getElementsByClassName(divs[div_index])[0].innerHTML = newParagraph;
        div_index++;
        newParagraph = '';
    }
}
if (newParagraph) { // If we didn't fill up the last DIV
    document.getElementsByClassName(divs[div_index])[0].innerHTML = newParagraph;
}


text:
Q: VBA defining a range from an array So I have a 2d array with 1000 rows and 10 columns. I want to create 10 ranges for each of the 10 columns and then use them as series to make a chart. MY question is, how do I define a range from an array, without using the entire array, just one column in it?
Sub ChartLord()

    Dim rows As Long
    Dim columns As Integer
    Dim mychart As Chart
    Dim data As Range
    Dim dataset() As Double

    rows = ShData.Cells(ShData.rows.Count, 1).End(xlUp).Row
    columns = ShData.Cells(1, ShData.columns.Count).End(xlToLeft).Column

    'set array range (includes column titles and xAxix column)
    dataset = ShData.Range(ShData.Cells(1, 1), ShData.Cells(rows, columns))

    For Z = 0 To 10

        Set data = ?
        Set mychart = shtCharts.Shapes.AddChart2(200, xlColumnClustered, 50 + 300 * Z, 50, 300, 200, 5).Chart

    Next Z

End Sub

A: The following will collect your range values into a 2D range then slice off the second column into a new 2D array. The latter is simply 1 to 1 'column' wide.
Dim rws As Long, cols As Long, d As Long
Dim dataset() As Variant, subdataset() As Variant
Dim ShData As Worksheet

Set ShData = Worksheets("Sheet4")

rws = ShData.Cells(ShData.rows.Count, 1).End(xlUp).Row
cols = ShData.Cells(1, ShData.columns.Count).End(xlToLeft).Column

'set array range (includes column titles and xAxix column)
dataset = ShData.Range(ShData.Cells(1, 1), ShData.Cells(rws, cols))

subdataset = Application.Index(dataset, 0, 2) '<~~second column
For d = LBound(subdataset, 1) To UBound(subdataset, 1)
    Debug.Print subdataset(d, 1)
Next d

ShData.Cells(1, "Z").Resize(UBound(subdataset, 1), UBound(subdataset, 2)) = subdataset

The last operation puts the values of the peeled off column back into the worksheet starting at Z1.


text:
Q: Debugging Cucumber Ruby in VS Code. Error : No such file or directory - exec I am trying to configure VS Code to debug Ruby and Cucumber
I followed this article to configure the VS Code : https://www.kloia.com/blog/development-environment-configuration-with-vscode-ruby-cucumber
I am getting Error: No such file or directory - exec. You can use cucumber --init to get started.
I did searched on google, I found that cucumber is searching for features folder, but I already specified it launch config settings of VS Code.
Launch Configuration for VS Code :
"configurations": [
      {
        "name": "Cucumber",
        "type": "Ruby",
        "request": "launch",
        "cwd": "${workspaceRoot}",
        "program": "${workspaceRoot}/bin/cucumber",
        "useBundler": true,
        "args": [
          "exec",
          "cucumber",
          "${workspaceRoot}/features",
          "-t",
          "@set_1"
        ]
      }
    ]

A: Solved: This issue by removing "exec" and "cucumber" both from args parameter in launch config. As these are passed to Cucumber::Cli::Main.rb as arguments of cucumber as paths option, hence cucumber tries to find feature files at exec and cucumber paths and hence throws error.
I hope article mentioned in question make correction.


text:
Q: Reading pixel data from xvfb So I'm having a strange problem with xvfb. Basically I have an application running through xvfb like so:
Xvfb :1 -screen 0 1920x1080x24+32 -fbdir /var/tmp &
export DISPLAY=:1
gimp &

And then I read the pixel data from the file like this:
#include <string>
#include <string.h>
#include <thread>
#include <math.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

char *fbp1 = 0;
int fbfd1;
long int screensize1;

int main() {
        fbfd1 = 0;
        screensize1 = 0;
        fbfd1 = open("/var/tmp/Xvfb_screen0", O_RDWR);

        screensize1 = 1920 * 1080 * 4;
        fbp1 = (char*)mmap(0,
              screensize1,
              PROT_READ | PROT_WRITE,
              MAP_SHARED,
              fbfd1,
              0);

        for (int i = 0; i < 1000; i++) {
                cout << ((int*)fbp1)[i] << endl;
        }
        return 0;
}

For some reason when I print out the first 1000 elements or so of the buffer it prints out a bunch of random data before it starts printing the actual visual on the screen.
Any help would be greatly appreciated!

A: As stated here, your file isn't just a pixel array, but in xwd format.
You can learn more about this format in your platform-specific xwdfile.h header and use e.g. xwud utility source to learn how it's been done before you.


text:
Q: EasyPhp Foreign Key I have a problem with EasyPHP. I have a web page un php, with a database creation script, which i think is right, but i do not understand why the "on delete cascade" doesn't work.
Here is my script :
//Création de la table Enquete
$tabenq = "CREATE TABLE IF NOT EXISTS 1_Enquete (
idEnquete INT NOT NULL AUTO_INCREMENT,
nomEnquete VARCHAR(255) NOT NULL,
PRIMARY KEY (idEnquete));";
//Création de la table rubrique
$tabrub = "CREATE TABLE IF NOT EXISTS 2_Rubrique (
idRubrique INT NOT NULL AUTO_INCREMENT,
nomRubrique VARCHAR(255) NOT NULL,
idEnquete INT NOT NULL,
PRIMARY KEY (idRubrique),
INDEX idEnq_ind (idEnquete),
FOREIGN KEY (idEnquete) REFERENCES 1_Enquete(idEnquete) ON DELETE CASCADE);";
//Création de la table Q1
$tabq1 = "CREATE TABLE IF NOT EXISTS 3_Q1 (
idQ1 INT NOT NULL AUTO_INCREMENT,
libelleQ1 VARCHAR(255) NOT NULL,
idRubrique INT NOT NULL,
PRIMARY KEY (idQ1),
INDEX idRub_ind (idRubrique),
FOREIGN KEY (idRubrique) REFERENCES 2_Rubrique(idRubrique) ON DELETE CASCADE);";
//Création de la table Q2
$tabq2 = "CREATE TABLE IF NOT EXISTS 4_Q2 (
idQ2 INT NOT NULL AUTO_INCREMENT,
libelleQ2 VARCHAR(255) NOT NULL,
idQ1 INT NOT NULL,
PRIMARY KEY (idQ2),
INDEX idQ1_ind (idQ1),
FOREIGN KEY (idQ1) REFERENCES 3_Q1(idQ1) ON DELETE CASCADE)";
//Création de la table Campagne
$tabCamp = "CREATE TABLE IF NOT EXISTS 5_Campagne (
idCampagne INT NOT NULL AUTO_INCREMENT,
dateCampagne DATE NOT NULL,
idEnquete INT NOT NULL,
PRIMARY KEY (idCampagne),
INDEX idEnqCamp_ind (idEnquete),
FOREIGN KEY (idEnquete) REFERENCES 1_Enquete(idEnquete) ON DELETE CASCADE);";

DB architecture in EasyPHP
There is no link between tables, and i don't understand why... does anyone have a clue?


text:
Q: Apache .htaccess redirects for URL's with Arabic characters I have been trying to add some .htaccess redirection rules for URL's with parts in Arabic. Obviously, I am using the Arabic part, URL encoded, but still Apache seems to not be able to resolve the URL, either catch it in the condition or redirect it. Does anyone have any experience on the subject?
This is one line from the config file
RewriteRule ^arabic/%D8%AE%D9%85%D8%B3-%D8%B7%D8%B1%D9%82-%D9%84%D8%B2%D9%8A%D8%A7%D8%AF%D8%A9-%D8%B3%D8%B1%D8%B9%D8%A9-%D8%A7%D9%84%D8%A8%D8%B1%D9%88%D8%AF%D8%A8%D8%A7%D9%86%D8%AF(.*)$ /blog/sa-ar/%D8%AE%D9%85%D8%B3-%D8%B7%D8%B1%D9%82-%D9%84%D8%B2%D9%8A%D8%A7%D8%AF%D8%A9-%D8%B3%D8%B1%D8%B9%D8%A9-%D8%A7%D9%84%D8%A8%D8%B1%D9%88%D8%AF%D8%A8%D8%A7%D9%86%D8%AF/$1 [R=301,L]

A: I had the same problem with "م" which is "%D9%85"
Just use this:
RewriteRule ^arabic/([\s\S]*)$ /blog/sa-ar/$1

that worked for me!
In fact you have to use ^([\s\S]*)$ instead of ^(.*)$


text:
Q: indexOf deletes the wrong item in AngularJS I am building a note taking application (something like a blog actually with different terms like post=note etc.) to practise my skills in AngularJS and Rails.
There is a sidebar on the left (controller Sidebar.js) which fetches all items form the Rails API and ng-repeats them to a list.
By clicking on one of them, the show.html renders inside ng-show on the right. The show view, has a link that lets you delete the item and then splices it from the sidebar on the left. After much blood, sweat and tears I believe I made it, except one detail: After deletion(=> destroy()) of the item, the wrong index gets deleted from the sidebar. I've tried to make it work with indexOf and then I console.logged the index - it always appears to be -1.
To share the same array of note objects I created a service that does that with a getter and a setter.
How can I delete the right item from the sidebar?
show.html

{{ note.title }}

    <button type="button" ng-click="destroy(note)" class="btn btn-default btn-xs pull-right">
      </button>

  {{ note.description }}

Sidebar.js
var app = angular.module('notepadApp');

app.controller('SidebarController',
  ['$scope', '$http', '$routeParams', '$location', 'Note', 'ShareNoteScope',
    function($scope, $http, $routeParams, $location, Note, ShareNoteScope) {

    $scope.notes = Note.query(function (){
      ShareNoteScope.setScope($scope.notes);
    });

    $scope.getClass = function (path) {
      if ($location.path().substr(0, path.length) === path) {
        return 'active';
      } else {
        return '';
      }
    }
  }]
);

sidebar.html

    {{ note.title }}

{{ tag }}

NoteCtrl.js
'use strict';

var app = angular.module('notepadApp');

app.controller('NoteController',
  ['$scope', '$http', '$routeParams', '$location',
    function($scope, $http, $routeParams, $location) {

  }]
);

app.controller('NoteShowController',
  ['$scope', '$http', '$routeParams', '$location', 'Note', 'ShareNoteScope',
    function($scope, $http, $routeParams, $location, Note, ShareNoteScope) {

      if ($routeParams.id) {
        Note.get({id: $routeParams.id}, function(note){
          $scope.note = note.note;
        });
      }
      else {
        $scope.note = ShareNoteScope.getScope().notes[0].id;
      }

      //Destroy method for deleting a note
      $scope.destroy = function(note) {
        Note.remove({id: note.id}, function() {
          var index = ShareNoteScope.getScope().notes.indexOf(note);
          console.log(index);
          ShareNoteScope.getScope().notes.splice(index, 1);
        });
        $location.path('/notes');
      }
  }]
);

app.controller('NoteCreateController',
  ['$scope', 'Note', '$routeParams', '$location','ShareNoteScope',
    function($scope, Note, $routeParams, $location, ShareNoteScope) {

    $scope.notes = ShareNoteScope.getScope().notes;

    $scope.newNote = {};
    $scope.createNote = function() {
      Note.create($scope.note, function (newNote) {
        $scope.notes.unshift(newNote.note);
        $scope.newNote = '';
        $scope.errors = '';
        $location.path('/notes/'+newNote.note.id);
      });
    }

}]);

models.js
'use strict';

var app = angular.module('notepadApp');

app.factory('Note', ['$resource', function($resource) {
  return $resource('/api/notes/:id', { id: "@id" }, {
    get: {
      method: 'GET'
    },
    query: {
      method: 'GET',
      isArray: false
    },
    create: {
      method: 'POST'
    }
  });
}]);

app.factory('ShareNoteScope', function (Note) {
  var $scope;
  return {
    setScope: function (scope) {
      $scope = scope;
    },
    getScope: function () {
      return $scope;
    }
  }
});

ShareNoteScope.getScope().notes contents
$$hashKey

    "object:5"
created_at

    "2015-11-29T09:07:18.614Z"
description

    null
id

    130
tags

    []
title

    "5345"
updated_at

    "2015-11-29T09:07:18.614Z"
user_id

    1

A: We went to the bottom of this in the chat. And the problem probably had to do with note not referencing an object in ShareNoteScope.getScope().notes. So to get a correct reference, we used filter in this case:
JavaScript
$scope.destroy = function(note) {
    Note.remove({id: note.id}, function() {
        var res = ShareNoteScope.getScope().notes.filter(function(el){
            return el.id == note.id;
        });
        note = res[0];
        var index = ShareNoteScope.getScope().notes.indexOf(note);
        console.log(index);
        ShareNoteScope.getScope().notes.splice(index, 1);
    });
    $location.path('/notes');
}

A: Pass $index in destroy method along with note object

{{ note.title }}

        <button type="button" ng-click="destroy(note,$index)" class="btn btn-default btn-xs pull-right">
            </button>

    {{ note.description }}

  $scope.destroy = function(note, $index) {
    Note.remove({id: note.id}, function() {
      ShareNoteScope.getScope().notes.splice($index, 1);
    });
    $location.path('/notes');
  }

Try this


text:
Q: Custom Callback made in Keras to stop "Overfitting and Overtraining" all in one is taking too much time to save model and weight I have made this CallBack to stop Overfitting specially and Overtraining secondly is taking too much time for model to save weights. SO the logic is that I want to save only and only that where current_val_loss is always less than min_val_loss AND less than min_train_loss. I want to save that weight as best_model_weight and restore that weight after the Training ends. Here is the code for that Callback:
class StopOverFit(tf.keras.callbacks.Callback):
  '''
  A class that stops Overfitting by saving the model/weights if val_loss < loss and val_loss < min_val_loss ever encountered
  Adds the functionality of ModelCheckpoint and EarlyStopping too. Currently works only with "val_loss"
  '''

  def __init__(self,filename=None,weights_only=True,restore_weights=False,early_stop=True,
               watch='val_loss',patience=5,stop_at=0.0001,min_delta=0.003):
    '''
    Constructor of the Callback
    args:
        filename: {str} should in the format "epoch: {epoch:02d}- val_loss: {val_loss:.3f}.hdf5"
        weights_only: {bool} whether to save the whole model or just the weights
        restore_weights: {bool} whether to restore the "best" weights at the end of training
        early_stop: {bool} whether to stop he model before reaching the epochs described
        watch: {str} which metri to watch out for
        patience: {int} if model has not improved with there continuous epochs, stop model training
        stop_at: {float} if the model has a metric less than equal to this value, stop training
        min_delta: {float} If the difference between best and current is greater than this, do not consider it as improvement
    '''
    super(StopOverFit,self).__init__()
    self.filename = filename
    self.weights_only = weights_only
    self.best_min_val_loss = np.inf # "best" means without overfitting
    self.min_loss = np.inf # min train loss
    self.restore = restore_weights
    self.best_weights = None # for restoring weights
    self.early_stop = early_stop
    self.watch = watch # which metric to watch out for
    self.patience = patience # how many epochs before stopping training
    self.counter = 0 # to get the counter of how many epochs it's been since the last improvement
    self.stop_at = stop_at # stop if the required metric has been achieved
    self.delta = min_delta # if last saved loss has improved more than delta, say it a progress

  def on_epoch_end(self, epoch, logs=None):
    '''
    Do something when each epoch begins like getting the logs dict and comparing the values
    arguments are provided by the model itself
    args:
      epoch: {int} epoch number. starts with 0
      logs: {dict} dictonary with metrices and losses as key. single value for each key
    '''
    val_loss = logs['val_loss']
    loss = logs['loss']
    val_f1 = logs['val_f1']

    if loss<self.min_loss:
      self.min_loss = loss

    if (val_loss<self.best_min_val_loss) and (val_loss<self.min_loss):
      print(f"\nbest val_loss improved from {self.best_min_val_loss:.4f} to {val_loss:.4f}. saving..")
      self.best_min_val_loss = val_loss
      self.best_weights = self.model.get_weights()

      if self.weights_only:
        if self.filename:
          self.model.save_weights('weights-'+self.filename.format(val_loss=val_loss,epoch=epoch+1,val_f1=val_f1))
        else:
          self.model.save_weights('best_weights.h5')
      else:
        if self.filename:
          self.model.save('model-'+self.filename.format(val_loss=val_loss,epoch=epoch+1,val_f1=val_f1))
        else:
          self.model.save('best_model.h5')

  def on_train_end(self, logs=None):
    '''
    Do something when when the model end. We'll restore the best_weights
    args:
      logs: {dict} dictonary with metrices and losses as key. key:list pair
    '''
    if self.restore:
      print("\nend of training. Restoring Best Weights")
      self.model.set_weights(self.best_weights)

Can someone help me understand why this is happening.

A: I would recommend not setting the criteria to save the weights based on both the validation loss being the lowest thus far AND being below the training loss. Generally the training loss of the previous epoch may be lower than the validation loss for the current epoch, especially in the later epochs. You want to continue training as long as the value loss continues to decrease. To do that you can just use the existing Keras callback EarlyStopping. Monitor validation loss and set  restore_best_weights=True. I also recommend that you include the callback ReduceLROnPlateau. Set it to monitor validation loss. Documentation is here.


text:
Q: Possible to weaken single-slit diffraction? Without changing the source of the waves or width of the slit, is it possible to make the electromagnetic waves passing a small slit spread less by changing some other aspects of the slit such as surface material or border geometry?

A: No.  The types of modifications you suggest can make small, practically undetectable, changes to the shape of the transverse intensity profile, but not the divergence angle.
I'm assuming here that when you say "border geometry" you mean the details of the edges:  rounded, chamfered, bezeled, sharp, ... without changing the size or shape of the slit.

A: One possible thing you can do is place another single-slit after the first single-slit to block the peripheral fringes and let only the middle fringe through.
The single-slit creates its own diffraction pattern as seen here and here. The trick I'm suggesting here is to block the bright spots/fringes to the sides using another slit. Now, there would indeed be a diffraction effect from the second slit, but because most of the light of the middle spot goes through the middle of the slit, the diffraction effect would be small/negligible. Hence, you suppress some of the diffraction effects of the first slit.

You asked about whether a single-slit with huge thickness can achieve the same thing, and the answer is no.
The problem is that the trick relies on you to create the single-slit pattern first, and then have parts of it get blocked.
When you let light from a single-slit, there is something called the Fresnel regime and the Fraunhofer regime. The Fresnel case has to do with the pattern formed when you're close to the slit. The Fraunhofer case has to do when you're far away from the slit, and that is the pattern I have linked above.
The thing is, the Fraunhofer pattern needs space before it begins to form, so you need light to go unimpeded for some distance (as far as I understand). Hence a single-slit with thick material wouldn't work, because it wouldn't let the Fraunhofer pattern to form for the suggested trick to work.
Again, I don't know if this is what you're looking for. If not, then I would say garyp's answer is correct.


text:
Q: DevExpress VerticalGrid Validate event and behavior with RadioButton cell editors I'm using the VerticalGrid in MultiRecordView.  Its Validate event fires when the grid detects that a record that has been changed is losing focus. I'm writing data to the database from this event.
My users want to use the keyboard left/right arrow keys to move forwards and backwards through the recordset, so I trap those keys and set the FocusedRecord accordingly.
If one of the row editors is a RepositoryItemRadioButton, the Validate event doesn't always fire. The users will click on the radio-button value desired and then, before they click on another row in the record, they'll hit the arrow key to move to the next record. The change to the radio button group has not been detected by the grid in that sequence of events.
The radio button change is detected only when the button loses focus.
Is there a way to cause the vertical grid to recognize that a radio button editor has been changed and fire the Validate event, if the user doesn't give another row in the record the focus?
I thought EditValueChangedFiringMode property controlled that behavior, but setting it to Default or to Buffered does not have the desired effect.
Thanks


text:
Q: General advice to regulate voltage in microcontroler and "high amp" peripherials Background

*

*I want to control a ws2812b 16x16 RGB LED matrix and a buzzer with an AVR ATTINY84-20PU board (programmed with an arduino).

*I want to power everything with a battery. Which? hopefully some combination of AA batteries will suffice, otherwise I'm happy to go down the 18650 route again.

*Ideal solutions should be simple enough for me to understand and learn (if possible) and be available in SMD format as I'm designing a PCB.

Issue

*

*The LED matrix and the buzzer draw together too much power from the microcontroler to handle. Although they work if they are individually driven by the microcontroler.

*The voltage supplied from the battery will drop with time.

Observations

*

*It is clear that I need to power either the LED matrix or/and the buzzer separately from the microcontroler and let the arduino only handle the control.

*It is clear that I need to somehow regulate the voltage from the battery to a constant 5V (as everything is rated 5V).

Questions

*

*I have seen that I can use a SMD 5V linear voltage regulator like the L78M05ABDT-TR but is rated for 500mA (maybe a bit low?) and the minimun input voltage is too high at 10V. I will probably be looking at a range of 5V-12V input voltage. Any ideas on what I could use?

*To control the buzzer on/off, I have read that I could use a MOSFET like BSS84 but Im fairly new to MOSFETs so Im unsure if it will work as I want. (The LED matrix doesnt need anything extra as it has a signal wire for controling).


text:
Q: Mirc, emulate akicklist saving in file the ip someone can suggest me as to do this:
if i type:
/akick nickname
Nickname should to be kicked and banned from current channel and to same time i need to save in a file (for example: akicklist.txt) the IP address of nickname.
In ON JOIN event, i need check if ip address of nickname that joined in channel is present in akicklist.txt and if result is true then proceed with a kick and ban to it.
Thanks very much, for help.

A: Those kinda lists are called Black/Enemy/Shit/etc List's..
You can find those in google as "mirc shit list"...
http://www.mircscripts.org/comments.php?cid=3653
http://www.mirc.net/projects.php?go=1089290479&get_review=1


text:
Q: symfony 2 annotation routes + group routing Is there any difference in using annotation routes or group routes in symfony 2 when it comes to performance, convenience, maintainability or in any aspect that would make the other more advisable to use?

A: Use SensioFrameworkExtraBundle, already shipped with Symfony 2. Having route names and paths in the same place of controller action is the right way to go. If you want to modify a path or action name simply go to that action, without editing routing.yml.
Then give a name to your "grouped routes" e.g. bundle_controller pattern or maybe bundle_entity (if controller is used for CRUD on a single entity):
# app/config/routing.yml
acme_hello_my_annotated_controller:
    resource: "@AcmeHelloBundle/Controller/MyAnnotatedController.php"
    type: annotation

Eventually prefixing all paths defined by annotations (add prefix: /my/path/prefix).
EDIT: don't know anything about performances. I'm talking only about convenience.


text:
Q: Manually fire button click event in DataGridView I've got a DataGridView including a DataGridViewButtonColumn. The user should be able to use the button directly so I set EditMode to EditOnEnter. But, the first click didn't fire the Click event - It seems like the first click selects/focus the row/column?
So I tried to use the CellClick Event:
Private Sub dgv_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgv.CellClick

 Dim validClick = (e.RowIndex <> -1 And e.ColumnIndex <> -1)
 If (TypeOf dgv.Columns(e.ColumnIndex) Is DataGridViewButtonColumn And validClick) Then
     dgv.BeginEdit(True)
     CType(dgv.EditingControl, Button).PerformClick()
 End If

End Sub

But this solution didn't work either. EditingControl always throws a NullReferenceException.
Any ideas?

A: I do not think there is a specific event available to handle when a DataGridViewButtonColumn cell is clicked. The DataGridView's Cell_Clicked and CellContentClicked events get fired.
I was not able to get the delay of clicking into the DataGridView once then having to click again to fire the button. When I clicked on the DataGridView button cell, the Cell_Clicked event was immediately fired. Changing the DataGridView's EditMode made no difference. The code below simply identifies WHICH cell was clicked from the Cell_Clicked event. If the cell clicked was a button column (1 or 2), then I call a created method ButtonHandler to handle which button was pressed and to continue on to the correct button method. Hope this helps.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
  if (e.ColumnIndex == 1 || e.ColumnIndex == 2) {
    // one of the button columns was clicked
    ButtonHandler(sender, e);
  }
}

private void ButtonHandler(object sender, DataGridViewCellEventArgs e) {
  if (e.ColumnIndex == 1) {
    MessageBox.Show("Column 1 button clicked at row: " + e.RowIndex + " Col: " + e.ColumnIndex + " clicked");
    // call method to handle column 1 button clicked
    // MethodToHandleCol1ButtonClicked(e.RowIndex);
  }
  else {
    MessageBox.Show("Column 2 button clicked at row: " + e.RowIndex + " Col: " + e.ColumnIndex + " clicked");
    // call method to handle column 2 button clicked
    // MethodToHandleCol2ButtonClicked(e.RowIndex);
  }
}


text:
Q: How do you get javascript to wait for input before continuing to run I'm trying to make a little text rpg in javascript.
I have a text field the user types into for input, then presses enter. And the games text changes to reflect their input.
I then need the code to wait for further input before running anymore code. Essentially, how do you pause and wait for further input. And I mean not just once, but for the whole game, every time.  Here's an image of my code and the webpage
const gamesText = document.querySelector('.games-text');
const usersInput = document.querySelector('#users-text-input');

StartTheGame();
function StartTheGame() {
    gamesText.innerHTML = "Welcome to the game!~ What is your name?";

    usersInput.addEventListener('keypress', e => {
        if (e.key === "Enter") {
            const usersName = usersInput.value;
            gamesText.innerHTML = "Good luck " + usersName + "!~";
            localStorage.setItem('name', usersName);
        }
    });

}

//EventListeners
document.addEventListener('keypress', e => {
    if (e.key === "Enter") {
        gamesText.innerHTML = `This is the only text
        you'll see, after pressing ENTER once.`;
    }
});

A: Simple
usersInput.addEventListener('keypress', e => {
        if (e.key === "Enter") {
         if(usersInput.value.length > 3){
            const usersName = usersInput.value;
            gamesText.innerHTML = "Good luck " + usersName + "!~";
            localStorage.setItem('name', usersName);
         }else{
          //message of error
         }

        }
    });


text:
Q: How does distribution key allocate data in segments for GreenPlum I understand that Greenplum Database will separate data into different segments according to table distribution key. And furthermore, from the documentation it says:
To achieve local joins for large tables commonly joined together, distribute the tables on the same column.
Assume there are tables as follow:

*

*T_1 contains key external columns (a,b)

*T_2 contains key external columns (a)

*T_3 contains key external columns (b)

So if I distribute T_1 by both (a,b), how should I distribute T_2 and T_3 in order to achieve maximum localization of a join?

A: You can't distribute T_2 and T_3 the same way as T_1, because you are missing columns in each table.
In your scenario you can either optimize T_2 by distributing T_1 by (a), or optimize T_3 by distributing T_1 by (b). And you have to use the same data types as well.


text:
Q: Java - Collectors Group By and Expand Map by number of records I have the following java list of UserRecords objects that are grouped by user_name.
List<UserRecords> userRecordsList = new ArrayList<UserRecords>();

    // load mock data into the data structure
    for(int i = 0; i < 20; i ++) {
            UserRecords entry = new UserRecords();
            entry.id = i;
            entry.record_type = "audit";
            entry.info = "some information.";

            if(i < 5) {
                entry.user_name = "John Doe";
            } else {
                entry.user_name = "Jane Doe";
            }

        userRecordsList.add(entry);
    }

    // group by user_name
    Map<String, List<UserRecords>> userGroup =
            userRecordsList.stream().collect(Collectors.groupingBy(UserRecords::getUser_name));

I want to be able to break down this list into small batches of 5 records if a user has more than 5 records.
Here's the result of my user group:
{John Doe=[
UserRecords{id=0, user_name='John Doe', record_type='audit', info='some information.'},
UserRecords{id=1, user_name='John Doe', record_type='audit', info='some information.'},
UserRecords{id=2, user_name='John Doe', record_type='audit', info='some information.'},
UserRecords{id=3, user_name='John Doe', record_type='audit', info='some information.'},
UserRecords{id=4, user_name='John Doe', record_type='audit', info='some information.'}],

Jane Doe=[
UserRecords{id=5, user_name='Jane Doe', record_type='audit', info='some information.'},
UserRecords{id=6, user_name='Jane Doe', record_type='audit', info='some information.'},
UserRecords{id=7, user_name='Jane Doe', record_type='audit', info='some information.'},
UserRecords{id=8, user_name='Jane Doe', record_type='audit', info='some information.'},
UserRecords{id=9, user_name='Jane Doe', record_type='audit', info='some information.'},
UserRecords{id=10, user_name='Jane Doe', record_type='audit', info='some information.'},
UserRecords{id=11, user_name='Jane Doe', record_type='audit', info='some information.'},
UserRecords{id=12, user_name='Jane Doe', record_type='audit', info='some information.'},
UserRecords{id=13, user_name='Jane Doe', record_type='audit', info='some information.'},
UserRecords{id=14, user_name='Jane Doe', record_type='audit', info='some information.'},
UserRecords{id=15, user_name='Jane Doe', record_type='audit', info='some information.'},
UserRecords{id=16, user_name='Jane Doe', record_type='audit', info='some information.'},
UserRecords{id=17, user_name='Jane Doe', record_type='audit', info='some information.'},
UserRecords{id=18, user_name='Jane Doe', record_type='audit', info='some information.'},
UserRecords{id=19, user_name='Jane Doe', record_type='audit', info='some information.'}]}

Since Jane Doe has more than 5 records, I would like her results to be split as follows:
  Jane Doe=[
     UserRecords{id=5, user_name='Jane Doe', record_type='audit', info='some information.'},
     UserRecords{id=6, user_name='Jane Doe', record_type='audit', info='some information.'},
     UserRecords{id=7, user_name='Jane Doe', record_type='audit', info='some information.'},
     UserRecords{id=8, user_name='Jane Doe', record_type='audit', info='some information.'},
     UserRecords{id=9, user_name='Jane Doe', record_type='audit', info='some information.'},
     UserRecords{id=10, user_name='Jane Doe', record_type='audit', info='some information.'}],

  Jane Doe1=[
        UserRecords{id=11, user_name='Jane Doe', record_type='audit', info='some information.'},
       UserRecords{id=12, user_name='Jane Doe', record_type='audit', info='some information.'},
       UserRecords{id=13, user_name='Jane Doe', record_type='audit', info='some information.'},
       UserRecords{id=14, user_name='Jane Doe', record_type='audit', info='some information.'},
       UserRecords{id=15, user_name='Jane Doe', record_type='audit', info='some information.'}],

   Jane Doe2=[
        UserRecords{id=16, user_name='Jane Doe', record_type='audit', info='some information.'},
       UserRecords{id=17, user_name='Jane Doe', record_type='audit', info='some information.'},
       UserRecords{id=18, user_name='Jane Doe', record_type='audit', info='some information.'},
       UserRecords{id=19, user_name='Jane Doe', record_type='audit', info='some information.'}]

How can I approach this?

A: I would recommend reading about Guava.
Try using this method, which divides a list for sublists of maximum chosen size.
List<List<UserGroup>> janeDoeUserGroups = Lists.partition(userGroup.get("Jane Doe"), 5);

Every element of the janeDoeUserGroups is a list containing maximum 5 elements of UserGroup, only the last one might contain less in case the total elements number % 5 != 0.
Also class fields should be written in camel case style, like:
String recordType;

Instead of
String record_type;

Hope it helps.


text:
Q: Unable to deploy static website to heroku, html and css not loading from php So I am trying to deploy static website to heroku but the main page isn't loading the html/css files.
Link to app:
https://randomstockpicker.herokuapp.com/
when I looked at the source code it shows:
<?php include_once("home.html"); ?>

this php code isn't loading the "home.html" file, the file exists and is uploaded as well.
I also got composer.json : {}
I followed this tutorial:
https://medium.com/@agavitalis/how-to-deploy-a-simple-static-html-website-on-heroku-492697238e48

A: Instead of using:
<?php include_once("home.html"); ?>

this worked perfectly
<?php include_once("./home.html"); ?>

A: The tutorial you followed asks you to rename the index.html file to a custom one (home.html), and uses a PHP file (which is a server-side scripting language) to "load" the static file.
It's not rendering the page because Heroku isn't configured to serve PHP files.
I recommend you mv home.html index.html (renaming you homepage back to index.html, which is a standard file that browsers look for) and you should see your static site.
Just as a side-note, PHP is not static, it's a dynamic scripting language, so if you're aiming at building a static site, avoid anything else than HTML + JS + CSS.


text:
Q: ImportError: cannot import name WebAPI I wanna use "shodan" API but It didn't work well with me.
First I did this command in terminal easy_install shodan
and here's the ouptut:
$easy_install shodan
Searching for shodan
Best match: shodan 0.8.1
Processing shodan-0.8.1-py2.7.egg
shodan 0.8.1 is already the active version in easy-install.pth

Using /usr/local/lib/python2.7/dist-packages/shodan-0.8.1-py2.7.egg
Processing dependencies for shodan
Finished processing dependencies for shodan

and then I wrote my code:
#! /usr/bin/python en

    from shodan import WebAPI

    SHODAN_API_KEY = "Key"

    api = WebAPI(SHODAN_API_KEY)

    # Wrap the request in a try/ except block to catch errors

It gave me an error:
ImportError: cannot import name WebAPI

I searched for similar problems some answers was changing file name and some was deleting pyc files. I tried both answers but It doesn't work also.

A: What's the name of your script? There could be a name collision going on if the name of your script is "shodan", i.e. the same name as the Shodan library. There was also an issue with Python 3 that caused some import problems, but if you're using the latest version of the Shodan API library that should be resolved. And I echo the comment of luc that the indentation looks wrong, so you will need to fix that as well in order for the script to execute.

A: I found the answer
I should install py crypto
sudo apt-get install python-crypto


text:
Q: Android ExpandableListView sliding children I'm currently trying to develop an expandablelistview with two or more children per group.
It works fine, but now I want to animate a slide animation to the children, when the user clicks on the parent.
I found this library https://github.com/tjerkw/Android-SlideExpandableListView and it works really well for one item per group. I tried to expand the xml layout file, so that I could use more items than only one per group. But it doesnt seem to work.
This is the original file. It includes two buttons in one row per group.
<LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/expandable"
        android:background="#000000">

        <Button
                android:id="@+id/buttonA"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.5"
                android:text="Action A"
                android:textSize="12dip"/>

        <Button
                android:id="@+id/buttonB"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.5"
                android:text="Action B"
                android:textSize="12dip"/>
</LinearLayout>

But when I now try to expand this layout, for example like this:
<LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/expandable"
        android:background="#000000">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <Button
                android:id="@+id/buttonA"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Action A"
                android:textSize="12dip"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <Button
                android:id="@+id/buttonB"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Action B"
                android:textSize="12dip"/>
        </LinearLayout>
</LinearLayout>

The "space" that is sliding down gets bigger, but I'm only able to see the first button. The place where the second button should be displayed is empty.
Has anybody an idea?

A: Please change parent layout orientation to vertical resolve your problem.


text:
Q: Unable to see GUI Hey I have Installed UBUNTU 12.04 on vmware work station on Windows 7 but when I start  it up in vmware I get a message on black screen of ubuntu i.e.
[ 7.3326] pixx4_smbus 0000:00:07.3: Host SMBus controller not enabled!

After that it asks for user id and password on black screen and after entering them I am still in a black screen, I am unable to see GUI.
Please suggest what to do. I am new to UBUNTU.

A: The SMBus is for information such as motherboard temperature and there isn't any on a virtual machine (as far as I am aware), but Linux still starts the driver for it. I am fairly sure it isn't related to your GUI issue.
Sorry if this sounds Mickey Mouse, but did you install Ubuntu workstation or server? The server hasn't got a GUI by default. Workstations put the GUI in terminal 7. You can switch terminal screens by pressing CTRL+ALT+F7 (F1 to F7 selects the different screens). So when your VM starts, try pressing CTRL+ALT+F7 and see what's on the screen. If it's just another logon prompt, then the GUI isn't working or not installed. Log in and try typing startx to see if the GUI strats. If not, check the messages you get and let us know.
If you've installed server and want a GUI, there are quite a few to be had. Some are lightweight and some are extremely heavy. One of the lighter is xfce4.


text:
Q: OperationalError at /admin/rentals/rental/ I had a database with following fields listingName,slug,property,city,place,ownerName,room,water,amenities,price,summary,phoneNumber,phone_image,email
I didn't want phone_image field so i removed it from models.py and applied the following command
python manage.py makemigrations rentals
python manage.py migrate

But i get below error
OperationalError at /admin/rentals/rental/
no such column: rentals_rental.phone_image

so i deleted my database first and then applied the command python manage.py migrate but still getting the same error though my models do not have phone_image field.
It works in localhost but not in remote. As i have hosted my application in digital ocean with nginx and gunicorn.
admin.py
from django.contrib import admin
from rentals.models import Rental,Gallery

class InlineGallery(admin.TabularInline):
    model = Gallery
    fk_name = 'rental'

class RentalAdmin(admin.ModelAdmin):
    inlines = [
        InlineGallery,
    ]
admin.site.register(Rental,RentalAdmin)
admin.site.register(Gallery)

models.py
ownerName = models.CharField(_("Owner's Name"),max_length=255, blank=True,null=True,
    help_text=_("Owner's Full Name"))
email = models.CharField(max_length=120,blank=True,null=True)
phoneNumber = models.PositiveIntegerField(blank=False,null=True,
    help_text=_("Phone number of contact person"))
listingName =  models.CharField(_("Lisitng Name"), max_length=255, blank=False,null=True,
    help_text=_("Title of the rental space"))
slug = models.SlugField(unique=True,blank=True,null=True)
summary = models.TextField(max_length=500, blank=True,null=True,help_text=_("Description of the rental space"))
property = models.CharField(_("Property type"),max_length=10,null=True)
room = models.PositiveIntegerField(_("No of Rooms"), blank=False, null=True,
    help_text=_("Number of bedrooms available"))
price = models.PositiveIntegerField(blank=False,null=True,
    help_text=_("Rental price of the space per month"))
city =  models.CharField(_("City"), max_length=255, blank=False,null=True,
    help_text=_("City of the rental space"))
place =  models.CharField(_("Place"), max_length=255, blank=False,null=True,
    help_text=_("Place of the rental space"))
water = models.CharField(_("water facilities"),max_length=50,null=True,
    help_text=_("Is there water facility?"))
amenities = models.CharField(_("amenities"),max_length=100,blank=True,null=True)
phone_image = models.CharField(blank=True, help_text='image form of the phone number', max_length=2048, null=True)
is_published = models.BooleanField(default=True)
created_on = models.DateTimeField(auto_now_add=True)
modified_on = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return self.listingName

I have two migrations file inside migration folder
0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-03-30 14:23
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
    migrations.CreateModel(
        name='Gallery',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('image', models.ImageField(blank=True, null=True, upload_to='upload/')),
        ],
        options={
            'verbose_name_plural': 'Galleries',
            'verbose_name': 'Gallery',
        },
    ),
    migrations.CreateModel(
        name='Rental',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('ownerName', models.CharField(blank=True, help_text="Owner's Full Name", max_length=255, null=True, verbose_name="Owner's Name")),
            ('email', models.CharField(blank=True, max_length=120, null=True)),
            ('phoneNumber', models.PositiveIntegerField(help_text='Phone number of contact person', null=True)),
            ('listingName', models.CharField(help_text='Title of the rental space', max_length=255, null=True, verbose_name='Lisitng Name')),
            ('slug', models.SlugField(blank=True, null=True, unique=True)),
            ('summary', models.TextField(blank=True, help_text='Description of the rental space', max_length=500, null=True)),
            ('property', models.CharField(max_length=10, null=True, verbose_name='Property type')),
            ('room', models.PositiveIntegerField(help_text='Number of bedrooms available', null=True, verbose_name='No of Rooms')),
            ('price', models.PositiveIntegerField(help_text='Rental price of the space per month', null=True)),
            ('city', models.CharField(help_text='City of the rental space', max_length=255, null=True, verbose_name='City')),
            ('place', models.CharField(help_text='Place of the rental space', max_length=255, null=True, verbose_name='Place')),
            ('water', models.CharField(help_text='Is there water facility?', max_length=50, null=True, verbose_name='water facilities')),
            ('amenities', models.CharField(blank=True, max_length=100, null=True, verbose_name='amenities')),
            ('phone_image', models.CharField(blank=True, help_text='image form of the phone number', max_length=2048, null=True)),
            ('is_published', models.BooleanField(default=True)),
            ('created_on', models.DateTimeField(auto_now_add=True)),
            ('modified_on', models.DateTimeField(auto_now_add=True)),
        ],
        options={
            'verbose_name_plural': 'Rents',
            'verbose_name': 'Rent',
        },
    ),
    migrations.AddField(
        model_name='gallery',
        name='rental',
        field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='gallery', to='rentals.Rental', verbose_name='Rental'),
    ),
]

0002_remove_rental_phone_image.py
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-04-20 02:01
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

dependencies = [
    ('rentals', '0001_initial'),
]

operations = [
    migrations.RemoveField(
        model_name='rental',
        name='phone_image',
    ),
]

How can i overcome this issue? Do i need to provide any more information?
Thanks

A: As you said in the answers above, the field got manually removed from the database, so the migration tries to delete a field that is no longer existing in the database.
Normally you should never delete fields directly in the db but use the migrations instead. As the field is already gone you can now only fake the migration to tell django that the changes were already made:
manage.py migrate rentals 0002 --fake

Make sure though that you are at migration 0001, otherwise that would be faked aswell.
just to be sure, you could run the following command first:
manage.py migrate rentals 0001

A: This type of error means that, there is no any column named phone_image in the table rental. So, your second migration is trying to remove a column that is not present in the table rental. Somehow, you removed that column from the table, and django migration system didn't notice it.
As a fix try one of these options:
1) delete 0002_remove_rental_phone_image.py and in 0001_initial.py remove this line:
('phone_image', models.CharField(blank=True, help_text='image form of the phone number'....)),
and try to apply migrations (if it says: table rental is already exist, try to DROP it from the database);
2) delete all your migration files, and recreate the database, make migrations and apply them.

A: When you write your code of models.py
then Run Command
python manage.py makemigrations rentals

after this command you will see 0001_any_name.py then Enter again command
python manage.py sqlmigrate rentals 0001    //0001 is prefix of above result

It will create your database accouding to models.py then you can migrate
python manage.pt migrate

So this process run first time when you first time create database but in any database column problem occurs then this above procedure repeat again.your problem will solve.


text:
Q: JPA cascade merge on a child list is not considering columns modified in @PreUpdate or @Prepersit I have two entities A and B. A is parent of B, ie A is having a list of B as child.
The JPA classes corresponding look like below :
The first entity :
@Entity
@Table(name = "A")
public class A {

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "refA", orphanRemoval = true)
    private List<B> listOfB;
}

The second entity :
public class B {

    @JoinColumn(name = "A_REF")
    @ManyToOne
    private CoreRecord refA;

    private int updatedColumn;

    @PrePersist
        private void prePersit() {
        this.updatedColumn = 1;
    }

    @PreUpdate
    private void preUpdate() {
        this.updatedColumn = 2;
    }
}

My issue now is that when i first persit A whith a list of B, everything goes fine. Each object of B is cascadly persisted and the updatedColumn if filled correcty.
Then juste after persisting A, if i add a new instance of B in the listOfB and call merge on A, the new instance of B will be persisted in the database but the value of updatedColumn not filled correctly.
When i debug the code, i can notice that the prePersit method is being called but the modification done to my updatedColumn field is never persisted in the database. I have also notice that the preUpdate method is never called.
I would like the modification done in one of the method prePersit or preUpdate to the updatedColumn of the new instance of B to be persisted in the database when i call merge on A.
I've been tourning around searching what i'm doing wrong. Since then i have'nt found the problem nor the solution. I need your help please. Thanks in advance.
My JPA provider is eclipselink 2.5.2


text:
Q: Comparing each line in CSV file to JSON hash on matching element to get unique matches only I searched SO before posting but perhaps I don't know the correct search terms.
I successfully read the CSV file into a new array and am trying to compare the eighth element in the array to the JSON response of my program.  The JSON response from my program (data["ip"]) is just an IP address that matches what is in row[8].
Everything is working for matches, however three non-matches will be found in every loop iteration. The only IP address that doesn't exist in the JSON is 100.100.100.300,  all the others will have a match.
My Code:
require 'csv'
require 'json'
require 'date'

CSV.foreach("list.csv", :headers => true) do |row|
  @response["response"]["results"].each do |data|
     if row[8].eql?(data["ip"])
      puts "Match: " + row[8] + " = " + data["ID"]
    else
      puts "No Match Found for " + row[8]
    end
  end
end

Here are the results I would like:
Match: 100.100.100.200 = 26826
Match: 100.100.100.100 = 26827
Match: 100.100.100.400 = 26827
No Match Found for 100.100.100.300

Here are the results I am getting:
No Match Found for 100.100.100.200
Match: 100.100.100.200 = 26826
No Match Found for 100.100.100.200
No Match Found for 100.100.100.200
No Match Found for 100.100.100.300
No Match Found for 100.100.100.300
No Match Found for 100.100.100.300
No Match Found for 100.100.100.300
Match: 100.100.100.100 = 26827
No Match Found for 100.100.100.100
No Match Found for 100.100.100.100
No Match Found for 100.100.100.100
No Match Found for 100.100.100.400
No Match Found for 100.100.100.400
No Match Found for 100.100.100.400
Match: 100.100.100.400 = 26827

'list.csv' looks like this:
Applicability,Person,Tier,Type,AType,Name,Code,Sub,IP Address,Location,Presence,Env,Main,Main2,Status,Contact,Group,FQDN,Outside,OutsideIdent,Category,Comments
Yes,Unit,Accepted,Level,Hardware,NameA,C1234565,Yes,100.100.100.200,"Nowhere",No,VP,Running,SomeKind,Active,"","",FullName,"","",Tool,""
Yes,Unit,Accepted,Level,Hardware,NameB,C1234566,Yes,100.100.100.300,"Nowhere",No,VP,Running,SomeKind,Inactive,"","",FullName,"","",Tool,""
Yes,"","",Something,Hardware,NameC,C1234567,Yes,100.100.100.100,"Nowhere",,"",,,"","Name, Contact","",FullNameFull,"","",Tool,""
Yes,"","",Something,Hardware,NameD,C1234568,No,100.100.100.400,"Nowhere",,"",,,"","Name, Contact","",FullNameFull,"","",Tool,""

A: You may not need two loops.  You could do as below:
(Not tested as JSON structure was not shared in question)
results = @response["response"]["results"]

CSV.foreach("list.csv", :headers => true) do |row|
  matching_entry  = results.find { |data| row["IP Address"] == data["ip"]}
  if matching_entry
    puts "Match: " + row["IP Address"] + " = " + matching_entry["ID"]
  else
    puts "No Match Found for " + row["IP Address"]]
  end
end

A: Another way of doing it would be creating a hash with the IP address as key. The benefit is that it would only have to iterate once to create the lookup.
ip_table = Hash[@response['response']['results'].map {|x| [x['ip'], x['ID']]}]

CSV.foreach("list.csv", :headers => true) do |row|
  if ip_table[row[8]]
    puts "Match: " + row[8] + " = " + ip_table[row[8]]
  else
    puts "No Match Found for " + row[8]
  end
end


text:
Q: Store function returns(derived values) in Graphite Is it possible to store them as new keys?
E.g. I want to calculate
highestAverage(divideSeries(total_request_processing_time.*,total_request_count.*),3)
while default Graphite syntax won't allow such combination.
Thanks.

A: i believe you want the division to be interleaved. As in divideSeries(A.*,B.*) should become- divideSeries(A.1,B.1), divideSeries(A.2,B.2)... and so on.
No. This is not straightforward because metrics with wildcards are returned as a seriesList.
Quoting the docs-

Series List:
A series name or wildcard which matches one or more series. Series
  lists are received by functions as a list of matching series. From a
  user perspective, a series list is merely the name of a metric. For
  example, each of these would be considered a single series list:
   metro_east.servers.apache02.system.load_average.1_min,
   metro_east.servers.apache0{1,2,3}.system.load_average.1_min
   metro_east.servers.apache01.system.load_average.*

So divideSeries(A.*,B.*) is resolved as divideSeries(A.1,A.2,B.1,B.2), which, is invalid as this function accepts only two series at a time.
What you can do is make a script that prepares the interleaved division-ready API calls.


text:
Q: Updating database at runtime I can't update even if my code is correct.
I tried to change the data type from String to Integer but still nothing happens.
Private Sub UpdateQuanLoop()
    For x As Integer = 0 To cartidentifier - 1
        UpdateQuantity(ID(x), Quantity(x))
    Next
End Sub

Private Sub UpdateQuantity(S_ID As String, S_Quan As String)
    Dim finder As Integer
    access.AddParam("@proID", S_ID)
    access.ExecQuery("SELECT product_quantity FROM product WHERE product_ID = @proID;")

    Dim Z As DataRow = access.DBDT.Rows(0)
    finder = Z("product_quantity").ToString - S_Quan
    access.AddParam("@ID", S_ID)
    access.AddParam("@quan", finder)
    access.ExecQuery("UPDATE product SET product_quantity = @quan WHERE product_ID = @ID;")
    If NoErrors(True) = False OrElse access.RecordCount < 1 Then Exit Sub
End Sub

I don't have any error but the database is not updated.


text:
Q: Git bash export function not recognized or without an effect I am using git-bash on windows, but unfortunately it seems I have a configuration issue. I am trying to use the export function to set environment variables, like so:
$ export php='/c/xampp/php/php.exe'

$ php -v
bash: php: command not found

This is also the case after a restart of git-bash.
Using the alias function works:
$ alias php='/c/xampp/php/php.exe'

$ php -v
PHP 7.4.7 (cli) (built: Jun  9 2020 13:36:15) ( ZTS Visual C++ 2017 x64 )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies

I've also tried to register the environment variables directly in the .bash_profile-configuration-file, which I assume is the one located under C:/Users/username, but that does not work either.
As of now, I assume if haven't setup git correctly or made some stupid mistake. Any hint what I am missing would be very much appreciated.

A: Variables are referenced with $, and you don't need to export them unless you want them to become environment variables of spawned programs.
php=/c/xampp/php/php.exe
$php -v

You should continue using alias for this, though – that's what it's for! – or extend your $PATH instead:
PATH="$PATH:/c/xampp/php"


text:
Q: Clear NSUserDefaults at set time How can I clear keys in NSUserDefaults at a given time? I have a local notification set up at 8p.m. and at that time I also want NSUserDefaults to be cleared. Other responses to similar questions have not fulfilled what I want — often they have code which is too complicated for my need.
I know how to clear NSUserDefaults on launch, but integrating this with a time interval or at a particular time is beyond me. Any code would be appreciated.

A: This is how you can clear everything in NSUserDefaults :
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];


text:
Q: Numpy array as an element in a Pandas DataFrame How do I put a numpy array into an element (single cell) of a Pandas DataFrame? For instance,
Driver  Make  Model  Coordinates
Bob     Ford  Focus  [[1, 0, 1],[1, 2, 3], [2, 0, 2]]
Sally   Ford  Echo   [[0, 0, 1],[0, 2, 0]]

I've tried to store the array on each row, but the documentation doesn't seem to support this.
Context:
I am hoping to use df.to_json() to export the data to a json file, from which the data can later be read into a DataFrame where each row is one of the individuals. Should I be thinking about doing this differently?

A: Yes, you can. Use .at[] or .iat[] to avoid broadcasting behavior when attempting to put an iterable into a single cell. This also applies to list and set.
The bad thing: It may be quite challenging to do such assignment in an optimized way that does not involve iteration through rows. That said, this is still doable for reasonably-sized arrays. And if you really have to store millions of such arrays, a fundamental redesign may be required. E.g. restructure your code, use MongoDB or other storage instruments instead, etc.
import pandas as pd
import numpy as np

# preallocate the output dataframe
df = pd.DataFrame(
    data=np.zeros((2,4), dtype=object),
    columns=["Driver", "Make", "Model", "Coordinates"]
)

# element-wise assignment
df.at[0, "Coordinates"] = np.array([[1, 0, 1],[1, 2, 3], [2, 0, 2]])
df.at[1, "Coordinates"] = np.array([[0, 0, 1],[0, 2, 0]])
# other elements were omitted

Result
print(df)
  Driver Make Model                        Coordinates
0      0    0     0  [[1, 0, 1], [1, 2, 3], [2, 0, 2]]
1      0    0     0             [[0, 0, 1], [0, 2, 0]]

print(df.at[0, "Coordinates"])
[[1 0 1]
 [1 2 3]
 [2 0 2]]

print(type(df.at[0, "Coordinates"]))
<class 'numpy.ndarray'>


text:
Q: how to break this line in multiple lines? This line with html inside php is too long and makes it hard to read, is there an elegant way to break this into multiple lines?
<a class="icon-button" href="<?php echo get_term_link( $term ); ?>"><?php echo $term->name; ?><svg class="eco-sprite icon icon--go" role="img"><use xlink:href="#shape-ButtonDetailBold"></use></svg>

A: Something like this you mean...
<?php
  . . .
?>
<a class="icon-button" href="<?php echo get_term_link( $term ); ?>">
    <?php echo $term->name; ?>
    <svg class="eco-sprite icon icon--go" role="img">
        <use xlink:href="#shape-ButtonDetailBold"></use>
    </svg>

<?php
 . . .
?>

A: Just indent your HTML:
<a class="icon-button" href="<?php echo get_term_link( $term ); ?>">
    <?php echo $term->name; ?>
    <svg class="eco-sprite icon icon--go" role="img">
        <use xlink:href="#shape-ButtonDetailBold"></use>
    </svg>

A: <a class="icon-button" href="<?php echo get_term_link( $term ); ?>">

        <?php echo $term->name; ?>

    <svg class="eco-sprite icon icon--go" role="img">
        <use xlink:href="#shape-ButtonDetailBold"></use>
    </svg>


text:
Q: Generate power through a charger I have 100 Nm going into a charging device such as a dynamo, alternator, etc. The rotation is 20 radians per second. The charger is 3-phase with a frequency of 50 Hz and 12 poles. What is the potential power output running over 1 hour in kWh?

A:
I have 100 Nm going into a charging device such as a dynamo, alternator, etc. The rotation is 20 radians per second.

You have a mechanical input of 100 * 20 = 2000 Watts

The charger is 3-phase with a frequency of 50 Hz and 12 poles.

Irrelevant

What is the potential power output running over 1 hour in kWh?

kWh is a measure of energy, not power.
The power output will be somewhere between the bounds of 0 and 2000 W, depending on the efficiency of the generator and anything that follows it, so maybe 1 kW, maybe 1.5 kW?
The energy output in kWh in one hour will be numerically equal to the power output.


text:
Q: Finding the height of an irregular cylinder? I need to find the height of an irregular cylinder. Its difficult due to both diameters being different.
Here are the Details
Capacity: 250 Ml
Bottom Diameter: 4.8 cm
Top Diameter 8 cm
Please help.

A: Are you describing a conical frustrum?  It is a cone with a cone cut off, similar to a trapezoid?  If the height is $h$ and the radii are $r_1,r_2$, $$V=\frac 13\pi h(r_1^2+r_1r_2+r_2^2)$$

A: So you are given a truncated cone with $r_1 = 0.048 \text{ m}$, $r_2 = 0.08 \text{ m}$, and volume $V = 0.00025 \text{ m}^3$.
$$ V = \frac{1}{3} \pi h (r_1^2 + r_1 r_2 + r_2^2) $$
So you can plug in your values and solve for $h$ where
$$ h = \frac{3 V}{\pi (r_1^2 + r_1 r_2 + r_2^2)} = 0.0190 \text{ m} = 1.9 \text{ cm}$$


text:
Q: Filter the no-responses questions? Is there a way to get the list of (recent) questions for which the poor souls authors didn't get any answer (0 response) yet?
There is such a fast rotation in questions that a few may have joined Voyager2 on the outer edges of space every day.

*

*a way that I didn't see (after honestly searching for 2 mn)

*or maybe a script / (scriptmonkey?)

A: Yes, you can do a search for answers:0, then hit the newest tab.
The direct URL for that is this.


text:
Q: Nodejs - removing substring from a huge file I need to remove a substring (that appears only in specific known lines of the file) from a file.
there are simple solutions of reading all file data to a string, removing the substring, and then write the fixed data to the file.
here is a code I found in here:
Node js - Remove string from text file
var data = fs.readFileSync('banlist.txt', 'utf-8');
var newValue = data.replace(new RegEx("STRING_TO_REMOVE"), '');
fs.writeFileSync('banlist.txt', newValue, 'utf-8');

My problem is, that the file is huge - up to billion lines of logs, so I can't read all content to the memory.

A: Why not a simple transform stream and replace()? replace can take a callback as second parameter i.e. .replace(/bad1|bad2|bad3/g, filterWords) in case you need to replace words rather than remove them completely.
const fs = require("fs")
const { pipeline, Transform } = require("stream")
const { join } = require("path")

const readFile = fs.createReadStream("./words.txt")
const writeFile = fs.createWriteStream(
  join(__dirname, "words-filtered.txt"),
  "utf8"
)

const transformFile = new Transform({
  transform(chunk, enc, next) {
    let c = chunk.toString().replace(/bad/g, "replaced")
    this.push(c)
    next()
  },
})

pipeline(readFile, transformFile, writeFile, (err) => {
  if (err) {
    console.log(err.message)
  }
})

A: https://nodejs.org/api/fs.html#fs_fs_read_fd_buffer_offset_length_position_callback
Dont read the whole file at once... read a small buffered piece of it.. and look for your input with that buffered piece.... then increment your buffer starting position and do it again....  would recommend having each buffer start not at the end of the previous buffer... but overlap by at least the expected size of the data being sought so that you dont run into half of your data being at end of one buffer and other half at beginning of the other

A: You could use a file read stream. However, you would have to find a way to detect if the read data only contains part of the result.

A: What you probably want to do is use streams so that you are writing after partial reads.  this example could probably work for you.  you need to copy over the output text file ".tmp" over the original to get the same behavior in your question.  It works by reading a chunk and then looking to see if you've come across a new line.  then it processes that line, writes it, then removes it from the buffer.  This should help with your memory problem.
var fs = require("fs");
var readStream = fs.createReadStream("./BFFile.txt", { encoding: "utf-8" });
var writeStream = fs.createWriteStream("./BFFile.txt.tmp");

const STRING_TO_REMOVE = "badword";
var buffer = ""

readStream.on("data", (chunk) => {
    buffer += chunk;
    var indexOfNewLine = buffer.search("\n");
    while (indexOfNewLine !== -1) {
        var line = buffer.substring(0, indexOfNewLine + 1);
        buffer = buffer.substring(indexOfNewLine + 1, buffer.length);
        line = line.replace(new RegExp(STRING_TO_REMOVE), "");
        writeStream.write(line);
        indexOfNewLine = buffer.search("\n");
    }
})

readStream.on("end", () => {
    buffer = buffer.replace(new RegExp(STRING_TO_REMOVE), "");
    writeStream.write(buffer);
    writeStream.close();
})

There are a few assumptions with this solution such as the data being UTF-8, there only being 1 bad word potentially per line, every line having some text (I didn't test for that), and that every line ends with new line and not some other line ending.
Heres the docs for streams in Node
another thought I had was to use pipe and a transform stream but that seems like over kill.

A: You can use this code to do it. I'm using fs stream. it's created for read huge files in small memory by chunks. docs
const fs = require('fs');

const readStream = fs.createReadStream('./XXXXX');
const writeStream = fs.createWriteStream('./XXXXXXX');

readStream.on('data', (chunk) => {
  const data = chunk.toString().replace('STRING_TO_REMOVE', 'XXXXXX');
  writeStream.write(data);
});

readStream.on('end', () => {
  writeStream.close();
});


text:
Q: How to set a directory for a executable file for different Operating Systems? I am trying to set a specific directory for my code which is a MFC project. A code for a dialog has been written(in visual studio c++) and now I am going to use .exe file of this code in different OS, and replace this file in those directory that I want. To arrive at this goal, I used GetModuleFileName function.Therefore, by following these suggestions I included this piece of code to OnInitDialog() function of my code:
//function that gets the directory without the file name:
    TCHAR szFilePath[_MAX_PATH];
    TCHAR driveLetter[3];
    TCHAR directory[MAX_PATH];
    TCHAR FinalPath[MAX_PATH];
    ::GetModuleFileName(NULL, szFilePath, _MAX_PATH);//Retrieves the current directory for the current process.
    // Add all the files and directories in the windows directory.
    //VERIFY(0 < ::GetWindowsDirectory(lpszWinPath, MAX_PATH));

    // Make the windows directory the current directory.
    ::GetCurrentDirectory(MAX_PATH, lpszOldPath);
    //::SetCurrentDirectory(lpszWinPath);
    ::SetCurrentDirectory("C:\\Program Files");

However, now I don't get any error message but I don't know why I can't see any output. As an example I expect a .exe file in specified directory be created.

A: The code above doesn't create any files whatsoever, so it won't create an EXE file. Assuming that it tried to create .\Foo.EXE it would effectively create C:\Program Files\Foo.EXE. This is not correct for a number of reasons. For starters, don't hardcode the path, as it differs from system to system. Call SHGetKnownFolderPath(FOLDERID_ProgramFiles, ...) to get that path.
Next, create a subdirectory there. Don't put executables there directly.
Finally, and perhaps most importantly, realize that this is the task of an installer running elevated. In normal use, Program Files is read-only. then normal programs don't create executables either.


text:
Q: Correct reasoning for a finite number of twin primes next to the lcm of first N numbers? Does the following argument make sense?
Let ${\rm lcm}(1,...,N)$ be the least common multiple of the first $N$ natural numbers.
In:
Highest Twin primes such that the number in between twins is the $\text{lcm}$ of first $N$ numbers
it is numerically shown that $N=47$ is the largest $N$ such that ${\rm lcm}(1,...,N) \pm 1$ are twin primes, for $N<36000$.
According to Brun's theorem the number of twin primes less than $n$, $\pi_2(n)$, does not exceed the following expression
$$\pi_2(n) < \frac{Cn}{\log^2n} $$
for some constant $C>0$. The ${\rm lcm}(1,...,N)$ can be written as
$${\rm lcm}(1,...,N)=e^{\psi(N)}$$
where $\psi(N)$ is the Chebyshev function that fulfills
$$|\psi(N)-N| = O\left(N^{\frac{1}{2}+\epsilon}\right)$$
for any $\epsilon > 0$.
Imagine we compute the first N ${\rm lcm}(1,...,j)$ with $j\leq N$, such that $n={\rm lcm}(1,...,N)=e^{\psi(N)}$. The probability $P$ that one of the ${\rm lcm}(1,...,j)$ is between 2 twin primes is as maximum given by
$$P < \frac{\frac{Ce^{\psi(N)}}{\log^2e^{\psi(N)}} }{e^{\psi(N)}}  = \frac{C}{\psi^2(N)} $$
and hence the number of ${\rm lcm}(1,...,j)$ in between twin primes is maximum $N\times P$,
$$ N\times P < \frac{CN}{\psi^2(N)} $$
which in the limit for very large $N$ vanishes,
$$\lim_{N \to \infty} \frac{CN}{\psi^2(N)} = 0$$
so in the limit $N\times P=0$, which cannot be consistent with infinite ${\rm lcm}(1,...,j)$ between Twin primes, right?
Note that the same argument for the number of single primes next to ${\rm lcm}(1,...,j)$ is consistent with infinite.


text:
Q: Retrieving a specific rows data from an html table I have the working code here that displays a table of users stored in my Oracle database:

                        User ID
                        Name
                        Username
                        Email
                        Joined
                        Profile

                    <c:forEach var="row" items="${users}">

                            ${row.user_id}
                            ${row.f_name} ${row.l_name}
                            ${row.username}
                            ${row.email}
                            ${row.joined}
                            View

                    </c:forEach>

What I'm trying to do is view a single users portfolio by clicking the "View" href. I need to somehow retrieve the information from that particular row so that I can put it into a Query and display all that particular users data.
Any ideas?


text:
Q: mysql constraint check produces error For homework we have to craft an sql statement that does quite a few things at once. I'll post it here
ALTER TABLE assn7 ADD gpa float DEFAULT 4.0
CONSTRAINT gpacheck
check(gpa >= 0.0 AND gpa <=4.0);
It should be obvious what I'm trying to do but I get an error
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CONSTRAINT gpacheck
check(gpa >= 0.0 AND gpa <=4.0)' at line 2
it works if I take out the constraint check but we need it to be one big sql statement.

A: your query statement is bit wrong. Per  MySQL manual it should be
ALTER TABLE assn7 ADD gpa float DEFAULT 4.0;
ALTER TABLE assn7 ADD CONSTRAINT gpacheck check(gpa >= 0.0 AND gpa <=4.0);

You can't mix both adding up a column and constraint together.
Though to point out; there is no Check constraint support in MySQL. Per manual it says

The CHECK clause is parsed but ignored by all storage engines.

Alternative, is to go for triggers (BEFORE INSERT TRIGGER)

A: Check constraints don't work in MySQL, but you can achieve your statement in one line by adding a comma like this:
ALTER TABLE assn7 ADD gpa float DEFAULT 4.0, ADD CONSTRAINT gpacheck check(gpa >= 0.0 AND gpa <=4.0);


text:
Q: iOS 7 - UIPickerView over UITableView I can't find anything else on the internet about this specific topic. Everyone else wants to know how to do inline UIPickerView, but there is nothing on just having a UIPickerView appear over a table.
I have a TableView with a bunch of populated cells. I also have a defunct button in the top left of the screen. What I want is to be able to press the button, bring up a Picker and sort the TableView's cells based on what is selected.
I've been looking around and trying for ages and I just can't find anything detailing a solution to my problem.

A: I would try using ActionSheetPicker-3.0
It makes it easy to present a UIPickerView over your current view without having to use a delegate as it uses callback blocks.


text:
Q: Numerical Integration of a high dimensional function My problem is the following, I have a function, with an input vector of $\mathbb{R^{3072}}$, which outputs {$\mathbb{ x \in R : 0 \leq x \leq 1}$}. I want to find the integral of the function over the box $\mathbb{[0, 255]^{3072}}$.
I know about the function, that in most case it outputs $\mathbb{0}$ or a value close to $\mathbb{0}$ and I know some vectors for which it outputs a value close to $\mathbb{1}$. I so far tried to use crude Monte Carlo Integration in order to approximate the integral, however the results are not very good, due to the very low probability of getting a random point that results in an output close to $\mathbb{1}$. I therefore wanted to ask if someone has an idea how to tackle my problem in order to find a better approximation of the integral of my function, given the available information about the function.


text:
Q: Internet Explorer takes considerably more time to load than FireFox-- to the point where it actually freezes. How can I prevent this? One of our main pages takes an immense amount of time to load in IE8 (have not tried IE7 or 6). It's so bad that IE actually freezes up for a few seconds while trying to load the page.
Firefox is perfectly fine...
I've tried a bunch of different things but I cannot figure out what it is.
It's not very js intensive, although we are using modules (platform is DNN) that may be using a lot of js.
here's the link: One World United
username: matt
password: globalbuying
Could you please take a look at the page and try to analyze what it is and what we can do to fix it.
Thanks,
Matt

A: Have you tested the site with IE8 compatibility mode on, and then compatibility mode off?  If either of those works significantly better, you could try something like forcing IE7 standards mode:
http://www.thechoppr.com/blog/2009/04/07/force-ie7-standards-on-ie8/

A: Are you trying to manipulate any divs with js before they are fully parsed? That will screw up IE but FireFox will process that just fine.

A: Didnt take much time to load for me either. This has happened to me occasionally when I had an unclosed div that was somehow conflicting with some JavaScript that I had at the end of the HTML.

A: well on my comp it took less than 5 seconds to load, did you test it on multiple computers or just one? if just one it could be an addin issue.


text:
Q: sqlAlchemy does not recognise changes to DB made outside of session Something peculiar I've noticed is that any changes committed to the DB outside of the session (such as ones made in MySQL's Workbench) are not recognised in the sqlAlchemy session. I have to close and open a new session for sqlAlchemy to recognise it.
For example, a row I deleted manually is still fetched from sqlAlchemy.
This is how I initialise the session:
engine   = create_engine('mysql://{}:{}@{}/{}'.format(username, password, host, schema), pool_recycle=3600)
Session  = sessionmaker(bind=engine)
session  = Session()
metadata = MetaData()

How can I get sqlAlchemy to recognise them?
My sqlAlchemy version is 0.9.4 and my MySQL version is 5.5.34. We use only sqlAlchemy's Core (no ORM).

A: To be able to read committed data from others transactions you'll need to set transaction isolation level to READ COMMITTED. For sqlalchemy and mysql:
To set isolation level using create_engine():
engine = create_engine(
    "mysql://scott:tiger@localhost/test",
    isolation_level="READ COMMITTED")

To set using per-connection execution options:
connection = engine.connect()
connection = connection.execution_options(
    isolation_level="READ COMMITTED")

source


text:
Q: Multiple action 'on' events in ember.js I'm trying to have an element be able to be clicked on by both touchscreens, and clicking, through the events touchStart and click.
How can I get both of these events connected to one Ember view?
I have tried:
{{action "itsClicked" on="click touchMove"}}
{{action "itsClicked" on="click, touchMove"}}
{{action "itsClicked" on="click"}} {{action "itsClicked" on="touchMove"}}

A: This is currently not supported. But there is an open issue about this, see #569 in the GitHub issue tracker. You should add a comment.
The suggested solution from the GitHub issue is to use a custom view, something like this:
Ember.View.extend({
    click: function(evt) {
        this.fire('itsClicked', evt);
    },
    touchMove: function() {
        this.fire('itsClicked', evt);
    },
    itsClicked: function(e) {
        ...
    }
})

A: Multiple actions are not supported - this forces you separate your code by creating components (or views).
However, you can easily solve the click/touch issue for your application by creating a custom event:
App = Ember.Application.create({
    customEvents: {touchend: "click"}
});

This means all your "click" events will fire when touched