text:
Q: getting undefined when trying to fetch data from api and change innerHTML. data shows on console but not in html page const buildPosts = (blogPosts) => {
  let blogPostsContent = "";

  for (blogPost of blogPosts) {
    const postDate = new Date(blogPosts.added_date).toDateString();

    blogPostsContent += `

${postDate}

${blogPosts.title}

${blogPosts.content}

             `;
  }
  document.querySelector(".blog-posts").innerHTML = blogPostsContent;
};

A: Since it's for (blogPost of blogPosts), you should access in the inner loop as blogPost instead of blogPosts.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

const blogPosts = [
  {
    added_date: '2021-01-01T05:07:59Z',
    title: 'Title1',
    content: 'Content1'
  },
  {
    added_date: '2021-01-02T05:07:59Z',
    title: 'Title2',
    content: 'Content2'
  }
];
let blogPostsContent = "";
for(blogPost of blogPosts) {
    const postDate = new Date(blogPost.added_date).toDateString();

    blogPostsContent += `

${postDate}

${blogPost.title}

${blogPost.content}

         `
 }
document.querySelector('.blog-posts').innerHTML = blogPostsContent;
.post {
  border: 1px solid red;
}


text:
Q: How to center navigation bar items CSS I have a navigation bar that it spanning the entire page's width. I've also added a jQuery script so that it changes to position:fixed after scrolling for a bit, but I don't think that will influence this issue.
My issue is that I can't get the navigation bar
's to center. I've tried countless things I've found on the internet, and even downloaded some templates to splice in. No luck. I'm sure I'm just missing something, but I'd like the
's to go smack-dab in the middle of the navbar, but everything I've tried either makes them slightly off, floats them to the left, or makes them not resize properly.
Here's my HTML:
<!doctype html>

        <link rel="stylesheet" type="text/css" href="stylesheet.css">

Blah blah blah

Home

Home

Home

            Lorem ipsum dolor sit amet...

            Nullam pellentesque nunc luctus...

            Donec sodales fermentum orci...

            Ut venenatis tellus ...

            Nullam quis molestie nunc...

And the CSS:
body{
background-image:url("woodPatternShadow.png");
background-size:75% auto;
padding:0;
font-family:"Verdana";
}

.nav{
height:40px;
background-color:rgba(0,0,0,0.25);
left:0;
right:0;
box-shadow: inset 0 3px rgba(255, 255, 255, 0.4), inset 0 10px 4px rgba(255, 255, 255, 0.3),inset 0 10px 20px rgba(255,255,255,0.25), inset 0 -15px 30px rgba(28,0,0,0.3);
border:1px solid rgba(0,0,0,0.1);
margin:0;
position:absolute;
}

#fixNav{
position:fixed;
top:0px;
}

.nav ul{
}

.nav ul li{
}

.nav ul li a{
}

.content{
background-color:white;
border-radius:20px;
padding:10px;
width:70%;
margin:100px auto 0;
}

The empty selectors are the places where I can't figure it out.
Can someone clear this up for me?

A: Set the ul to have text-align: center and set display: inline-block on the li elements.
.nav ul {
   list-style: none;
   text-align: center;
}

.nav ul li {
   display: inline-block;
}

Elements with display: inline-block are treated as inline elements even though they act like block elements in most respects, so setting text-align: center on the container will center the inline li elements inside of it.
Obviously this is a barebones functional answer - you will need to add styles to adjust presentation of the li and a elements.  All this code does is remove the default bullets and centers the li elements.

A: There's always
text-align: center;

http://jsfiddle.net/M4Q5h/
Then there's:
.nav ul li{
    display: table;
    margin-left: auto;
    margin-right: auto;
}

