text:
Q: How to make filestream check for duplicate appends? So, I'm coding for a C++ program (well, actually a .dll plugin for RpgMaker 2003), and I have a code like this:
#include <DynRPG/DynRPG.h>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

std::map<std::string, std::string> configuration;

bool onStartup(char *pluginName) {
               // We load the configuration from the DynRPG.ini file here
               configuration = RPG::loadConfiguration(pluginName);
               return true; // Don't forget to return true so that the start of the game will continue!
}

bool onComment( const char* text,
                const RPG::ParsedCommentData*   parsedData,
                RPG::EventScriptLine*   nextScriptLine,
                RPG::EventScriptData*   scriptData,
                int     eventId,
                int     pageId,
                int     lineId,
                int*    nextLineId )
{
    std::string cmd = parsedData->command;
    std::string filecode;
    std::string scanfile;
    string FileName;

    if(!cmd.compare("file_string")) //new code
    {
        ofstream myfile;
        myfile.open ("dynstore.txt", ios::app);
        myfile << parsedData->parameters[0].text << "\n";
        myfile.close();
        return false;
    }
    if(!cmd.compare("store_file")) //new code
    {
        ofstream myfile;
        myfile.open ("dynstore.txt", ios::app);
        myfile << RPG::actors[parsedData->parameters[0].number]->name << "\n";
        myfile.close();
        return false;
    }
    if(!cmd.compare("load_file")) //new code
    {
        ifstream myfile;
        myfile.open ("dynstore.txt");
        if(myfile.good()) //this should skip if the file doesn't exist.
        {
            getline (myfile, filecode);
            RPG::actors[parsedData->parameters[0].number]->name = filecode;
        }
        myfile.close();
        return false;
    }

    //These first three allow only storage using dynstore.

    if(!cmd.compare("create_file")) //custom file name, plus storing text
    {
        FileName = parsedData->parameters[0].text;
        ofstream myfile;
        myfile.open (FileName.c_str(), ios::app);
        myfile << parsedData->parameters[1].text << "\n";
        myfile.close();
        return false;
    }
    //This stores a word and makes a new line

    if(!cmd.compare("create_save")) //custom file name, plus storing text
    {
        int GameFile = RPG::variables[3351];

        ofstream myfile;
        if(GameFile == 0)
        {
            FileName = parsedData->parameters[0].text;
            myfile.open (FileName.c_str(), ios::app);
        }
        if(GameFile == 1)
        {
            myfile.open ("Save01.txt", ios::app);
        }
        if(GameFile == 2)
        {
            myfile.open ("Save02.txt", ios::app);
        }
        if(GameFile == 3)
        {
            myfile.open ("Save03.txt", ios::app);
        }
        if(GameFile == 4)
        {
            myfile.open ("Save04.txt", ios::app);
        }
        if(GameFile == 5)
        {
            myfile.open ("Save05.txt", ios::app);
        }
        if(GameFile == 6)
        {
            myfile.open ("Save06.txt", ios::app);
        }
        myfile << parsedData->parameters[1].text << "\n";
        myfile.close();
        return false;
    }
    //This stores a word and makes a new line

    if(!cmd.compare("make_file")) //custom file name, plus storing text
    {
        FileName = parsedData->parameters[0].text;
        ofstream myfile;
        myfile.open (FileName.c_str(), ios::app);
        myfile << RPG::actors[parsedData->parameters[1].number]->name;
        myfile.close();
        return false;
    }
    //This stores a name

    if(!cmd.compare("read_file")) //sets data info to name for easy read
    {
        FileName = parsedData->parameters[0].text;
        ifstream myfile;
        myfile.open (FileName.c_str());
        if(myfile.good()) //this should skip if the file doesn't exist.
        {
            getline (myfile, filecode);
            RPG::actors[parsedData->parameters[1].number]->name = filecode;
        }
        myfile.close();
        return false;
    }
    if(!cmd.compare("clear_file")) //sets data info to name for easy read
    {
        FileName = parsedData->parameters[0].text;
        ofstream myfile;
        myfile.open (FileName.c_str());
        myfile.clear();
        myfile.close();
        return false;
    }

     if(!cmd.compare("scan_save"))
    {
        //Attempt ONE to scan the file for a string
        //this one works by turning on a switch if the string is found

        int GameFile = RPG::variables[3351];

        ifstream myfile;
        if(GameFile == 0)
        {
            FileName = parsedData->parameters[0].text;
            myfile.open (FileName.c_str());
        }
        if(GameFile == 1)
        {
            myfile.open ("Save01.txt");
        }
        if(GameFile == 2)
        {
            myfile.open ("Save02.txt");
        }
        if(GameFile == 3)
        {
            myfile.open ("Save03.txt");
        }
        if(GameFile == 4)
        {
            myfile.open ("Save04.txt");
        }
        if(GameFile == 5)
        {
            myfile.open ("Save05.txt");
        }
        if(GameFile == 6)
        {
            myfile.open ("Save06.txt");
        }
        scanfile = parsedData->parameters[1].text;
        int switchnum = parsedData->parameters[2].number;

        if(myfile.good()) //this should skip if the file doesn't exist.
        {
             for(std::string temp;!myfile.eof();std::getline(myfile,temp))
             {
                 if(temp.find(scanfile)!=std::string::npos)
                 {
                     RPG::switches[switchnum] = true;
                //Turns on the switch if the string has been found in the file
                //ideally, I'd want to save a new name using the scanfile, but I can't figure out how to copy it
                 }
             }
        }
        myfile.close();
        return false;
    } //This checks only the current save, defaulting to the input if none exists

    if(!cmd.compare("scan_file"))
    {
        //Attempt ONE to scan the file for a string
        //this one works by turning on a switch if the string is found
        FileName = parsedData->parameters[0].text;
        ifstream myfile;
        myfile.open (FileName.c_str());
        scanfile = parsedData->parameters[1].text;
        int switchnum = parsedData->parameters[2].number;

        if(myfile.good()) //this should skip if the file doesn't exist.
        {
             for(std::string temp;!myfile.eof();std::getline(myfile,temp))
             {
                 if(temp.find(scanfile)!=std::string::npos)
                 {
                     RPG::switches[switchnum] = true;
                //Turns on the switch if the string has been found in the file
                //ideally, I'd want to save a new name using the scanfile, but I can't figure out how to copy it
                 }
             }
        }
        myfile.close();
        return false;
    }

    if(!cmd.compare("file_good"))
    {
        //Checks for the existence of a file.
        FileName = parsedData->parameters[0].text;
        ifstream myfile;
        myfile.open (FileName.c_str());
        int switchnum = parsedData->parameters[1].number;

        if(myfile.good()) //this should skip if the file doesn't exist.
        {
             RPG::switches[switchnum] = true;
        }

        else
        {
            RPG::switches[switchnum] = false;
        }

        myfile.close();
        return false;
    }

    //End of cmd
    return true;
}

Generally, this is how the .dll plugin works: It runs the DynRPG headers through the linker settings, and the RPG_RT.exe of RpgMaker as its host arguments. onStartup and onComment are DynRPG-specific codes to run compatibly with RpgMaker. You don't need to know most of this, except to know that these  if(!cmd.compare(" ")) codes basically are commands for RpgMaker. So, I am telling various files to open text files, but I've been having problems:

*

*I have a code to clear file, and it does clear the file. But I think
it creates the file in order to clear it, rather than skipping over
if it doesn't exist. In fact, I think this is a persistent issue, I
dunno how to get the code to skip over nonexistent file names, so it
makes new files if the code checks files.

*If possible, that clear file should actually delete the files rather
than just making it blank.

*It appends information into the file I make (and there doesn't seem
to be any memory leak), but it doesn't check to make sure that I
haven't already entered the same word or phrase. When I'm writing
into the file, I want to check  But I think I only know how to check
output when loading output, not before input. I want to avoid
duplicates. Currently, I have a file called "awards.txt" (unlockable
awards) and I have the file with like 6 instances of the same word.
I want it to write the same code only once. This is my main problem.

Don't give obtuse advice, assuming I will understand what you mean. Show me actual code. I barely pieced together this much code from reading and adapting other tutorials, and I do not have a degree in computer science (I was a history major, so the theory of C++ code doesn't always make sense to me). Oh and uhhhh, not all the header files are necessary, I tend to include more than I need just in case.

A: Point 1
In
    if(!cmd.compare("clear_file")) //sets data info to name for easy read
    {
        FileName = parsedData->parameters[0].text;
        ofstream myfile;
        myfile.open (FileName.c_str());
        myfile.clear();
        myfile.close();
        return false;
    }

the default file open mode used in myfile.open (FileName.c_str()); will create an empty file, overwriting an exiting file. Cool. Empty file is what you wanted, but yeah, it created an empty file where none existed. To avoid that, you'd need to specify an open mode that won't create a new file. Using this groovy table here, specifying the in open mode will raise an error if the file doesn't exit rather than opening it. Unfortunately if you keep reading you'll find there is no combination of openmodes that will truncate (clear) a file without also creating a new file.
Well doesn't that suck?
In C++17 we can use the <filesystem> Library's resize_file function.
std::error_code code;
std::filesystem::resize_file(FileName, 0, code);
// test code here if you care. Someone else could have the file open and prevent clearing.

Before C++17, its easiest to use system-specific API calls. You mention DLL above, so I'm going to assume a Windows target
HANDLE h = CreateFileA(FileName.c_str(),
                       GENERIC_WRITE,
                       0,
                       NULL,
                       TRUNCATE_EXISTING,
                       FILE_ATTRIBUTE_NORMAL,
                       NULL);
if (h != INVALID_HANDLE_VALUE)
{
    CloseHandle(h);
}

Documentation on CreateFileA. Note I use CreateFileA and not CreateFileW or CreateFile because FileName doesn't contain wide characters.
There might be a more direct call. I'm not really that familiar with the Win132 API.
A POSIX compliant target like Linux  (Maybe Mac. I know even less about Macs) uses truncate
int code = truncate(FileName.c_str(), 0);
// test code here and look at errno if you care. Someone else could have the file open.

If you're lucky the compiler developers ported truncate to Windows for you and simplify your job because you only have to support one target.
Side note
Because the openmode was what's actually clearing the file, we should take a look at what myfile.clear(); does: clears error flags on a stream. Normally when a stream operation fails error flags are set so you can check to see what went wrong. When any error flags are set, the stream refuses to process any further transactions and instantly returns. It's on you-the-programmer to check the state of the stream after every transaction to ensure that it worked because if it didn't and you don't check, you'll never know. The stream state and error flags are the ONLY warning you get.
So, you check the flags, handle the flagged error, and then call clear to signal you've resolved the issue and are ready to get back to reading and writing. Note: Sometimes handling the error requires you to clear the flag early in order to remove, read out, bad data so that the program doesn't immediately find the same garbage and fail again once you return to the regular flow of the code.
Point 2
Deleting a file... Now that's easier. In C++17
std::error_code code;
std::filesystem::remove("test", code);
// Wrap in an if and test code if you care about failure. I would.
// If it's file not found, cool!

And in the old world,
if (remove(FileName.c_str()) !=)
{
    //check errno to find out why
}

