Q: what ruby gem should I use to handle tar archive manipulation? I need to download a tar.gz file, and replace a directory in it with the contents of another tar.gz file. So far, I've tried the following gems, and found them lacking

*

*archive-tar2: it lost the penultimate path separator ("/") so couldn't actually extract

*archive-tarsimple: simply didn't extract the compressed tarball, and returned no error msg

*minitar: ran into a bug where it failed for filepaths longer than 100 characters

*archive-tar-minitar - fails the same as its parent Errno::ENAMETOOLONG / File name too long

*libarchive: bundle install failed the gcc compile (even after successful brew install libarchive)

I'm starting to lose faith. Is there a good, up to date, well maintained tar archive gem that just works? I'd prefer one that doesn't call out to the command line, since I'd like to eliminate the possibility of commandline injection attacks. But at this point I'll take anything that avoids manually calling out to a shell.

A: You can also check out archive-tar-minitar, it is partially based on minitar that you already tested out, and it doesn't seem that it emmits calls to the command line.

A: I ended up giving up with using a gem to manipulate the tar archives, and just doing it by shelling out to the commandline.
`cd #{container} && tar xvfz sdk.tar.gz`
`cd #{container} && tar xvfz Wizard.tar.gz`

    #update the framework packaged with the wizard
    FileUtils.rm_rf(container + "/Wizard.app/Contents/Resources/SDK.bundle")
    FileUtils.rm_rf(container + "/Wizard.app/Contents/Resources/SDK.framework")
    FileUtils.mv(container +  "/resources/SDK.bundle", container + "/Wizard.app/Contents/Resources/")
    FileUtils.mv(container +  "/resources/SDK.framework", container + "/Wizard.app/Contents/Resources/")

    config_plist =  render_to_string({
             file: 'site/_wizard_config',
             layout: false,
             locals: { app_id: @version.app.id },
             formats: 'xml'
            })

File.open(container + "/Wizard.app/Contents/Resources/Configuration.plist", 'w') { |file| file.write( config_plist ) }

`cd #{container} && rm Wizard.tar.gz`
`cd #{container} && tar -cvf Wizard.tar 'Wizard.app'`
`cd #{container} && gzip Wizard.tar`

All these backticks make me feel like I'm writing Perl again.


Q: Generating unique IDs for multiple sources Consider N sources of data, each with a stream of events
Event{
    long id;
    Object data;
}

Some of the events within one stream might have the same id, as events might span across Updated, New etc. So we can see the following two streams:
<1, 2, 3, 1, 5, 2>
<3, 3, 4, 5, 4>

I would now like to combine these into one stream s.t. each order id is definitely going to be unique.
The easy way would be to use a String instead of long and append source number, generating sth like:
<"1 - 1", "1 - 2", "1 - 3", "2-3", "2-3" ... >

Is there a more memory coimpact way/better approach?

A: Your String solution is fine and in fact quite common. If you're interested in making it more compact, you may want to use a tuple of integers.
Another common method used in distributed systems is to use range allocation: have a central (singleton) server which allocates ranges in which each client can name its IDs. Such server could allocate, for example, the range 0-99 to client1, 100-199 to client2 etc. When a client exhausts the range it was allocated, it contacts the server again to allocate a new range.

A: Depending on the ranges of your stream/event numbers, you could combine the two numbers into a single int or long, placing the stream number in the top so many bits and the event number in the bottom so many bits. For example:
public static int getCombinedNo(int streamNo, int eventNo) {
    if (streamNo >= (1 << 16))
      throw new IllegalArgumentException("Stream no too big");
    if (eventNo >= (1 << 16))
      throw new IllegalArgumentException("Event no too big");
    return (streamNo << 16) | eventNo;
}

This will only use 4 bytes per int as opposed to in the order of (say) 50-ish bytes for a typical String of the type you mention. (In this case, it also assumes that neither stream nor event number will exceed 65535.)
But: your string solution is also nice and clear. Is memory really that tight that you can't spare an extra 50 bytes per event?


Q: Continous deployments for on prem databases with Azure DevOps Everyone, I'm looking on a way to deploy updates to our on prem databases using Azure DevOps and I'm running into a roadblock on the release definition.  I have my DACPAC ready to go, but not sure how to get that over to my on prem server.
I see the WinRM-SQL Server DB Deployment as a task, but not sure how to set that up.  I have seen a couple of videos that use the SQL Server Database Deploy as an option, but it looks like that task has been deprecated, so it looks like I will need to use the WinRM-SQL task.  So, could anyone point me in the right direction on how to set this task up to use my local SQL server or possibly a tutorial that help get me started?

A: You will also have to install a release agent on the target server where you will be deploying the database, assign it to a Deployment Group, create your release pipeline template and then run a release. I wrote a blog post about how to deploy a database to an on-prem SQL Server by leveraging Azure DevOps: https://jpvelasco.com/deploying-a-sql-server-database-onto-an-on-prem-server-using-azure-devops/
Hope this helps.

A: If you already created a Deployment Group, within your Pipeline:

*

*Click to Add a new stage: [1]: https://i.stack.imgur.com/vc5TI.png

*On the right side, (SELECT A TEMPLATE screen) type SQL in the search box

*Select: IIS website and SQL database deployment, this will add a Stage with Two tasks: IIS deployment and SQL DB Deploy.

*Delete the IIS Deployment Task

*Configure the SQL DB Deploy task - It does not say it is deprecated.


Q: how to insert data with laravel and ajax? I have this error:
http://localhost:8000/monthlyadd 500 (Internal Server Error)
error code:
message: "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'monthly_id' cannot be null (SQL: insert into `month_monthly` (`month_id`, `monthly_id`) values (1, ?))"

how to solve this error?
my controller code
   public function store(Request $request)
    {
        $monthly = new Monthly();
        $monthly->user_id = Auth::id();
        $monthly->result = $request->input('result');
        $monthly->problem = $request->input('problem');
        $monthly->suggestion = $request->input('suggestion');
        $monthly->months()->attach(request('month'));
        $monthly->years()->attach(request('year'));
        $monthly->save();
    }

js code:
<script>
      $(document).ready(function(){
          $('#addform').on('submit', function(e){
              e.preventDefault();
              $.ajax({
                  type: "post",
                  url: "/monthlyadd",
                  data: $('#addform').serialize(),
                  success: function(response){
                      console.log(response)
                      $('#exampleModal').modal('hide')
                      alert ("data seved")
                  },
                  error: function(error){
                      console.log(error)
                      alert ("data not seve")
                  }
              });
          });
      });
    </script>

route:
Route::post('/monthlyadd', 'MonthlyController@store');

modal monthly
public function months()
    {
        return $this->belongsToMany(Month::class);
    }

modal month:
  public function monthlies()
    {
        return $this->belongsTo(Monthly::class);
    }

A: your error is : monthly_id cannot be null
you can fix it by setting default value for it from your migration or phpmyadmin
or
in your store function set it to something:
$monthly->monthly_id= 'some-value';


Q: hasNextInt() From Scanner behaving weirdly I have a very simple loop that waits for a number (int) and as long as that number is not exitOption it does not leave the loop, however I get an unexpected error, and I don't know what's causing it.
Edit
Adding another snippet so you can compile
public static void main(String[] args) throws   FileNotFoundException,
                                                SecurityException,
                                                IOException,
                                                ClassNotFoundException {

    while (controller.selectOptionMM());

/Edit
public boolean selectOptionMM() throws  SecurityException,
                                        FileNotFoundException,
                                        IOException {

    int cmd = ui.getExitOption();

    ui.mainMenu();
    cmd = utils.readInteger(">>> "); // this is my problem, right here
                                     // code in next snippet
    while (cmd <1 || cmd > ui.getExitOption()) {
        System.out.println("Invalid command!");
        cmd = utils.readInteger(">>> ");
    }

    switch (cmd) {
    case 1:
    case 2:
    case 3:
    case 4: this.repository.close();
            return true;
    case 5: return false;
    }

    return false;
}

Here is what fails:
public int readInteger(String cmdPrompt) {
    int cmd = 0;
    Scanner input = new Scanner(System.in);

    System.out.printf(cmdPrompt);
    try {
        if (input.hasNextInt())
            cmd = input.nextInt(); // first time it works
            // Second time it does not allow me to input anything
                            // catches InputMissmatchException, does not print message
                            // for said catch
                            // infinitely prints "Invalid command" from previous snippet

    } catch (InputMismatchException ime) {
        System.out.println("InputMismatchException: " + ime);
    } catch (NoSuchElementException nsee) {
        System.out.println("NoSuchElementException: " + nsee);
    } catch (IllegalStateException ise) {

    } finally {
        input.close(); // not sure if I should test with if (input != null) THEN close
    }

    return cmd;
}

First time I pass trough, it reads the number no problem. Now if the number is not 5 (in this case exitOption), it passes again trough readInteger(String cmdPrompt) except this time it jumps to catch (InputMismatchException ime) (debug) except it does not print that message and just jumps to Error, input must be number and Invalid command.
Is something stuck in my input buffer, can I flush it, why is it (input buffer) stuck (with random data)???
I'll try debugging again and see what's stuck in my input buffer, if I can figure out how to see that.

A: The problem is in the call to input.close() - this causes the underlying input stream to be closed. When the input stream being closed is System.in, bad things happen (namely, you can't read from stdin any more). You should be OK just eliminating this line.

A:      input.hasNextInt()

This line throws the exception if there is no Integer, so instead of it going to else block it forward to catch block. It will never go to else block if exception get caught.


Q: Picking up correct cell value by mail script where ArrayFormula is applied I don't know anything about Google Scripts. All the scripts mentioned here under including the formulas have been researched on internet and improvised gradually. I need help of experts like you to achieve my outcomes. I am a beginner, hence please write your answer which I can understand. It would be great if you improve my script / formulas with brief explanation in simple language.
I have two sheets:
1) Form Response Sheet (linked to form)
2) DataBnak Sheet (importing form response data via query: =query('Form Responses 3'!$A:$BH,"",1)
I am using ArrayFormula in "DataBank" Sheet to create a unique text report based on values pulled  "Form Responses". This report needs to be emailed to each respondent upon form submit. the report is pulled in CH column thru (ArrayFormula), and once the mail is sent, I am marking "1" in CM column so to ensure duplicate mails are not sent every time the script runs.
=ArrayFormula(IF(ROW($B:$B)=1,"Breif Report",IF(ISBLANK($B:$B),"",if(NOT(ISBLANK($CM:$CM)),"",iferror(vlookup(BU:BU&BV:BV&BW:BW&BX:BX,BriefProfile!$E:$F,2,0),"")))))
Formula Explanation: where Cell in B column is not blank, and where cell in CM column is not blank (mail not sent), then bring the pre-written text based on the look-up value within columns (BU,BV,BW,BX).
What works correct:
1) The ArrayFormula works perfect (it pulls correct pre-written text)
2) Mail Script Works perfect (it sends to mails to those who have not been sent mail earlier)
What does not work:
1) The text report picked for a respondent is same for all respondents. When I remove ArrayFormula and ValuePaste the text report instead of calling it thru the formula mentioned above, then mail script picks up the correct unique report for each respondent and sends mail.
My mail script is mentioned below:
function sendEmails() { // Sends non-duplicate emails with data from the current spreadsheet.
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DataBank");
    var Avals = sheet.getRange("A1:A").getValues(); // helps getting last fillled row^
    var Alast = Avals.filter(String).length; // helps getting last fillled row^
    var startRow = 2; // First row of data to process
    var numRows = Alast-1; // Number of rows to process - last filled row^

    var dataRange = sheet.getRange(startRow, 1, numRows, 91);  // Fetch the range of cells A2:B3 //.getrange(row,column,numRows,numColumns) numColumns should equal to max column number where data process is required.

  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var emailAddress = row[1]; // second column, actual column minus one
    var message = row[85]; // 85th column, actual column minus one
    var emailSent = row[90]; // 90th column, actual column minus one
    if (emailSent !== EMAIL_SENT) { // Prevents sending duplicates
      var subject = row[84] //'Sending emails from a Spreadsheet';
      MailApp.sendEmail(emailAddress, subject, message);
      sheet.getRange(startRow + i, 91).setValue(EMAIL_SENT);
      Utilities.sleep(120000); // keeps the script waiting untill the sheet gets updated values from "ArrayFormula"
    }
SpreadsheetApp.flush(); // Make sure the cell is updated right away in case the script is interrupted
  }
}