http://jsfiddle.net/gnM5f/
2nd is probably the best way but if you want text centered anyway then the first might be fine (EDIT: In which case Ennui's answer is more complete).

A: Apply list-style:none and text-align:center to .nav class.
CSS:
.nav{
    ----
    ----
    list-style:none;
    margin:0;
    padding:0;
    text-align:center;
}
.nav li{
    display:inline;
}
.nav a{
    display:inline-block;
    padding:10px;
}

See demo

A: just add this

nav {
    background-color: rgb(0, 0, 0);
    overflow: hidden;
    font-family: consolas;
    align-items: center;
}
nav a {
    text-decoration: none;
    padding: 20px;
    text-align: center;
    float: center;
    color: white;
    margin-left: auto;
    margin-right: auto;
}

        Home
        Videos
        Resources
        Projects
        About Us

redpajama_set_name: RedPajamaStackExchange


text:
Q: GitHub CI/CD - Run elevated commands I have a CI/CD pipeline in GitHub.
I need to run a software in elevated permission (e.g "Run As Administrator") in the pipeline
Currently running:
step:
run: software.exe
gives error:light.exe : error LGHT0217.

A: After investigating the issue:
GitHub pipeline runs as administrator.
To solve the light.exe : error LGHT0217
I added
 project.LightOptions = "-sval";


text:
Q: Unhandled rejection SequelizeEagerLoadingError: modalB is not associated to modelA I'm using sails.js with sequelize.js ORM. This is how I define my models to work with the associations:
https://github.com/KSDaemon/sails-hook-sequelize
model User:
module.exports = {
  attributes: {
    user_id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    username: Sequelize.STRING,
    password: Sequelize.STRING,
    createdAt: Sequelize.DATE,
  },
  associations: function () {
    Response.hasMany(Post, { as: 'posts', foreignKey: 'user_id' });
    Response.hasMany(Response, { as: 'responses', foreignKey: 'user_id' });
  },
  defaultScope: function () {
    return {
      include: [
        { model: Post, as: 'posts' },
        { model: Response, as: 'responses' },
      ]
    };
  },
  options: {
    freezeTableName : false,
    tableName       : 'users',
    schema          : 'codigomx',
    classMethods    : {},
    instanceMethods : {},
    hooks           : {}
  }
};

and my model Response:
module.exports = {

  attributes: {
    response_id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    response_content: Sequelize.TEXT,
    createdAt: Sequelize.DATE
  },
  associations: function () {
    Response.belongsTo(User, { foreignKey: 'user_id', targetKey: 'user_id'});
    Response.belongsTo(Post, { foreignKey: 'post_id', targetKey: 'post_id'});
  },
  options: {
    freezeTableName : false,
    tableName       : 'responses',
    schema          : 'codigomx',
    classMethods    : {},
    instanceMethods : {},
    hooks           : {}
  }

};

but when I try to run this:
User.findOrCreate({where: {username: 'user'}, defaults: {password: 'psw'}});

It gives me this error: Unhandled rejection SequelizeEagerLoadingError: Response is not associated to User!
and I do have the associations correctly, can someone tell me if my associations have something wrong?
here is my repo: https://github.com/AlfredoDaAs/codigomx

A: I think there is a typo in the user model.
Instead of Response.hasMany(Post, { as: 'posts', foreignKey: 'user_id' });, it should be User.hasMany(Post, { as: 'posts', foreignKey: 'user_id' });


text:
Q: ng-repeat for ui.sref in AngularJS Is it possible to print the menus with ui-sref using ng-repeat?
Pseudo code:

    {{menu.text}}

Here, ui-sref="{{menu.sref}}" or ui-sref="menu.sref" is not working. sref is an attribute that exists in menu.


text:
Q: HTML Add multiple file to the input I know that it is easy and I just need to add "multiple" line to the file input. But.
I am using
http://the-stickman.com/web-development/javascript/upload-multiple-files-with-a-single-file-element/
this script (I also know there is new one but I'd like to use this one, and there are scripts like dropzone.js but I couldn't figure out something (I asked about it here, but no-one answered).
So I've choosen this script.
I added it into my dropzone form like this:

                    <input type="file" name="file" id="my_file_element" multiple/>
                    click here to add file or drag and drop

                    up to 5 files

All works as I want it to work but the big issue is I can add only one file at once. Even if I choose more, or drag and drop more - only one is added.
Could anyone help change the code so I will be able to put few files at once, no one by one?
@@@@@
here is the script if you don't want to download it:
/**
 * Convert a single file-input element into a 'multiple' input list
 *
 * Usage:
 *
 *   1. Create a file input element (no name)
 *      eg. <input type="file" id="first_file_element">
 *
 *   2. Create a DIV for the output to be written to
 *      eg.

 *
 *   3. Instantiate a MultiSelector object, passing in the DIV and an (optional) maximum number of files
 *      eg. var multi_selector = new MultiSelector( document.getElementById( 'files_list' ), 3 );
 *
 *   4. Add the first element
 *      eg. multi_selector.addElement( document.getElementById( 'first_file_element' ) );
 *
 *   5. That's it.
 *
 *   You might (will) want to play around with the addListRow() method to make the output prettier.
 *
 *   You might also want to change the line
 *       element.name = 'file_' + this.count;
 *   ...to a naming convention that makes more sense to you.
 *
 * Licence:
 *   Use this however/wherever you like, just don't blame me if it breaks anything.
 *
 * Credit:
 *   If you're nice, you'll leave this bit:
 *
 *   Class by Stickman -- http://www.the-stickman.com
 *      with thanks to:
 *      [for Safari fixes]
 *         Luis Torrefranca -- http://www.law.pitt.edu
 *         and
 *         Shawn Parker & John Pennypacker -- http://www.fuzzycoconut.com
 *      [for duplicate name bug]
 *         'neal'
 */
function MultiSelector( list_target, max ){

    // Where to write the list
    this.list_target = list_target;
    // How many elements?
    this.count = 0;
    // How many elements?
    this.id = 0;
    // Is there a maximum?
    if( max ){
        this.max = max;
    } else {
        this.max = -1;
    };

    /**
     * Add a new file input element
     */
    this.addElement = function( element ){

        // Make sure it's a file input element
        if( element.tagName == 'INPUT' && element.type == 'file' ){

            // Element name -- what number am I?
            element.name = 'file_' + this.id++;

            // Add reference to this object
            element.multi_selector = this;

            // What to do when a file is selected
            element.onchange = function(){

                // New file input
                var new_element = document.createElement( 'input' );
                new_element.type = 'file';

                // Add new element
                this.parentNode.insertBefore( new_element, this );

                // Apply 'update' to element
                this.multi_selector.addElement( new_element );

                // Update list
                this.multi_selector.addListRow( this );

                // Hide this: we can't use display:none because Safari doesn't like it
                this.style.position = 'absolute';
                this.style.left = '-1000px';

            };
            // If we've reached maximum number, disable input element
            if( this.max != -1 && this.count >= this.max ){
                element.disabled = true;
            };

            // File element counter
            this.count++;
            // Most recent element
            this.current_element = element;

        } else {
            // This can only be applied to file input elements!
            alert( 'Error: not a file input element' );
        };

    };

    /**
     * Add a new row to the list of files
     */
    this.addListRow = function( element ){

        // Row div
        var new_row = document.createElement( 'div' );

        // Delete button
        var new_row_button = document.createElement( 'input' );
        new_row_button.type = 'button';
        new_row_button.value = 'Delete';

        // References
        new_row.element = element;

        // Delete function
        new_row_button.onclick= function(){

            // Remove element from form
            this.parentNode.element.parentNode.removeChild( this.parentNode.element );

            // Remove this row from the list
            this.parentNode.parentNode.removeChild( this.parentNode );

            // Decrement counter
            this.parentNode.element.multi_selector.count--;

            // Re-enable input element (if it's disabled)
            this.parentNode.element.multi_selector.current_element.disabled = false;

            // Appease Safari
            //    without it Safari wants to reload the browser window
            //    which nixes your already queued uploads
            return false;
        };

        // Set row value
        new_row.innerHTML = element.value;

        // Add button
        new_row.appendChild( new_row_button );

        // Add it to the list
        this.list_target.appendChild( new_row );

    };

};

@@@@@
this is script inside html file:

@edit
https://jsfiddle.net/1sbbepn4/8/  here's what I got now
working example of what i got is up here


text:
Q: Windows Server 2003 forgets folder shares from ISCSI-Volume after restart I have running a Server 2003 with the Microsoft ISCSI Initiator. I mapped an ISCSI-Volume and after the restart of the server, the the folders aren't shared anymore. The NTFS-rights are still rigth and the drive letter does not change. Any idea?
Thanks,
cyntaxx

A: Please reference the MS KB regarding this issues:
http://support.microsoft.com/kb/870964
Basically:

Make the Server service dependent on
  the iSCSI Initiator service. For
  information about how to do this, see
  the "Make the Server service dependent
  on the iSCSI Initiator service"
  section


text:
Q: Can we write trigger on LoginHistory object I want to copy login history data in custom object when new entry added to login history. If trigger is not possible then is there workaround for the same

A: You can't create a trigger on LoginHistory object. But as workaround you can create a scheduled apex which will query LoginHistory objects
global class CopyLoginHistory implements Schedulable {
    global void execute(SchedulableContext ctx) {
        List<LoginHistory> loginHistories = [SELECT ApiType,
                                                    ApiVersion,
                                                    Application,
                                                    Browser,
                                                    ClientVersion,
                                                    Id,
                                                    LoginTime,
                                                    LoginType,
                                                    LoginUrl,
                                                    Platform,
                                                    SourceIp,
                                                    Status,
                                                    UserId
                                            FROM LoginHistory
                                            WHERE LoginTime <: System.now()
                                            AND LoginTime >: System.now().addMinutes(-1)];
        if ( !loginHistories.isEmpty()) {
            List<LoginHistoryCopy__c> lhc = new List<LoginHistoryCopy__c>();
            for (LoginHistory lh: loginHistories) {
                lhc.add(new LoginHistoryCopy__c(ApiType__c       = ApiType ,
                                                ApiVersion__c    = ApiVersion ,
                                                Application__c   = Application ,
                                                Browser__c       = Browser ,
                                                ClientVersion__c = ClientVersion ,
                                                Id__c            = Id ,
                                                LoginTime__c     = LoginTime ,
                                                LoginType__c     = LoginType ,
                                                LoginUrl__c      = LoginUrl ,
                                                Platform__c      = Platform ,
                                                SourceIp__c      = SourceIp ,
                                                Status__c        = Status ,
                                                UserId__c        = UserId
                ));
            }
            insert lhc;
        }
   }
}

and copy these records to custom object


text:
Q: How to install driver for TP-Link Archer T9E V1 in Ubuntu 16.04 LTS I have just installed Ubuntu 16.04 and nether wire connection works or wirless.
Now I have bought a PCI adapter from https://www.tp-link.com/us/download/Archer-T9E.html#videos
I have followed the link: How to install TP-LINK Archer T4U driver?
but it didn't worked for me ~/Desktop/rtl8812AU_8821AU_linux-master$ sudo modprobe rt18812au
modprobe: FATAL: Module rt18812au not found in directory /lib/modules/4.13.0-38-generic
Does anyone know what does it mean or how can solve this ?

A: Okay so I just fell over something that could help you.
I use the T9E network card as well and everything works for me:

*

*Open the Software & Updates application

*Go to the Additional Drivers tab

*Look for the Broadcom Limited: BCM4360 802.11ac Wireless Network Adapter device (this is your TP-Link)

*Choose the Broadcom 802.11 Linux STA wireless driver source from bcmwl-kernel-source (proprietary) option to enable it

A: I had similar problem. The driver wasn't  install by itself:
Run

apt-get update && apt-get upgrade && apt-get dist-upgrade

Reboot and run

apt-get install broadcom-sta-dkms
modprobe -r b44 b43 b43legacy ssb brcmsmac bcma
modprobe wl

And reboot again
Link to topic when i found solution:
https://unix.stackexchange.com/questions/381848/installing-wifi-drivers-for-14e443a0-rev-3-broadcom-pcie-device-cant-find-bc?newreg=80f009f225c94792b01c46e3d6c4b062

A: If you have internet while you install Ubuntu it will install the T9E driver by itself. I sadly do not know how to do it after install.
I do have a working T9E driver. If you know any way I can help do ask.

A: Why are you trying a T4U driver when you have a T9E card?
The T4U is a USB device uses a Realtek chip. The T9E is a pcie card and it uses a Broadcom chip hence you need to use the Broadcom wl driver.


text:
Q: No second operating system available and no boot menu available (only Windows 8.1 starts and is visible in WIN-Boot-Menu) I have no boot-menu after installing UBUNTU 16 on SAME HD (separate partition) than Windows 8.1
I have a HP ENVY DV7 Laptop with Windows 8.1RT, on which I try to install and boot UBUNTU 16
Can anyone tell me what to doä?
Tks a lot,

A: I have tried many things and I think HP does not want to allow dual boot on my machine and others like it.  My HP 15 (not Envy) started with Windows 8.1 but was first upgraded with the Windows 10 "free" version and now the anniversary version.  All had the same issue- no boot menu (with dual boot option) at startup.  The workaround I found is long and not convenient.  Go to SETTINGS/UPDATE AND SECURITY/RECOVERY/ADVANCED STARTUP (needs to restart)/USE A DEVICE/UBUNTU.  Then, the traditional dual boot screen appears (default is Ubuntu).  It is a long way around.  I had read of the boot repair option mentioned earlier but was reluctant to go that route.
Good luck


text:
Q: Need help simplifying my code on poker evaluation I am currently creating a poker evaluator that compares the hand from multiple players and decide who the winner is. However, the method for the actual comparison and tie-breaking turns out to be much more work than it should. Is there any way I can perhaps simplify my code? Since I am not posting all of the source code I will discuss the functionality for some of the methods called within:
int HandEval(Card[] hand) takes an array of cards and return an int which symbolizes the score of the hand(ie. three of a kind will have a higher score than one pair)
int GetHighCard(Card[] hand) takes an array of cards and return the rank of the high card used for tie-breaking.(ie. in the case of three of a kind, the rank of one of these three kinds will be returned)
 public void FindWinner()
    {
        int maxScore = 0;
        int maxRank = 0;
        List<String> potentialWinners = new List<string>();
        List<Card[]> candHand = new List<Card[]>();

        Dictionary<string, Card[]> deckTable = new Dictionary<string, Card[]>();
        Dictionary<string, int> scoreTable = new Dictionary<string, int>();
        Dictionary<string, int> highTable = new Dictionary<string, int>();

        //place each player to deckTable which holds the player name and their hand
        //place each player to scoreTable which holds the player name and the score of their hand
        for (int i = 0; i < players.Count; i++)
        {
            deckTable.Add(players[i].GetName(), players[i].GetSorted());
            scoreTable.Add(players[i].GetName(), HandEval(players[i].GetSorted()));

        }

        //display the player name and the score of their hand
        foreach (KeyValuePair<string, int> pair in scoreTable)
        {
            Console.WriteLine("{0}, {1}", pair.Key, +pair.Value);
        }

        //find the max score of the current game
        foreach (var kvp in scoreTable)
        {
            if (kvp.Value > maxScore)
            {
                maxScore = kvp.Value;
            }
        }

        //display the max score
        Console.WriteLine("The maximum score is " + maxScore);

        //for all players with the max score, add them to the potential winners list
        foreach (var kvp in scoreTable)
        {
            if (kvp.Value == maxScore)
            {
                potentialWinners.Add(kvp.Key);
            }
        }

        //if there are more than one potential winner, run the tie-break checks
        if (potentialWinners.Count > 1)
        {
            Console.WriteLine("Potential winners include: ");
            for (int i = 0; i < potentialWinners.Count(); i++)
            {
                Console.WriteLine("" + potentialWinners[i] + "");
            }

            //add the name of the potential winners and the rank of the high card as a key value pair to highTable
            for (int i = 0; i < potentialWinners.Count(); i++)
            {
                if (deckTable.ContainsKey(potentialWinners[i]))
                {
                    Card[] cHand = deckTable[potentialWinners[i]];
                    highTable.Add(potentialWinners[i], GetHighCard(cHand));
                }
            }

            Console.WriteLine("Displaying potential winners with their high card rank.");
            foreach (KeyValuePair<string, int> pair in highTable)
            {
                Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
            }

            //find the max rank of high card from all potential winners
            foreach (var kvp in highTable)
            {
                if (kvp.Value > maxRank)
                {
                    maxRank = kvp.Value;
                }
            }

            Console.WriteLine("The final winner after tie-breaking is");

            //display the winner(s) with the highest rank of card
            foreach (var kvp in highTable)
            {
                if (kvp.Value == maxRank)
                {
                    Console.WriteLine("" + kvp.Key + "");
                }
            }
        }
        //if there is only one potential winner, display the name
        else
        {
            Console.WriteLine("The final winner is");
            Console.WriteLine(potentialWinners[0]);
        }
    }
}

Any help or hints will be greatly appreciated!

A: Your biggest mistake is to ignore what kind of language you are using. Your style is imperative, not object oriented.
What you want to do is to create classes to handle those things, like cardHand or scoreTable. Then you give them methods like getBestHand.
The part of the code in which you print out stuff should look something like this pseudo-code:
print "The winner is " + table.getBestHand.getPlayer.name
that is, without any for each loop or the like in that part of the code. You want to separate logic and output. Usually it's a good sign when a single function or method has the size of not more than half the screen (exceptions occur of course). Take everything that you could describe in a single word but has more than five lines of code and make a method out of it.
For this isolated example, this will of course produce more code, but I suppose that even in a poker game, having proper classes will already pay out. If not in amount of code, then at least in readability and maintainability.

A: for (int i = 0; i < potentialWinners.Count(); i++)
{
    Console.WriteLine("" + potentialWinners[i] + "");
}

//add the name of the potential winners and the rank of the high card as a key value pair to highTable

for (int i = 0; i < potentialWinners.Count(); i++)
{
    if (deckTable.ContainsKey(potentialWinners[i]))
    {
        Card[] cHand = deckTable[potentialWinners[i]];
        highTable.Add(potentialWinners[i], GetHighCard(cHand));
    }
}

You are basically calling the same for loop 2 times, you could bring the
Console.WriteLine("" + potentialWinners[i] + "");

in the for loop after it... also pls remove the ("") out of your Console WriteLine´s its doing basically nothing but making your Code slower
the same is said for these loops
foreach (var kvp in highTable)

and
foreach (var kvp in scoreTable)

simple things to make your code smaler and more efficient
Greetings


text:
Q: Backreference to capturing group in vim In some text I need to find a string which may be one of the followning
foo#foo%foo
foo#foo%bar
foo#bar%foo
foo#bar%bar
bar#foo%foo
bar#foo%bar
bar#bar%foo
bar#bar%bar

I could write regex matcher like this
/\(foo\|bar\)#\(foo\|bar\)%\(foo\|bar\)

which works fine.
But I want to avoid duplication of capturing groups in the matcher.
If I write something like
/\(foo\|bar\)#\1%\1

it matches only FIRST and LAST possible strings I mentioned in the beginning.
Q: could I reference to previous capturing group itself, NOT previous match?

A: I completely under wanting to create and reuse sub-patterns and reusing them like @Amadan and @lcd047 alluded to however Vim does not support this behavior that I am aware of.
As an alternative you can use <c-f> while editing your pattern to open up the command-line-window. Inside this window you can edit the pattern with your normal Vim commands, e.g. daw, ct), etc. Once you are done you can press <cr> and run the search/command.
There is a nice Vimcast episode about this: Refining search patterns with the command-line window.
For more help see:
:h command-line-window
:h q/
:h c_Ctrl-f


