text:
Q: A problem on $(a, b)$-homogeneous or simply homogeneous function Let $f$ be a real $(a, b)$-homogeneous or simply homogeneous function that means $f(ax)=bf(x)$ for $a,b>0$ and $0 \leq x  \leq \frac{1}{a}$. I want find this limit: $$\lim_{x\to0^+}f(x)$$

A: We'll need to impose some restriction on $f$ in order to have any chance of the limit existing. So in what follows we will assume $f$ is continuous. (Less restrictive assumptions might be made.)
First we rewrite the homogeneity relation in a more convenient form. Since the relation holds for $0 \le x \le 1/a$ we write $x=t/a$ and note that for $0 \le t \le 1$ we have the required inequality on $x$, and since $ax=t$ the relation now reads
$$[1]\ \ \ \ f(t)=bf(t/a),\ \ 0 \le t \le 1.$$
Now suppose $a<1$. Then the interval $[0,1]$ is partitioned by the powers of $a$ into subintervals $$...[a^3,a^2],\ [a^2,a],\ [a,1]$$ and the function $f$ is completely determined by its values on $[a,1]$, and may be arbitrary in that interval with the only restriction from $[1]$ being $f(a)=bf(1).$ Since $f$ is continuous we can let $m,M$ respectively be the minimum and maximum of $f(t)$ on the interval $[a,1].$ Now if $t \in [a^{k+1},a^k]$ the relation [1] gives $f(t)=b^kf(t')$ for some $t' \in [a,1]$. This gives
$$b^km \le f(t) \le b^kM.$$ So provided $b<1$ we may conclude that $\lim_{t \to 0+}f(t)=0,$ which implies $\lim_{x \to 0+}f(x)=0$ since $x=t/a.$
On the other hand, if $b>1$ and $m>0$ we arrive at $\lim_{t \to 0+}f(t)=\infty.$ And if all we assume is that the maximum $M>0$ we see that as $t \to 0^+$ the values of $f$ are unbounded, so again the limit fails to exist.
The case of $a>1$ has a similar way to work things out, with again the limit being $0$, or nonexistent depending on $m,M$, according to on which side of $1$ the number $b$ lies. There remain the cases of one of $a,b$ being $1$; these are not difficult to analyze. Note that if $a=b=1$ the relation says nothing about $f$.


text:
Q: Obtener n caracteres de un string con swift Necesito obtener los 4 primeros caracteres de un string en Swift.
¿Hay alguna función para ello?

A: La forma más simple es la siguiente:
var str = "Obtener n caracteres de un string con swift"

let index: String.Index = str.index(str.startIndex, offsetBy: 4)
var result: String = str.substring(to: index)

A: aqui te va una extension de string que también te puede venir bien
extension String {
    func subString(startIndex: Int, length: Int) -> String {

       //primero compruebo que tengo mas elementos del que me quiero posicionar
       if startIndex > self.characters.count{
        return self
       }
       let start = self.startIndex.advancedBy(startIndex)
       //he de comprobar que no quiera un rango mayor al que existe
       var end : Index = start
       if (startIndex + length) <= self.characters.count {
           end = self.startIndex.advancedBy(startIndex + length)
       } else {
           //me piden hasta la posicion x y no hay tantos caracteres. Devuelvo hasta el final de la cadena
           end = self.startIndex.advancedBy(self.characters.count)
       }

       let r = start ..< end
       return self.substringWithRange(r)
   }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get Text Between Tags From a Google Docs File I need a script that allows me to send each document contained in a folder to a specific email address. Inside every doc there is the email address to which that document needs to be sent.
The email address is incapsulated between two tags.
Example: <<example@example.com>>
I would like the script to search for the text contained between << and >> but I don't know how.
Is anyone able to help?
Thanks a lot!

A: From your following reply,

Each document is a Google Docs file. I need to extract the email address which is written in the body of the document, convert the document to PDF, and send it as an attachment to the email address extracted from the original Doc.

I believe your goal is as follows.

*

*You have a folder including Google Document files.

*Each Google Document has a text like <<example@example.com>>.

*You want to retrieve the email address of example@example.com from <<example@example.com>> in Google Document, and want to convert the Google Document to PDF format, and then, you want to send an email to the retrieved email address including the PDF file as an attachment file.

*You want to achieve this using Google Apps Script.

In this case, how about the following sample script?
Sample script:
Please copy and paste the following script to the script editor of Google Apps Script, and set the folder ID of your folder, and save the script.
function myFunction() {
  const folderId = "###"; // Please set your folder ID.

  const folder = DriveApp.getFolderById(folderId);
  const docs = folder.getFilesByType(MimeType.GOOGLE_DOCS);
  const token = ScriptApp.getOAuthToken();
  while (docs.hasNext()) {
    const file = docs.next();
    const id = file.getId();
    const doc = DocumentApp.openById(id);
    const obj = doc.getBody().getText().match(/<<(.+?)>>/);
    if (obj) {
      MailApp.sendEmail({ to: obj[1].trim(), subject: "sample subject", body: "sample body", attachments: [doc.getBlob()] });
    } else {
      console.log(`Email was not found in "${file.getName()}" document file.`);
    }
  }
}

*

*When this script is run, Google Document files are retrieved from the folder, and the email address is retrieved from the document body. And, the document is converted to PDF format, and an email is sent to the retrieved email address by including the PDF data.

*In this sample script, the subject and body of the email are the sample text. Please modify them for your actual situation.
Note:

*

*I thought that in this case, const pdf = doc.getBlob(); and const pdf = UrlFetchApp.fetch(`https://docs.google.com/feeds/download/documents/export/Export?exportFormat=pdf&id=${id}`, { headers: { authorization: "Bearer " + token } }).getBlob(); might be able to be used for converting to PDF format.

References:

*

*getFilesByType(mimeType)

*sendEmail(message)


text:
Q: Launching default apps with intents How, in android, do I start an app set as the default (i.e. Handcent for Messaging, Dolphin for browsing)?
I can only find how to use definite package names for intents:
Intent i = new Intent(Intent.ACTION_MAIN);
        i.addCategory(Intent.CATEGORY_LAUNCHER);

        switch (position) {
        case 0: //messages
            i.setPackage("com.android.mms");
            break;
        case 1: //inbox
            i.setPackage("com.android.email");
            break;
        case 2: //browser
            i.setPackage("com.android.browser");
        default:
            i = null;
        }

A:
How, in android, do I start an app set as the default (i.e. Handcent for Messaging, Dolphin for browsing)?

"Default" is for a specific operation (e.g., sending a message), not for some abstract notion of "Messaging" in general.
Also, the code you are showing above uses things that are not in the SDK (namely, specific packages). Your code will break on some devices, where the device manufacturer has replaced the app. Your code may break in future versions of Android, when the stock apps are refactored or otherwise renamed.
I think you need to reconsider what it is you are trying to accomplish.

A: You can search for apps that satisfy a given Intent (e.g., ACTION_SEND), decide which one you want, retrieve its component name, and then launch it with a different Intent that specifies the component name.
Start with:
Intent intent = new Intent(...);
List<ResolveInfo> list = getPackageManager().queryIntentActivities(
    intent, PackageManager.MATCH_DEFAULT_ONLY);


text:
Q: Vue.js Failed to mount component: template or render function not defined I'm learning to use Vue.js with Laravel from this series the narrator doesn't get any error but I've encountered the following error while I click to change the route.

[Vue warn]: Failed to mount component: template or render function not defined.

Below code is from my app.js:

require('./bootstrap');

window.Vue = require('vue');

import VueRouter from 'vue-router'
Vue.use(VueRouter)

let routes = [{
    path: '/dashboard',
    component: require('./components/Dashboard.vue')
  },
  {
    path: '/profile',
    component: require('./components/Profile.vue')
  }
]

const router = new VueRouter({
  routes
})

Vue.component('example-component', require('./components/ExampleComponent.vue'));

const app = new Vue({
  el: '#app',
  router
});

Code snippet from my Dashboard.vue:

<template>

Dashboard Component

                        I'm an example component.

</template>

Code snippet from my master.blade.php layout:

//sidebar

    <router-link to="/dashboard" class="nav-link">Dashboard

    <router-link to="/profile" class="nav-link">Profile

//content

  <router-view></router-view>

I'm running app at localhost:3000with browserSync and npm run watch. Does it has anything to do with error ?

A: Try adding .default to your component requires:
let routes = [{
    path: '/dashboard',
    component: require('./components/Dashboard.vue').default
  },
  {
    path: '/profile',
    component: require('./components/Profile.vue').default
  }
]

A: While not applicable to the specifics of this question, the error message above can also be encountered when failing to wrap one's HTML in <template>...</template> tags. This would cause vue to not detect a template, as none has been defined via tags or object properties.
For example, within Dashboard.vue, if one were to write (within Dashboard.vue):

Dashboard Component

                    I'm an example component.

rather than:
<template>

Dashboard Component

                        I'm an example component.

</template>

one would receive the error message: Vue.js Failed to mount component: template or render function not defined

A: // Just add "import Vue from 'vue'" and the component will be shown !

require('./bootstrap');

window.Vue = require('vue');

import VueRouter from 'vue-router'
Vue.use(VueRouter)

let routes = [{
    path: '/dashboard',
    component: require('./components/Dashboard.vue')
  },
  {
    path: '/profile',
    component: require('./components/Profile.vue')
  }
]

const router = new VueRouter({
  routes
})

Vue.component('example-component', require('./components/ExampleComponent.vue'));

const app = new Vue({
  el: '#app',
  router
});

A: This was bugging me for so long, the change is so small that I could barely notice it in two different router files, among which one works, one doesn't.
Instead of
let routes = [{
    path: '/dashboard',
    component: require('./components/Dashboard.vue')
  }]

you should use
let routes = [{
        path: '/dashboard',
        component:()=> import('./components/Dashboard.vue')
      }]

The point is component property will also accept a function, and in that function, you can return an imported component which will only be called when it is required. If you give require() directly, it is imported immediately.


text:
Q: Regex: how to separate parsed elements without mixing the output I have the following two use cases of parsing an expression inside a SQL query:

*

*[some_date:week] should result in week. week here is one of a few keywords that are known in advance.

*[some_expression|condition] should result in 1 or any other unrelated character, doesn't matter here.

I first came up with a following regex:
r"\[(.*)\:(sec|min|hour|day|date|week|month|year|aggregate)\]"

However, it is not working properly when there's multiple occurrences of such an expression.
I then only found a way to limit the length of expressions inside brackets using {,30} so for the second use case it becomes:
r"\[.{,30}\|.{,30}\]"

I don't feel that this is an optimal way to do it and looking forward to your suggestions!
Edit: here's some examples of how it works now and how it should work.
txt = """select [first:week] as time,
                [next:month] as date
         from table"""

exp = r"\[(.*)\:(sec|min|hour|day|date|week|month|year|aggregate)\]"

print(re.sub(exp, r"\1", txt, flags = re.S|re.I))

>>  select first:week] as time,
           [next as date
    from table

Should be:
    select first as time,
           next as date
    from table

A: You may use
r"\[([^][:]*):(sec|min|hour|day|date|week|month|year|aggregate)]"

See the regex demo.
The main point is to use [^][:]* - any zero or more characters other than ], [ and : - instead of .*.
Note that .*? won't work here either: if there is a non-matching substring between two matching ones, the first match will be longer than expected.


text:
Q: Unable to store data via mysqli_connect Hey guys currently I'm trying to create a login activity for android application and I have no idea why the user data is not stored upon registration. Is there something wrong with the php files as shown below?
Register.php stores registration for users
<?php
    $con = mysqli_connect("mysql13.000webhost.com", "a1641537_fetch", "password", "a1641537_fetchdb");

    $name = $_POST["name"];
    $username = $_POST["username"];
    $password = $_POST["password"];

    $statement = mysqli_prepare($con, "INSERT INTO Fetch (name, username, password) VALUES (?, ?, ?) ");

    mysqli_stmt_bind_param($statement, "sss", $name, $username, $password);
    mysqli_stmt_execute($statement);

    mysqli_stmt_close($statement);

    mysqli_close($con);
?>

FetchUserData.php fetches username and password of a user.
<?php
    $con = mysqli_connect("mysql13.000webhost.com", "a1641537_fetch", "password", "a1641537_fetchdb");

    $username = $_POST["username"];
    $password = $_POST["password"];

    $statement = mysqli_prepare($con, "SELECT * FROM Fetch WHERE username = ? AND password = ?");
    mysqli_stmt_bind_param($statement, "ss", $username, $password);
    mysqli_stmt_execute($statement);

    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $name, $username, $password);

    $user = array();

    while(mysqli_stmt_fetch($statement)) {
        $user[name] = $name;
        $user[username] = $username;
        $user[password] = $password;
    }

    echo json_encode($user);

    mysqli_stmt_close($statement);

    mysqli_close($con);
?>

A: fetch is a reserved word in mysql so you need to quote it in backticks.
For example:
$statement = mysqli_prepare($con, "INSERT INTO `Fetch` (name, username, password) VALUES (?, ?, ?) ");

To catch these kinds of mistakes, it is useful to add error handling. I prefer to do that by having msyqli throw an exception when anything goes wrong.
To activate that, just add mysqli_report(MYSQLI_REPORT_STRICT); to the top of your script and make sure that errors are displayed.
If you don't add any try - catch blocks yourself, php will show you a detailed unhandled exception error when a problem occurs so you can take it from there. Obviously in live code this is not the preferred way to handle that.


text:
Q: Gitlab DNS Entry For Kubernetes Setup? I have a n00b question about setting up gitlab on a kubernetes.  I'm running a basic minkube cluster on my home machine and I want to install gitlab onto it.  The setup instructions note the following prequesite:

The ability to point a DNS entry or URL at your GitLab install

How do I do this?  What is the basic mechanism for setting up a "DNS entry" on a home machine running minikube?  There example shows:

externalUrl: 'http://gitlab.example.com'

If I own a domain how would I set this up?  Why does the setup need an external URL?
Thank you in advance for you consideration and response.

A: You'll be setting it up with a nodeport and can access it normally through that. If you really want a DNS entry you can just add one in your hosts file at /etc/hosts:
[minikube ip] myfakelocalgitlabendpoint.com

You can get minikube's IP by running minikube ip.


text:
Q: ASP.NET MVC FileContentResult download file in jquery ajax From my view I make a GET call with ajax jquery to my controller, which returns a FileContentResult this is an excel file what it returns. The file is created instantly, it is not on the server, I cannot pass a url to download the file since it does not exist.
It works for me if I return the FileContentResult from the controller, but on the page the user does not know when the download will finish or if it continues to download, I need to know if the download is still in progress and if the download has finished. I can't show a popup because I don't know if the download continues, I only know that the file has been downloaded when I see it in my browser downloaded.
Controller code:
DataTable table = new DataTable("MyExcel");
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.ContentType = contentType;
Response.AddHeader("Content-disposition", "attachment; filename=MyExcel.xlsx");
return File(Utils.XLS(table), contentType, "MyExcel.xlsx");

**Utils.XLS(table):** this function return byte[] from table

The excel file is generated correctly, I have checked.
When the call Ajax is finished I retrieve the data and do the following:
$.get(url, function (data, status, xhr) {
    var contentType = xhr.getResponseHeader("Content-Type");
    var filename = xhr.getResponseHeader("Content-disposition");
    filename = filename.substring(filename.lastIndexOf("=") + 1);
    var blob = new Blob([data], {
             type: contentType
    );
    var url = URL.createObjectURL(blob);
    var link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
});

The excel file downloads successfully but appears corrupted and does not contain any information inside.
I have tried many ways that I have been finding but none have worked for me.
Solution
In the request of the ajax request you have to add the responsetype 'arrayBuffer'
var xhrOverride = new XMLHttpRequest();
xhrOverride.responseType = 'arraybuffer';

$.ajax({
     url: url,
     method: 'POST',
     xhr: function () {
          return xhrOverride;
     }
}).done(function (data, status, xhr) {
   //request correct
}


text:
Q: Create a Countdown Timer in Silverlight I want to have a counter that counts down from 60 seconds to 0. I want the user to see the number of seconds on the UI. To accomplish this, I thought I would display a basic TextBlock like such:
<StackPanel>
  <TextBlock Text=" " />
  <TextBlock Text=" seconds remaining" />
</StackPanel>

I then was thinking of using a Timer. The only timer I'm aware of though is the DispatcherTimer. However, that doesn't show how much time has elapsed or how much time is remaining. Because of this, I have nothing to bind to.
private DispatcherTimer myTimer = new DispatcherTimer();
public MainPage() {
  myTimer.Interval = new TimeSpan(0, 0, 60);
  myTimer.Tick += new EventHandler(myTimer_Tick);
  myTimer.Start();
}

I'm not sure how to do this. A co-worker told me that I shouldn't even do this because it will slow down the UI. But the users really want it. Can somebody tell me:
1) Will it really bog down the UI that much?
2) If not, how do I do this?
Thanks!

A: *

*Yes. It will slow it down by an imperceivable amount. Frankly, it would be absolutely ridiculous to be worried about this.

*On every tick, decrement a property. Bind your UI to that property. Alternatively, simply invalidate a property on every tick, and have the property getter calculate the time remaining.
Option 1
myTimer.Interval = TimeSpan.FromSeconds(1);
myTimer.Tick += delegate
{
    this.SecondsRemaining = this.SecondsRemaining - 1;

    if (this.SecondsRemaining == 0)
    {
        myTimer.Dispose();
    }
};
this.SecondsRemaining = 60;
myTimer.Start();

...

// assumes your class implements INotifyPropertyChanged and you have a helper method to raise OnPropertyChanged
public int SecondsRemaining
{
    get { return this.secondsRemaining; }
    private set
    {
        this.secondsRemaining = value;
        this.OnPropertyChanged(() => this.SecondsRemaining);
    }
}

Option 2
myTimer.Interval = TimeSpan.FromSeconds(1);
myTimer.Tick += delegate
{
    this.OnPropertyChanged("TimeRemaining");

    if (this.TimeRemaining <= 0)
    {
        myTimer.Dispose();
    }
};
this.endTime = DateTime.UtcNow.AddMinutes(1);
myTimer.Start();

public int TimeRemaining
{
    get { return (endTime - DateTime.UtcNow).TotalSeconds; }
}

A: No it should not bog the UI down since it will be firing every second; sample on how to do this can be found here.
In addition you could also use a Storyboard which runs for your specified time frame and adjusts a UI component accordingly however I would not recommended that approach.


text:
Q: sort Python dictionary with two keys I have a python dictionary of this form:
text.items()[: 2]
[(('id','id1'), text', ('id','id1'), 'text', ('id','id1'), 'text')]

and i would like to sort it by id1. Any help?

A: Assuming the dictionary.items returns:
items = [(('id','id1'), 'text'), (('id','id1'), 'text'), (('id','id1'), 'text')]

you can sort by the first element of the the tuple by doing:
items.sort(key=lambda item: item[0][0])

A: A Python dictionary is unordered and therefore can't be sorted. However as you seem to understand, it is possible to sort the value returned from itsitems()oriteritems()methods. If the keys of the dictionary were tuples as shown in your example, and you wanted to sort on the second value in each one of them,  here's an efficient way to do it:
text = {('idA','id2'): 'text',
        ('idB','id1'): 'text',
        ('idC','id3'): 'text',}

print sorted(text.iteritems(), key=lambda item: item[0][1])

Output:
[(('idB', 'id1'), 'text'), (('idA', 'id2'), 'text'), (('idC', 'id3'), 'text')]


text:
Q: Singleton for different NSURLConnection I always used for connect with Server singleton class. I didn't check response from server and easy take data. Now I need use 10 different requests. I create property NSURLConnection. So how can I identify what connections I use in delegate methods like
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

Because from each request I take different data

A: What you could do is have a custom connection class representing a connection, its data, and optionally some info about the connection. I use this:
@interface MyConnection : NSObject

@property NSURLConnection *connection;
@property id info;
@property NSMutableData *data;

@end

Then just put the connections in an array, and compare the actual NSURLConnection objects to each other, in order to find out which connection received data/failed etc.
Creating a connection:
 NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:someRequest delegate:self];

    if (connection){
        MyConnection *con = [[MyConnection alloc] init];
        con.connection = connection;
        con.data = [NSMutableData data];
        [self.arrayWithConnections addObject:con];
    }

The methods:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    MyConnection *con = [self getConnection:connection]
    [con.data appendData:data];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    MyConnection *con = [self getConnection:connection];
    [con.data setLength:0];
}

-(MyConnection *)getConnection:(NSURLConnection *)con
{
    for (MyConnection *myCon in self.arrayWithConnections)
        if ([con isEqual: myCon.connection])
            return myCon;
    return nil;
}


text:
Q: Print List<> to PrintDocument - display first 37 items, then the next 37 and so on Objective: Print out records that are read into my application and stored in Lists<> like this http://www.codeproject.com/Tips/733680/Printing-and-Previewing-multiple-pages-in-Csharp and https://stackoverflow.com/a/11067893/2952390. More so I want to print out the first 37 records (if there is that much) on the first page, then the next 37 on the second page and so on. The information is displayed into a basic table with many columns in my PrintDocument. I could have up to 22500 records! For example, if I have 104 records I would need 3 pages and the general layout should be like the following:

The following code displays all records on all pages but overlapping. I can see that the code has managed to divide the records into displaying 37 at a time in the correct position, but the page doesn't clear so it just overlaps. Also the if statement may be incorrect as I'm not sure if it will display only 74 records or the whole 104 records.
int currentpage = 0;
int pagesleft = 0;
readonly PrintDocument docccc = new PrintDocument();
readonly PrintPreviewDialog printpreviewdialog = new PrintPreviewDialog();

    private void Summary_Preview(object sender, EventArgs e)
    {
        printpreviewdialog.Document = docccc;
        docccc.DefaultPageSettings.Landscape = true;
        docccc.PrintPage += new PrintPageEventHandler(Summary_English);
        printpreviewdialog.ShowDialog();
    }

    private void Summary_Print(object sender, EventArgs e)
    {
        docccc.PrintPage += new PrintPageEventHandler(Summary_English);
        printDialog1.Document = docccc;
        docccc.DefaultPageSettings.Landscape = true;
        printDialog1.ShowDialog();

        if (printDialog1.ShowDialog() == DialogResult.OK)
        {
            docccc.Print();
        }
    }

private void Summary_English(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    // Title
    // Extra text
    // Table headers

    int rec_count = Details.rec_num.Count; // Counts the total records from file
    int pageCount = (rec_count + 37 - 1) / 37; // Calculates how many pages there should be
    currentpage = currentpage + 1;

    if (currentpage == 1)
    {
        pagesleft = pageCount;
    }

    e.Graphics.DrawString(currentpage.ToString() + " | " + pageCount.ToString(), new Font("Courier New", 8, FontStyle.Bold), Brushes.Gray,
         new System.Drawing.Rectangle(22, 780, 1125, 15), Align_Centre);

    int rec = 1; // Initiate record to read
    int y = 257; // Initiate text position

    for (; rec < rec_count; rec++)
    {
        e.Graphics.DrawString(Details.rec_num[rec - 1] + "\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(22, y, 32, 485));
        e.Graphics.DrawString(Details.datetime[rec] + "\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(54, y, 96, 485));
        e.Graphics.DrawString(Details.volt[rec] + "V\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(240, y, 40, 485));
        e.Graphics.DrawString(Details.expectedAtime[rec] + " S\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(394, y, 68, 485));
        e.Graphics.DrawString(Details.actualtime1[rec] + " S\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(462, y, 102, 485));
        e.Graphics.DrawString(Details.expectedBtime[rec] + " S\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(564, y, 69, 485));
        e.Graphics.DrawString(Details.actualtime2[rec] + " S\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(633, y, 102, 485));
        e.Graphics.DrawString(Details.error[rec] + "\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(735, y, 92, 485));

        y += 13; // Increment line gap between each rec

        if (rec % 37 == 0)
        {
            y = 257;
        }

        if (currentpage < pageCount)
        {
            e.HasMorePages = true;
        }
        else
        {
            e.HasMorePages = false;
        }
    }
}

A: I've fixed it!!! YAY! So happy. For people who were in my position and struggling:
int currentpage = 0;
int pagesleft = 0;
int rec = 0;

private void Summary_English(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    rec = rec += 1;

    // Title
    // Extra text
    // Table headers

    int rec_count = Details.rec_num.Count; // Counts the total records from file
    int pageCount = (rec_count + 37 - 1) / 37; // Calculates how many pages there should be
    int y = 257;
    currentpage = currentpage + 1;

    if (currentpage == 1)
    {
        pagesleft = pageCount - 1;
    }

    for (; rec < rec_count; rec++)
    {
        e.Graphics.DrawString(Details.rec_num[rec - 1] + "\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(22, y, 32, 485));
        e.Graphics.DrawString(Details.datetime[rec] + "\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(54, y, 96, 485));
        e.Graphics.DrawString(Details.volt[rec] + "V\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(240, y, 40, 485));
        e.Graphics.DrawString(Details.expectedAtime[rec] + " S\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(394, y, 68, 485));
        e.Graphics.DrawString(Details.actualtime1[rec] + " S\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(462, y, 102, 485));
        e.Graphics.DrawString(Details.expectedBtime[rec] + " S\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(564, y, 69, 485));
        e.Graphics.DrawString(Details.actualtime2[rec] + " S\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(633, y, 102, 485));
        e.Graphics.DrawString(Details.error[rec] + "\n", ar_7_reg, Brushes.Black, new System.Drawing.Rectangle(735, y, 92, 485));

        y += 13;

        if (rec % 37 == 0)
        {
            y = 257;
            break;
        }
    }

    e.HasMorePages = currentpage < pageCount;
}

There wasn't as much code as I first anticipated!


text:
Q: How to get all possible combinations of array elements without duplicate I have a vector of string elements vector = {'A','B','C'}.
I want to generate all possible combination of the three elements of the array but without duplicate.
I expect the following result: {'A', 'B', 'C', 'AB', 'AC', 'BC', 'ABC'}.
How can I do that in MATLAB?

A: Judging from your desired result, you want all the combinations with 2 choices of 'A', 'B', 'C', and '' (nothing). You can do it with nchoosek as follows
result = nchoosek(' ABC', 2) % note space for empty

Output
result =
  6×2 char array
    ' A'
    ' B'
    ' C'
    'AB'
    'AC'
    'BC'

Then removing the spaces and converting the combinations to a cell array:
result = strrep(cellstr(result), ' ', '')

As Wolfie pointed out, this only works for single character input, for multi character inputs we can use string arrays instead of char arrays:
result = nchoosek(["","A1","B2","C3"], 2);
result = result(:,1) +  result(:,2) % string cat
% result = cellstr(result); % optional if want cell output

result =
  6×1 string array
    "A1"
    "B2"
    "C3"
    "A1B2"
    "A1C3"
    "B2C3"


text:
Q: Is it possible to call named method within a call to Where? I am trying to understand some performance implication of Linq from this free ebook by RedGate
ftp://support.red-gate.com/ebooks/under-the-hood-of-net-memory-management-part1.pdf
On page 157-158 in this book, they created following example.
Order[] pastDueAccounts = null;
DateTimedueDate = DateTime.Today.AddDays(-7);
using(varcontext = new Context())
{
    pastDueAccounts = context.Accounts.Where(account => account.DueDate < dueDate).ToArray();
}

They then re-factored part of lamda expression into following function.
public bool PastDueAccount(Account account)
{
    return account.DueDate < DateTime.Today.AddDays(-7);
}

Finally they used this function as follows.
Order[] pastDueAccounts = null;
using(varcontext = new Context())
{
    pastDueAccounts = context.Accounts.Where(account => PastDueAccount(account)).ToArray();
}

Based on what I researched so far, its not possible to run this linq query as LINQ will not be able  recognize the method and cannot be translate into a store expression. I wonder if this example is wrong and simply not possible to run or if I am just having hard time getting my heard around on how to simulate this problem?

A: You are correct, this would not be able to be called by LINQ-to-Entities the way it's displayed.
The only way it could be used in LINQ-to-Entities is to:

*

*Create the equivalent of the function on the server side.

*Map the function in the model appropriately so that it translates the call correctly.

A: As casperOne said, you can't do that with a function.  This answer is a way to do what you need to do (reuse a where filter).
You can create an Expression somewhere you can access, then reuse it.
System.Linq.Expressions.Expression<Func<Account, bool>> pastDueAccountFunc = account => account.DueDate < System.Data.Objects.EntityFunctions.AddDays(DateTime.Now, -7);
Then to use it later:
var pastDueAccounts = context.Accounts.Where(pastDueAccountFunc);
This is the full code I'm using with this:
System.Linq.Expressions.Expression<Func<SomeNeatEntity, bool>> func = x => x.DateCreated < System.Data.Objects.EntityFunctions.AddDays(DateTime.Now, -7);

var entities = new MyEntities();

var t = entities.SomeNeatEntities.Where(func);
Console.WriteLine(t.Count());

var h = entities.SomeNeatEntities.Where(x => x.SomeField != null).Where(func);
Console.WriteLine(h.Count());

MyEntities is the ObjectContext in the project.
entities.SomeNeatEntities is ObjectSet<SomeNeatEntity>.


text:
Q: Wordpress user input security I have written a Wordpress php template to take user input via a HTML form. The information in the form is used to create a new (draft) post. I have escaped all the input using.
esc_html($_POST['name']);

I also check user input is present before submit. How do I protect against sql injection? Are there another precautions I should take.

A: If you're using the built in functions (such as wp_insert_post) for creating the post then you don't need to worry about SQL injections; WordPress escapes the content before inserting into the database.
If you are running any additional queries, make sure you use $wpdb->prepare() to bind your parameters. The escaping will be taken care of for you.
You should read this article:
https://codex.wordpress.org/Data_Validation#Database
You should also look into adding a nonce to your form:
https://codex.wordpress.org/Function_Reference/wp_nonce_field


text:
Q: Convert to byte array so I can decode with ATOB I'm currently sending a byte array of a pdf from the server which is generated using Converter.Convert from the ceTe.DynamicPDF.HtmlConverter package.
When I try to decode it using ATOB in angular it gives this error:

InvalidCharacterError: Failed to execute 'atob' on 'Window': The
string to be decoded is not correctly encoded.

I've seen this error online and the solutions were just using other functions that have ATOB in them so the error persists.

A: atob decodes a base64 encoded string, ceTe.DynamicPDF.HtmlConverter doesn't look like it outputs a base64 string, but a pdf, so that's going to be your issue.


text:
Q: Pass updated super class values to subclasss I am trying to pass a value that has been updated in the super class to the subclass is this possible?
For example I have:
public class1{
    @FXML
    ListView <String> list;

    // then list gets changed in a method

    public void method (){
    list.getItems().add("hello");
    }
}

And in a different class:
public anotherClass extends class1{

    public void method(){
    System.out.println(list);
    // here it seems that the list has not been updated and I get a null value when printing it instead of a list filled with "hello"
    }
}

How can I do this?

A: How about
public anotherClass extends class1{

    public void method(){
      super.method ();
      System.out.println(list);
    }
}

A: In your example, you override the method in class1. Generally, we write such code like this:
class anotherClass extends class1
{
    @Override // Since you replace the method in class1
    public void method()
    {
        // do something

If you're trying to  call the method defined in class at the same time as when you call the method in anotherClass, call it using the super keyword:
public void method()
{
    super.method();
    // do something else!


text:
Q: Не могу задать индекс для создаваемого Pandas DateFrame Имею следующие исходные данные:
# список столбцов
report_columns = ['Date', 'Result', 'Status', 'Count']
# создаём новый пустой DataFrame с использованием списка столбцов
report_df = pd.DataFrame(columns=report_columns)
# преобразуем первый столбец в datetime:
report_df[report_columns[0]] = pd.to_datetime(report_df[report_columns[0]])  # 'Date'
# остальные:
report_df[report_columns[1]] = report_df[report_columns[1]].astype(str)  # 'Result'
report_df[report_columns[2]] = report_df[report_columns[2]].astype(str)  # 'Status'
report_df[report_columns[3]] = report_df[report_columns[3]].astype(float)  # 'Count'

report_df = report_df.reset_index(drop=True)

def BuildReportItem(t_date, t_result, t_status, t_count):
    return {"Date": t_date, "Result": t_result, "Status": t_status, "Count": t_count}

for index, row in data_sience_csv.iterrows():
    .....
    check_signals = []
    .....
    if ...
        signal = BuildReportItem(row[0], s_compact, s_stat, iPointData)
        check_signals.append(signal)
    ....

    if check_signals != []:
        report_df = report_df.append(check_signals)
        print(report_df)

report_df.to_csv(csv_path2reports, sep=';')

В результате я получаю примерно следующее:
                 Date  Result  Status  Count
0 2020-03-12 13:00:00   Found    Warr    0.0
0 2020-06-03 11:00:00   Found      Ok   73.0

Как видно из вывода "индекс" почему-то всегда равен '0'!
Хотя я понимаю, что скорее всего это даже и не индекс. Отсюда два вопроса

*

*Как указать индекс? Чтобы в первом столбце (который без имени) шли 0, 1, 2, 3 ... Т.е у DataFrame был числовой индекс, начинающийся с нуля.

*Можно ли в качестве индекса указать столбец 'Date'?
Я это пробовал (через report_df.set_index), но результат увы такой же...

PS1:
На самом деле удивлён, что большинство сосредоточилось не на заданных мною вопросах, а на том как я заполняю DataFrame и откуда я получаю значения s_compact, s_stat, iPointData.. Хотя какая связь между этими вопросами и созданием пустого DataFrame, у которого почему-то не формируется index я так и не понял.. Ну да ладно, постараюсь ответить

*

*на тему iterrows - для меня скорость не критична, но если есть более скоростные решения буду признателен за рассказ о них (или за ссылку на пример кода).

*на тему s_compact, s_stat, iPointData - я даже не знаю что ответить.. Там кода обработки данных примерно на 400 строк (не считая вспомогательных функций) - его весь что-ли нужно приводить? Есть три функции, каждая из которых вызывает ещё несколько, которые обрабатывают фрейм из исходных данных (результаты работы двух медицинских приборов, выгруженные в CSV). Первая - если заданный критерий сработал, то возвращает строку, которая может иметь значения "Found" или "May be". Вторая возвращает строку, которая может иметь значения "Success", "Warr", "Info" и "Err". Третья - число, рассчитанное по определённому алгоритму. Чем это вам поможет - не знаю.

По-пробую ещё раз кратко описать задачу:

*

*Нужно создать пустой DateFrame, который в процессе выполнения алгоритма наполняется данными (подготовленными строками).

*Как установить индекс для пустого DateFrame? Я использовал report_df = report_df.set_index('Date') но такой вариант не срабатывает.. И можно ли сделать нумерацию не по дате, а просто - с нуля и до конца.

PS2: вопрос решился, спасибо @MaxU за подсказку!
Необходимо было после report_df = report_df.append(check_signals) добавить следующий код:
if (len(report_df) > 0):
    report_df = report_df.reset_index(drop=True)
    print(report_df)`

Тогда индекс в DataFrame отображается в виде целых чисел от 0 до N-1!
Ещё раз спасибо! Не думал, что каждый раз, при добавлении строки, придётся reset_index делать!

A: Вы используете очень неэффективные подходы:

*

*data_sience_csv.iterrows() - один из самых медленных и неэффективных способов работы с DataFrame

*Тоже самое можно сказать о добавлении по одной строке к DataFrame

По первому пункту:
Если вы поясните откуда и как вы получаете значения s_compact, s_stat, iPointData, то, наверняка, получите адекватный и идиоматический ответ.
Кроме того в вопросе следует приводить небольшие воспроизводимые примеры входных данных и то, что вы зотите получить в результате
По второму пункту:
В общем случае, можно собрать списки значений для каждого столбца и в конце создать DataFrame  следующим образом:
df = pd.DataFrame({
    "Date": pd.to_datetime(list_of_date_strings),
    "Result": list_of_result_values,
    "Status": list_of_stats,
    "Count": pd.to_numeric(list_of_counts, errors="coerce")
})

Значения индекса тогда по умолчанию будут от 0 до N-1
Но, возможно, объяснив подробнее вашу задачу и приведя примеры входных и выходных данных, вам дадут более эффективный ответ.

UPD: чтобы установить индекс в DataFrame'е в виде целых чисел от 0 до N-1:
df = df.reset_index(drop=True)

PS эту операцию нужно делать  после окончания заполнения DF! Делать это на пустом DataFrame - бессмысленно, т.к. в пустом DF нет ни строк ни значений индекса.

A: Насколько я понимаю, пользователь хочет, чтобы у создаваемого им DataFrame был индекс.
У самого была некоторое время назад такая же проблема, но решить не удалось и я забил на неё.
Судя по приведённому результату в DataFrame не получается установить индекс почему-то.
Я так понимаю, что автор хочет получить в 1 столбце индекс и чтобы была возможность сделать индекс в двух вариантах:

*

*Числовой - когда нумерация идёт с нуля: т.е 1 строка - 0, 2-ая - 1, 3-я -2 и т.д.

*Индекс по столбцу "Date".

P.S: ответ предыдущего автора не понятен

*

*Какая разница какие входные данные.. Из приведённого примера видно, что они формируются в программе, потом передаются в функцию BuildReportItem, которая возвращает dict, добавляемый в DataFrame

*И чем плох iterrows() если нужно перебрать все строки по одной?


text:
Q: Inserting ads within content I want to show adsense ads below the 4th and 20th paragraph of every blog post, ONLY if there is a 20th paragraph.
I managed to insert an ad below the 4th ad by placing the following code in my functions.php file, however I don't know how to add an additional ad after the 20th.
// Insert ads after second paragraph of single post content.

add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {

    $ad_code = '

';

    if ( is_single() && ! is_admin() ) {
        return prefix_insert_after_paragraph( $ad_code, 3, $content );
    }

    return $content;
}

// Parent Function that makes the magic happen

function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
    $closing_p = '
';

    $paragraphs = explode( $closing_p, $content );

    foreach ( $paragraphs as $index => $paragraph ) {

        if ( trim( $paragraph ) ) {
            $paragraphs[ $index ] .= $closing_p;
        }

        if ( $paragraph_id == $index + 1 ) {
            $paragraphs[ $index ] .= $insertion;
        }
    }

    return implode( '', $paragraphs );
}

A: Have faith ;-)
Unfortunately, your code ain't correct in multiple ways. It assumes that the content only consists of content enclosed by paragraphs and doesn't work correctly if not.
This would be one solution:

add_filter('the_content', 'prefix_insert_post_ads');

/**
 * Content Filter
 */
function prefix_insert_post_ads($content) {

    $insertion = 'Your AD Code';

    if (is_single() && ! is_admin()) {
        return prefix_insert_after_paragraphs($content, $insertion, array(4,20));
    }

    return $content;

}

// Function that makes the magic happen correctly

function prefix_insert_after_paragraphs($content, $insertion, $paragraph_indexes) {

    // find all paragraph ending offsets

    preg_match_all('#
#i', $content, $matches, PREG_SET_ORDER+PREG_OFFSET_CAPTURE);

    // reduce matches to offset positions

    $matches = array_map(function($match) {
        return $match[0][1] + 4; // return string offset + length of
 Tag
    }, $matches);

    // reverse sort indexes: plain text insertion just works nicely in reverse order

    rsort($paragraph_indexes);

    // cycle through and insert on demand

    foreach ($paragraph_indexes as $paragraph_index) {
        if ($paragraph_index <= count($matches)) {
            $offset_position = $matches[$paragraph_index-1];
            $content = substr($content, 0, $offset_position) . $insertion . substr($content, $offset_position);
        }
    }

    return $content;

}

Best regards from Salzburg!

A: To properly count paragraphs, and to be consistant, the best will be is to make use of raw post content, and then apply the wpautop filter to the raw content. This way, WordPress will handle all the variables which at the end will determine how paragraphs are build and displayed
We can also look at a couple of other things to make this as reliable as possible

*

*Because this is only needed for a single post, we will make use of the queried object to get our raw post content from

*Make sure we have a minimum amount of paragraphs before inserting our adds

*Make use of the in_the_loop() condition to only target the main query loop
-

I have decided to add all of this in a class
/**
 * Class AdsINParagraphs
 *
 * Class to inject ads into single post's content between paragraphs
 * as required
 */
class GoogleAdsINParagraphs
{
     /**
     * @var string $ad
     * @access protected
     * @since 1.1.0
     */
    protected $ad;

     /**
     * @var int|string $min
     * @access protected
     * @since 1.1.0
     */
    protected $min;

     /**
     * @var array $inject
     * @access protected
     * @since 1.1.0
     */
    protected $inject;

     /**
     * @var $post = NULL
     * @access protected
     * @since 1.1.0
     */
    protected $post = NULL;

     /**
     * @var $paragraphs = NULL
     * @access protected
     * @since 1.1.0
     */
    protected $paragraphs = NULL;

     /**
     * @var $paraCount = 0
     * @access protected
     * @since 1.1.0
     */
    protected $paraCount = 0;

     /**
     * @var $contentReplacement = NULL
     * @access protected
     * @since 1.1.0
     */
    protected $contentReplacement = NULL;

    /**
     * Public method __construct()
     *
     * Constructor for the GoogleAdsINParagraphs class
     *
     * @param string     $ad     The add that should be injected
     * @param string|int $min    The minimum amount of paragraphs that must exist
     * @param array      $inject An array of paragraph numbers where the add should be injected
     *                           If you need an ad before the content, simply pass 0 as first value
     * @access public
     * @since 1.1.0
     */
    public function __construct( $ad = NULL, $min = 4, $inject = [] )
    {
        $this->ad     = $ad;
        $this->min    = $min;
        $this->inject = $inject;
    }

    /**
     * Public method init()
     *
     * Initialize the 'the_content' filter callback
     *
     * @access public
     * @since 1.1.0
     */
    public function init()
    {
        add_filter( 'the_content', [$this, 'postContent'] );
    }

    /**
     * Protected method initHelperMethods()
     *
     * Initialize all the helper functions for the 'the_content' filter callback
     *
     * @access protected
     * @since 1.1.0
     */
    protected function initHelperMethods()
    {
        $this->post();
        $this->paragraphs();
        $this->paraCount();
        $this->contentReplacement();
    }

    /**
     * Protected method post()
     *
     * Gets the current post object and sanitize the post object. Sanitation
     * is done as precaution should the query object being altered by some other
     * program/function/malicious code
     *
     * @access protected
     * @since 1.1.0
     */
    protected function post()
    {
        $post_raw   = get_queried_object();
        // Sanitize the post object in case that something externally changed the queried object
        $post       = sanitize_post( $post_raw );
        $this->post = $post;
    }

    /**
     * Protected method paragraphs()
     *
     * Gets the current post's post content, sanitizes it and then applies the wpautop filter
     * function to it to apply p tags to the raw content. After the filter function is applied,
     * the content is exploded into an array of paragraphs
     *
     * @access protected
     * @since 1.1.0
     */
    protected function paragraphs()
    {
        // Just in case, as extra precaution, run the raw post comment through wp_kses_post
        $noEvilContent    = wp_kses_post( $this->post->post_content );
        $peedContent      = wpautop( $noEvilContent );
        $paragraphs       = explode( '
', $peedContent );

        $this->paragraphs = $paragraphs;
    }

    /**
     * Protected method paraCount()
     *
     * Counts the amount of paragraphs created by the paragraphs() method
     *
     * @access protected
     * @since 1.1.0
     */
    protected function paraCount()
    {
        $paraCount       = count( $this->paragraphs );

        $this->paraCount = (int) $paraCount;
    }

    /**
     * Protected method contentReplacement()
     *
     * This is where everything happens. The following checks are run
     * before ads are inserted into the content
     * - Check if there is at least the set minimum amount of paragraphs.
     *   Checks are done against $this->min
     * - Check if there at least enough paragraphs to fullfil the lowest
     *   passed number in $this->inject
     * - Check to see if $this->inject is a valid array with values
     *
     * If all checks pass, ads is inserted into the content. If any value
     * in $this->inject is more than the amount of paragraphs, the ad is ignored
     * and not inserted
     *
     * @access protected
     * @since 1.1.0
     */
    protected function contentReplacement()
    {
        // Lets first run all our checks

        $this->contentReplacement = $contentReplacement = NULL;

        // Make sure that we have at least more paragraphs than our minimum, bail if not
        if ( $this->paraCount < $this->min )
            return $this->contentReplacement;

        // Make sure that $this->inject is an array and not empty
        if (    !is_array( $this->inject )
             || !$this->inject
        )
            return $this->contentReplacement;

        /**
         * We will do the following checks and validation on $this->inject
         * - validate the array of ID's and remove negative numbers
         * - sort $this->inject array numerically ASC according to passed ID's
         * - remove possible dublicates
         */
        $this->inject = filter_var(
            $this->inject,
            FILTER_VALIDATE_INT,
            [
                'flags' => FILTER_REQUIRE_ARRAY,
                'options' => [
                    'min_range' => 0
                ]
            ]
        );
        asort( $this->inject );
        $this->inject = array_unique( $this->inject );

        // Make sure that we actaully have enough paragraphs to inject an add into

        if ( $this->paraCount < $this->inject[0] )
            return $this->contentReplacement;

        // Now we can start to inject our ads into our content. Set $output as empty string
        $output = '';
        foreach ( $this->paragraphs as $key=>$paragraph ) {
            // Add ad in front of content if $this->inject[0] === 0
            if (    0 === $key
                 && 0 === $this->inject[0]
            ) {
                $output .= '
' . $this->ad . '
' . $paragraph;
            } elseif ( !in_array( $key, $this->inject ) ) {
                $output .= $paragraph;
            } else {
                $output .= $paragraph . '
' . $this->ad . '
';
            }
        } // endforeach

        $this->contentReplacement = $output;
    }

   /**
     * Public method postContent()
     *
     * This is the callback method for the 'the_content' filter. The content passed by reference
     * inside the filter is replaced by any valid value from $this->contentReplacement. This is done
     * purely for convenience
     *
     * @access public
     * @since 1.1.0
     * @return $content
     */
    public function postContent( $content )
    {
        // Lets first run our checks, make sure this is a single page and the main query
        if ( !is_single() )
            return $content;

        if ( !in_the_loop() )
            return $content;

        // Initialize our other helper methods. They should only run inside our condition
        $this->initHelperMethods();

        // Make sure $this->contentReplacement is not NULL, if so, just return $content
        if ( NULL === $this->contentReplacement )
            return $content;

        // We can now replace $content with $this->contentReplacement
        $content = $this->contentReplacement;

        return $content;
    }
} // end of class GoogleAdsINParagraphs

You can now use it as follow
$ad      = 'PLACE YOUR AD HERE';
$add_ads = new GoogleAdsINParagraphs(
    $ad,     // Your ad which you want to add
    4,       // There should be at least 4 paragraphs
    [4, 20]  // Array of paragraph numbers after which you want to inject an add
);
$add_ads->init();


text:
Q: Internet Connection : NURLConnection didFailWithError method not called I face a problem when develop an Iphone application and test it through Iphone Simulator.
In my Iphone application, there exist a button. When I click on this button, the code will check whether the Iphone is connected to internet or not. If is connected, then it will start load data from server and then insert data to my application's local database. And show a view which display the loaded data. If internet is not connected, the didFailWithError method will called and pop up a alert to alert user "no internet connection".
But my problem is when the internet connection on my Mac is on, and I click that button, the data will be loaded successfully and display a view which consists the loaded data. Then I close that view, and off the internet connection on Mac, then I click that button again, the didFailWithError seems not get invoked. And a view will displayed to user too but the data is not updated, it seems look same as the data loaded from first time.
And for another case that is,once I start use the application, and off the internet connection on Mac first, and click that button for first time, the didFailWithError is invoked and alert user "No Internet Connection".
So, anyone encountered this kind of problem before? Or anyone have comments, suggestion and solutions?
Really appreciate your reply. Thanks.

A: So probably you have got the solution to your problem as this is very old question but I post answer incase you still need it.
The simple solution for it is use the reachabillity class of apple's Reachability
just use this example to solve your problem.


text:
Q: Using PHP to connect to MS Access DB using ODBC keeps on locking I know this is not the best setup, but I'm stuck with it and cannot change it.
PHP connects to a local MS Access DB (.mdb) to log certain activities being done by the script. This works fine when only one instance of the script is running. However, if run two instances, I occasionally get the following error:
odbc_exec(): SQL error: [Microsoft][ODBC Microsoft Access Driver] Could not update; currently locked., SQL state S1000 in SQLExecDirect

This only happens intermittently so I'm assuming it's only when the two scripts both happen to be trying to write to the same table at the same time. I never had this issue with other DBs such as MySQL. How can I tell PHP/ODBC/Access to either not lock or try again if it is locked?
I also usually have the Access DB open on my screen for troubleshooting purposes.

A: odbc_exec() returns FALSE if the query fails, so you could just check the result of the query and keep trying until it succeeds:
$sql = "UPDATE [Clients] SET [Position]='somewhere' WHERE [ID]=1";
while (TRUE) {
    $result = odbc_exec($conn, $sql);
    if ($result) {
        break;
    }
    else {
        $lastError = odbc_error();
        if ($lastError != "S1000") {
            echo "ODBC error $lastError";
            break;
        }
    }
    sleep(1);
}


text:
Q: IF there is another row I'm trying to write an if statement to check if their is another row after the current one in the database. Where the current one is the id of the page.
<?php if($new_id>id): ?>
yes
<?php else: ?>
no
<?php endif; ?>

$new_id is the selected page. so if their is an entry after it it will say yes, or if it the most recent addition it will say no.
I know how to do this in a select statement: WHERE id>$new_id
this tells me if there is another row after it but I don't know how to write it as an IF statement.

A: Assuming you have a post table with an autoincrementing id field using MySQL:
CREATE TABLE post (
   id       INT NOT NULL AUTO_INCREMENT,
   ...
   PRIMARY KEY ( id )
);

You could use something like this (pseudo-php):
<?php
  // somehow you calculate the current id
  $the_id = your_get_the_id_func();

  // then execute this sql row with your favourite sql library
  // and get the returned single value which may be the stings '0' or '1'
  $has_newer_post = your_exec_sql_and_get_sql_value("
    SELECT EXISTS ( SELECT 1 FROM post WHERE id > $the_id LIMIT 1 );
  ");
?>

<?php
  // if('0') === if(false) only in php: http://codepad.org/IlUx8J1Y
  if( $has_newer_post ) :
?>
  yes
<?php else: ?>
  no
<?php endif; ?>


text:
Q: What's the difference between "text/event-stream" and "application/stream+json" @GetMapping(path = "/cars", produces = "text/event-stream")
public Flux<Car> getCarStream() {
    System.out.println("application/stream+json");
    return this.repository.findCarsBy().log();
}

What's the difference between the above code and the following:
@GetMapping(path = "/cars", produces = "application/stream+json")
public Flux<Car> getCarStream() {
    System.out.println("application/stream+json");
    return this.repository.findCarsBy().log();
}

So far I've found the contradictory information: some say they both mean server-sent events and others that there is a difference.

A: TL;DR: that dzone article is wrong, and Rossen's talk is right.
text/event-stream is the official media type for Server Sent Events (SSE); it will prefix data bits with a data: prefix and you can also choose your prefix to change the meaning of that piece of data for the client. This media type is for browsers, as they support that using the EventSource JavaScript API.
application/stream+json is for server to server/http client (anything that's not a browser) communications. It won't prefix the data and will just use CRLF to split the pieces of data. Note that the Spring team is reconsidering that media type, because SPR-16742 (don't hesitate to comment there!).
Update: application/x-ndjson is now the preferred media type for streaming JSON values.


text:
Q: Grid View not displaying first time after Android SDK 28 to 32 upgrade This code has worked for more than a decade now. Today upgraded the SDK from 28 to 32 and the view does not display when it appears first time(first screen of the app). The items count is coming in as 4 as desired, the control is going into getView method. But it does not display. If I go to another screen and press back button, then the grid view appears. Is there a change in grid view w.r.t SDK 30 or above? Any help is appreciated. Rest of the app is all working fine with existing code. Showing partial code here. On pressing back button, onRestart is called and view displays properly.
public class MainActivity extends BaseActivity implements Constants {
public GridView gridView;
MainActivityAdapter adapter;

private ArrayList<String> topicNames;
private ArrayList<Integer> topicIconIds;
private ArrayList<OnTouchListener> onClickListeners;

@Override
protected void onCreation(Bundle savedInstanceState) {
    setLayout(new MainLayout());
    try {
        configureUI();
    } catch (MyException exception) {
        exception.handleMe(this);
    }
    UIUtils.handleLastCrashIfAny(this);
}

private void configureUI() throws MyException {
    ((MainLayout) getBaseLayout()).configureUI();
    prepareList();
    Log.d("MainActivity", " creating mainlayout with topics=" + topicNames.stream().count());
    adapter = new MainActivityAdapter(this, topicNames, topicIconIds);
    gridView.setAdapter(adapter);
}

class MainActivityAdapter extends BaseAdapter {
    private final ArrayList<String> adapterTopicNames;
    private final ArrayList<Integer> adapterTopicIcondIds;

    public MainActivityAdapter(Activity activity, ArrayList<String> listTopic, ArrayList<Integer> listImage) {
        super();
        this.adapterTopicNames = listTopic;
        this.adapterTopicIcondIds = listImage;
    }

    @Override
    public int getCount() {
        return adapterTopicNames.size();
    }

    @Override
    public String getItem(int position) {
        return adapterTopicNames.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder view = null;
        if (convertView == null) {
            convertView = ((MainLayout) getBaseLayout()).getView();
        }
        view = (ViewHolder) convertView.getTag();

        // set image view parameters
        ((MainLayout) getBaseLayout()).setTopicImageParameters(view);

        view.textView.setText(adapterTopicNames.get(position).replace(" and ", " & "));
        view.imageView.setId(position);

        view.imageView.setImageResource(adapterTopicIcondIds.get(position));
      view.position = position;

        convertView.setId(position);
        view.imageView.setOnTouchListener(onClickListeners.get(position));
        return convertView;
    }
}

public ArrayList<String> getTopicNames() {
    return topicNames;
}

@Override
protected void onRestart() {
    super.onRestart();
    adapter.notifyDataSetChanged();
    getBaseLayout().hideBuyFullVersionButtonIfNeeded();
    Log.d("MainActivity", "onRestart");

}

MainLayout.configureUI method is
  public void configureUI() throws MyException {

    int landscapeRowsPortraitColumns = ApplicationDetails.getLandscapeRowCountPortraitColumnCount();
    int landscapeColumsPortraitRows = ApplicationDetails.getLandscapeColumnCountPortraitRowCount();

    if (activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        numberOfRows = landscapeColumsPortraitRows;
        numberOfColumns = landscapeRowsPortraitColumns;

    } else if (activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        numberOfRows = landscapeRowsPortraitColumns;
        numberOfColumns = landscapeColumsPortraitRows;
    }

    gridView = new GridView(activity) {
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            super.onLayout(changed, l, t, r, b);
            if (!areCellDimensionsCalculated) {
                getCellDimensions();
            }
        }
    };

    gridView.setVerticalSpacing(1);
    gridView.setHorizontalSpacing(1);
    gridView.setOverScrollMode(GridView.OVER_SCROLL_NEVER);
    gridView.setStretchMode(GridView.NO_STRETCH);
    gridView.setSelector(android.R.color.transparent);
    gridView.setBackgroundColor(ApplicationDetails.getMainScreenDividerColor());
    RelativeLayout.LayoutParams gridViewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT);
    gridViewParams.addRule(RelativeLayout.BELOW, navigationBar.getId());
    gridViewParams.addRule(RelativeLayout.ABOVE, footerBar.getId());
    contentView.addView(gridView, gridViewParams);

    ((MainActivity) activity).gridView = gridView;

}

A: Thanks to https://stackoverflow.com/a/14119464/8094329, found the answer. The problem was GridView's onLayout was getting called AFTER setting the adapter, so I added a listener on onLayout and within that listener set the adapter.
private void configureUI() throws WebrichException {
    ((MainLayout) getBaseLayout()).configureUI();
    prepareList();
    adapter = new MainActivityAdapter(this, topicNames, topicIconIds);

    gridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            gridView.setAdapter(adapter);
            gridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });
}


text:
Q: Call an ORACLE Stored Procedure from Excel VBA, including string and number parameters Hi StackOverflow friends,
I would like to ask you how to call an ORACLE Stored Procedure from Excel VBA, including two different parameters kind (string and number). I have been looking for in StackOverflow and Google how to do it, but I never find a good answer. So, I have decided to ask here for this specific matter.
I have this ORACLE Stored Procedure:
CREATE OR REPLACE PROCEDURE InsertDayTable (
    PNTable    in VARCHAR2,
    PMonth     in VARCHAR2,
    PDay       in VARCHAR2,
    PProvince  in VARCHAR2,
    PBusiness  in VARCHAR2,
    PCode      in NUMBER,
    PValue     in NUMBER,
    PAccum     in NUMBER
) AS
    v_sql         VARCHAR2(1000);
BEGIN
    /*
     *  Development of the procedure...
     */
END;

I have an Excel file used like a program, where I calculate the data to insert in ORACLE. After calculate this data, I send it to an Excel procedure. This Excel procedure is responsible for call the ORACLE Stored Procedure. However, I don't know how to call using VARCHAR2 and NUMBER parameters.
For VARCHAR2 parameters, I am using:
Set oParam1 = oCmd.CreateParameter("PNTable", adVarChar, adParamInput, 10, "MyTable")
oCmd.Parameters.Append oParam1

For NUMBER parameters, I am using:
Set oParam7 = oCmd.CreateParameter("PValue", adNumeric, adParamInput, 5, iValue)

However, I always have errors (Error '-2147217887 (80040e21)'), don't matter the changes that I make. Could you help me with some tips or an example? Thank you very much.


text:
Q: When is anonymous namespace data initialized? I have been using anonymous namespaces to store local data and functions and wanted to know when the data is initialized?  Is it when the application starts in the same way as static data or is it compiler dependent?  For example:
// foo.cpp
#include "foo.h"

namespace {

const int SOME_VALUE = 42;

}

void foo::SomeFunc(int n)
{
    if (n == SOME_VALUE)
    {
        ...
    }
}

The question arises out of making some code thread-safe.  In the above example I need to be certain that SOME_VALUE is initialized before SomeFunc is called for the first time.

A: C++ Standard, 3.6.2/1 :

Zero-initialization and
  initialization with a constant
  expression are collectively called
  static initialization; all other
  initialization is dynamic
  initialization. Objects of POD types
  (3.9) with static storage duration
  initialized with constant expressions
  (5.19) shall be initialized before any
  dynamic initialization takes place.
  Objects with static storage duration
  defined in namespace scope in the same
  translation unit and dynamically
  initialized shall be initialized in
  the order in which their definition
  appears in the translation unit.

This effectively means, even when another translation unit calls your SomeFunc function from outside, your SOME_VALUE constant will always be correctly initialized, because it's initialized with a constant expression.
The only way for your function being called early (before main) is while initializing an object with dynamic initialiation. But by that time, according to the standard quote, the initialization of your POD variable is already done.

A: In this particular case (a global variable that is const) the variable is "initialized" at compile time.
SOME_VALUE is always equal to 42.
In fact, most (all?) compiler will actually compile this as if it was hardcoded :
void foo::SomeFunc(int n)
{
    if (n == 42)
    {
        ...
    }
}

A: For the right answer to your actual question see Mathieu's answer.
However, note that the anonymous namespace doesn't affect the beginning and end of the lifetimes of global and / or static objects.  In other words, you're just as vulnerable to static initialization order problems as by using plain old globals.
The link also has some tips on avoiding the issue, using "construction on first use", in the next topic.

A: Namespaces have nothing to do with the time of initialization. All that a namespace does is change names that belong to it.


text:
Q: Angular CLI(v1.7.3) ng new returning error When I run
cd ~/projects
ng new myapp

I get
Error: Path "/app/app.module.ts" does not exist.
Path "/app/app/module.ts" does not exist.

My configuration is
Angular CLI : 1.7.3
Node: 9.8.0
OS: Ubuntu 16.04.4 LTS
NVM: 0.33.8

I have tried various combinations of nodejs and Angular CLI but nothing I have tried works.
Can anybody point me in the right direction?


text:
Q: Split pandas dataframe into blocks based on column values I want to break dataframe into blocks from one True value to next True value:

data
flag

MODS start 12/12/2020
True

Some data
False

Some data
False

MODS start 30/12/2020
True

Some data
False

Some data
False

To

data
flag

MODS start 12/12/2020
True

Some data
False

Some data
False

data
flag

MODS start 30/12/2020
True

Some data
False

Some data
False

Please help

A: You can use cumsum to create groups then query the datafame for each group:
df = pd.DataFrame({'data':['MODS start 12/12/202','Some data', 'Some data', 'MODS starts 30/12/2020', 'Some data', 'Some data'],
                  'flag':[True, False, False, True, False, False]})

df['grp'] = df['flag'].cumsum()

print(df)

Output:
                     data   flag  grp
0    MODS start 12/12/202   True    1
1               Some data  False    1
2               Some data  False    1
3  MODS starts 30/12/2020   True    2
4               Some data  False    2
5               Some data  False    2

The use:
df.query('grp == 1')

                   data   flag  grp
0  MODS start 12/12/202   True    1
1             Some data  False    1
2             Some data  False    1

and
df.query('grp == 2')

                     data   flag  grp
3  MODS starts 30/12/2020   True    2
4               Some data  False    2
5               Some data  False    2

A: You can use numpy.split:
np.split(df, df.index[df.flag])[1:]

Here, I used [1:] because numpy.split also consider the groups before the first index, even if it's empty.

That said, you can also use a simple list comprehension:
idx = df.index[df.flag].tolist() + [df.shape[0]]
[df.iloc[idx[i]:idx[i+1]] for i in range(len(idx)-1)]

Output (both approaches):
                    data   flag
0  MODS start 12/12/2020   True
1              Some data  False
2              Some data  False

                    data   flag
3  MODS start 30/12/2020   True
4              Some data  False
5              Some data  False

A: Get a list of indices of rows with flag = True
true_idx = df[df['flag']==True].index
n = len(true_idx)

Loop over true_idx and create a list of dataframes from each true index to next
new_dfs_list = [df.iloc[ true_idx[i]:true_idx[i+1], :] for i in range(n-1)]

append last df from last true index to the tail of df
new_dfs_list.append(df.iloc[ true_idx[n-1]:, :])

access any of your new_dfs by index
print(new_dfs_list[-1])


text:
Q: Is there a way to write to PowerShell Verbose stream from C# static (non-PSCmdlet) method I have a custom class library that my PowerShell Advanced Functions utilize.  One of the class library features is a static method within a custom class to mimic PowerShell's Write-Verbose, called Utilities.Write.Verbose().  It is called within my class library only by other classes and their public methods.  Here is the code snippet of that utility class:
namespace Utilities
{

    public class Write
    {

        public static void Verbose(string msg, string source)
        {

            ConsoleColor originalForeGroundColor = Console.ForegroundColor;
            ConsoleColor originalBackGroundColor = Console.BackgroundColor;
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.BackgroundColor = ConsoleColor.Black;
            Console.Write("VERBOSE: {0} {1}{2}", source, msg, Environment.NewLine);
            Console.ForegroundColor = originalForeGroundColor;
            Console.BackgroundColor = originalBackGroundColor;

        }

    }

}

As you can see, I am writing to just the standard console of whatever the host is.  But, when I need to capture verbose output, the Console.Write isn't capture, nor is it directed to PowerShells Verbose stream.
I came across some other sample code on getting access to the RunSpace, but it does not display any verbose output:
using (PowerShell ps = PowerShell.Create(RunspaceMode.CurrentRunspace))
{

    var _msg = string.Format("VERBOSE: {0} {1}{2}", source, msg, Environment.NewLine);

    VerboseRecord verboseRecord = new System.Management.Automation.VerboseRecord(_msg);

    ps.Streams.Verbose.Add(verboseRecord);

}

So, my question is this:  Is there a way to getting the host or PSHost object from a C# class method, or be able to write string to PowerShell's verbose stream?  My PowerShell module targets Windows Management Framework 4.0, and the Class Library targets .Net 4.6 Framework.


text:
Q: excel increment cell containing time in hour and minute format using active x controls I hope someone can please help with this, i have an excel spreadsheet where i have the following time displayed in my cell A1.
Cell A1
00:00

the first set of 00 is my hours the second set of 00 is my minutes.
Next to this cell i have two sets of Active X Controls which are up/down arrows
Cell A1   ^ ^
          V V

When a user clicks the arrows i want the time to increment, so if they click up on the first set of arrows this will increment the time to 01, 02, 03 etc as my hours all the way to 23 hours and then back to 00 hours representing 12 o clock midnight.
If the user clicks the down arrow this should de-increment the numbers, i.e. if the time is 03:00 and the user clicks the down arrow, this should go down like, 02, 01, 00 hours.
The next set of active x control arrows should control the minutes, like so :
01-59 and when the minutes go to 60 this should increment the hour up by 1.
so something like this:
22:59  ^ ^  <--- If user hits the up arrow for the minutes this then shows:

23:00

could someone please show me how i could create a vba code that would do what i need. many thanks

A: it is very simple just do this
for up arrow
Hours -> range("A1").value = DateAdd("h", 1, range("A1").value)
Minutes -> range("A1").value = DateAdd("m", 1, range("A1").value)
Seconds -> range("A1").value = DateAdd("s", 1, range("A1").value)

for down arrow
Hours -> range("A1").value = DateAdd("h", -1, range("A1").value)
Minutes -> range("A1").value = DateAdd("m", -1, range("A1").value)
Seconds  -> ("A1").value = DateAdd("s", -1, range("A1").value)


text:
Q: Is it possible to convert List to HList without infer types? I'm new to shapeless and I doing this
val list1 = List(1, 2, 3)
val list2 = List("a", "b", "c")

val lists = List(list1, list2)
val hlist = lists.toHList[List[Int] :: List[String] :: HNil]

This is fine but I want to create my HList when I won't know the size and types of my List lists. Is it possible? If not, is there any workaround?
Thanks in advance
UPDATE
To give you some context this is my use case
case class Data[T: ClassTag](list: List[T])

trait Transformation {
  type T
  type U
  def transform(data: Data[T]) : Data[U]
}

class FromInt2String extends Transformation {
  override type T = Int
  override type U = String

  override def transform(data: Data[T]) = new Data(List("1s", "2s", "3s"))
}

class FromString2Int extends Transformation {
  override type T = String
  override type U = Int

  override def transform(data: Data[T]) = new Data(List(4, 5, 6))
}

object andThen extends Poly2 {
  implicit def functions[A, B, C] = at[A => B, B => C](_ andThen _)
}

These are my objects and this is my code
val data = new Data(List(1, 2, 3))
val int2String = new FromInt2String()
val string2Int = new FromString2Int()

val transformationsHList = int2String.transform _ :: string2Int.transform _ :: HNil
val functions = transformationsHList.reduceLeft(andThen)
val data2 = functions(data)

I tried to do something like this
val transformationsList = List[Transformation](int2String, string2Int)
val transformations = allTransformations.toHList


text:
Q: Why can't i use two state in a reactjs class component?  class Pumashoe01 extends Component {
  state = {
    products: [
      {
        "_id": "1",
        "title": "Puma Shoes",
        "src": [
          "https:h_1440,q_90,w_1080/v1/assets/images/11335328/2020/5/21/63e51b29-0e3d-4e0e-a9c5-6f2c34720ef41590079916986PumaMenNavyBlueGreenLevelIDPSneakers4.jpg",

        ],
        "description": "Men Black Flex Fire V1 IDP Sneakers",
        "content": " A pair of round-toe black sneakers, has regular styling, lace-up detail Textile upper Cushioned footbed Textured and patterned outsole.",
        "price": 2364,
      }
    ],
    index: 0
  };
  myRef = React.createRef();

  handleTab = index => {
    this.setState ({ index: index })
    const images = this.myRef.current.children;
    for (let i = 0; i < images.length; i++) {
      images[i].className = images[i].className.replace("active", "");
    }
    images[index].className = "active";
  };

  componentDidMount() {
    const { index } = this.state;
    this.myRef.current.children[index].className = "active";
  }

  constructor(props) {
    super(props);
    this.state = {count: 0 }
    this.increment = this.increment.bind(this)
  }

  increment() {
this.setState( {count:this.state.count + 1},
  () => {
console.log('callback value', this.state.count)})
console.log(this.state.count)}

  render() {
    const { products, index } = this.state;
 return (
  {
          products.map(item => (

{item.title}

                  ₹{item.price}

{item.description}

{item.content}

                <DetailsThumb images={item.src} tab={this.handleTab} myRef={this.myRef} />

You clicked {this.state.count } times

                   <button onClick={this.increment}  className="cart">Add to cart</button>

                <button   className="Buynow">Buy Now</button>

          ))
        }

    );
  };
}

Why can't i use two state with same spelling in a class component. if i set same state spelling in two times it displays map is undefined error. If i change the state spelling in the constructor its function will not work. help me with this why dont i use two different functionality state in a single class component on reactjs.


text:
Q: IndexOf returns -1 in foreach object in list When I run the code, it returns -1, although the object (in my understanding) has to be there, since it's being produced by the foreach statement.
Does anyone have an idea?
public partial class Class1
{
    private List<Master_Menu_Item> Config
    {
        get { return JsonConvert.DeserializeObject<List<Master_Menu_Item>>(Json_string.Config); } //if you need an example json, i can provide it
    }

    private void Reload_Master_stack()
    {
        if (Config != null)
        {
            foreach (Master_Menu_Item master_Menu_Item in Config)
            {
                int index = Config.IndexOf(master_Menu_Item);
                Debug.WriteLine(index);
            }
        }
    }
}

class Master_Menu_Item
   {
       public string Name { get; set; }
        public string Icon_path { get; set; }
       public List<Bottom_Menu_Item> Bottom_Menu_Items { get; set; }
   }

A: You can use below code:
 if (Config != null)
            {
                foreach (Master_Menu_Item master_Menu_Item in Config)
                {
                    int index = Config.FindIndex(a => a.Id == Master_Menu_Item.Id );
                }
            }


text:
Q: Excel 2013 - Filling Zeroes based on Row/Cell Value I'm working on cleaning up timesheets for an Access database, and I'm having issues with cleaning up the data.
I have a time sheet with names in the first column, then all of the columns after that, from C to M (or so) have hours. What I am trying to accomplish is that when the Macro finds a name in the first column, it selects the columns in that row, finds the cells without hours, and fills them with zeroes
Dim r As Integer
Dim c As Range

    For r = 2 To 15 Step 1
        If Cells(r, 1).Value <> "" Then
            Range(Cells(r, 3), Cells(r, 10)).Select
        End If
    Next

    For Each c In Selection
        If IsEmpty(c) Then
            c.Value = 0
        End If
    Next

I'm attempting to loop and fill rows with zeroes based on the cell having a named entered in it.  The problem that I'm running into is that cells are only being filled in the last name/row in the spreadsheet.  The macro seems to be skipping over all but the last row.
I'm just learning VBA, so maybe I'm just missing something in the syntax.
Thanks for the help!

A: The problem is that you are moving on to the next selection, all the way to the last row, before you start filling in your 0s. Try this modification to your code:
Dim r As Integer
Dim c As Range

For r = 2 To 15 Step 1
    If Cells(r, 1).Value <> "" Then
        Range(Cells(r, 3), Cells(r, 10)).Select
    End If
    For Each c In Selection
        If IsEmpty(c) Then
            c.Value = 0
        End If
    Next c
Next r

Using this method, you fill in the 0s before moving on to the next selection/row.
Note: I avoid the use of .select/Selection because of the problems it can cause, so I am not sure if you will receive an error message if a row does not contain a name. If you wish to avoid this potential error, try the below:
Dim r As Integer
Dim c As Range
Dim c2 As Range

For r = 2 To 15 Step 1
    If Cells(r, 1).Value <> "" Then
        Set c2 = Range(Cells(r, 3), Cells(r, 10))
    End If
    For Each c In c2
        If IsEmpty(c) Then
            c.Value = 0
        End If
    Next c
Next r

By the way, did you strip out the Workbook and Sheet names from Range(Cells(r, 3), Cells(r, 10)) to simplify your post? I was surprised you were able to use that without errors. If so, you'd obviously have to put them back in for my code to work.

A: possibly,
Sub Button1_Click()
    Dim Rws As Long, Rng As Range
    Rws = Cells(Rows.Count, "A").End(xlUp).Row
    Set Rng = Range(Cells(2, 1), Cells(Rws, 1)).SpecialCells(xlCellTypeConstants)
    Rng = 0
End Sub

A: You want to take all of the blank cells and turn them into zeroes.
Sub zeroed_hours()
    Dim rw As Long
    With Sheets("Sheet1")    '<-set this worksheet reference properly!
        For rw = 2 To .Cells(Rows.Count, 1).End(xlUp).Row
            If CBool(Len(.Cells(rw, 1))) Then 'found a name!
                'C:M on this row
                .Cells(rw, 3).Resize(1, 11).Replace what:="", replacement:=0, lookat:=xlWhole
            End If
        Next rw
    End With
End Sub

This loops through the cells in column A. If it finds a value (something with length greater than zero) then it replaces all blank cells in C:M on that row with zeroes.


text:
Q: Python plot scikit-fuzzy not responding Hello i tried to make fuzzy system by scikit-fuzzy, the output seems running well but when i try to figure it according scikit-fuzzy new api, my plot is not responding. I remember last time when I using scikit-fuzzy my plot is running well, whats wrong? Do my code is lack something?
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

# crisp set
keramaian = ctrl.Antecedent(np.arange(0, 30, 1), 'KERAMAIAN')
ukuran = ctrl.Antecedent(np.arange(0, 25, 1), 'UKURAN')
vol = ctrl.Consequent(np.arange(0, 100, 1), 'UKURAN VOLUME')

# fuzzyfication
ukuran['Kecil'] = fuzz.trimf(ukuran.universe, [0, 0, 13])
ukuran['Sedang'] = fuzz.trimf(ukuran.universe, [0, 12, 24])
ukuran['Besar'] = fuzz.trimf(ukuran.universe, [12, 24, 24])

keramaian['sunyi'] = fuzz.trimf(keramaian.universe, [0, 0, 15])
keramaian['Cukup Ramai'] = fuzz.trimf(keramaian.universe, [0, 15, 29])
keramaian['Berisik'] = fuzz.trimf(keramaian.universe, [15, 29, 29])

vol['Pelan'] = fuzz.trimf(vol.universe, [0, 0, 40])
vol['Sedang'] = fuzz.trimf(vol.universe, [30, 50, 70])
vol['Kencang'] = fuzz.trimf(vol.universe, [60, 99, 99])

# rule set
rule1 = ctrl.Rule(ukuran['Kecil'] & keramaian['Berisik'], vol['Kencang'])
rule2 = ctrl.Rule(ukuran['Kecil'] & keramaian['Cukup Ramai'], vol['Kencang'])
rule3 = ctrl.Rule(ukuran['Kecil'] & keramaian['Cukup Ramai'], vol['Kencang'])
rule4 = ctrl.Rule(ukuran['Sedang'] & keramaian['Berisik'], vol['Sedang'])
rule5 = ctrl.Rule(ukuran['Sedang'] & keramaian['Cukup Ramai'], vol['Sedang'])
rule6 = ctrl.Rule(ukuran['Sedang'] & keramaian['sunyi'], vol['Sedang'])
rule7 = ctrl.Rule(ukuran['Besar'] & keramaian['Berisik'], vol['Pelan'])
rule8 = ctrl.Rule(ukuran['Besar'] & keramaian['Cukup Ramai'], vol['Pelan'])
rule9 = ctrl.Rule(ukuran['Besar'] & keramaian['sunyi'], vol['Pelan'])

vol_suara_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9])
vol_suara = ctrl.ControlSystemSimulation(vol_suara_ctrl)
keramaian['sunyi'].view()
vol_suara.input['KERAMAIAN'] = int(input("Masukkan jumlah keramaian?\n"))
vol_suara.input['UKURAN'] = int(input("Masukkan ukuran speaker?\n"))

# defuzification
vol_suara.compute()
vol.view(sim=vol_suara)

print(vol_suara.output['UKURAN VOLUME'])

A: Import import matplotlib.pyplot as plt
And try to use plt.show() at the end of your code.


text:
Q: Rails apply a condition within a sort_by looking for value I'm working on sorting a list of employees by their title with the following:
TAGS = {
'Region Manager' => 1,
'Region Sales Manager' => 2,
'General Manager' => 3,
'Residential Sales Manager' => 4,
'Commercial Sales Manager' => 5,
'Other' => 6
}.freeze

def sorting_by_title(employees)
 employees.sort_by do |x|
   TAGS[x[:title]]
 end
end

Works fine but...I also need to do an additional sort if an employee last name is Smith and needs to go before other individuals.
So I've tried doing something like:
return TAGS[x[:title]] unless x.last_name == "Smith"

Not working. It's erroring out on the show page with undefined method `each' for 2:Integer.
So my thought was I would build out another method to look for the last name.
def nepotism(employees)
 employees.group_by do |emp|
   case emp.last_name
   when /Smith/ then :moocher
   end
 end
end

So I tried then referencing it like:
return TAGS[x[:title]] unless x.nepotism
return TAGS[x[:title]] unless x.moocher

Neither of those work. Nepotism ends up with undefined method `nepotism' for # and Moocher ends up with the same. Then I realized a simple query would work a bit better:
def nepotism
 @nepotism = Employee.where(last_name: "Smith")
end

Is there a better way to sort_by a last_name if it matches Smith and THEN by the tags?

A: Here's a nice trick: in ruby you can compare arrays. And, consequently, use them as value in sort_by. They are compared element by element. If ary1[0] < ary2[0], then ary1 will be less than ary2, no matter the rest of the elements.
 employees.sort_by do |x|
   [
     x.last_name == "Smith" ? 0 : 1, # all zeroes come before all ones
     TAGS[x[:title]] # your main ordering parameter
   ]
 end

This would work very well, if there were many Smiths and you needed to sort them by titles between themselves. If there's only one Smith, then @Björn's solution is simpler.

A: Combine them like this
employees.sort_by do |x|
  x.last_name == "Smith" ? 0 : TAGS[x[:title]]
end

You can do it in the database as well (assuming Postgresql here)
def nepotism
  tagstring = "array_position(ARRAY"+TAGS.keys.to_s.gsub(/\"/,"'")+", last_name)"
  @nepotism = Employee.order("last_name = 'Smith' desc, " + tagstring)
end


text:
Q: Find all entities by given rank I am trying to understand ranking functions in T-SQL, but I am not sure I do. I am practising DENSE_RANK() and having troubles with understanding what's happening here:
SELECT
   EmployeeID,
   FirstName,
   LastName,
   Salary,
   DENSE_RANK() OVER
   (PARTITION BY Salary ORDER BY EmployeeID) AS Rank
FROM  Employees
WHERE Salary BETWEEN 10000 AND 50000
ORDER BY Salary DESC

Why columns with equal salaries have a different rank?

The rows within a partition that have the same values will receive the same rank.

My next question is if it's possible to find only the entities whose Rank is 2?

A: The behaviour is correct. You are creating a group based on salary and then order by employee id
I guess you want:
DENSE_RANK() OVER(ORDER BY Salary DESC) AS Rank

To filter rows you need to use inline view/cte:
WITH cte AS (
SELECT
   EmployeeID,
   FirstName,
   LastName,
   Salary,
   DENSE_RANK() OVER(ORDER BY Salary DESC) AS Rank
FROM  Employees
WHERE Salary BETWEEN 10000 AND 50000
)
SELECT *
FROM cte
WHERE Rank = 2
ORDER BY Salary DESC

EDIT:

Why columns with equal salaries have a different rank?

The issue is that you partitioned data based on salary. Salaries with the same value are in single group. Now for that group ordering is performed by using employee_id column which is different per employee.
Without PARTITION BY the entire dataset is single partition and ranks are based on descending salary value.

A:
Why columns with equal salaries have a different rank?

Try following if you don't want see different RANK for same Salary
   DENSE_RANK() OVER (ORDER BY Salary desc) AS Rank,

My next question is if it's possible to find only the entities whose Rank is 2?

You can use either sub-query method or CTE, following is sub-query example
select *
from (
SELECT
   EmployeeID,
   FirstName,
   LastName,
   Salary,
   DENSE_RANK() OVER (ORDER BY Salary desc) AS Rank
FROM  Employees
WHERE Salary BETWEEN 10000 AND 50000
) as t
where r.rank = 2


text:
Q: Left outer join two tables through lookup table I have two tables
Person: { PersonId, Name }
Position: { PositionId, PositionName }

They are linked together through a lookup table [PersonPosition] { PersonId, PositionId }
The idea is one person can have 0 or more position.
How can I write entity query in C# to left outer join Person with Position through the [PersonPosition] lookup, and produce result like this:
[
{
   PersonId: "100":
   Position: ["Dev, QA"]
},
{
   PersonId: "200";
   Position: ["Dev"];
},
{
   PersonId: "300";
   Position: null;
},
]

Thanks,

A: You can do it with 2 LINQ queries (still might be not an optimal solution)
using System;
using System.Linq;

namespace AppTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var persons = new Person[]
            {
                new Person { Id = 100, Name = "Alpha"},
                new Person { Id = 200, Name = "Beta"},
                new Person { Id = 300, Name = "Gamma"}
            };

            var positions = new Position[]
            {
                new Position { Id = 1, Name = "Dev"},
                new Position { Id = 2, Name = "QA"},
                new Position { Id = 3, Name = "BA"}
            };

            var personPositions = new PersonPosition[]
            {
                new PersonPosition { PersonId=100, PositionId =1},
                new PersonPosition { PersonId=100, PositionId =2},
                new PersonPosition { PersonId=200, PositionId =2},
            };

            var positionsJoin = from position in positions
                                join personPositiontion in personPositions on position.Id equals personPositiontion.PositionId
                                select new
                                {
                                    personPositiontion.PersonId,
                                    position.Name
                                };

            var result = from person in persons
                         join personPositiontion in positionsJoin on person.Id equals personPositiontion.PersonId into jointTable
                         from joint in jointTable.DefaultIfEmpty()
                         select new
                         {
                             person.Id,
                             person.Name,
                             PositionName = joint?.Name
                         };

            foreach (var line in result.ToArray())
            {
                Console.WriteLine($"id:{line.Id}, name:{line.Name}, position:{line.PositionName}");
            }
        }
    }

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class Position
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class PersonPosition
    {
        public int PersonId { get; set; }
        public int PositionId { get; set; }
    }
}


text:
Q: using loop/foreach on args from graphQL's resolvers? I was wondering if it was possible to loop on "args" of a graphQL resolver ?
I would like to be able to do an automatic processing of arguments, the goal is to dynamically modify the restrictions of an SQL query.
for example :
  query  {
  getPerson(firstName: "Jane", lastName: "Doe") {
    someElement
  }
}

here, i want to do a SQL query in my resolver like :
SELECT *
FROM persons
WHERE firstName = "Jane"
AND lastName = "Doe"

but when my query is :
  query  {
  getPerson(firstName: "Jane", lastName: "Doe", email: "a.b@gmail.com") {
    someElement
  }
}

i would like :
SELECT *
FROM persons
WHERE firstName = "Jane"
AND lastName = "Doe"
AND email = "a.b@gmail.com"

so, there is something like ? :
foreach different args
   add "AND ... " to my Query's String

A: You can make each argument optional and then check if it was given and include it in your query. But because you didn't gave us your resolver we can't provide the needed changes.


text:
Q: How can we override getJobExplorer() when we create a SpringBatchConfig? I've extended my SpringBatchConfig from BatchConfigurer, and everything went right but when it comes to getJobExplorer, it returns NullPointerException when calling it:

    @Override
    @Bean
    public JobExplorer getJobExplorer() throws Exception {
        return jobExplorer;
    }

A: I did something like that and worked
public JobExplorer getJobExplorer() throws Exception {
        JobExplorerFactoryBean jobExplorerFactoryBean = new JobExplorerFactoryBean();
        jobExplorerFactoryBean.setDataSource(dataSource);
        jobExplorerFactoryBean.afterPropertiesSet();
        return jobExplorerFactoryBean.getObject();
    }


text:
Q: Search for String in XML that matches its ending with one Substring and contains another substring How can I replace a string that is under a CData element in an XML?
 Here I'm trying to match on 2 conditions like below:
<xsl:template match="@*[ends-with((local-name(),'mustEndWithThisSubstring'))] and not(contains((local-name(),'mustContainThisSubstring')))" >

1- How to have multiple conditions for the "xsl:match" section ?
2- How to replace the string matched on(unknown) with the desired string(known) ?
See the snippet below.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" cdata-
section-elements=replacingWith"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="@*[ends-with((local-name(),'mustEndWithThisSubstring'))] and not(contains((local-name(),'mustContainThisSubstring')))" >
    <xsl:copy>
            <replacingWith"/>
                       <xsl:value-of select="substring-after(., '<foundStringThatMatchesConditions>'), '</foundStringThatMatchesConditions>')"/>
            </replacingWith>
    </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Input:
<soap:Body>
  <pre:getResponse>
     <![CDATA[
           <foundStringThatMatchesConditions>
    .......
           </foundStringThatMatchesConditions>
    ]]>
</pre:getResponse>
</soap:Body>

Output:
<soap:Body>
  <pre:getResponse>
        <![CDATA[
               <replacingWith>
        .......
           </replacingWith>
        ]]>
</pre:getResponse>
</soap:Body>

A:
How can I replace a string that is under a CData element in an XML?

Exactly the way you replace a string in the value of any other text node.  Which is to say, no distinction is made after parsing between character data obtained from a CDATA section in the input document and other character data.  All are represented as text nodes in the XPath data model used also by XSLT.  In fact, they are subject to merging so that no text node has another text node as an immediately following sibling.  text() is a node test that matches text nodes specifically.
Note in particular that the contents of a CDATA section has no structure as far as XSLT is concerned.  Where CDATA is used to embed XML in another XML document, the contents of the section cannot be accessed (directly) as if they were XML.  For the host document's purposes, they aren't.
XSLT 1.0 does not have a built-in function for substring search and replace, but you can do it -- with a bit of effort -- via a template.  Refer to the substring-before(), substring-after(), and maybe contains() functions.
You also ask,

1- How to have multiple conditions for the "xsl:match" section ?

You can provide multiple predicates or use boolean operators to combine conditions inside the same predicate.  For example,
<xsl:template match="@*[ends-with(local-name(),'mustEndWithThisSubstring') and not(contains(local-name(),'mustContainThisSubstring'))]" >

or
<xsl:template match="@*[ends-with(local-name(),'mustEndWithThisSubstring')][not(contains(local-name(),'mustContainThisSubstring'))]" >

Where the relational operator is and, the two forms have similar, but not identical, semantics.  Do note, however, that those particular expressions match attributes (@*), which cannot either contain or be contained by CDATA.

2- How to replace the string matched on(unknown) with the desired
  string(known) ?

You may not know in advance which string will be matched against, but you certainly know in the context of the relevant template which text is being matched against.  In the expressions above, it is the return value of the local-name() function.  If you wish, you can capture this in a variable or pass it to another template as a parameter.  As I already said, it is possible to write a template to handle the job of string replacement.  The details are left as an exercise.