Documentation for std::filesystem::remove
Documentation for remove
Point 3
I just saw the time and I need to stop. You should remove point three from the question since it is a completely different issue and deserves its own question.


text:
Q: Command line XML validator that doesn't read the whole XML file into memory? I have an XML file that's 6.7GB compressed. I want to check this is valid XML from the command line. I tried using xmlstarlet and xmllint but the both balloned in memory.
Is there some sort of stream  XML validator for linux I can run on the command line?

A: Did you try xmllint --stream?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to redirect to URL using SPRING BeanNameViewResolver Is it possible to redirect to another URL inside Spring MVC controller while using BeanNameViewResolver?
Perhaps in a way just escaping the bean name resolving?
This obviously only works with the UrlBasedViewResolver
@RequestMapping(value = "/**", method = RequestMethod.GET)
public ModelAndView postPage(HttpServletRequest req){
    return "redirect:http://localhost:9090/flowID";
}

A: Found the Answer
    @RequestMapping(value = "/**", method = RequestMethod.GET)
public View postPage(HttpServletRequest req, Map<String, Object> model){
    RedirectView redirectView = new RedirectView("http://localhost:9090/flowID");
    return redirectView;
}


text:
Q: reactjs pagination with json data from mongodb Am trying to implement pagination in reactjs with JSON data from mongodb. But pages is not navigating as per the records available.
Below points are working :
Pagination buttons has been available.
Am able to click and change the button from the pagination navbar.
Below point are not working :
Tables records are not changing as the the pagination navbar button click.
Please find the code below.
class SearchResults extends React.Component {
constructor(props) {
super(props);
this.state = {  };
this.handlePageChange=this.handlePageChange.bind(this);
}

getNumPages(currentPage) {
{ this.handlePageChange }
this.setState({ per_page: this.props.results , currentPage: currentPage + 1 , previousPage: currentPage - 1  } );
}

handlePageChange(page, evt) {
const currentPage = this.state.currentPage || 1;
const numPages = this.getNumPages();
const pageLinks = [];
if (currentPage > 1) {
if (currentPage > 2) {
pageLinks.push(1);
pageLinks.push(' ');
}
pageLinks.push(currentPage - 1);
pageLinks.push(' ');
}
for (let i = 1; i <= numPages; i++) {
const page = i;
pageLinks.push(page);
}
if (currentPage < numPages) {
pageLinks.push(' ');
pageLinks.push(currentPage + 1);
if (currentPage < numPages - 1) {
pageLinks.push(' ');
pageLinks.push(numPages);
}
}
this.setState({ currentPage: currentPage + 1  } );
this.setState({ previousPage: currentPage - 1  } );
}

render() {
const per_page = "10";
const paginationData = this.props.results;
let numPages = Math.ceil(paginationData.length / per_page);
if (paginationData.length % per_page > 0) {
numPages++;
}
return (

ORDERS LIST

Customer Name
Assignee
Status
Creation Date

<SearchResultsList items={ this.props.results } open={ this.props.open } />

<Pagination id="content" className="users-pagination pull-right" bsSize="medium"
first last  next  prev  boundaryLinks items={numPages}
activePage={ this.state.currentPage } onSelect={ this.handlePageChange } />

);
}
}

class SearchResultsList extends React.Component {
constructor(props) {
super(props);
this.state = { };
}

render() {
const per_page=10;
let currentPage=8;
let start_count =0;
return (
{ this.props.items
.sort((a, b) => moment(b.order_date) - moment(a.order_date) || b.order_number - a.order_number)
.map((item, index) => <SearchResultsItem key={ item.id } item={ item } open={ this.props.open }  />
)
}
);
}
}

A: Finally it got working for me. Please find Pagination working code.
class SearchResults extends React.Component {
constructor(props) {
super(props);
this.state = {  };
this.handlePageChange=this.handlePageChange.bind(this);
}

getNumPages(currentPage) {
{ this.handlePageChange }
this.setState({ per_page: this.props.results , currentPage: currentPage + 1 , previousPage: currentPage - 1  } );
}

handlePageChange(page, evt) {
const currentPage = this.state.currentPage || 1;
const numPages = this.getNumPages();
const pageLinks = [];
if (currentPage > 1) {
if (currentPage > 2) {
pageLinks.push(1);
pageLinks.push(' ');
}
pageLinks.push(currentPage - 1);
pageLinks.push(' ');
}
for (let i = 1; i <= numPages; i++) {
const page = i;
pageLinks.push(page);
}
if (currentPage < numPages) {
pageLinks.push(' ');
pageLinks.push(currentPage + 1);
if (currentPage < numPages - 1) {
pageLinks.push(' ');
pageLinks.push(numPages);
}
}
this.setState({ currentPage: currentPage + 1  } );
this.setState({ previousPage: currentPage - 1  } );
}

render() {
    const per_page = "10";
const paginationData = this.props.results;
let numPages = Math.ceil(paginationData.length / per_page);
if (paginationData.length % per_page > 0) {
numPages++;
}
return (

ORDERS LIST

Customer Name
Assignee
Status
Creation Date

<SearchResultsList items={ this.props.results } open={ this.props.open } current_Page={ this.state.currentPage }  />

<Pagination id="content" className="users-pagination pull-right" bsSize="medium"
first last  next  prev  boundaryLinks items={numPages}
activePage={ this.state.currentPage } onSelect={ this.handlePageChange } />

);
}
}

class SearchResultsList extends React.Component {
constructor(props) {
super(props);
this.state = { };
}

    render() {

const per_page=10;
const pages = Math.ceil(this.props.items.length / per_page);
const current_page = this.props.current_Page || 1 ;
const start_offset = (current_page - 1) * per_page;
let start_count =0;
return (
{ this.props.items
.sort((a, b) => moment(b.order_date) - moment(a.order_date) || b.order_number - a.order_number)
.map((item, index) => {
if (index >= start_offset && start_count < per_page) {
start_count++;
return <SearchResultsItem key={item.id} item={item} open={this.props.open} />;
}
})
}

);
}
}


text:
Q: Gitlab backup to S3 bucket I have started backing up my Gitlab data to AWS S3 bucket as per instruction(https://docs.gitlab.com/ee/raketasks/backup_restore.html). As of now it is working fine but I'm unable to move this data automatically to sub folder in S3 bucket(like s3://my_gitlab_bucket_backup/NewFolder)
Currently, I performed following changes to move the backup to root folder in bucket.
gitlab_rails['manage_backup_path'] = true
 gitlab_rails['backup_path'] = "/var/opt/gitlab/backups"
 gitlab_rails['backup_archive_permissions'] = 0644 # See: http://doc.gitlab.com/ce/raketasks/backup_restore.html#backup-archive-permissions
 gitlab_rails['backup_pg_schema'] = 'public'
 gitlab_rails['backup_keep_time'] = 604800
 gitlab_rails['backup_upload_connection'] = {
   'provider' => 'AWS',
   'region' => 'us-east-1',
   'aws_access_key_id' => 'ABCDEF',
   'aws_secret_access_key' => 'XYZAL'
 }
 gitlab_rails['backup_upload_remote_directory'] = 'my_gitlab_bucket_backup'

Any help to move this backup to sub-folder in bucket will be highly appreciated

A: Given that the configuration above works, and my_gitlab_bucket_backup has the backups deposited into the root folder of your bucket. If you want to place subsequent backups into your_folder (a path/folder at the root of your bucket), you can try to use a new feature by setting DIRECTORY= on your backup rake task as noted here.
e.g. sudo gitlab-rake gitlab:backup:create DIRECTORY=your_folder
If you are asking for a feature that will move the older backup files into this folder, I do not believe that exists.


text:
Q: Debugging Issues using iOS Web Inspector I have a web application project which is built using asp.net mvc. It is built with custom views for mobile devices and combines a combination of knockout and razor bindings. The app started crashing when iOS upgraded to version 11.3.1 on one specific page. The error is specific to that iOS version  11.3.1 on mobile. On any Android device or desktop , including Safari, it works. On any older version of iOS it works also. In order to debug and recreate the error I want to view the console logs in developer tools . To do that I connected the mobile  device to desktop Mac and used the Mac web inspector tools.
But here is the catch. As soon as I connected to desktop Web Inspector and ran the page again, the page worked on my mobile device. As soon as I disconnected , it stopped working again. It is as though the connection of the mobile device  to the desktop's Web Inspector altered the running of the page on my mobile device.
Is there any way to prevent the Web Inspector in Safari interfering with the  actual operation of a page on a mobile device?
Alternatively , is there any alternative method anyone would have to debug the latest iOS version?  (I researched existing emulators such as browserstack , however they do not support the latest iOS version)


text:
Q: What's the equalivent of SAS function INTNX in Teradata? I have a Proc SQL code from SAS which I want to convert to a Teradata readable code to create a new table view. The code has an intnx function command to join two date fields to find the day value and then subtracted by a month renewal date field to get the final value. The issue I am having is figuring how to convert the code into Teradata layman terms in order to pull the data.
Here is the code:
INTNX CODE
MTURE_RNW_DT  OPEN_RNW_DT   BNK_TRM_IN_MTH_VAL
9/8/2005       9/8/2004     12
3/11/2013      9/11/2011    18
11/20/2014     5/20/2014    6
10/20/2013     1/26/2012    21
12/11/2011    12/10/2008    36
3/23/2015      3/22/2012    36
5/4/2010        3/5/2010    2
8/21/2012      1/29/2011    18
5/4/2014       4/27/2012    24


text:
Q: Using fxml with jruby I've seen how to write raw JavaFX code in Java, how to write FXML code in Java, how to write raw JavaFX code in JRuby, but can't seem to find anything on using FXML with JRuby. Is it currently possible to use FXML with JRuby? If so, are there any nice tutorials?
UPDATE: JRubyFX 0.9.1 and later have FXML support

A: It is possible to use fxml with jruby.
I couldn't find any tutorials for this so I wrote my first Ruby program.  The program demonstrates using fxml with jruby.  It is a conversion of an earlier demonstration I wrote to demonstrate using fxml with java.
Output of the ruby version of the program:


text:
Q: How do I use a compass-generated sprite for generated content? Is it possible to use a compass-generated sprite to replace the icon path below?
a:before {
  content: url(/pathto/icon.png);
}
Although I can work out how to get the sprite path in there, I don't know if it's possible to get the correct bit of the sprite showing.

A: Don't load the sprite map as "content". Set content to " ", load the sprite as a background, and control it the way you would with any other text/image-replacement sprite.
a:before {
  @include <map>-sprite(<icon>);
  @include sprite-dimensions(<map>, <icon>);
  content: " ";
}

Where <map> and <icon> are replaced by your specific sprite-map and icon names.


text:
Q: Can't get intellisense on angular-cli.json file All help online I have found so far shows people who properly have intellisense(autocomplete) in the angular-cli.json file in order to reference resources.
I can't understand why I always get "No suggestions." when I press "ctrl+space".
I have all the following extensions installed in the Visual Studio Code.
Any direction is appreciated:

A: I found the solution by installing this Extension:

A: This should be fine with the latest version of Angular-Cli. Anyhow you can refer the related issue from the  Autocomplete No Longer Works With Angular 6


text:
Q: Conditional Include not working with Entityt Framework 5 I'm trying to use the Conditional Include (explained here, but it's not retrieving the child information. Why? I think I've followed all the steps...
I'm using WebApi controllers and Visual Studio 2012
I've alread checked and I have doorTypes assigned to each house. It's a many to many relationship.
I have this:
DoorType has this property
public virtual ICollection<House> Houses{ get; set; }

House has this property
public virtual ICollection<Door> DoorTypes{ get; set; }

And I'm querying this method
public IEnumerable<House> GetList(string latitude, string longitude, string idHousesTypeList)
{
    IEnumerable<int> intIds = null;

    if (!string.IsNullOrEmpty(idHousesTypeList))
    {
        var ids = idHousesTypeList.Split(',');
        intIds = ids.Select(int.Parse);
    }

    var location = DbGeography.FromText(string.Format("POINT ({0} {1})", latitude, longitude), 4326);
    var count = 0;
    var radius = 0.0;
    IEnumerable<House> houses = null;

    while (count < 5 && radius < 500)
    {
        radius += 2.5;
        var radiusLocal = radius;

        var dbquery =
            from house in Uow.Houses.GetAll()
            where house.Location.Distance(location) / 1000 <= radiusLocal
            orderby house.Location.Distance(location)
            select new
            {
                house,
                doorTypes= from doorType in house.DoorTypes
                                where intIds.Contains(doorType.Id)
                                select doorType
            };

        houses = dbquery
        .AsEnumerable()
        .Select(p => p.house);

        count = houses.Count();
    }

    if (houses != null && houses.Any())
    {
        return houses;
    }

    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}

I'm using generic EFRepository
public class EFRepository<T> : IRepository<T> where T : class
{
    public EFRepository(DbContext dbContext)
    {
        if (dbContext == null)
            throw new ArgumentNullException("dbContext");
        DbContext = dbContext;
        DbSet = DbContext.Set<T>();
    }

    protected DbContext DbContext { get; set; }

    protected DbSet<T> DbSet { get; set; }

    public virtual IQueryable<T> GetAll()
    {
        return DbSet;
    }

    public virtual IQueryable<T> GetAllIncluding(params Expression<Func<T, object>>[] includeProperties)
    {
        IQueryable<T> query = DbContext.Set<T>();
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }

        return query;
    }

    public virtual T GetById(long id)
    {
        return DbSet.Find(id);
    }

    public virtual IQueryable<T> GetByPredicate(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
    {
        IQueryable<T> query = DbContext.Set<T>().Where(predicate);
        return query;
    }

    public virtual IQueryable<T> GetByPredicateIncluding(System.Linq.Expressions.Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includeProperties)
    {
        IQueryable<T> query = DbContext.Set<T>().Where(predicate);
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }

        return query;
    }

    public virtual void Upsert(T entity, Func<T, bool> insertExpression)
    {
        if (insertExpression.Invoke(entity))
        {
            Add(entity);
        }
        else
        {
            Update(entity);
        }
    }

    public virtual void Add(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State != EntityState.Detached)
        {
            dbEntityEntry.State = EntityState.Added;
        }
        else
        {
            DbSet.Add(entity);
        }
    }

    public virtual void Update(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State == EntityState.Detached)
        {
            DbSet.Attach(entity);
        }
        dbEntityEntry.State = EntityState.Modified;
    }

    public virtual void Delete(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State != EntityState.Deleted)
        {
            dbEntityEntry.State = EntityState.Deleted;
        }
        else
        {
            DbSet.Attach(entity);
            DbSet.Remove(entity);
        }
    }

    public virtual void Delete(int id)
    {
        var entity = GetById(id);
        if (entity == null) return; // not found; assume already deleted.
        Delete(entity);
    }
}