text:
Q: GAS for fetch data from webpage to spreadsheet and check it against last one saved I have a script that:

*

*fetches data from a webpage

*pastes it to a spreadsheet

*is executed every day with time-driven trigger

I have two problems so far:

*

*Data on desired webpage isn't refreshed every day and my question is
is it possible to make some adjustments that the script doesn't save
data from webpage to SS if that data on webpage is same as last one
saved? Maybe to test last one row from webpage to last one from
spreadsheet? How to do that?

*Second problem is that script is executed and the all data is saved
to SS but I get this message:

"Exception: The number of columns in the data does not match the number of columns in the range. The data has 1 but the range has 8. (line 115, file "Code")"

Line 115 of the code is:
  eigenSheet.getRange(eigenRow, 1, eigenValues.length, eigenValues[0].length).setValues(eigenValues);

I think that the problem maybe is that on webpage I have empty rows sometimes? Is that a problem or sth else and how to fix it?
The whole script code is here:
regularSheetName = "Regular method";
eigenSheetName = "EIGENVECTOR Analysis";

function updateSheet(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  var regularSheet = ss.getSheetByName(regularSheetName);
  var eigenSheet = ss.getSheetByName(eigenSheetName);

  var date = Utilities.formatDate(new Date(), 'CET', "dd.MM.yyyy");

  var content = UrlFetchApp.fetch("link").getContentText().split('======================================================================================================');

  if(content.length<2){
    return SpreadsheetApp.getUi().alert("Unable to fetch data.");
  }

  var strLines = content[1].split("\n");

  var regularValues = [];
  var eigenValues = [];

  var isRegular = true;
  var ignore = false;
  for(var i=1;i<strLines.length;i++){
    var str = strLines[i];

    if(str.length<10){
      if(isRegular){
        ignore = true;
      }else{
        continue;
      }
    }else if(str.indexOf("EFAVORITE")>-1){
      ignore = false;
      isRegular = false;

      i++;
      str = strLines[i];
    }else if(str.indexOf("endfile")>-1){
      ignore = true;
    }

    if(!ignore){
      if(isRegular){
        //process regular method rows
        var lineSplit = str.split(" ");
        var row = [date];

        var curVal = "";
        for(var j=0;j<lineSplit.length;j++){
          if(lineSplit[j]===""){
            continue;
          }

          if((row.length==1&&curVal==="")||(isWord(lineSplit[j])&&isWord(lineSplit[j-1]))){
            if(curVal!=""){
              curVal += " ";
            }
            curVal += lineSplit[j];
          }else{
            row.push(curVal);
            curVal = lineSplit[j].replace(".", ",");
          }
        }
        row.push(curVal);

        regularValues.push(row);
      }else{
        //process eigen rows
        var lineSplit = str.split(" ");
        var row = [];

        var curVal = "";
        for(var j=0;j<lineSplit.length;j++){
          if(lineSplit[j]===""){
            continue;
          }

          if((row.length==0&&curVal==="")||(isWord(lineSplit[j])&&isWord(lineSplit[j-1]))){
            if(curVal!=""){
              curVal += " ";
            }
            curVal += lineSplit[j];
          }else{
            if(row.length==1&&curVal!="@"&&curVal!="N@"&&curVal!="N"){
              row.push("");
            }

            if(row.length>0){
              row.push(curVal);
            }else{
              row.push(date);
            }
            curVal = lineSplit[j].replace(".", ",");
          }
        }

        if(row.length==6&&curVal!="@"){
          row.push("");
        }

        row.push(curVal);

        eigenValues.push(row);
      }
    }
  }

  //append to sheets
  var regRow = regularSheet.getLastRow()+1;
  regularSheet.getRange(regRow, 1, regularValues.length, regularValues[0].length).setValues(regularValues);

  var eigenRow = eigenSheet.getLastRow()+1;
  eigenSheet.getRange(eigenRow, 1, eigenValues.length, eigenValues[0].length).setValues(eigenValues);
}

function isWord(checkStr){
  return (checkStr.indexOf("%")==-1 && checkStr!="@" && checkStr!="N@" && checkStr!="N" && isNaN(checkStr));
}

A: Try this:
Range.getValues().filter(function(r){return r.join('').length;});//if r.join.length is zero the row is empty

A: Supplementary answer
Long ago I created a utility to lessen the debugging time in tricky situations when one has to apply a set of values received from one source Range to another:
/**
 * @summary checks if range can accept an array of values
 * @param {GoogleAppsScript.Spreadsheet.Range} rng
 * @param {any[][]} values
 * @returns {boolean}
 */
const checkBounds = (rng, values) => {
    const targetRows = rng.getHeight();
    const targetCols = rng.getWidth();

    const { length } = values;
    const [firstRow] = values;

    return length === targetRows &&
        firstRow.length === targetCols;
};

Empty rows
In addition to Cooper's answer, you can also check if the row is empty with this, taking advantage of the fact that Boolean() constructor returns false on falsy values (you have to be careful, as a row filled with 0s will also be filtered out):
const isEmpty = (row) => row.every(Boolean);

Or just use the built-in method service isBlank() method


text:
Q: Get data with not,and MongoDB get data with not,and How to get value for INID not equal to 1 and SESSION not equal to 1 ( need to match INID and SESSION in same document ).
Ex:
{
    "_id" : ObjectId("5946800b962d74070729407a"),
    "INID" : 2,
    "SESSION" : 1,
    "TD" : ISODate("2017-06-18T13:28:43.409Z"),
    "ID" : 2,
    "OUT" : [
        {
            "score" : 50,
            "id" : "0",
            "out" : {
                "status" : "unreachable"
            }
        }
    ]
}

{
    "_id" : ObjectId("5946800b962d74070729407a"),
    "INID" : 3,
    "SESSION" : 1,
    "TD" : ISODate("2017-06-18T13:28:43.409Z"),
    "ID" : 2,
    "OUT" : [
        {
            "score" : 50,
            "id" : "0",
            "out" : {
                "status" : "unreachable"
            }
        }
    ]
}

{
    "_id" : ObjectId("5946800b962d74070729407a"),
    "INID" : 1,
    "SESSION" : 1,
    "TD" : ISODate("2017-06-18T13:28:43.409Z"),
    "ID" : 2,
    "OUT" : [
        {
            "score" : 50,
            "id" : "0",
            "out" : {
                "status" : "unreachable"
            }
        }
    ]
}

I want the first two documents.

A: Well, this worked for me:
db.yourCollectionName.find(
    { $or : [ { INID : {$gt: 1} }, { SESSION : {$gt: 1} } ] }
)

With this query you can have INID larger than 1 or SESSION larger than 1 or both larger than one. Why would you need to negate?
I guess you can also do this:
db.yourCollectionName.find(
    { $or : [ { INID : {$ne: 1} }, { SESSION : {$ne: 1} } ] }
)


text:
Q: how to temporarily pause drawing updates of a realtime data chart I would like a "Pause" the chart's series updates to do some job (like i have a button when i click it will suspend the chart update and then when I click resume button, it will update all suspended point in series.
I know about
chart1.Series.SuspendUpdates();

but it does not seem to work with me. I use mschart sample -- realtime data (thread safe).
Here is the full code
public partial class RealTimeSample : Form
{
    public RealTimeSample()
    {
        InitializeComponent();
    }
    private Thread addDataRunner;
    private Random rand = new Random();

    public delegate void AddDataDelegate();
    public AddDataDelegate addDataDel;
    private void RealTimeSample_Load(object sender, System.EventArgs e)
    {

        // create the Adding Data Thread but do not start until start button clicked
        ThreadStart addDataThreadStart = new ThreadStart(AddDataThreadLoop);
        addDataRunner = new Thread(addDataThreadStart);

        // create a delegate for adding data
        addDataDel += new AddDataDelegate(AddData);

    }

    /// Main loop for the thread that adds data to the chart.
    /// The main purpose of this function is to Invoke AddData
    /// function every 1000ms (1 second).
    private void AddDataThreadLoop()
    {
        while (true)
        {
            chart1.Invoke(addDataDel);

            Thread.Sleep(1000);
        }
    }

    public void AddData()
    {
        DateTime timeStamp = DateTime.Now;

        foreach (Series ptSeries in chart1.Series)
        {
            AddNewPoint(timeStamp, ptSeries);
        }
    }

    /// The AddNewPoint function is called for each series in the chart when
    /// new points need to be added.  The new point will be placed at specified
    /// X axis (Date/Time) position with a Y value in a range +/- 1 from the previous
    /// data point's Y value, and not smaller than zero.
    public void AddNewPoint(DateTime timeStamp, System.Windows.Forms.DataVisualization.Charting.Series ptSeries)
    {
        double newVal = 0;

        if (ptSeries.Points.Count > 0)
        {
            newVal = ptSeries.Points[ptSeries.Points.Count - 1].YValues[0] + ((rand.NextDouble() * 2) - 1);
        }

        if (newVal < 0)
            newVal = 0;

        // Add new data point to its series.
        chart1.Series.SuspendUpdates();
        ptSeries.Points.AddXY(timeStamp.ToOADate(), rand.Next(10, 20));
        chart1.Series.SuspendUpdates();
        // remove all points from the source series older than 1.5 minutes.
        double removeBefore = timeStamp.AddSeconds((double)(90) * (-1)).ToOADate();
        //remove oldest values to maintain a constant number of data points
        while (ptSeries.Points[0].XValue < removeBefore)
        {
            ptSeries.Points.RemoveAt(0);
        }

        chart1.ChartAreas[0].AxisX.Minimum = ptSeries.Points[0].XValue;
        chart1.ChartAreas[0].AxisX.Maximum = DateTime.FromOADate(ptSeries.Points[0].XValue).AddMinutes(2).ToOADate();

    }

