text:
Q: How to use goal seek function in Excel user function? There is method to use goal seek in MS excel like follows code. It works fine.
   Sub GSeek()
      With Worksheets("Sheet1")
             .Range("H18").GoalSeek _
              Goal:=.Range("H21").Value, _
               ChangingCell:=.Range("G18")
     End With
   End Sub

And I would like to use a function to do the goal seek like follows.
  Function fSeek(a As Range, b As Range, c As Range)
     a.GoalSeek Goal:=b.Value, ChangingCell:=c
     fSeek = "Ok"
   End Function

However, the code work peacefully and no answer was got in the range c. Where am I wrong?

A: I am writing an answer because it seems this question is resurging.
Bottom line is that User-Defined Functions (UDF) are not allowed to change other cells when invoked from a formula.
Solution: To automate godl-seeking, write a VBA macro, not a UDF.
A macro can automate goal-seeking on any range or set of cells. Since a macro does not have parameters, there are many ways to permit the user specify the set of cells to GoalSeek and the parameters, and to route these to the Range.GoalSeek method:
1- Design a dedicated UserForm
2- Use VBA's InputBox function, or possibly Excel's Application.InputBox fuction with parameter type:=8 to enter a range.
3- dedicate some cells on the worksheet where the user can enter the parameters.

A: Thank you all for answering me. I found my question again here after a long time.
I happened to find the solution to the this question by using the event.
In the Microsoft Excel Object-Sheet1(Sheet1), we can only write the following code:
 '----------------------------------------------
 ' Goal seeking when the worksheet changes.
 '----------------------------------------------
 ' Here we want to do goal seek for Range("H18")
 '  with the Goal cell as  Range("H21")
 '  and  the changing cell as Range("G18").
 '
 Private Sub Worksheet_Change(ByVal Target As Range)
     Range("H18").GoalSeek Goal:=Range("H21"), ChangingCell:=Range("G18")
 End Sub

Is it cool?
Yun


text:
Q: How to display French character encoding in RSS feed with python using feedgen I am using Feedgen to generate a RSS feed but how can I set the encoding to show French character.
app.py
# Flask package
# pip install flask
from flask import make_response
from flask import Flask, Response

# Other Python external packages
# pip install feedgen
from feedgen.feed import FeedGenerator

app = Flask(__name__, static_url_path='')

def get_feed_object():
    fg = FeedGenerator()
    fg.title("STO Bug")
    fg.description(
        "STO question"
    )
    fg.link(href="https://sto.com")
    return fg

@app.route("/", methods=("GET",))
def rss():

    fg = get_feed_object()

    downloads = [
        {
            'Survey': "Enquête sociale générale, cycle 29",
        },
        {
            'Survey': 'Enquête sociale générale, cycle 30',
        }
    ]

    for survey in downloads[:20]:
        fe = fg.add_entry()
        fe.title(
            survey["Survey"]
        )

    response = make_response(fg.rss_str(encoding='UTF-8'))
    response.headers.set("Content-Type", "application/rss+xml")

    return response

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)

A: I need to set the encoding in the response.header
response.headers.set("Content-Type", "application/rss+xml; charset=utf-8")

redpajama_set_name: RedPajamaStackExchange


text:
Q: NiFi | Controller Service is not getting updated I created a sample controller service - 'MyControllerService' and packaged it into nar and pasted into nifi lib directory. I restarted nifi service to see changes. I was able to see MyControllerService in Controller setting. After that i made small label change into controller service and followed same process but changes are not getting affected.
Even i removed nar files from nifi/lib just to check if it getting removed from list. That too not happening.
Even I don't see any exception in nifi/log.
Any pointer for this issue?

A: One potential reason is that when starting up NiFi it will unpack the nars into the work directory. Try stopping the NiFi instance, removing the NIFI-HOME/work/ directory and starting NiFi again.
This should force the changes to take effect.


text:
Q: UNQL with COUCHBASE I am having a requirement that i want to inserted the record into COUCHBASE using UNQL,Can any one suggest me how to connect COUCHBASE using UNQL.
Regards
Pradeep

A: Unql is an open project and a preview intended to help discussion on use cases for a query language with these newer databases.  It's not included in any release of Couchbase at the moment.
See couchbase.com/develop for info on how to insert data, etc.


text:
Q: How to fix Unity locked disabled settings? I am not able to adjust any of the settings in Ubuntu 14.04. Everything in Unity is locked/disabled. I've tried uninstalling Unity and reinstalling it. I've tried installing xscreensaver and that did not work. The PC would suspend and then lock after 5 minutes.
Then I tried opening unity from the terminal and when trying to change the lock settings this showed up... I have no idea what this means but maybe someone a little more knowledgeable can discern what it says and hopefully help me fix the problem?
(unity-control-center:4202): dconf-WARNING **: failed to commit changes to dconf:
GDBus.Error:org.gtk.GDBus.UnmappedGError.Quark._g_2dfile_2derror_2dquark.Code17:
Cannot open dconf database: invalid gvdb header

A: It seems that your ~/.config/dconf/user* files are corrupted. Try the following command, it should recreate a new one and allow you to store your settings persistently:
mv ~/.config/dconf/ ~/.config/dconf.bak

Note that you may loose some customization that you may have set on your system as all of them will be reset.
If it does not solve your problem all you have to do is:
mv ~/.config/dconf.bak ~/.config/dconf/


text:
Q: how to run multiple docker containers so that each container run the same applications/functions but with different arguments I have a python script doing data processing. On laptop, it probably takes 30 days to finish. A single function is being executed through a for-loop for hundreds of times. Each time a new argument will be feed into the single function.
I am thinking to design some parallel/distributed computing manner to speed up the script: divide the for-loop into multiple docker containers, and each container is responsible for a subset of the for-loop but with different arguments.
Here is some pseudo code:
def single_fun(myargs):
   #do something here
   data = file_data(myargs)
   post_process(data)

def main_fun():
   for i in range(100):
       single_fun(i)

my idea:

*

*docker container 1: take argument 1~5, run function single_fun()

*docker container 2: take argument 6~10, run function single_fun()

*docker container n: take argument n-5 ~ n, run function single_fun()

*after each docker container being finished, i can copy the results from each container, to the host computer hard drive.

My question: Is my idea doable? any useful feedback here? Thanks.
How do I implement this idea? Any framework or tool I can leverage to do finish this idea?


text:
Q: Send email if user hasn't logged in for X amount of time Is there a way to do the following:

*

*Find out when a user last logged into Wordpress.

*If it's longer than X amount of time then send an email alert.

Essentially the idea is to encourage users to log in and update the website.
I've found this plugin which gives me the last login time. I can also use wp_mail(); to send emails but how would I trigger all that / continually check it the last login date?

A: With the plugin you mentioned, you'll have a new database column in your wp_users table, which gives you a good starting point.
Next, as @bswatson mentioned, you can leverage WP Cron to run a task that checks for inactive users (if low site traffic is a concern, you might consider setting up WP Cron to use a real cron job). The daily task would look something like this:

*

*Collect all users from the database who haven't logged in in the last X days or more.

*

*You might consider installing the plugin before rolling out the cron task, or risk emailing everyone.

*As you probably don't want to spam people daily, I'd recommend adding a bit of user meta to indicate this person has been emailed already; you can filter out those users as you build your list of people to email, then delete that user meta when the user logs in.

*Depending on the size of your WordPress site, you'll probably want to limit this to only a few users; it might make sense to email admins and editors (people with publishing capabilities) but maybe not authors/contributors/subscribers. If you need to email large numbers of people, I'd recommend batching (you can even register cron jobs from within cron jobs) to avoid sending out dozens/hundreds/thousands of emails at once.

*Loop through the users, emailing them using wp_mail() to nudge them to log in.

*

*Once an email is sent, add a bit of user meta to prevent duplicate emails.

Good luck!

A: Well it depends on what options you have on your hosting. I don't know how to do it purely in WordPress (and I don't know if something like that is possible).
But I would use some cron job to run some small script. If you can use system cron, of course.
EDIT:
I found this WP plugin. But as I suspected, it depends on users visiting your website. So if you want to send emails independently on your website traffic, then you need to use some OS solution.

A: WordPress has a built in system called WP Cron which mimics a system cron, but can be set up and configured directly in code. There are some drawbacks, such as needing traffic to kick of a task.
Here's a pretty thorough breakdown of how WP Cron works including some ways to workaround the issues.


text:
Q: Li-Po Battery Charging and UPS Scenario:
The main device is a bank of Li-Po 18650 batteries as the main power source. Sometimes the device will be plugged into AC power when needed for longer periods of time than what the battery packs will handle. Sometimes the device will not be plugged into AC power and will only use the battery packs as the power source. If connected to AC power and there is a power loss, the device should switch to the battery pack for power (UPS). The main device will power 2 other devices. One will be 5V @ approximately 800 milliamps. The second device will be 12V @ approximately 1 amp.
Questions:

*

*What charging options are available for this many batteries in this configuration?

*Is there a charging option that will keep the batteries balanced in this configuration?

*Should I be using batteries with protection IC?

*I found this board that sounds like it may work, but is there something similar that is cheaper or is there a better board for my setup? Open UPS

*Is my layout ok? If not, what should I change?
Thanks!

A: Check the battery manufacturers charging specification data sheet for the details on the chemistry / battery type you want to use.
Letting the batteries discharge too quickly or letting them discharge to a low voltage can permanently damage them. Also the charging rate needs to be within the manufacturers specification or you will damage the chemistry / life.
The batteries tend to self balance themselves, however again most manufacturers don't recommend using multiple batteries in parallel.
That board looks cool, and it probably will save a lot of work, and end up costing about the same as diy.

A: 1) Given that you're using regulators to power your downstream system, you could get away with simply connecting a Li-Po-compatible battery charger to your +ve & -ve buses, because the charger isn't going to apply any more than 4.2V per cell-in-series (i.e. 8.4 Volts).  But bear in mind that when recharging, the Li-Po charger will need to be rated for the power demand of both charging (at the rate you choose) AND the load (assuming you want the device to work while charging).
2) Certainly. Many options.  Do the math on the max recharge current needed to recharge this behemoth of yours within the time period you need.  Google.  Just know that putting 9 cells in parallel is non-trivial, make sure you initially connect them together in a fully charged state, and to use BPMs on each cell.  Having 2 such batteries in series to get you 8.4V (full, down to 6.0V flat) suggests 'cell balancing' would be ideal, but whether you can find a charger within budget that will do balancing at whatever your system current draw is, can't be gleaned from your question.
3) *Always (*almost). Li-Po are fickle and deadly mistresses.  Anything above 4.25V (check datasheets for your particular 18650s), anything below ~3.0V (check datasheets), current's in excess of their stated Maximum-xC-discharge-rate, will shorten the life of the cells well beyond reasonable expectations.  That's why cell/battery protection modules/PCBs are typically added to 'loose' Li-Pos, to protect hobbyists from what most of them don't understand.
4) It's nice, but its 'power path' feature probably isn't needed in your application, and if it's too expensive, then look for simpler recharge-only alternatives, which comes back to Question-2.
5) as someone commented above, you also want 'under-voltage lock out' (UVLO) between battery & voltage-regulators (or Vregs with settable UVLO threshold voltage), to stop your system bleeding the battery dry below the safe level of ~3.0V/cell.
It's hard to be specific or more helpful without (a) knowing a lot more about what's being powered & for how long, & (b) finding someone else willing to engineer this for you properly.