The output shows all the houses correctly but the array of doorTypes is empty.
What am I missing?

A:
It's a many to many relationship.

That's the problem. Relationship Fixup does not work for many-to-many relationships, only for one-to-one or one-to-many relationships.
You need to build up the navigation property manually after the query is executed. But you can do it relatively simple in this case:
houses = dbquery
    .AsEnumerable()
    .Select(p => {
        p.house.DoorTypes = p.doorTypes;
        return p.house;
    });

It is the same reason why explicit loading of navigation collections into the context does not work for many-to-many relationships, see this question: EF 4.1 loading filtered child collections not working for many-to-many and the answer to it, especially the reference to  Zeeshan Hirani's explanation about relationship fixup for a deeper background about the subject.

A: It's not clear how your Uow.Houses.GetAll() implemented, but try to include DoorTypes into result, when you are getting all houses from context:
return context.Houses.Include("DoorTypes");

And make sure you are passing idHousesTypeLis with existing ids.
UPDATE: Include is a member of DbQuery. It becomes unavailable when you cast Set to IQueriable<T>. So, try this:
public class HouseRepository : EFRepository<House>
{
    public override IQueryable<House> GetAll()
    {
        return DbContext.Set<House>().Include("DoorTypes");
    }
}


text:
Q: RecordFuture future.get() did not return (seldom) I run a KaaClient on intel edison with temperature sensor, and updating the temperature onto KaaServer, but sometimes when I start or resume the client, it will hang on
RecordInfo recordInfo = future.get();
After investigating log, I was wondering if it is becuase that I sent the information to server[2] between those logs[1][3]:
[1] [pool-68-thread-1]INFO o.k.k.c.c.i.DefaultOperationDataProcessor - Created Sync request: {"requestId": 1, "syncRequestMetaData": ,...
[2] [Thread-47] INFO  c.i.i.k.e.k.KaaModbusComponent-[readTemperature] sent log record to server
[3] [pool-68-thread-1] INFO  o.k.k.c.c.i.c.DefaultOperationTcpChannel - ConnAck (ACCEPTED) message received for channel [default_operation_tcp_channel]
...
In the above sequence, [1][2][3], it will always hang on future.get();
In other sequences, such as [2][1][3] or [1][3][2], it works.
Could some expert help if it is caused by this? if yes, please help guide me what's the good way to resolve this. thanks.


text:
Q: Orthographic projection matrix I'm trying to find the matrix of a generic orthographic projection onto a given plane $A$ that passes at the origin and the n-vector as the normal vector to the plane.
I only found matrices related to clipping planes, can anyone give me a general matrix for the case described above ?
Thanks.

A: The operation "project onto the (hyper)plane $A$" can be done as follows:
$$\pi(x) = x-(v\cdot x)v$$
where $v$ is one of the two unit normal vectors to $A$. This operation is linear, and thus it has an expression as a matrix. In fact:
$$\pi(x)_i = x_i - v_jx_jv_i$$
(with summation over repeated indices) and thus we see that the matrix corresponding to the projection $\pi$ is:
$$P_{ij}=\delta_{ij}-v_iv_j$$
or:
$$P = 1-vv^T$$

A: First find a basis of $\mathbb{R}^3$ given by vectors $v_1,v_2,n$ so that $v_1\perp n$ and $v_2\perp n$. Then the change of basis matrix is given by the matrix with column vectors $v_1,v_2,$ and $n$, $A=(v_1,v_2,n)$. Once in this basis, the projection matrix is
$$ P=\begin{pmatrix}1&0&0\\0&1&0\\0&0&0\end{pmatrix}$$
Now change back to the standard basis. That is, the projection matrix is $A^{-1}PA$.


text:
Q: Regarding the proof that similar matrices have the same characteristic polynomial The proof is:
$$|\lambda I-P^{-1}AP|=|P^{-1}(\lambda I)P-P^{-1}AP|=|P^{-1}((\lambda I)P-AP)|=|P^{-1}((\lambda I)-A)P)|=|P^{-1}|\cdot|((\lambda I)-A)|\cdot|P|=|\lambda I-A|$$
What I do not understand is why $|\lambda I-P^{-1}AP|=|P^{-1}(\lambda I)P-P^{-1}AP|$ why can we multiple $|\lambda I|=|P^{-1}(\lambda I)P|$?

A: $\lambda I=\lambda (P^{-1}IP)=P^{-1}(\lambda I)P$

A: This is simple:

*

*$I=P^{-1}P$ and $P^{-1}P=P^{-1}IP$

*Multiply by the scalar $\lambda$, you get: $\lambda I = \lambda P^{-1}IP$

*Scalars can be moved anywhere in the product, result: $\lambda I = P^{-1}(\lambda I)P$

Note that your equality $|\lambda I|=|P^{-1}(\lambda I)P|$ is true but can't be used to answer your question.

A: So $I$ is the identity matrix and $\lambda$ is some number. Now clearly $P^{-1}IP=I$ since the identity matrix commutes with any matrix, i.e. $AI=IA$ for all $A$. Now simply multiply the identity $P^{-1}IP=I$ by $\lambda$.
Also, $|A|$ denotes the determinant of $A$. So the rest follows from the fact that $\det(AB)=\det(A)\det(B)$ and $\det(A^{-1})=\frac{1}{\det(A)}$.


text:
Q: Intellij IDEA(ulti ver): add SpringFramework-mvc I want to create a project that adds spring mvc in the maven environment.
but I can't make spring-MVC appear.
feat
my intellij version
how can i solve it??

*

*remvoe intellij twice


text:
Q: Problem with IE7 JQuery, Ajax and CSS In a simple web page I load some new HTML into a div using load(url)
Works fine in most browsers but, surprise, surprise, IE7 behaves differently.
All the other browsers apply the pages CSS styles to the newly loaded HTML but IE7 doesn't.
Any ideas?
Ken

Update
The new HTML is just a code fragment, e.g.

blah blah blah