    /// Clean up any resources being used.
    protected override void Dispose(bool disposing)
    {
        if ((addDataRunner.ThreadState & ThreadState.Suspended) == ThreadState.Suspended)
        {
            addDataRunner.Resume();
        }
        addDataRunner.Abort();

        if (disposing)
        {
            if (components != null)
            {
                components.Dispose();
            }
        }
        base.Dispose(disposing);
    }

    private void startTrending_Click_1(object sender, EventArgs e)
    {
        // Disable all controls on the form
        startTrending.Enabled = false;
        // and only Enable the Stop button
        stopTrending.Enabled = true;

        // Predefine the viewing area of the chart
        var minValue = DateTime.Now;
        var maxValue = minValue.AddSeconds(120);

        chart1.ChartAreas[0].AxisX.Minimum = minValue.ToOADate();
        chart1.ChartAreas[0].AxisX.Maximum = maxValue.ToOADate();

        // Reset number of series in the chart.
        chart1.Series.Clear();

        // create a line chart series
        Series newSeries = new Series("Series1");
        newSeries.ChartType = SeriesChartType.Line;
        newSeries.BorderWidth = 2;
        newSeries.Color = Color.OrangeRed;
        newSeries.XValueType = ChartValueType.DateTime;
        chart1.Series.Add(newSeries);

        // start worker threads.
        if (addDataRunner.IsAlive == true)
        {
            addDataRunner.Resume();
        }
        else
        {
            addDataRunner.Start();
        }
    }

    private void stopTrending_Click_1(object sender, EventArgs e)
    {
        if (addDataRunner.IsAlive == true)
        {
            addDataRunner.Suspend();
        }

        // Enable all controls on the form
        startTrending.Enabled = true;
        // and only Disable the Stop button
        stopTrending.Enabled = false;
    }
}

EDIT:
I figured out that as long as you set the minmum or the maximum property for the Axis the chart will keep display even if you have used
chart1.Series.SuspendUpdates();

I had to to remove those lines after i call SuspendUpdates() and now i can see the chart series suspended
chart1.ChartAreas[0].AxisX.Minimum = ptSeries.Points[0].XValue;
chart1.ChartAreas[0].AxisX.Maximum = DateTime.FromOADate(ptSeries.Points[0].XValue).AddMinutes(2).ToOADate();

A: MsChart does support this directly and indeed using Series.SuspendUpdates() is a good way but you need to do it right. (See however the update below for a drawback)
MSDN says this:

A call to the Invalidate method will have no effect after the
  SuspendUpdates method is called.
If you call the SuspendUpdates method several times, you will need to
  call the ResumeUpdates method an equal number of times.

This would explain why it doesn't work for you: Keeping the calls balanced is crucial. You need to keep track of them yourself as there is no counter you could query. But if you overshoot the ResumeUpdates calls, nothing bad happens, extra calls are simply ignored and the next SuspendUpdates will pause again.
Here is an example screenshot, watch the suspension counter..!

Note that normally adding points will automatically triggger an Invalidate. If you are doing other things, like drawing in a Paint event etc.. you may need to call Chart.Invalidate(), which SuspendUpdates will prevent, until cancelled by the same number of ResumeUpdates..

Alternatively you can also use one of these simple workarounds:

*

*The most straightforward will create the DataPoints via a constructor and then either

*

*use series.Add(theNewPoint) for normal, or..

*use someList<DataPoint>.Add(theNewPoint) for paused mode.

When setting to pause mode simply add all points to the series.Points before clearing it. Unfortunately there is no points.AddRange so you will have to use a foreach loop. Maybe chart.SuspendLayout could help with performance.

*

*The other workaround that comes to mind may or may not be suitable: You could play with the xAxis.Maximum and maybe xAxis.Minimum values. By setting them to fixed values you would allow addding points to the right without displaying them. To show the whole set of points you would reset them to double.NaN. This may work for you but it may also interfer with what you have.

Update: As noted by OP, the data are updated when he changes the Minimum and/or Maximum of an Axis. The same effect will show on many other occasions:

*

*Calling chart.AreasRecalculateAxesScale();

*Changing the chart's Size

*Changing any Axis property like Color or Width..

*Changing the LegendText of a Series

*and many more..

So I guess the updated data are needed whenever the ChartArea is manipulated and forced to update itself..
So, this may well make the 1st workaround the better because the more robust solution.


text:
Q: Autodesk Forge: Transparent objects in overlay scenes turn opaque I have a Forge scene with some semi-transparent custom geometry. After upgrading to version 7.21.0 of the Forge viewer, we had to move the custom geometry to an overlay scene, as described in the Forge guide. The resulting geometry is semi-transparent while navigating, but turns opaque about half a second after stopping.
This code can be used for testing on http://lmv.ninja.autodesk.com. In this example, you can see the blue sphere through the green one, but once you hover over the plane (I tested the Toy Plane model), you cannot.
const geometry = new THREE.SphereGeometry(20,32,32)
const material = new THREE.MeshBasicMaterial({
        color: '#00ff00',
        transparent: true,
        opacity: 0.5,
    })
const sphere1 = new THREE.Mesh(geometry, material)
sphere1.position.y = 90
NOP_VIEWER.overlays.addScene('custom-scene')
NOP_VIEWER.overlays.addMesh(sphere1, 'custom-scene')

const material2 = new THREE.MeshBasicMaterial({color: '#0000ff'})
const sphere2 = new THREE.Mesh(geometry.clone(), material2)
sphere2.position.y = 60

NOP_VIEWER.overlays.addMesh(sphere2, 'custom-scene')

How do I make the geometry stay transparent?
I have tried setting useIdBufferSelection: true, as suggested here.
Setting depthTest: false or depthWrite: false in the material fixes the transparency issue, but (unsurprisingly) breaks the order of rendering, so that close objects may appear behind far away objects.

A: Backgrounder:
The problem is THREE.js doesn't handle overlapping transparency very well.
ForgeViewer has a special multi-pass renderer, that renders diffuse objects first, then blends overlapping transparent objects.  It's not as accurate as OIT, but it's good enough.
Unfortunately, the viewer.impl.scene and impl.sceneAfter and overlay, all use the standard THREE.js traverser, which doesn't handle overlapping transparent objects... BUT ! ....
You can try these workarounds:

*

*Draw your meshes with LMV.SceneBuilder (which elevates three.js mesh objects into LMV geometrybuffer objects) (https://forge.autodesk.com/blog/custom-models-forge-viewer)

*Force 'double sided' renderering to your three.js transparent materials.  Still not perfect, but worth a shot


text:
Q: Using Python to remove duplicated contents in cells in Excel I am trying to use Python to remove the duplicated contents in the cells of an Excel Spreadsheet.
The data is in 1 column, in the original file. (names separated by ", " in each cell)
Noah, Mason, Emily, Isabella, Emily
Liam, Madison, Mia, Ava, Mia
Jacob, Ethan, Jayden, Mia, Jayden
Mason, Emily, Daniel, Emily, Daniel
Madison, Mia, Sophia, Abigail, Sophia
Ethan, Jayden, Elizabeth, Madison, Elizabeth
Emily, Daniel, Olivia, Elizabeth, Olivia
Mia, Sophia, Isabella, Isabella
Jayden, Elizabeth, Ava, Ava
Daniel, Olivia, Mia, Mia
Sophia, Isabella, Emily, Emily
Elizabeth, Ava, Abigail, Abigail
Olivia, Mia, Madison, Madison
Isabella, Emily, Elizabeth, Elizabeth

Codes I worked out so far is:
old_file = open_workbook('c:\\Book1.xls',formatting_info=True)
old_sheet = old_file.sheet_by_index(0)

new_file = xlwt.Workbook(encoding='utf-8', style_compression = 0)
new_sheet = new_file.add_sheet('Result', cell_overwrite_ok = True)

for row_index in range(0, old_sheet.nrows):
    column_con = old_sheet.cell(row_index, 0).value
    aaa = dict.fromkeys(column_con).keys()
    new_sheet.write(row_index, 0, aaa)

new_file.save('c:\\Book New 1.xls')

however when run, it removes all the duplicated letters, instead of the wanted words, and became:
a bEihM,oNmsyenIl
a diMmLo,sAvn
a cbEdihJM,ontye
a EDimM,onsyel
a bdgihM,onpsASl
a bEdihJM,onstyezl
a zEDihm,Olbtvyen
a bIihM,olpSes
a bedihJ,nAtvyEzl
a eDiMlOnv,
a bIihm,olpSyesE
a bEgihl,Atvez
a diM,Olsovn
a beIhml,istyEz

how can I have the duplicated names removed? Thanks.

A: dict.fromkeys() takes a sequence and not a string
Try this:
for row_index in range(0, old_sheet.nrows):
    column_con = old_sheet.cell(row_index, 0).value

    # First split into a list and convert to sequence
    column_con = tuple(column_con.split(', '))

    aaa = dict.fromkeys(column_con).keys()

    # Since aaa is a list of keys, you also need to join them in a string
    aaa = ', '.join(aaa)
    new_sheet.write(row_index, 0, aaa)

A: use set to store the data you read from excel
data=xlrd.open_workbook("C:\\Users\\I307658\\Desktop\\test.xlsx")
old_sheet = data.sheet_by_index(0)
new_file = xlwt.Workbook(encoding='utf-8', style_compression = 0)
new_sheet = new_file.add_sheet('Result', cell_overwrite_ok = True)

for row_index in range(0, old_sheet.nrows):
    column_con = old_sheet.cell(row_index, 0).value
    print column_con
    aaa =set(column_con.split(","))

    print ', '.join(aaa)
    new_sheet.write(row_index, 0, ', '.join(aaa))

new_file.save("C:\\Users\\I307658\\Desktop\\Book New 1.xls")


text:
Q: Help configuring JBoss MySQL datasource Okey so, im kind of new to JBoss. My problem is that i dont know how to properly create a mySQL datasource.This is what i´ve done so far:
1.) I created the mysql-ds.xml file and put it in the JBOSS/server/default/deploy folder
2.) I named the datasource DSE_MySQL
3.) I start jboss...
and im getting the following error:
    ERROR [AbstractKernelController] Error installing to Real: name=vfs:///C:/jboss-6.0.0.Final/server/default/deploy/mysql-ds.xml state=PreReal mode=Manual requiredState=Real: org.jboss.deployers.spi.DeploymentException: Error deploying: jboss.jca:service=ManagedConnectionFactory,name=DSE_MySQL
    at org.jboss.deployers.spi.DeploymentException.rethrowAsDeploymentException(DeploymentException.java:49) [:2.2.0.GA]
    at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:125) [:6.0.0.Final]
    at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:49) [:6.0.0.Final]
    at org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62) [:2.2.0.GA]
    at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:55) [:2.2.0.GA]
    at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:179) [:2.2.0.GA]
    at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1832) [:2.2.0.GA]
    at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1550) [:2.2.0.GA]
    at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1571) [:2.2.0.GA]
    at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1491) [:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:379) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:2044) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:1083) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractController.executeOrIncrementStateDirectly(AbstractController.java:1322) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1246) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1139) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:939) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:654) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.deployers.plugins.deployers.DeployersImpl.change(DeployersImpl.java:1983) [:2.2.0.GA]
    at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:1076) [:2.2.0.GA]
    at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:679) [:2.2.0.GA]
    at org.jboss.system.server.profileservice.deployers.MainDeployerPlugin.process(MainDeployerPlugin.java:106) [:6.0.0.Final]
    at org.jboss.profileservice.dependency.ProfileControllerContext$DelegateDeployer.process(ProfileControllerContext.java:143) [:0.2.2]
    at org.jboss.profileservice.dependency.ProfileDeployAction.deploy(ProfileDeployAction.java:151) [:0.2.2]
    at org.jboss.profileservice.dependency.ProfileDeployAction.installActionInternal(ProfileDeployAction.java:94) [:0.2.2]
    at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:54) [jboss-kernel.jar:2.2.0.GA]
    at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:42) [jboss-kernel.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:379) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:2044) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:1083) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractController.executeOrIncrementStateDirectly(AbstractController.java:1322) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1246) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1139) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:939) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:654) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.profileservice.dependency.ProfileActivationWrapper$BasicProfileActivation.start(ProfileActivationWrapper.java:190) [:0.2.2]
    at org.jboss.profileservice.dependency.ProfileActivationWrapper.start(ProfileActivationWrapper.java:87) [:0.2.2]
    at org.jboss.profileservice.dependency.ProfileActivationService.activateProfile(ProfileActivationService.java:215) [:0.2.2]
    at org.jboss.profileservice.dependency.ProfileActivationService.activate(ProfileActivationService.java:159) [:0.2.2]
    at org.jboss.profileservice.bootstrap.AbstractProfileServiceBootstrap.activate(AbstractProfileServiceBootstrap.java:112) [:0.2.2]
    at org.jboss.profileservice.resolver.BasicResolverFactory$ProfileResolverFacade.deploy(BasicResolverFactory.java:87) [:0.2.2]
    at org.jboss.profileservice.bootstrap.AbstractProfileServiceBootstrap.start(AbstractProfileServiceBootstrap.java:91) [:0.2.2]
    at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:132) [:6.0.0.Final]
    at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:56) [:6.0.0.Final]
    at org.jboss.bootstrap.impl.base.server.AbstractServer.startBootstraps(AbstractServer.java:827) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-5]
    at org.jboss.bootstrap.impl.base.server.AbstractServer$StartServerTask.run(AbstractServer.java:417) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-5]
    at java.lang.Thread.run(Unknown Source) [:1.6.0_22]