text:
Q: Overwrite not working as expected I am trying to display a message in template when there are no viewed_products. So I have tried to overwrite class Mage_Reports_Block_Product_Viewed and its method like this.
Module etc/config.xml file
<config>
    <global>
        <blocks>
            <reports>
                <rewrite>
                    <product_viewed>Myclass_Overwrites_Block_Reports_Product_Viewed</product_viewed>
                </rewrite>
            </reports>
        </blocks>
    </global>
</config>

Block in app/code/local/Myclass/Overwrites/Block/Product/Viewed.php
class Myclass_Overwrites_Block_Reports_Product_Viewed extends Mage_Reports_Block_Product_Viewed
  {
    ...

      protected function _toHtml(){

             if ($this->getCount()) {
               $this->setRecentlyViewedProducts($this->getItemsCollection());
             }
         return parent::_toHtml();
       }
...
  }

Now it overwrites it, if i click on a product and refresh the page i can clearly see with debuging ON that its getting overwritten and that product is shown. But if i don't click on a product (if visited product/s arent stored) it doesnt show anything (i guess it runs the class from Core, i also tried to change it just to see if it would work in core files and it does). I am doing this because i want to show else statement from template
Template design/frontend/Project/default/template/reports/product_viewed.phtml
 <?php if ($_products = $this->getRecentlyViewedProducts()): ?>

 //Code if there are Viewed Products

 <?php else: ?> // This doesn't show

<?php echo $this->__('Recently Viewed Products') ?>

You haven't viewed any Products

Am i doing something wrong or could i do this some other way?

A: Please follow bellow steps:
Module etc/config.xml file
<config>
    <global>
        <blocks>
            <reports>
                <rewrite>
                    <product_viewed>Myclass_Overwrites_Block_Reports_Product_Viewed</product_viewed>
                </rewrite>
            </reports>
        </blocks>
    </global>
</config>

created block in app/code/local/Myclass/Overwrites/Product/Viewed.php
> and a class has to be defined
class Myclass_Overwrites_Block_Reports_Product_Viewed extends Mage_Reports_Block_Product_Viewed
{
// some code
}

A: I havent figured out how to display Recently viewed products if the user didnt click on any product. So i have left it by defualt to not show.


text:
Q: PowerShell keyboard shortcuts Currently I am using Bash on Windows via MSYS2. I have this file .inputrc:
"\33[1;3A": "cd ..\n"

Whenever I press Alt Up Arrow, it moves to the parent directory. Does PowerShell
have a similar method to map shortcuts?

A: Yes, PowerShell on Windows 10 uses "PSReadline" which mimics bash's Readline in many ways (though not in the terseness of ~/.inputrc). The module is also installable on older Windows.
However, I haven't actually managed to bind Alt+UpArrow successfully – no events are generated for it even if I call [System.Console]::ReadKey() – so you might have to use Ctrl instead.
You can bind keys using Set-PSReadLineKeyHandler, either to a familiar PSReadline action or to a custom PowerShell function:
Set-PSReadLineKeyHandler -Chord Ctrl+UpArrow -ScriptBlock {
    [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()
    [Microsoft.PowerShell.PSConsoleReadLine]::Insert("cd ..")
    [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
}

Overall this is similar to using the 'bind' command in ~/.bashrc, and to make such bindings persistent you need to put them in PowerShell's profile script, which is located at $Profile:
PS> $Profile.CurrentUserAllHosts
C:\Users\Me\Documents\WindowsPowerShell\profile.ps1

PS> $Profile.CurrentUserCurrentHost
C:\Users\Me\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

A: The other answer is excellent, but this seems to work too:
Set-PSReadLineKeyHandler Ctrl+UpArrow {
   Set-Location ..
   [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
}

https://docs.microsoft.com/PowerShell/module/psreadline/Set-PSReadlineKeyHandler


text:
Q: changing repeats value of UNTimeIntervalNotificationTrigger i have a local notification that i am repeating every 60s:
var trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true);

i want to change the repeats value of the UNTimeIntervalNotificationTrigger from true to false if a certain condition is met i.e.:
if (condition) {
    trigger!.repeats = true;
}

however this doesn't seem to work as i dont think i can change the repeats value after creating the object.
is there any way to do what i'm trying to do?

A: You can remove the local notification as
UIApplication.shared.cancelAllLocalNotifications()

And if you want to true again then again assign
trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)

May be this Work


text:
Q: Access 2010, insert bold label in ribbon Is-it possible to insert bold label in a ribbon Access or change the color or font of some label ?
Excuse my very bad English
Thank you in advance,
Franck

A: I double it. I don't see an attribute for font family or font weight. The available attributes for labels are (from here look for the label)
enabled
id
idMso
idQ
insertAfterMso
insertAfterQ
insertBeforeMso
insertBeforeQ
label
screentip
showLabel
supertip
tag
visible

A full XSD for the ribbon XML can be found here


text:
Q: xpath getting the name in a certain pattern I want to get a class name like the following:
class="hostHostGrid0_body"

The integer in between hostHostGrid and _body can change, but everything else I want it just like that in the order.
How can I achieve this?

A: In XPath 1.0 you can use this:
//*[starts-with(@class,'hostHostGrid') and substring-after(@class,'_') = 'body']

to select any element containing one class. It will match tags in any context. It will match all three elements below:

    xxx

Limitations: it doesn't restrict what is between them to a number. It can be anything, including spaces (ex: it will also match this: class="hostHostGrid xyz abc_body")
This one allows for the class occurring among other classes:
//*[contains(substring-before(@class,'_body'),'hostHostGrid')]

It will match:

    xxx

(it also has the same limitations - will match anything between 'hostHostGrid' and '_body')


text:
Q: A tree structure recursive algorithm with numpy I constructed several arrays using the "previous" array, following this rule :
D = 500
eta = 10
T = 4

D1 = np.array([D-eta, D+eta])
D2 = np.array([[D1-eta], [D1+eta]], dtype=object)
D3 = np.array([[D2-eta], [D2+eta]], dtype=object)
D4 = np.array([[D3-eta], [D3+eta]], dtype=object)
D5 = np.array([[D4-eta], [D4+eta]], dtype=object)

I would like to create Ds area more efficiently, using T value. But before I would like to fully unzip each D area.
For instance, for D2, output is :
[[[480 500]]
[[500 520]]]
and I would like to get :
[480, 500, 500, 520]
Do you know how the extract simply the results ?
By the way I would like to use these arrays for a backward algorithm, for instance at t = 4, for Dt = 480, I would like to to use the mean value of 490 and 470...
Thanks all in advance !

A:
Do you know how the extract simply the results?

Use np.ravel. Check your output with print(np.ravel(D2))

A: The function np.hstack allows you to stack the arrays. I'll then go for something like this:
Dt = np.array(D)
for i in range(T):
    Dt = np.hstack([Dt - eta, Dt + eta])


text:
Q: What's the mobile industry standard for handling timezones? I make mobile apps that use web services coming from a .NET server that I do not control.
We always run into trouble when scheduling events that are in different timezones.
The server is on EST time and much of the data coming from the web services are presented this way.
We end up having to add display dates fields and it's very confusing.
In addition, I have code that is essentially the same except it depends if I'm talking to the server or if I'm calculating something on the device. Also a pain.
Here is an example of what I'm doing to handle the EST times:
Data Coming In:
- (void)initWithWebServiceData:(NSDictionary *)data {

    self.scheduleDate = [self dateFromDotNetJSONString:data[@"ScheduleDate"]];

    //...and other stuff
}

- (NSDate *)dateFromDotNetJSONString:(NSString *)stringInEST {

    int secondsESToffset = 14400;

    static NSRegularExpression *dateRegEx = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dateRegEx = [[NSRegularExpression alloc] initWithPattern:@"^\\/date\\((-?\\d++)(?:([+-])(\\d{2})(\\d{2}))?\\)\\/$" options:NSRegularExpressionCaseInsensitive error:nil];
    });
    NSTextCheckingResult *regexResult = [dateRegEx firstMatchInString:stringInEST options:0 range:NSMakeRange(0, [stringInEST length])];

    if (regexResult) {
        // milliseconds
        NSTimeInterval seconds = [[stringInEST substringWithRange:[regexResult rangeAtIndex:1]] doubleValue] / 1000.0;
        // timezone offset
        if ([regexResult rangeAtIndex:2].location != NSNotFound) {
            NSString *sign = [stringInEST substringWithRange:[regexResult rangeAtIndex:2]];
            // hours
            seconds += [[NSString stringWithFormat:@"%@%@", sign, [stringInEST substringWithRange:[regexResult rangeAtIndex:3]]] doubleValue] * 60.0 * 60.0;
            // minutes
            seconds += [[NSString stringWithFormat:@"%@%@", sign, [stringInEST substringWithRange:[regexResult rangeAtIndex:4]]] doubleValue] * 60.0;
        }
        return [NSDate dateWithTimeIntervalSince1970:seconds - secondsESToffset];
    }
    return nil;
}

Data Going Out:
- (void)requestRegistrationForEvent
{
    NSString *fullDateTime = [NSString stringWithFormat:@"%@ %@", [self.scheduleDate webServiceStringValue], [self.scheduleDate dateTimeText]];

    [self.dataController requestRegistrationForEvent:[self.eventID stringValue]
                                              onDate:fullDateTime];
}

- (NSString *)webServiceStringValue {

    NSString *webServiceStringValue = nil;

    if ([self isKindOfClass:NSDate.class]) {
        NSDate *date = (NSDate *)self;

        //format the date how the web service expects it
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"M/d/yyyy"];

        NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
        [dateFormatter setTimeZone:gmt];

        webServiceStringValue = [dateFormatter stringFromDate:date];
    }
    return webServiceStringValue;
}