Update I think I'm calling it OK.
This isn't what I'm actually doing but a simplified version which reproduces the problem ...
.
.
.
google.load("jquery", "1.3.2");
    google.setOnLoadCallback(function() {
       $(document).ready(function() {
         $("#nav-home").click(function() {
           $("#girc-content").load("home.html");
         });
.
.
.

Update On further investigation the problem appears to be slightly more odd than I thought.
I tried Steerpike's suggestion because I originally thought the problem was that the CSS styles were not being applied.
However, it now appears that only some of the styles are being applied.
For example, the text color attribute for the
 tag is applied, but the width attribute for the
 tag is not.

A: In light of extra information, take 2...
Are the styles not being applied in the master HTML page or the page you're loading?  If they're in the page you're loading it seems that IE strips out script and style tags from XMLHttpRequest objects.
Given that it's not that and I'm intrigued I constructed a sample:

<title>test</title>

blah blah blah

<input type="button" value="click me" id="nav-home">

and test2.html:

This is a test

This works perfectly for me in IE8 standards and compatibility mode (sorry no IE7 any more).
I did notice when I copied your google onload snippet that you were missing some closing braces/parentheses. Was this just a cut and paste error or a problem with your Javascript?  It might explain the inconsistent behaviour.

A: Try 'touching' the content again after you load it. The simplest way tends to just add a null string to the innerHTML
$("#nav-home").click(function() {
    $("#girc-content").load("home.html");
    $("#girc-content")[0].innerHTML += '';
});

A: The link helped me; essentially, adding the style tag into the head, even dynamically, applies the styles through ie. I added this to the top of the onready handler and it worked well.
http://topsecretproject.finitestatemachine.com/2009/09/how-to-load-javascript-and-css-dynamically-with-jquery/
$("head").append("<link>");
css = $("head").children(":last");
css.attr({
  rel:  "stylesheet",
  type: "text/css",
  href: "/javascripts/jwysiwyg/jquery.wysiwyg.css"
});

A: I had similar problem - IE8 sometimes has a problem with apply styles in content loaded by ajax jQuery function. I don't know why but this helped:
$.ajax({
url: 'content.html',
success: function(data) {
   $('#content').html(data); //styles doeas not appear in ie8
   document.getElementById('content').innerHTML = data; /* ie8 - now it works oO */
}


text:
Q: Calculate the lenght of list items with Javascript I have setup a Javascript function that generate random numbers for every of my search results which are list items and I want to calculate the lenght of the list without knowing in advance the number of search results that will be displayed since every queries are different.
Is there any ways to do that?
Currently, I add a number to itemLength manually within this Javascript function because I know the number of results for a particular query:

But knowing that every queries won't always give 8 results back and that I have to call the results from the backend in the html like this:

   {% if  page_obj.object_list %}

          {% for result in page_obj.object_list %}

{{result.object.title}}

{{ result.object.destination }}

           {% endfor %}

    {% endif %}

How can I automaticaly calculate the itemLength?

A: I think what you're looking for is
orderedList.children.length


text:
Q: Replace LibXML2 with Yocto Built LibXML2 I have been working on this all day, but I think I finally have my base case figured out. I am using a GitHub repo DBCPPP in my application. This repo relies on LibXml2, to ensure it is available LibXml2 is included as a submodule and build with dbcppp through a series of CMakeLists.txt. I am trying to resolve an issue with my build in which the Linux kernel and the DBCPPP recipe are both attempting to install /usr/lib/libxml2.so.2.9.10. I have an open question about it here.
My potential solution is to prevent DBCPPP from creating the libxml2.so.2.9.10 file, and instead build using the libxml2.so.2.9.10 file created by Yocto.
So far my CMakeLists.txt contains:
cmake_minimum_required(VERSION 3.12)
project("libdbcppp" VERSION 0.1.0)

set(LIBXML2_INCLUDE_DIR /mnt/WorkDrive/Documents/EVCC_Application/build-fb/tmp/work/cortexa7t2hf-neon-poky-linux-gnueabi/libxml2/2.9.10-r0/libxml2-2.9.10/include)
set(LIBXML2_LIBRARIES /mnt/WorkDrive/Documents/EVCC_Application/build-fb/tmp/work/cortexa7t2hf-neon-poky-linux-gnueabi/libxml2/2.9.10-r0/image/usr/lib)

#include(FindPkgConfig)
#include(FindLibXml2 REQUIRED)
find_package(LibXml2 REQUIRED)

option(build_tests "Build tests" ON)
option(build_examples "Build examples" ON)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_STATIC_LIBRARY_PREFIX "")
set(CMAKE_SHARED_LIBRARY_PREFIX "")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)

if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
    add_definitions("/bigobj")
endif()

include_directories("include")
include_directories("third-party/libxmlmm/libxmlmm")
include_directories("/mnt/WorkDrive/Documents/EVCC_Application/build-fb/tmp/work/cortexa7t2hf-neon-poky-linux-gnueabi/boost")
include_directories("/mnt/WorkDrive/Documents/EVCC_Application/build-fb/tmp/work/cortexa7t2hf-neon-poky-linux-gnueabi/libxml2/2.9.10-r0/libxml2-2.9.10/include")
include_directories("third-party/cxxopts/include")

file(GLOB libxmlmm_header
    "third-party/libxmlmm/libxmlmm/*.h"
)
file(GLOB libxmlmm_src
    "third-party/libxmlmm/libxmlmm/*.cpp"
)

add_library(libxmlmm SHARED "")
target_link_libraries(libxmlmm LibXml2::LibXml2)

target_sources("libxmlmm"
    PRIVATE ${libxmlmm_header}
    PRIVATE ${libxmlmm_src}
)

install(TARGETS "libxmlmm" EXPORT ${PROJECT_NAME}Targets DESTINATION ${CMAKE_INSTALL_LIBDIR})
install(
    DIRECTORY "libxmlmm"
    DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/libxmlmm
    FILES_MATCHING PATTERN "*.h")

set(CMAKE_STATIC_LIBRARY_PREFIX "")
set(CMAKE_SHARED_LIBRARY_PREFIX "")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)

CONFIGURE_FILE(
  "${CMAKE_CURRENT_SOURCE_DIR}/cmake_uninstall.cmake.in"
  "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake"
  IMMEDIATE @ONLY
)

ADD_CUSTOM_TARGET(uninstall
  "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake"
)

Edit: I am updating my question with my latest CMakeLists.txt. I am integrating this with a Yocto project. This appears to work within Ubuntu but when I added it to the Yocto build I get the error.
error: /mnt/WorkDrive/Documents/MAIN_Application/build-fb/tmp/work/cortexa7t2hf-neon-poky-linux-gnueabi/libxml2/2.9.10-r0/image/usr/lib: read: Is a directory
| collect2: error: ld returned 1 exit status
| ninja: build stopped: subcommand failed.
| WARNING: exit code 1 from a shell command.


text:
Q: Java Sync values in every one hour I have a class that calculates currency conversions per hour. The class is provided below,
public class CurrencyUtilities {

    public static String getCurrencyExchangeJsonData(String urlToRead) throws Exception {

        StringBuilder result = new StringBuilder();
        URL url = new URL(urlToRead);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        rd.close();
        return result.toString();
    }

    public static Map<String, Double> getConvertionRates() {

        /*
         * https://openexchangerates.org/api/latest.json?app_id=50ef786fa73e4f0fb83e451a8e5b860a
         * */
        String s = "https://openexchangerates.org/api/latest.json?app_id=" + "50ef786fa73e4f0fb83e451a8e5b860a";

        String response = null;

        try {
            response = getCurrencyExchangeJsonData(s);
        } catch (Exception e) {

        }

        final JSONObject obj = new JSONObject(response.trim());

        String rates = obj.get("rates").toString();

        JSONObject jsonObj = new JSONObject(rates);

        Iterator<String> keys = jsonObj.keys();

        Map<String, Double> map = new HashMap<>();

        double USD_TO_EUR = Double.parseDouble(jsonObj.get("EUR").toString());
        map.put("USD", (1.0 / USD_TO_EUR));

        while (keys.hasNext()) {

            String key = keys.next();
            double v = Double.parseDouble(jsonObj.get(key).toString());

            map.put(key, (double) (v / USD_TO_EUR));
        }

//        for (Map.Entry<String, Double> entry : map.entrySet()) {
//            System.out.println(entry.getKey() + " " + entry.getValue());
//        }

        return map;
    }
}

Inside the API, I call the values as provided,
@RestController
@RequestMapping("/api/v1/users")
public class UserAPI {

    static Map<String, Double> currencyMap = CurrencyUtilities.getConvertionRates();

     // .....................................
     // .....................................
}

I need to sync the values of the currencyMap per hour with the openexchangerates.org. What's the best way to do that?
Thank you.
PS
I mean what's the best way to call this method CurrencyUtilities.getConvertionRates() in each hour?

A: You can annotate the method with @Scheduled and provide some fixed time between invokation. Here you can find usage examples. Also remember to annotate some config class with @EnableScheduling. In your case, you can use cron:
@Scheduled(cron = "0 */1 * * *")

A: Best way to do what you need is to use @Scheduled. See THIS link for example in Spring.
Long story short - you can annotate method with @Scheduled, and it will be executed based on provided rules. You should put results in database, and in REST service just get last result, or more if you need history data.


text:
Q: WiX to install EventSource I created my event source based on this example. My event source looks like this:
[EventSource(Name = "Samples-EventSourceDemos-EventLog")]
public sealed class MinimalEventSource : EventSource
{
    public static MinimalEventSource Log = new MinimalEventSource();

    [Event(1, Message = "{0} -> {1}", Channel = EventChannel.Admin)]
    public void Load(long baseAddress, string imageName)
    {
        WriteEvent(1, baseAddress, imageName);
    }
}

The example use code to simulate install/uninstall process. From some other SO questions, I saw another example of installing event source using event message file.
But it is missing some good examples how to install/register the EventSource that defined by manifests. I am investigating using CustomAction to do something like:
wevtutil.exe im <EtwManifestManFile> /rf:"EtwManifestDllFile" /mf:"EtwManifestDllFile"
but wondering if you have any suggestions?

A: Figured out after some search. In the WixUtilExtension, there is build-in support. After referencing it and adding namespace, it is pretty easy.
Here are the changes in the Product.wxs:
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
     xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">
...
      <Component Id="etwManifest.dll">
        <File Id="etwManifest.dll" KeyPath="yes"
              Source="$(var.SampleClassLibrary.TargetDir)\SampleClassLibrary.Samples-EventSourceDemos-EventLog.etwManifest.dll" />
      </Component>
      <Component Id="etwManifest.man">
        <File Id="etwManifest.man" KeyPath="yes"
              Source="$(var.SampleClassLibrary.TargetDir)\SampleClassLibrary.Samples-EventSourceDemos-EventLog.etwManifest.man">
          <util:EventManifest  MessageFile="[etwManifest.dll]"  ResourceFile="[etwManifest.dll]"></util:EventManifest>
        </File>
      </Component>
</Wix>

The only trick I had to do is reduce the length of component Id and File Id (used to match with the file names) to avoid the following error: Error 25540. There was a failure while configuring XML files.

A: For me, the sollutions was to add permission to both files, the .dll and the .man. (https://stackoverflow.com/a/32727624/5500092)
<util:PermissionEx User="Everyone" ReadPermission="yes" ReadAttributes="yes" ReadExtendedAttributes="yes" />

I also had to add the full path to correctly registrate the manifest file. When i didn't do that, the manifest file still refer to the bin/release folder of my visual studio solution.
<util:EventManifest MessageFile="[INSTALLFOLDER]SampleClassLibrary.Samples-EventSourceDemos-EventLog.etwManifest.dll" ResourceFile="[INSTALLFOLDER]SampleClassLibrary.Samples-EventSourceDemos-EventLog.etwManifest.dll"/>

Code:
<DirectoryRef Id="INSTALLFOLDER">
    <Component Id="etwManifest.dll" Guid="PUT-GUID-HERE">
        <File Id="etwManifest.dll" KeyPath="yes"  Source="$(var.SampleClassLibrary.TargetDir)\SampleClassLibrary.Samples-EventSourceDemos-EventLog.etwManifest.dll" >
            <util:PermissionEx User="Everyone" ReadPermission="yes" ReadAttributes="yes" ReadExtendedAttributes="yes" />
             <util:PermissionEx User="Administrators"   ReadPermission="yes" ReadAttributes="yes" ReadExtendedAttributes="yes"/>
        </File>
    </Component>

    <Component Id="etwManifest.man" Guid="PUT-GUID-HERE">
        <File Id="etwManifest.man" KeyPath="yes" Source="$(var.SampleClassLibrary.TargetDir)\SampleClassLibrary.Samples-EventSourceDemos-EventLog.etwManifest.man" >
            <util:PermissionEx User="Everyone"   ReadPermission="yes" ReadAttributes="yes" ReadExtendedAttributes="yes"/>
            <util:PermissionEx User="Administrators"   ReadPermission="yes" ReadAttributes="yes" ReadExtendedAttributes="yes"/>
            <util:EventManifest MessageFile="[INSTALLFOLDER]SampleClassLibrary.Samples-EventSourceDemos-EventLog.etwManifest.dll" ResourceFile="[INSTALLFOLDER]SampleClassLibrary.Samples-EventSourceDemos-EventLog.etwManifest.dll"/>
        </File>
    </Component>
</DirectoryRef>

Using WiX Toolset v3.10
(Please do correct me if my English is bad)


text:
Q: Flutter - set result to return when the user navigates back When calling Navigator.pop() a result can be passed to the previous screen. Is there a way to set the result so that if the user navigates back on their own the result is still returned to the previous page?
I could pass an object to the second page and then modify it so that the first page can check it when the second page returns, but I'd rather use the result returned from the Navigator as it's more readable.
Overriding the back button's tap detector as I've seen suggested elsewhere is not an acceptable solution because the user may navigate back in some other way such as swiping or pressing the Android back button.

A: Yes, you can pass data between screens both ways.
While popping back, send the data you wish to send like this from the second screen
RaisedButton(
  onPressed: () {
    // The Nope button returns "data" as the result.
    Navigator.pop(context, 'data');
  },
  child: Text('Nope!'),
);

And catch the result in the your first screen like this
final result = await Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => SecondScreen()),
  );

source
For the other concern where the user is able to go back to the previous screen by pressing the back button, you can wrap your second screen with WillPopScope widget and provide the onWillPop callback. This will override the popping of the second screen and execute the callback where you can define the value you wish to return from the second screen.
@override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(), // or your widget
      onWillPop: () {
        return Future.delayed(Duration(microseconds: 0), () {
          return Navigator.pop(context, "return-data");
        });
      },
    );
  }