Caused by: java.lang.IllegalStateException: jboss.jca:name=DSE_MySQL,service=ManagedConnectionFactory is already installed.
    at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:835) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:641) [jboss-dependency.jar:2.2.0.GA]
    at org.jboss.system.ServiceController.doInstall(ServiceController.java:653) [:6.0.0.Final (Build SVNTag:JBoss_6.0.0.Final date: 20101228)]
    at org.jboss.system.ServiceController.install(ServiceController.java:256) [:6.0.0.Final (Build SVNTag:JBoss_6.0.0.Final date: 20101228)]
    at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:93) [:6.0.0.Final]

A: You might need to post your ds.xml. I hope you copied your ds.xml from the samples (that is packaged with most of the Jboss servers .. in samples folder).
I decided to answer because your problem looks simpler. It looks like that you  have  a duplicate ds.xml, with the same datasource defined or you have defined the same data source twice in your ds.xml.
In either case your datasource should have been defined anyways. So look for duplicates and also make sure that the datasource is already defined from Jboss JMX Console.


text:
Q: How to get specific instance of class from another class in Java? I've created the following class with the main method, which creates new instance of Application and instances of ApplicationModel, ApplicationView and ApplicationController for this particular Application.
public class Application
{

    // Variables

    private ApplicationSettings         settings;
    private ApplicationModel            model;
    private ApplicationView             view;
    private ApplicationController       controller;

    // Constructor

    public Application()
    {
        settings        = new ApplicationSettings();
        model           = new ApplicationModel();
        view            = new ApplicationView(model);
        controller      = new ApplicationController();
    }

    // Main method

    public static void main(String[] args)
    {
        Application application = new Application();
    }

    // Getters for settings, model, view, controller for instance of Application

}

I know, that there will always be only one unique instance of Application.
And I want to get this particular instance in my ApplicationModel, ApplicationView and ApplicationController classes.
How is it possible?

A: I would use a singleton on Application class.
Put a public static method to return your one and only application instance.
public class Application
{
    private Application() { } // make your constructor private, so the only war
                              // to access "application" is through singleton pattern

    private static Application _app;

    public static Application getSharedApplication()
    {
        if (_app == null)
            _app = new Application();
        return _app;
    }
}

You can read more about singleton design pattern here.
Every time you need the one and only Application instance, you do:
Application app = Application.getSharedApplication();

A: You want to use the Singleton design pattern if you need to guarantee there will only be one instance of Application and you need it to be accessible by those classes. I'm not going to comment on if it's the best way to build your application, but it will satisfy the requirements in your question.
Singleton design pattern tutorial

A: Change the constructor of your Application class to be private and send the this object to the ApplicationXxx classes.
private Application()
{
    settings        = new ApplicationSettings(this);
    model           = new ApplicationModel(this);
    view            = new ApplicationView(this, model);
    controller      = new ApplicationController(this);
}

You will be able to call new on the Application class from within the main method.
Your ApplicationSettings, ApplicationModel, ApplicationView and ApplicationController must be updated to take an Application object in their constructors.

A: Add parameter of the Application type to the constructors of the composites. When you create their instances just pass this. For example
public class Application {
  String s = "Setting";
  class ApplicationSettings {
    Application sc;
    ApplicationSettings(Application sc){
      this.sc = sc;
      System.out.println(sc.s);
    }
  }

  // Variables

  private ApplicationSettings settings;

  // Constructor

  public Application()
  {
    settings = new ApplicationSettings(this);
  }

  // Main method

  public static void main(String[] args)
  {
    Application application = new Application();

  }

  // Getters for settings, model, view, controller for instance of Application

}

A: I tried this right now, you can pass this as a constructor arg within the constructor of Application to other classes (assuming the have a reference declared for the main class). That way you can obviously make multiple instances of the Application class. If that is what you want...


text:
Q: How to configure amazon S3 bucket for read-only access to host a static website? I have a very small (static) website hosted on Amazon S3. Yesterday I received the following message, that had this subject line:

Notification of Amazon S3 buckets configured for public access

And the message had this this content (screenshot):

Hello,
We're writing to notify you that your AWS account XXXXXXX has one or
  more S3 buckets that allow read or write access from any user on the
  Internet. By default, S3 buckets allow only the account owner to
  access the contents of a bucket; however, customers can configure S3
  buckets to permit public access.
Unless you have a specific reason (such as hosting a public website)
  for this configuration, we recommend that you update your bucket and
  restrict public access. Your list of buckets configured to allow
  access by anyone on the Internet as of August 9, 2019 are:
ACCOUNT_XXXXXXXXXXXXXXXXXXX
If you did not intend to provide public access to this bucket then you
  should take immediate action by enabling S3 Block Public Access 1 on
  this bucket. This feature is free of charge and it only takes a minute
  to enable. For step by step instructions on setting up S3 Block Public
  Access via the S3 management console, see Jeff Barr's blog 2. Once
  you've locked down your bucket, we recommend checking for past
  unintended access to your bucket per the instructions below on
  analyzing logs.
For more information on S3 Block Public Access, check out the video
  tutorial on Amazon S3 Block Public Access 3. For AWS's definition of
  "Public Access," please see The Meaning of "Public" [4].

I logged in to my Amazon S3 account and tried to find a way to set up my files for the read-only access. Again, all it has to do is to allow anyone to download. That is it. (As I was obviously not aware of anyone being able to modify my files when I set it up. Allowing this by default would be kinda silly, don't you think?)
I was able to find these controls:

but I honestly got a raging headache trying to understand how to do that.
Can someone please explain how can I set up my files for read-only access?

EDIT: To reply to the answer below, the bucket policy is already set to this:

A: Click on Bucket Policy and make sure action as below.
"Action": "s3:GetObject",
Get Object means people can read only.


text:
Q: Appending images to an existing Excel file into a new sheet with Python I recently started with Python and I am appending the resulting data frame to an existing Excel file.
I want to do the same by appending a figure that I am generating earlier in the code to the same Excel file but on a different sheet.
plt.savefig('image.png', dpi = 1200, bbox_inches = 'tight')

writer = pd.ExcelWriter('output.xlsx', engine = 'openpyxl', mode = 'a', if_sheet_exists = 'replace')
df.to_excel(writer, sheet_name = 'Sheet', index = 'False')
writer.close()

Is it possible to efficiently add the data frame and image by opening the excel file only once?


text:
Q: iPhone just keeps offloading SoundCloud app even though it is used heavilly My question is related to peculiar behavior of my iPhone, as suggested in the title.
Offloading means deleting the app from the phone, however data remains, so after user installs it back from appstore, it just works in continuity from before the deletion of the app. Operating System on iOS allows automatic offloading of apps, which were not used much, to save memory/space.
Yes my iPhone is full, and I allowed offloading of unused apps. (and I really need this). ... it makes sense that iOS wants to offload some app, but why SounCloud? Many other apps are still present, untouched.
The strange thing is, that SoundCloud is probably the most used app on my phone, and it would be just too much, if it was offloaded/deleted even ones. Even that would not make sense. However, it just keeps be deleted over and over on regular basis. I have to reinstall the app in quite unexpected situations if I want listen to music again. Often in situations without strong data signal.
I didn't notice that there would be any other apps, which would be offloaded/deleted prematurely like this. It seems to me, that otherwise only apps which I did not use for a long time are targeted by the system and offloaded.
In the case of Soundcloud - I use it kind of at least for few hours a day. Often I can let it run from the morning to the night nonstop. Everyday! Still - after being in subway for an hour (not data signal - not using anything, or after watching YouTube for few hours - and bang! Souncloud is gone! Again! All that the system apparently needs to decide, that my SoundCloud is unused to delete it is few hours of me doing something else and it targets SounCloud preferentially and deletes it!
My question is actually double:
1) First, I just really want to stop offloading this particular application (while keeping the system decide what other app was not used lately and let it automatically offload that) .. if there exist any more specific setting allowing me to make an exception for an app, that I wish the particular app to not be offloaded, I would love to use it.
2) Second, I am just amused and curious, why that particular app might be targeted in the first place? Does not make sense at all! It even feels as if iOS is picking on SoundCloud or something. Any reasons?
I have iPhone SE and always with the latest OS (and behavior is the same regardless on the version of iOS). I have 32 GB of memory space and it is always close to be full. ... And I keep listening something on earphones non-stop, either music on SoundCloud, or some podcast or YouTube.
(I would suggest tags I cannot add: SoundCloud and Offloading)

