text:
Q: Need regex to find text outside the tags ONLY javascript Need regex to find text outside any HTML tags
like
<tag>Some</tag>Text, you have <tag url="something">Here</tag>

Result:
"Text, you have "

Here, a tag can be any HTML tag, not specified. Regex should ignore tags and text between text and return text which is outside of all tags

A: It is better to do dom parsing than regex for html content parsing

var string = '<tag>Some</tag>Text, you have <tag url="something">Here</tag>';

var tmp = document.createElement('div');
tmp.innerHTML = string;
var lst = [];
for (var i = 0; i < tmp.childNodes.length; i++) {
  if (tmp.childNodes[i].nodeType == Node.TEXT_NODE) {
    lst.push(tmp.childNodes[i].nodeValue);//use trim if needed
  }
}

var text = lst.join('');
snippet.log(text)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

A: Just remove all the tags.

var s = '<tag>Some</tag>Text, you have <tag url="something">Here</tag>';
alert(s.replace(/<(\w+)\b[^<>]*>[\s\S]*?<\/\1>/g, ''))

DEMO


text:
Q: Show offer depending on product price I currently looked around for some attractive ways to engage to customers perspectives and I came across to elaborate a message for each product "depending on its price".
This topic is mainly for Business Catalyst but some expert on javascript may help.
The target is use liquid or some flexible Javascript on the small-product layout and calculate product price if higher or equal to 30 and display a you got free shipping for this product
I am currently using a jquery but not working dont know why!?
$('.price').each(function(){
    if(parseInt($(this).val()) > 30) {
   $('#get-free').show();
}
});

SALE

{tag_smallimage}

{tag_name}

{tag_saleprice}

{tag_retailprice}

{tag_instock} IN STOCK

FREE SHIPPING FOR THIS PRODUCT

{tag_itemurl_nolink}

 {tag_addtofavorites,
  ADD TO FAVORITES
,
 REMOVE FAVORITE}

Some help is much appreciated.
Thanks