A: Yes, this is possible, when navigating to Screen B from Screen A, make the onTap() functionasynchronous and await the result from Screen B.
Check the code below: It works perfectly:
On Screen A, put this code:
 onTap: () async {
        // receive the data you are sending from screen B here
        final result = await Navigator.push( context);
       },

On Screen B, put this code:
onTap: (){
    // pass the data you want to use in screen A as the second paramter
     Navigator.pop(context,number);
      },

I hope this helps


text:
Q: Is there a way to stop multiple threads after the first thread finishes it's job? I've been trying to speed up the number of password attempts being posted to a test website using threading.
import string
import random
import requests
import threading

threads=[]
threadLength=10

def typeCheck():

  passType = input("\nWhat Type Of Password Is Used? Type 'help' For More Help\nL=Letters, D=Digits, S=Symbols: ")

  if passType == "L":
    pt = string.ascii_letters
  elif passType == "D":
    pt = string.digits
  elif passType == "S":
    pt = string.punctuation
  elif passType == "LD":
    pt = string.ascii_letters + string.digits
  elif passType == "DS":
    pt = string.digits + string.punctuation
  elif passType == "LS":
    pt = string.ascii_letters + string.punctuation
  elif passType == "LDS":
    pt = string.ascii_letters + string.digits + string.punctuation
  elif passType == "help":
    help()
    exit()
  else:
    exit("Invalid Type, Try Again.")
  return pt

def lengCheck():

  passLeng = int(input("\nWhat Is The Password Length?\nAny Positive Integer: "))

  if passLeng > 0:
    pl = passLeng
  else:
    exit("Invalid Password Length.")
  return pl

def createThreads(passType, passLength, url, username, userData, passData):
  for i in range(threadLength):
    global t
    t = threading.Thread(target=breaker, args=[passType, passLength, url, username, userData, passData, threads])
    threads.append(t)
  return threads

def breaker(passType, passLength, url, username, userData, passData, threads):

  remAttempts=[]
  sesh=requests.session()
  attempts=0
  print()

  while True:

    attempt = 'tes'+''.join(random.choice(passType)for i in range(passLength))
    if attempt in remAttempts:
      pass
    else:
      remAttempts.append(attempt)
      request = sesh.post(url, data={
        ''.join(userData):username,
        ''.join(passData):attempt
      })
      print('<-------'+attempt+'------->')
      logAuth=request.cookies
      if logAuth:
        break
      else:
        pass

    attempts += 1
  print("\nThe Password is "+str(attempt)+" and it took "+str(attempts)+" attempts")
  # I had code here to exit the script, but realized it only affected one thread

def getForm():

  username = input("Username: ")
  url = input("Url: ")
  userData = input("Username form data: ")
  passData = input("Password form data: ")
  return [url, username, userData, passData]

def bruteForce(threads):

  for i in range(threadLength):
    threads[i].start()
  for i in range(threadLength):
    threads[i].join()

Here is the main.py file that actually gets run
import pBreak

formData =  pBreak.getForm()

passType = pBreak.typeCheck()
passLeng = pBreak.lengCheck()

threads = pBreak.createThreads(passType, passLeng, formData[0], formData[1], formData[2], formData[3],)

details = pBreak.bruteForce(threads)

When I run the code at this point, it will run all ten threads one after another, each one at 10x speed. I want to end the entire thing after one thread going at 10x speed, instead of running the breaker(...) method ten times. Also, it doesn't have to be with threading, I just want what I described to happen, so any type of solution works.

A: import string
import random
import requests
import threading

threads=[]
threadLength=10
end_breaker = False

def typeCheck():

  passType = input("\nWhat Type Of Password Is Used? Type 'help' For More Help\nL=Letters, D=Digits, S=Symbols: ")

  if passType == "L":
    pt = string.ascii_letters
  elif passType == "D":
    pt = string.digits
  elif passType == "S":
    pt = string.punctuation
  elif passType == "LD":
    pt = string.ascii_letters + string.digits
  elif passType == "DS":
    pt = string.digits + string.punctuation
  elif passType == "LS":
    pt = string.ascii_letters + string.punctuation
  elif passType == "LDS":
    pt = string.ascii_letters + string.digits + string.punctuation
  elif passType == "help":
    help()
    exit()
  else:
    exit("Invalid Type, Try Again.")
  return pt

def lengCheck():

  passLeng = int(input("\nWhat Is The Password Length?\nAny Positive Integer: "))

  if passLeng > 0:
    pl = passLeng
  else:
    exit("Invalid Password Length.")
  return pl

def createThreads(passType, passLength, url, username, userData, passData):
  for i in range(threadLength):
    global t
    t = threading.Thread(target=breaker, args=[passType, passLength, url, username, userData, passData, threads])
    threads.append(t)
  return threads

def breaker(passType, passLength, url, username, userData, passData, threads):
  global end_breaker
  if not end_breaker:
    remAttempts=[]
    sesh=requests.session()
    attempts=0
    print()

    while True:

        attempt = 'tes'+''.join(random.choice(passType)for i in range(passLength))
        if attempt in remAttempts:
        pass
        else:
        remAttempts.append(attempt)
        request = sesh.post(url, data={
            ''.join(userData):username,
            ''.join(passData):attempt
        })
        print('<-------'+attempt+'------->')
        logAuth=request.cookies
        if logAuth:
            break
        else:
            pass

        attempts += 1
    print("\nThe Password is "+str(attempt)+" and it took "+str(attempts)+" attempts")
    end_breaker = True
  # I had code here to exit the script, but realized it only affected one thread

def getForm():

  username = input("Username: ")
  url = input("Url: ")
  userData = input("Username form data: ")
  passData = input("Password form data: ")
  return [url, username, userData, passData]

def bruteForce(threads):

  for i in range(threadLength):
    threads[i].start()
  for i in range(threadLength):
    threads[i].join()
Here is the main.py file that actually gets run

import pBreak

formData =  pBreak.getForm()

passType = pBreak.typeCheck()
passLeng = pBreak.lengCheck()

threads = pBreak.createThreads(passType, passLeng, formData[0], formData[1], formData[2], formData[3],)

details = pBreak.bruteForce(threads)

I think creating a global variable to end the task is a quick fix for your problem.


text:
Q: Can't connect to wireguard server from WAN I'm trying to connect to my wireguard server, but it's not working, and I'm out of my depth. I suspect it's more of a network issue than a wireguard issue, but I could be mistaken. I'm hoping someone can give me some pointers.
What I've done / What is working
I've created several configurations on the server, and one of them I've added to the client running Pop-OS. If it's on the (W)LAN, it can connect to the server without problems.
Details
Set-up of client.
# /etc/wireguard/wg0.conf

[Interface]
PrivateKey = [removed]
Address = 10.6.0.4/24
MTU = 1420
DNS = 8.8.8.8, 8.8.4.4

[Peer]
PublicKey = [removed]
PresharedKey = [removed]
Endpoint = somesubdomain.chickenkiller.com:51820  # I tried with this one...
#Endpoint = 192.168.1.220:51820  # ...and with this one.
AllowedIPs = 0.0.0.0/0, ::0/0

In the LAN, this works, regardless of the Endpoint that's commented in:
# sudo wg-quick up wg0