A: I am actually using this 'Offload' feature for a long time and I took care of my apps about whether they are still ready to use...
But..
I have never seen the situation that you've faced. It's interesting for iPhone to execute Offload App command such an app which is in being used constantly.
My advice you to delete the app without offload and backup, directly erase the app, then install again and start from zero to use. I hope it DOES work in time!


text:
Q: Adding configurations to manually created startup.cs class in asp.net web api project I am new to asp.net and started with a web API project in visual studio. I would like to use these web APIs for an angular app. For that I will have to enable CORS and configure SignalR
In the ConfigureServices method, we are adding SignalR to the IService collection. And in a Configure
method, we are adding SignalR to the request pipeline by pointing to our ChartHub with the provided /chart path.

reference - "https://code-maze.com/netcore-signalr-angular/".
I don't have a Startup.cs file in my web API project, so I have added an OWIN startup class. This class has a Configuration method but not ConfigureService or Configure. I am confused on how to add enable CORS and SignalR in startup.cs. Can someone help me with how to add these configurations in startup.cs class?

A: You need to add Startup class in root of your project and marked it with OwinStartup attribute to indicate the class to be used for automatic setup.
Then you need to implement Configuration method where you can setup things like authentication, CORs, Signalr and many more.
You also can add Owin Startup Class via Add Item in Visual Studio. It will add basic setup to config for you. https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-startup-class-detection#create-an-aspnet-web-app-using-owin-startup
[assembly: OwinStartup(typeof(Example.Web.Startup))]
namespace Example.Web
{
    public class Startup
    {
        private static CorsOptions _corsOptions = new CorsOptions
        {
            PolicyProvider = new CorsPolicyProvider
            {
                PolicyResolver = context =>
                {
                    var policy = new CorsPolicy();
                    foreach (string domain in ConfigHelper.AllowedCorsDomains.Split(','))
                    {
                        policy.Origins.Add(domain);
                    }

                    policy.AllowAnyMethod = true;
                    policy.AllowAnyHeader = true;
                    policy.SupportsCredentials = true;
                    return Task.FromResult(policy);
                }
            }
        };

        public void Configuration(IAppBuilder app)
        {
            app.UseCors(_corsOptions);
            app.MapSignalR();

            AccessTokenFormat = new SecureDataFormat<AuthenticationTicket>(new TicketSerializer(), app.GetDataProtectionProvider().Create("ASP.Net Identity"), new Base64TextEncoder());

            OAuthBearerAuthenticationOptions = new OAuthBearerAuthenticationOptions()
            {
                AccessTokenFormat = AccessTokenFormat
            };

            if (provider != null)
            {
                OAuthBearerAuthenticationOptions.Provider = provider;
            }

            app.UseOAuthBearerAuthentication(OAuthBearerAuthenticationOptions);
        }
    }
}


text:
Q: What happens when an Azure Logic App is disabled? What happens when an Azure Logic App is disabled?
Does the current "run" finish, or is it terminated at whatever action is currently on?
In our case, we have a logic app that has a trigger on a message being added to a Service Bus queue ... the Logic App is doing a Peek/Lock read of the message
Various actions, including a SQL Db write, and finishing with a Service Bus complete on the message
If the current run finishes, then we don't have to worry, as that particular message has been "processed"
But if the current run is terminated wherever it is, Service Bus will return the message to the queue after the timeout, and then when the Logic App is re-enabled, we'd re-process the original message from the Service Bus queue

A: Current in flight runs will finish, but the trigger will stop checking for new events and invoking new runs. You can cancel runs to stop ones that are in progress, but currently is a separate gesture to just disable.


text:
Q: Track git changes in subfolders in VSCode I have a project that has a root git repository that have multiple subfolders that are also git repositories. My structure is like this:
/Project
/Project/module/libs
/Project/module/src
Every folder has a separate git repository, because libs and src are used from another projects.
In root project I have ignored the others libs and src, but I want them to be tracked from the VSCode (Web Storm does it).

A: You should try and clone the main project elsewhere, then try and add the Git repos libs and src as submodule (assuming that those repos are already pushed somewhere)
cd /path/to/Project
git submodule add /url/repo/libs module/libs
git submodule add /url/repo/src module/src

Then you can open Project in VSCode: it should track as well libs and src.
VSCode is still developing its Git submodule support, starting with PR 36313.

A: I'm 2 days new to vsCode (in 2021) and had the same problem during setup. I closed the Parent Workspace that was ignoring the nested repos and created a new workspace of the nested repos. VsCode started showing the changes like it did with the parent.  Then I saved the workspace and added the parent repo to the new repo with the nested repos and everything is now being tracked and displayed.


text:
Q: CocoaPod Pods-HockeySDK Archive Error: Could not build module 'UIKit' This issue is driving me nuts, since I updated to Xcode 5.1.1  The weird thing is that this only occurs on my machine.  On my co-worker's installation of Xcode, the project archives successfully.
The project compiles and run successfully on my device.
Obviously there must be a config setting that is different on our systems, but I'm at a loss at where to look at
I've already checked the following:

*

*Remove ARM64 from my build setting's ARCHS (necessary due to a static library out product's using)

*

*Removed (and re-addeed) UIKit.framework, as per this SO question

Here's my Podfile:
# Podfile

platform :ios, "6.1"
inhibit_all_warnings!

pod 'Reachability',  '~> 3.0'
pod 'KAProgressLabel', :git => 'https://github.com/Ranter/KAProgressLabel.git', :commit => '87f69fda798fd034fee1739f651d44761c37362b'
pod 'Facebook-iOS-SDK', '~> 3.14'
pod 'iToast', '~> 0.0'
pod 'AWSiOSSDK/S3'
pod 'AFNetworking', '~> 2.2'
pod 'AFNetworkActivityLogger', '~> 2.0'
pod 'CWPopup', '~> 1.2.4'
pod 'TheAmazingAudioEngine', '~> 1.3'
pod 'HockeySDK', '~> 3.5.0'
pod 'iCarousel', :git => 'https://github.com/nicklockwood/iCarousel.git', :commit => 'fc618c721fcb9a682317ff198590c3a775033487'

post_install do |installer_representation|
    installer_representation.project.targets.each do |target|
        # Fixes issue with some pods not supporting ARM64
        target.build_configurations.each do |config|
            config.build_settings['ONLY_ACTIVE_ARCH'] = 'NO'
        end

        # Rename conflicting kBufferSize symbol in TheAmazingAudioEngine
        if target.name == 'Pods-TheAmazingAudioEngine' then
            target.build_configurations.each do |config|
                # Only add to Debug flags since Release inherits from it
                if config.name == 'Debug' then
                    config.build_settings['OTHER_CFLAGS'] ||= []
                    config.build_settings['OTHER_CFLAGS'] << '-DkBufferSize=TAE_kBufferSize'
                end
            end
        end
    end
end

Thanks!


text:
Q: Java: Splitting .GIF image in BufferedImages Gives Malformed Images So I have a very small piece of code, which takes a .gif image as input, and then it splits this .gif image into an array of BufferedImage. After that, it stores the images in the array on the disk. When I do this, the output images contain heavy white-pixel noise which isn't visible in the input .gif image.
Example of the input gif:

Example of malformed output image (the 3rd frame in the gif):

The code I am using to split the gif is as follows:
public static void main(String[] args) throws Exception {
        splitGif(new File("C:\\test.gif"));
}

public static void splitGif(File file) throws IOException {
    ImageReader reader = ImageIO.getImageReadersBySuffix("gif").next();     reader.setInput(ImageIO.createImageInputStream(new FileInputStream(file)), false);
    for(int i = 0; i < reader.getNumImages(true); i++) {
        BufferedImage image = reader.read(i);
        ImageIO.write(image, "PNG", new File(i + ".png"));
    }
}

Can anyone help me out?

A: So the problem was that when reading .gif files into java, then all pixels in a given frame that did not change color compared to their previous frame will be fully transparent. If you want to read a .gif and split it in an array of properly rendered BufferedImages, then you have to fill the transparent pixels of the current frame with the last non-transparent pixel of one of the previous frames.
Code:
public static void splitGif(File file) throws IOException {
    ImageReader reader = ImageIO.getImageReadersBySuffix("gif").next();
    reader.setInput(ImageIO.createImageInputStream(new FileInputStream(file)), false);
    BufferedImage lastImage = reader.read(0);
    ImageIO.write(lastImage, "PNG", new File(0 + ".png"));

    for (int i = 1; i < reader.getNumImages(true); i++) {
        BufferedImage image = makeImageForIndex(reader, i, lastImage);
        ImageIO.write(image, "PNG", new File(i + ".png"));
    }
}

private static BufferedImage makeImageForIndex(ImageReader reader, int index, BufferedImage lastImage) throws IOException {
    BufferedImage image = reader.read(index);
    BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);

    if(lastImage != null) {
        newImage.getGraphics().drawImage(lastImage, 0, 0, null);
    }
    newImage.getGraphics().drawImage(image, 0, 0, null);

    return newImage;
}

A: You solved it yourself, but for good order: every next frame is the accumulation of all prior frames filling up the transparent pixels in the current frame.
public static void splitGif(File file) throws IOException {
    ImageReader reader = ImageIO.getImageReadersBySuffix("gif").next();
    reader.setInput(ImageIO.createImageInputStream(new FileInputStream(file)), false);
    BufferedImage outImage = null;
    Graphics2D g = null;
    for (int i = 0; i < reader.getNumImages(true); i++) {
         BufferedImage image = reader.read(i);
         if (g == null) {
             BufferedImage outImage = new BufferedImage(image.getWidth(), image.getHeight(),
                     BufferedImage.TYPE_4BYTE_ABGR);
             g = (Graphics2D) outImage.getGraphics();
         }
         g.drawImage(lastImage, 0, 0, null);
         ImageIO.write(outImage, "PNG", new File(i + ".png"));
     }
     if (g != null) {
         g.dispose();
     }
}

*

*getGraphics==createGraphics should be balanced be a dispose as documented.


text:
Q: Application that replaces the default windows authentication system I want to write an application, which will replace the default authentication system in windows ( username and password). The new system ask for one or more extra field along with username, password. And this data will be sent to a server like system connected in network. And if that system ( stores all the authentication data ) validates the info received, it will send "yes".
Then only the client side application pass the authentication and allow to login. Can you help in doing this using VC++. Thanks in advance for your valuable time.

A: The Novell NetWare Client for Windows XP/2000 provides a single, synchronized login to the Windows XP or Windows 2000 desktop and the NetWare network; users have to enter their names and passwords only once to access all the resources they are authorized to use.
So, it's possible to supplement the Windows login process.  Probably not very easy, but possible.
It would probably be cheaper to purchase Novell NetWare.