- (NSString *)dateTimeText {

    NSString *text = @"";
    NSDate *date;

    if ([self isKindOfClass:NSDate.class]) {

        date = (NSDate *)self;

        NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
        [timeFormatter setDateFormat:@"h:mm a"];

        NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
        [timeFormatter setTimeZone:gmt];

        text = [timeFormatter stringFromDate:date];

        text = [text lowercaseString];
        text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    return text;
}

Question
Am I doing something wrong and what can I recommend to my .NET partner to handle timezones?

A: It's not so much about a mobile industry standard as an integration and international time standard: timestamps should use always use offsets or UTC (zulu) time. GMT is a timezone, like EST, so UTC is preferred as a universal time. It just so happens that GMT does not observe daylight savings time so it is often interchangeable. Your partner should send timestamps in the UTC standard: https://en.wikipedia.org/wiki/ISO_8601, which looks like 2014-11-09T10:37:27+00:00, or zulu: 2014-11-09T10:37:27Z. Sometimes folks use variants such as 2014-11-09 10:37:27UTC, but you can build a date formatter for any of them.
The date format will be dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSz". I usually put a UTC date format factory into an NSDateFormatter category.
If the day is the only thing that matters and the exact time truly doesn't, than your method should be sufficient, except that you will also need to format anything resulting from the timestamp without times or do calculations using calendars.


text: Q: What is the equivalent of System.Drawing.Graphics.CopyFromScreen in UWP? I need to use CopyFromScreen but as far as I can see System.Drawing.Graphics is unavailable on the Universal Windows Platform. What can I use instead?


text:
Q: How to create zipcode boundaries in R I am trying to create a map that has the name of the 'community' showing the boundaries of multiple zip codes. Data that I have is similar to below. Where the variable is the name of the community and the numbers are the corresponding zipcodes.
Tooele       <- c('84074','84029')
NEUtahCo     <- c('84003', '84004', '84042', '84062')
NWUtahCounty <- c('84005','84013','84043','84045')

I was able to make a map of the entire area I want using
ggmap(get_map(location = c(lon=-111.9, lat= 40.7), zoom = 9))

Attached is a picture of what I want.

A: You have a decent foundation for this already by having figured out the shapefile and how it matches the zips you want to show. Simple features (sf) make this pretty easy, as does the brand new ggplot2 v3.0.0 which has the geom_sf to plot sf objects.
I wasn't sure if the names of the different areas (counties?) that you have are important, so I just threw them all into little tibbles and bound that into one tibble, utah_zips. tigris also added sf support, so if you set class = "sf", you get an sf object. To keep it simple, I'm just pulling out the columns you need and simplifying one of the names.
library(tidyverse)
library(tigris)
library(ggmap)

Tooele       <- c('84074','84029')
NEUtahCo     <- c('84003', '84004', '84042', '84062')
NWUtahCounty <- c('84005','84013','84043','84045')
utah_zips <- bind_rows(
  tibble(area = "Tooele", zip = Tooele),
  tibble(area = "NEUtahCo", zip = NEUtahCo),
  tibble(area = "NWUtahCounty", zip = NWUtahCounty)
)

zips_sf <- zctas(cb = T, starts_with = "84", class = "sf") %>%
  select(zip = ZCTA5CE10, geometry)

head(zips_sf)
#> Simple feature collection with 6 features and 1 field
#> geometry type:  MULTIPOLYGON
#> dimension:      XY
#> bbox:           xmin: -114.0504 ymin: 37.60461 xmax: -109.0485 ymax: 41.79228
#> epsg (SRID):    4269
#> proj4string:    +proj=longlat +datum=NAD83 +no_defs
#>       zip                       geometry
#> 37  84023 MULTIPOLYGON (((-109.5799 4...
#> 270 84631 MULTIPOLYGON (((-112.5315 3...
#> 271 84334 MULTIPOLYGON (((-112.1608 4...
#> 272 84714 MULTIPOLYGON (((-113.93 37....
#> 705 84728 MULTIPOLYGON (((-114.0495 3...
#> 706 84083 MULTIPOLYGON (((-114.0437 4...

Then you can filter the sf for just the zips you need—since there's other information (the county names), you can use a join to get everything in one sf data frame:
utah_sf <- zips_sf %>%
  inner_join(utah_zips, by = "zip")
head(utah_sf)
#> Simple feature collection with 6 features and 2 fields
#> geometry type:  MULTIPOLYGON
#> dimension:      XY
#> bbox:           xmin: -113.1234 ymin: 40.21758 xmax: -111.5677 ymax: 40.87196
#> epsg (SRID):    4269
#> proj4string:    +proj=longlat +datum=NAD83 +no_defs
#>     zip         area                       geometry
#> 1 84029       Tooele MULTIPOLYGON (((-112.6292 4...
#> 2 84003     NEUtahCo MULTIPOLYGON (((-111.8497 4...
#> 3 84074       Tooele MULTIPOLYGON (((-112.4191 4...
#> 4 84004     NEUtahCo MULTIPOLYGON (((-111.8223 4...
#> 5 84062     NEUtahCo MULTIPOLYGON (((-111.7734 4...
#> 6 84013 NWUtahCounty MULTIPOLYGON (((-112.1564 4...

You already have your basemap figured out, and since ggmap makes ggplot objects, you can just add on a geom_sf layer. The tricks are just to make sure you declare the data you're using, set it to not inherit the aes from ggmap, and turn off the graticules in coord_sf.
basemap <- get_map(location = c(lon=-111.9, lat= 40.7), zoom = 9)

ggmap(basemap) +
  geom_sf(aes(fill = zip), data = utah_sf, inherit.aes = F, size = 0, alpha = 0.6) +
  coord_sf(ndiscr = F) +
  theme(legend.position = "none")

You might want to adjust the position of the basemap, since it cuts off one of the zips. One way is to use st_bbox to get the bounding box of utah_sf, then use that to get the basemap.


text:
Q: num_rows is 0 when it should be >0 for php mysqli code My num_rows is coming back as 0, and I've tried calling it several ways, but I'm stuck.  Here is my code:
    $conn = new mysqli($dbserver, "dbuser", "dbpass", $dbname);

    // get the data
    $sql = 'SELECT AT.activityName, AT.createdOn
            FROM userActivity UA, users U, activityType AT
            WHERE U.userId = UA.userId
            and AT.activityType = UA.activityType
            and U.username = ?
            order by AT.createdOn';
    $stmt = $conn->stmt_init();
    $stmt->prepare($sql);
    $stmt->bind_param('s', $requestedUsername);
    $stmt->bind_result($activityName, $createdOn);
    $stmt->execute();

    // display the data
    $numrows = $stmt->num_rows;
    $result=array("user activity report for:  " . $requestedUsername . " with " . $numrows . " rows:");
    $result[]="Created On --- Activity Name";
    while ($stmt->fetch())
    {
        $msg = " " . $createdOn . " --- " . $activityName . " ";
        $result[] = $msg;
    }

    $stmt->close();

There are multiple rows found, and the fetch loop process them just fine.  Any suggestions on what will enable me to get the number of rows returned in the query?
Suggestions are much appreciated.  Thanks in advance.

A: You need to call $stmt->store_result() first, just before $stmt->num_rows.

A: Try to add this before you call num_rows;.
$stmt->store_result();

A: I don't know if this will fix it, but you can't bind_results until after you execute the query, if I'm not mistaken.
Also your while loop:
while ($stmt->fetch())
 {
     $msg = " " . $createdOn . " --- " . $activityName . " ";
     $result[] = $msg;
 }

you will lose all of the $msg variables with each iteration of the loop, except the last setting because you either need to do $msg .= or make $msg an array $msg[] =

A: $stmt->store_result();
$numrows = $stmt->num_rows;

Check this: http://php.net/manual/en/mysqli-result.num-rows.php and this
http://php.net/manual/en/mysqli-stmt.num-rows.php


text:
Q: table of contents: adding a vertical space In a table of contents that has been generated with LaTeX's \tableofcontents command, I would like to add a vertical space before a Chapter item in the table of contents. One way that I have in my notes is to use
\addtocontents{toc}{\protect\vspace{10pt}}

at a desired location in the document so that this gets processed by \tableofcontents to include an appropriate vertical space in the table of contents. I have two questions:

*

*Is the above the correct way to get a vertical space in a table of contents?

*Why is it necessary to use the \protect command here?
Thank you...

A: *

*It's the correct way if it's just for fine tuning the final appearance of the table of contents; if it's a general need for all chapters, customizing directly the table of contents typesetting would be preferable.

*\addtocontents writes to the .toc file and this causes commands to be expanded, but you want to write \vspace{10pt} in the .toc file, not the instructions to leave a space (that will be done when the .toc file is read).


text:
Q: Saving images faster on disk I have developed a  Python multi-thread program, one producer thread which acquires frames (512 x 640, 16uint) at high fps (around 75 fps), and two consumer-threads, one for real-time visualization and other for saving as 16-bit tiff. For each one of the consumers, I use a different queue.
Visualizing at real-time works fine, but saving takes so much time after the video is stoped ( even 20 seconds for a 2-minute recording). For saving, I used tifffile library or cv2, with similar performances.
UPDATED info
The images are gray-scale 16-bit numpy arrays directly placed in the queue, not compression, saved using tifffile.imsave. The second queue for visualization works properly on real-time, so saving must be the slowest process. I need to save each image independently, saving 3D is not an option for the time being. Using different threads for saving may ruin my acquisition order.
Is there any way, both in Python and/or OS (windows10) to accelerate the process, taking into account I need to save them in the same order they were recorded? I have a SSD 970 EVO disk drive
 class VideoGet():

            def __init__(self,input_dict,folder,record):
                self.handle=input_dict['handle']
                self.frame_t=input_dict['frametype']
                self.frameSize= input_dict['frameSize']
                # self.buffer = np.zeros(shape=(513,640), dtype=np.uint16)
                self.record = record
                self.save = False
                self.done=False
                self.counter=0
                self.folder = folder

            def displayer(self,q2):

                while self.record is True:
                    if q2.empty() is True:
                        pass
                    else:
                        framedisplay = q2.get()
                        cv2.namedWindow("Video", cv2.WINDOW_NORMAL)
                        cv2.imshow("Video", framedisplay[:-1,:])

                        cv2.waitKey(1)
                        q2.task_done()

                cv2.destroyAllWindows()

            def consumer(self,q):
                data=[]

                while True:

                        if q.empty():
                            time.sleep(0.002)
                            pass

                        else:

                            frame_get = q.get()
                            if frame_get is None:
                                print('gone')
                                break
                            imsave(os.path.join(self.folder,(str(self.counter).zfill(5)+'.tiff')), frame_get[:-1,:])
                            if self.counter==0:
                                TS=1.0e-3 *struct.unpack('Q',(frame_get[-1,6:10]).tobytes())[0]
                            entr=[str(self.counter).zfill(5),str(round(1.0e3*(1.0e-3 *struct.unpack('Q',(frame_get[-1,6:10]).tobytes())[0]-TS)))]
                            data.append(entr)

                            self.counter=self.counter+1
                            q.task_done()

                if data:
                      df = pd.DataFrame(data, columns = ['Picture', 'Timestamp'])
                      df.to_csv(os.path.join(self.folder,'timestamps.txt'), header=False, index=False, sep=' ')
                      print('done')
                      self.done=True

            def producer(self,buffer,q,q2):

                while self.record is True:

                   buffer=np.empty_like(buffer)
                   if camera.properties.get_frame(self.handle,self.frame_t,4,buffer,self.frameSize)==0:
                       frame=buffer
                       q2.put(frame)

                       if self.save is True:
                           q.put(frame)

                       del frame

                print('None')
                q.put(None)

            def run(self,buffer,q,q2):

                    prod_thread=Thread(target=self.producer,args=(buffer,q,q2,))
                    display_thread=Thread(target=self.displayer,args=(q2,))
                    con_thread= Thread(target=self.consumer, args=(q,))

                    prod_thread.start()
                    display_thread.start()
                    con_thread.start()

A: It's hard to say what's going wrong when you don't show your code. Also, it is not clear to me why the acquisition order would change if you have multiple writers.
Here is a script to generate synthetic frames the same size as your images and save them as TIFF files, in order. It scales up in speed pretty linearly with more writer threads:
NFRAMES      NWRITERS       TIME(s)
1000            1             1.48
1000            2             0.78
1000            4             0.48

#!/usr/bin/env python3

import time
import numpy as np
import threading, queue
from tifffile import imsave

def writer(q):
    print('[WRITER] Started')
    total = 0
    while True:
        (frameNum, im) = q.get()
        if frameNum < 0:
            break
        # Save as TIFF
        imsave(f'frame-{frameNum}.tif', im)
        total += 1
    print(f'[WRITER] Complete: wrote {total} frames')

if __name__ == "__main__":

    # Edit these to suit
    NFRAMES = 1000
    NWRITERS= 4

    # Create dummy image of correct size
    h, w = 640, 512
    im = np.random.randint(0, 65536, (h,w), dtype=np.uint16)

    # Create a queue to pass frames to writer(s)
    q = queue.Queue(16)

    print('[MAIN] Started')
    start = time.time()

    # Create and start writer thread(s)
    threads = []
    for _ in range(NWRITERS):
        t = threading.Thread(target=writer, args=(q,))
        t.start()
        threads.append(t)

    # Generate a large number of frames to store
    for frameNum in range(NFRAMES):
        # Put a tuple of frameNum and image in queue
        q.put((frameNum, im))

    # Sentinel to tell each writer to exit
    for _ in range(NWRITERS):
        q.put((-1,-1))

    # Wait for our writer thread(s) to exit
    for thread in threads:
       thread.join()

    elapsed = time.time() - start;
    print(f'[MAIN] Complete: {NFRAMES} frames, with {NWRITERS} writers in {elapsed} seconds')

Sample Output
[MAIN] Started
[WRITER] Started
[WRITER] Started
[WRITER] Started
[WRITER] Started
[WRITER] Complete: wrote 250 frames
[WRITER] Complete: wrote 250 frames
[WRITER] Complete: wrote 250 frames
[WRITER] Complete: wrote 250 frames
[MAIN] Complete: 1000 frames, with 4 writers in 0.4869719505310059 seconds

One thing I noticed, is that it runs about 10% faster if you replace tifffile.imsave() with:
np.save(f'frame-{frameNum}.npy', im)


text:
Q: Angular.js share controller methods I am working on a CMS that I originally was using Knockout but I decided to try Angular because it like more of its functionality. In the CMS, one of the sections will be 'Users'. It has a table that allows the headers to be clicked to sort the data. The controller is below:
userControllers.controller('UserListControl', ['$scope', 'User',
    function($scope, User) {
        $scope.users = User.query();

        $scope.columns = [
            { 'field': 'last', 'label': 'Last Name' },
            { 'field': 'first', 'label': 'First Name' },
            { 'field': 'username', 'label': 'Username' },
            { 'field': 'email', 'label': 'Email' },
        ];
        $scope.orderProp = 'last';
        $scope.orderDirection = false;
        $scope.tableSort = function(field) {
            if ($scope.orderProp === field) {
                $scope.orderDirection = !$scope.orderDirection;
            }
            $scope.orderProp = field;
        };
        $scope.tableSortClass = function(field) {
            if ($scope.orderProp === field) {
                if ($scope.orderDirection) {
                    return 'sortDesc';
                }
                return 'sortAsc';
            }
        };
    }]);

It is part of my adminApp that I created. Since there will be other sections that will also use the table sort properties (orderProp, orderDirection) and methods (tableSort, tableSortClass), is there a place I can put these methods so my eventual recordsController will also have access to them?
OK, so I am trying to create it using a service and factory function. This is all new to me so I am not completely sure what I am doing but here is what I have:
adminServices.factory('TableSort', [
    function() {
        var orderProp = 'id';
        var orderDirection = false;

        function sort(field) {
            alert('test');
            if (orderProp === field) {
                orderDirection = !orderDirection;
            }
            orderProp = field;
        }

        function sortClass(field) {
            if (orderProp === field) {
                if (orderDirection) {
                    return 'sortDesc';
                }
                return 'sortAsc';
            }
        }
    }]);

I was hoping to access them in my html using something like ng-click="TableSort.sort(field)" but it doesn't work as it is right now.

A: You can use a Service or a Factory to hold these common methods. Additionally, you could use the $rootScope.

A: You can create a service and put all those properties and method in it. Here is an example for the same:
userControllers.service('UserListControl', function() {
    var orderProp = 'last';
    var orderDirection = false;
    return {
       tableSort : function(field) {
        if (orderProp === field) {
            orderDirection = !orderDirection;
        }
        orderProp = field;
    };
      tableSortClass: function(field) {
        if (orderProp === field) {
            if (orderDirection) {
                return 'sortDesc';
            }
            return 'sortAsc';
        }
    };
   }
});

A: As stated above in the other posts, you can create a service that you can inject into various controllers to "share" the code.
Below is a full example:
myApp.service('myService', function myService() {
    return {
        someVar: "Value",
        augmentName: function(name){
            return "Sir " + name;
        }
    }
});

This first piece is the service. I've defined a "myService" and given it one function "augmentName" Now you can inject the myService and access the augment name function.
myApp.controller('testCtrl', function ($scope, myService) {

    $scope.testFunction = function(name){
      console.log(myFunction.someVar); //This will access the service created variable
      return myService.augmentName(name);
    }
}

The controller injects the service and then calls it within one of its functions.
Now your HTML code should have access to the controller if you have defined an ng-controller with "testCtrl" or if you have put testCtrl as the controller in your router.
You can now call ng-model="testFunction(someName)" and it will resolve as expected.
Hope that helps. Let me know if you want me to go into greater depth
If you are still trying to figure out how everything in angular works, the angular phone cat tutorial helped me allot when I started out. I'd recommend donating an hour or so into playing with it.
Also, I highly recommend experimenting as early as possible with yeoman/angular generator, this will force you to use angular "the angular way" and can really help you with getting your project set up correctly.


text:
Q: (Opencart)Не обновляется stylesheet.css в браузере Редактирую stylesheet.css в редакторе потом загружаю через ftp,при просмотре файла в редакторе изменения есть,но в браузерах старые стили.Есть sass файлы ,так для инфы.

A: В opencart 3 используется шаблонизатор twig с его родным кешированием. В админку под этот случай выведена кнопка управления кешированием (шестерёнка - см. скриншот). Она даёт возможность управлять кешированием на стадии разработки


text:
Q: iPhone ALAssets: Can assets be destructively edited? Looking at the ALAssetsLibrary API, I see a few methods for creating new assets:
writeImageDataToSavedPhotosAlbum:metadata:completionBlock:
writeImageToSavedPhotosAlbum:metadata:completionBlock:
writeImageToSavedPhotosAlbum:orientation:completionBlock:
writeVideoAtPathToSavedPhotosAlbum:completionBlock:
These seem to indicate that you should only be creating new assets. My question though is this: Is there a way to make destructive edits to assets? Or do you always create new images for the edits? I'm hoping for the latter as I want each asset to be treated as a unique, created only once asset.

A: I have found no possible way to remove or alter assets in the library. Its kind of a pain when I create items in the assets library and I cannot remove them. But that appears to be apples wishes. Most likely because they do not want an app to be able to delete images and videos from the users library. Only by going to the camera app or another "Apple" app will the asset be able to be removed.
I kind of wish they would let you popup a delete confirmation window for an asset to let the user decide on a (apple created) confirmation page.

A: I haven't tried it, but as of iOS 5 it seems to be possible to edit an image using the setImageData method on ALAsset, if the image is flagged as editable (only if the image was originally created by your app):
http://developer.apple.com/library/ios/#documentation/AssetsLibrary/Reference/ALAsset_Class/Reference/Reference.html#//apple_ref/occ/instm/ALAsset/setImageData:metadata:completionBlock:
It doesn't seem to be possible to delete images though.


text:
Q: MSSQL c++ connector I am looking for a way to connect to a MS SQL database from a unmanaged C++ program.
The only thing that I found is http://www.sqlapi.com/, but this is payed, any idea of a free alternative?
Also I would like a solution that has both a Linux and Windows connector.

A: How about standart API: ODBC?
You may see a good example of connector in this link:
http://cs.dvc.edu/HowTo_SQL.html
But there are a string:
char db[] = "myDatabase"; // ODBC database name

It isn't a database name, it's name of server. For example: MSSQLSERVER.


text:
Q: There is any official "Inputmask" or "a mask for a input field" in Angular 4? There is any official input mask in angular 4?
Would be great if we had a official lib.
I'm trying some users libs but they are broken.

A: Seems to don't have a official lib.
But I test this one that developer033 recommended  and worked very well:
github.com/text-mask/text-mask


text:
Q: ZipFile to File to FileField Django Python I'm doing a call from a API that give me a zip file with two file in it.
I manage to extract the file i need (cause it's a PDF)
and now i just can't find a solution to save it in my filefield without creating the file in my pc.
        with ZipFile(io.BytesIO(response3.content)) as z: # response3 is my response to the API
            for target_file in z.namelist():
                if target_file.endswith('pdf'):
                    z.extract(member=target_file) # that's how i can have acces to my file and know it is a valid PDF

                    # here begin the trick
                    with io.BytesIO() as buf:
                        z.open(target_file).write(buf)
                        buf.seek(0)
                    f = File.open(buf) # File is an import of django.core.files
                    rbe, created = RBE.objects.update_or_create(file=f)

With this code i get an error with write of z.open(...).write as below:
    z.open(target_file).write(buf)
io.UnsupportedOperation: write

Thanks :)

A: So with intense hardwork 2 migraine and 1 ragequit i finally manage it.
Hope it might help someone
        with ZipFile(io.BytesIO(response3.content), 'r') as z:
            for target_file in z.namelist():
                if target_file.endswith('pdf'):
                    with z.open(target_file) as myfile:
                        with io.BytesIO() as buf:
                            buf.write(myfile.read())
                            buf.seek(0)
                            file = File(buf, target_file) # still the File from django
                            rbe = RBE.objects.create(file=file, establishment=establishment)


text:
Q: why the function returns value to the previous function when it is not returned in the code? why the following code is returning the output even if I am not returning the output of variable a to the previous function.
int fact(int n)
{
    int a;
    if (n <= 1)
        return 1;
    else
        a = n*fact(n-1);
}
int main()
{
    int c=fact(5);
    printf("%d",c);
}

A: Quoting C11, chapter §6.9.1

If the } that terminates a function is reached, and the value of the function call is used by
  the caller, the behavior is undefined.

So, your program exhibits undefined behavior.


text:
Q: CPU and HDDs temperature in Ubuntu 22.04 I have a conky config using hhdtemp and hwmon to retrieve CPU and HDDs temperature.
Now in Ubuntu 22.04 those packages are not available anymore, what alternative do I have?
I need something from CLI, to use it in my conky config, that just prints the CPU and HDDs temperature in celsius.
Thanks

A: To read CPU and HDD temperatures in Ubuntu 22.04 you need to use hwmon, which can be accessed using sensors. HDD temperatures are included in the output when the drivetemp module is loaded.
sudo apt install lm-sensors
sudo modprobe drivetemp
sensors

To make drivetemp load automatically every boot, add it to /etc/modules as follows:
echo drivetemp | sudo tee -a /etc/modules

A: I'm using everyday the application that display the temperature of CPU, HDD and also Graphic card in the top bar of the screen.
It's called Psensor. It's available in Ubuntu Software.


text:
Q: Error: Gradle DSL method not found: 'google()' I'm trying to add an external library to my existing project. I created a libs folder and added my MaterialDrawer library in the root directory. Here is my settings.gradle file:
include ':app'
include 'libs:MaterialDrawer'

But gradle sync is failed and getting following error:

Error:Gradle DSL method not found: 'google()'

I couldn't find any solution in SO regarding my problem. Anyone would be kind enough to help?
Here is the build.gradle (Project):
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.1'
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://maven.google.com" }
    }
}