A: You should try using .text() (http://api.jquery.com/text/) or .html() instead of val(). val() is used mainly for form input fields (http://api.jquery.com/val/)

A: Use text() instead of val() for non-input elements like divs.  Also, you should test for NaN using isNaN when using parseInt, although in this case the desired effect (showing the free pricing) would not occur if the price field were blank.
if(!isNaN(parseInt($(this).text())) && parseInt($(this).text()) > 30)

Here is a Fiddle Demo

A: Thanks to a piece of code from Vitorino I was able to come to a clear point but the real reason why it didn't get the string correctly was because of the "£" sign that was generated by the {tag_saleprice} by using .replace(/[^0-9.]/g, "");  that I used before, I was able to pass the value clear of the sign "£", below is the code for those who need:
$('.price').each(function() {
var price = $(this).text().replace(/[^0-9\.]/g, "");
   if (parseInt(price) >= 30) {
    $(this).siblings('.get-free').show();
  }
});

Demo

redpajama_set_name: RedPajamaStackExchange


text:
Q: Alternative solution for Azure Service Fabric distributed cache I have an application running in Service Fabric with multiple nodes. All the running nodes share some cache data using distributed caching available in Service Fabric.
Now, I am looking to move out from Service Fabric due to cost issues.
What would be a good solution for me where I can also maintain caching between multiple instances ( like the distributed cache in Service Fabric).
I need to install it in an Azure environment.

A: If you're looking for an alternative managed by Microsoft, the best choice would be Azure Redis Cache.
More info:
https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/


text:
Q: Step by step with django-jet-demo I am trying to see django-jet-demo in action, i.e. https://github.com/geex-arts/django-jet-demo, but It didn't work.

*

*git clone https://github.com/geex-arts/django-jet-demo.git

*mkvirtualenv venv

*cd django-jet-demo

*pip install -r requirements/base.txt

*django makemigrations
I have the errors
1- configparser.NoSectionError: No section: 'common'
If I remove config.get(..., 'common') inside application/settings.py
2- configparser.NoSectionError: No section: 'email'
If I remove config.get(..., 'email') inside application/settings.py
3- configparser.NoSectionError: No section: 'database'
How could I fix this problem? What are the steps to make django-jet-demo works? Does it work well on your computer?
UPDATE
If I modify default.conf file, I got the same first error.
[common]
secret_key='t_g&c7^(!jb*$caaeue%$t_0pdtx5z(a7v%b6#svl1&0$5h9o-'
debug=False

[email]
server_email=test@test.com
host=localhost
port=1025
user=
password=
tls=True

[database]
ENGINE=django.db.backends.mysql
NAME=capitaine
USER=root
PASSWORD=wd9598%%DD
HOST='localhost'
PORT=3306

A: There is a file named default.conf where the values of each section are empty and you should add appropriate values for at least secret_key, server_email and the [database] section.
If you don't want to use mysql as the db backend, use sqlite instead (without the need of NAME, USER, PASSWORD etc).
Also note that you have to create this .conf file under the path:
/path/to/project/conf/project_name.conf

Of course, change project_name to your actual project's name.


text:
Q: Why is it discouraged to use absolute paths in Shiny includeScript()? From ?includeScript:

path:
   The path of the file to be included. It is highly recommended to use a relative path (the base path being the Shiny application
  directory), not an absolute path.

But the function includeScript reads the script with readLines, it doesn't somehow include the path in HTML so that it would get loaded client side (which would obviously be bad). So I don't see why I shouldn't use an absolute path. In particular, my application would be includeScript(system.file("js/blub.js", package="mypackage")) (and my Shiny app is in objects, not sourced) so to me this is the nice way to do it. Am I wrong?

A: You wouldn't want to use an absolute path as, if you moved the application to another system, it might stop working---if the directory structure on the systems differed.
But, it doesn't look like you are using an absolute path. An absolute path is something like /home/meow/blub.js.


text:
Q: How do I manage Protected Custom Settings in a BETA package? As I understand there are two visibility modes for Custom Settings:

*

*Public settings, accessed via Setup > Custom Settings

*Protected settings, via Grant Login Access after installing a security reviewed package

The latter is great for hiding your dirty post-install laundry from package users. Or for using settings as invisible tables to hold generated data (like countries and states) that can't be messed with.
But it seems with Protected Custom Settings, there is no way to administer them in BETA.
If there is no License record and hence no Login Access, how can the settings be administered through the native user interface?

A: Here's a suggestion that may be of use to you that's based on the classic test helper class such as the one below which contains a few snippets of one I used recently for an org I was working in. I'll explain some suggested modifications at the end.
/**
 * A collection of utilities and methods for use in unit tests.
 * @author crmprogdev
 */

@isTest(seeAllData=true)
global class XXXX_Test_Helper_Util {

global PrimAdmin_CustSttng__c Admin {set;}
global PrimAdmin_CustSttng__c Admin1 {set;}
global TBA_CustSttng__c TBA {set;}
global EHcc_CustSttng__c CC1 {set;}
global Pub_Boolean_A__c BoolA {get;}
global Pub_Bool_B__c BoolB {get;}

global static void init() {
    /* create our global settings object and set the defaults */

    PrimAdmin_CustSttng__c Admin = generateTestPrimAdmin();
    PrimAdmin_CustSttng__c Admin1 = generateTestPrimAdmin1();
    EHcc_CustSttng__c CC1 = generateTestCC1();

    User TBA_u = generateTBA();

    TBA_CustSttng__c TBA = generateTestTBA(TBA_u);

}

/** a default user to use in System.runAs() */
private static User testRunner {
    get {
        if (null == testRunner) {
            // all test code should execute under a user we can control so as to avoid
            // surprises when deploying to different environments.
            UserRole[] roles = [SELECT Id FROM UserRole WHERE DeveloperName = 'Admin'];
            if (roles.isEmpty() == true) {
                roles.add(new UserRole(DeveloperName = 'Admin', Name = 'r0'));
                insert roles;
            }

            testRunner = new User(Alias = 'tstr01', Email='tstr01@kube.com', EmailEncodingKey='UTF-8', FirstName= 'TstrFrst', LastName='TstrLst01', LanguageLocaleKey='en_US', LocaleSidKey='en_US', TimeZoneSidKey='America/Los_Angeles', UserName='tstt01@xxx.com');
            testRunner.UserRoleId = roles[0].Id;
            insert testRunner;
        }

        return testRunner;
    }

    private set;
}

global static PrimAdmin_CustSttng__c generateTestPrimAdmin(){
        PrimAdmin_CustSttng__c Admin = new PrimAdmin_CustSttng__c();
        if (PrimAdmin_CustSttng__c.getValues('Admin') == null){

            Admin.ContactName__c = 'Carey XXXX' ;
            Admin.UserID__c = 'xxxxxxxxxx'; //(sandbox, prod)
            Admin.UserName__c = 'support@xxxx.com';
            Admin.Email__c = 'support@xxxx.com';    // support@xxx.com.xxxxsandb
            Admin.Name = 'Admin';
            upsert Admin;

        }
        else if (PrimAdmin_CustSttng__c.getValues('Admin') != null ){
            Admin = PrimAdmin_CustSttng__c.getValues('Admin');

        }

        return Admin;
}

global static PrimAdmin_CustSttng__c generateTestPrimAdmin1(){
        PrimAdmin_CustSttng__c Admin1 = new PrimAdmin_CustSttng__c();
        if (PrimAdmin_CustSttng__c.getValues('Admin1') == null){
            Admin1.ContactName__c = 'Steven XXXXX';
            Admin1.UserID__c = xxxxxxxxxx; //(sandbox, prod)
            Admin1.UserName__c = 'xxxxxxxxxx@gmail.com';
            Admin1.Email__c = 'stevenjxxxxxx@gmail.com';
            Admin1.Name = 'Admin1';
            upsert Admin1;

        }
        else if (PrimAdmin_CustSttng__c.getValues('Admin1') != null ){
            Admin1 = PrimAdmin_CustSttng__c.getValues('Admin1');

        }
        return Admin1;
}

global static EHcc_CustSttng__c generateTestCC1(){
        EHcc_CustSttng__c CC1 = new EHcc_CustSttng__c();
        if (EHcc_CustSttng__c.getValues('CC1') == null){
            CC1.Name = 'CC1';
            CC1.SendCC__c = true;
            upsert CC1;

        }
        else if (EHcc_CustSttng__c.getValues('CC1') != null ){
            CC1 = EHcc_CustSttng__c.getValues('CC1');

        }
        return CC1;
}

global static User generateTBA(){

    User U0 = [SELECT Id, Name, email, Division, Title, UserRoleId, ProfileId, Username FROM User WHERE IsActive = True AND (Profile.DeveloperNameId = 'Admin' OR Profile.Id = 'FloridaAdmin') limit 1];
    User U1 = [SELECT Id, Name, email, Division, Title, UserRoleId, ProfileId, Username FROM User WHERE IsActive = True AND (Profile.DeveloperNameId = 'SalesManager' OR Profile.Id = 'FloridaSalesManager') AND UserRole.Name = 'Project Manager' limit 1];
    list<Account> TBAa = new list<Account>(); // TBA contact list
    list<Id> TBAasrId = new list<Id>(); // TBAa insert results validation list
    list<Contact> TBAc = new list<Contact>(); // TBA contact list
    list<Id> TBAcsrId = new list<Id>(); // TBAc insert results validation list
    list<User> TBAu = new list<User>(); // TBA user list
    list<Id> TBAusrId = new list<Id>(); // TBAu insert results validation list

    if(U0.Id == null ){
        TBAu[0] = null;

    } else
    system.RunAs(U0){

    /* create the TBA acct */

    Account tbaact = new Account(Name = 'TBAact', Is_Active__c = true, Region__c = 'SouthEast', OwnerID = U1.Id  );

    TBAa.add(tbaact);

    /* insert the new Accts */

    if(TBAa.IsEmpty() == false)Insert TBAa;

        /* Create the TBA contact */

    Contact tbaCtc = new Contact( AccountID = TBAa[0].Id, LastName = 'TBAtst1', Phone = '777-755-0001', MailingStreet = '999 TBD St', MailingCity = 'TBA', MailingState = 'FL', Position__c = 'Ambassador', MobilePhone = '777-755-1001', RecordTypeId = '012400000005IeZAAU' );

    TBAc.add(tbaCtc);

    /* insert the tbaCtc */

    if(TBAc.IsEmpty() == false) Insert(TBAc);

    /* create the TBA user */

    User tbaUsr = new User(ContactID = TBAc[0].Id, Alias = 'tbatst1', Email='tbatst1@xxxxtst.com', EmailEncodingKey='UTF-8', LastName= TBAc[0].LastName, LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = U5.ProfileId, MobilePhone = TBAc[0].MobilePhone, Phone = TBAc[0].Phone,TimeZoneSidKey='America/Los_Angeles', UserName='tbatst1@xxtst.com');

    TBAu.add(tbaUsr);

    if(TBAu.IsEmpty() == false) Insert TBAu;

    TBA_CustSttng__c TBA2 = new TBA_CustSttng__c();
    TBA2 = Kube_Test_Helper_Util.generateTestTBA(TBAu[0]);
    }
    return TBAu[0];
}

public static TBA_CustSttng__c generateTestTBA(User TBA_u){

    User TBAu = TBA_u;
    TBA_CustSttng__c TBA1 = new TBA_CustSttng__c ();
    if(null == TBA1){
    TBA1.ContactID__c = TBAu.ContactId;
    TBA1.ContactName__c = 'TBAtst1';
    TBA1.CtcRecTypeID__c = '012400000005IeZAAU';
    TBA1.UserID__c = TBAu.Id;
    TBA1.UserName__c = TBAu.UserName;
    TBA1.UserProfileID__c = TBAu.ProfileId;
    TBA1.Email__c = TBAu.Email ;
    TBA1.Name = 'TBA1';
    upsert TBA1;
    }
    return TBA1;

    }
}

You'll notice I've included a number of custom settings in the above. The custom settings that I'd want to be private would be:
PrimAdmin_CustSttng__c Admin {set;}
PrimAdmin_CustSttng__c Admin1 {set;}
TBA_CustSttng__c TBA {set;}

All of the above contain information about UserID's, email addresses, etc that you don't want to be visible to anyone else.
The custom settings to be set as public would be:
    global EHcc_CustSttng__c CC1 {set;}
global Pub_Boolean_A__c BoolA {get;}
global Pub_Bool_B__c BoolB {get;}

The first one simply is used to set whether or not a CC is sent with an error handler message. The latter two are booleans that I've added for the purpose of answering this post. By using a strategy of setting Booleans in a Public Custom Setting, values could presumably be changed if the Boolean were set to True. So by altering the above code as below, I believe something like this could potentially work as a solution:
global static PrimAdmin_CustSttng__c generateTestPrimAdmin(){
        PrimAdmin_CustSttng__c Admin = new PrimAdmin_CustSttng__c();
        if (Pub_Boolean_A__c.getValues('BoolA') != null && BoolA.Value == 'true'){

            Admin.ContactName__c = BoolA.ContactName__c ;
            Admin.UserID__c = BoolA.UserID__c
            Admin.UserName__c = BoolA.UserName__c;
            Admin.Email__c = BoolA.Email__c;    // support@xxx.com.xxxxsandb
            Admin.Name = BoolA.Name;
            upsert Admin;

        }
        else if (Pub_Boolean_A__c.getValues('BoolA') == null || BoolA.Value == 'false'){

            Admin.ContactName__c = 'Carey XXXX' ;
            Admin.UserID__c = 'xxxxxxxxxx'; //(sandbox, prod)
            Admin.UserName__c = 'support@xxxx.com';
            Admin.Email__c = 'support@xxxx.com';    // support@xxx.com.xxxxsandb
            Admin.Name = 'Admin';
            upsert Admin;

        }
        else if (PrimAdmin_CustSttng__c.getValues('Admin') != null ){
            Admin = PrimAdmin_CustSttng__c.getValues('Admin');

        }

        return Admin;
}

It would seem to me that using this type of approach would allow a developer of managed packages to have their private custom settings, yet also all them to "edit" them using public custom settings during development.
Note: I have not tested this, instead only taking the time to collect some snippets of code and modify them "on the fly" to present the concept for consideration. I do not develop "officially" managed packages as yet but can see where this approach would seem likely to prove fruitful. Obviously the runAs user in the code I presented would not be necessary. I included it to illustrate the source and context of the original code.


text:
Q: Green function for Fourier transform In the context of a project, I had to solve numerically Poisson equation with cylindrical coordinates. I put here results for z = 0 on a 3D mesh 256x256x256.
When I define Green function, have I to add a factor space_x, space_y and space_z (size of cell on the grid) respectively for dx, dy, dz ? I mean like this below :
 dx = sqrt(pow((double) (i-Ng/2),2.0))*space_x;
 dy = sqrt(pow((double) (j-Ng/2),2.0))*space_y;
 dz = sqrt(pow((double) (k-Ng/2),2.0))*space_z;

If I don't add these factors, i.e :
 dx = sqrt(pow((double) (i-Ng/2),2.0));
 dy = sqrt(pow((double) (j-Ng/2),2.0));
 dz = sqrt(pow((double) (k-Ng/2),2.0));

I don't know if I have to include these space_x, space_y and space_z in Green function.
Any help is welcome,

A: The gravitational potential at the point $ \vec{x_0} $ of a collection of $ n $ point objects of mass $ M_i $ each located at a point $ \vec{x_i} $ is:
\begin{align}
\Phi = \Sigma_{i=1}^{n} \frac{-GM_i}{|\vec{x_i}-\vec{x_0}|}
\end{align}
I'm not entirely use what you are doing with the Green's function array (is this a built in function?), but for this problem it is unnecessary as you can simply sum up the contribution from each mass. Also, are your stars spaced only along x? If not, it looks like you might have a looping error:
for (i=0; i< numStars; i++)
{
   dx = sqrt(pow((double) (i-Ng/2),2.0))*space_x;
   dy = sqrt(pow((double) (j-Ng/2),2.0))*space_y;
   dz = sqrt(pow((double) (k-Ng/2),2.0))*space_z;

   green_grid[i][j][k] = -1.0/(4.0*M_PI*sqrt(dx*dx + dy*dy + dz*dz));
}

Since i is referring both to the star entry and its x position?


text:
Q: One object changes another objects background image...? I am making a quiz project, like a TV game show, and when a player hovers or selects their quiz response, a light on the side of the game board lights up.
Basically, I'd like a hover and a click to change the background image of a separate object.
Please help me to do this.
I am using CSS and HTML5
Thank you.

A: Oh. The joy.
Mooseman's suggestion about sibling combinators helped me find this post:
CSS event on one element, changing an other
Sorry that my post is redundant.
But I'm just glad I got it working.
Thank you.


text:
Q: How to add login Items by code to mountain lion osx I want to add login items programmatically in Mountain Lion (10.8).
Until now I was able to add login items by editing this plist:
/Users/test/Library/Preferences/loginwindow.plist

and adding items (path,name,hide) to AutoLaunchedApplicationDictionary dictionary
in the OS doesn't work anymore. Items that are added to this dictionary are not launched on login. I see that the login items are saved in a file called: com.apple.loginitems.plist
but I don't understand how to add an item to this file. I tried to add the item to CustomListItems dictionary with parameters like name,path, hide but they were not launched on login.
Does anyone know how can I add from code login item?

A: I understand you want to start your program automatically when your user logs in.
In older versions of OS X, it was possible to add login items manually by editing loginwindow.plist. Apple deprecated this approach when they added LaunchAgent and LaunchDaemon functionality to the OS.
Since you are using Mountain Lion, the correct way to have a program launch is to create a launchagent for it. This is a .plist file that you can use to tell OS X to a) perform some action (e.g.: launch /some/program.app) when b) a specific event occurs (e.g.: logging in, logging out, etc)
You will find Apple's official document on creation of LaunchAgents over here.

A: This looks like a great tutorial on the modern way of doing things: The launch at login sandbox project
It starts with a paragraph buried in the App Sandbox design guide:
Creating a Login Item for Your App

To create a login item for your sandboxed app, use the SMLoginItemSetEnabled function (declared in ServiceManagement/SMLoginItem.h) as described in "Adding Login Items Using the Service Management Framework" in Daemons and Services Programming Guide.

(With App Sandbox, you cannot create a login item using functions in the LSSharedFileList.h header file. For example, you cannot use the function LSSharedFileListInsertItemURL. Nor can you manipulate the state of launch services, such as by using the function LSRegisterURL.)
And rolls from there...


text:
Q: Using microservices to create a trigger framework I recently heard about a trigger framework that's based on the microservices architecture. I have searched around and nothing useful has come up. Does anybody have any resources to share?
I can picture Process Builder being the entry-point here, but don't know how the rest of it could look like.


text:
Q: What lib (custom JTabbedPane) is used on this picture? I found a picture - java swing nimbus. There they use non-standard JTabbedPane. I want such custom JTabbedPane! What lib should I use for that? Can you advise lib like that?

A: Nimbus is a type of look an feel in swing and you can set it as follows
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");


text:
Q: Two timers causing conflict in WinForms application I have two timers (System.Windows.Forms.Timer) in a WinForms application.
Both timers start at the same time.  One timer starts and stops throughout the life of the program updating three labels, the other just runs and does its work at every tick event updating one label.  However, when the first timer is running code in its tick event the second timer isn't running.
In the first timer tick event code I have inserted multiple System.Threading.Thread.Yield(); statements, but the second timer is still being blocked.  Searches for this comes up null.
I tried using system threading for the second timer, but it isn't doing anything.
I'm at a loss.
Any ideas?
public partial class fMain2 : Form
{
    private System.Windows.Forms.Timer timer;
    private System.Windows.Forms.Timer timer2;
    private Thread tThread;