Can you review my mail script and help me improve it so that it picks up correct unique report?

A: I just solved it. declaring var data = dataRange.getValues(); within the for loop solved my problem. I found the solution just now Thank you all!.
by declaring the variable before the for loop, I was actually storing the static data and the same was used in each iterations. When I declared the variable within for loop, the data started changing at each iteration.


Q: Django APscheduler prevent more workers running scheduled task I use APScheduler in Django, on Windows IIS to run my background script. Problem is, taks gets run multiple times. If I run same program on my PC, it only runs once, but when I upload to windows server (which hosts my Django app) it runs more times. I guess it has some connection with the number of workers? Job is scheduled, but each time job task is done, it's like it runs random number of instances. First 1 time, then 2, then 10, then again 2. Even tho I have 'replace_existing=True, coalesce= True, misfire_grace_time = 1, max_instances = 1'
planer_zad.py
from apscheduler.schedulers.background import BackgroundScheduler
from blog.views import cron_mail_overdue

def start():

scheduler.add_job(cron_mail_overdue, "cron", hour=7, minute=14, day_of_week='mon-sun', id="task002", replace_existing=True, coalesce= True, misfire_grace_time = 10, max_instances = 1)

scheduler.start()

apps.py
from django.apps import AppConfig

class BlogConfig(AppConfig):
    name = 'blog'

    def ready(self):
        #print('Starting Scheduler...')
        from .planer import planer_zad
        planer_zad.start()

For test I tried 'interval':
scheduler.add_job(cron_mail_overdue, "interval", minutes=1, id="task002", replace_existing=True, coalesce= True, misfire_grace_time = 10, max_instances = 1)

Tried:
    scheduler = BackgroundScheduler({
        'apscheduler.executors.default': {
            'class': 'apscheduler.executors.pool:ThreadPoolExecutor',
            'max_workers': '1'
        },
        'apscheduler.executors.processpool': {
            'type': 'processpool',
            'max_workers': '1'
        },
        'apscheduler.job_defaults.coalesce': 'True',
        'apscheduler.job_defaults.max_instances': '1',
        'apscheduler.timezone': 'UTC',
    })

scheduler.add_job(cron_mail_overdue, "cron", hour=9, minute=3, second=00, day_of_week='mon-sun', id="task002", replace_existing=True, coalesce= True, misfire_grace_time = 10, max_instances = 1)

scheduler.start()

Does not work. Sometimes it runs only once, then 12 times.

A: Just test if the object already exists in ready() :
# django/myapp/apps.py
from django.apps import AppConfig
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger

class BlogConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'blog'

    def __init__(self, app_name, app_module):
        super(BlogConfig, self).__init__(app_name, app_module)
        self.planer_zad = None

    def ready(self):
        if os.environ.get('RUN_MAIN', None) != 'true':
            return
        if self.planer_zad is None:
            background_scheduler = BackgroundScheduler()
            background_scheduler.add_job(task1, CronTrigger.from_crontab('* * * * *')) # Every minutes (debug).
            background_scheduler.start()
            return background_scheduler

    def task1(self):
        print("cron task is working")

You can then call it later :
# api.py
from django.apps import apps

@router.get("/background-task")
def background_task(request):
    """
        Run a background task.
    """
    user = request.user
    blog_config= apps.get_app_config('blog')
    background_scheduler = blog_config.background_scheduler
    return {"status": "Success", "True": str(background_scheduler)}


Q: Cannot delete rows in GridView(PosgtesQL) by _RowDeleting command I have asp.net web application, and i need to delete rows in my GridView1 which works with PostgreSQL. I need to delete rows, but i don't have to use ObjectDataSource. Here's my GridView1_RowDeleting method:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int ID2 = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);

        string constr = ConfigurationManager.ConnectionStrings["postgresConnectionString"].ConnectionString;
        using (NpgsqlConnection cn = new NpgsqlConnection(constr))
        {
            string query = "DELETE FROM mainpage WHERE id=@ID";
            NpgsqlCommand cmd = new NpgsqlCommand(query, cn);
            cmd.Parameters.Add("@ID2", NpgsqlDbType.Integer).Value = ID2;
            cn.Open();
            cmd.ExecuteNonQuery();
        }

And here's my GridView in .aspx file:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" Width="1650px" AutoGenerateDeleteButton="True" OnRowDeleting="GridView1_RowDeleting" >

Each time i'm clicking delete button i get error: "Index is out of range. The index must be a positive number, and its size should not exceed the size of the collection.
Parameter name: index".
   I think problem in my int Id.
   What i've tryed:
int ID = (int)GridView1.DataKeys[e.RowIndex].Value;
string ID = GridView1.DataKeys[e.RowIndex].Value.ToString(); and much more...

A: I think ArgumentOutOfRangeException occurred because you're not setting DataKeyNames attribute property on the grid, hence the row index is still out of bounds when calling e.RowIndex. You should set it to ID/primary key column name like this:
DataKeyNames="[ID or PK column name]"

Here is an example usage:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="id"
              AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None"
              Width="1650px" AutoGenerateDeleteButton="True" OnRowDeleting="GridView1_RowDeleting">
</asp:GridView>

Update 1
Additionally, I found parameter name mismatch on this query:
string query = "DELETE FROM mainpage WHERE id=@ID";
NpgsqlCommand cmd = new NpgsqlCommand(query, cn);
cmd.Parameters.Add("@ID2", NpgsqlDbType.Integer).Value = ID2;

The correct one should be like example below:
string query = "DELETE FROM mainpage WHERE id=@ID";
NpgsqlCommand cmd = new NpgsqlCommand(query, cn);
cmd.Parameters.Add("@ID", NpgsqlDbType.Integer).Value = ID2;

Reference: GridView.DataKeyNames Property


Q: Bigquery: Will switching from BQ sandbox to BQ paid will change 60 days data limit setup in sandbox Bigquery: Will switching from BQ sandbox to BQ paid will change 60 days data limit setup in sandbox.
Also, will I be able to export all GA4 data (last 1 year minimum) post switching to BQ paid?
currently we only have 60 days data in BQ sandbox and want to know if moving to BQ paid service will remove this limitation.
lso, will I be able to export all GA4 data (last 1 year minimum) post switching to BQ paid?

A: I'm not sure if the change from 60 days is automatic, you may have to change it manually.
Unfortunately, you can't export old data from GA4. Once you are out of the sandbox and have changed the data limit, you will start to get more days stored.