text:
Q: Sort array in Θ(n) complexity
Prove that an array A of size n can be sorted in Θ(n) when it has O(n) inversions.

I don't know exactly what this question is asking.  My best guess is that we use insertion sort on a presorted input and that way we can achieve Θ(n) complexity by sorting.  Is this what the question is asking me?

A: As a hint - the runtime of insertion sort is Θ(n + I), where n is the number of elements and I is the number of inversions in the array. What happens if you insertion sort the array, given that it only has O(n) inversions? What will the time complexity be?
Hope this helps!


text:
Q: Publish ASP.NET Core 1.1 to a Linux based App Service When I'm trying to publish using Web Deploy (Visual Studio 2017 for Windows) to a Linux app service hosted in Azure the following error occurs:
Could not connect to the remote computer ("my-linux-api.scm.azurewebsites.net") using the specified process ("Web Management Service") because the server did not respond. Make sure that the process ("Web Management Service") is started on the remote computer.  Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_COULD_NOT_CONNECT_TO_REMOTESVC.
The remote server returned an error: (405) Method Not Allowed.

The link in the error description seems to refer windows based hosts.
The service is up and running and responds to my request:

How can I fix that?

A: There is no Web Deploy on Linux. That's a Windows/IIS thing.
Push with git instead. The .scm. service (Kudu) knows how to handle the ASP.NET Core deployment on Linux.


text:
Q: Addition of Sum From different tables I already posted it as a different question, and I got the answer, but the answer itself has a flaw.
I have 4 different tables and each of them have two fields in common total_share and idea_user_id.
I want to get the sum of "SUM of total_share" from all the tables
Here's my query
SELECT SUM
        (
            ifnull(s.total_share, 0) +
            ifnull(r.total_share, 0) +
            ifnull(c.total_share, 0) +
            ifnull(p.total_share, 0)
        ) as total_sum
FROM idea_submitter_percentage s
left outer join idea_revisor_percentage r on r.idea_user_id = s.idea_user_id
left outer join idea_contributor_percentage c on c.idea_user_id = s.idea_user_id
left outer join idea_comparisor_percentage p on p.idea_user_id = s.idea_user_id
WHERE s.idea_user_id = 3

It works fine, but there are two issues:

*

*If idea_submitter_percentage doesn't have any tuples where idea_user_id=3, then it returns null, however if other tables have no entry it doesnt return null.

*If all of the tables don't have any tuple where idea_user_id=3, it returns null, however it should return 0.

A: The problem is that when doing a JOIN you expect one "master" table that has at least one result. In your case, that is not guaranteed. The way to solve your problem is to use the UNION statement:
SELECT idea_user_id, SUM(total_share) AS total_share
FROM (

    SELECT s.idea_user_id, s.total_share
    FROM idea_submitter_percentage s
    WHERE s.idea_user_id = 3

    UNION ALL

    SELECT r.idea_user_id, r.total_share
    FROM idea_revisor_percentage r
    WHERE r.idea_user_id = 3

    UNION ALL

    SELECT c.idea_user_id, c.total_share
    FROM idea_contributor_percentage c
    WHERE c.idea_user_id = 3

    UNION ALL

    SELECT p.idea_user_id, p.total_share
    FROM idea_comparisor_percentage p
    WHERE p.idea_user_id = 3
) a

A UNION will happily ignore tables that don't have any results. You can see that it works at this SQL Fiddle: http://sqlfiddle.com/#!2/4b048/8


text:
Q: R is a vector a 1 row matrix or 1 column matrix a <- c(1,2,3)
b <- c(2,4,6)

Then:
c = cbind(a,b)

In this case, I expect the result is a 1x6 matrix, but it turns out a 3x 2 matrix
d = rbind(a,b)

This turns out a 2x3 matrix. Why are the structures of a and b not consistent? What are the underlined rules here?

A: a and b are plain vectors (not arrays) and cbind treats plain vectors (and one dimensional arrays) as columns while rbind treats plain vectors (and one dimensional arrays) as rows.
If given 2 dimensional inputs then they do act in the way described in the question.
For example,
A13 <- matrix(1:3, 1)  # 1x3 matrix
B13 <- matrix(4:6, 1)  # 1x3 matrix

cbind(A13, B13)
##      [,1] [,2] [,3] [,4] [,5] [,6]
## [1,]    1    2    3    4    5    6

rbind(A13, B13)
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6

A31 <- matrix(1:3, 3)  # 3x1 matrix
B31 <- matrix(4:6, 3)  # 3x1 matrix

rbind(A31, B31)
##      [,1]
## [1,]    1
## [2,]    2
## [3,]    3
## [4,]    4
## [5,]    5
## [6,]    6

cbind(A31, B31)
##      [,1] [,2]
## [1,]    1    4
## [2,]    2    5
## [3,]    3    6