    private int totTime;
    private int curTime;
    private int exTime = 0;
    public int runTime = 0;

    private void cmdRun_Click(object sender, EventArgs e)
    {
        //calculate total time
        totTime = iCount * iDuration;
        lblTotTime.Text = totTime.ToString();
        lblTotEx.Text = exTime.ToString();
        System.Threading.Thread.Yield();

        curTime = int.Parse("0" + txtDuration.Text);

        System.Threading.Thread.Yield();

        this.Refresh();

        strFile = "Begin" + ".wav";
        snd.SoundLocation = strSoundFilePath + strFile;
        snd.PlaySync();

        //select first item in the listview
        lvTimer.Items[0].Selected = true;
        lvi = lvTimer.Items[0];
        lvTimer.Refresh();

        strFile = lvi.SubItems[1].Text + ".wav";
        snd.SoundLocation = strSoundFilePath + strFile;
        snd.PlaySync();
        System.Threading.Thread.Yield();

        strFile = "Go" + ".wav";
        snd.SoundLocation = strSoundFilePath + strFile;
        snd.PlaySync();

        //attempted using a thread for timer2
        timer.Start();
        //tThread = new Thread(new ThreadStart(timer2.Start));

        timer2.Start();
        //tThread.Start();
    }

    private void timerTick(object sender, EventArgs e)
    {
        string strFile;

        curTime -= 1;
        totTime -= 1;

        exTime += 1;

        System.Threading.Thread.Yield();

        lblCurTime.Text = curTime.ToString();
        lblTotTime.Text = totTime.ToString();
        lblTotEx.Text = exTime.ToString();
        this.Refresh();

        System.Threading.Thread.Yield();

        if (curTime == 0)
        {
            timer.Stop();

            System.Threading.Thread.Yield();
            System.Threading.Thread.Yield();

            strFile = "Stop" + ".wav";
            snd.SoundLocation = strSoundFilePath + strFile;
            snd.PlaySync();

            System.Threading.Thread.Yield();
            System.Threading.Thread.Yield();

            if (totTime == 0)
            {
                //this marks the end of the program
                timer2.Stop();
                //tThread.Abort();

                //more code but not relevant
                return;
            }
            else
            { //we are still working down the listview

                try
                {
                    lvi = lvTimer.Items[lvi.Index + 1];
                    lvTimer.Items[lvi.Index].Selected = true;
                    lvTimer.FocusedItem = lvTimer.Items[lvi.Index];
                    lvTimer.Refresh();
                    System.Threading.Thread.Yield();
                    System.Threading.Thread.Yield();
                    System.Threading.Thread.Yield();
                }
                catch (IndexOutOfRangeException ei)
                {
                    strFile = "End" + ".wav";
                    snd.SoundLocation = strSoundFilePath + strFile;
                    snd.PlaySync();
                    bRunning = false;
                    ResetTime();
                    return;
                }

                curTime = int.Parse("0" + txtDuration.Text);

                lblCurTime.Text = curTime.ToString();
                lblTotTime.Text = totTime.ToString();

                System.Threading.Thread.Yield();
                System.Threading.Thread.Yield();

                //I'm wondering if the soundplayer is causing the problem
                strFile = lvi.SubItems[1].Text + ".wav";
                snd.SoundLocation = strSoundFilePath + strFile;
                System.Threading.Thread.Yield();
                System.Threading.Thread.Yield();

                snd.PlaySync();

                System.Threading.Thread.Yield();
                System.Threading.Thread.Yield();

                strFile = "Go" + ".wav";
                snd.SoundLocation = strSoundFilePath + strFile;
                snd.PlaySync();

                System.Threading.Thread.Yield();
                System.Threading.Thread.Yield();

                System.Threading.Thread.Yield();

                timer.Start();
            }
        }
    }

    private void timer2Tick(object sender, EventArgs e)
    {
        //this is all timer2 does.  It runs as long as the
        //  program is running.
        runTime += 1;
        lblTotTotal.Text = (runTime / 60).ToString()
            + ":" + (runTime % 60).ToString("00");
    }
}

I am using VS 2017.

A: System.Windows.Forms.Timer is designed to run code on the UI thread. Calling System.Threading.Thread.Yield() tells the system to run another thread that is ready to run on the current core, but your timers want to run on the UI thread so it doesn't help in any way.
It seems to me that you're blocking the UI thread playing your sound with .PlaySync().
I'm going to suggest that you push the playing of the sound to a background thread to free up the UI.
From what I can gather from your code, you're trying to play a series of sounds like this:
"Begin.wav", then "ListItem1.wav", then"Go.wav"
(wait a period of time)
"ListItem2.wav", then "Go.wav"
(wait a period of time)
"ListItem3.wav", then "Go.wav"
(wait a period of time)
"End.wav"

However, if a timer runs out then cancel playing these sounds and play a "Stop.wav" sound instead.
This structure can be modelled with a Queue<Queue<string>> and you just need to a nested dequeue and pay all of the sounds.
Queue<Queue<string>> queue =
    new Queue<Queue<string>>(new[]
    {
        new Queue<string>(new[] { "Begin.wav", "ListItem1.wav", "Go.wav" }),
        new Queue<string>(new[] { "ListItem2.wav", "Go.wav" }),
        new Queue<string>(new[] { "ListItem3.wav", "Go.wav" }),
        new Queue<string>(new[] { "End.wav" }),
    });

Here's the code to dequeue the queues:
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;

Task task = Task.Run(async () =>
{
    while (queue.Any())
    {
        if (ct.IsCancellationRequested)
        {
            break;
        }
        Queue<string> inner = queue.Dequeue();
        while (inner.Any())
        {
            if (ct.IsCancellationRequested)
            {
                break;
            }
            string soundLocation = inner.Dequeue();
            using (System.Media.SoundPlayer sp = new System.Media.SoundPlayer())
            {
                sp.SoundLocation = soundLocation;
                sp.PlaySync();
            }
        }
        if (ct.IsCancellationRequested)
        {
            using (System.Media.SoundPlayer sp = new System.Media.SoundPlayer())
            {
                sp.SoundLocation = soundLocationStop;
                sp.PlaySync();
            }
        }
        else
        {
            await Task.Delay(TimeSpan.FromSeconds(2.0));
        }
    }
});