Q: How to open an existing file in a custom syscall and write to it I'm having some trouble opening and writing an existing file with a syscall. The syscall is set up correctly. The syscall itself takes in a file name as a char* but I keep getting errors
linux-2.6.22.19/mycall/mycall.c:24: undefined reference to `open'
linux-2.6.22.19/mycall/mycall.c:25: undefined reference to `write'
linux-2.6.22.19/mycall/mycall.c:26: undefined reference to `close'

What is the proper way to open and write to a file directly from a syscall if I am unable to use open, write, and close?


Q: R package `libs` directory too large after compilation to submit on CRAN I am the developer of the following package https://gitlab.inria.fr/gdurif/pCMF and I have a problem: the compiled library is too big.
When I check it with R CMD check, I get the following note regarding the size of the compiled library:

checking installed package size ... NOTE   installed size is 31.0Mb   sub-directories of 1Mb or more:
      libs  30.8Mb

My package is based on C++ code interfaced thanks to the package rcpp and heavily uses the algebra template library Eigen based on the package RcppEigen.
Since Eigen is templated, I think that the compiled library can become large. However, I would like to submit my package on the CRAN and I have no idea at all how I could solve this.
Thanks


Q: What is the expected behavoir when StreamBridge.send method returns false? I notice a lot of usage of the StreamBridge.send method in Spring Cloud Stream apps but none of them check its return value.
What is the expected behavior when the send method returns false? Should we do the retry if it returns false?
@OlegZhurakousky
Thanks!

A: It means that the channel.send() returned false. As for Should we do the retry, i don't know as I don't know your requirements.
Also, I would be interested why are you using StreamBridge? Indeed it is a component of s-c-stream, but 90% of what it does could be done in a more idiomatic way without it. In fact it was designed for one specific purpose, hence my interest.


Q: Sort a string to determine if it is a Anagram or Palindrome in Swift Xcode I have a extension names String, with two functions names isAnagramOf and isPalindrome. The first function is supposed to take input as a String, then first it will replace whitespace with no space then sort and compare the string and return a Bool to determine if anagram or not.
The second function named isPalindrome and will also ignore whitespaces and capitalization, it will then reverse the String and compare to return if it is reversed.
I am new to swift and following a tutorial, but I kept getting these errors no matter how I tried to write it. I have gone through it at least 10 times now and cant get it to work
If anyone can help with this code that would be great, I would also be open to someone showing me another way to write. Perhaps as a array first then to sort the string, I am not sure though.
extension String {
  func isAnagramOf(_ s: String) -> Bool {
    let lowerSelf = self.lowercased().replacingOccurrences(of: " ", with: "")
    let lowerOther = s.lowercased().replacingOccurrences(of: " ", with: "")
    return lowerSelf.sorted() == lowerOther.sorted()   // first error:Value of type 'String' has no member 'sorted
  }

  func isPalindrome() -> Bool {
    let f = self.lowercased().replacingOccurrences(of: " ", with: "")
    let s = String(describing: f.reversed())           //second error:Value of type 'String' has no member 'reversed'
    return f == s
  }
}

A: In Swift 3 a String itself is not a collection, so you have to
sort or reverse its characters view:
extension String {
    func isAnagramOf(_ s: String) -> Bool {
        let lowerSelf = self.lowercased().replacingOccurrences(of: " ", with: "")
        let lowerOther = s.lowercased().replacingOccurrences(of: " ", with: "")
        return lowerSelf.characters.sorted() == lowerOther.characters.sorted()
    }

    func isPalindrome() -> Bool {
        let f = self.lowercased().replacingOccurrences(of: " ", with: "")
        return f == String(f.characters.reversed())
    }
}

A slightly more efficient method to check for a palindrome is
extension String {
    func isPalindrome() -> Bool {
        let f = self.lowercased().replacingOccurrences(of: " ", with: "")
        return !zip(f.characters, f.characters.reversed()).contains(where: { $0 != $1 })
    }
}

because no new String is created, and the function "short-circuits",
i.e. returns as soon as a non-match is found.
In Swift 4 a String is collection of its characters, and
the code simplifies to
extension String {
    func isAnagramOf(_ s: String) -> Bool {
        let lowerSelf = self.lowercased().replacingOccurrences(of: " ", with: "")
        let lowerOther = s.lowercased().replacingOccurrences(of: " ", with: "")
        return lowerSelf.sorted() == lowerOther.sorted()
    }

    func isPalindrome() -> Bool {
        let f = self.lowercased().replacingOccurrences(of: " ", with: "")
        return !zip(f, f.reversed()).contains(where: { $0 != $1 })
    }
}

Note also that
let f = self.lowercased().replacingOccurrences(of: " ", with: "")

returns a string with all space characters removed. If you want
to remove all whitespace (spaces, tabulators, newlines, ...) then use
for example
let f = self.lowercased().replacingOccurrences(of: "\\s", with: "", options: .regularExpression)


Q: Selenium Expected Conditions - possible to use 'or'? I'm using Selenium 2 / WebDriver with the Python API, as follows:
from selenium.webdriver.support import expected_conditions as EC

# code that causes an ajax query to be run

WebDriverWait(driver, 10).until( EC.presence_of_element_located( \
    (By.CSS_SELECTOR, "div.some_result")));

I want to wait for either a result to be returned (div.some_result) or a "Not found" string. Is that possible? Kind of:
WebDriverWait(driver, 10).until( \
    EC.presence_of_element_located( \
         (By.CSS_SELECTOR, "div.some_result")) \
    or
    EC.presence_of_element_located( \
         (By.CSS_SELECTOR, "div.no_result")) \
);

I realise I could do this with a CSS selector (div.no_result, div.some_result), but is there a way to do it using the Selenium expected conditions method?

A: Ancient question but,
Consider how WedDriverWait works, in an example independent from selenium:
def is_even(n):
    return n % 2 == 0

x = 10

WebDriverWait(x, 5).until(is_even)

This will wait up to 5 seconds for is_even(x) to return True
now, WebDriverWait(7, 5).until(is_even) will take 5 seconds and them raise a TimeoutException
Turns out, you can return any non Falsy value and capture it:
def return_if_even(n):
    if n % 2 == 0:
        return n
    else:
        return False

x = 10
y = WebDriverWait(x, 5).until(return_if_even)
print(y) # >> 10

Now consider how the methods of EC works:
print(By.CSS_SELECTOR) # first note this is only a string
>> 'css selector'

cond = EC.presence_of_element_located( ('css selector', 'div.some_result') )
# this is only a function(*ish), and you can call it right away:

cond(driver)
# if element is in page, returns the element, raise an exception otherwise

You probably would want to try something like:
def presence_of_any_element_located(parent, *selectors):
    ecs = []
    for selector in selectors:
        ecs.append(
            EC.presence_of_element_located( ('css selector', selector) )
        )

     # Execute the 'EC' functions agains 'parent'
     ecs = [ec(parent) for ec in ecs]

     return any(ecs)

this WOULD work if EC.presence_of_element_located returned False when selector not found in parent, but it raises an exception, an easy-to-understand workaround would be:
def element_in_parent(parent, selector):
    matches = parent.find_elements_by_css_selector(selector)
    if len(matches) == 0:
        return False
    else:
        return matches

def any_element_in_parent(parent, *selectors):
    for selector in selectors:
        matches = element_in_parent(parent, selector)
        # if there is a match, return right away
        if matches:
            return matches
    # If list was exhausted
    return False

# let's try
any_element_in_parent(driver, 'div.some_result', 'div.no_result')
# if found in driver, will return matches, else, return False

# For convenience, let's make a version wich takes a tuple containing the arguments (either one works):
cond = lambda args: any_element_in_parent(*args)
cond( (driver, 'div.some_result', 'div.no_result') )
# exactly same result as above

# At last, wait up until 5 seconds for it
WebDriverWait((driver, 'div.some_result', 'div.no_result'), 5).until(cond)

My goal was to explain, artfulrobot already gave a snippet for general use of actual EC methods, just note that
class A(object):
    def __init__(...): pass
    def __call__(...): pass

Is just a more flexible way to define functions (actually, a 'function-like', but that's irrelevant in this context)

A: I did it like this:
class AnyEc:
    """ Use with WebDriverWait to combine expected_conditions
        in an OR.
    """
    def __init__(self, *args):
        self.ecs = args
    def __call__(self, driver):
        for fn in self.ecs:
            try:
                res = fn(driver)
                if res:
                    return True
                    # Or return res if you need the element found
            except:
                pass

Then call it like...
from selenium.webdriver.support import expected_conditions as EC
# ...
WebDriverWait(driver, 10).until( AnyEc(
    EC.presence_of_element_located(
         (By.CSS_SELECTOR, "div.some_result")),
    EC.presence_of_element_located(
         (By.CSS_SELECTOR, "div.no_result")) ))

Obviously it would be trivial to also implement an AllEc class likewise.
Nb. the try: block is odd. I was confused because some ECs return true/false while others will throw NoSuchElementException for False. The Exceptions are caught by WebDriverWait so my AnyEc thing was producing odd results because the first one to throw an exception meant AnyEc didn't proceed to the next test.

A: Not exactly through EC, but does achieve the same result - with a bonus.
Still using WebDriverWait's until() method, but passing the pure find_elements_*() methods inside a lambda expression:
WebDriverWait(driver, 10).until(lambda driver: driver.find_elements_by_id("id1") or \
                                               driver.find_elements_by_css_selector("#id2"))[0]

The find_elements_*() methods return a list of all matched elements, or an empty one if there aren't such - which is a a boolean false.  Thus if the first call doesn't find anything, the second is evaluated; that repeats until either of them finds a match, or the time runs out.
The bonus - as they return values, the index [0] at the end will actually return you the matched element - if you have any use for it, in the follow-up calls.

A: I did this and it worked fine for me:
WebDriverWait(driver, 10).until( EC.presence_of_element_located(By.XPATH, "//div[some_result] | //div[no_result]"));


Q: HippoMocks throws NotImplementedException when not specifying expectation I am investigating using mocking for unit tests I'm adding to existing code. For this I'm using HippoMocks. This involves another class calling some methods on my mock (that are all virtual). I want to avoid overspecifying all this but HippoMocks keep throwing NotImplementedException whenever the other class calls functions on my mock that I have not specified.
The below code exposes my issue.
void test()
{
    class SimpleClassToMock
    {
    public:
        virtual void memberFunction1() {}
        virtual void memberFunction2() {}
    };

    MockRepository mocks;
    // true or false here makes no difference.
    mocks.autoExpect = true;

    SimpleClassToMock* m = mocks.Mock<SimpleClassToMock>();
    // I care about this function getting called.
    mocks.ExpectCall(m, SimpleClassToMock::memberFunction1);

    m->memberFunction1();
    // HippoMocks fails on the next line by throwing NotImplementedException.
    m->memberFunction2();
}

Is there any way to tell HippoMocks not to fail here? I only want to specify the expectations for things I care about for a particular test, not every single thing that is called.
PS: To those that have mocking experience, am I thinking about this all wrong? Is overspecifying the test in cases such as this not a problem/"what you want"?

A: To avoid overspecifying, you can use OnCall to allow them to be called 0-N times (optionally with argument checks, order checks and so on).


Q: Changing the default cursor in sublime text3 - windows10 I am relatively new user of sublime so please consider helping me out,
I am aware that pressing the "insert" key in windows changes sublime into the overwrite mode
(with a underbar), and pressing "insert" again reverts it back to the "append" mode, and the vertical line cursor, discused here
My question - is there a way of changing the default cursor (append mode) to the underbar.
Any help is appreciated!
Thanks!
Please excuse me for any gramatical errors.

A: There is a way to modify the cursor, but it comes with a catch. The feature is only available in the Sublime Text "4" alpha builds, which you can only run if you're a registered user and willing to run alpha-level software, which means occasional random crashes and features not working right as the bugs get ironed out. You're also committing to upgrading to each new build as it's released and reporting issues back to the dev team. If you're interested, start at the Sublime Discord server here. The new builds are posted in #announcements.
You say you're a relatively new user, so I would not recommend running the alpha builds at this time, especially if it's just for this one feature.


Q: React Router, change path alternative of link element Is it possible to change route in react by react-router by other way than <Link></Link> ?
(e.g change route when onClick, or onKeydown event runs some function)

A: There is another way. You can use history.push in your code:
import { useHistory } from 'react-router-dom';

const YourComponent = () => {
  const history = useHistory();

  return <button onClick={() => history.push('/profile')}>Profile</button>;
};


Q: Unit testing function XPath query results? I'm having a little bit of a dilemma. I have a very basic class with functions returning specific XPath query results.
Here is the code I'm currently using.
[TestFixture]
public class MarketAtAGlance_Test
{
    private XmlDocument document;
    private MarketAtAGlance marketAtAGlance;

    [SetUp]
    public void setUp()
    {
        this.document = new XmlDocument();
        // load document from file located in the project
        this.marketAtAGlance = new MarketAtAGlance(document);
    }

    [Test]
    public void getHourlyImport_Test()
    {
        Assert.AreEqual(100.0d, marketAtAGlance.getHourlyImport());
    }

    [Test]
    public void getHourlyExport_Test()
    {
        Assert.AreEqual(1526.0d, marketAtAGlance.getHourlyExport());
    }
}

public class MarketAtAGlance
{
    XmlDocument document;

    public MarketAtAGlance(XmlDocument document)
    {
        this.document = document;
    }

    public double getHourlyImport() {
        double value = Convert.ToDouble(document.SelectSingleNode("//information[@id=\"dat11\"]/new_val").InnerText);

        return value;
    }

    public double getHourlyExport() {
        double value = Convert.ToDouble(document.SelectSingleNode("//information[@id=\"dat12\"]/new_val").InnerText);

        return value;
    }
}

This is my first use of unit testing so I'm still unsure of many minor things. As you can see, I'm loading a static XML file located on my hard drive. Should I have the extra dependency or put the XML text in a big string? I'm loading an older XML file (with the same format) because I can test with already known values.
Also, how would I go about unit testing an XmlHttpReader (class that takes in an XML url and loads it as a document?
Any comments on my question or comments about the design?

A: I would construct the XML in the test setup, but limit the XML to only what you need for the test to pass. It looks like your XML document could be very simple in this case.
<someRoot>
   <someNode>
        <information id='dat11'><new_val>100.0</new_val></information>
        <information id='dat12'><new_val>1526.0</new_val></information>
   </someNode>
 </someRoot>

That XML would pass your test.
I also wouldn't test the XmlHttpReader, if that is a system class. You could mock a dependency to it. You might need to wrap it with something to help you easily decouple it as dependency from your class.

A: For your first question, whether you should have a big XML string or load it from a file.  I would say either works.  To be honest though since you are loading from a file inside the project I would keep it in the project as an embedded resource and load it via reflection.  That would take the mess of file structure out of the picture if any of your colleages run it from their pc's.  The only best practice I've really encountered with Unit Tests is to make sure you're testing properly and make sure others can run the test easily.
For your second question, about the XmlHttpReader.  It would depend on your output.  If you can test that you have valid XML then go for it.  I would reccommend negative testing as well.  Point it to http://stackoverflow.com, or a URL you know will error out and decorate the test with the appropriate expected error.


Q: Failed to initiate service connection to simulator? When i install  AFNetworking pod file for connecting web service. After installation pod then run my program Xcode show message "unable to contact local DTServiceHub to bless simulated connection".
I help this link for error from stackoverflow but not solve issue.
I used: Xcode 8.2.1, OSX 10.11.6 and Objective-C.
Thanks in Advance.


Q: Maximum interval on react loop->addPeriodicTimer is 2147 seconds I'm running a timer using react\eventloop on my ratchet wamp app. I would like to have it run hourly at 3600 seconds, but for some reason if I set the interval higher than 2147 seconds I get this warning:
Warning: stream_select(): The microseconds parameter must be greater than 0 in C
:\wamp\www\vendor\react\event-loop\StreamSelectLoop.php on line 255

What's so special about 2147 seconds? And what can I do to bypass this contraint?
The Event Handler
class Pusher implements WampServerInterface, MessageComponentInterface {
    private $loop;
}

public function __construct(LoopInterface $loop) {
    $this->loop = $loop;

    $this->loop->addPeriodicTimer(2147, function() {
         //code
    });
}

public function onSubscribe(ConnectionInterface $conn, $topic) {}
public function onUnSubscribe(ConnectionInterface $conn, $topic) {}
public function onOpen(ConnectionInterface $conn) {}
public function onClose(ConnectionInterface $conn) {}
public function onCall(ConnectionInterface $conn, $id, $topic, array $params) {}
public function onPublish(ConnectionInterface $conn, $topic, $event {}
public function onError(ConnectionInterface $conn, \Exception $e) {}

The Server
$loop = Factory::create();

$webSock = new Server($loop);
$webSock->listen(8080, '0.0.0.0');

new IoServer(
    new HttpServer(
        new WsServer(
            new SessionProvider(
                new WampServer(
                    new Pusher($loop)),
                $sesshandler
            )
        )

    ),
    $webSock
);

$loop->run();

A: It is because of the limit of PHP integers on 32-bit platforms.
2147 (seconds) * 1000000 (microseconds in one second) ~= PHP_INT_MAX on 32-bit platforms.
On 64-bit platforms the limit would be ~ 300k years.
The strange thing is that React's React\EventLoop\StreamSelectLoop calls stream_select() only with microseconds parameter, while it also accepts seconds. Maybe they should fix this issue. As a workaround you could override StreamSelectLoop implementation so that it make use of $tv_sec parameter in stream_select().

I created a pull request, let's see if it will be accepted


Q: PHP Regex cut off space with preg_replace I have some string like this
Name xxx Product 1 Pc 100
Name Pci Product2Pc.200
Name Pcx Product 3 Pcs300

I want to turn PC to Price
And this is result that I want
Name xxx Product 1 Price 100
Name Pci Product 2 Price 200
Name Pcx Product 3 Price 300

At first I use
$pattern = array('/(\s*)Product(\s*)/', '/(\s*)(Pc\.?|Pcs)(\s*)/');

But it came to change all of my PC to Price
Name xxx Product 1 Price 100
Name Price i Product 2 Price 200
Name Price x Product 3 Price 300

This is my code now.
$pattern = array('/(\s*)Product(\s*)/', '/[^a-z](Pc\.?|Pcs)[^a-z]/');
$replacement = array(' Product ', ' Price ');
$title = preg_replace($pattern, $replacement, $title, -1);

But it result like this
Name xxx Product 1 Price 100
Name Pci Product Price 00
Name Pcx Product 3 Price 00

Thanks you.

A: Regex:
(Product)\s*(\d+)\s*Pc[.s]?\s*(\d+)

Replacement string:
$1 $2 Price $3

DEMO
$string = <<<EOT
Name xxx Product 1 Pc 100
Name Pci Product2Pc.200
Name Pcx Product 3 Pcs300
EOT;
$pattern = "~(Product)\s*(\d+)\s*Pc[.s]?\s*(\d+)~";
echo preg_replace($pattern, "$1 $2 Price $3", $string);

Output:
Name xxx Product 1 Price 100
Name Pci Product 2 Price 200
Name Pcx Product 3 Price 300

A: The reason your attempt is not working is because you are removing things that you don't want to.
You could use the following regular expression.
$title = <<<DATA
Name xxx Product 1 Pc 100
Name Pci Product2Pc.200
Name Pcx Product 3 Pcs300
DATA;

$title = preg_replace('/Product\K\s*(\d+)\D+(\d+)/', ' $1 Price $2', $title);
echo $title;

Output:
Name xxx Product 1 Price 100
Name Pci Product 2 Price 200
Name Pcx Product 3 Price 300


Q: Reading strings from file into dynamically allocated array in C I'm trying to learn C and can't seem to figure out how to read in strings from a file into an array.  I have a 2D array of chars as an array of strings and try to read those in by using malloc but I keep getting a SegFault.  Any tips on how to fix my code?
#include <stdio.h>
#define MAX_WORDS 10
#define MAX_WORD_SIZE 20

unsigned int getLine(char s[], unsigned int uint, FILE *stream);

int main( void ){

 FILE *infile1;
 unsigned int i = 0;
 unsigned int j = 0;
 unsigned int index;
 char c;

 char wordList[ MAX_WORDS+1 ][ MAX_WORD_SIZE + 1];

 infile1 = fopen("myFile.txt", "r");

 if (!(infile1 == NULL))
printf("fopen1 was successful!\n");

 while( (c = getc(infile1)) != EOF){
  while ((c = getc(infile1)) != ' '){
    wordList[i] = (char *)malloc(sizeof(char) );
        wordList[i][j] = getc(infile1);
        j++;
  }
  j = 0;
  i++;
}

printf("\nThe words:\n");
for (index = 0; index < i; ++index){
printf("%s\n", wordList[index]);
}

A: How are you compiling this.  The compiler should give you and error on the assignment:
wordList[i] = (char *)malloc(sizeof(char) );

The array wordlist is not of type char *
Also you are missing an include for malloc (stdlib.h probably) and you shouldn't be casting the return from malloc.

A: One obvious problem - you are allocating one char for wordList[i], then using it as if you had a character for each wordList[i][j].
You don't need to allocate any memory here, as you've defined wordlist as a 2 dimensional array rather than as an array of pointers or similar.
Next obvious problem - you are reading in characters and never providing an end of string, so if you ever got to the printf() at the end you are going to keep going until there happens to be a 0 somewhere in or after wordList[index] - or run off the end of memory, with a Segfault.
Next problem - do you intend to only detect EOF immediately after reading a space - AND throw away alternate characters?


Q: ListView - onContextItemSelected manipulate the item instead of toString As you can see in the code below, when I LongClick on an item in ListView, i get a popup menu with option to manipulate the item (delete, update, etc).
the problem is that I use my function on item.toString instead the item itself.
How can i get the item itself, and put it as an argument in my functions?
onCreateContextMenu:
public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    if (v.getId() == R.id.db_list_view) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_list, menu);
    }
}

onContextItemSelected:
public boolean onContextItemSelected(android.view.MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    Object obj = lv.getItemAtPosition(info.position);
    String nameToString = obj.toString();

    if (item.getTitle().equals("Delete")) {
        deletePlayerFromLongClick(nameToString);
    } else if (item.getTitle().equals("Update")) {
        updatePlayerFromLongClick(nameToString);
    } else if (item.getTitle().equals("Change Host/Guest")) {
        changeMembership(nameToString);
    }
    return true;
}

A: do like:
yourAdapter.getItem(info.position);

or
((YourAdapter)lv.getAdapter()).getItem(position);

or even simpler,
listOfItem.get(info.position);


Q: Checking for a Discourse topic title I have a ruby function that creates a discourse topic if the title is not found.
def get_topic(user,title,created_at,bumped_at,last_posted_at,excerpt)

  title = title.gsub(/  /,' ')
  puts "get_topic.title:'#{title}' user.id:#{user.id} created_at:#{created_at} last_posted_at:#{last_posted_at} excerpt:#{excerpt}"
  result = Topic.find_by_title(title)
  if result == nil then
    result = Topic.create
    result.title = title
    result.fancy_title = title
    result.user_id = user.id
    result.last_post_user_id = user.id
    result.updated_at = last_posted_at
    result.created_at = created_at
    result.bumped_at = bumped_at
    result.last_posted_at = last_posted_at
    result.excerpt = excerpt
    result.save!
  else
      puts result
      puts created_at,bumped_at,last_posted_at
      if result.user_id != user.id then
        result.user_id = user.id
        result.last_post_user_id = user.id
      end
      if result.updated_at != last_posted_at then
        result.updated_at = last_posted_at
      end
      if result.created_at != created_at then
        result.created_at = created_at
      end
      if result.bumped_at != bumped_at then
        result.bumped_at = bumped_at
      end
      if result.last_posted_at != last_posted_at then
        result.last_posted_at = last_posted_at
      end
      if result.excerpt != excerpt then
        result.excerpt = excerpt
      end
      if result.changed.length > 0 then
        result.save!
        puts result.slug
        post = result.first_post
        post.created_at = created_at
        post.updated_at = result.updated_at
        post.baked_at = result.bumped_at
        post.last_version_at = result.last_posted_at
        post.user_id = result.user_id
        post.last_editor_id = result.user_id
        post.raw = result.excerpt
        post.save!
        puts post
        #puts user.id
      end
  end
  puts "get_topic.result.slug:#{result.slug}"
  return result
end

Before the code creates a topic it searches for the title.
title = title.gsub(/ /,' ') result = Topic.find_by_title(title)
If a nil result occurs it then creates a topic.
It works for most topics, however, for one title it’s throwing ActiveRecord::RecordInvalid: Validation failed: Title has already been used when the topic is being saved.
The valiation settings for topic.title is
validates :title, if: Proc.new { |t| t.new_record? || t.title_changed? },
                    presence: true,
                    topic_title_length: true,
                    censored_words: true,
                    quality_title: { unless: :private_message? },
                    max_emojis: true,
                    unique_among: { unless: Proc.new { |t| (SiteSetting.allow_duplicate_topic_titles? || t.private_message?) },
                                    message: :has_already_been_used,
                                    allow_blank: true,
                                    case_sensitive: false,
                                    collection: Proc.new { Topic.listable_topics } }

I’ve checked in the console using Topic.find_by_title(‘title’). No topics exist with the title. I checked using Topic.find_by_sql("select * from topics where title like ‘start of title%’). No topics exist with the first word of the title.
What other checks can done … what could be causing the error saying the topic title has already been used when there are no topics found with that title?
Further information
I tried turning on allowing duplicate titles. The code ran through without an error yet there were no topics with the title that was causing the error after the import. Feels like the error message is wrong.


Q: Way to share task and results between Azure website and workers We need to change our system to a two-tiered structure on azure with an Azure website handling requests and adding tasks to a queue which will then be processed in priority order by a set of Azure worker roles. The website will then return the results to the end user. The data and results sets for each task will be largish (several megabytes). What's the best way to broker this exchange of data.
We could do it via an Azure storage blob but they are quite slow. Is there a better way? Up until now we have been doing everything in scaled azure website which allows all instances access to the same disk.

A: If this is a long-running process I doubt that using blob storage would add that much overhead, although you don't specify what the tasks are.
On Zudio long-running tasks update Table Storage tables with progress and completion status, and we use polling from the browser to check when a task has finished. In the case of a large result returning to the user, we provide a direct link with a shared access signature to the blob with the completion message, so they can download it directly from storage. We're looking at replacing the polling with SignalR running over Service Bus, and having the worker roles send updates directly to the client, but we haven't started that development work yet so I can't tell you how that will actually work.


Q: pass current browser url address to bean I want to send the browser url address to bean,I found this
HttpServletRequest requestObj = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
String url = requestObj.getRequestURL();

I did not get the right browser address,so I will use javasript window.location to get the browser address,but how can I send this to back bean?Every answers will be helpful,any ideas?

A: Use
FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap().get("referer")

in the back bean, you can have the request url. This bothers me for a long long time, hope this will help someone.


Q: How to upload an artifact to an Azure DevOps build using the API Can anyone shed some light on how to use the ADO API to upload an artifact to a build. I can't find an example that shows how to do this.
https://learn.microsoft.com/en-us/rest/api/azure/devops/build/artifacts/create
I know there is the vso task: ##vso[artifact.upload]local file path
But, I need to do this from another script and the vso task isn't available.
Thanks.


Q: Tkinter - the button I made doesn't work I have tried to make a following program: when opening the program, it shows an entry and a button labeled as '9'. Character '9' is added at the end of the entry when clicking the button '9'.
The code given below is I have written, but it doesn't work as I intended. The button doesn't work and the entry shows '09' rather than '0'.
# -*- coding : utf-8 -*-
import Tkinter as Tk
class calculator:
   def __init__(self, master):
       self.num = Tk.StringVar()
       self.opstate = None
       self.tempvar = 0

       # entry
       self.entry = Tk.Entry(root, textvariable = self.num, justify=Tk.RIGHT, width = 27)
       self.entry.pack(side = Tk.TOP)
       self.num.set("0")

       # Buttons
       self.numbuts = Tk.Frame(master)
       self.ins9 = Tk.Button(self.numbuts, text = "9", width = 3, command = self.fins(9))
       self.ins9.pack()

       self.numbuts.pack(side = Tk.LEFT)

   ##### Functions for Buttons #####
   def fins(self, x):
       self.entry.insert(Tk.END, str(x))

root = Tk.Tk()
calc = calculator(root)
root.mainloop()

I guess the part command = self.fins(9) is problematic but I don't know how to resolve it. Thanks for any help.

A: The code is passing the return value of the method call, not the method itself.
Pass a callback function using like following:
self.ins9 = Tk.Button(self.numbuts, text="9", width=3, command=lambda: self.fins(9))
                                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^


Q: How I can access Class method variable in instance method OR Use a common variable for both? I have this Class method to create a hero object.
+(id)hero
{
    NSArray *heroWalkingFrames;
    //Setup the array to hold the walking frames
    NSMutableArray *walkFrames = [NSMutableArray array];
    //Load the TextureAtlas for the hero
    SKTextureAtlas *heroAnimatedAtlas = [SKTextureAtlas atlasNamed:@"HeroImages"];
    //Load the animation frames from the TextureAtlas
    int numImages = (int)heroAnimatedAtlas.textureNames.count;
    for (int i=1; i <= numImages/2; i++) {
        NSString *textureName = [NSString stringWithFormat:@"hero%d", i];
        SKTexture *temp = [heroAnimatedAtlas textureNamed:textureName];
        [walkFrames addObject:temp];
    }
    heroWalkingFrames = walkFrames;
    //Create hero sprite, setup position in middle of the screen, and add to Scene
    SKTexture *temp = heroWalkingFrames[0];

    Hero *hero = [Hero spriteNodeWithTexture:temp];
    hero.name =@"Hero";
    hero.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:hero.size];
    hero.physicsBody.categoryBitMask = heroCategory;
    hero.physicsBody.categoryBitMask = obstacleCategory | groundCategory | homeCategory;
    return hero;
}

and I have another instance method to perform run animation for my hero.
-(void)Start
{
        SKAction *incrementRight = [SKAction moveByX:10 y:0 duration:.05];
        SKAction *moveRight = [SKAction repeatActionForever:incrementRight];
        [self runAction:moveRight];
}

now  heroWalkingFrames variable in Start method so I can perform animation, I want to add this line in Start method
 [SKAction repeatActionForever:[SKAction animateWithTextures:heroWalkingFrames timePerFrame:0.1f resize:NO restore:YES]];

Is there any way I can use this variable for both ?

A: Sure, in Hero.h add:
@property (nonatomic, retain) NSArray *walkingFrames;

Then, in your +(id)hero method, instead of declaring a new array NSArray *heroWalkingFrames, use:
+(id)hero
{
    //Setup the array to hold the walking frames
    NSMutableArray *walkFrames = [NSMutableArray array];
    //Load the TextureAtlas for the hero
    SKTextureAtlas *heroAnimatedAtlas = [SKTextureAtlas atlasNamed:@"HeroImages"];
    //Load the animation frames from the TextureAtlas
    int numImages = (int)heroAnimatedAtlas.textureNames.count;
    for (int i=1; i <= numImages/2; i++) {
        NSString *textureName = [NSString stringWithFormat:@"hero%d", i];
        SKTexture *temp = [heroAnimatedAtlas textureNamed:textureName];
        [walkFrames addObject:temp];
    }

    //We set hero texture to the first animation texture:
    Hero *hero = [Hero spriteNodeWithTexture:walkFrames[0]];
    // Set the hero property "walkingFrames"
    hero.walkingFrames = walkFrames;

    hero.name =@"Hero";
    hero.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:hero.size];
    hero.physicsBody.categoryBitMask = heroCategory;
    hero.physicsBody.categoryBitMask = obstacleCategory | groundCategory | homeCategory;
    return hero;
}


Q: Function template argument deduction with variadic class template as function call parameter All the examples are from here and here.
Specifically,
template<class...> struct Tuple { };
template<          class... Types> void g(Tuple<Types ...>);        // #1
// template<class T1, class... Types> void g(Tuple<T1, Types ...>);    // #2
template<class T1, class... Types> void g(Tuple<T1, Types& ...>);   // #3

g(Tuple<>());                     // calls #1
g(Tuple<int, float>());           // calls #2
g(Tuple<int, float&>());          // calls #3
g(Tuple<int>());                  // calls #3

With #2 uncommented, g()'s are resolved as described in the comments. What surprises me is that if I comment out the #2 line, the g()'s calls are resolved as follows:
g(Tuple<>());                     // calls #1
g(Tuple<int, float>());           // calls **#1 ???? why not #3????**
g(Tuple<int, float&>());          // calls #3
g(Tuple<int>());                  // calls #3

From the following examples and explanations below I can't see why g(Tuple<int, float>()); can't resolved to #3. It is the direction application of the following two rules:

If a parameter pack appears as the last P, then the type P is matched against the type A of each remaining argument of the call. Each match deduces the template arguments for the next position in the pack expansion.

template<class ... Types> void f(Types& ...);
void h(int x, float& y) {
const int z = x;
f(x, y, z); // P=Types&..., A1=x: deduces the first member of Types... to int
            // P=Types&..., A2=y: deduces the second member of Types... to float
            // P=Types&..., A3=z: deduces the third member of Types... to const int
           // calls f<int, float, const int>

If P has one of the forms that include a template parameter list <T> or <I>, then each element Pi of that template argument list is matched against the corresponding template argument Ai of its A. If the last Pi is a pack expansion, then its pattern is compared against each remaining argument in the template argument list of A. A trailing parameter pack that is not otherwise deduced, is deduced to an empty parameter pack.

A: There's a misconception here between your two examples. In the 2nd example with f, you are deducing reference arguments to a function. In the 1st example with g, you are deducing reference template parameters to an argument to a function. The latter must match exactly, but the former is deduced against the referred types. They are not the same.

In your fist example,
g(Tuple<int, float>());

cannot call g(Tuple<T1, Types&...>). The template deduction process is about picking a deduced argument type that is identical to the called argument type. There are some exceptions (for referenced cv-qualifications, pointers, derived classes, arrays, functions), but none of those apply here. We simply need to pick T1 and Types... such that Tuple<T1, Types&...> is the same type as Tuple<int, float>. This is impossible as there is no such pack Types... for which Types&... is {float}, since float is not a reference!
So once you comment out (2), there's only one viable candidate: (1).

On the other hand,
template<class ... Types> void f(Types& ...);
void h(int x, float& y) {
    const int z = x;
    f(x, y, z);
}

Here, Types&... is actually the type of the parameter itself (rather than a template argument of it), so (temp.deduct.call):

If P is a reference type, the type referred to by P is used for type deduction.

We deduce Types... to match the arguments. This succeeds because all the arguments are lvalues, and we simply pick {int, float, const int}.


Q: Xamarin ListView item click animation For some reason, i have this animation/effect by default when I press any items of my ListView (chat). I dont have any codes for that, it is just present/default.

Why is that? How can I turn it off or on?

A: It called "Ripple effect".
there are many related question in SO, see this https://stackoverflow.com/a/27237195/3814729 .


Q: R - Looping through Values in Variable and Dropping Duplicates Based on Condition I would like to loop through each unique value in the variable "Item" (i.e. A, B, C), and only keep the rows with the lowest ID number for each item, deleting the other rows for each corresponding item.
So, I have a data frame that looks like this right now:
Item    Cost    ID

A        4       1
A                3
B       39      10
B               18
B               21
C       290     15
C

And I want something that looks like this:
Item    Cost    ID

A        4       1
B       39      10
C       290     15

How do I do this?
(Thanks in advance - I'm new to R!)

A: your task is quite easy with dplyr, but there is a variety of approaches.
library(dplyr)
df %>% group_by(Item) %>% filter(ID == min(ID, na.rm = TRUE))

Source: local data frame [3 x 3]
Groups: Item [3]

    Item  Cost    ID
  <fctr> <dbl> <dbl>
1      A     4     1
2      B    39    10
3      C   290    15

Data used:
structure(list(Item = structure(c(1L, 1L, 2L, 2L, 2L, 3L, 3L), .Label = c("A",
"B", "C"), class = "factor"), Cost = c(4, NA, 39, NA, NA, 290,
NA), ID = c(1, 3, 10, 18, 21, 15, NA)), .Names = c("Item", "Cost",
"ID"), row.names = c(NA, -7L), class = "data.frame")


Q: jquery image change doesnt work The following code should work but I cant seem to find the problem why it doesnt work, I am testing it with google chrome

        <input id="unos" type="submit" name="change_src" value="change image" />

A:

        <input id="unos" type="submit" name="change_src" value="change image" />


Q: How to enable (or set up) MySQL to use "group commit"? I've read a lot of good reviews of MySQL Group Commit, which was broken in MySQL 4.x but was fixed in 5.1 and 5.5. See http://dev.mysql.com/doc/innodb/1.1/en/innodb-performance-group_commit.html
But I could not find any document showing how to enable (or set up) Group Commit in MySQL 5.5. The above link only says sync_binlog needs to be set to 0 for group commit to support binary log. But it does not mention any config variable to turn on group commit.
Maybe Group Commit is an internal optimization in MySQL that's always "enabled" without a user doing any explicit config change?


Q: Using MDX Correlation() function to find correlation of 2 dimentional members I'm trying to find the Pearson correlation of a single measure between two members of a dimension, but the msdn docs are a bit sparse.  Specifically I have a cube with a fact count measure, a date dimension, and a tool dimension and I'd like to find the correlation of tool X and tool Y over the date dimension.

A: take a look at the following script (Adventure Works DW 2008 R2):
It will return correlation of [Internet Sales Amount] measure for two different product subcategories ("Mountain Bikes"/"RoadBikes") for months of current date member on rows (Calendar Year 2007 quarters and Calendar Year 2007). I have left other comparable members in comments.
with
member ActualMeasure    AS  [Measures].[Internet Sales Amount]

member m1 AS
(
    [Product].[Product Categories].[Subcategory].&[1] -- Mountain Bikes
--  [Sales Territory].[Sales Territory].[Group].&[North America]
--  [Customer].[Gender].&[F]
    ,ActualMeasure
)
member m2 AS
(
    [Product].[Product Categories].[Subcategory].&[2] -- Road Bikes
--  [Sales Territory].[Sales Territory].[Group].&[Europe]
--  [Customer].[Gender].&[M]
    , ActualMeasure
)
member x as
Correlation
(
    {Descendants([Date].[Calendar].CurrentMember,[Date].[Calendar].[Month]) } as dates
    , m1
    , m2
), Format_String="Standard"

select
{   x,m1,m2 } on 0,
{
    Descendants
    (
        [Date].[Calendar].[Calendar Year].&[2007]
        , [Date].[Calendar].[Calendar Quarter]
    )
    ,[Date].[Calendar].[Calendar Year].&[2007]
} on 1
from [Adventure Works]

HTH,
Hrvoje Piasevoli


Q: find and replace string on a line I'm trying to make a find and replace on strings
?version(.*) -> ?versionMyVersionHere

ex :
<script src="js/script.js?versionSomeVersionHere"></script>
<script src="js/messages.js?version"></script>

<script src="js/script.js?versionMyVersionHere"></script>
<script src="js/messages.js?versionMyVersionHere"></script>

I've tried something like :
sed -i -e "s/\?version/?versionMyVersionHere/g" index.html

But it append the text to the one already present...
Thank you for taking the time to help me with this !

A: sed 's#\?version.*\"#\?versionMyVersionHere\"#g'

Demo :
$echo -e '<script src="js/script.js?versionSomeVersionHere"></script>
<script src="js/messages.js?version"></script>'  |  sed 's#\?version.*\"#\?versionMyVersionHere\"#g'
<script src="js/script.js?versionMyVersionHere"></script>
<script src="js/messages.js?versionMyVersionHere"></script>
$

A: You may use:
sed -i 's/?version"/?versionMyVersionHere"/' index.html

Details:

*

*? doesn't need to be escaped in default BRE.

*Make sure to match trailing " in order to avoid matching partial word.

A: If you want to substitute all all occurrences of ?version for substitute in your file index.html, then execute the following command:
sed -i 's/?version"/?versionMyVersionHere"/' index.html


Q: order_products column connected with Google Checkout transaction in osCommerce I am using Google Checkout with osCommerce and want to know which column of the order_products database table is connected with the transaction.
Google Checkout displays the price details of every product and I want to know from where in the code this detail comes from.

A: In osCommerce the payment modules have a method called process_button().
This method draws a form with the hidden fields the payment method needs. In the case of Google Checkout it will draw the fields needed by Google to show the information.
You can check in catalog/includes/modules/payment/<your Google Checkout module>.php that function to see which fields are sent to Google Checkout to show the information.


Q: NSIS - Detect drivers available and let the user decide where to install an specific file (the license of the software) What I need is:
After the software is installed, I need to identify the drivers available (Hard Disks, Pen Drives, etc), and the user can chose in which drive he wants to install the license of the software. When he chooses, a .txt file is created and it's written there the drive he choose (Example: C:).
My code without that feature is here:
  !include "MUI2.nsh"
  !define NOME "S-Monitor"

  Name "${NOME}"
  OutFile "${NOME}.exe"
  InstallDir "C:\${NOME}"

  ShowInstDetails show

;--- Paginas ---

  !define MUI_ICON Labels\SetupICO.ico

    !define MUI_HEADERIMAGE
    !define MUI_HEADERIMAGE_RIGHT
    !define MUI_HEADERIMAGE_BITMAP Labels\Header.bmp
    !define MUI_WELCOMEFINISHPAGE_BITMAP Labels\Left.bmp

  !insertmacro MUI_PAGE_WELCOME
  !insertmacro MUI_PAGE_DIRECTORY
  !insertmacro MUI_PAGE_INSTFILES

  !define MUI_FINISHPAGE_NOAUTOCLOSE
    !define MUI_FINISHPAGE_RUN
    !define MUI_FINISHPAGE_RUN_CHECKED
    !define MUI_FINISHPAGE_RUN_TEXT "Criar atalho na Área de Trabalho"
    !define MUI_FINISHPAGE_RUN_FUNCTION "AtalhoDesktop"

  !insertmacro MUI_PAGE_FINISH

;--- Idiomas ---

!insertmacro MUI_LANGUAGE "Portuguese"
!insertmacro MUI_LANGUAGE "English"
!insertmacro MUI_LANGUAGE "Spanish"

Function .onInit

  !insertmacro MUI_LANGDLL_DISPLAY

FunctionEnd

;--------------------------------
;Arquivos a serem instalados

Section "Instalacao"

SetShellVarContext all

  SetOutPath "$INSTDIR"
  File /r Ficheiros\*.* ; LOCALIZACAO DA APLICACAO DO S-MONITOR

SectionEnd

Function AtalhoDesktop
createShortCut "$DESKTOP\S-Monitor.lnk" "C:\SMonitor.exe"
FunctionEnd

A: The user smilepleeeaz helped me at another question, and that can also be used to answered this.
The code with the feature that I wanted is down below:
!include "MUI2.nsh"
  !include FileFunc.nsh
  !insertmacro GetDrives

  var newCheckBox

  !define NOME "S-Monitor"

  Name "${NOME}"
  OutFile "${NOME}.exe"
  InstallDir "C:\${NOME}"

  ShowInstDetails show
  AllowRootDirInstall true

;--- Paginas ---

  !define MUI_ICON Labels\SetupICO.ico

    !define MUI_HEADERIMAGE
    !define MUI_HEADERIMAGE_RIGHT
    !define MUI_HEADERIMAGE_BITMAP Labels\Header.bmp
    !define MUI_WELCOMEFINISHPAGE_BITMAP Labels\Left.bmp

  !insertmacro MUI_PAGE_WELCOME
  !insertmacro MUI_PAGE_DIRECTORY
  !insertmacro MUI_PAGE_INSTFILES
  Page Custom CustomCreate CustomLeave

  !define MUI_FINISHPAGE_NOAUTOCLOSE
    !define MUI_FINISHPAGE_RUN
    !define MUI_FINISHPAGE_RUN_CHECKED
    !define MUI_FINISHPAGE_RUN_TEXT "Criar atalho na Área de Trabalho"
    !define MUI_FINISHPAGE_RUN_FUNCTION "AtalhoDesktop"

!define MUI_PAGE_CUSTOMFUNCTION_SHOW showNewCheckbox
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE launchNewLink

  !insertmacro MUI_PAGE_FINISH

;--- Idiomas ---

!insertmacro MUI_LANGUAGE "Portuguese"
!insertmacro MUI_LANGUAGE "English"
!insertmacro MUI_LANGUAGE "Spanish"

Function .onInit

  !insertmacro MUI_LANGDLL_DISPLAY
  InitPluginsDir
         GetTempFileName $0
         Rename $0 '$PLUGINSDIR\custom.ini'

FunctionEnd

;--------------------------------
;Arquivos a serem instalados

Section "Instalacao"

SetShellVarContext all

  SetOutPath "$INSTDIR"
  File /r Ficheiros\*.* ; LOCALIZACAO DA APLICACAO DO S-MONITOR

  MessageBox MB_OK "O software BDE (Borland Database Engine) será instalado agora"
  ExecWait "Ficheiros\bde_install_Win7_32_e_64.exe"

  FileOpen $1 '$INSTDIR\S-monitor.cpy' w
  FileWrite $1 "CPY Location=C:\S-Monitor.cpy"
  FileClose $1

  writeUninstaller $INSTDIR\uninstall.exe

SectionEnd

Section "Uninstall"

MessageBox MB_YESNO "Deseja desinstalar o S-Monitor?" IDYES true IDNO false
true:
  SetShellVarContext all
  delete $INSTDIR\uninstall.exe
  RMDir /R /REBOOTOK $INSTDIR
  Goto +2
false:
MessageBox MB_OK "Desinstalação cancelada."
SectionEnd

Function AtalhoDesktop
createShortCut "$DESKTOP\S-Monitor.lnk" "C:\SMonitor.exe"
FunctionEnd

Function showNewCheckbox
${NSD_CreateCheckbox} 120u 110u 100% 10u "&Iniciar o S-Monitor ao terminar a instalação"
Pop $newCheckBox
FunctionEnd

Function launchNewLink
${NSD_GetState} $newCheckBox $0
${If} $0 <> 0
    Exec "C:\S-Monitor\Smonitor.exe"
${EndIf}
FunctionEnd

Function CustomCreate
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Settings' 'NumFields' '6'

         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Type' 'Label'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Left' '5'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Top' '5'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Right' '-6'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Bottom' '17'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Text' \
         'Selecione o drive a ser instalada a licensa do S-Monitor:'

         StrCpy $R2 0
         StrCpy $R0 ''
         ${GetDrives} "HDD+FDD" GetDrivesCallBack

         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Type' 'DropList'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Left' '30'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Top' '26'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Right' '-31'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Bottom' '100'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Flags' 'Notify'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'State' '$R1'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'ListItems' '$R0'

         push $0
         InstallOptions::Dialog '$PLUGINSDIR\custom.ini'
         pop $0
         pop $0
FunctionEnd

Function CustomLeave
        ReadIniStr $0 '$PLUGINSDIR\custom.ini' 'Settings' 'State'
        StrCmp $0 '2' 0 next
        ReadIniStr $0 '$PLUGINSDIR\custom.ini' 'Field 2' 'State'
        strcpy $R0  $0
        StrCpy $0 $0 3
        FileOpen $1 '$INSTDIR\S-monitor.cpy' w
        FileWrite $1 "CPY Location=$R0S-Monitor.cpy"
        FileClose $1

        Abort
     next:
        ReadIniStr $0 '$PLUGINSDIR\custom.ini' 'Field 2' 'State'
        StrCpy '$INSTDIR' '$0'
FunctionEnd

Function GetDrivesCallBack
         StrCmp $R2 '0' 0 next
         StrCpy $R3 '$R4'
         StrCpy $R1 '$9'
         IntOp $R2 $R2 + 1
      next:
         StrCpy $R0 '$R0$9|'
         Push $0
FunctionEnd


Q: How to measure distance between apple watch and iPhone? I know that core bluetooth is not available in watchOS2 so there is no way to read RSSI. But app like lookout released watch app that has a distance indicator. How did they do that? Any thought?

A: Using interactive messing pass mobile location to apple watch and calculate distance to shown on watch
Refer below apple link for communicating with the counterpart app
https://developer.apple.com/documentation/watchconnectivity/wcsession


Q: How to have make a div take a minumum of 50% space but if no sibling is present take 100% Simply put I have:
#Container {
display:'flex';
flex-wrap:'wrap';
}

.item {
flex-basis: '50%'
}

Scenario one:

 33 %

 33 %

 33%

Scenario 2

 50 %

 50 %

scenario 3:

 100 %

What I want in general tems is this to be fluid, the more items I put in the less space each item will have but if there is only 1 then I want it to take full space.

A: First you have to add display: flex; to #Container
#Container{
  display: flex;
}

If you want to equally distribute the space between children then you can use flex property as
.item{
  flex: 1;
}

Above CSS is minimum required styles, rest is for demo

#Container {
  display: flex;
  margin-top: 1rem;
}

.item {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1rem;
}

.item:nth-child(1) {
  background-color: red;
}

.item:nth-child(2) {
  background-color: blueviolet;
}

.item:nth-child(3) {
  background-color: aquamarine;
}

33 %

33 %

33 %

 50 %

 50 %

100 %

A: I think that this example could give you an idea of how to achieve what you want:
https://codepen.io/Eylen/pen/vYJBpMQ
.Container {
 display: flex;
 flex-wrap: wrap;
  margin-bottom: 8px;
}

.item {
  flex-grow: 1;
  margin: 0 12px;
  background: #f1f1f1;
}

Your main issue in the code that you gave, is that you're missing the flex item behaviour. I have just set that the item can grow to fill the space with the flex-grow:1.

A: You can make sure a flex child covers up the space if it can, you can provide flex-grow: 1

#Container {
  display:flex;
}

.item {
  width: 100%;
  flex-grow: 1;
  border: 1px solid;
  text-align: center;
}

 Scenario 1

33 %

33 %

33%

 Scenario 2

50 %

50 %

 Scenario 3

100 %

A: Added a demo below.

$( document ).ready(function() {
  $( "#add" ).click(function() {
    $('#container').append('

');
  });
   $( "#remove" ).click(function() {
    $('#container').children().last().remove();
  });
});
#container {
  width:100%;
  height:500px;
  background-color:#ebebeb;
  display:flex;
  flex-direction: column;
}

.item {
  width:100%;
  display: flex;
  flex: 1;
  border-bottom:1px solid #007cbe;
}
.item1 {
  background:#007cbe;
}
.item2 {
  background: #d60000;
}
.item3 {
  background: #938412
}

1

2

3

<button id="add"> Add

<button id="remove"> Remove

A: Apply to the below CSS to fulfill your requirement.
#Container {
    display: flex;
}

.item {
    width: 100%;
    min-height: 100px;
    border: 1px solid;
}


Q: Good practice for finding existing instance of a class from another class that is not a child I'm trying to develop simple TowerDefense game but
it seems like I miss the very basics of OOP as I encountered problem
must be somehow fixable as everyone programming in OOP must have
enountered it.
Here's very very basic structure
Game
|__ Map

Player
|__ UnitController

+ Block
+ Unit

So basically Map() controller creates 100 new Block() passing x and y coordinates to it
and stores information about those Blocks() inside a List<>. One of those Block is starting
position (it's still a Block object).
Now UnitController() has SpawnUnit() method. It creates new Unit() and it (here comes the problem)
has to put this unit instance ON the starting block. In order to do that, UnitController will have to
ask Map for starting position (that is a variable stored by Map) but.. How does the UnitController
can contact Map instance. The only way I see is that Map is a singleton and I simply can do Map.getStartingPos
otherwise if Map is not a singleton (thus instance) then how UnitController will find this instance?
I could pass this instance to UnitController when I was instantiating UnitController but that's not an option I guess
because there'll be tons of other examples in this game (for example Towers which attacks units, it has to find a unit and ...)
and I can't simply throw those instances all around the code?
thanks

A: Why are you against giving the UnitController a reference to its Map?
public UnitController {

    private final Map map;

    public UnitController(Map map) {
        this.map = map;
    }
}

Now your UnitController has a reference to the Map.  And this makes sense, if you think about it.  What units can be controlled without a map?  Shouldn't all UnitControllers have a Map on which they are controlling units?  It makes sense as a property, does it not?
You certainly don't want to make Map a singleton, as you suggest, as this sort of breaks the elegant object-orientedness of your model.  The whole point is to be able to have multiple Maps, on which multiple UnitControllers can be acting.  Restricting this to one run at a time, one Map at a time, makes the code much more procedural than object-oriented.
No matter what you do, the Map and the UnitController will have to have something in common in order to share data, even if you don't want them to have direct references to each other.
As far as "towers which attack the nearest unit" being a reason not to use this model, it doesn't make sense; a Tower ought to simply request the nearest unit from the Map object (i.e., map.getNearestUnit(int x, int y)).  No need for any more convoluted references, as long as everything can push and pull information from the Map.
For a more complicated example of the threaded Tower you're concerned with:
public class Tower extends Unit implements ActionListener {

    private final Timer fireTimer;
    private final Map map;
    private int damage;
    private int range;

    public Tower(Map map, int damage, int range, int fireRate) {
        this.map = map;
        this.damage = damage;
        this.range = range;
        fireTimer = new Timer(fireRate, this);
        fireTimer.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == fireTimer) {
            map.damageNearestUnit(this, range, damage);
        }
    }

}

... where the signature for map.damageNearestUnit is something like damageNearestUnit(Unit unit, int range, int damage).  This should essentially take the passed in Unit, get its coordinates, and find the nearest unit in the int range.  If one exists in range, deal the int damage to that other unit.  Then if the damaged Unit has less than 1 health, it should be removed from the Map, trigger a UI change, etc.
Actually, if I had simple getters and setters in my Tower and had my damageNearestUnit method assume that one unit was damaging another, I could simply have its signature be damageNearestUnit(Unit attacker).
I hope this shows how the Map is the fabric that binds everything else together and controls that which exists on it.


Q: how to check if x-staticmap-api-warning response header exists? I'm working on a project for school using the google static map api. There is a table with a list of locations. When you click on a location it brings up a modal window with the google map. If the api cannot find the location it just shows a map of water with an error. I noticed in the developer console under network there is a response header under the staticmap call titled x-staticmap-api-warning which contains the error.
Is there a way in javascript that can check if this response header exists so I can display a "Location unknown" message instead?


Q: Swift 3 CollectionView scaling I recently implemented a collection view in a app, the only problem I'm experiencing is that the collection view goes from 2 column to 1 column on smaller devices with a lot of padding on both sides
heres on a display smaller then a iPhone 6:

and heres how it looks on a display bigger or equal to a iPhone 6:

I did try several method where if the display width was smaller then a certain number it would scale up the cells, but it failed to work out because the cells where indeed scaled up but where not centered and over-lapping themselves.

A: You need to calculate your sizes depending on the phone size - if two cell's width are larger then screen size ( including all offsets between them ) they will layout as in the first picture.
You have two options:
One is to deal with sizes and rescale cells according to device size
Two leave it as is - Make small changes for iphone6/6s/7.
If you opt out for first one, you will need to set up constraint for these sizes - aspect ratio or center horizontally ( which could crop the image a little ).
For changing sizes dynamically, take a look at:
https://developer.apple.com/reference/uikit/uicollectionviewdelegateflowlayout
More specific:
https://developer.apple.com/reference/uikit/uicollectionviewdelegateflowlayout/1617708-collectionview

A:
You need to calculate the cell width.Try this code.

class YourClass: UIViewController {
        //MARK:-Outlets
        @IBOutlet weak var yourCollectionView: UICollectionView!

        //Mark:-Variables
        var cellWidth:CGFloat = 0
        var cellHeight:CGFloat = 0
        var spacing:CGFloat = 12
        var numberOfColumn:CGFloat = 2

        //MARK:-LifeCycle
        override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()

            yourCollectionView.contentInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)

            if let flowLayout = yourCollectionView.collectionViewLayout as? UICollectionViewFlowLayout{
                cellWidth = (yourCollectionView.frame.width  - (numberOfColumn + 1)*spacing)/numberOfColumn
               cellHeight = cellWidth //yourCellHeight = cellWidth if u want square cell
                flowLayout.minimumLineSpacing = spacing
                flowLayout.minimumInteritemSpacing = spacing
            }
        }

     extension YourClass:UICollectionViewDelegateFlowLayout{
            func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
                return CGSize(width: cellWidth, height: cellHeight)
            }
    }


Q: R How to take Median of Rows in Dataframe I am wondering if there is any way to a median of the rows in a data frame. I understand the function rowmeans exists, but I do not believe there is a row median function. I would like to store the results in a new column in the dataframe. Here is my example
I tried to look online. There was one mention of row medians, but I could not find the function in R.
 C1<-c(3,2,4,4,5)
   C2<-c(3,7,3,4,5)
   C3<-c(5,4,3,6,3)
   DF <- data.frame(ID=c("A","B","C","D","E"),C1=C1,C2=C2,C3=C3)

   DF

  # This is as far as I have gotten, but not streamlined

  MA <- median(C(3, 3, 5). na.rm = T)   # A
  MB <- median(C(2, 7, 4). na.rm = T)   # B
  MC <- median(C(4, 3, 3). na.rm = T)   # C
  MD <- median(C(4, 4, 6). na.rm = T)   # 4
  ME <- median(C(5, 5, 3). na.rm = T)   # E

  CM <- c(MA, MB, MC, MD, ME)C1<-c(3,2,4,4,5)

   ID C1 C2 C3
  1  A  3  3  5
  2  B  2  7  4
  3  C  4  3  3
  4  D  4  4  6
  5  E  5  5  3

   ID C1 C2 C3  CM
  1  A  3  3  5
  2  B  2  7  4
  3  C  4  3  3
  4  D  4  4  6
  5  E  5  5  3

Is there anyway I can streamline the process so it would be like DF$CM <- median(...

A: If you would like to use dplyr, you can find an example here, especially mpalanco's answer. Briefly, after using rowwise to indicate that the operation should be applied by row (rather than to the entire data frame, as by default), you can use mutate to calculate and name a new column off of a selection of existing columns. Check out the documentation on each of those functions for more details.
E.g.,
library(dplyr)

DF %>%
  rowwise() %>%
  mutate(CM = median(c(C1, C2, C3), na.rm = TRUE))

will yield the output:
# A tibble: 5 x 5
  ID       C1    C2    C3    CM
  <fct> <dbl> <dbl> <dbl> <dbl>
1 A         3     3     5     3
2 B         2     7     4     4
3 C         4     3     3     3
4 D         4     4     6     4
5 E         5     5     3     5

A: Just a little bit more flexible and up to date. We use c_across with rowwise function and it allows to use tidy-select semantics. Here we choose where to specify we only want the numeric column to calculate the median.
library(dplyr)

DF %>%
  rowwise() %>%
  mutate(med = median(c_across(where(is.numeric)), na.rm = TRUE))

# A tibble: 5 x 5
# Rowwise:
  ID       C1    C2    C3   med
  <chr> <dbl> <dbl> <dbl> <dbl>
1 A         3     3     5     3
2 B         2     7     4     4
3 C         4     3     3     3
4 D         4     4     6     4
5 E         5     5     3     5

A: To calculate the median of df, you can do the following
df$median = apply(df, 1, median, na.rm=T)

A: Oneliner that allows you to pick your desired columns:
apply(DF[, c("C1", "C2", "C3")], 1, median)

  ID C1 C2 C3 CM
1  A  3  3  5  3
2  B  2  7  4  4
3  C  4  3  3  3
4  D  4  4  6  4
5  E  5  5  3  5


Q: Akka-http: How do I map response to object Not sure if I'm getting this whole routing DSL thing right but here's the question. I want to do a post to external service such as:
val post = pathPrefix("somePath") {
  post {
    //get the response mapped to my Output object
  }
}

Then I want the response (which is a Json) to be mapped to an object matching the fields for example Output (assuming I have my JsonProtocol set up). How is this done?

A: You are using HTTP server directives to "retrieve" something "externally". This is what typically an HTTP client does.
For this sort of things, you can use akka http client api.
For example:
val response = Http().singleRequest(HttpRequest(uri = "http://akka.io"))
response onComplete {
  case Success(res) =>
    val entity = Unmarshal(res.entity).to[YourDomainObject]
    // use entity here
  case Failure(ex) =>  // do something here
}

However, this requires some Unmarshaller (to deserialize the received json). Take also a look at Json Support, as it helps you define marshallers easily:
case class YourDomainObject(id: String, name: String)
implicit val YourDomainObjectFormat = jsonFormat2(YourDomainObject)

A: I think what you are trying to ask is how to get the body i.e in JSOn format to the Case class that you have
Here is a quick example:
    path("createBot" / Segment) { tag: String =>
            post {
              decodeRequest {
                entity(as[CaseClassName]) { caseclassInstance: CaseClassName =>
                   val updatedAnswer = doSomeStuff(caseclassInstance)
                  complete {
                    "Done"
                  }
                }
          }

You can find more detailed example from here : https://github.com/InternityFoundation/Stackoverflowbots/blob/master/src/main/scala/in/internity/http/RestService.scala#L56
I hope it answers your question.


Q: Reading CSV file through Flask I'm currently trying to read through a CSV file that is being provided through Flask-WTF(orms) and I continue to run into issues when trying to load it through csv.DictReader or pandas.
The file (a FileStorage object) is not actually being uploaded anywhere, and I am trying to grab the data within the CSV to use within my code.
This is how I'm trying to grab it now using pandas
f = form.upload.data
data = pandas.read_csv(f.stream)
logger.debug(data)

However this returned the error pandas.errors.EmptyDataError: No columns to parse from file
When I tried grabbing it through csv.reader this way:
reader = csv.reader(f.read(), delimeter=',')

for row in reader:
    logger.debug(row)

I got this error instead: _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
I received a similar error when trying out csv.DictReader as well.
Has anyone tried to do anything similar to this, or know if this is even possible without uploading the file anywhere? I've looked around but I can't seem to find a proper solution.
For reference, my CSV file has a pretty basic format:
C1,C2
Data,Data

Thanks!


Q: Create Resource Group with Azure Management C# API Is there a way to create a Resource Group with the Azure Management C# API?
Basically this REST API call:
https://msdn.microsoft.com/en-us/library/azure/dn790525.aspx
I found a way to create an Affinity Group by using client.AffinityGroups.Create, but that's the closest thing I've found.

A: I found the API call was hidden in a library which is only in preview mode at the moment. It's found in the following NuGet package, enable include prerelease in Visual Studio to find it in the NuGet client.
https://www.nuget.org/packages/Microsoft.Azure.Management.Resources/
Then to create a resource group I can use
var credentials = new TokenCloudCredentials("", "");
var client = new Microsoft.Azure.Management.Resources.ResourceManagementClient(credentials);
var result = c.ResourceGroups.CreateOrUpdateAsync("MyResourceGroup", new Microsoft.Azure.Management.Resources.Models.ResourceGroup("West US"), new System.Threading.CancellationToken()).Result;

There is another stack overflow post explaining how to do the authentication:
How to get Tags of Azure ResourceManagementClient object
The following blog post explains how to set up TokenCloudCredentials, required for the authentication part, in more detail, but only for command line apps:
http://www.bradygaster.com/post/using-windows-azure-active-directory-to-authenticate-the-management-libraries
If you want to use something other than a command line app the following can work for authentication:
http://www.dushyantgill.com/blog/2015/05/23/developers-guide-to-auth-with-azure-resource-manager-api/

A: Go to https://resources.azure.com - the ARMExplorer shows both the REST and the PowerShell commands to create a resource group.  All the APIs are REST based.  In C#, send a WebClient request.


Q: Download handler (php code) is called multiple times for a single request I have a PHP script which handles the download requests. this script can be accessed by the client using a GET request like this (Javascript):
if (true)
{
  window.open('/download?mode=paper&fid=' + fid, '_blank');
  return;
}

And here is the (simplified) handler:
function downloadPaper($fid)
{
    // Adds a record to the database, but it seems to be called multiple times
    Daban\PaperTools::addPaperDownloadRecord($fid);

    header('Content-Description: File Transfer');
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=$fakeFileName");
    header('Content-Transfer-Encoding: binary');
    header('Connection: Keep-Alive');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header("Content-Length: " . filesize($file));

    $fh = fopen($file, "rb");
    while (!feof($fh))
    {
        echo fgets($fh);
        flush();
    }
    fclose($fh);
}

The problem is that according to the database, there are multiple download records for each download. In other words, the handler is called multiple times for a single request (or at least that is what I believe).
P.S. addPaperDownloadRecord() is jsut some piece of SQL code and it is not the culprit. I also checked the client side, it sends only once.

A: I managed to find the reason. If anyone has a similar problem, this may help. Since I had a download manager in my system, it sent multiple requests to divide the file in order to expedite the download process.


Q: User Generated Hyperlinks to Files Hosted on a Network Share My ultimate goal is to allow users to select a file from a dialog as if they are uploading a file.  Instead of file being saved to the server, a hyperlink will be generated from the file's path.  This hyperlink will then be used on our intranet page in order to open the file located on our network share.  Is there any practical way to accomplish this?
I have tried both an HTML file type insert and .Net's FileUpload Control but neither will work since for security reasons the full path of the file is never accessible.
The intranet site is built in VB.Net.

A: You would not be able to do this through a regular web page, since a web site gaining access to a file's path would be a gross security violation.  One thing you could do is have a control on your page where the server creates a file tree from browsing the network share.  Then the user would select the file path from this server-generated tree.

A: suppose your network share drive is the S: drive
if you use plain old file:// style URI's the links will auto open to your files on the share drive.
i.e. file://s:\techfiles\myfile.txt
in order to put the file on the share drive, you must be running that webapp on the share drive server(or have access to it), so just save that file off to the share server, then generate the path. The fact that the webapp server temporarily holds on to the file before storing it shouldn't bother you too much...


Q: php group array together based on key value being the same I have the following array
Array
(
[0] => Array
    (
        [id_product_option] => 1
        [id_option] => 1
        [id_product] => 3
        [option_value] => White
        [option_name] => color

    )

[1] => Array
    (
        [id_product_option] => 2
        [id_option] => 2
        [id_product] => 3
        [option_value] => 9oz
        [option_name] => size

    )

[2] => Array
    (
        [id_product_option] => 3
        [id_option] => 1
        [id_product] => 3
        [option_value] => Blue
        [option_name] => color

    )

)

What i need to do is loop through it and find the ones where the id_option values match and group them into a new array that should look like
Array
(
[0] => Array
    [0] => Array
        (
            [id_product_option] => 1
            [id_option] => 1
            [id_product] => 3
            [option_value] => White
            [additional_cost] => 0
            [is_active] => 1
            [created_on] => 2014-11-15 01:29:35
            [option_name] => color
            [option_text] => Color
        )

    [1] => Array
        (
            [id_product_option] => 3
            [id_option] => 1
            [id_product] => 3
            [option_value] => Blue
            [additional_cost] => 0
            [is_active] => 1
            [created_on] => 2014-11-15 01:29:35
            [option_name] => color
            [option_text] => Color
        )

[1] => Array
    (
        [id_product_option] => 2
        [id_option] => 2
        [id_product] => 3
        [option_value] => 9oz
        [additional_cost] => 0
        [is_active] => 1
        [created_on] => 2014-11-15 01:29:35
        [option_name] => size
        [option_text] => Size
    )

)

where the options with id_option 1 are grouped together
I tried the following but no luck
    $groupOptions = array();
    $prev = "";
    foreach($productOptions as $key=>$options) {
        $id_option = $options['id_option'];

        if($id_option != $prev) {
            $groupOptions[] = $productOptions[$key];
        }

        $prev = $id_option;
    }

A: You should use that id_option as the key in your new array, otherwise you're stuck having to hunt through the new array to find where the matching items are, which you're ALREADY doing in the first loop
$newarray = array();
foreach($oldarray as $item) {
   $newarray[$item['id_option']][] = $item;
}

A: I have tested with you example and seems to work fine :
$notFactored; # you should provide here your input array
$factored = array();
foreach($notFactored as $nf) {
    $found = FALSE;
    foreach($factored as &$f) { # passed by address !
        if(!empty($f[0]) && $nf['id_option'] == $f[0]['id_option']) {
            $f[] = $nf;
            $found = TRUE;
            break;
        }
    }
    if(!$found) {
        $factored[count($factored)][] = $nf;
    }
}
print 'my factored array : ' . print_r($factored);

Hope that Helps :)