Here is the build.gradle (app):
android {
    compileSdkVersion 25
    buildToolsVersion '25.0.0'
defaultConfig {
    applicationId "com.myapp"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 38
    versionName "2.1.8"

    generatedDensities = []

}

dexOptions {
    javaMaxHeapSize "4g"
}

aaptOptions {
    additionalParameters "--no-version-vectors"
}

    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

tasks.whenTaskAdded { task ->
    if (task.name.equals("lint")) {
        task.enabled = false
    }
}

repositories {
    mavenCentral()
    maven { url "https://jitpack.io"}
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(":libs:MaterialDrawer")
}

apply plugin: 'com.google.gms.google-services'

A: Method google() was added in Gradle 4.0
You should use maven { url 'https://maven.google.com' } on old versions
Also remove repositories section from your app build.gradle (you may merge it with root build.gradle)
Read how to add library to build.gradle here
compile('com.mikepenz:materialdrawer:5.9.5@aar') {
    transitive = true
}


text:
Q: How do I extract a partial string based on another column of strings? I am transforming output from a scheduling system.  I want to create 2 new columns from one initial column. The first desired column has the first six characters from the initial column. The desired second column should have a combination of blank rows and partial string matches. I am a beginner. Resources welcome where I am making ignorant syntax mistakes.
Initial data file looks like:
# A tibble: 6 x 2
  `Schedule Title` `Staff or Resource Name`
  <chr>            <chr>
1 Consultation     BIO210 (Bio stat); Carl; LSP143 (computer lab)
2 Weekly           PHY111; (Physics I); Noah/Prof Stubbin
3 Weekly           CHM111 (Gen Chem); Ali/Prof Van Arman
4 Workshops        CHM111 Quant Skills Workshop, KAU104
5 Workshops        CPS111 Study Jam (Computer Science)
6 Workshops        CHM211 Organic Chem Study Tips from Q&SC Tutors, HARWOOD

Desired file:
# A tibble: 6 x 3
  `Schedule Title` `Course` `WorkshopName`
  <chr>            <chr>  <chr>
1 Consultation     BIO210
2 Weekly           PHY111
3 Weekly           CHM111
4 Workshops        CHM111 Quant Skills Workshop
5 Workshops        CPS111 Study Jam
6 Workshops        CHM211 Organic Chem Study Tips from Q&SC Tutors

I have no problem using str_sub to create 'Course'.
However, I have not been able to create 'WorkshopName' successfully.  I have tried a) filtering by 'Type' then extracting characters 8-end.  I have tried b) extracting characters 8-end and then replacing anything after , ; or \( with empty text.  Both approaches (even if they worked) are only a partial solution.
#1. This works and creates the Course column
QSC$Course <- str_sub(QSC$Staff.or.Resource.Name, start = 1, end = 6)

#2. This does not work.  I was trying to filter by 'Type', then create WorkshopName for only those of Type: Workshop. I would still need to clean up the WorkshopNames to eliminate everything after a , ; or (.
QSC %>%
filter(str_detect(Type, 'Workshops') ) %>%
WorkshopName = str_sub('Staff or Resource Name', start = 8, end = -1)

#3. This also does not work.  I tried to extract characters 8-end, then replace anything after , ; or (.
#I have not been able to successfully escape the character (.
#I haven't even gotten to the part where I intended to filter and replace the strings with blanks for all but Type:Workshop.
QSC$WorkshopName <- str_sub(QSC$`Staff or Resource Name`, start = 8, end = -1)
QSC$WorkshopName <- str_split(QSC$WorkshopName,",", 1)
QSC$WorkshopName <- str_split(QSC$WorkshopName,";", 1)
QSC$WorkshopName <- str_split(QSC$WorkshopName,"\(", 1)

*

*Creates the 'Course' column I desire.

*results in
Error in QSC %>% WorkshopName = str_sub("Staff or Resource Name", start = 8,  : could not find function "%>%<-"

*results in
Error: '\(' is an unrecognized escape in character string starting ""\("

A: QSC %>%
filter(str_detect(Type, 'Workshops') ) %>%
WorkshopName = str_sub('Staff or Resource Name', start = 8, end = -1)

This fails because you need to use mutate in order to create a new variable with dyplr :
QSC %>%
filter(str_detect(Type, 'Workshops') ) %>%
mutate(WorkshopName = str_sub('Staff or Resource Name', start = 8, end = -1))

Moreover, to achieve what do you want in your comment, you can use ifelse
QSC %>%
mutate(WorkshopName = if_else(str_detect(Type, 'Workshops'), str_sub('Staff or Resource Name', start = 8, end = -1), NA))

Now:
QSC$WorkshopName <- str_split(QSC$WorkshopName,"\(", 1)

Fails becuuse you need an extra \ to make R interpret ( correctly:
QSC$WorkshopName <- str_split(QSC$WorkshopName,"\\(", 1)

Finally, the last argument in all three str_split being 1... I think it makes no sense.
If you read ?str_split

n: number of pieces to return. Default (Inf) uses all possible split
  positions

So if you put 1, it will return the whole string, you need 2 or more. If what you want is to get the first piece after the split, you need this so you retain the piece before the (first) split and drop what comes after
str_split(QSC$WorkshopName, "\\(")[[1]][1]

Best


text:
Q: XEmacs menubar is not enabled Using Windows 10 I installed Cygwin32 and all available emacs/xemacs packages.
When I start emacs now it works fine but for some reason the 'menu bar' with all items like 'File', 'Edit', 'Options' are not enabled.
Hence I can't use it. E.g. I want to enable the option copy/paste as C-c - C-v but since it's disabled I can't do it.
This is my version:
$ ./emacs-X11.exe --version
GNU Emacs 26.1
Copyright (C) 2018 Free Software Foundation, Inc.
GNU Emacs comes with ABSOLUTELY NO WARRANTY.
You may redistribute copies of GNU Emacs
under the terms of the GNU General Public License.
For more information about these matters, see the file named COPYING.

My question: how could I enable this menu? Should I add some other Cygwin packages or etc?
Thanks

A: Please ignore my question.
I found that in my case I simply forgot to install XServer.
After installing it the issue disappeared


text:
Q: Alembic try to drop table after create table instead of before I'm trying to migrate with Alembic.
Env.py :

from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context

import sys
import os

sys.path.insert(0, os.getcwd())
print(sys.path)
from appli.Base import Base

print(Base.metadata.sorted_tables)

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.

def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )

    with context.begin_transaction():
        context.run_migrations()

def run_migrations_online():
    """Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """
    connectable = engine_from_config(
        config.get_section(config.config_ini_section),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )

    with connectable.connect() as connection:
        context.configure(
            connection=connection, target_metadata=target_metadata
        )

        with context.begin_transaction():
            context.run_migrations()

if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()

alembic.ini :

# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = alembic

# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# timezone to use when rendering the date
# within the migration file as well as the filename.
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =

# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; this defaults
# to alembic/versions.  When using multiple version
# directories, initial revisions must be specified with --version-path
# version_locations = %(here)s/bar %(here)s/bat alembic/versions

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url = mysql+pymysql://root@localhost/test_migration

[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts.  See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks=black
# black.type=console_scripts
# black.entrypoint=black
# black.options=-l 79

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

I initialize the database with that in first :

from sqlalchemy import create_engine
import pymysql
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint

Base = declarative_base()
engine = create_engine('mysql+pymysql://root@localhost/test_migration')

#The axis on which the tests are executed
class AXIS(Base):
    __tablename__ = 'Axis'
    id_axis        = Column(Integer, primary_key = True)
    name_axis      = Column(String(10), nullable=False)

And I get that in the version upgrade. Everything is right.

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('Axis',
    sa.Column('id_axis', sa.Integer(), nullable=False),
    sa.Column('name_axis', sa.String(length=10), nullable=False),
    sa.PrimaryKeyConstraint('id_axis')
    )
    # ### end Alembic commands ###

Next i add a column named test to my table named axis to test the migration :

#The axis on which the tests are executed
class AXIS(Base):
    __tablename__ = 'Axis'
    id_axis        = Column(Integer, primary_key = True)
    name_axis      = Column(String(10), nullable=False)
    test           = Column(String(10), nullable=False)

Then we get a new version file:

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('Axis',
    sa.Column('id_axis', sa.Integer(), nullable=False),
    sa.Column('name_axis', sa.String(length=10), nullable=False),
    sa.Column('test', sa.String(length=10), nullable=False),
    sa.PrimaryKeyConstraint('id_axis')
    )
    op.drop_table('axis')
    # ### end Alembic commands ###

But I noticed that alembic first tried to create the tables (already existing) and then tried to delete them. For the upgrade to work, you must move the drop before the create.
Why is the drop after the create? If it's normal, please explain it to me. If it's not normal, what could be the source of my error?
Thank you for your help !

A: I met the same problem, you can change the __tablename__ = 'Axis' to __tablename__ = 'axis'. It works at least, but I don't know how to work with the Upper table name


text:
Q: How to I generate a CSV file from a python list with each list item in a seperate row I've tried some code I got from another question (list_of_paths is a list I generated earlier in the code)
myfile = open('/home/graham/Desktop/Experiment/listcsv.csv', 'wb')
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(list_of_paths)

But it put the entire list in one cell. I want each item in a different row. The program I use for CSV files is LibreOffice Calc if that makes a difference.

A: Use writerows as follow:
myfile = open('/home/graham/Desktop/Experiment/listcsv.csv', 'wb')
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerows([path] for path in list_of_paths)

A: I would use standard Input/Output to implement this.
$ cat getCSV.py
input_list = range(10)   # replace range(10) with your list
for elem in input_list:
    print '"' + str(elem) + '"'

$ python getCSV.py > output.csv
$ cat output.csv
"0"
"1"
"2"
"3"
"4"
"5"
"6"
"7"
"8"
"9"

And if each elem in your list is again, a list or tuple.. you could use join command to separate them into columns.
>>> row = [str(i) for i in range(10)]
>>> row
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> ','.join(row)
'0,1,2,3,4,5,6,7,8,9'
>>> ','.join(['"' + col + '"' for col in row])
'"0","1","2","3","4","5","6","7","8","9"'


text:
Q: Chartjs - custom y axis range I wanted to add custom y axis range to chartjs. Currently its picking automatically.My data range is too large so min and max doesn't work properly,most of the items are invisible in that case.
Sample Data
I wanted to add some custom y axis range some thing like this
Range Required
Please give me some suggestions.

A: I am able to fix this issue by following configurations.
yAxes: [{
        scaleLabel: {
            display: true,
            labelString: 'LABEL',
        },
        type: 'logarithmic',
        position: 'left',
        ticks: {
             min: 0, //minimum tick
             max: 10000000, //maximum tick
             callback: function (value, index, values) {
                 return Number(value.toString());//pass tick values as a string into Number function
             }
        },
        afterBuildTicks: function (chartObj) { //Build ticks labelling as per your need
            chartObj.ticks = [0,10,100,1000,10000,100000,1000000,10000000];
        }
    }]


text:
Q: How can I read Variables from data pool with Selenium IDE? I am using Selenium IDE to test a web based HR/SW system.
There is a screen that used to enter vacation for employees.
I am having nearly 3000 employee.
I built a test case that enter vacations for one employee using variables.
How can I repeat the test case for all 3000 employees without creating the test case 3000 times. It will take an impossible effort to do that. Note: Each employee is having different vacation data (Type, start date, End date)
Is there any way that I can use a file (Excel,....) that variable can use to read its data from?
Is there any solution for my case???
I will be very very grateful I any one could help me.
Thank you.

A: You could use an XML file as an input.
1) At first you have to add following user extensions:
sideflow.js - (http://51elliot.blogspot.com/2008/02/selenium-ide-goto.html - additionally this article explains how to add user extension files)
datadriven.js
include.js
At the moment I can't find links where I took the last two, therefore I will give their code in the end of my post. Code is taken from my working directory. You just put the code to correspondent files, then add files to SelemiunIDE user extension and use them.
2) Create an XML file test_data.xml:
<testdata>
    <test employee="1" type="1" startDate="01.01.2013" endDate="01.02.2013" />
    <test employee="2" type="1" startDate="01.02.2013" endDate="01.03.2013" />
    <test employee="3" type="1" startDate="01.03.2013" endDate="01.04.2013" />
...
</testdata>

3) In your test case use code like this:
${DataPath} - full path to a directory with XML-files

    loadTestData
    file://${DataDir}/test_data.xml

    while
    !testdata.EOF()

    nextTestData

    echo
    employee=${employee} type=${type} ...

...

    endWhile

Used user extensions:
include.js
/**
 * Original Developer: Jerry Qian(qqqiansjtucs@hotmail.com)
 * Modified By: John Witchel (jwitchel@colevalleygroup.com)
 * include extension for Selenium-IDE edition
 * refer to includeCommand_2.1.3 for Selenium-Core edition
 * @version 1.3
 *
 */
function IDEIncludeCommand() {}

IDEIncludeCommand.LOG_PREFIX = "IDEIncludeCommand: ";
IDEIncludeCommand.BEGIN_TEMPLATE = "begin$Template$";
IDEIncludeCommand.END_TEMPLATE = "end$Template$";
IDEIncludeCommand.VERSION = "1.1";

IDEIncludeCommand.prototype.prepareTestCaseAsText = function(responseAsText, paramsArray) {
    /**
     * Prepare the HTML to be included in as text into the current testcase-HTML
     * Strip all but the testrows (tr)
     * Stripped will be:
     *  - whitespace (also new lines and tabs, so be careful wirt parameters relying on this),
     *  - comments (xml comments)
     * Replace variable according to include-parameters
     * note: the include-variables are replaced literally. selenium does it at execution time
     * also note: all selenium-variables are available to the included commands, so mostly no include-parameters are necessary
     *
     * @param responseAsText table to be included as text (string)
     * @return testRows array of tr elements (as string!) containing the commands to be included
     *
     * TODO:
     *  - selenium already can handle testcase-html. use selenium methods or functions instead
     *  - find better name for requester
     */
    // removing new lines, carret return and tabs from response in order to work with regexp
    var pageText = responseAsText.replace(/\r|\n|\t/g,"");
    // remove comments
    // begin comment, not a dash or if it's a dash it may not be followed by -> repeated, end comment
    pageText = pageText.replace(//g,"");
    // find the content of the test table = <[spaces]table[char but not >]>....< /[spaces]table[chars but not >]>
    var testText = pageText.match(/<\s*table[^>]*>(.*)<\/\s*table[^>]*>/i)[1];

    // Replace 	 with  	 for iE - credits Chris Astall
    // rz: somehow in my IE 7 this is not needed but is not bad as well
    testText = testText.replace(/<\s*td[^>]*>\s*<\s*\/td[^>]*>/ig,"	");// jq: no space

    // replace vars with their values in testText
    for ( var k = 0 ; k < paramsArray.length ; k++ ) {
        var pair = paramsArray[k];
        testText = testText.replace(pair[0],pair[1]);
    }

    // removes all

    // in order to split on

    testText = testText.replace(/<\/\s*tr[^>]*>/ig,"");
    // split on

    var testRows = testText.split(/<\s*tr[^>]*>/i);
    return testRows;
};

IDEIncludeCommand.prototype.getIncludeDocumentBySynchronRequest = function(includeUrl) {
    /**
     * Prepare and do the XMLHttp Request synchronous as selenium should not continue execution meanwhile
     *
     * note: the XMLHttp requester is returned (instead of e.g. its text) to let the caller decide to use xml or text
     *
     * selenium-dependency: uses extended String from htmlutils
     *
     *  TODO use Ajax from prototype like this:
     *   var sjaxRequest = new Ajax.Request(url, {asynchronous:false});
     *   there is discussion about getting rid of prototype.js in developer forum.
     *   the ajax impl in xmlutils.js is not active by default in 0.8.2
     *
     * @param includeUrl URI to the include-document (document has to be from the same domain)
     * @return XMLHttp requester after receiving the response
     */
    var url = this.prepareUrl(includeUrl);
    // the xml http requester to fetch the page to include
    var requester = this.newXMLHttpRequest();
    if (!requester) {
        throw new Error("XMLHttp requester object not initialized");
    }
    requester.open("GET", url, false); // synchron mode ! (we don't want selenium to go ahead)
    try {
        requester.send(null);
    } catch(e) {
      throw new Error("Error while fetching url '" + url + "' details: " + e);
    }
    if ( requester.status != 200 && requester.status !== 0 ) {
        throw new Error("Error while fetching " + url + " server response has status = " + requester.status + ", " + requester.statusText );
    }
    return requester;
};

IDEIncludeCommand.prototype.prepareUrl = function(includeUrl) {
    /** Construct absolute URL to get include document
     * using selenium-core handling of urls (see absolutify in htmlutils.js)
     */
    var prepareUrl;
    // htmlSuite mode of SRC? TODO is there a better way to decide whether in SRC mode?
    if (window.location.href.indexOf("selenium-server") >= 0) {
        LOG.debug(IDEIncludeCommand.LOG_PREFIX + "we seem to run in SRC, do we?");
        preparedUrl = absolutify(includeUrl, htmlTestRunner.controlPanel.getTestSuiteName());
    } else {
        preparedUrl = absolutify(includeUrl, selenium.browserbot.baseUrl);
    }
    LOG.debug(IDEIncludeCommand.LOG_PREFIX + "using url to get include '" + preparedUrl + "'");
    return preparedUrl;
};

IDEIncludeCommand.prototype.newXMLHttpRequest = function() {
    // TODO should be replaced by impl. in prototype.js or xmlextras.js
    //     but: there is discussion of getting rid of prototype.js
    //     and: currently xmlextras.js is not activated in testrunner of 0.8.2 release
    var requester = 0;
    var exception = '';
    // see http://developer.apple.com/internet/webcontent/xmlhttpreq.html
    // changed order of native and activeX to get it working with native
    //  xmlhttp in IE 7. credits dhwang
    try {
        // for IE/ActiveX
        if(window.ActiveXObject) {
            try {
                requester = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e) {
                requester = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        // Native XMLHttp
        else if(window.XMLHttpRequest) {
            requester = new XMLHttpRequest();
        }
    }
    catch(e) {
        throw new Error("Your browser has to support XMLHttpRequest in order to use include \n" + e);
    }
    return requester;
};

IDEIncludeCommand.prototype.splitParamStrIntoVariables = function(paramString) {
    /**
     * Split include Parameters-String into an 2-dim array containing Variable-Name and -Value
     *
     * selenium-dependency: uses extended String from htmlutils
     *
     * TODO: write jsunit tests - this could be easy (if there were not the new RegExp)
     *
     * @param includeParameters string the parameters from include call
     * @return new 2-dim Array containing regExpName (to find a matching variablename) and value to be substituted for
     */
    var newParamsArray = new Array();
    // paramString shall contains a list of var_name=value
    var paramListPattern = /([^=,]+=[^=,]*,)*([^=,]+=[^=,]*)/;
    if (! paramString || paramString === "") {
        return newParamsArray;
    } else if (paramString.match( paramListPattern )) {
        // parse parameters to fill newParamsArray
        var pairs = paramString.split(",");
        for ( var i = 0 ; i < pairs.length ; i++ ) {
            var pair = pairs[i];
            var nameValue = pair.split("=");
            //rz: use String.trim from htmlutils.js of selenium to get rid of whitespace in variable-name(s)
            var trimmedNameValue = new String(nameValue[0]).trim();
            // the pattern to substitute is ${var_name}
            var regExpName = new RegExp("\\$\\{" + trimmedNameValue + "\\}", "g");

            if (nameValue.length < 3) {
               newParamsArray.push(new Array(regExpName,nameValue[1]));
            } else {
                var varValue = new String(nameValue[1]);
                for (var j = 2; j < nameValue.length; j++) {
                    varValue=varValue.concat("="+nameValue[j]);
                }
                newParamsArray.push(new Array(regExpName,varValue));
            }
        }
    } else {
        throw new Error("Bad format for parameters list : '" + paramString + "'");
    }
    return newParamsArray;
};

IDEIncludeCommand.prototype.doInclude = function(locator, paramString) {
    // Rewrite logic for Selenium IDE by Jerry Qian
    var currentSelHtmlTestcase = testCase;

    var includeCmdRow = testCase.debugContext.currentCommand();

    if (!includeCmdRow) {
        throw new Error("IDEIncludeCommand: failed to find include-row in source testtable");
    }

    var paramsArray = this.splitParamStrIntoVariables(paramString);

    var inclDoc = this.getIncludeDocumentBySynchronRequest(locator);

    // Get an array of commands from the include text with all whitespace stripped
    var includedTestCaseHtml = this.prepareTestCaseAsText(inclDoc.responseText, paramsArray);

    this.injectIncludeTestCommands(locator,includeCmdRow,includedTestCaseHtml);
};

IDEIncludeCommand.prototype.injectIncludeTestCommands = function(locator,includeCmdRow,  testRows) {
    // Rewrite logic for Selenium IDE by Jerry Qian
    var newCommands = new Array();
    // skip first element as it is empty or

    for (var i = 1 ; i < testRows.length; i++) {
          if(i == 1){// add BEGIN-END block
            var beginCommand = new Command(IDEIncludeCommand.BEGIN_TEMPLATE,locator,"");
            newCommands.push(beginCommand);
          }

          var newText = testRows[i];
          if(newText.match(/<\s*td.*colspan=.*>(.*)<\/\s*td[^>]*>/i)){//delete comment step
             continue;
          }

          // removes all
          // in order to split on
          newText = newText.replace(/<\/\s*td[^>]*>\s*<\/\s*tbody[^>]*>/ig,""); //remove
first
          newText = newText.replace(/<\/\s*td[^>]*>/ig,"");
          var newCols = newText.split(/<\s*td[^>]*>/i);
          var new_cmd,new_target,new_value;

          for (var j = 1 ; j < newCols.length; j++) {//skip 0
            if(j == 1) {
                new_cmd = newCols[j].replace(/\s/g,"");//trim \s
            }else if(j == 2) {
              new_target = newCols[j].replace(/\s+$/g,"");//trim end \s
            }else if(j == 3) {
              new_value = newCols[j].replace(/\s+$/g,"");//trim end \s
            }
          }

          var newCommand =  new Command(new_cmd,new_target,new_value);
          newCommands.push(newCommand); //correct all steps
    }
    var endCommand = new Command(IDEIncludeCommand.END_TEMPLATE,locator,"");
    newCommands.push(endCommand);//add BEGIN-END block

    var cmsBefore = testCase.commands.slice(0,testCase.debugContext.debugIndex + 1);
    var cmdsBehind = testCase.commands.slice(testCase.debugContext.debugIndex + 1, testCase.commands.length);
    testCase.commands = cmsBefore.concat(newCommands).concat(cmdsBehind);//Injection

    // Don't inject if it appears the injection has already been done
    // (i.e., if the next command is the BEGIN).
    if (testCase.commands.length <= testCase.debugContext.debugIndex+1
        || beginCommand.toString() != testCase.commands[testCase.debugContext.debugIndex+1].toString())
    {
        // The include command cannot be the last command in the TestCase, or else
        // the de-injection code in doEnd$Template$ will cause an error. So we'll
        // add a simple echo if it is the last.
        if (testCase.commands.length == testCase.debugContext.debugIndex+1)
        {
            // Using concat instead of push so that we don't trigger the TestCase's set-modified flag.
            testCase.commands = testCase.commands.concat(new Command("echo", "The include command cannot be the last line in a TestCase, so this command was added. It can be left in place or removed, as desired.", "The include command cannot be the last line in a TestCase, so this command was added. It can be left in place or removed, as desired."));
        }

        // This is original code.
        var cmsBefore = testCase.commands.slice(0,testCase.debugContext.debugIndex + 1);
        var cmdsBehind = testCase.commands.slice(testCase.debugContext.debugIndex + 1, testCase.commands.length);
        testCase.commands = cmsBefore.concat(newCommands).concat(cmdsBehind);//Injection
    }
};

Selenium.prototype.doInclude = function(locator, paramString) {
    LOG.debug(IDEIncludeCommand.LOG_PREFIX + "Version " + IDEIncludeCommand.VERSION);
    var ideIncludeCommand = new IDEIncludeCommand();
    ideIncludeCommand.doInclude(locator, paramString);

    // If goto scripts exist then reindex the labels.  goto_sel_ide.js creates an array of labels when the
    // script is initialized but an included file's labels are not part of that initial read, so this function
    // re-initializes that array with the included files labels (if any).  If goto_sel.ide.js is not included
    // it's ignored.
    try {
        this.initialiseLabels();
    }
    catch (e) {
        LOG.debug("Goto Script not used.");
    }

};

// Array to hold the starting position of the Begin$Template$ marker.  Pushing and popping the position onto an array
// allows us to correctly handle nested includes during clean up.
var beginTemplateIndex = new Array();

// Mark the beginning of the include
Selenium.prototype.doBegin$Template$ = function(locator){
    LOG.info("Begin Template " + locator + " at position " + testCase.debugContext.debugIndex);
    // Add the current position to the tail of the beginTemplateIndex
    beginTemplateIndex.push(testCase.debugContext.debugIndex);
};

// Clean up everything between the closest Begin$Template$ and this $End$Template$, and pop the position off the array.
Selenium.prototype.doEnd$Template$ = function(locator){

    // Remove the last Begin$Template$ from the tail of the beginTemplateIndex
    var currentBeginTemplateIndex = beginTemplateIndex.pop();
    LOG.info("End Template " + locator + " at position " + currentBeginTemplateIndex);

    // Delete the commands that we injected in injectIncludeTestCommands.
    testCase.commands =
        testCase.commands.slice(0,currentBeginTemplateIndex).concat(
            testCase.commands.slice(testCase.debugContext.debugIndex+1, testCase.commands.length));

    // Set the current command to the next one after the injected block.
    testCase.debugContext.debugIndex = currentBeginTemplateIndex-1;

    //Must refresh to syncup UI
    editor.view.refresh();
};

datadriven.js
/************************************ DATADRIVEN EXTENSION START ********************************************/
/*
NAME:
    datadriven

    Licensed under Apache License v2
    http://www.apache.org/licenses/LICENSE-2.0

PURPOSE:
    Basic data driven testing.

    Full documentation at http://wiki.openqa.org/display/SEL/datadriven

EXAMPLE USE:
    The structure of your data driven test case will be;
    -------------------------------------------
    COMMAND       |TARGET          |VALUE
    -------------------------------------------
    loadTestData  |<file path>     |
    while         |!testdata.EOF() |
    testcommand1  |                |
    testcommand...|                |
    testcommandn  |                |
    endWhile      |                |
    -------------------------------------------

AUTHOR:
    Jonathan McBrien
    jonathan@mcbrien.org
    2008-10-22: v0.1:   Initial version.
    2009-01-16: v0.2:   Updated for Firefox 3.
                xmlTestData.prototype.load now uses the include extension's getIncludeDocumentBySynchronRequest method for better portability.
                (Why reinvent the wheel? :) - with appreciation to the include extension's authors.)
*/

XML.serialize = function(node) {
    if (typeof XMLSerializer != "undefined")
        return (new XMLSerializer()).serializeToString(node) ;
    else if (node.xml) return node.xml;
    else throw "XML.serialize is not supported or can't serialize " + node;
}

function xmlTestData() {
    this.xmlDoc = null;
    this.testdata = null;
    this.index = null;
}

xmlTestData.prototype.load = function(xmlloc) {
    loader = new IDEIncludeCommand();
    var xmlHttpReq = loader.getIncludeDocumentBySynchronRequest(xmlloc);
    this.xmlDoc = xmlHttpReq.responseXML;

    this.index = 0;
    this.testdata = this.xmlDoc.getElementsByTagName("test");

    if (this.testdata == null || this.testdata.length == 0) {
        throw new Error("Test data couldn't be loaded or test data was empty.");
    }
}

xmlTestData.prototype.EOF = function() {
    if (this.index != null && this.index < this.testdata.length) return false;
    return true;
}

xmlTestData.prototype.more = function() {
    return !this.EOF();
}

xmlTestData.prototype.next = function() {
    if (this.EOF()) {
        LOG.error("No test data.");
        return;
    }

    LOG.info(XML.serialize(this.testdata[this.index])); // Log should anything go wrong while testing with this data.

    if (this.testdata[this.index].attributes.length != this.testdata[0].attributes.length) {
        LOG.error("Inconsistent attribute length in test data.");
        return;
    }

    for (i=0; i<this.testdata[this.index].attributes.length; i++){
        if (null == this.testdata[0].getAttribute(this.testdata[this.index].attributes[i].nodeName)) {
            LOG.error("Inconsistent attribute names in test data.");
            return;
        }

        selenium.doStore(this.testdata[this.index].attributes[i].nodeValue, this.testdata[this.index].attributes[i].nodeName);
    }

    this.index++;
}

Selenium.prototype.testdata = null;

Selenium.prototype.doLoadTestData = function(xmlloc) {
    testdata = new xmlTestData();
    testdata.load(xmlloc);
};

Selenium.prototype.doNextTestData = function() {
    testdata.next();
};

/************************************ DATADRIVEN EXTENSION END **********************************************/

A: Current solution is a SelBlocks component which allows you to do cycles according to the dataset in XML
ForXML | XMLFileName.XML
... test case steps
EndForXML

The XML should have specific structure
<testdata>
   <vars storedVariable1="xxxxx" storedVariable2="yyyyy" .. storedVariableN="zzzzz" />
   .. other record(s)
</testdata>

Each stored variable vill be available in test case as ${storedVariableN}.
You can produce XML by MS Excel or LibreOffice using Formulas like this one and copy it to whole table:
 ="<vars "&
 " "&$A$1&"="""&A2&""" "&
 " "&$B$1&"="""&B2&""" "&
 ..
 " "&$X$1&"="""&X2&""" "&
 "/>")

XML can be easily copypasted after each change of the dataset.
Selblocks contains the while, datadriven, goto, loop and other extensions mentioned in previous answers.  You can use other functionalities of the Selblocks as conditional jumps, conditions, catch-try blocks, functions, etc. See full reference here: http://refactoror.wikia.com/wiki/Selblocks_Reference
Beware with new Selenium 3 release and Sel Core absence it is not guaranteed, that tests with Selblock addon will work in the future versions of the firefox.

A: You can also check this very nice blog article:
http://seleniumworks.blogspot.com/2014/01/selenium-ide-data-driven.html
This gives an explanation on how to use the needed plugins and where to download them from. It worked perfectly for me.
This answer pretty much has the same approach as the one provided by @Yevgen Ulyanenkov as I used his answer in order to find the above article. But has some more googling to it that hopefully will be helpful to someone.

A: I think you need to use loop I don't see your code so just check this one for selenium-ide loop If you have any more problem if so comment my answer. I can't comment into your question because reputation is not enough so. If possible please add your code into your question.


text:
Q: how to group route by name in laravel
Route::prefix('/admin/post')->middleware('admin')->name('admin.')->group(function(){
    Route::get('/all', [AdminPostController::class, 'index'])->name('post');
    Route::name('post.')->group(function(){
        Route::get('/create', [AdminPostController::class, 'create'])->name('create');
        Route::post('/store', [AdminPostController::class, 'store'])->name('store');
        Route::get('/{post:slug}/edit', [AdminPostController::class, 'edit'])->name('edit');
        Route::patch('/{post:slug}/update', [AdminPostController::class, 'update'])->name('update');
        Route::delete('/{post:slug}', [AdminPostController::class, 'destroy'])->name('delete');
    });
});

I am trying to group route by name but I don't know how can  I group
  Route::get('/all', [AdminPostController::class, 'index'])->name('post');

this route in this group
Route::prefix('/admin/post')->middleware('admin')->name('admin.')->group(function(){});

this group
I am trying to group route by name but I don't know how can  I group them


text:
Q: supportsAllDrives is appearing as deprecated what was is the alternative to this parameter? supportsAllDrives   boolean
Warning: This item is deprecated.
Deprecated - Whether the requesting application supports both My Drives and shared drives. This parameter will only be effective until June 1, 2020. Afterwards all applications are assumed to support shared drives. (Default: false)
supportsTeamDrives  boolean
Warning: This item is deprecated.
Deprecated use supportsAllDrives instead. (Default: false)
both got deprecated but what is the alternative to both parameters ?

A:
in 2020 GDrive will start ignoring those parameters and will always
  list contents from Team drives, too, so effectively setting them to
  false in KGAPI would look like a bug.

From https://phabricator.kde.org/D20789
Not really clear from the documentation if we need to update anything.
Looks like setting the parameter supportsAllDrives to true resolve the issue and will be ignored in the future because it will list the shared drives by default.


text:
Q: Two handles to same variable in C Is there any way I can create two variables that point to the same memory location, so that I can read same memory as int, float, char, any way I like?
I want something like this, only without pointer to f, so that I do not have to dereference every time I read/write to f.
char myArray[100];
float* f = (float *)&myArray[10];

I want to closest thing to C++'s reference in C.
I hope the question makes sense.
Edit: I read stream (4 Kb worth) of bytes from flash memory. This stream contains shorts, ints and floats. I know the locations of these ints and floats in the array. And I want to read/write the aforementioned ints and floats like they are ordinary variables.

A: This example reads the data into a predefined struct, packed (if necessary). Beware of endian-ness! And of data types: an int on your target might be short on you PC.
#include<stdio.h>

#pragma pack(push, 1)
struct mydata {
    int version;
    char title[16];
    float reading[8];
} mydata;

#pragma pack(pop)

int main(void)
{
    FILE *fp;
    struct mydata data = {0};
    fp = fopen("mydata.bin", "rb");

    if (1 != fread(&data, sizeof(data), 1, fp))
        { // error
        }

    printf("Version = %d\n", data.version);

    fclose(fp);
    return 0;
}

A: This is why unions exist.
union u {
  char c[4];
  float f;
  int i; // assuming sizeof(int) = 4 for this example
};

union u cf;
cf.f = 1.;
int i = cf.i;

Beware that the last line is actually incorrect per the C standard, because of strict aliasing. See for example What is the strict aliasing rule? You should always access the binary representation through a char l-value.


text:
Q: Regular expression related to credit card I would like to validate master card for New series The BIN range (222100-272099). currently I have Regular expression for existing mastercard series...5[1-5][0-9]{14}

A: Edit : based on the comment of Kul-Tigin
When working with numbers this may be easier :
Title = "Valid card number or not"
Do
    CardNumber = InputBox("Please type your card number ",Title,"222100")
    If IsValidcard(CardNumber) = True Then
        MsgBox CardNumber & " The Card number is valid !",64,Title
    Else
        MsgBox CardNumber & " The Card number is not valid !",16,Title
    End if
Loop Until CardNumber = ""
'**********************************************************************
Function IsValidCard(Num)
    IsValidCard = False
    Set regEx = New RegExp
    regEx.Pattern = "^\d{6}$"
    If regEx.Test(Num) then
        x = CDbl(num)
        if x >= 222100 AND x <= 272099 Then
            IsValidCard = True
        Else
            'not in range
        End If
    Else
        'not 6 digits
    end if
End Function
'**********************************************************************


text:
Q: How to put data from the database to the template I want to put data from my database into my template file. This data will be selected based on user id.
I have the template file set up and I have the code to select a user based on their id, what I don't know and have been unable to work out is where the code that selects the data needs to be placed i.e. block, helper etc...
I assume its needs to go in a block, from there I don't know how I would get the data to the template and place each piece of data into their respective input fields?
my questions are:

*

*where would the code go

*how do I call that code from the template

===EDIT===
Namespace/Module/Block/Blockname.php
class Namespace_Module_Block_Blockname.php
extends Mage_Core_Block_Template
{
public function postsGetByIdAction($id)
{
    $params = $this->getRequest()->getParams();
    $prefs = Mage::getModel('module/model');
    $prefs->load($params['id']);
    $data = $prefs->getData();
    return$data;
}
}

template/namespace/module/templatefile.phtml
<?php echo $this->postsGetById(); ?>//returns invalid method Mage_Core_Block_Template::postsGetById(Array())

I have tried var_dump as the error message said 'array' at the end but I still get the same message

A: Magento works in this way, in MVC design pattern, is different to the usual MVC.
In Magento we have:
- Model
- View :
   - Blocks
   - Layouts
   - Templates
     The blocks grabs the data from the model, and pass this data to the template, all through   the layout system.
- Controllers
So, the answer to your question is that your need a method in one model, and invoke it through the block, and then, pass the data in this way:
block:
class Mynamespace_Mymodule_Block_Myblock extends Mage_Core_Block_Template
{
    public function getMyProductData()
    {
        $product = Mage::getModel('catalog/product')->load($id);
        return $product;
    }
}

And then you can retrieve it in your phtml like this:
$_product = $this->getMyProductData();
echo $_product->getName();

Greetings from México :D


text:
Q: Cassandra copy table into doesn't produce output I want to copy the data of my table into a csv file. But it never writes a single row. It just creates a 0B file and the process looks to be simply hung in the CQLSH terminal.
If I end this through ^c, it just prints
copy emp(empid,empname) to 'emp1.csv';
Using 1 child processes

Starting copy of ea_sc_ww_elf.emp with columns [empid, empname].
IOError:
IOError:
IOError:
IOError:
IOError:
IOError:
IOError:
IOError:
IOError:

Any configuration causing this ???
Please note: for testing, I created a simple employee table with 2 rows of data and only 2 columns empid, empname.

A: I Re-installed Cassandra in a different server and tried to export the data into csv, It worked fine.
All I can guess is this Might be related to some setting in cassandra.yaml with any of the below properties:

*

*rpc_address

*broadcast_rpc_address

I haven't got free time to experiment on this. I will leave a confirmation when I do.

A: Try to run cqlsh with "–debug" flag. You will have more detailed information, thath helps in troubleshooting.


text:
Q: Interactive World Map, highlight countries on mouseover I need to create an interactive world map on the front page of a site, the view portal will be about 650x200 pixels. The interactivity would include the following, mouse-over a country would highlight (the countries are will literally be filled with "red" for example) that country  and display the countries' name (preferably text in a div), I will also be linking the highlighting event with a  that will highlight a country when selected.
I am having a difficult time finding a suitable solution, I refuse to use  or learn a proprietry technology such as flash so it is not an option. I created a simple mockup using openlayers and a custom map image but the countries' markers load too slowly in IE6.
Also svg seems too large, as I tried to use RaphaelJS, but abondoned it when I realised the world map data is 1.2mb which is totally un acceptable for the front page of a site..
I am really at a loss on how I am going to do this, my last resort is to manually create 250+ (however many countries there are) pngs and apply mouseover events to hotspots in the image... but this is probably going to be a dead end too.. desperately seeking a solution, any helpful comments will be appreciated!

A: Why reinvent the wheel. Google Charts already does this.

A: I finaly settled with RaphaelJS, importing all the paths from an svg in inkscape, works amazingly well!

A: I developed jVectorMap for that purpose.

A: We've developed Highmaps, related to Highcharts, to easily solve data visualization problems like this. We also supply a map collection of over 350 maps, optimized for size to keep things lightweight.
For a drilldown example (loading more detailed map on mouse click) see this demo.
Highmaps is free for non-commercial use.

A: Do you have country coordinate data stored somewhere?
If so setting up functions to parse through the passed in data and create 250+ paths should not be that large.


text:
Q: XCODE 8.0 quits unexpectedly Everytime I open my project in xcode 8.0 it quits unexpectedly as soon as I press any key for coding in view controller swift file and when i again open xcode my project is started automatically and again the problem persists. Please help me in solving this issue.
when i open viewconroller.swift file or any other swift file in any project it simply exits xcode and the error message "xcode quits Unexpectedly" arrives. attached image of error. my project type is ios application, working in os sierra version 10.12.2
 and in xcode 8.0

A: I occasionally get this problem -  if you clear out the DerivedData folders you should be sorted.
The DerivedData folders should be in your user
/CurrentUser/Library/Developer/Xcode/DerivedData

you can search for DerivedData if it's not there.
Delete those folders, and redstart your project.  It will take a little while, depending on the size of the project to reindex, but you should be able to continue development.

A: Facing same problem sometimes - there is two way to solve this issue.
1)
Follow the screen shot.
Follow 4 steps that highlighted in photo and remove derived data then restart your project.

2)
if first salutation is not worked then uninstall your Xcode and reinstall it will works.
Thanks, Good Luck.