Note that this is all run in a Task.Run so it's not blocking the UI thread.
To stop the processing of the sound, just call cts.Cancel();.
You now just need to build your queue in the cmdRun_Click method.
private void cmdRun_Click(object sender, EventArgs e)
{
    string[][] soundLocationGroups =
    (
        from x in lvTimer.Items.Cast<ListViewItem>()
        from y in x.SubItems.Cast<ListViewItem.ListViewSubItem>()
        select new[] { Path.Combine(strSoundFilePath, $"{y.Text}.wav"), Path.Combine(strSoundFilePath, $"Go.wav") }
    ).ToArray();

    soundLocationGroups =
        soundLocationGroups
            .Take(1)
            .Select(xs => xs.Prepend(Path.Combine(strSoundFilePath, $"Begin.wav")).ToArray())
            .Concat(soundLocationGroups.Skip(1))
            .Append(new[] { Path.Combine(strSoundFilePath, $"End.wav") })
            .ToArray();

    string soundLocationStop = Path.Combine(strSoundFilePath, $"Stop.wav");

    Queue<Queue<string>> queue = new Queue<Queue<string>>(soundLocationGroups.Select(x => new Queue<string>(x)));

You still need a single timer to know if you should call cts.Cancel().
I did test my Task.Run code before posting. It works.

A: My suggestion is to use async/await.
Step 1: Get rid of all the System.Threading.Thread.Yield(); calls.
Step 2: Get rid of all the .Refresh(); calls.
Step 3: Make the timerTick async: private async void timerTick(object sender, EventArgs e)
Step 4: Replace every occurrence of snd.PlaySync(); with await Task.Run(() => snd.PlaySync());
The Task.Run method invokes the specified lambda on the ThreadPool. The await allows the current thread to continue doing other things, like responding to user input, while the lambda is running on the ThreadPool. After the lambda completes, the current thread continues executing the code that follows the await, until the next await, or until the end of the handler.
After doing these changes the UI should be responsive again, and the other timer should be ticking normally every second.
Be aware that by making the timerTick handler async, it is now possible to be invoked in an overlapping manner. It's up to you to prevent the overlapping, by checking and updating fields of the form.


text:
Q: Java spring LDAP - Waring LDAP password expire We are using active directory to manage user account. Now we want to use password policy to set max password age to force user reset password after 2 months. And we need to warn user after they login if his password is going to be expired soon (3 days, for example).
How can we obtain this? We are using Spring LDAP 1.3.0.
I googled and see the password max age property is set in domain. However, I don't know how to get this value.
Thanks
COL

A: Credentials expiration date and time
Getting the date and time at which the password was last changed:
private final static long DIFF_NET_JAVA_FOR_DATE_AND_TIMES = 11644473600000L;
long adDateTime = Long.parseLong(pwdLastSet);
long milliseconds = (adDateTime / 10000) - DIFF_NET_JAVA_FOR_DATE_AND_TIMES;
Date pwdLastSetDate = new Date(milliseconds);

Getting the number of max days that could have the password:
private final static int ONE_HUNDRED_NANOSECOND = 10000000;
private final static long SECONDS_IN_DAY = 86400;
long maxPwdAge = Math.abs(Long.parseLong(maxPwdAgeStr));
long maxPwdAgeSecs = maxPwdAge / ONE_HUNDRED_NANOSECOND;
int maxPwdAgeDays = (int) (maxPwdAgeSecs / SECONDS_IN_DAY);

Getting the the date and time at which the password will expire
Calendar cal = Calendar.getInstance();
cal.setTime(pwdLastSetDate);
cal.add(Calendar.DATE, maxPwdAgeDays);
Date credentialsExpiresDate = cal.getTime();

A: You need to use the extended password request and response controls to get this information. See my answer to this question for a link to the necessary Java code.


text:
Q: Convert CSV to excel using xlsxwriter and save it to django Model Now I don't have any problems about converting this csv or downloading it I have a problem saving it to django model at filefield
The minmized sample code:
def download_convert_reports_s3_temp():
    def get_report_url():
        bucket_name = 'temp_bucket'
        conn = boto.connect_s3(AWS_ACCESS_KEY_ID,
                               AWS_SECRET_ACCESS_KEY)
        bucket = conn.get_bucket(bucket_name)
        key = bucket.get_key('TEMP_2017-01-10.csv')
        return key.generate_url(expires_in=600)

    def get_doc():
        return Doc.objects.get(owner=User.objects.first())

    def get_file(file):
        file_temp = NamedTemporaryFile(delete=True)
        file_temp.write(file.content)
        file_temp.flush()
        return File(file_temp)

    def convert_csv_to_xlsx():
        request = requests.get(get_report_url())
        csvfile = get_file(request)

        from django.conf import settings
        excelFile = xlsxwriter.Workbook('report.xlsx', {
                                            'strings_to_numbers': True,
                                            'default_date_format': 'yy/mm/dd',
                                            'tmpdir': settings.MEDIA_ROOT +
                                                      '/documents/%s'.format(file.name.rsplit('.')[0] + '.xlsx')
                                        }

        excelFile = get_doc().file
        worksheet = excelFile.add_worksheet()
        worksheet.write('A1', 'data')
        worksheet.write('B1', 'data')
        worksheet.write('C1', 'data')
        worksheet.write('D1', 'data')
        worksheet.write('E1', 'data')
        # Start from the first cell. Rows and columns are zero indexed.
        row = 1
        col = 0
        with open(csvfile, 'rb') as f:
            content = csv.reader(f)
            # Iterate over the data and write it out row by row.
            for row_data in content:
                for data in row_data:
                    worksheet.write(row, col, data)
                    col += 1
                row += 1
                col = 0

        f.close()
        excelFile.close()

    return convert_csv_to_xlsx()

Now the problem that I really don't know to to save this excel file to the doc.file,
and I tried django fieldfile save
---> 19     read = property(lambda self: self.file.
AttributeError: 'Workbook' object has no attribute 'read'
Any suggestion Thanks

A:     def convert_csv_to_xlsx():
    csvfile = get_file()
    from django.conf import settings
    excelFile = xlsxwriter.Workbook(filename=settings.MEDIA_ROOT + '/documents%s' % (
        csvfile.name.rsplit('.')[0] + '.xlsx'))
    bold = excelFile.add_format({'bold': 1, 'align': 'left', 'bg_color': 'red', 'color': 'white'})
    worksheet = excelFile.add_worksheet()
    worksheet.set_column(0, 4, width=15)
    worksheet.write('A1', 'Sender MSISDN', bold)
    worksheet.write('B1', 'Reciever MSISDN', bold)
    worksheet.write('C1', 'Amount', bold)
    worksheet.write('D1', 'Transaction ID', bold)
    worksheet.write('E1', 'Datetime', bold)
    # Start from the first cell. Rows and columns are zero indexed.
    row = 1
    col = 0

    # Iterate over the data and write it out row by row.

    for row_data in csv.reader(csvfile):
        for idx, data in enumerate(row_data):
            if idx == 0:
                worksheet.write(row, col, data)
            elif idx == 1:
                worksheet.write(row, col, data)
            elif idx == 2:
                worksheet.write(row, col, data)
            elif idx == 3:
                worksheet.write(row, col, data)
            elif idx == 4:
                worksheet.write(row, col, data)
            col += 1
        row += 1
        col = 0
    csvfile.close()
    doc = get_doc()
    now = datetime.now()

    excelFile.close()
    doc.file.save(
        name='RECHARGE_%d-%s-%s.xlsx' % (now.year,
                                         validate_date(now.month),
                                         validate_date(now.day)
                                         ),
        content=File(open(settings.MEDIA_ROOT + '/documents%s' % (
            csvfile.name.rsplit('.')[0] + '.xlsx',)))
    )
    os.remove(settings.MEDIA_ROOT + '/documents%s' % (
        csvfile.name.rsplit('.')[0] + '.xlsx'), )


text:
Q: C++ 11 operator overload with return type deduction I have a template class that depends on one type (for example template <typename T> class Vector). Now, I want to overload the arithmetic operators such that:

*

*I can use them with Vectors instantiated with two different types;

*The result is deduced in the same way of the template instance types;

Example:
Vector<float> fv = {1.5, 2.5};
Vector<int> iv = {1,2};
auto s1 = fv + iv;   // s1 MUST be of type Vector<float> == {2.5, 4.5}
auto s2 = iv + fv;   // s2 MUST be of type Vector<float> == {2.5, 4.5}

I think that, in a generic purpose mathematical library that implements Matrices, Vectors, Polynomials, etc., this would be a feature that makes the difference in terms of usability.
I found three ways to obtain this result with C++11

*

*-> notation
template <typename T, typename U>
auto operator +(const Vector<T> &lhs, const Vector<U> &rhs)
    -> Vector<decltype(lhs[0]+rhs[0])>
{
    Vector<decltype(lhs[0]+rhs[0])> res(lhs);
    res += rhs;
    return res;
}

*declval
template <typename T, typename U>
Vector<decltype(std::declval<T>()+std::declval<U>())>
operator +(const Vector<T> &lhs, const Vector<U> &rhs)
{
    Vector<decltype(lhs[0]+rhs[0])> res(lhs);
    res += rhs;
    return res;
}

*declval as default type arg
template <typename T, typename U,
          typename R = decltype(std::declval<T>()+std::declval<U>())>
Vector<R> operator +(const Vector<T> &lhs, const Vector<U> &rhs)
{
    Vector<R> res(lhs);
    res += rhs;
    return res;
}

What, in your opinion, the best approach to implement such a feature?
If is there a FOURTH better solution I'll appreciate it.
Do you consider such "interworking" operators a worthwhile feature?
Thanks and Best Regards,
Davide

A: Whether or not such operators are a "good idea" depends on your use-cases. But if you want to implement them, I suggest you use a traits class, derived from std::common_type, to gain more control:
template<typename T, typename U>
struct VectorCommonType : std::common_type<T,U> {};

template<typename T, typename U>
using VectorCommonTypeT = Vector<typename VectorCommonType<T,U>::type>;

That way you (or the user of the class) can specialize it when needed. Use it like this:
template<typename T, typename U>
VectorCommonTypeT<T,U> operator+(const Vector<T> &lhs, const Vector<U> &rhs)
{
    VectorCommonTypeT<T,U> res(lhs);
    res += rhs;
    return res;
}


text:
Q: Which data type I need to use for [byte] In base memory address? I working on a program that "hacks" GTA: San Andreas.
I'm using WriteProcessMemory function to write data into the base memory of the specific item, and FindWindow to find the GTA: San Andreas Window.
My Problem is that the second and the third WriteProcessMemory does not working, It does not affect the game and does nothing.
I saw here the base memory addresses and the data type I need, you can scroll down to Cheats options and see that the base memory and the data type [byte] they need.
Example:
#include <iostream>
#include <Windows.h>

using namespace std;

void GameHack(LPCSTR winname)
{
    int newValue = 125555;
    byte bytes = 1;
    HWND GameWindow = FindWindowA(NULL, winname);
    if (GameWindow == NULL) {
        auto errorcode = GetLastError();
        std::cout << "Failed to FindWindow & Error Code: " << errorcode;
        Sleep(3000);
        exit(1);
    }
    else {
        DWORD procID;
        GetWindowThreadProcessId(GameWindow, &procID);
        HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procID);

        if (handle == NULL) {    // compare handle to NULL, not procID to FALSE
            auto errorcode = GetLastError();  // 1st thing to do
            std::cout << "procID Failed & Error Code: " << errorcode;
            Sleep(3000);
            exit(1);
        }
        else {
            int option;
            cout << "\n 1. Money Booster!\n 2. Weapon Set 1\n 3. Max Muscle\n\n";
            cout << " Choose One Option You Want To Do: "; cin >> option;
            if (option == 1) {
                WriteProcessMemory(handle, (LPVOID)0x00C0F188, &newValue, sizeof(newValue), NULL);
            }
            if (option == 2) {
                WriteProcessMemory(handle, (LPVOID)0x969130, &bytes, sizeof(bytes), NULL);
            }
            if (option == 3) {
                WriteProcessMemory(handle, (LPVOID)0x969155, &bytes, sizeof(bytes), NULL);
            }
            CloseHandle(handle);
        }
    }
}

int main()
{
    GameHack("GTA: San Andreas");
    return 0;
}

I want to add Weapon Set 1 to my character and Max Muscle.
Which data type and value should I need to use for this ?

A: The website you linked lists the data type you need to use as a byte, which you are doing.  If your first WriteProcessMemory works but the second 2 do not work, then the addresses have changed.
Your first address for money is listed as 0x00C0F188 which differs from the one listed on the website and it works.
If you are having to use a different address for money, then most likely you will have different addresses for all the variables.
You need to find the version of your game first and compare it against that guide.  Either way the best solution is always to reverse the addresses yourself rather than relying on someone else's work which may be outdated.


text:
Q: Context menu not fully visible if to point from below of the page Context menu goes down, when point from down, it is not fully visible, how can I make to be fully visible at bottom of page by CSS
CSS

Screen

A: The usual solution for this is to dynamically adjust the position of the element so that it does not extend outside the window. You appear to already be setting the position via top and left so you probably only need to modify your calculation to incorporate the window limits.


text:
Q: how to serialize and deserialize over two different assembly? This is a C# project. I am using BinaryFormatter as the serializer and deserializer for my applications.
Because there are two application and the assembly names are different from each other, I am using a serialization binder to solve the issue on finding types.
but I still get an error which is :
Unable to find assembly 'GameServer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
and this is my serialization binder code :
    public override Type BindToType(string assemblyName, string typeName)
    {
        if (assemblyName.Contains("GameServer"))
        {
            assemblyName = "Assembly-CSharp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=12345";
        }
        return Type.GetType(typeName);
    }

in the above code, i just check if an assembly named "GameServer" found, then rename it to the local assembly name.
am i missing something here?

A: Honestly, the only "good" answer here is "don't use BinaryFormatter", followed closely by "really, don't use BinaryFormatter". There are many good reasons that it is considered deprecated in .NET Core / .NET 5+, and this minor inconvenience of matching similar types: didn't even make that list! (Btw, you can avoid having to do that by moving your DTO types to a library assembly that both other projects reference).
Note: for virtually any other serializer - JSON, xml, protobuf, etc - it would already "just work": the types being in different assemblies wouldn't remotely matter. So frankly, the best advice here is simply: "change serializer".


text:
Q: How to copy column names from Teradata I want to export the column names into excel sheet by running the query in Teradata. I used ctrl+c  but it didnt work. Thanks in advance.

A: Change your settings in Result Set View Preferences\Copy Options\
check "Copy Include Column Headers"
The "Result Set View Preferences" is the first button that looks like pliers on the result set view window.

A: To get column names, open you answerset, and save the result set.
File > save as >

A: I've found the answer show table tablename

A: I frequently want to report out the colums and the dbc.columns is the best way to do this.  They all come out right padded so a trim makes them paste into excel nicely. I also added a case statement that will translate the datatype for you.
sel
  trim(databasename)
, trim(tablename)
, trim(columnname)
, max(case
   when columntype = 'D'  then 'decimal(' || decimaltotaldigits || ', ' || decimalfractionaldigits || ')'
   when columntype = 'CV' then 'varchar(' || columnlength || ')'
   when columntype = 'CF' then 'char('    || columnlength || ')'
   when columntype like 'I%'  then 'integer'
   else 'unknown' end) as colDDL
from dbc.columns where tablename in (<sometableList>)
and databasename in (<someDBList>)
order by column_id

A Full List of DBC.columns data tpe mapping example:
create volatile table vt_woe_col_list
as (
select
  trim(columnname) as column_name
, case when ColumnType in ('CF','CV')             then 'Character'
       when ColumnType in ('D','F','I1','I2','I') then 'Numeric'
       when ColumnType in ('DA')                  then 'Date'
       when ColumnType in ('SZ','TS')             then 'TimeStamp'
       else 'Skip' end as process_type
, case trim(columntype)
    when 'AT' then 'TIME'
    when 'BF' then 'BYTE'
    when 'BO' then 'BLOB'
    when 'BV' then 'VARBYTE'
    when 'CF' then 'CHAR'
    when 'CO' then 'CLOB'
    when 'CV' then 'VARCHAR'
    when 'D'  then 'DECIMAL'
    when 'DA' then 'DATE'
    when 'DH' then 'INTERVAL DAY TO HOUR'
    when 'DM' then 'INTERVAL DAY TO MINUTE'
    when 'DS' then 'INTERVAL DAY TO SECOND'
    when 'DY' then 'INTERVAL DAY'
    when 'F'  then 'FLOAT'
    when 'GF' then 'GRAPHIC'
    when 'GV' then 'VARGRAPHIC'
    when 'HM' then 'INTERVAL HOUR TO MINUTE'
    when 'HR' then 'INTERVAL HOUR'
    when 'HS' then 'INTERVAL HOUR TO SECOND'
    when 'I1' then 'BYTEINT'
    when 'I2' then 'SMALLINT'
    when 'I'  then 'INTEGER'
    when 'MI' then 'INTERVAL MINUTE'
    when 'MO' then 'INTERVAL MONTH'
    when 'MS' then 'INTERVAL MINUTE TO SECOND'
    when 'SC' then 'INTERVAL SECOND'
    when 'SZ' then 'TIMESTAMP WITH TIME ZONE'
    when 'TS' then 'TIMESTAMP'
    when 'TZ' then 'TIME WITH TIME ZONE'
    when 'YM' then 'INTERVAL YEARTO MONTH'
    when 'YR' then 'INTERVAL YEAR'
    when 'UT' then 'UDT Type'
    end as column_type_desc
,  a.*
from dbc.columns A
where trim(tablename   )='t_woe_data_samp'
  and trim(databasename)= 'DUCSMAD'
) with data
primary index(column_name)
on commit preserve rows;


text:
Q: Problem with Ethernet connection on PC, integrated network card (Ubuntu 14.04) In the network manager : unplugged cable (but cable allright), I dissconect and connect - dont solve the problem.
If lspci -nnk | grep -iA2 net - I have this:
Ethernet controller [0200]: Realtek Semiconductor Co., Ltd RTL-8129 [10ec:8129] (rev 01)
Subsystem: Coreo Inc RTL8111/8168 PCIe Gigabit Ethernet (misconfigured) [11ec:8129]
Kernel driver in use: 8139too

A: You need to switch the driver. Do in terminal.
sudo modprobe -r 8139too
echo "10ec 8129" | sudo tee /sys/bus/pci/drivers/r8169/new_id
sudo modprobe -r r8169
sudo modprobe r8169

If your network cards starts working, I will add how to make it permanent after reboot.


text:
Q: What is the sequence that maximizes this distance? I have posted this question here without answer. Maybe I can get some light here.
Suppose we are given $n$ segments $l_1,...,l_n$ in $\mathbb{R}^2$ such that $|l_i|=i,\ \forall\ i=1,...,n$, where $|l_i|$ is the length of $l_i$. Let $\alpha_1,...,\alpha_{n-1}$ be $n-1$ angles such that $\alpha_i>0$ and $\sum_{i=1}^{n-1}\alpha_i\leq\frac{\pi}{2}$.
Consider the following operation: (All angles are assumed to be "clockwise").
1) Place $l_{1}$ anywhere in $\mathbb{R}^2$,
2) Place $l_{2}$ at either of the end points of $l_{1}$, making an angle of $\alpha_{1}$,
3) Place $l_{3}$ at the end point of $l_{2}$ not occupied by $l_{1}$, making an angle of $\alpha_{2}$,
...
n-1) Place $l_{n-1}$ at the end point of $l_{n-2}$ not occupied by $l_{n-3}$, making an angle of $\alpha_{n-2}$,
n) Place $l_{n}$ at the end point of $l_{n-1}$ not occupied by $l_{n-2}$, making an angle of $\alpha_{n-1}$.
Now consider arbitrary permutations both of the angles $\alpha_i$ and of the lengths $l_i$. Which ordering of the angles and lengths maximizes the distance between the two endpoints of the chain of segments?