text:
Q: Pyodbc in Azure functions I'm trying to run locally Azure functions with some Python code. I want to use pyodbc to connect to the database. I'm getting the following error:
[2021-07-01T14:32:06.429Z] Worker failed to function id e64112a7-17de-4bd8-bb94-46ddfe91a75b.
[2021-07-01T14:32:06.429Z] Result: Failure
[2021-07-01T14:32:06.429Z] Exception: ImportError: dlopen(/Users/gonczor/trimmed/azure_functions/.venv/lib/python3.8/site-packages/pyodbc.cpython-38-darwin.so, 2): Library not loaded: /usr/local/opt/unixodbc/lib/libodbc.2.dylib
[2021-07-01T14:32:06.429Z]   Referenced from: /Users/gonczor/trimmed/azure_functions/.venv/lib/python3.8/site-packages/pyodbc.cpython-38-darwin.so
[2021-07-01T14:32:06.429Z]   Reason: image not found. Troubleshooting Guide: https://aka.ms/functions-modulenotfound
[2021-07-01T14:32:06.429Z] Stack:   File "/usr/local/Cellar/azure-functions-core-tools@3/3.0.3477/workers/python/3.8/OSX/X64/azure_functions_worker/dispatcher.py", line 302, in _handle__function_load_request
[2021-07-01T14:32:06.430Z]     func = loader.load_function(
[2021-07-01T14:32:06.430Z]   File "/usr/local/Cellar/azure-functions-core-tools@3/3.0.3477/workers/python/3.8/OSX/X64/azure_functions_worker/utils/wrappers.py", line 42, in call
[2021-07-01T14:32:06.430Z]     raise extend_exception_message(e, message)
[2021-07-01T14:32:06.430Z]   File "/usr/local/Cellar/azure-functions-core-tools@3/3.0.3477/workers/python/3.8/OSX/X64/azure_functions_worker/utils/wrappers.py", line 40, in call
[2021-07-01T14:32:06.430Z]     return func(*args, **kwargs)
[2021-07-01T14:32:06.430Z]   File "/usr/local/Cellar/azure-functions-core-tools@3/3.0.3477/workers/python/3.8/OSX/X64/azure_functions_worker/loader.py", line 83, in load_function
[2021-07-01T14:32:06.430Z]     mod = importlib.import_module(fullmodname)
[2021-07-01T14:32:06.430Z]   File "/usr/local/Cellar/python@3.8/3.8.10/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module
[2021-07-01T14:32:06.430Z]     return _bootstrap._gcd_import(name[level:], package, level)
[2021-07-01T14:32:06.430Z]   File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
[2021-07-01T14:32:06.430Z]   File "<frozen importlib._bootstrap>", line 991, in _find_and_load
[2021-07-01T14:32:06.430Z]   File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
[2021-07-01T14:32:06.430Z]   File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
[2021-07-01T14:32:06.430Z]   File "<frozen importlib._bootstrap_external>", line 848, in exec_module
[2021-07-01T14:32:06.430Z]   File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
[2021-07-01T14:32:06.430Z]   File "/Users/gonczor/trimmed/azure_functions/generate_report/__init__.py", line 2, in <module>
[2021-07-01T14:32:06.430Z]     from config import get_db_cursor
[2021-07-01T14:32:06.430Z]   File "/Users/gonczor/trimmed/azure_functions/config.py", line 3, in <module>
[2021-07-01T14:32:06.430Z]     import pyodbc
[2021-07-01T14:32:06.430Z] .

I have pyodbc listed in my requirements.txt file:
azure-functions==1.7.2
certifi==2021.5.30
chardet==4.0.0
idna==2.10
pyodbc==4.0.30
requests==2.25.1
urllib3==1.26.6

The troubleshooting guide on Microsoft's site mentions pyodbc in a context, where too many connections are made, but I'm only creating one of those. There's a config file in the project root:
import os

import pyodbc

def get_pyodbc_db_url() -> str:
    db_user = os.environ.get("DB_USER")
    db_password = os.environ.get("DB_PASSWORD")
    db_host = os.environ.get("DB_HOST")
    db_name = os.environ.get("DB_NAME")

    return 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + db_host + ';DATABASE=' + db_name + ';UID=' + db_user + ';PWD=' + db_password

def get_db_cursor() -> pyodbc.Cursor:
    # https://learn.microsoft.com/en-us/sql/connect/python/pyodbc/step-3-proof-of-concept-connecting-to-sql-using-pyodbc?view=sql-server-ver15
    connection = pyodbc.connect(get_pyodbc_db_url())
    return connection.cursor()

A: It turned out that I was missing drivers. Instructions for macos on how to install them can be found here.


text:
Q: Logarithms and big O notation Recall the equivalence:
$$m=2^k \implies k=log_2m$$
(a) Consider the sequence:
$a_1=1, a_{k+1}=2a_k$
what is the smallest k for which $a_k \geq n$? Your answer should be a function of n, and you can leave it in big-O notation.
(b) Consider the sequence:
$a_1=2, a_{k+1}=a_k^2$
what is the smallest k for which $a_k \geq n$? Your answer should be a function of n, and you can leave it in big-O notation.

i am totally confused about this question, can someone please walk me through this problem or give me a nudge in the right direction, (also where does the n come from?)

A: $n$ is just another variable.
This is really just a compound problem: you need to break it into parts and solve the parts.
For example, one part of the first problem could be

Find a formula for the general term of the sequence given by $a_1 = 1$, $a_{u+1}=2a_u$

(I changed the dummy variable because it doesn't matter, but it might help eliminate confusion between this part and the rest of the problem)
(I say 'could be', because this is just one approach to the problem)


text:
Q: Salvaged STM32 programming with ST-Link V2 clone I bought a ST-Link V2 clone to try and program a STM32 MCU that I salvaged from a hoverboard PCB (STM32F031C6T6). I've been having some difficulty getting it to work.
I downloaded STM32CubeIDE and set it to use OpenOCD for programming. The GDB server says the device ID is 0x00000000, which is why I'm guessing it says it can't recognize the device as STM32 family.
I have tried using hardware reset, and connected the clone programmer's reset pin to the MCU's reset pin, but the hardware reset does not trigger, I found this question and tried the hack to bridge the programmer's PB0 pin on the MCU, but I am still not getting a hardware reset.
Would it need a correct device ID before it triggers a reset?
I'm also unsure why the device ID reads as 0x00000000; I've read about corrupted flash but since I can't program the MCU, I can't rewrite the flash, or is there another way?
I don't think the chip is faulty, because other GDB console outputs seem to detect it correctly, and when I manually trigger a hardware reset by pulling the chip's reset pin low, then GDB shows the event on the terminal output.
I hope someone can help. Here is the GDB output:
Open On-Chip Debugger 0.12.0-rc1+dev-00061-g5e9b46d77 (2022-10-20-14:50)
[https://github.com/STMicroelectronics/OpenOCD]
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
Info : Listening on port 6666 for tcl connections
Info : Listening on port 4444 for telnet connections
Info : STLINK V2J40S7 (API v2) VID:PID 0483:3748
Info : Target voltage: 3.053435
Info : clock speed 4000 kHz
Info : stlink_dap_op_connect(connect)
Info : SWD DPIDR 0x0bb11477
Info : [STM32F031C6Tx.cpu] Cortex-M0 r0p0 processor detected
Info : [STM32F031C6Tx.cpu] target has 4 breakpoints, 2 watchpoints
Info : starting gdb server for STM32F031C6Tx.cpu on 3333
Info : Listening on port 3333 for gdb connections
Info : accepting 'gdb' connection on tcp/3333
Info : device id = 0x00000000
Warn : Cannot identify target as a STM32 family.
Error: auto_probe failed
Error: Connect failed. Consider setting up a gdb-attach event for the target to prepare target for GDB connect, or use 'gdb_memory_map disable'.
Error: attempted 'gdb' connection rejected
shutdown command invoked

This is the programmer:

It uses a STM32F103CBT6 MCU.
The target is interfaced using SWD at 3.3 V.
This is the MCU:

A: It turns out the MCU is not an STM32F031C6T6 as I (incorrectly) assumed. After finding another MCU from the same manufacturer, and searching for it's datasheet, I found that the manufacturer is called Mind Motion. I then looked for the manufacturer's datasheet for the MM32F031C6T6 chip, and found that the memory mappings are completely different from the STM32F031C6T6. I was unable to program or erase it using STM32CubeIDE and STM32CubeProgrammer, so I ended up using Keil uVision, because it has built-in support for the Mind Motion MCUs.
Using uVision, I was able to successfully erase and program the chip.
Software based reset also works correctly.


text:
Q: AngularJS - how to pass id to api from nested ng-repeat

{{ items.title }}

          <ion-slide-box show-pager="false" on-slide-changed="slideHasChanged($index)" class="padding">
            <ion-slide ng-repeat="ite in allvodsforcategory">

            </ion-slide>
          </ion-slide-box>

$http.get('http://api.com?user=' + $scope.apiusername + '&pass=' + $scope.apipassword + '&id=' . items.id).success(function(data) {
       $scope.allvodsforcategory = data.videos;
   });

$http.get('http://api.com?user=' + $scope.apiusername + '&pass=' + $scope.apipassword).success(function(data) {
        $scope.allcategories = data.categories;
    });

There is my code you can see the first ng-repeat on the ul item that is listing categories in side I want to list images no you can see the second ng-repeat on the ion-slide now I need to pass the items.id to the controller then put it into the url but I can not find a way to do that please help my all help is appreciated THANK YOU

A: If my understanding of your question is correct, I think that what you would have to do is create an isolate scope for your custom directive (ion-slide). This will allow you to pass the item id as an attribute. And it will be available to use in your controller. What I mean is:
    ...
        .directive(ionSlide, function(...) {
             return {
                 scope: {
                      itemId: '@',
                 },
                 .... // Other things
             };
        });

        // In your html you would then have
        ...
       <ion-slide item-id="{{item.id}}" ng-repeat="ite in allvodsforcategory">

                </ion-slide>
         ...

        // And in your controller,
        ...
        .controller(function($scope, ...){
            var id = $scope.itemId; // you have your id here.

            $http.get('http://api.com?user=' + $scope.apiusername + '&pass=' + $scope.apipassword + '&id=' id).success(function(data) {
       $scope.allvodsforcategory = data.videos;
     });
});

Hope this helps.


text:
Q: После сборки проекта картинки в формате webp перестают работать Когда запускаю проект локально все нормально работает, а после сборки и заливки на сервер перестает работать, вес картинки почему то намного меньше чем на самом деле и тип text-html
Для создания проекта использовал vue-cli 4


text:
Q: What is the portable way in CMake to determine the size of a file? I need to determine the number of bytes in an arbitrary file via a CMake script, but in a portable manner.
This file may be large, so reading it in with the file(READ...) command and counting the string length isn't optimal.
If I only had to run on MacOS and/or Linux I'd just use wc -c, which gives me exactly what I want. But the script needs to be Windows compatible assuming only the Windows toolchain. (I'm not very knowledgeable with Windows development.)
I expected this to be a common operation, but am not finding anything similar in the CMake Modules source (likely searching for the wrong thing), and it doesn't appear to be supported by andy of the cmake -E commands.
So I'm looking for either some clever way of getting this info with a single command, or a recommendation on what command(s) I could use in Windows and wrap around a if(WIN32) conditional.

A: Not sure if you're going to like this, but I think compiling and running a small C program and using its output would be the easiest way to do this. After all, what you need to do is pretty custom, but easy to do in C.
cmake_minimum_required(VERSION 2.8)
project(test)

try_run(RUN_RESULT COMPILE_RESULT ${CMAKE_CURRENT_BINARY_DIR}/bin
    ${CMAKE_CURRENT_SOURCE_DIR}/filesize.c
    RUN_OUTPUT_VARIABLE FILE_SIZE
    ARGS ${CMAKE_CURRENT_SOURCE_DIR}/bigfile)

if (NOT COMPILE_RESULT)
    message(FATAL_ERROR "Filesize failed to compile")
endif()

if (RUN_RESULT EQUAL 0)
    message(STATUS "Filesize ${FILE_SIZE}")
else()
    message(WARNING "Filesize failed")
endif()

And in filesize.c:
#include <stdio.h>
int main(int argc, const char *argv[])
{
        FILE *fp = fopen(argv[1], "rb");
        if (fp != NULL) {
                fseek(fp, 0, SEEK_END);
                printf("%d", ftell(fp));
                fclose(fp);
                return 0;
        }
        return 1;
}

COMPILE_RESULT is TRUE or FALSE. And if the file isn't found try_run returns an error (in RUN_RESULT). Otherwise cmake runs the program, which seeks to the end of the file and prints the size in bytes. The result is captured in the FILE_SIZE variable.
The only problem with this is that it won't work for cross-compilation, as try_run doesn't run anything in that case.

A: There is a CMake module called FileInformation which lets you obtain the size of a file in a portable way. It adds a new sub-command to CMake's built-in file command:
file (SIZE filename variable)

A: Well, for short files you can do:
function(get_file_size var filename)
    file(READ "${filename}" content HEX)
    string(LENGTH "${content}" content_length)
    math(EXPR content_length "${content_length} / 2")
    set(${var} ${content_length} PARENT_SCOPE)
endfunction()

get_file_size(len "main.c")
message(STATUS "len(main.c)=${len}")


text:
Q: Could not store streamed data in a file using Python I want to store the data in csv or excelsheet type of format. I am currently receiving the data at my serial port. But, I want to store few bytes from continuous stream bytes into my csv file. Below is my code I am working. I am new at python programming so I would appreciate your inputs.
import struct,serial,csv
ser = serial.Serial('COM3', 9600)
print("Connected to: " + ser.portstr)
ser.isOpen()
ser.write("\x7E\x00\x0F\x10\x01\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFE\x00\x00\x61\x92") #Send command to distant node
while 1:
    read_val = ser.read(300)
    str1=list(read_val)
    str2= #String value that match the address of node
    ''' Do some math to achieve parametric result from 'read_val'''

def csv_write():
    with open(tst.csv, "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    for line in data:
        writer.writerow(line)

if __name__ == "__main__":
    csv_writer()
    data = <list format result from math calculations,which is done on 'read_val'>

Although I am receiving continuous data but when I am unable to make csv file from calculated readings.


text:
Q: PHP Datetime Add to DateTime in While loop 30 times I need help,
i have a while loop with dates for one month from mysql.
i have calculated the difference between times.
now i must sum that all differences at the end.
i have tried a lot. is there any option to add all that differences without writing each day?
while($row = mysqli_fetch_assoc($sql)){  // <---- while loop makes round 30 times... 1 month long
    $usern = $row['title'];
    $arbeit = $row['description'];
    $start_com = $row['start']; // <--- DATETIME
    $end_com = $row['end']; // <----- DATETIME
    $shop = $row['category'];

            $time_from = strtotime( $start_com );
            $time_from = date("H:i", $time_from);
            $time_to = strtotime( $end_com );
            $time_to = date("H:i", $time_to);

    $dteStart = new DateTime($start_com);
    $dteEnd   = new DateTime($end_com);
    $dteDiff  = $dteStart->diff($dteEnd);

    $e = MyDateInterval::fromDateInterval($dteDiff);
    $e->add($dteDiff);      // ----- this not works

    echo '.$dteDiff->format("%H:%I").';

}
// echo $e->format("%H:%I:%S"); // ------- not working...
// <---- here i need sum of the datetimes diff ---->

$dteDiff must at the end the complete diff all times. Can anyone help me?

A: Assuming $e is a DateTime object your formatting is not correct for your dates.
Please see http://php.net/manual/en/function.date.php
I (capital i) is daylight saving time you should use i for minutes.
S (capital s) is English ordinal suffix for the day of the month, 2 characters such as 2nd, 1st, 5th you should use s for seconds.
So you would need to use $e->format('H:i:s') to display the formatted hours, minutes, and seconds. to output 14:30:54.

Simplified
Instead of attempting to add DateIntervals, it can be simplified by setting an initial date and a compare date to get the resulting difference from.
$initialDate = new DateTime;
$compareDate = clone $initialDate;
while($row = mysqli_fetch_assoc($sql)) {
    $start_com = $row['start']; // <--- DATETIME - PAST
    $end_com = $row['end']; // <----- DATETIME - FUTURE
    $startDate = DateTime::createFromFormat('Y-m-d H:i:s', $start_com);
    $endDate = DateTime::createFromFormat('Y-m-d H:i:s', $end_com);
    if ($startDate && $endDate) {
        $initialDate->add($startDate->diff($endDate));
    }
}
$sumDiff = $compareDate->diff($initialDate);
var_dump($sumDiff);

Outputs:
object(DateInterval)#6 (15) {
  ["y"]=>
  int(312)
  ["m"]=>
  int(3)
  ["d"]=>
  int(12)
  ["h"]=>
  int(19)
  ["i"]=>
  int(53)
  ["s"]=>
  int(50)
  //...
}

Example: http://ideone.com/v9bzLe