[#] ip link add wg0 type wireguard
[#] wg setconf wg0 /dev/fd/63
[#] ip -4 address add 10.6.0.4/24 dev wg0
[#] ip link set mtu 1420 up dev wg0
[#] resolvconf -a tun.wg0 -m 0 -x
[#] wg set wg0 fwmark 51820
[#] ip -6 route add ::/0 dev wg0 table 51820
[#] ip -6 rule add not fwmark 51820 table 51820
[#] ip -6 rule add table main suppress_prefixlength 0
[#] ip6tables-restore -n
[#] ip -4 route add 0.0.0.0/0 dev wg0 table 51820
[#] ip -4 rule add not fwmark 51820 table 51820
[#] ip -4 rule add table main suppress_prefixlength 0
[#] sysctl -q net.ipv4.conf.all.src_valid_mark=1
[#] iptables-restore -n

# sudo wg

interface: wg0
  public key: [removed]
  private key: (hidden)
  listening port: 44709
  fwmark: 0xca6c

peer: [removed]
  preshared key: (hidden)
  endpoint: 12.34.567.89:51820     # (WAN IP address or LAN IP address, depending on commented-in Endpoint in wg0.conf)
  allowed ips: 0.0.0.0/0, ::/0
  latest handshake: Now
  transfer: 17.84 MiB received, 230.08 KiB sent

For my smartphone, using the wireguard app, the same is true: the connection is working when the phone is in the WLAN.
What is not working
When the client tries to connect through the internet, it's no longer working. The output of sudo wg-quick up wg0 is the same as when it's in the LAN, but sudo wg takes a long time to produce an output, and when it does, it is always at 0 trafic:
# sudo wg

interface: wg0
  public key: [removed]
  private key: (hidden)
  listening port: 60955
  fwmark: 0xca6c

peer: [removed]
  preshared key: (hidden)
  endpoint: 12.34.567.89:51820
  allowed ips: 0.0.0.0/0, ::/0
  transfer: 0 B received, 2.31 KiB sent

Details
Seems to me that there is a problem getting into the LAN from the WAN, so I better crack out the old network diagram.
This is the set-up of the LAN:

On both the routers, port forwarding for UDP traffic on port 51820 is active. (on the primary router, to the secondary one, and on the secondary one, to the vpn server)
It's surely not relevant, but the client is connected to the internet through a USB-tethered smartphone's cellular data connection, over which it can ping google and access the internet just fine.
The VPN Server is running a service to update the somesubdomain.chickenkiller.com DDNS service, and pinging this shows that it indeed resolves to my WAN address. The pings get a response as well:
~$ ping somesubdomain.chickenkiller.com
PING somesubdomain.chickenkiller.com (12.34.567.89) 56(84) bytes of data.
64 bytes from xxxxxxx.dynamic.kabel-deutschland.de (12.34.567.89): icmp_seq=1 ttl=47 time=77.1 ms
64 bytes from xxxxxxx.dynamic.kabel-deutschland.de (12.34.567.89): icmp_seq=2 ttl=47 time=76.1 ms

I'm not working on networks and networking infrastructure every day, so excuse me in advance if this has an obvious reason, or if I left out any critical information; just ask and I'll happily provide any additional data that is needed.
Additional information / Primary router settings

*

*I can connect to the VPN server whether on LAN1 or LAN2, so the port forwarding on the own/secondary router seems to be working just fine; the problem must be in the ISP/primary router or its modem.

*The following port forwarding rules are set in this router; correctly AFAICS:

*The ISP router has a firewall, but it's an on-or-off one without any settings.

A: Solution (well, workaround): bridge mode
A traceroute somesubdomain.chickenkiller.com -U -p 51820 showed that the packets were reaching the primary router, but died there.
I assume there is some accidental or intended blocking of these packets by the ISP-provided hardware, and turned the device into bridge mode. The secondary router has been promoted to primary router and the setup is now working perfectly fine. I can reach and connect to the wireguard server without problem.
Thanks for your help.
And thanks Vodafone for being less than helpful.


text:
Q: Homogeneous ideal and its system of generators Let $I$ be a homogeneous ideal in a graded commutative ring $R$, $S$ be its minimal system of generators.
What is the conclusion that we can say about the element in $S$ ? Is the cardinality of $S$ uniquely determined by $I$ ?
In the book Commutative ring theory of Matsumura, theorem 2.3, page 8 there is a theorem for local ring which we can deduce that the number of generator is unique. So, is there a version of that theorem for the graded ring ?
What about the degree of generator in $S$ ?

A: Also, Proposition 1.5.15 in Cohen-Macaulay rings by Bruns and Herzog might help you. This is a bit more general than what Karl mentioned above.

A: I gave a short answer to this question here: https://math.stackexchange.com/questions/209218/homogeneous-ideal-and-degree-of-generators.
A more general answer says the following: if $K$ is a field, $R$ is an $\mathbb{N}$-graded $K$-algebra finitely generated over $K$, and $M$ a $\mathbb{Z}$-graded finitely generated $R$-module, then
$$\beta_{ij}(M)=\dim_K\operatorname{Tor}_i^R(K,M)_j,$$
where $\beta_{ij}(M)$ are the graded Betti numbers of $M$.


text:
Q: pip install error: package directory does not exist I've looked at similar questions, but with no luck of answer, I have the following structure
├── README.rst
├── setup.py
└── my_package
    ├── conf.py
    ├── sub_module1
    │   └── __init__.py
    │   └── some_code.py
    ├── sub_module2
    │   └── __init__.py
    │   └── some_other_code.py
    ├── some_main_code.py
    └── __init__.py

And my setup.py looks something like
..
setup(name=..
      ...
      packages=find_packages('my_package')

When installing I get the following error
    ERROR: Command errored out with exit status 1:
     command: /some_path/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-req-build-f7hcw6xa/setup.py'"'"'; __file__='"'"'/tmp/pip-req-build-f7hcw6xa/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-req-build-f7hcw6xa/pip-egg-info
         cwd: /tmp/pip-req-build-f7hcw6xa/
    Complete output (8 lines):
    running egg_info
    creating /tmp/pip-req-build-f7hcw6xa/pip-egg-info/my_package.egg-info
    writing /tmp/pip-req-build-f7hcw6xa/pip-egg-info/my_package.egg-info/PKG-INFO
    writing dependency_links to /tmp/pip-req-build-f7hcw6xa/pip-egg-info/my_package.egg-info/dependency_links.txt
    writing requirements to /tmp/pip-req-build-f7hcw6xa/pip-egg-info/my_package.egg-info/requires.txt
    writing top-level names to /tmp/pip-req-build-f7hcw6xa/pip-egg-info/my_package.egg-info/top_level.txt
    writing manifest file '/tmp/pip-req-build-f7hcw6xa/pip-egg-info/my_package.egg-info/SOURCES.txt'
    error: package directory 'sub_module1' does not exist
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

If sub_module1 is there, and has an init.py file in it - why wouldn't the installation recognize it?

A: EDIT: Kudos to sinoroc for pointing out there of course is more than one solution to this issue.
Solution #1
The error message tells you that the interpreter thinks you have a package called 'sub_module1'. Since that is obviously intended to be a module and not a package, you can see that you are missing one level in your directory structure for the way you are currently trying to make use of find_packages().
You could add a "src" folder to the structure of your project. Then you would have to do something like:
mkdir src
mv my_package src/

And inside setup.py point find_packages to 'src' instead of 'my_package':
packages=find_packages(where="src"),
package_dir={'': 'src'},

Solution #2
Alternatively you could try to use find_packages without any parameter at all (as suggested by https://packaging.python.org/tutorials/packaging-projects/):
packages=find_packages()

This did not work for me when I set up my package and in the long run it turned out that I would have been off better with the src/ solution anyways. That is why my initial version of an answer assumed you would want to add src/.
Personal Conclusio
Keep in mind that if you might have more packages in the future, want to add scripts to your package or do anything more complex than just one package it might be wise to go with src/. I am aware this has been topic of discussions for years that's why I call this a "personal conclusio".


text:
Q: How to convert an Eloquent query to Adonis lucid? So I'm rewriting a Laravel app to an Adonis app and here are my models
// A customer can have multiple invoices
class Customer extends Model {
    invoices() {
        return this.hasMany('App/Models/Invoice');
    }

    invoiceItems() {
        return this.manyThrough('App/Models/Invoice', 'items');
    }
}

// An invoice can have multiple invoice items
class Invoice extends Model {
    items() {
        return this.hasMany('App/Models/InvoiceItem');
    }

    customer() {
        return this.belongsTo('App/Models/Customer');
    }
}

// An invoice item belongs to an invoice
class InvoiceItem extends Model {
    product() {
        return this.belongsTo('App/Models/Product');
    }

    invoice() {
        return this.belongsTo('App/Models/Invoice');
    }
}

I want to get the sum of invoice items price * qty and here's a sample output of my /api/customers
Customer.query()
.withCount('invoiceItems as invoice_items_total', builder => {
    builder.select(
          DB.raw('sum(price * quantity)')
    );
})
.fetch()

[
    {
        "id": 2,
        "account_no": "Solana-2",
        "type": "person",
        "first_name": "Mark",
        "middle_name": "",
        "last_name": "Soriano",
        "company_name": "",
        "address": "Solana",
        "created_at": "2019-12-08 10:22:12",
        "updated_at": "2019-12-08 10:24:09",
        "__meta__": {
            "invoice_items_total": 1, // Still returns total no. of rows instead of sum(product * quantity) ?
        }
    }
]

Weird thing here is instead of the value of DB.raw('sum(price * quantity)'), I'm still getting the total number of invoice_items  rows which is 1.
My laravel code looks like this and it works:
Customer::withCount([
            'invoice_items as invoice_items_total' => function($query) {
                $query->select(DB::raw('sum(price * quantity)'));
            },
 ])->get();

This code returns the sum instead of total number of rows.
Am I missing something here? Or is that out of scope for withCount constraints in Adonis?


text:
Q: Firefox returns pages without http status code I know, there were several questions about that but it seems like there are a ton of reasons for that and I still can't figure out what's wrong in my case.
We have a website on 2 cluster servers. Requests to these servers are routed by user IP (so each particular user is always routed to the same server). One of the servers works perfectly fine, whereas on the other there is this strange behavior. In Firefox there are no HTTP response codes for ANY webpage I'm navigating to. As you can see on the screenshot all "documents" have no response code whereas "subdocuments" do have 200. For this test, I visited several website pages. No Ajax, no nothing, just click on various links on a page. All other resources (CSS, JS, images) also correctly returned with 200 status.
What's more confusing is that the page is correctly displayed in the browser, so the connection is not lost/interrupted/timedout. Everything seems normal except no HTTP status code.
Moreover, it seems like "under the hood" Firefox actually makes 2 calls to the server every time (only shows it as 1 call with no response code in the Network tab).
Chrome, Opera and IE work fine. Server Response headers are exactly the same in all browsers (except that Firefox shows "Response headers (0 Gb)" for some reason).
Does anyone know what could be the cause?
Thanks in advance.

A: We can check what is going on with a simple test:
In summary: no HTTP request is being made
If you look closely, these entries are coming with 0 for all timing measurements.
The headers are coming without a remote address, protocol version and status.
Ok, no requests, but the response is there -> cache
To validate the assumption that the tool is not telling you, explicitly, that it is from a cached file, one can go to the storage section of the inspector and clean up all data from that site. After doing that, one would see that all requests have a code. Disabling the cache is not enough. But after that experiment you can re-enable the cache to see the phenomenon again.
A very important piece of information that is a complement, is that if there is a request, there shall be a code. The lack of code, headers linked to the origin of the data and such, are a clue that points to caching. (I would rather have an explicit message telling me that, at least as explicit as in chrome)


text:
Q: Heroku configuration for Ruby on Rails application I've set a client up with Heroku for their Ruby on Rails application and have had a great deal of trouble over the years with their application not running well regardless of how much money we spend on additional resources, find their documentation highly confusing. I've never been able to understand their specific terminology and documentation. We are constantly getting "H12" errors and "R14" errors etc. The memory usage and dyno loads are constantly spiking. And yet this is a small to medium-sized business without a massive amount of traffic. Wondering if anybody out there who does understand the ins and outs of Heroku can look this configuration over and tell me if it makes sense:
DB_POOL: 10
MALLOC_ARENA_MAX: 2
RAILS_MAX_THREADS: 5
WEB_CONCURRENCY: 4

Ruby 2.7
Rails 6.0
Puma

8 2x web dynos
5 1x worker dynos
$50 Postgres standard 0 database
$15 Memcachier
$10 Rediscloud
...etc addons

A: Your WEB_CONCURRENCY is too high for your Standard-2x dynos. The recommended default is 2: https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server#recommended-default-puma-process-and-thread-configuration
This is likely contributing to your R14 errors as higher web concurrency means more memory usage. So you need to either lower your web concurrency (which may mean you also need to increase the # of dynos to compensate) or you need to use bigger dynos.
You already have MALLOC_ARENA_MAX=2 but not sure if you are using jemalloc. You might want to try that too.
Of course, you may also have other memory issues in your app - check out some tips here. I also recommend adding a monitoring tool like AppSignal as it's capable of tracking memory allocations per transaction.
For mitigating H12s:

*

*Ensure you have installed something like the rack-timeout gem, which ensures that a long-running request is dropped at the dyno-level and thus avoids the H12 error (you get a Rack::TimeoutError exception instead). Set the timeout to 15s so that it is well under the 30s for H12 timeout.

*Investigate your slow transactions. A monitoring tool is key here, i.e. New Relic (start with lowest-priced paid plan - free plan does not allow transaction tracing). Here is their blog post on how to trace transactions

*When you've identified the problem - fix it!

*

*if the bottleneck is external:

*

*check for external API limits and throttling

*add timeouts and make app resilient to slow external responses

*if the bottleneck is due to the database:

*

*optimize slow queries

*check cache hit rates

*check for the # of waiting connections and db locks -> if the number of waiting connections is consistently above 0 for X minutes, that indicates you have some long locks that you'll need to investigate. Waiting connections is easiest to track over time with Librato (free plan should do fine)

*if the bottleneck is other app code:

*

*add more custom instrumentation to get more insights, i.e. New Relic instructions

*address app code issues

I want to stress the importance of monitoring tools to help diagnose issues and help determine optimal resource usage. Doing things like figuring out the correct concurrency configs, the correct size and # of dynos to run are virtually impossible without proper monitoring tools. Hopefully you have some already that are covered by your etc add-ons that are not listed, but if you do not, I'll summarize my recommendations and mention a couple other tips:

*

*To get more metrics info, ensure you have enabled log-runtime-metrics

*Also enable Ruby language metrics

*Add a monitoring tool that can track Ruby memory allocations like AppSignal. Scout APM can do this too but I think their plans capable of this are more expensive (requires Scout Insights feature)

*Add the lowest-paid version of New Relic. This is my go-to tool for transaction tracing. AppSignal can do this too if you don't want to pay for another tool, but I find it easier with New Relic.

*Add Librato. It offers some great charts out of the box, including a set of Postgres charts in its own dashboard.

*Set alerts in your monitoring apps to warn you about things like response times so you can look into them!

*And of course, make all your changes in staging first AND load test them to see the impacts of your changes before attempting in production!

Update: I also just noticed that you said you are using Standard-0 Postgres, which means it has a 120 connection limit. So if you end up lowering your WEB_CONCURRENCY and increasing the # of dynos, watch out for your total connections to that database. Beyond just the fact that there is a limit, more connections also mean more overhead for your db anyway so if you are close to your connection limit, you are more likely to see db performance suffer. You may want to upgrade to another plan that has a higher connection limit or use pgbouncer as your connection pooler to avoid connection limits.


text:
Q: Two Different Right Hand Grip Rules I have a question about TWO DIFFERENT right hand grip rules I was told about my teacher today and I'd like to have the legitimacy of them confirmed. The first one describes that in an individual peice of wire, if the thumb describes the direction of current, then the other fingers describe the direction of the magnetic field. The second one, which I'm more unsure about, says that in a coil, if the fingers describe the direction of current in the coil, then the thumb points towards the north magnetic pole of the electromagnet. Are both of these correct?

A: If you consider a coil of wire in a plane, with current going anti-clockwise, and apply the "magnetic field from current" rule to the right hand side of the coil (where the current is flowing up), you will see that your fingers are on the inside of the loop, pointing towards you. This confirms that the magnetic field is pointing towards you in such a configuration (diagram below adapted from https://en.wikipedia.org/wiki/Right-hand_rule)

And if you hold your right hand over the page so your fingers point in the direction of the current, your thumb is pointing towards you.
Both rules are correct.
I am not sure why you need independent confirmation of this - it's something you can so easily convince yourself of.


text:
Q: Which PostGIS SRID is most efficient for a spatial index? I have a PostGIS-enabled database with a table called locations that stores latitude-longitude points (SRID 4326) in a column called coordinates. However, all of my lookups on that table convert the points to a metric projection (SRID 26986) mainly to do distance comparisons.
Obviously I'd like to create a spatial index on the coordinates column. My question is, which is the best (most computationally efficient) SRID to use in the coordinates spatial index in this case?
I can either index using SRID 4326...
CREATE INDEX locations_coordinates_gist
ON locations
USING GIST (coordinates);

Or using SRID 26986...
CREATE INDEX locations_coordinates_gist
ON locations
USING GIST (ST_Transform(coordinates, 26986));

A: I discovered this helpful information reading the PostGIS documentation on the ST_Transform function...

If using more than one transformation, it is useful to have a
  functional index on the commonly used transformations to take
  advantage of index usage.

So it seems the answer is, use both! I have created two indices, one with each SRID.


text:
Q: How can I replace aeiou with bfjpv in Perl? I want to replace aeiou with bfjpv in user inputted string. Here is the code which is not working :-
print "Enter any String :";
while(($string = <>) ne "\n"){

    @arr = split(//,$string);

    for($i = 0 ; $i < $#arr ; $i++){
        $char = $arr[$i];

        if($char eq 'a' || $char eq 'e' || $char eq 'i' || $char eq 'o' || $char eq 'u'){
            $char = $char + 1;
        }
        print $char;
    }

}

What should I do to add one character? I mean how do I replace a with b.

A: $string =~ tr/aeiou/bfjpv/;

Does the whole job. See the perlop manual.

A: $char = chr(ord($char) + 1);

ord = convert character to integer
chr = convert integer to character

A: You can just do
$char++;

in place of
$char = $char + 1;

Also you really don't need to loop to do the replacement. Just use the tr operator as:
($new_string = $string) =~ tr [aeiou] [bfjpv];


text:
Q: Poor performance of Android Canvas.drawBitmap - switch to OpenGL? I'm porting a 2D action game from Windows Phone 7 (developed in XNA 4.0) over to Android. I'm using a lot of Canvas.drawBitmap() calls - around 200-300 per frame update - with different Paints for each call to handle varying transparency and colourisation at draw-time. This is managing particle systems and various other overlays and in-game effects as well as a tiled background and in-game sprites. I'm not doing any on-demand resizing or rotating, it's simple src->dest rectangles of the same size.
On WP7 this runs at 30+fps but I'm struggling to get 12fps on my test 'droid hardware (Samsung Galaxy S). This is making the game unplayable. Having profiled the code, I've confirmed that all my time is being lost in Canvas.drawBitmap()
I seem to be following all the usual performance advice - using a SurfaceView, mindful of GC so not creating loads of throwaway objects, and avoiding Drawables.
Am I right in understanding that Canvas.drawBitmap() is CPU-bound, and if I want to improve performance I have to switch to OpenGL which will use the GPU? I can't find it stated that baldly anywhere, but reading between the lines of some comments I think that might have to be my next step...?

A: This is normal. Canvas is amazingly slow when using transparency (like ARGB_8888).
2 options:

*

*Switch to OpenGL ES

*Use the least possible transparency on your bitmaps (i.e use RGB_565 the most you can).

A: Perhaps this will run better on Android 3+ since it uses hardware acceleration for canvas operations.


text:
Q: Converting jpeg to bmp version 4 using imagemagick? I can't seem to find a way to properly convert my images to bmp using imagemagick. Whenever I use this website with the current settings it works flawlessly in my program. https://online-converting.com/image/convert2bmp/
I've tried these commands:
convert disney.jpeg -format bmp:format=bmp4 out.bmp
convert disney.jpeg -define bmp:format=bmp4 -type truecolor -compress none out.bmp

Nothing seems to work. Not sure how to set up imagemagick so that it gives me back the same format as the website.
As for the program, you basically feed it the bmp file. It works when I convert with the website, but not with imagemagick.


text:
Q: Win XP Screen saver / power management not working I have a PC running Win XP, and even though I have the power management set to turn off the monitor after 10 minutes, and I have the windows screen saver set up, many times they never kick in.  I come home or wake up to a monitor that is fully on so perhaps some process is keeping the PC active?  Of course it's not consistent and hard to re-produce when I want to.

A: This might help figure out a setting you have misplaced. It's hard to tell without checking all your settings.
http://tips.oncomputers.info/archives2003/0303/2003-mar-09.htm


text:
Q: Looping a Json object in map.arc() i am using http://jsbin.com/nutawiboci/1/edit?html,output to show the location of the origin and destination coordinate and draw an arc between them. so i modified the map.arc() to loop through a given origin and destination coordinate:
    for (var i = 0; i < data.length; i++) {

      var origin_long  = data[i][0][0];
      var origin_lat   = data[i][0][1];

      var destination_long = data[i][1][0];
      var destination_lat  = data[i][1][1];

        map.arc([
          {
            origin: {
                latitude: origin_lat,
                longitude: origin_long
            },
            destination: {
                latitude: destination_lat,
                longitude: destination_long
            }
          }
          ], {strokeWidth: 2});
    };

This actually works, but it only draws the last(from the loop) since it destroys the previous arcs before drawing the next. i just don't know how to iterate in the map.arc(). i want the loop to return something like this:
        map.arc([
          {
            origin: {
                latitude: 43.445,
                longitude: 83.435345
            },
            destination: {
                latitude: 324.2323,
                longitude: -6
            }
          },
          {
            origin: {
                latitude: -53.445,
                longitude: 333.4345
            },
            destination: {
                latitude: -24.2323,
                longitude: 46.454
            }
          },
          {
            origin: {
                latitude: 53.045,
                longitude: 663.4345
            },
            destination: {
                latitude: -94.2323,
                longitude: 996.4454
            }
          }
          ], {strokeWidth: 2});

any other way than looping it is also appreciated, i just want it working this way. Thanks!

A: You are overwriting values in your loop..try pushing each co-ordinate into a temporary array first and then assign the temporary array to map arc try something like:
 var temp = []
 for (var i = 0; i < data.length; i++) {

  var origin_long  = data[i][0][0];
  var origin_lat   = data[i][0][1];

  var destination_long = data[i][1][0];
  var destination_lat  = data[i][1][1];

   var prepare  =
        {origin: {
            latitude: origin_lat,
            longitude: origin_long
        },
        destination: {
            latitude: destination_lat,
            longitude: destination_long

      }};
  temp.push(prepare);
};

map.arc(temp,{strokeWidth: 2})


text:
Q: Resgatar o valor de uma variavel no VBA e colocar em uma celula no Excel Tenho uma variavel (um nome) declarada no VBA como faço para resgatar  este nome para colocar em uma célula de uma planilha Excel (se possível através de uma fórmula) Obrigado

A: O valor de uma variável é destruido após a execução de uma função. Para salvar o valor da mesma é necessário alocar esse valor em algum lugar como por exemplo em uma célula enquanto o código ainda está rodando.
Range("A1").Value = variavel


text:
Q: Why can't I have a two-level-deep inner class with the same name as its containing class? Today, some other developer found an XML schema with some interesting nesting, which JAXB compiled into a structure like this:
public class Choices
{
    public static class Choice
    {
        public static class Choice
        {
        }
    }
}

If you try to compile this, the Java compiler says,
class Choices.Choice is already defined in class Choices

with of course, the underline on the innermost class Choice declaration.
But I say, class Choices.Choice is not what it was trying to declare. Rather, it was trying to declare Choices.Choice.Choice, which would be a different class.
Interestingly, this is fine:
public class OuterClass
{
    public static class Inner1
    {
        public static class Inner2
        {
        }
    }

    public static class Inner2
    {
        public static class Inner1
        {
        }
    }
}

But this is banned:
public class OuterClass
{
    public static class Inner1
    {
        public static class Inner2
        {
            public static class Inner1
            {
            }
        }
    }
}

So I guess the rule is that the name of a class can't be the same as a containing class at any level. Obviously the fix here is already known- get JAXB not to generate invalid code.
But my question is, why is this restriction even present? What is the Java compiler trying to avoid by not letting us create an inner class with the same name as a containing class?

A: Java lets you refer to an outer class without fully specifying its name, like this:
public static class Inner1
{
    public static class Inner2
    {
        public static class Inner3
        {
            public void demo() {
                Class<Inner2> c = Inner2.class; // This is allowed
            }
        }
    }
}

Had nesting of classes allowed the use of identical names at any level of hierarchy, referencing by unqualified name would have been impossible. It is this ability that the Java compiler is trying to preserve by prohibiting nested declarations to collide with names of their outer classes.

A: Create a complexType,then refer to the 2nd level (of same name).  Use a different name, this will create a different class and satisfy java requirements.
i.e.
Choices = Choices.class
Choice  = Choice.class
Choice(2nd level) = InnerChoice.class
<complexType name = "innerChoice" >
  <sequence>
    .....
  </sequence>
</complexType>

 <element name="choices">
   <complexType>
     <sequence>
       <element name="choice">
         <complexType>
           <sequence>
             <!-- NEW! -->
             <element name="choice"  type="innerChoice">
             <!- This used to say
             <element name="choice">
               <complextype>
                <sequence>
                  ....
                </sequence>
               </complexType>
             -->
          .....

Now your generated class files will be Choices.Choice.InnerChoice which will be assigned to variable choice (variable names can be nested ok, not class names)


text:
Q: JSON stringify sporadically replaces separator with closing square bracket I am running a node.js script that culls through a directory and extracts any regex matches it finds, then pushes them onto an array. Once the query has run, I am stringifying the array into a standalone JSON file for safekeeping until it's needed.
I'm running into sporadic errors where the array in the JSON file is malformed and causes an error when I try to parse it out later on. It is sporadic, and I cannot determine a pattern, but every time (so far) the character that is causing the error is a closing square bracket - just like the one between the 2nd and 3rd elements below:
["first string","second string"]"third string"]
It's almost as if my array.push() is just adding another element onto the end of the existing array, and "forgetting" to change the closing square bracket to a comma...
I have searched, but cannot find references to a known error that would cause this. Has anyone seen this before?
Environment:
Node.js v19.0.0 | Ubuntu 22.04.1 LTS | Intel i7 processor
Here's my code for generating the JSON files:
const fs = require('fs');
const path = require('path');
const devPath = '/home/user/directory';
const activeReminder = [];

function buildArray() {
  let getFiles = fs.readdirSync(devPath);
  getFiles.forEach(file => {
    splitMD(file);
  });
}

function splitMD(file) {
  if (path.extname(file) == ".md" & file != {}) {
    let data = fs.readFileSync(file, 'utf8');
    const line = data.split(/\r?\n/);
     const match = line.find(element => {
        extractions(element, file);
    });
  }
};

function extractions(element, file) {
  if (element.includes("- [ ] reminder: ")) { //the - [ ] is markdown for Obsidian
    const datedReminder = "- [ ] [["+file+"]]" + element.split('- [ ] reminder:')[1]
    activeReminder.push(datedReminder);
    buildReminderJSON();
  }
}

function buildCcioJSON() {
  const reminderJSON = JSON.stringify(activeReminder);
  fs.writeFile("reminder.json", reminderJSON, 'utf8', function (err) {
    if (err) {
      console.log("Error while writing CCIO JSON:");
      return console.log(err);
    }
  })
}

buildArray();

module.exports = { buildArray };

A: I don't know what's causing the anomaly described above, but I created a script to correct it as a workaround until I can figure out a root cause. I'm running it as a crontab a few minutes after the crontab that creates the original array.
const fs = require('fs')
const path = require('path')
const devPath = '/home/user/directory'

function cleanup() {
    let getFiles = fs.readdirSync(devPath);
    getFiles.forEach(file => {
        splitJSON(file);
    });
  }

function splitJSON(file) {
  if (path.extname(file) == ".json" & file != {}) {
    let data = fs.readFileSync(file, 'utf8');
    const line = data.split(/\r?\n/);
     const match = line.find(element => {
        jsonCheck(element, file);
    });
  }
};

function jsonCheck(element, file) {
  if (element.includes("\"]\"")) {
    fs.readFile(file, 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        var result = data.replace(/\"\]\"/g, '","');
        fs.writeFile(file, result, 'utf8', function (err) {
           if (err) return console.log(err);
        });
      });
  }
}
cleanup();
module.exports = { cleanup };


text:
Q: How exactly does string slicing work in C++ (using string)? I have the following code:
string str1 = "first string";
string str2(str1, 6, 6)

// Output: string

*

*1st param points to the variable which has to be sliced

*2nd param tell the starting index (starting from 1)

*3rd param tells how many characters you want to take from str1 - basically the ending index

I understand all of the above. However, when I came across the below code block I got very confused.
Why does this work? It doesn't have 3 params.
string str3(str1.begin(), str1.begin() + 5); // Why no 3rd param ?
// Output: first

Also here, the 2nd param goes till the 5 index as opposed to starting from there (like in the first example). Can someone explain what's different b/w code blocks 1 and 2?
Thank you.

A: As @Ch3steR mentioned in the comment, they are all ctors(constructors), and that particular constructor takes two parameters.

*

*Parameter is an "iterator" that points to starting character

*Parameter is an "iterator" that points to end character.

Here is the link on bccnsoft docs:
a string of characters denoted by the start and end iterators
Here is the link on cppreference docs:
Constructs the string with the contents of the range (first, last)
Here is the link on cplusplus docs:
(7) range constructor


text:
Q: Clarification on FSM machine diagram
I have a simple state machine like the above. As far as, I looked over the online resources (example - x-sate) the state machine could have three different things "State", "Action Or Event" and "Side effect".
So Basically the event comes from outside of the state machine like User clicks, Reboot triggered etc., and the state machine should change its state based on those events. Also, each state could perform some side effects, but the side effect should not affect the state machine (for example, perform a cleanup task before Reboot)
Questions:

*

*Is it allowed for a state to perform some operations(side effects) which could change the state of the state machine(fetch A, B, C in the above diagram) without any external event or action?


text:
Q: Multiple checkboxes with same id but only one works So my idea is that when i check the checkbox every div named .picpic fades out(except the filtered ones) and when i uncheck they fade back in. The problem is that this jQuery code works only on the first checkbox. Thank you for your ideas.
Checkboxes
<form>
    <label>
      <input type="checkbox" id="selectedv" value="a1"/> a1 </label>

    <label>
      <input type="checkbox" id="selectedv" value="a2" /> a2 </label>

    <label>
      <input type="checkbox" id="selectedv" value="a3" /> a3 </label>

  </form>

jQuery
If checkbox is checked every .picpic div fades out except the filtered ones and when unchecked they fade back in.
if(document.getElementById('selectedv').checked) {
$('.picpic').not($filteredResults).fadeOut(1000)
} else {
    $('.picpic').fadeIn(1000)();
}
});

A: document.getElementById does just that: gets one element with that ID. The HTML specs don't allow you to have more than one element for any ID.
In this instance you could switch to class or name.

A: If you're going to style multiple elements using one text area try using classes rather than ids.

A: So i got the solution i wanted.

*

*Used classes instead of ID's because ID's are supposed to be unique.

*If checkbox is checked it makes every div except the filtered ones

*fade out. If every checkbox is checked all of the divs are showing.
Checkboxes
    <form>
        <label>
          <input type="checkbox" class="selected v" value="a1"/> a1 </label>

        <label>
          <input type="checkbox" class="selected a" value="a2" /> a2 </label>

        <label>
          <input type="checkbox" class="selected z" value="a3" /> a3 </label> <br>

</form>

jquery
 if($('input.selected').is(':checked')) {
        $('.picpic').not($filteredResults).fadeOut(1000)
        $($filteredResults).fadeIn(1000)()
        } else {
            $('.picpic').fadeIn(1000)();
    }

https://jsfiddle.net/01o2pawk/1/


text:
Q: "Harvesting" a graph Suppose we have a graph where each edge is paired with a pair of numbers (cost to travel down that edge,time to travel down that edge), and each vertex is paired with a pair of numbers (gain,time) where the time associated with each vertex is an integer representing the amount of moves on the graph before the gain can be collected again from that vertex.
When can an optimal circuit through the graph be formed (in terms of maximizing average profit/time)?


text:
Q: Not able to subscribe to Reports? Keeps giving error! I am getting following error when trying to subscribe to reports -
"We couldn't set up your subscription. Try subscribing again. If you still can't subscribe, ask your Salesforce admin for help."
I am doing the Lightning Experience Reports & Dashboards Specialist superbadge.

I checked/unchecked many reports related permissions on Profile, but it keeps giving this error.
I am not able to find why is this happening & its really frustrating as its the last step to complete the Superbadge.
Please help.

A: Finally found a solution to this weird problem.
I was not able to subscribe because storage limit was exceeded in my Developer Org.
Max limit is 5.0 MB and in my Org it was showing 6.2 MB.
So i deleted around 1000 records to bring size below 5.0 MB.
You can find it under Setup > Storage Usage.
And then I was able to subscribe Reports again.
Got to learn something new..!!


text:
Q: How to edit NSObject data I hava an NSObject class where I am saving my array data. I am displaying that array data in OutlineView. On click of button I am adding a new element under selected item. I want to add a new element inside array. Any help?
I am able to append new element at the end of the array but not under parent item(Selected item in outlineview).
@IBAction func CreateFolderClicked(_ sender: Any) {
    let newIndex = selectedItemIndex
    let parent = foldersOutlineView.item(atRow: selectedRow)
    if let Temp = parent as? objectData{
        folderArray.append(Temp)
        myOutlineView.insertItems(at: newIndex, inParent: Temp, withAnimation: .slideDown)
        myOutlineView.reloadData()
    }
}


text:
Q: Private Yammer Group Activity, Possible? Is it possible to post an Activity (as described here) to a Private Group?
I am currently posting a message but I would like to include some more meta information.


text:
Q: WooCommerce Order Status (Autocomplete orders) I am making a simple e-commerce website using WooCommerce plugin on Wordpress. I am using Paypal as my payment gateway. When user is purchasing product from my store and give payment successfully, WooCommerce should automatically change order status from 'pending' to 'completed', but it is not changing order status.
How can I achieve this?

A: This is a snippet code (that you can find in wooCommerce docs):

/**
 * Auto Complete all WooCommerce orders.
 */
add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order');
function custom_woocommerce_auto_complete_order( $order_id ) {
    if ( ! $order_id ) {
        return;
    }

    $order = wc_get_order( $order_id );
    $order->update_status( 'completed' );
}

But this snippet does not work for "BACS", "Pay on delivery" and "Cheque" payment methods. It's ok for Paypal and Credit Card gateways payment methods.

There is also a wordpress (woocommerce) free plugin working with all payment methods except some others Credit Card gateways payment methods:
Auto complete paid Orders (depending on Payment methods)
WooThemes - WooCommerce Autocomplete Orders
Regards