A:
"Place $l_{2}$ at either of the end points of $l_{1}$, making an angle of $\alpha_{1}$"...

Making an angle $\alpha_{1}$ with respect to which line, measured in which direction?  Here is a possible example with $\alpha_i=\pi/8$, but until you remove the ambiguity in your stipulation, it is unclear
if this accord with your intention:

The OP has now made clear that the above fails his definition.
So, if $\alpha_i$ is a constant, the distance is entirely determined.
For $\alpha_i=\pi/8$, here is the determined shape and so end-to-end distance:


text:
Q: regex is not is not matching value in Jenkins pipeline I'm trying matching number value in a list and regex is working fine on Jenkins script console but when I use the same code in the pipeline my code it returns match as false

def tag = ["fork-point", "fork-3.0.1", "fork-3.0.0", "2.0.2", "2.0.1", "2.0.0", "1.0.1", "1.0.0"]

List<String> extractSubListUsingRegex( List<String> l) {

    String regex = "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)"
    List<String> subList = []
    for (String tag in l) {
        println tag
        boolean isMatching = (tag ==~regex)
        if (isMatching == true){
            subList.add(tag)
        }
    }

    return subList
}
println extractSubListUsingRegex(tag)

Here is the regex
https://regex101.com/r/BvqB6e/1

A: The problem was regex was looking for non string value but the parameter output value was a string and hence failing.


text:
Q: Centos 7 public static IP address for a KVM guest I am on Centos 7 with KVM and virt-manager installed. I have a virtual (guest) machine with Debian 8.1 on it. Network on guest was configured with virt-manages using NAT (with default settings). So now my virtual machine has Internet access and local IP 192.168.122.227.
On my host system I have 1 physical network interface and 1 main public ip and 3 additional public ips on it.
My public ips (example): 85.0.0.1, 85.0.0.2, 85.0.0.3, 85.0.0.4
Broadcast ips are also examples.
My ifconfig from host:
enp2s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 85.0.0.1 netmask 255.255.255.192 broadcast 85.0.0.127
ether d4:3d:7e:ec:b3:55 txqueuelen 1000 (Ethernet)
RX packets 4920 bytes 416179 (406.4 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 2298 bytes 392837 (383.6 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

enp2s0:0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 85.0.0.2 netmask 255.255.255.192 broadcast 85.0.0.127
ether d4:3d:7e:ec:b3:55 txqueuelen 1000 (Ethernet)

enp2s0:1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 85.0.0.3 netmask 255.255.255.192 broadcast 85.0.0.127
ether d4:3d:7e:ec:b3:55 txqueuelen 1000 (Ethernet)

enp2s0:2: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 85.0.0.4 netmask 255.255.255.192 broadcast 85.0.0.127
ether d4:3d:7e:ec:b3:55 txqueuelen 1000 (Ethernet)

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
loop txqueuelen 0 (Local Loopback)
RX packets 30 bytes 2856 (2.7 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 30 bytes 2856 (2.7 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

virbr0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.122.1 netmask 255.255.255.0 broadcast 192.168.122.255
ether 52:54:00:cf:32:9d txqueuelen 0 (Ethernet)
RX packets 18 bytes 1407 (1.3 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 8 bytes 779 (779.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

vnet0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
ether fe:54:00:96:2d:23 txqueuelen 500 (Ethernet)
RX packets 18 bytes 1659 (1.6 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 574 bytes 30211 (29.5 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

When I do this on the host machine, I still keep coming to host machine by ssh 85.0.0.2 but not to the guest:
iptables -t nat -I PREROUTING -d 85.0.0.2 -i enp2s0:0 -j DNAT --to-destination 192.168.122.227

iptables -t nat -I POSTROUTING -s 192.168.122.227 -o enp2s0:0 -j SNAT --to-source 85.0.0.2 iptables -P FORWARD ACCEPT

iptables -P FORWARD ACCEPT

My enp2s0:0 config:
# Generated by parse-kickstart
UUID=9928e0a6-df18-45ef-a826-edaf8b4dc370
DNS2=85.0.0.10 #(example)
DNS1=85.0.0.10 #(example)
BOOTPROTO=none
DEVICE=enp2s0:0
ONBOOT=yes
IPV6INIT="no"
TYPE=Ethernet
IPADDR=85.0.0.2
PREFIX=26
GATEWAY=85.0.0.127
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes
IPV6_FAILURE_FATAL=no
NAME="System enp2s0:0"

I am not stupidly duplicating question, I've already read and googled a lot, but still can't solve this problem. Please help!

A: You should not have IP addresses meant for guests assigned to the host. (And you should not be using interface aliases. Those were deprecated many years ago.)
Instead, create a bridge, and add enp2s0 to it. Then assign your KVM guests to that bridge and assign their IP addresses in each guest.


text:
Q: "while" loop to change interval of "setTimeout" NOT WORKING I created a rectangle , and i want to give it a speed that change over time (acceleration) .
So I made a "setTimeout"  inside  a "while" loop.
Supposedly , the "while" loop should continuously change the interval of the "setTimeout" (var=interval) by -1 , but instead it replaces it with 1 !!, wich makes the rectangle print every 1 milliseconds   .
I would like to know why this happens .
the same thing happens if i use the "for" loop.
and i wouldn't mind any other alternative to create acceleration effect.
thank you

var canvas = document.getElementById("canvas")
var context = canvas.getContext("2d")

var posX=20;
var posY=20;

var interval = 500;

function print () {

             //background

context.fillStyle="black";
context.fillRect(0, 0, 500, 500);

            //object

context.fillStyle="#4286f4";
context.fillRect(posX, posY, 50, 50);

posX = posX + 1;
posY = posY + 1;

        }

while (interval > 300) {

        interval-- ;

 setTimeout(print, interval);

    }

<!DOCTYPE html>
<html>
    <head>
        <title>Particles</title>
        <meta charset="UTF-8"/>
    </head>

    <body>
        <canvas id="canvas" width="500" height="500"></canvas>

    </body>

</html>

A:
the "while" loop should continuously change the interval of the "setTimeout"

No, it schedules a new timer at the new interval. The previous one keeps running as well. You very, very, very quickly end up with a bunch of timers pending -- which all then expire one right after the next.
Once you start a timer, you can't change when it fires. You can cancel it, but you can't change when it fires.
setTimeout also schedules a single timed callback. If you want repeated ones, use setInterval or schedule a new callback from the setTimeout callback when it runs.
I recommend taking a step back and experimenting with the basics of timers and intervals before moving on to something complex like doing animations.
Separately: setTimeout and setInterval are the wrong tools for animation, at least in isolation. Instead, when you know you need to update the circle, use requestAnimationFrame to have the browser call you immediately before it renders the display (it will fire ~60 times/second, so only request it when you need it). That helps you coordinate with the browser's internal display cycles.
Something along these lines:
scheduleNext();

function scheduleNext() {
  if (interval > 300) {
    setTimeout(function() {
      requestAnimationFrame(function() {
        print();
        scheduleNext();
      });
    }, interval);
  }
}

Live Example:

var canvas = document.getElementById("canvas")
var context = canvas.getContext("2d")

var posX = 20;
var posY = 20;

var interval = 500;

function print() {
  //background
  context.fillStyle = "black";
  context.fillRect(0, 0, 500, 500);

  //object
  context.fillStyle = "#4286f4";
  context.fillRect(posX, posY, 50, 50);

  posX = posX + 1;
  posY = posY + 1;
}

scheduleNext();

function scheduleNext() {
  if (interval > 300) {
    setTimeout(function() {
      requestAnimationFrame(function() {
        print();
        scheduleNext();
      });
    }, interval);
  }
}
<canvas id="canvas" width="500" height="500">

A: setTimeout doesn't pause the script, it schedules the callback to be run in the given milliseconds. This means that you're scheduling all the callbacks right away, and there's only a 1 millisecond difference between them, which isn't enough to cause an observable difference.

A: Update :
ahaa , Yes its possible to create the animation loop with just "setTimeout" ,

function test () {

print ();
interval = interval - 10;
setTimeout(test, interval);

}

 test ();


text:
Q: tkinter GUI doesn't appear? Small problem here, my code seem to be clean but the tkinter GUI doesn't appear ? Can seem to figure it out. The GUI / Code is for a report form type.
Thanks for your help in advance
from tkinter import *

class FicheDeSignalement(Frame):
    def __init__(self):
        Frame.__init__(self)

        programme = Frame()
        programme.pack(side="top", fill="both", expand=True)
        programme.grid_rowconfigure(0, weight=5)
        programme.grid_columnconfigure(0, weight=5)

        self.pages = {}
        for onePage in (StartProgram, InformationsPage):
            start_page = onePage(programme, self)
            self.pages[onePage] = start_page
            start_page.grid(row=0, column=0, sticky="nsew")
        self.show_pages(StartProgram)

    def show_pages(self, cont):
        see_start_page = self.pages[cont]
        see_start_page.tkraise()

class StartProgram(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent, controller)
        label = Label(self, text="Fiche de Signalement", font=LARGE_FONT)
        label.pack(padx=10, pady=10)

        start_button = Button(self, text="Commencer", command=lambda: controller.see_page(InformationsPage))
        start_button.pack()

class InformationsPage(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent, controller)

        label = Label(self, text="Informations sur le suspect", font=LARGE_FONT)
        label.pack(side="top", fill="both", expand=True, padx=10, pady=10)

        person_suspected = Label(self, text="Prenom")
        person_suspected.grid(row=0, column=0, padx=10, pady=10)
        first_name = Entry(self)
        first_name.grid(row=0, column=1, padx=10, pady=10)

        person_suspected_2 = Label(self, text="Nom")
        person_suspected_2.grid(row=0, column=2, padx=10, pady=10)
        last_name = Entry(self)
        last_name.grid(row=0, column=3, padx=10, pady=10)

        person_height = Label(self, text="Grandeur")
        person_height.grid(row=1, column=0, padx=10, pady=10)
        size_height = Entry(self)
        size_height.grid(row=1, column=1, padx=10, pady=10)

        person_weight = Label(self, text="Poids")
        person_weight.grid(row=1, column=2, padx=10, pady=10)
        size_weight = Entry(self)
        size_weight.grid(row=1, column=3, padx=10, pady=10)

app = FicheDeSignalement()
app.mainloop()

A: In addition to indentation errors and missing import statements and missing definition of LARGE_FONT, you have this problem:
label = Label(self, text="Informations sur le suspect")
label.pack(side="top", fill="both", expand=True, padx=10, pady=10)

person_suspected = Label(self, text="Prenom")
person_suspected.grid(row=0, column=0, padx=10, pady=10)

Both label and person_suspected share the same parent (self), but one uses pack and one uses grid. You can't use both of them with widgets that share a common parent. You must use only grid or only pack.


text:
Q: How to plot 3d parametric equations in R? From the parametric equations on wiki page ( http://en.wikipedia.org/wiki/Parametric_equation  ), I can plot 2d equations as follows:
#for a circle:
x = seq(-pi, pi, length.out=30)
plot(sin(x),cos(x))

# for a star:
a=10; b=10/1.8
x=seq(-50,50,length.out=500)
plot((a-b)*cos(x)+b*cos(x*((a/b)-1)), (a-b)*sin(x)-b*sin(x*((a/b)-1)), ylim=range(-13,13))

How can I plot 3d equations on a 3d plot of a Helix given by equations:
x=a*cos(t)
y=a*sin(t)
z=b*t

From searching I found that the 3d plotting functions take either a matrix or x,y,z values but not math curve functions.

A: You can plot 3D equations like you did the 2D ones.
library(lattice)
t<-seq(-2*pi, 2*pi, length.out=200)
cloud(z~x+y,data.frame(x=3*cos(t),y=3*sin(t), z=2*t))

So yes, you can't supply a raw function directly, but you can easily calculate points to plot based on those functions. Let me know if you had something else in mind.
Here's a two-parameter torus
t <- seq(0, 2*pi, length.out=50);
u <- seq(0, 2*pi, length.out=50);
tu<-expand.grid(t=t,u=u)
R <- 6;
r <- 3;
tu <- transform(tu,
    x = cos(t)*(R+r*cos(u)),
    y = sin(t)*(R+r*cos(u)),
    z = r*sin(u)
)

rr<-c(-10,10)
cloud(z~x+y, tu, xlim=rr, ylim=rr, zlim=rr, screen=list(y=20));

Actually, I just realized wireframe is better, just took me a bit longer to figure out the syntax.
xm<-outer(t,u,function(t, u)cos(t)*(R+r*cos(u)))
ym<-outer(t,u,function(t, u)sin(t)*(R+r*cos(u)))
zm<-outer(t,u,function(t, u) r*sin(u))

rr<-c(-10,10)
wireframe(zm~xm+ym, xlim=rr, ylim=rr, zlim=rr, screen=list(y=30))

More details found on the ?cloud help page

A: With plotly:
library(plotly)

t <- seq(-2*pi, 2*pi, length.out=200)
dat <- data.frame(x=3*cos(t), y=3*sin(t), z=2*t)

plot_ly(dat, x = ~x, y = ~y, z = ~z, type = 'scatter3d', mode = 'lines',
        line = list(width = 4))


text:
Q: Magento - Load product by url How would one load a product model in Magento, if the product id is not available and only the product's url is? For example, I want to retrieve the product model from it's friendly url, such as
electronics/cameras/olympus-stylus-750-7-1mp-digital-camera.html

I found the following code in another post:
$oRewrite = Mage::getModel('core/url_rewrite')->loadByRequestPath(
    $path
);

but it doesn't seem to work correctly. The Magento documentation is very lacking in this area; does anyone know how to accomplish this?

A: I'm curious as to why you need to do this, since this might not be the best solution. This should be easy enough using the addAttributeToFilter() method on the collection:
$path = 'folder/folder/my-product-name';

// Get the product permalink
$productName = explode('/', $path);
$productName = end($productName);

// Filter the url_path with product permalink
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToFilter('url_path', $productName)
         ->getFirstItem();

Zend_Debug::dump($products->getData());exit;

A: Here's an alternative solution.
First use the URL rewrite model to find the route which matches your product:
    $vPath = 'electronics/cameras/olympus-stylus-750-7-1mp-digital-camera.html';
    $oRewrite = Mage::getModel('core/url_rewrite')
                    ->setStoreId(Mage::app()->getStore()->getId())
                    ->loadByRequestPath($vPath);

Then you can call getProductId() on the route to locate the produc's id:
    $iProductId = $oRewrite->getProductId();

Finally if you require the product model object itself it's then a simple matter to call:
    $oProduct = Mage::getModel('catalog/product')->load($iProductId);

The main difference between the above, and the code example you've posted is the call to setStoreId.  The same product may have different URLs depending on which store it's in, so the routing component needs to have the appropriate store context before it can locate the product to display.
The advantages of this over Zachary Schuessler's solution is that using the URL rewriter will locate the correct product every time if the trailing portions of the url are the same for different products (e.g. folder1/my-product-name and folder2/my-product-name are different products).  Using the URL rewriter also works in situations where "folder1/my-product" refers to different products on different stores.  This may or may not apply to your environment.


text:
Q: How to properly match types when using Numeric.AD in Haskell? I'm trying to implement Newton–Raphson root-finding algorithm using the ad package, but I can't properly match function types. I know there's a proper answer to a similar question, which was answered by the creator of ad himself, but the package have changed greatly since version 1.0.6 (current version is 4.3.4).
This first minimum example compiles and works when I iterate over it:

import Numeric.AD
import Numeric.AD.Internal.Forward

g :: Fractional a => a -> a
g x = - x + 2

g' :: Fractional a => a -> a
g' x = diff g x

newtonG :: Fractional a => a -> a
newtonG x = x - (g x) / (g' x)

But if I try to abstract the function, like this:

import Numeric.AD
import Numeric.AD.Internal.Forward

g :: Fractional a => a -> a
g x = - x + 2

newton :: Fractional a => (a -> a) -> a -> a
newton f x = x - (f x) / (diff f x)

GHC returns the following error:

fsolve.hs:8:32: error:
    * Couldn't match type `a' with `AD s (Forward a)'
      `a' is a rigid type variable bound by
        the type signature for:
          newton :: forall a. Fractional a => (a -> a) -> a -> a
        at fsolve.hs:7:11
      Expected type: AD s (Forward a) -> AD s (Forward a)
        Actual type: a -> a
    * In the first argument of `diff', namely `f'
      In the second argument of `(/)', namely `(diff f x)'
      In the second argument of `(-)', namely `(f x) / (diff f x)'
    * Relevant bindings include
        x :: a (bound at fsolve.hs:8:10)
        f :: a -> a (bound at fsolve.hs:8:8)
        newton :: (a -> a) -> a -> a (bound at fsolve.hs:8:1)

If I use Numeric.AD.Rank1.Forward instead of Numeric.AD, the compiler says it cannot match a with Forward a, instead of a with AD s (Forward a). I also tried several ways of creating a dual number from x to pass it to f, e.g. snd . unbundle . f $ bundle x 1, but it only works if I create a new g' x using it, like in first case. Using this within newton doesn't work either.
In Numeric.AD, diff :: Num a => (forall s. AD s (Forward a) -> AD s (Forward a)) -> a -> a. And in Numeric.AD.Rank1.Forward, it's diff :: Num a => (Forward a -> Forward a) -> a -> a. So why do they accept a function of type a -> a in the first case, but not in the second? Besides using polymorphic functions, should I take any special care when creating functions to use with Numeric.AD? Lastly, how should I change my code to make it work? I know the package already has a function to find roots, but I don't want to use yet (since I'm still learning Haskell), and looking at the documentation trying to sort this out, felt like running in circles.

A: Observe that your function:
newton :: Fractional a => (a -> a) -> a -> a
newton f x = x - (f x) / (diff f x)

uses the function argument f in two places.  First, the
subexpression f x uses f with the type:
f :: Fractional a => a -> a

Second, due to the use of diff the subexpression diff f x uses f with the type:
f :: forall s a. Fractional a => AD s (Forward a) -> AD s (Forward a)

The error message you got is the type system observing that these
are different types that cannot be unified.
The solution is to explicitly quantify the function argument of newton
to work for all types satisfying the appropriate numeric type class constraint(s).  This requires the RankNTypes language extension:
{-# LANGUAGE RankNTypes #-}

newton
  :: Fractional a
  => (forall b. Fractional b => b -> b)
  -> a
  -> a
newton f x = x - (f x) / (diff f x)


text:
Q: how do you model your javascript? I'm trying to model my javascript object using visio, visio doesn't support javascript data types.
Then I start thinking, how do you desing model your javascript code?
Cheers

A: In the past, I've used Open Source tools like Dia and just fudged the data types where needed...
It's enough to get the idea across, but you're definitely not going to get anything even close to code generation from it.

A: I prefer Object Oriented design - even for JavaScript - so I suggest Rational Rose.  I like some of the features of OO (e.g. encapsulation and abstraction) and like to add some discipline to a potentially undisciplined environment - especially when working with developers new to JavaScript.  Rose meets my needs.


text:
Q: Visual Studio C++ exception... weirdness I have a Qt application that I compile in release configuration, run, and then perform operation X in the program. Everything runs fine.
I then compile it in debug configuration, run without debugging (so CTRL+F5), perform operation X in the program. Everything still runs dandy fine.
But when I try to run the debug configuration with debugging (so just F5) and then perform operation X, Visual Studio breaks in with a message that an exception has been thrown... in a completely unrelated part of the program (code being executed is far from the site where VS breaks, in the QHash template)... and then VS hangs and I have to kill it with the Task Manager. I can repeat this ad infinitum, and it always freaks out the same way.
Boost::exception is used for the exceptions. VS is 2008, SP1. Qt is 4.6.2, using the precompiled VS binaries from the Qt site.
Does anyone have a clue what is going on?

A: Visual Studio has a feature called "first chance exception handling" where, when running attached to the debugger, you can have the debugger break when exceptions of certain types are thrown.
You can change these settings by going to Debug -> Exceptions (Ctrl+Alt+E) and (un)checking the appropriate checkboxes.
When it breaks you should get a message in the Output window indicating what exception was thrown.
If you have _HAS_ITERATOR_DEBUGGING enabled (it is enabled by default in debug builds), it can cause a lot of iterator errors to throw exceptions instead of performing operations that would cause access violations.  That's the only thing I can think of off the top of my head that would cause an exception to occur "randomly."


text:
Q: Replace a certain value in OCaml list in every occurrence with another value I'm working out a simple program that replaces a certain value (in every occurrence) with another given value inside a list. I tried to follow this:
Ocaml, replace all specified elements with a given element in a list
But unfortunately I can't use the when construct here. Here's my code:
let rec replace (l:int list) (i:int) (j:int) :int list =
    match l with
        | hd::tl -> if hd = i then j::tl else replace tl i j
        | [] -> l
;;

When I tried to replace an entry, It doesn't gives the whole list. instead it only gives the changed value. Can anyone help me out ?

A: Your description of the problem doesn't match your code, or maybe I don't understand. If I try your code here's what I see:
# replace [1; 4; 1; 4; 2] 4 6 ;;
- : int list = [6; 1; 4; 2]

I see two problems. First, the return value starts at the first replaced value rather than the beginning of the list. Second, only one value is replaced, not all values.
To solve the first problem, you have to make sure you return the full list all the time. You're not returning the full list when hd = i is false.
To solve the second problem you need to process the tail of the list in all cases. You're not processing the tail of the list when hd = i is true.


text:
Q: Imperative towards the sun? For example, in novels, or poems, if I happen to make some kind of imperative towards the sun, or third-person things as such, how should I do?
For instance, when I want the sun to rise. Is it:

Rise, the sun!

But I've never heard such sentence, so I doubt it's right.

A: Arise, Oh Sun!
Although there are equivalent third-person formulations using let or may, you do not use an article in a second-person imperative. This is because you are directly addressing someone or something, and so no article is needed — nor allowed.
Therefore you can just say Rise, sun! or Arise, sun!
You can use the so-called vocative particle O before sun to indicate a noun of direct address, as in Rise O Sun! This is sometimes spelled oh, such as Arise, oh sun! But when it has a single letter, O must be capitalized, just as I have done here.
Poetry often uses personification, so a second-person imperative is not uncommon there, even to things not people.
You can go different routes on this, as have many poets before you.

Third-Person Imperatives
Let the Sun Rise
From the musical Hair comes the song "Let the Sunshine In":

So let the sun shine in, face it with a grin
  Smilers never lose and frowners never win
  So let the sun shine in, face it with a grin
  Open up your heart and let the sun shine in

Or from the lovely anthem "Fly My Pretties" by Angels:

Let the sun rise in the morning,
  Let the clouds take on a silver sheen,
  and I'll remember you with each dawning
  as you rest in angels wings.

May the Sun Rise
We also have the style of this traditional Irish blessing:

May the road rise up to meet you.
  May the wind always be at your back.
May the sun shine warm upon your face,
  and rains fall soft upon your fields.
  And until we meet again,
  May God hold you in the palm of His hand.

Second-Person Imperatives
Rise O Sun
And of course you can switch to second person, as in this translation of the Kalevala:

Rise, oh sun, henceforth and ever,
  Still with every morn returning:
  Bring a blessing to our homsteads,
  To our hunting, to our fishing,
  to our planting, to our sowing,
  And, at eve, on clouds of crimson,
Rest, reposing as a warrior,
  As a hero after battle,
  Browned with praises, crowned with honor,
  Route thee all the sunset's glory,
  All the grateful earth beneath thee.

Or from the late William Furr's poem "Rising Sun":

Rise, oh, sun of God;
  Rise up to warm earth's son.
  Men will see you fair
  For angels braided your hair.
Rise up, oh, lamp of God;
  The heavens will see you plod.
  To earth's four corners you shall shine
  As if to warm earth's kind.

And from the poet William Blake we have this excerpted verse:

Rise up, oh sun! most glorious minister of light and day,
  Flow on, ye gentle airs, and bear the voice of my rejoicing.
  Wave freshly, you clear water flowers, around the tender grass.
  Follow me, oh my flocks! and hear me sing my rapturous song.

Shine Here
Poets have forever addressed the sun in the second person. From John Donne comes this shining example in his poem "The Sun Rising", in which Donne uses the (archaic) second person throughout when addressing the sun, this time rather vexingly:

Busy old fool, unruly sun,
  Why dost thou thus,
  Through windows, and through curtains call on us?
  Must to thy motions lovers' seasons run?
  Saucy pedantic wretch, go chide
  Late school boys and sour prentices,
Go tell court-huntsmen that the king will ride,
Call country ants to harvest offices,
  Love, all alike, no season knows nor clime,
  Nor hours, days, months, which are the rags of time.
Thy beams, so reverend and strong
  Why shouldst thou think?
  I could eclipse and cloud them with a wink,
  But that I would not lose her sight so long;
  If her eyes have not blinded thine,
  Look, and to-morrow late, tell me,
  Whether both th' Indias of spice and mine
  Be where thou leftst them, or lie here with me.
  Ask for those kings whom thou saw'st yesterday,
  And thou shalt hear, 'All here in one bed lay.'
She's all states, and all princes, I,
  Nothing else is.
  Princes do but play us; compared to this,
  All honour's mimic, all wealth alchemy.
Thou, sun, art half as happy as we,
  In that the world's contracted thus.
Thine age asks ease, and since thy duties be
  To warm the world, that's done in warming us.
Shine here to us, and thou art everywhere;
  This bed thy center is, these walls, thy sphere.

Apparently Donne was not so pleased with the sun's rising, reversing the psalmist's famous reflection of Psalms 30:5 that

Weeping may endure for the night,
  But a shout of joy cometh in the morning.

Donne inverts the psalmist, instead taking his delight by night and lamenting the morn.


text:
Q: How to reduce Grails' reload check interval Whenever I touch (save) a groovy class, in Grails development mode, there's a noticeable interval (around 10 seconds) before I start seeing Compiling 1 source files messages.
Is there a setting to reduce (speed up) the interval between checks?
Is there a way to make it ring the terminal bell (beep) when the reloading is done?

A: Put a development copy of your project repository in a ramdisk (but always remember to commit and push your modifications!).
This will practically zero your disk access time, since it won't be accessing the disk at all (mostly).


text:
Q: JmsTemplate batch issue my current use case is in my listener it will:

*

*Consume an event(let's call it original event) from queue, this event includes list of replay events(let's call it sub events).

*Produce those replay events (sub events) in a batch to other queue.

*Update Cassandra.

I can produce all the replay events based on what Gary mention, and rollback all the replay events if any exceptions happen during produce.

Use one of the execute methods with a ProducerCallback...
SessionCallback and ProducerCallback
Then, in your ProducerCallback.doInJms() method...
Use the producer to send multiple messages. When the callback exits,
  the transaction will be committed.

However, if there are any exception happen in step 3 we can only rollback the original event but not those replay events, since in step 2 we already committed those replay events after the callback exits and those replay events already in another queue and cannot be rollback.
Does someone has any better idea about how we can rollback everything if step 3 has exception?

A: You have to do everything within the same session; consume, produce..., cassandra.
All inside doInJms()...

*

*session.createConsumer()

try {

*

*consumer.receive()

*producer send() ...

*cassandra update

finally {

*

*consumer.close()

}


text:
Q: Does finding all locations in a region fill out unexplored areas of the map? In Xenoblade Chronicles 1, if you discovered every named location and landmark in a region any unexplored sections of the map would be filled in automatically.
Does the same apply to Xenoblade Chronicles 3? Will finding every landmark and named area fill in the map?

A: Yes! An easy map to test this:

 While climbing the sword, the outer area does not have many POIs or waypoints; you can test it by finishing this area.

This is a very helpful way to finish off a certain gigantic map.


text:
Q: Grouping by a column and counting number of positive and negative values corresponding to each value in R I want to have a list of positive and negative values corresponding to each value that comes after grouping a column. My data looks like this:
dataset <- read.table(text =
"id value
1 4
1 -2
1 0
2 6
2 -4
2 -5
2 -1
3 0
3 0
3 -4
3 -5",
header = TRUE, stringsAsFactors = FALSE)

I want my result to look like this:
id num_pos_value num_neg_value num_zero_value
1 1 1 1
2 1 3 0
3 0 2 2

I want to extend the columns of the above result by adding sum of the positive and negative values.
id num_pos num_neg num_zero sum_pos sum_neg
1 1 1 1 4 -2
2 1 3 0 6 -10
3 0 2 2 0 -9

A: We create a group by 'id' and calculate the sum of logical vector
library(dplyr)
df1 %>%
   group_by(id) %>%
   summarise(num_pos = sum(value > 0),
             num_neg = sum(value < 0),
             num_zero = sum(value == 0))
# A tibble: 3 x 4
#     id num_pos num_neg num_zero
#  <int>   <int>   <int>    <int>
#1     1       1       1        1
#2     2       1       3        0
#3     3       0       2        2

Or get the table of sign of 'value' and spread it to 'wide'
library(tidyr)
df1 %>%
   group_by(id) %>%
   summarise(num = list(table(factor(sign(value), levels = -1:1)))) %>%
   unnest %>%
   mutate(grp = rep(paste0("num", c("pos", "zero", "neg")), 3)) %>%
   spread(grp, num)

Or using count
df1 %>%
   count(id, val = sign(value)) %>%
   spread(val, n, fill = 0)

data
df1 <- structure(list(id = c(1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
 3L), value = c(4L, -2L, 0L, 6L, -4L, -5L, -1L, 0L, 0L, -4L, -5L
 )), class = "data.frame", row.names = c(NA, -11L))


text:
Q: UI framework design: different approaches to determine preselected item in a list? Something I've been wondering about: if I was to implement some kind of list like UI widget (no specific target platform is assumed here, but I'm using C# to illustrate), I can see three ways of determining the preselected entry in my list.
Look at the stubs below. All three implementations have a delegate that asks the implementation for the items to be displayed instead of passing the items in directly. The idea is that the items will only be requested if the UI element actually is about to be displayed.
The first implementation has a setter that allows defining the preselected item.
public class ListWidget<T>
{
  public Action<IList<T>> GetListItems;

  public SetPreselectedItem(T item)
  {
    this.preselectedItem = item;
  }
}

or:
This follows the idea that the list widget at some point asks the implementation - by looping all the items it knows - if an item should be preselected or not. Advantage I see here: it would allow multi selection.
public class ListWidget<T>
{
  public Action<IList<T>> GetListItems;

  public Action<bool> IsItemPreselected(T item);
}

or:
This is asking the implementation for the the preselected item whenever it needs to render its contents.
public class ListWidget<T>
{
  public Action<IList<T>> GetListItems;

  public T GetPreselectedItem();
}

If I look at Apple's UIKit, they kind of use the first approach: the list is asking for the data to be displayed but the selected item is set directly.
The problem I see with a setter and the last version: you can set any value, even if that item does not exist in the list. It requires either an extra check if the item to be set actually exists in the list.
I have seen all variations of the patterns above on different platforms but I'm wondering if there is a best approach? Or is there yet another version of implementing it?


text:
Q: parsing string for dropdownlist options I have a string (q.ADDLOption) with values like
Select,|IE,IE|Safari,Safari|Chrome,Chrome|

I want to parse it to be the options in a dropdownlist
Optionddl oddl = q.ADDLOption.Split('|').ToList<Optionddl>(); <== this is giving error

I have also a class
public class Optionddl
{
    public string text { get; set; }
    public string value { get; set; }
}

A: This might do the trick for you
List<Optionddl> oddl = q.ADDLOption.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries)
                       .Select(x => new Optionddl
                       {
                           text = x.Split(',')[0],
                           value = x.Split(',')[1]
                       })
                       .ToList<Optionddl>();

The first problem with the code is q.ADDLOption.Split.ToList is going to return a list and not an object of Optionddl. Secondly we cannot directly convert an array of string[] to List because 'string[]' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList(System.Collections.Generic.IEnumerable)' has some invalid arguments would be the error. Lastly it is optional to create ToList or ToList<Optionddl>.
Hope this helps

A: Because Optionddl is not something can be converted to a List.
Consider this:
List<Optionddl> oddl = q.ADDLOption.Split(new string[]{'|'}).ToList<Optionddl>();

A: Alternatively you can create some implicit/explicit operators :
public class Optionddl
{
    public string text { get; set; }
    public string value { get; set; }

    public static implicit operator string(Optionddl option)
    {
        return option.text + "," + option.value;
    }

    public static implicit operator Optionddl(string str)
    {
        string[] extracted = str.Split(",");
        return new Optionddl { text = extracted[0], value = extracted[1] };
    }
}

This way you can make something like :
Optionddl meOption = new Optionddl { value = "IE", text = "IE" };
string meOptionString = meOption; // result of meOptionString = "IE,IE"
meOption = meOptionString; // result of meOption = { text = "IE", value = "IE" }


text:
Q: Is there an equivalent concept of a "variety" for SAT? Couldn't find anything via google - I was wondering what work is out there looking at SAT problems from the perspective akin to an algebraic variety, e.g. a set of variables $X_1=$true, $X_2=$false, .., $X_k=$true, etc define a set of propositions which are all satisfed by that particular set of values in much the same way that a variety defines a set of polynomials that all happen to vanish at the same points.
Thanks.

A: First, let me address the dual question (which is easier): visualizing a SAT instance as a variety.
There is a natural way of representing any instance of SAT as a variety in $(\mathbb{Z}/2\mathbb{Z})^n$ (where $n$ is the number of variables). This is because we can interpret the two-element Boolean algebra $(2, \vee, \wedge, \neg)$ in the two-element ring $(\mathbb{Z}/2\mathbb{Z}, +, \times)$:

*

*"$a\wedge b$" is shorthand for "$a\times b$".

*"$a\vee b$" is shorthand for "$a+b+ab$".

*"$\neg a$" is shorthand for "$1-a$" (that is, the element of the ring $\mathbb{Z}/2\mathbb{Z}$ which when added to $a$ equals $1$). Note that $1-a=1+a$ in this context.
So, for instance, to the SAT-instance $$(a\vee b)\wedge (\neg a)$$ we associate the polynomial $$(a+b+ab)(1-a)=a+b+ab+a+ab+ab=b+ab.$$ Finding a solution to the SAT-instance corresponds to finding a point where this polynomial equals 1 (not zero), that is, to finding a zero for the polynomial $$1+b+ab.$$ It's easily checked that the only zero of this polynomial is $b=1$, $a=0$, which agrees with the SAT-instance.
See https://en.wikipedia.org/wiki/Boolean_ring.

OK, now onto the question you ask.
The problem is that in order to even begin to think of something as a variety, we have to think of that thing as a subset of $R^n$ for some ring $R$ and some number $n$. The problem is, the set of SAT instances does not form a ring in any obvious way (let alone the set of ordered pairs from a ring).
This can be fixed: equivalence classes of SAT instances can be thought of as a ring. Specifically, identify $\varphi$ and $\psi$ if their solution sets are the same. The result is a Boolean algebra, which can be turned into a Boolean ring (see above). Now to each valuation of the $k$-many propositional variables (we fix $k$ ahead of time), we can associate a subset of this ring, and this subset is indeed a variety. But this is kind of ugly; in particular, the equivalence class construction requires us to solve SAT!
Based on this, I would tentatively say that there is no "natural" and computationally efficient way to view the set of SAT instances which are solved by a fixed valuation as a variety.

A: For one variety over one finite field, the algebraic geometry translation of a SAT problem is not all that useful.  Switching between the two descriptions is computationally trivial. Algebraic geometry doesn't help with finding solutions so much as describing relations between solutions. SAT problems do not lead to structured varieties like elliptic curves or algebraic surfaces where algebraic geometry comes into its own.
The advantage of geometry is when there are many varieties, or many fields and rings in which to solve the equations, or both.
This is roughly the idea of Aaronson and Wigderson's paper on Algebraization as a barrier to $P \neq NP$ proofs.  General arguments about computation with bits, thought of as facts about polynomials or varieties where we look for solutions mod $2$, also would work over finite fields with more than $2$ elements, or more general rings than that. In those more general settings they can arrange oracles for which $P = NP$, so things are not that easy.
Geometric Complexity Theory proposed by Mulmuley is an application of algebraic geometry to complexity and an approach to the $P=NP$ problem, but the geometry does not come from mapping SAT problems to algebraic equations mod $2$.  The idea is to look for algebraic problems in invariant theory and group representation theory that are close enough analogues of $P=NP$ that solving the algebra problems would have implications for computational complexity theory.  Algebraic geometry appears in GCT because it is a tool for the algebra problems that appear.


text:
Q: Unzip a multipart format file in-memory How to unzip a multipart file in-memory in java without creating it temporarily on disk? I cannot find any way to unzip it in-memory.
I am getting a zip bundle of SSL certificates from API in multipart format. I want to unzip this and read into X509Certificate.
Here is my code (but its creating file on disk):
 if (!uploadedFile.isEmpty()) {
            File file = new File(uploadedFile.getOriginalFilename());
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(uploadedFile.getBytes());
            fos.close();

            ZipFile zipFile = new ZipFile(file);
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream((File) uploadedFile));
            ZipEntry zipEntry = zipInputStream.getNextEntry();

            X509Certificate mainCert = null;
            Set<X509Certificate> certChain = new HashSet<>();

            while (zipEntry != null) {
                if (!zipEntry.isDirectory()) {
                    String fileName = zipEntry.getName();
                    if (fileName.endsWith(".cer") || fileName.endsWith(".crt") || fileName.endsWith(".pem") ||
                            fileName.endsWith(".cert") || fileName.endsWith(".key")) {
                        InputStream inputStream = zipFile.getInputStream(zipEntry);
                        CertificateFactory fact = CertificateFactory.getInstance("X.509");

                        X509Certificate certificate = (X509Certificate) fact.generateCertificate(inputStream);
                        if (certificate.getBasicConstraints() == -1) {
                            mainCert = certificate;
                        } else {
                            certChain.add(certificate);
                        }
                    }
                }
                zipEntry = zipInputStream.getNextEntry();
            }
            zipInputStream.closeEntry();
            zipInputStream.close();

P.S. I don't want to use Bouncy Castle libs for zip/unzip.