text:
Q: listing file is specific order linux I would like to ask you for help with some script.
I have files in one directory with one extension:
1_of_meany_files.ext
2_of_meany_files.ext
3_of_meany_key1_files.ext
5_of_meany_files.ext
6_key2_of_meany_files.ext

Now i'm trying build file.txt with list of these files but in specific order:
3_of_meany_key1_files.ext
6_key2_of_meany_files.ext
1_of_meany_files.ext
2_of_meany_files.ext
5_of_meany_files.ext

I would be appreciate for help.
Thanks
Marcin
==EDIT==
Hi, Thanks for your help.
The scripts are working fine. However I have problem with one thing:
If the key word has a digit inside it works perfect.
But the key words can be without digits (S114 or S_114)
then these scripts aren't works. What can I do with this?
General I would like to sort files and put one on the top of the list with the key (S114 or S_114).
So the files after sorting can looks like this:
Option One
    one_file_S114_text.ext
    rest_of_files_1.ext
    rest_of_files_2.ext
    rest_of_files_3.ext

Option Two
    one_file_S_114_text.ext
    rest_of_files_1.ext
    rest_of_files_2.ext
    rest_of_files_3.ext

In directory can be only one file with the key, but the key can be S114 or S_114
Thanks for your time
regard Marcin

A: This is a bit tricky, because you want the files with no key in the end, so you can't just do print $2+0,$0 in the awk command. However, this awk-sort-cut pipeline should do what you want:
$ printf "%s\n" * | awk -F'_key' '{print $2+0==0?1000000:$2+0,$0}'| sort -n | cut -d' ' -f 2-
3_of_meany_key1_files.ext
6_key2_of_meany_files.ext
1_of_meany_files.ext
2_of_meany_files.ext
5_of_meany_files.ext

A: With perl:
perl -e 'print"$_\n"for sort{($a=~/key(\d+)/?$1:1e+9)-($b=~/key(\d+)/?$1:1e+9)}<*>'


text:
Q: Why doesn't Automator service appear in iTunes? I'm trying to write an Automator service for iTunes so that I can immediately open a file from iTunes in VLC, so I don't have to do (show in finder, launch with other application, vlc).
I go to Automator, create a Service, in the top right dropdowns, I choose: "Service receives selected audio files in any application", and the script itself is just "Open Finder Items" with VLC.
However, the service doesn't appear. Not in finder, not in iTunes.. I'm very confused. Any thoughts what's going on? I tried restarting computer, restarting iTunes, all to no avail.
Thanks!

A: To get it to work in iTunes, you can try setting it up like this:
Service receives selected: text in: iTunes
Actions:
"Get Selected iTunes Tracks" - Get selected: tracks
"Open Finder items" - Open with: VLC

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't get gcc version from to switch from 4.2.1 to 4.6 even after selecting it (MacPorts) I'm running Snow Leopard and need to compile something using a more recent version of GCC than 4.2.1. I've been using MacPorts but can't seem to get the command-line GCC to recognize the MacPorts version:
[15:01:47] ~/Downloads$
port select gcc
Available versions for gcc:
gcc40
gcc42
llvm-gcc42
mp-gcc44
mp-gcc45
mp-gcc46 (active)
none
[15:10:04] ~/Downloads$
sudo port select gcc mp-gcc46
Selecting 'mp-gcc46' for 'gcc' succeeded. 'mp-gcc46' is now active.
[15:10:24] ~/Downloads$
sudo port select --set gcc mp-gcc46
Selecting 'mp-gcc46' for 'gcc' succeeded. 'mp-gcc46' is now active.
[15:11:34] ~/Downloads$
gcc -version
i686-apple-darwin10-gcc-4.2.1: no input files
[15:11:40] ~/Downloads$

Even though I use MacPorts select to specify a newer version, that switch does not seem to do anything (even after rebooting, etc.). I feel like I'm missing something very simple but I have looked in multiple places for some help on remedying this without luck.
Thanks!

A: Never mind everybody. I changed my .bashrc file so that, in the PATH, the Mac ports directories come before /usr/bin instead of after.


text:
Q: How to prevent link formatting from changes when editing link using VBA? I'm currently using the following code to update all the links in my application:
Sub AddSources()
    Dim pubPage As Page
    Dim pubShape As Shape
    Dim hprlink As Hyperlink
    Dim origAddress() As String
    Dim exportFileName As String
    exportFileName = "TestResume"
    Dim linkSource As String
    linkSource = "TestSource2"

    For Each pubPage In ActiveDocument.Pages
        For Each pubShape In pubPage.Shapes
            If pubShape.Type = pbTextFrame Then
                For Each hprlink In pubShape.TextFrame.TextRange.Hyperlinks
                    If InStr(hprlink.Address, "http://bleaney.ca") > 0 Then
                        origAddress = Split(hprlink.Address, "?source=")
                        hprlink.Address = origAddress(0) + "?source=" + linkSource
                    End If
                Next hprlink
            End If
        Next pubShape
    Next pubPage
    ThisDocument.ExportAsFixedFormat pbFixedFormatTypePDF, "C:\" + exportFileName + ".pdf"
End Sub

The problem is that when I update the links, they lose their formatting. How can I preserve the formatting of the hyperlink? I tried looking at the Copy and Paste methods, but it seems like what I would really need is Paste Special, which doesnt exist on the Range property on the Hyperlink object.

A: Try adding the following lines to capture the color and underline and then set it back after the address change
Sub AddSources()
    Dim pubPage As Page
    Dim pubShape As Shape
    Dim hprlink As Hyperlink
    Dim origAddress() As String
    Dim exportFileName As String
      Dim undline AS Long
      Dim clr AS Long
    exportFileName = "TestResume"
    Dim linkSource As String
    linkSource = "TestSource2"

    For Each pubPage In ActiveDocument.Pages
        For Each pubShape In pubPage.Shapes
            If pubShape.Type = pbTextFrame Then
                For Each hprlink In pubShape.TextFrame.TextRange.Hyperlinks
                    If InStr(hprlink.Address, "http://bleaney.ca") > 0 Then
                        undline = hprlink.Range.Font.Underline
                        clr = hprlink.Range.Font.Color
                        origAddress = Split(hprlink.Address, "?source=")
                        hprlink.Address = origAddress(0) + "?source=" + linkSource
                        hprlink.Range.Font.Color = clr
                        hprlink.Range.Font.Underline = undline
                    End If
                Next hprlink
            End If
         Next pubShape
    Next pubPage
    ThisDocument.ExportAsFixedFormat pbFixedFormatTypePDF, "C:\" + exportFileName + ".pdf"
End Sub


text:
Q: How to show percentage of the progress bar on the left side of bar and outside of it? Bootstrap Progress Bar I need to show percentage of the Bootstrap progress bar on the left side like this:
Now I have this:

My HTML:
            76%

Photoshop

Any way I can put in on the left side outside the bar? Using Bootstrap 4

A: Simply create a flex container since you are using V4 of Bootstrap:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">

  76%

Photoshop


text:
Q: Access servlet-api within javaagent I'm trying to access classes from the servlet-api within a javaagent jar that is added to my application via the -javaagent:my-agent.jar flag. My application runs on Tomcat. The problem is that I get a ClassNotFoundException, because the agent jar is loaded by a classloader that has no access to the servlet-api classes.
More specifically, I want to include a ServletContainerInitializer in my javaagent
public class MyInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
        System.out.println(ctx);
    }
}

META-INF/services/javax.servlet.ServletContainerInitializer
org.example.MyInitializer

The result is a ClassNotFoundException because ServletContainerInitializer could not be found.
Is there any way to access the servlet-api within a javaagent? Or more generally, is it possible to access any class that is loaded via the ApplicationClassLoader, like classes from the spring framework?

A: If your agent has a premain method with a signature like
public static void premain(String agentArgs, Instrumentation inst)

You get hands on an Instrumentation object which provides the methods getAllLoadedClasses() and getInitiatedClasses(ClassLoader). Now it would be awkward to search these arrays each time and use the Class instances via Reflection only. But you can use these methods to find the desired API class, determine its runtime ClassLoader and create a new ClassLoader using it as a resolve parent and pointing to your agent classes which require them.

A: What worked for me was I added servlet-api.jar file in the ClassPool.insertClassPath. And that resolved the issue.
    ClassPool $pool = ClassPool.getDefault();
            try {
                $pool.insertClassPath("/apache-tomcat-7.0.50/lib/servlet-api.jar");
            } catch (NotFoundException e) {
                throw new RuntimeException(e);
            }
    return $pool;

https://github.com/presci/MyAgent.git


text:
Q: minify external url & multiple style sheets 2 part problem whilst using minify. Finally got it working on localhost.
1) I have some scripts which can be linked externally to CDN, how do i include these in the minify?
         <script type="text/javascript" src="/min/b=highaccess/js&f=styleswitcher.js,jquery-1.7.2.js,jquery-ui-1.8.19.custom.min.js,downloadxml.js,geometa.js"></script>

I also need to include this:http://maps.google.com/maps/api/js?key=AIzaSyAOpIKcVcsbojjjFIwnAOSsDwi_lARLp8o&sensor=false
If possible i will use hosted scripts.
2) I have managed to minify the CSS, but i have a style switcher for 3 layouts, when i include them in the minify they cascade, not what i intended. Is there a way to minify this or must I have seperate elements for each style?

A: 1) Minifying the external assets from a CDN kinda defeats the purpose of using a CDN in the first place. You're offloading the content to another server and you gain the benefit of having those files being likely to have been cached already (downloaded when a user visits a site using the same CDN as you). If you must have them minified, just get your own local copy and include it in your minify script. Otherwise, I would just leave them as separate script calls.
2) Minifying CSS means that everything is combined into a single request, so yes, styles added later will override the earlier styles. If you have 3 separate themes, you'll need to have 3 separate minification processes for each theme. Just load them dynamically in  tags with javascript and they will override at the time you switch.


text:
Q: How to used a http conection for send a string like email to a server? on Blackberry I have a little trouble, i need to create a way to send a string to a server, i a kinda system of complains
            try {
                String errMsg = validateData();
                if(errMsg == null){
                    String mailURL = CLIENT_CONTACT_URL_MAIL_SERVICE;
                    mailURL = Utils.replaceAll(mailURL, "@toAddress", TO_DEFAULT_ADDRESS);
                    String content = "";
                    content = "Nombre: " + this.names.getText() + "\n";
                    content += "Apellido: " + this.surname.getText() + "\n";
                    content += "Email: " + this.email.getText() + "\n";
                    content += "Telefono: " + this.phone.getText() + "\n";
                    content += "Mensaje: " + this.complains.getText() + "\n";
                    mailURL = Utils.replaceAll(mailURL, "@bodyContent", URLUTF8Encoder.encode(content));
                    Utils.getWebData(mailURL, this);
                }else{
                    Dialog.alert(errMsg);
                }
            } catch (IOException e) {
                Logger.logErrorEvent("Error while sending client contact mail");
            }
            break;

A: The following code will send data to server.
        static String responce;
        static String httpURL;
        httpURL=your_server_url+content;  //here add your server url like- http://www.google.com/ then append the string content.
        try {
        if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
                && RadioInfo
                        .areWAFsSupported(RadioInfo.WAF_WLAN)) {
            httpURL += ";interface=wifi"+";ConnectionTimeout=30000";
        }
        //Dialog.alert(httpURL);
        HttpConnection httpConn;
        httpConn = (HttpConnection) Connector.open(httpURL);
        httpConn.setRequestMethod(HttpConnection.POST);
        DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
        byte[] request_body = httpURL.getBytes();
        for (int i = 0; i < request_body.length; i++) {
            _outStream.writeByte(request_body[i]);
        }
        DataInputStream _inputStream = new DataInputStream(
        httpConn.openInputStream());
        StringBuffer _responseMessage = new StringBuffer();
        int ch;
        while ((ch = _inputStream.read()) != -1) {
            _responseMessage.append((char) ch);
        }
        String res = (_responseMessage.toString());
        responce = res.trim();
        //Dialog.alert(responce);
        httpConn.close();

    }catch (Exception e) {
        Dialog.alert("Connection Time out");
    }

    return responce;


text:
Q: Show identity $\sum_{k=0}^{n-s}(\Delta^sq_k)^2=(KQ)^TKQ$.
Show the identity
$$\sum_{k=0}^{n-s}(\Delta^sq_k)^2=(KQ)^TKQ$$

where
$$Q=(q_0,\ldots,q_n)^T$$
$$\Delta^sq_k=\sum_{v=0}^{s}(-1)^v\binom{s}{v}q_{k+v}$$
$$K=(K_{ij})_{0\leq i \leq n-s,\  0 \leq j \leq n}$$ with
$$K_{ij}=(-1)^{j-i}\binom{s}{j-i}, \ \ \ \ \ \binom{s}{k}=0\ \mathrm{for}\ k<0$$

A: This is just the definition of matrix multiplication, written out.
$KQ$ is a column vector, hence $(KQ)^TKQ$ is the sum of squares of its components.
The $i$-th component ($0\leqslant i\leqslant n-s$) of $KQ$, by the definition, is equal to $$\require{cancel}\sum_{j=0}^{n}K_{ij}q_j=\sum_{j=\cancel{0}\color{red}{i}}^{n}(-1)^{j-i}\binom{s}{j-i}q_j\underset{j=i+k}{=}\sum_{k=0}^{\cancel{n-i}\color{red}{s}}(-1)^k\binom{s}{k}q_{i+k}=\Delta^s q_i$$ because $n-i\geqslant s$ [and $\binom{s}{k}=0$ when $k>s$].


text:
Q: Create a scatterplot from the data of two dataframes? I have two dataframes in python. The content of them is the following:
Table=conn
A   B   relevance
1   3   0.7
2   7   0.1
5   20  2
6   2   7

table=point
Point  Lat   Lon
1      45.3  -65.2
2      34.4  -60.2
3      40.2  -60.1
20     40.4  -63.1

In the first table, column A represents an origin, column B a destination and the relevance of the link.
On the other hand, in the second table we have for each point (origin or destination) its coordinates.
The problem is that I want to create a visualization in Python that allows to query the coordinates of each origin or destination (column A and B of the first table) in the second table and make a scatterplot with it. Then, link each of the origins and destinations of the first column taking into account the relevance with thicker lines as it has more relevance.
link refers to the line that joins the points in the graphic representation.
Any idea? I've started with a very basic code approach but I'm really having trouble following along.
for row in conn.interrows():
    row[1][0]
    row[1][1]
    row[1][3]

A: Do you have two DataFrames: point and conn, right?
# To set indexes of "point" equal to "Points"
point.set_index(point.Point, inplace=True)

# config width of lines
min_width = 0.5
max_width = 4.0

min_relevance = conn.relevance.min()
max_relevance = conn.relevance.max()
slope = (max_width - min_width)/(max_relevance - min_relevance)
widths = min_width + slope*(conn.relevance - min_relevance)

# plot lines
for i in range(len(conn)):
    origin = conn.loc[i, 'A']
    destin = conn.loc[i, 'B']
    lat = point.loc[[origin, destin], 'Lat']
    lon = point.loc[[origin, destin], 'Lon']
    plt.plot(lat, lon, c='red', lw=widths[i])

# plot points
plt.plot(point.Lat, point.Lon, ls='', marker='o', c='blue')


text:
Q: How do I connect items from one parse method to another? '''
    import scrapy
    from ..items import GooddealItem

    class FarmtoolsSpider(scrapy.Spider):
        name = 'farmtools'
        allowed_domains = ['www.gooddeal.com']
        start_urls = ['https://www.gooddeal.com/all?
        source=private&sort=publishdate%20desc']

        def parse(self, response):

            items = GooddealItem()

            rows = response.xpath('//ul[@class="card-collection"]/li')

            for row in rows:
                link = row.xpath('.//a/@href').get() #this is the full link.
                link_split = link.split('/')[-1] #this splits the url link th first time.
                linkid = link_split.split('?')[0] #this splits it the second time.
                title = row.xpath('.//div[1]/p[@class="card__body-title"]/text()').get()
                county = row.xpath('.//a/div/div[2]/div[1]/ul[@class="card__body-keyinfo"]/li[contains(text(),"min")]/following-sibling::node()/text()').get()
                price = row.xpath('.//p[@class="card__price"]/span[1]/text()').get()
                subcat = row.xpath('.//a/div/div[2]/div[1]/p[2]/text()[2]').get()
                zero = row.xpath('.//a/div/div[2]/div[1]/ul[@class="card__body-keyinfo"]/li[contains(text(),"min")]/text()').get()
                if zero == '0 min':

                     items['linkid'] = linkid
                     items['title'] = title
                     items['county'] = county
                     items['price'] = price
                     items['subcat'] = subcat
                     items['zero'] = zero
                     items['link'] = link

                    yield response.follow(url = link, callback=self.parse_item_page)

        def parse_item_page(self, response):

            items = GooddealItem()

            rows = response.xpath('/html/body[1]')

            for row in rows:
                category = row.xpath('.//main/div/div[1]/div/div[1]/div/nav/span/a[1]/span/text()').get(),
                views = row.xpath('.//main/div/div[1]/div/div[2]/div[2]/div[1]/div[3]/div[1]/div/div[1]/div/div/span[2]/text()').get(),
                seller_id = row.xpath('.//main/div/div[1]/div/div[2]/div[2]/div[2]/div[3]/div/div[1]/div[1]/div[2]/a/@href').get(),
                seller_ads = row.xpath('.//main/div/div[1]/div/div[2]/div[2]/div[2]/div[3]/div/div[2]/div/dl[3]/dd/text()').get(),
                lifetime_ads = row.xpath('//main/div/div[1]/div/div[2]/div[2]/div[2]/div[3]/div/div[2]/div/dl[4]/dd/text()').get()

                items['category'] = category
                items['views'] = views
                items['seller_id'] = seller_id
                items['seller_ads'] = seller_ads
                items['lifetime_ads'] = lifetime_ads

                yield items

'''
I'm stuck on this as it's my first attempt. When I run the code I'm just getting back:
2020-07-12 22:53:21 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.gooddeal.com/dogs-for-sale/dachshunds/25348559>
{'category': (None,),
'lifetime_ads': None,
'seller_ads': (None,),
'seller_id': (None,),
'views': (None,)}
Any help will be appreciated, thanks

A: I'm assuming you want the data scraped in parse method to be joined together with the data scraped in the parse_item_page.
If you are using Scrapy v1.7+ you can use cb_kwargs when building the request.
This parameter receives a dict with arbitrary data that will be used as argument in the callback function. So you would have to do something like this in your request:
        ...
        yield response.follow(url = link, callback=self.parse_item_page, cb_kwargs={'scraped_item': items})

For this to work, you also need to change the callback function to receive this parameter. Like this:
    def parse_item_page(self, response, scraped_item):
        ...

Scrapy will take care of sending the scraped_item when calling the parse_item_page.
If you are using Scrapy v1.6 or older:
You will need to use the meta parameter. This method still works in more recent versions, but cb_kwargs(solution above) are preferable.
When building the request you will use the meta parameter to include some arbitrary data in the request. The data will be accessible in the response object that the callback function receives. Your request should look like this:
        ...
        yield response.follow(url = link, callback=self.parse_item_page, meta={'scraped_item': items})

In this case you will access the data by calling response.meta:
    def parse_item_page(self, response):
        items = response.meta.get('scraped_item') #response.meta is a dict
        ...


text:
Q: NestJS Serialization - how to instantiate default values I have the following classes and enum in one of my nestjs service
export enum Gender {
    MALE = 'M',
    FEMALE = 'F',
}

export class Address {
  address1: string = '';
  address2: string = '';
  address3: string = '';
  city: string = '';
  state: string = 'TX';
  country: string = 'USA';
}

export class Profile {
  constructor(data?: any) {
        if (data) {
            Object.assign(this, data);
        }
  }

  id: string;
  firstName: string;
  lastName: string;
  email: string;
  gender: Gender;
  address?: Address = new Address();
}

When I instantiate a Profile object with new operator like below, it correctly populates
address field with default values (e.g.state and country fields)
let profile: Profile = new Profile();
I have an end-point - POST - /profiles
  @Post('profiles')
  @HttpCode(204)
  @ApiResponse({
    status: 204,
    description: 'Audit Entry Created',
  })
  @ApiResponse({
    status: 400,
    description: 'Invalid Audit.',
  })
  @ApiResponse({
    status: 401,
    description: 'Unauthorized Access.',
  })
  @ApiResponse({
    status: 500,
    description: 'System Error.',
  })
  public async create(@Body() profile: Profile): Promise<void> {
    await this.service.create(profile);
  }

which takes profile JSON in request body

{
  'id':'123',
  'firstName': 'John',
  'lastName': 'Doe',
  'email':'john.doe@johndoe.com',
  'gender': 'M'
}

When i don't pass address part of request body, i am expecting
a default address object will be created with the default values as I have that part of Profile class.  Which is not happening.
Any suggestions?

A: Without using any transformations, the incoming body will just be a plain JSON representation of the request. To get the body to be an instance of the Profile class, you'd need to use the ValidationPipe, or a custom pipe of your own, and instantiate the Profile class using the incoming body.
Otherwise, @Body() just maps to express or fastify's req.body which won't do any de-serialization for you

A: This issue was resolved after adding @UsePipes(new ValidationPipe({ transform: true }))
  @Post('profiles')
  @UsePipes(new ValidationPipe({ transform: true }))
  public async create(@Body() profile: Profile): Promise<void> {
    await this.service.create(profile);
  }


text:
Q: Ajax and PHP, post request not working So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
 $(function (){
              $(".commit").on('click',function(){
                const sha_id = $(this).data("sha");
                const sha_obj = JSON.stringify({"sha": sha_id});
                $.ajax({
                   url:'commitInfo.php',
                   type:'POST',
                   data: sha_obj,
                   dataType: 'application/json',
                   success:function(response){
                      console.log(response);
                      window.location.replace("commitInfo");
                    },
                   error: function (resp, xhr, ajaxOptions, thrownError) {
                        console.log(resp);
                     }
                 });
              });
           });

Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);

However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!

A: You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
  $(".commit").on('click', function() {
    const sha_id = $(this).data("sha");
    const sha_obj = {
      "sha": sha_id
    };
    $.ajax({
      url: 'commitInfo.php',
      type: 'POST',
      data: sha_obj,
      dataType: 'json',
      success: function(response) {
        console.log(response);
      },
      error: function(resp, xhr, ajaxOptions, thrownError) {
        console.log(resp);
      }
    });
  });
});

And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
   const sha_id = $(this).data("sha");
   window.location.replace("commitInfo.php?sha=" + sha_id );
});


text:
Q: Python logging time since start of program I'm using the logging module to create loggers and output data. Instead of using $(asctime)s in logging.Formatter, is there a good way to log the timestamp relative to the creation of the logger?

A: I liked Franky1's answer but I didn't want to lose %(asctime)s style in the log format. Here's a solution that adds a %(delta)s style.
import datetime
import logging
import time

class DeltaTimeFormatter(logging.Formatter):
    def format(self, record):
        duration = datetime.datetime.utcfromtimestamp(record.relativeCreated / 1000)
        record.delta = duration.strftime("%H:%M:%S")
        return super().format(record)

# add custom formatter to root logger
handler = logging.StreamHandler()
LOGFORMAT = '+%(delta)s - %(asctime)s - %(levelname)-9s: %(message)s'
fmt = DeltaTimeFormatter(LOGFORMAT)
handler.setFormatter(fmt)
logging.getLogger().addHandler(handler)
logger = logging.getLogger()

# test of the logger output
logger.error('Test')
for sleep in (1, 2, 3, 4, 5):
    time.sleep(sleep)
    logger.error('logging')

A: Using %(relativeCreated)d field in a conventional Formatter format string will display the milliseconds elapsed since the logging module was loaded. While milliseconds might not be what you want, there's no additional coding required.

A: You could write your own formatter:
from datetime import timedelta
import logging
import time

class ElapsedFormatter():

    def __init__(self):
        self.start_time = time.time()

    def format(self, record):
        elapsed_seconds = record.created - self.start_time
        #using timedelta here for convenient default formatting
        elapsed = timedelta(seconds = elapsed_seconds)
        return "{} {}".format(elapsed, record.getMessage())

#add custom formatter to root logger for simple demonstration
handler = logging.StreamHandler()
handler.setFormatter(ElapsedFormatter())
logging.getLogger().addHandler(handler)

log = logging.getLogger('test')
log.error("Message 1")

time.sleep(5)

log.error("Message 2")

Your question refers to the elapsed time from the 'start of program' as well as 'creation of logger' which could mean different things.
This will measure the time elapsed from the creation of CustomFormatter which you could do close to the start of the program or when a logger is created.

A: I wrote my own solution based on some stackoverflow ideas.
It is a subclass of logging.Formatter
import datetime
import logging
import time

# subclass of logging.Formatter
class RuntimeFormatter(logging.Formatter):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.start_time = time.time()
    def formatTime(self, record, datefmt=None):
        duration = datetime.datetime.utcfromtimestamp(record.created - self.start_time)
        elapsed = duration.strftime('%H:%M:%S')
        return "{}".format(elapsed)

# add custom formatter to root logger
LOGFORMAT = '%(asctime)s - %(levelname)-9s: %(message)s'
handler = logging.StreamHandler()
fmt = RuntimeFormatter(LOGFORMAT)
handler.setFormatter(fmt)
logging.getLogger().addHandler(handler)
logger = logging.getLogger()

# test of the logger output
logger.error('Test')


text:
Q: ASP.NET v4 Extensionless URL feature does not work on IIS 6.0 To avoid static requests impact performance, I want to use the ASP.NET v4.0 Extensionless URL feature, but it does not work.
My environment:

*

*windows server sp2 and IIS6

*asp.net MVC 3 with .net 4

*The site is configured for ASP.NET 4.0 and no virtual folders

*no isapi rewriting

I requested the url like "http://domain.com/home/", then get "/home/eurl.axd/f7e1f50533b94f47869a8856c16dffdf/" 404 error.
Error message show that: Microsoft .NET Framework version:4.0.30319; ASP.NET version:4.0.30319.1
It seems that: aspnet_filter.dll appends "/eurl.axd/GUID" to extensionless URLs and aspnet_isapi.dll does not remove "/eurl.axd/GUID".
I want to know how to resolve this problem?
(I need extensionless url and can not use wildcard script mapping)
Thanks

Update - Resolved

Remove the v2.0 aspnet_isapi.dll in the root web site's ISAPI Filters

A: To use ASP.NET v4 extensionless URL feature, check this list:
1) v4.0 aspnet_filter.dll is registered as an ISAPI filter at the web server level.
2) ".axd" is script mapped to the v4.0 aspnet_isapi.dll at the web site level.
3) the web site has read and script permission.
4) "EnableExtensionlessUrls" in registry is not set or is set to 1.
5) the web site configure to asp.net 4.0
6) v2.0 aspnet_filter.dll is not registered,check the root website's ISAPI Filter List(this cause my problem)
If the above checks out, the only other thing you need is a routing table or some ASP.NET code that remaps the URL to a managed handler.

A: Notice that IIS 6 and IIS 7 have two different pipelines and so ASP.NET applications run differently in these two invironments.
Please read: ASP.NET Integration with IIS 7

In IIS 7, the ASP.NET request-processing pipeline overlays the IIS pipeline directly, essentially providing a wrapper over it instead of plugging into it.

but

In IIS 6.0 and previous releases, ASP.NET was implemented as an IIS ISAPI extension.


text:
Q: How should I add Column Level CHARSET using Fluent NHibernate? I am using Fluent Nhibernate with MySQL Configuration to expose schema.
    Below is my database entity with entity mapping.
public class MyEntity
{
    public MyEntity() { }
    public virtual int ID {get;set;}
    public virtual string FormalName { get; set; }
}

public class MyEntityMap : ClassMap<MyEntity>
{
    public MyEntityMap()
    {
        Table("MyEntity");
        LazyLoad();
        Id(x => x.ID).GeneratedBy.Assigned().Column("ID");
        Map(x => x.FormalName).Column("FormalName").Length(200); // In Script must be FormalName VARCHAR(200) CHARSET Latin1
    }

A: Simplest way as I think would be to add CustomSQLType in Map and add CHARSET within it.
eg.
Your code should be :
Map(x => x.FormalName).Column("FormalName").CustomSqlType("varchar(200) charset latin1").Length(200); // In Script must be FormalName VARCHAR(200) CHARSET Latin1

Notice the CustomSqlType in above code.


text:
Q: CasperJs : How can I submit a Form that has action="" (That has no action)
In the sample code in the documentation of casperjs, submitting form is through this:
var loginFormSelector = 'form[name="loginForm"]';
casper.waitForSelector(loginFormSelector,
        function() {
            this.echo("Login page loaded. Entering in username and password");
            this.fillSelectors(loginFormSelector, {
                'input#username': username,
                'input#password': password'
            }, true);
        },
        function() {
            this.die("Login form not found");
        });

My Error Log
Login page loaded. Entering in username and password
[info] [remote] attempting to fetch form element from selector: 'form[name="loginForm"]'
[debug] [remote] Set "username" field value to usrname
[debug] [remote] Set "password" field value to ***********
[info] [remote] submitting form to unknown, HTTP POST
[info] [phantom] Step anonymous 4/5: done in 14362ms.


text:
Q: how to calculate coskew and cokurtosis You can calculate skew and kurtosis with the the methods

*

*pd.Series.skew

*pd.Series.kurt

*pd.DataFrame.skew

*pd.DataFrame.kurt
However, there is no convenient way to calculate the coskew or cokurtosis between variables.  Or even better, the coskew or cokurtosis matrix.

Consider the pd.DataFrame df
import pandas as pd
import numpy as np

np.random.seed([3,1415])
df = pd.DataFrame(np.random.rand(10, 2), columns=list('ab'))

df

          a         b
0  0.444939  0.407554
1  0.460148  0.465239
2  0.462691  0.016545
3  0.850445  0.817744
4  0.777962  0.757983
5  0.934829  0.831104
6  0.879891  0.926879
7  0.721535  0.117642
8  0.145906  0.199844
9  0.437564  0.100702

How do I calculate the coskew and cokurtosis of a and b?

A: References

*

*Coskewness

*Cokurtosis
Calculating coskew
My interpretation of coskew is the "correlation" between one series and the variance of another.  As such, you can actually have two types of coskew depending on which series we are calculating the variance of.  Wikipedia shows these two formula
'left'

'right'

Fortunately, when we calculate the coskew matrix, one is the transpose of the other.
def coskew(df, bias=False):
    v = df.values
    s1 = sigma = v.std(0, keepdims=True)
    means = v.mean(0, keepdims=True)

    # means is 1 x n (n is number of columns
    # this difference broacasts appropriately
    v1 = v - means

    s2 = sigma ** 2

    v2 = v1 ** 2

    m = v.shape[0]

    skew = pd.DataFrame(v2.T.dot(v1) / s2.T.dot(s1) / m, df.columns, df.columns)

    if not bias:
        skew *= ((m - 1) * m) ** .5 / (m - 2)

    return skew

demonstration
coskew(df)

          a         b
a -0.369380  0.096974
b  0.325311  0.067020

We can compare this to df.skew() and check that the diagonals are the same
df.skew()

a   -0.36938
b    0.06702
dtype: float64

Calculating cokurtosis
My interpretation of cokurtosis is one of two

*

*"correlation" between a series and the skew of another

*"correlation" between the variances of two series

For option 1. we again have both a left and right variant that in matrix form are transposes of one another.  So, we will only focus on the left variant.  That leaves us with calculating a total of two variations.
'left'

'middle'

def cokurt(df, bias=False, fisher=True, variant='middle'):
    v = df.values
    s1 = sigma = v.std(0, keepdims=True)
    means = v.mean(0, keepdims=True)

    # means is 1 x n (n is number of columns
    # this difference broacasts appropriately
    v1 = v - means

    s2 = sigma ** 2
    s3 = sigma ** 3

    v2 = v1 ** 2
    v3 = v1 ** 3

    m = v.shape[0]

    if variant in ['left', 'right']:
        kurt = pd.DataFrame(v3.T.dot(v1) / s3.T.dot(s1) / m, df.columns, df.columns)
        if variant == 'right':
            kurt = kurt.T
    elif variant == 'middle':
        kurt = pd.DataFrame(v2.T.dot(v2) / s2.T.dot(s2) / m, df.columns, df.columns)

    if not bias:
        kurt = kurt * (m ** 2 - 1) / (m - 2) / (m - 3) - 3 * (m - 1) ** 2 / (m - 2) / (m - 3)
    if not fisher:
        kurt += 3

    return kurt

demonstration
cokurt(df, variant='middle', bias=False, fisher=False)

          a        b
a  1.882817  0.86649
b  0.866490  1.63200

cokurt(df, variant='left', bias=False, fisher=False)

          a        b
a  1.882817  0.19175
b -0.020567  1.63200

The diagonal should be equal to kurtosis
df.kurtosis() + 3

a    1.882817
b    1.632000
dtype: float64


text:
Q: How to get user's username in v2.0 or later of Facebook's Graph API I used to get the user's username in the API 1.0 fairly easily, using /me and getting the username property of the response object.
Now I'm getting this error with API 2.0:

"(#12) username is deprecated for versions v2.0 and higher"

The only way I found to get this until now was to use FQL, but now it seems deprecated.
Is there a way around this?

A: I found a simple workaround that involves a get request to Facebook. Instead of the username, Facebook will give you an ID that is unique to your application.
I have found that making a request to https://www.facebook.com/[profile_id] will then redirect to the user's real profile. The username can be extracted from the redirect URL.
Example:
> curl -i https://www.facebook.com/710290539
HTTP/1.1 301 Moved Permanently
Location: https://www.facebook.com/colinskow

(Note: Since I am the owner of the app in test mode, this could possibly be an exception. Please let me know in comments if you are able to confirm this in a production environment.)

A: As a workaround you can use the email as a unique identifier. Email address can be retrieved using  "email" as the permission scope.
Facebook has removed the username field from the new API version. It is not possible to retrieve the username. But Facebook provides an application specific unique ID. If you need to share the same user between several apps you can use the newly introduced Business Mapping API. This allows to add all the required apps to a group. In this case the ID will be unique among all the apps in the group.
More information on Business Mapping API is available at https://developers.facebook.com/docs/apps/for-business 1

A: I don't mean to be unhelpful, but it appears access to username has been removed from the API, as far as I can tell.  Places where an app may have been using username, such as in the old share dialogs, can no longer do that when used with the 2.0 API.  I think its also a way of preventing apps from having access to usable unique identifiers outside of the app scope - any user IDs you retrieve under 2.0 API are specific to your app alone.


text:
Q: How to create a summary table Given a table that lists actions of actors (I hide irrelevant timestamp column), we would like to have a summary table listing a row per actor with counts per action he did.
we have predefined three possible actions
Standard SQL or Google BigQuery Syntax

Actor   |   Action
_________________
Sam         shoot
Sam         shoot
Sam         heal
Sam         dead
Bob         shoot
Bob         shoot
Bob         shoot
Bob         dead

To

Actor   |  shoot  |  heal   | Dead
_____________________________________
Sam        2          1         1
Bob        3          0         1

A: If you know the columns that you want, use countif():
select actor,
       countif(action = 'shoot') as shoot,
       countif(action = 'heal') as heal,
       countif(action = 'dead') as dead
from t
group by actor;

If you don't, then you have a challenge, because SQL queries tend to need to know what columns are in the result set.  One workaround is to put the values in rows rather than columns:
actor    action     count
 sam     shoot        2
 . . .

That is:
select actor, action, count(*)
from t
group by actor, action;

(This does not include 0 counts, but the query can be adjusted fro this.)
Or to use JSON or arrays to store the values for every action.


text:
Q: How to automatically disable inactive accounts when AD is not used Need a way to automatically identify and disable accounts after 90 days of inactivity.
The environment is Windows Server 2008 and Active Directory is not used.
I find scripts to doing this when AD is used but nothing otherwise.

A: There is no built-in mechanism to do this with local accounts.
If I wanted to do something like this without using AD, I would build some kind of script to check for the user popping up in the security event log in the last 90 days.

A: There is a powershell module in the technet repository for local user mgmt.  I have not worked with it, but it appears to do what you need.  It can be found here: http://gallery.technet.microsoft.com/scriptcenter/Local-Account-Management-a777191b.
This snippet might get you started:
get-localuser mypc\greg |select name,lastlogin

Name                LastLogin
----                ---------
Greg                6/13/2012 6:35:56 PM


text:
Q: Match "\b(OneTwoThree|OneTwo|TwoThree)\b" with least repetition I managed this with PCRE only, but I'd like it to work with Javascript's RegExp as well. That, and the regex is ugly. Are there any other, saner ways of accomplishing this?
Note, that while the topic says "OneTwoThree", I'm using "qwe" for brevity.
$ cat test.txt | grep -oP '\b(q(\g<we>|\g<w>)|(?<we>(?<w>w)e))\b'
qwe
qw
we

File test.txt contains:
qwe qw we q w e qq qe wq ww eq ew ee qqq qqw qqe qwq qww qeq qew qee wqq wqw wqe wwq www wwe weq wew wee eqq eqw eqe ewq eww ewe eeq eew eee
(Only the first three should match.)

A: Something like this would work for your sample data:
/\b(qwe?|we)\b/
/\b(q?we|qw)\b/

Which you can test here.
But for the full pattern you specified in the title it would be
/\b(OneTwo(Three)?|TwoThree)\b/
/\b((One)?TwoThree|OneTwo)\b/

Now, this is not more readable, but it does reduce redundancy slightly:
/\b(?!w\b)q?we?\b/

Which you can test here
Or for your full pattern:
/\b(?!Two\b)(One)?Two(Three)?\b/

A: Maybe this but not sure -
 # \b(?=..)q?we?\b

 \b
 (?= . . )
 q? w e?
 \b


text:
Q: Efficient creating of SQLite db with Qt desktop app I have a small desktop application that stores its data in an SQLite db.
Currently, when the app is first run (or the user wants to create a new config) I just delete the db file and run a load of QSqlQuery.exec("CREATE TABLE...") statements.
When I realised I had to change the db structure, this lead to a fair bit of work hunting down all the SQL I had used and updating it to work. So now I am trying to come up with a more modular approach to storing the SQL\creating tables...
My first idea was to store the SQL statements for creating the db in a text file, as a Qt resource, but now I've actually implemented it, it feels 'clunky' (QFile->QTextStream->loop on readLine()) and doesn't allow me to format my SQL statements in the text file for readability.
Another way I could do it is to generate an empty db at compile-time and store that as a resource, but to me I think the extra size of the binary would outweigh the gains in simplicity for new db creation.
I could create a load of global const QStrings, but I like this idea least of all and would prefer to seperate non-C++\Qt from the source code if possible.
So, any ideas from the gurus out there??

A: If you search for a ; at the end of a line, you can format SQL statements over multiple lines.
An empty DB file is not big if you compress it.


text:
Q: Can I use the maven war as a form of overwriting the other projects that already exist? I am beginner on Spring and Maven.
In Spring Framework,
I want to manage a separate version control flow.
1. Main Project that already exist.
2. Module of the partial use that packaged by maven war.

Two projects should be treated separately when Push and Pull.
But Files on two projects may be present in the same folders.
How can I use this?

A: This is actually related with version control system you currently use. Git for example supports submodules. You can create a maven module directly in your root project folder and define it as git submodule. So they have different git tracks and may seperately maintained.

A: I believe what you need might be achievable by using 'war-overlays' as documented here
To summarize, you specify the 'child' project as a dependency in the 'Main' project:
...
  <dependencies>
    <dependency>
      <groupId>com.example.projects</groupId>
      <artifactId>documentedprojectdependency</artifactId>
      <version>1.0-SNAPSHOT</version>
      <type>war</type>
      <scope>runtime</scope>
    </dependency>
    ...
  </dependencies>
  ...

And you define the overlay in the maven-war-plugin's configuration:
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.6</version>
        <configuration>
            <overlays>
                <overlay>
                    <id>my-webapp-index.jsp</id>
                    <groupId>com.example.projects</groupId>
                    <artifactId>my-webapp</artifactId>
                    <includes>
                        <include>index.jsp</include>
                    </includes>
                </overlay>
                <overlay>
                    <!-- empty groupId/artifactId represents the current build -->
                </overlay>
            </overlays>
        </configuration>
    </plugin>


text:
Q: Regular expression to check contains only EDIT: Thank you all for your inputs. What ever you answered was right.But I thought I didnt explain it clear enough.
I want to check the input value while typing itself.If user is entering any other character that is not in the list the entered character should be rolled back.
(I am not concerning to check once the entire input is entered).

I want to validate a date input field which should contain only characters 0-9[digits], -(hyphen) , .(dot), and /(forward slash).Date may be like 22/02/1999 or 22.02.1999 or 22-02-1999.No validation need to be done on either occurrence or position. A plain validation is enough to check whether it has any other character than the above listed chars.
[I am not good at regular expressions.]
Here is what I thought should work but not.
  var reg = new RegExp('[0-9]./-');

Here is jsfiddle.

A: Your expression only tests whether anywhere in the string, a digit is followed by any character (. is a meta character) and /-. For example, 5x/- or 42%/-foobar would match.
Instead, you want to put all the characters into the character class and test whether every single character in the string is one of them:
var reg = /^[0-9.\/-]+$/

*

*^ matches the start of the string

*[...] matches if the character is contained in the group (i.e. any digit, ., / or -).
The / has to be escaped because it also denotes the end of a regex literal.
- between two characters describes a range of characters (between them, e.g. 0-9 or a-z). If - is at the beginning or end it has no special meaning though and is literally interpreted as hyphen.

*+ is a quantifier and means "one or more if the preceding pattern". This allows us (together with the anchors) to test whether every character of the string is in the character class.

*$ matches the end of the string

Alternatively, you can check whether there is any character that is not one of the allowed ones:
var reg = /[^0-9.\/-]/;

The ^ at the beginning of the character class negates it. Here we don't have to test every character of the string, because the existence of only character is different already invalidates the string.
You can use it like so:
if (reg.test(str)) { // !reg.test(str) for the first expression
    // str contains an invalid character
}

A: Try this:
([0-9]{2}[/\-.]){2}[0-9]{4}

A: If you are not concerned about the validity of the date, you can easily use the regex:
^[0-9]{1,2}[./-][0-9]{1,2}[./-][0-9]{4}$

The character class [./-] allows any one of the characters within the square brackets and the quantifiers allow for either 1 or 2 digit months and dates, while only 4 digit years.
You can also group the first few groups like so:
^([0-9]{1,2}[./-]){2}[0-9]{4}$

Updated your fiddle with the first regex.


text:
Q: Requiring a folder and using exports.{function} Currently I have this setup:
// index.js
var example = require('./folder');

and:
// folder/index.js
require('./more');

// folder/test.js
exports.thing = function() {
    console.log('test');

    return true;
}

But when I try in index.js to call example.thing I get:
example.thing is not a function
Is there any way to make it work? Cheers.

A: Directory requiring is not supported by node. It requires index.js if it presented in the directory.
To export thing in index.js do the following:
// index.js
exports.thing = require('./test.js').thing;

A: Are you calling it right? Because I tried it and it's working.
You should call it like example.thing() and not example.thing.


text:
Q: php submit javascript form I'm parsing a website with php to retrieve data. Part of the data becomes visible after selecting values in a javascript combobox.
Is their a way for php to select a value in the combobox, submit it and handle result?

A: I'm afraid not. You will have to dissect the page you are scraping to see where the data that becomes visible comes from. Use Firebug to help you.

A: I ended up using the Developer Tools from Chrome on the network tab. This allowed me to capture the form data that is been posted with the javascript combobox.
With cURL I performed the post in php.


text:
Q: Rails 3 - Help with view, dynamic html attr? Right now, I have a do loop for a task model in my view:
<% @tasks.each do |t| %>

    <%= link_to t.name, edit_task_path(t) %>

<% end %>

I need some help making it so the div class changes based off my model data. I've tried doing this:
   <% @tasks.each do |t| %>

        <%= link_to t.name, edit_task_path(t) %>

    <% end %>

But that failed miserably. I then read up on content tag, and was trying something like:
content_tag(:div, :class => t.theme){<%= link_to t.name, edit_task_path(t) %>}

in the loop but that was rendering it as text.
Anyway, just need some help learning how to change html tag attributes based off the model data? Is this something I would build a view helper for?
Thanks

A: <% @tasks.each do |t| %>
  <div class="task <%= t.theme %>">
    <%= link_to t.name, edit_task_path(t) %>

 <% end %>

A: The reason your first approach isn't working, is that you haven't included the ERb tags (<%= %>) to output the return value from t.theme. In order for that to show up in the output, you need to do this:
<% @tasks.each do |t| %>
  <div class="task <%= t.theme%>">
    <%= link_to t.name, edit_task_path(t) %>

<% end %>

Remember: ERb knows nothing about HTML, it just scans the entire file for <% %> or <%= %> tags, and evaluates the ruby code within them.
content tag should work the way you've got it there, but I'd rather pass in the tag's content as the third parameter instead of using a block (I assume you're using Rails 3, the syntax is slightly different in previous versions):
<% @tasks.each do |t| %>
  <%= content_tag :div,
                  :class => "task #{t.theme}",
                  link_to(t.name, edit_task_path(t)) %>
<% end %>


text:
Q: XML inside XML attributes. C# app settings in console application in a XML settings file I am using for console application You have such structure:
...
< appSettings>
        < add key="Message" value="Hello, World!" />
< /appSettings>
...

You access them with ConfigurationSettings.AppSettings["Message"]
I have also large strigs with line breaks etc. (e.g. SQL scripts templates) inside value-attribute. It works great.
Also I have a XML template, which I had as separate file.
My target is to save all configurable parameters in this app settings file. XML template also.
I know, while saving large text inside XML attributes may be passably ok, but saving XML inside XML attributes is crazy.
Is there any way to store all kinds of settings in this file or do I have to deploy separate XMl file?
Thank You!

A: You can create your own config section as explained in this post.
The article describes customizing web.config sections but it should work exactly the same way for .exe.config.


text:
Q: Efficiency when populating a vector Which would be more efficient, and why?
vector<int> numbers;

for (int i = 0; i < 10; ++i)
    numbers.push_back(1);

or
vector<int> numbers(10,0);

for (int i = 0; i < 10; ++i)
    numbers[i] = 1;

Thanks

A: The fastest would be:
vector <int> numbers(10, 1);

As for your two methods, usually the second one; although the first one avoids the first zeroing of the vector in the constructor, it allocates enough memory from the beginning, avoiding the reallocation.
In the benchmark I did some time ago the second method won even if you called reserve before the loop, because the overhead of push_back (which has to check for each insert if the capacity is enough for another item, and reallocate if necessary) still was predominant on the zeroing-overhead of the second method.
Note that this holds for primitive types. If you start to have objects with complicated copy constructors generally the best performing solution is reserve + push_back, since you avoid all the useless calls to the default constructor, which are usually heavier than the cost of the push_back.

A: In general the second one is faster because the first might involve one or more reallocations of the underlying array that stores the data. This can be aleviated with the reserve function like so:
vector<int> numbers;
numbers.reserve(10);

for (int i = 0; i < 10; ++i)
    numbers.push_back(1);

This would be almost close in performance to your 2nd example since reserve tells the vector to allocate enough space for all the elements you are going to add so no reallocations occur in the for loop. However push_back still has to check whether vector's size exceeds it's current capacity and increment the value indicating the size of the vector so this will still be slightly slower than your 2nd example.

A: In general, probably the second, since push_back() may cause reallocations and resizing as you proceed through the loop, while in the second instance, you are pre-sizing your vector.

A: The second one is faster because of preallocation of memory. In the first variant of code you could also use numbers.reserve(10); which will allocate some memory for you at once, and not at every iteration (maybe some implementation does more bulky reservation, but don't rely on this).
Also you'd better use iterators, not straight-forward access. Because iterator operation is more predictable and can be easely optimized.
#include <algorithm>
#include <vector>
using namespace std;

staitc const size_t N_ELEMS = 10;

void some_func() {
  vector<int> numbers(N_ELEMS);

  // Verbose variant
  vector<int>::iterator it = numbers.begin();
  while(it != numbers.end())
    *it++ = 1;

  // Or more tight (using C++11 lambdas)
  // assuming vector size is adjusted
  generate(numbers.begin(), numbers.end(), []{ return 1; });
}

//

A: Use the second, and if you have iota available (C++11 has it) use that instead of the for loop.
std::vector<int> numbers(10);
std::iota(numbers.begin(), numbers.end(), 0);

A: There is a middle case, where you use reserve() then call push_back() a lot of times. This is always going to be at least as efficient than just calling push_back() if you know how many elements to insert.
The advantage of calling reserve() rather than resize() is that it does not need to initialise the members until you are about to write to them. Where you have a vector of objects of a class that need construction, this can be more expensive, especially if the default constructor for each element is non-trivial, but even then it is expensive.
The overhead of calling push_back though is that each time you call it, it needs to check the current size against the capacity to see if it needs to re-allocate.
So it's a case of N initializations vs N comparisons. When the type is int, there may well be an optimization with the initializations (memset or whatever) allowing this to be faster, but with objects I would say the comparisons (reserve and push_back) will almost certainly be quicker.


text:
Q: Reliability of Steam's off-line mode What are the general experiences with it? I've only tried it once, on one game, and it did work, but I am used to hearing that it is very unreliable and very unlikely to work in most cases.
Obviously, I am not asking about multiplayer games.

A: Steam Offline mode has been improved during the last year of Steam developments.
You shouldn't have any issues while playing offline, but I can give you some advice and suggestions:

*

*Games that use Cloud features, played offline, will not allow you to get old savegames.

*Achievements will not work offline (it seems at least Can the Steam achievements be gained also offline?).

*Leaderboards, if implemented by the game, will not work offline.

In addition to this, if you plan to play offline for long time I suggest you to do this before you do go offline:

*

*Set for all game, using Properties, the option to not udpate automatically

*Then choose from the Steam menu, the command Go Offline

*Restart Steam

*Verify that all games you are interested to play start

Could be a bit paranoid but it will prevent bad surprises.

A: It works good for every game able to play offline, but make sure you activate it before you go for a trip without internet.
Because 90% of times, it will work, detect that no connection, and propose you the offline mode. But the remaining 10%, it will consider it didn't connect correctly the last time it launched. And since you are not authenticated for him, it will refuse to open the offline mode, and ask you to connect to the Steam network.
So be sure to switch to offline mode before having to use it.

A: Never had any problems playing:

*

*Counter Strike: Condition Zero

*Plants vs Zombies

*Left for Dead

so I don't think it's an issue


text:
Q: C++11 packaged_task doesn't work as expected: thread quits and no output I've this code snippet:
#include<future>
#include<iostream>
using namespace std;
int main() {
  cout << "---------" << endl;
  packaged_task<int(int, int)> task([](int a, int b){
    cout << "task thread\n";
    return a + b;
  });
  thread tpt(move(task), 3, 4);
  cout << "after thread creation\n";
  future<int> sum = task.get_future();
  cout << "before join\n";
  tpt.join();
  cout << "after join\n";
  sum.wait();
  cout << "after wait\n";
  cout << sum.get() << endl;
  return 0;
}

It only printed
---------
after thread creation
task thread

then hang for about 2 seconds, and ends. I don't see my packaged_task function execute. It didn't print "after join\n" and "after wait\n"
Why my program ended unexpectedly, how to fix?

A: You're moving the packaged task into the thread and then trying to get the future object from the moved-from task which no longer has any state. For me this throws an exception: https://godbolt.org/z/Gh534dKac

terminate called after throwing an instance of 'std::future_error'
what():  std::future_error: No associated state

You need to instead get the future from the task before moving it into the thread:
...
future<int> sum = task.get_future();
thread tpt(move(task), 3, 4);
cout << "after thread creation\n";
...

https://godbolt.org/z/xhzKxh96K


text:
Q: Web Scraping, unable to scroll down web page using selenium web driver I am trying to extract all the links from a forum (https://www.pakwheels.com/forums/c/travel-n-tours)
My scraper class stops after scrolling down once.
from bs4 import BeautifulSoup

sourceUrl='https://www.pakwheels.com/forums/c/travel-n-tours'

#----------------------------------Source of below code:http://stackoverflow.com/questions/32391303/how-to-scroll-to-the-end-of-the-page-using-selenium-in-python--------------------#
#----------------------- Scrolling to the bottom of page ----------------------------- ----------#

from selenium import webdriver
import time
chrome_path=r"C:\Users\Shani\Desktop\chromedriver.exe"
driver=webdriver.Chrome(chrome_path)
driver.get(sourceUrl)
updatedLenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
scrollComplete=False
while(scrollComplete==False):
        currentLenOfPage = updatedLenOfPage
        updatedLenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
        print('Scrolling down')
        time.sleep(5)
        if currentLenOfPage==updatedLenOfPage:
            scrollComplete=True
time.sleep(10)
pageSource=driver.page_source

# ------------------------------------- Getting links ---------------------------------- #
soup = BeautifulSoup(pageSource, 'lxml')
# print(soup)

blogUrls=[]
for url in soup.find_all('a'):
    if((url.get('href').find('/forums/t/')!=-1) and (url.get('href').find('about-the-travel-n-tours-category')==-1) and (url.get('href').find('/forums/t/topic/')==-1)):
        blogUrls.append(url.get('href'))
        print(url.get('href'))
print(len(blogUrls))

It gives the following error
Traceback (most recent call last):
  File "D:\LiclipsWorkSpace\NLKTLib\Scraping\scrolling.py", line 32, in <module>
    if((url.get('href').find('/forums/t/')!=-1) and (url.get('href').find('about-the-travel-n-tours-category')==-1) and (url.get('href').find('/forums/t/topic/')==-1)):
AttributeError: 'NoneType' object has no attribute 'find'

Please help

A: You don't need Selenium, you can get all links from json response. This code gets urls from first 5 pages (for getting all pages simply change last 5 to 264).
import requests

for i in range(0, 5):
    r = requests.get(
        'https://www.pakwheels.com/forums/c/travel-n-tours/l/latest.json?page={}'.format(i)).json()
    topics = r['topic_list']['topics']
    for topic in topics:
        print ('https://www.pakwheels.com/forums/t/{}/{}'.format(topic['slug'], topic['id']))


text:
Q: Disply a Dialog box for user input in a Win 8 Store XAML app Is there a way to achieve the Dialog like effect in a Win 8 Store XAML app; similar to the one indicated in this post where the content of the dialog is a custom control to gather user input.
Here is some sample XAML content that I would like to display centered similar to the one indicated in the post above.
<common:LayoutAwarePage
x:Class="App1.UserControls.Control1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
>

<Grid HorizontalAlignment="Stretch" Background="Gold" VerticalAlignment="Center">
    <StackPanel  VerticalAlignment="Center" HorizontalAlignment="Center" AreScrollSnapPointsRegular="True" Margin="20">
        <TextBlock Text="This is sample text" FontSize="20" Style="{StaticResource HeaderTextStyle}"/>
        <Button Content="Close" Click="btnClose_Click" Margin="0,20,0,0" HorizontalAlignment="Right"/>
    </StackPanel>
</Grid></common:LayoutAwarePage>

I am using the Popup control to display this from a Main page like so:
<common:LayoutAwarepage>
<Grid Style="{StaticResource LayoutRootStyle}">
   <Popup x:Name="ParentedPopup" VerticalOffset="300" HorizontalOffset="200"
    HorizontalAlignment="Stretch">
            <usercontrols:CreateCategory/>
   </Popup>
 </Grid>
<Page.BottomAppBar>
    <AppBar x:Name="bottomAppBar" Padding="10,0,10,0">
        <Grid>
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
                <Button Style="{StaticResource AddAppBarButtonStyle}" Click="AddButton_Click"/>

            </StackPanel>
        </Grid>
    </AppBar>
</Page.BottomAppBar></common:LayoutAwarePage>

private void AddButton_Click(object sender, RoutedEventArgs e)
{
    if (!ParentedPopup.IsOpen) { ParentedPopup.IsOpen = true; }
}

However, this is not displaying as I intend it to, the popup does not show the xaml content centered, it shows up at the top and is not centered and stretched as I would like.
Is there a simple way to achieve this?
Note: I do not want to take dependencies on any libraries.

A: Why would you not want to take a dependency on any binaries if they solve your problem?  Take a look at Callisto which has a CustomDialog that will do this for you as shown in the documentation - https://github.com/timheuer/callisto/wiki/CustomDialog.  It is Open Source so you could also use the source.  But you are either way taking a dependency on someone's code answer to you or a binary :-)

A: assign the vertical offset to the height of the screen
popup.VerticalOffset = (Window.Current.Bounds.Height / 2) - popup.ActualHeight / 2;
Width = Window.Current.Bounds.Width;

VerticalAlignment="Center";

Also
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" x:Name="ContentColumn"/>
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>

//Place content in "ContentColumn" to center it
<Grid>

put the content in ContentColumn to center it.


text:
Q: How to show all the GraphicsLayoutWidget in srcollarea? In order to embed pyqtgraph's drawing into the UI, GraphicsLayoutWidget is used, and it is put into the QScrollArea, but QScrollArea cann't completely display the entire graph.
here is my code:
'''
from PySide2.QtWidgets import QApplication
from PySide2.QtUiTools import QUiLoader
import pyqtgraph as pg
from graph import Graph  # this is my worte class

class MyWin:
    def __init__(self):

        self.ui = QUiLoader().load('./UI/window2.ui')

        self.graph = pg.GraphicsLayoutWidget()

        self.plot_graph = Graph(self.graph)
        self.ui.graph_layout.addWidget(self.graph)
        self.plot_graph.set_fig(show_mode=1,row=8,col=8,channel=64,channel_mode=1)

if __name__ == '__main__':
    app = QApplication([])
    win = MyWin()
    win.ui.show()
    app.exec_()

'''
here is my result:
enter image description here
there is no srcollbar appearing, even when I zoom in on the entire window. what's happending?


text:
Q: Trying to figure out a spreadsheet equation to balance bills Basically I have a spreadsheet to show what has been paid by each member of a household on monthly bills, and I want it to show how much is owed to each other tenant, so that each has paid an equal share.
e.g. if tenant 1 pays $100, 2 pays $200 and 3 pays $300, tenant 1 would owe tenant 3 $100.

Any help will be greatly appreciated
Edit: I've since made this question a lot clearer. I'm sorry if it was a little sloppy before :(
Edit: I have tried (((C:2 + C:3 + C:4) / 3) - C:4) which shows how much more tenant 3 has to pay, but now I need to split that between tenants 1 and 2 so that they have each paid $132.67

A: I changed your layout slightly so I can copy the formula down.
I am using Excel but it Should work in Google Sheets:
=IF(SIGN(VLOOKUP(A7,A:C,3,FALSE)-AVERAGE($C$2:$C$4))=-1,MIN(MAX(VLOOKUP(B7,A:C,3,FALSE)-AVERAGE($C$2:$C$4),0),AVERAGE($C$2:$C$4)-VLOOKUP(A7,A:C,3,FALSE)),0)


text:
Q: Issues with fstack-protector? I want to detect stack overflow or corruption in my code. Hence, i wrote a small program where stack overflow is simulated. I compiled it using the command:
gcc overflow.c -g -fstack-protector-all

However, upon executing the binary i got segmentation fault but no other information.
Can anybody please help me where did i go wrong?

A: If ulimit -c is set to a value much bigger than zero, a core dump named core is written; you can see the backtrace via running gdb program core and then typing backtrace at the prompt.


text:
Q: TSQL increment value based on month(date) I have a query that selects the month (date) for dateadd(month, 3, getdate()). Sorry I'm writing this in pseudocode. It gets the month of the next 3 months. I need to assign another field to say month1, month2, month3 regardless of what the actual month value is.
Could someone please tell me a simple way to do this in SQL?

A: Your question is not entirely clear; but on the off chance I've understood correctly...
SELECT Month(DateAdd(month, 1, GetUtcDate())) AS month1
     , Month(DateAdd(month, 2, GetUtcDate())) AS month2
     , Month(DateAdd(month, 3, GetUtcDate())) AS month3
;

A: I ended up using a pivot query as follows:
select * from
  (
  SELECT
wl.partnumber
,isnull(sum(wl.QORDER),0) as qty_usage
,datename(month, ws.start_DATE)  AS MonthUsed
,month(ws.start_date) as MonthDate

from wo_hdr
join wo_line wl on wo_hdr.DOC_NO = wl.DOC_NO
join [WO_HDR_STATUS] ws on ws.PARENT_DOC_NO = wl.DOC_NO
join CUSTVEND c on c.acctno = wl.ACCTNO
 where 1=1

and wl.PARTNUMBER = @partnumber
and ws.START_DATE between dateadd(year,-2,getdate()) and dateadd(year, -2,dateadd(month,3.5, getdate()))
group by wl.partnumber, datename(month, ws.start_DATE) ,month(ws.start_date)

)
        DataTable PIVOT (avg(qty_usage) FOR
          [MonthUsed] IN ( [January], [February], [March], [April], [May], [June], [July], [August],
    [September], [October], [November], [December])) pivottable
Output results in gridview.


text:
Q: How do I apply RStudio themes only to the source and console backgrounds and not to the whole GUI? I'm using RStudio 1.1.383 and R 3.4.3 and I'm trying to apply a theme under Options > Appearance only to the background text area of the source pane and the console pane. This is exactly what happens when I apply a theme on my desktop computer (Win10), but when I apply a theme on my laptop (also Win10), it applies the theme to the entire GUI except for the top menu bar (i.e. File, Edit, Code, etc). The result looks jarring. Why might themes be behaving differently between my two computers which use identical setups? Is there an option that I might have selected somewhere on one and not the other that would cause the theme to apply to just the text area of a couple panes in one case and the entire GUI in the other?

A: This is a change in RStudio v1.1 -- now, when a 'dark' editor theme is selected, the entire IDE will be themed to match that.
If you'd prefer to have a dark editor theme with a light IDE theme, that's unfortunately not possible in v1.1. You might want to file a feature request at https://github.com/rstudio/rstudio/issues.


text:
Q: MAMP: How to upgrade PEAR When trying to upgrade MAMP pear the following error is raised:
Notice: unserialize(): Error at offset 276 of 1133 bytes in Config.php on line 1050
ERROR: The default config file is not a valid config file or is corrupted.

Some suggestions how to fix this?
Steps to reproduce:

*

*Installed MAMP (version 2.0.5)

*cd /Applications/MAMP/bin/php/php5.3.6/bin

*sudo ./pear upgrade pear

*above mentioned error is thrown

Update (1):
Based on answer 8375349/420953 I tried 2 possibilities to fix this

*

*A: delete pear.conf

*

*rm /Applications/MAMP/bin/php/php5.3.6/conf/pear.conf

*B: edit pear.conf

*

*change "php_dir";s:44 to "php_dir";s:43
both resulted in error:
Could not get contents of package "/Applications/MAMP/bin/php/php5.3.6/bin/pear". Invalid tgz file.
upgrade failed

Update (2):
running

*

*which pear

results in output

*

*/usr/local/bin/pear

With this, I noticed that I was using the "local" version of PEAR.
I removed it with

*

*sudo pear uninstall pear

and then tried to upgrade the MAMP version of PEAR with

*

*/Applications/MAMP/bin/php/php5.3.6/bin/pear upgrade pear

this results in error
Cannot install, php_dir for channel "pear.php.net" is not writeable by the current user

upgrading with

*

*sudo /Applications/MAMP/bin/php/php5.3.6/bin/pear upgrade pear

installs it locally (again).
running

*

*which pear

outputs

*

*/usr/local/bin/pear

this brings me back to the starting point of Update (2). Seems that I am not able to upgrade PEAR under a MAMP directory.
Update (3):
I posted question

*

*MAMP PEAR configuration is pointing to local directories
because my assumption is that the root of this issue is related to MAMP PEAR config.
Update (4):
I did not install a local PEAR version and this was causing quite some issues. After also installing a local version (and not only the MAMP) version, upgarding the MAMP version worked perfectly.

A: Edit the pear.conf: Adding a forward slash "/" to the end of the php_dir path, while keeping the s:44 solved the problem for me and a couple coworkers.

A: People with the your exact problem seem to has solved it in this MAMP forum thread.
You can either delete /Applications/MAMP/bin/php/php5.3.6/conf/pear.conf, or change a line in that file from "php_dir";s:44 to "php_dir";s:43.

A: I have XAMPP installed, and I just deleted /xampp/php/pear.ini and that solved the same problem

A: Just chipping in with a late response for others finding this answer. My PEAR config had several issues and not just the php_dir config setting.
I had to go over all of my settings to verify that the count was correct. When all errors where fixed my PEAR was working fine again.
Seeing this message in the terminal:
Notice: unserialize(): Error at offset 276 of 1133 bytes in Config.php on line 1050
ERROR: The default config file is not a valid config file or is corrupted.

*

*Go to your PEAR Config file (probably located here /MAMP/bin/php/php7.0.10/conf/pear.conf)

*Go to the 276th character in that file and verify that the string length matches the s43 that's defined before the string.

*Run a PEAR command again (e.g. pear version)

*If you have more errors located at e.g. 317th character you count that string and write the length in the s:XX before the string.

Just for clarifying for others finding this issue. The PEAR Config file is a serialized object that is unserialized when running commands.
A serialized object looks like s:5:"value" with the s:5 defining the length the string.


text:
Q: Git Bash for windows not working properly I am having a very annoying issue with git bash for windows.
When first lauching git bash, everything works fine, but after I type in node -v to check the nodejs version, nothing is returned and every subsequent text I type in is not displayed (although when pressing enter these commands' outputs get displayed).
In the image below I ran the commands in this order:
- node -v (no output)
- npm -v (no input displayed)
- git --version (no input displayed)
Image showing the problem
Everything started with a SIGFAULT error when running any node or npm command. After unninstalling git for windows and installing again, it is working like this.
But, when I use the bash as a attached terminal for vscode, I get these errors in every command I run:
Attached terminal throwing Segmentation fault error
How can I solve it?


text: Q: How can I get tracking number in default fedex in magento 1.7.0.2 I have setup default magento fedex shipping method. It's working fine. But I am not getting tracking number and shipment. Can anyone suggest me how can I get those things?


text:
Q: End a conversation c# bot I'm building a ChatBot in C# and I want that after some messages the conversation stop, but I don't know how to do it. I have already set a limit of messages, and I want that after the reach of this limit no more messages can be send. There is my code:
private int NombreDeMessages;

protected override async Task MessageReceived(IDialogContext context, IAwaitable<IMessageActivity> item)
{
    var message = await item;
    NombreDeMessages += 1;

    if (message.Text != null && NombreDeMessages < 3)
    {
         await base.MessageReceived(context, item);
    }
    else
    {
         var reply = context.MakeMessage();
         await context.PostAsync(reply);
         context.Wait(this.MessageReceived);
    }
}

I deleted the HeroCard part because it is useless here.
The thing that I want is after the context.Wait at the end, add a end of conversation so the user can't talk more to the chatbot.

A: Thank you I have solved my problem. I post the code if it can help someone !
private int NombreDeMessages;
        protected override async Task MessageReceived(IDialogContext context, IAwaitable<IMessageActivity> item)
        {
            var message = await item;
            NombreDeMessages += 1;
            string code = EndOfConversationCodes.CompletedSuccessfully;
            CancellationToken cancellationToken = default(CancellationToken);

            if (message.Text != null && NombreDeMessages < 3)
            {
                await base.MessageReceived(context, item);

            }
            else if (message.Text != null && NombreDeMessages == 3)
            {
                AdaptiveCard card = new AdaptiveCard();
                card.Body.Add(new TextBlock()
                {
                    Text = "STOP FLOODING",
                    Weight = TextWeight.Bolder,
                    IsSubtle = true,
                    Wrap = true,
                    Size = TextSize.Large
                });

                card.Body.Add(new TextBlock()
                {
                    Text = "You have reach the limit of queries",
                    IsSubtle = false,
                    Wrap = true,
                    Size = TextSize.Normal
                });

                card.Body.Add(new Image()
                {
                    Url = "http://images.roadtrafficsigns.com/img/dp/lg/traffic-stop-sign.png",

                    HorizontalAlignment = HorizontalAlignment.Center,
                    Size = ImageSize.Stretch
                });

                Attachment attachment = new Attachment()
                {
                    ContentType = AdaptiveCard.ContentType,
                    Content = card
                };
                var flood = context.MakeMessage();
                flood.Attachments.Add(attachment);

                await context.PostAsync(flood);

            }
            else
            {

                var reply = context.MakeMessage();

                reply.Type = ActivityTypes.EndOfConversation;
                reply.AsEndOfConversationActivity().Code = code;

                await context.PostAsync(reply, cancellationToken);

            }

        }

A: Your question is a little ambiguous,What do you mean by end conversation do you want the user to never be able to talk to the chatbot again?  One thing you can do in the else block you have you can call context.Done() and remove your  context.Wait(this.MessageReceived)  that would allow your user to send messages but get no response, or in the case below let the user know the conversation has ended.
else
{

    var reply = context.MakeMessage();
    reply.Text = "conversation ended";
    await context.PostAsync(reply);
    context.Done(this);
}


text:
Q: Git remote branches are wrongly listed twice If I do a git branch -a, I get my local branches listed correctly, but my remote branches are listed double... e.g.
master
remotes/github/master
remotes/origin/master

I think the reason for this is that I started out with a remote called github mapped to my github repository URL and then later changed its name to origin, still keeping the same URL.
If I do a git remote -v, I get the correct single name/url listing:
origin  git@github.com:username/Repo.git (fetch)
origin  git@github.com:username/Repo.git (push)

I tried removing the remote URL completely in the config file so that git remote would return nothing, but git branch -a still returned those doubled remote branches.
How do I get rid of this double listing?

A: try
git branch -d -r remotes/github/master


text:
Q: Angular Material - Triggering Table Data Refresh I have a angular-material table with the datasource coming from a variable array
The array can have elements pushed to by the onscreen form. This works fine, and the element is pushed and to ensure it I print out the entire datasource and my the new object is reflected there.
Here is that code:
reportFields = [{name: "name_test", filter: "filter_test" }];
 addReportField(){
        this.reportFields.push({
            name: this.fieldToAdd.name,
            filter: this.fieldToAdd.filter
        });
        this.frmField.reset();
        this.changeDetectorRefs.detectChanges();
        console.log(this.reportFields);
    }

reportFields is the datasource, and when the page load the table loads with that data inside. But when I add one during run time, using the addReportField method, the datasource doesn't reload.
I tried using that ChangeDectectorRef and then detect changes but that didn't work.
Here is the HTML for the table
<mat-table [dataSource]="reportFields" style="background: inherit;">
            <ng-container matColumnDef="field">
                <mat-header-cell *matHeaderCellDef>Field Name</mat-header-cell>
                <mat-cell *matCellDef="let element">{{element.name}}</mat-cell>
            </ng-container>

            <ng-container matColumnDef="filter">
                <mat-header-cell style="margin-right: 20px;" *matHeaderCellDef>Filter</mat-header-cell>
                <mat-cell style="margin-right: 20px;" *matCellDef="let element">
                    {{element.filter}}
                </mat-cell>
            </ng-container>

            <ng-container matColumnDef="delete">
                <mat-header-cell style="text-align: end;" *matHeaderCellDef></mat-header-cell>
                <mat-cell *matCellDef="let element" style="text-align: end;">
                    <mat-icon (click)="deleteReturn(element.id, 'standard')" style="font-size: 24px; cursor: pointer;" matTooltip="Delete">clear</mat-icon>
                </mat-cell>
            </ng-container>

            <mat-header-row *matHeaderRowDef="reportFieldsColumns"></mat-header-row>
            <mat-row *matRowDef="let row; columns: reportFieldsColumns;"></mat-row>
        </mat-table>

A: The table doesn't detect dynamic changes at runtime, you have to refresh the table yourself.
Have a look at this example. You can see that after pushing a new element to the array, I have to reset the dataSource manually.


text:
Q: Azure App Configuration, Key Vault and client certificate credentials I am currently working on a few services that uses keyvault, authenticating with ClientCertificateCredential / Registered Apps. These are running on-premise.
Looking into using Azure App Configuration in a similar way, combined with keyvault. So a couple of questions arises:

*

*Can i authorize against App Configuration the same way as with KeyVault, using ClientCertificateCredential ? If yes, how ?

*If not, another option is to use a connection string against App Config. However, this is a secret, and should be stored in keyvault (absolutely not in appsettings.json). That means I have to access keyvault before setting up App Config. Is there a clean way to do this ?
Or, perhaps there is something else I should consider.

A: •   Yes, you can surely authorize against App configuration as you do against key vault to retrieve client secrets, connection strings and other sensitive information with the help of managed identities. Managed identities create a service principal for the said application when enabled depending on the user to be assigned to that application or directly to the application itself as a system assigned managed identity that is created for the lifetime of that application.
By leveraging managed identity, it eliminates the need for an access token that contains secrets. Your code can access the App Configuration store using only the service endpoint. You can embed this URL in your code directly without exposing any secret.
•   For more information on configuring managed identity to access the application configuration without exposing or leveraging any type of access token, please refer to the documentation link below for more details: -
https://learn.microsoft.com/en-us/azure/azure-app-configuration/howto-integrate-azure-managed-service-identity?tabs=core5x


text:
Q: Cron job in Google app engine with spring boot There are answers on how to schedule tasks on Spring Boot
There are also links on how to create a Cron Job in App Engine
I am using Spring Boot for Google App Engine, so how can I have Cron jobs using Spring Boot?

A: The cron service in GAE is simply a scheduler for GET requests to certain URLs handled by the application. From the very cron documentation reference you posted:

A cron job will invoke a URL, using an HTTP GET request, at a given
  time of day.

So all you have to do is:

*

*Configure the schedule of the jobs and the URLs to be invoked

*Add handlers for those URLs into your app code to perform the necessary actions for the jobs

You can also validate that the GET requests for those URLs are only coming from App Engine.


text:
Q: SQL - SELECT - FOREIGN KEY VISITSEXIT              VISITSENTRY               VISITOR
idvisitsexit            idvisitsentry             idvisitor
idvisitsentry           idvisitante               visitor
idvisitor               visitor
visitor
dateexit
timeexit

I need to select the table VISITSEXIT where when she bring the VISITSENTRY also will bring idvisitor and description of idvisitor (visitor).

A: A simple straightforward JOIN will give you what you want:
SELECT
  t.idvisitor,
  t.visitor,
  t.dateexit,
  t.timeext,
  ... -- the rest of the columns you want to select
FROM VISITSEXIT       AS t
INNER JOIN VisitEntry AS e ON t.idvisitentry = e.visitentry
INNER JOIN Visitor    AS v ON e.idvisitante  = v.idvisitor;

You might also need to use LEFT JOIN if you want to include those unmatched rows from the other tables. See this post for more information about the JOIN types:

*

*A Visual Explanation of SQL Joins


text:
Q: Django serializer not raising exception over model constraints I have this dummy model
from django.db import models
class ChertModel(models.Model):
    username = models.CharField(gettext_lazy('username'), max_length=150, unique=True)
    o2 = models.CharField(gettext_lazy('username2'), max_length=150,editable=False, default='lllss')

and with serializer
class ChertSer(serializers.ModelSerializer):
    class Meta:
        model = ChertModel
        fields = ['username','o2']

note I have an instance with username='sd' and o2='434as'
so when in the view I want to update the o2 fields which is supposedly editable=False it doesnt update it which is ok but the problem is that it doesnt raise exception over model constraints.
note I have checked this configuration with editable=True and the serializer applies changes thus there is no problem with serializer.
class ChertView(views.APIView):
    def get(self, request):
        lt1=ChertModel.objects.get(username='sd')
        print('1',lt1.o2)
        ser=ChertSer(instance=lt1, data={'username':'sd','o2':'newo2'}, partial=True)
        print(ser.is_valid())
        ser.is_valid(raise_exception=True)
        ser.save()
        lt1=ChertModel.objects.get(username='sd')
        print('2',lt1.o2)

since it shows the serializer.is_valid True and wont raise exception would make problem of changes of user not applied to model instance without acknowledging it to user.
so my question is how to detect the times the updating object is not applied due to model constraints?
of course I can manually detect it by checking ser.data=={'username':'sd','o2':'newo2'} but ser.data is only can be achieved after saving the instance and not before it. besides this way doesnt specify the constraint which is not applied. the equivalent is to manually check for all attributes which is not agreeable when we are using a framework.
so is there any more formal or common way to automatically detect constraints not being applied before saving the instance?

A: If False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True.
The validation on perticuler field is skipped by default, what you can do is overwrite the validation function in serializer and raise exception from their.

A: When editable=False is specified. The field won't be shown in admin or any other ModelForms, they are also skipped during validation.
You can specify read_only_fields at the serializer level.
class ChertSer(serializers.ModelSerializer):
    class Meta:
        model = ChertModel
        fields = ['username','o2']
        read_only_fields = ('o2',)

If there are multiple serializers for this model and you dont want to dupilicate adding these. You can define read only fields at an AbstractSerializer and inherit it over serializer.


text:
Q: Why and how does node.js cast objects assigned to process.env to strings? So, while working on my application, I tried assigned my config as an environment variables by creating a property config in the process.env.
However, while using it, I found out that node.js casts objects to string when assigned to process.env.
Here is a sample code to demonstrate this:
const config = {
    port: 3000,
    url: 'url'
}

process.env.config = config;

console.log(process.env.config) // prints '[object Object]'
console.log(typeof process.env.config) // prints 'string'

Is there any specific reason this happens?
Also, assuming process.env is an object passed to my application when it starts, HOW is this casting achieved?

A: From 8.9.4 API docs

Assigning a property on process.env will implicitly convert the value to a string.

const config = { x : 1 };
const otherconfig = 1;

console.log(typeof config); // object
console.log(typeof otherconfig); // number

process.env.config = config;
console.log(process.env.config); // [object Object]
console.log(typeof process.env.config); // string

process.env.otherconfig = otherconfig;
console.log(process.env.otherconfig); // 1
console.log(typeof process.env.otherconfig); // string

Why is casted as string ?

The process.env property returns an object containing the user environment. See environ(7).

and looking at environ.

The variable environ points to an array of pointers to strings called
         the "environment".

So yeah its pretty low level its casted back and forth, because the process is an global variable and its always stored as string.
Just try to avoid defining environment variables this way its easier and less difficult to debug when the variables have been already defined or use dotenv to make it a lot easier to define different configurations.

A: The values in process.env typically come from the execution environment. So in a UNIX shell, you can issue a command like MY_TEST_VALUE=abc123 node index.js and in your index.js you will have access to a value process.env.MY_TEST_VALUE. Hence, everything in process.env is stored as strings.
That being said, you could always store a stringified JSON value in process.env:
process.env.CONFIG = JSON.stringify(config)
// and parse it when consuming
parsedConfig = JSON.parse(process.env.CONFIG)


text:
Q: Android Studio не читает аннотации Я хочу сделать Веб-сервис. На ПК запускается сам сервис, а андроид телефон используется как клиент В Intellij IDEA все работает, в Android Studio ругается на аннотации:WebService, SOAPBinding, WebMethod.
Вот код:
    import javax.jws.WebService;

@WebService(endpointInterface = "com.example.maxim.project_r.mWebService")
public class WebServiceImpl implements mWebService {
    @Override
    public String getHelloString(String name) {
        return "Hello, " + name + "!";
    }
}

import android.app.Service;

import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.namespace.QName;

public class WebServiceClient {
    public static void connect_ws() throws MalformedURLException {
        try{
            URL url = new URL("http://192.168.0.90:1986/wss/hello?wsdl");

            QName qname = new QName("http://ws.mnolimp.ru/", "WebServiceImplService");

            Service service = Service.create(url, qname);
            mWebService hello = service.getPort(mWebService.class);

            System.out.println(hello.getHelloString("Service"));
        }catch (WebServiceException e){
            System.out.println("Web Service not available");
        }
    }
}

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface mWebService {
    @WebMethod
    public String getHelloString(String name);
}

Помогите пожалуйста, я новичок в Андроид и Веб технологиях


text:
Q: Floated Tableless Layout Can anyone tell me how to execute this layout with floats and clears? Ive been trying for 2 days with total failure

A: Should be pretty simple, it's a basic 2 column layout with a header.
Something like this should work fine:

1

2

3

4

5

6

And some basic CSS
#column1, #column2{
width:45%;
float:left;
}

I've put a quick example here: http://jsfiddle.net/9DfRg/

A: of course there are many solutions. One could be the following:
html

One

Two

Three

Four

Five

Six

css
#wrapper {
    width:960px;
}
#one {
    width:100%;
    height:100px;
    background:#0C9;
}
#two, #three, #four, #five, #six {
    width:480px;
}
#two, #four, #six {
    float:left;
    height:100px;
}
#three, #five {
    float:right;
}
#three {
    height:200px;
}
#five {
    height:150px;
}
#two {
    background:#06F;
}
#three {
    background:#093;
}
#four {
    background:#699;
}
#five {
    background:#F06;
}
#six {
    background:#666;
}

live example: http://jsbin.com/iquyu5


text:
Q: Replace one column in matrix by > 1 columns How to easily replace a (N x 1) vector/column of a (N x M) matrix by a (N x K) matrix such that the result is a (N x (M - 1 + K)) matrix?
Example:
a <- matrix(c(1, 3, 4, 5), nrow = 2) # (2 x 2)
b <- matrix(c(1, 3, 5, 6, 7, 7), nrow = 2) # (2 x 3)

I now want to do something like this:
a[, 1, drop = FALSE] <- b # Error

which R does not like.
All I could think of is a two-step approach: attach b to a and subsequently delete column 1. Problem: it mixes the order the columns appear.
Basically, I want to have a simple drop in replacement. I am sure it is possible somehow.

A: You can use cbind:
cbind(b, a[,-1])
#     [,1] [,2] [,3] [,4]
#[1,]    1    5    7    4
#[2,]    3    6    7    5

If you need to insert in the middle of a large matrix (say, at column N), rather than one end you can use,
cbind(a[, 1:(N-1)], b, a[, (N+1):NCOL(a)])

For a generalized version that works wherever the insert is (start, middle or end) we can use
a <- matrix(1:10, nrow = 2)
b <- matrix(c(100, 100, 100, 100, 100, 100), nrow = 2)

N <- 6 # where we want to insert
NMAX <- NCOL(a) # the largest column where we can insert

cbind(a[, 0:(N-1)], b, {if(N<NMAX) a[,(N+1):NMAX] else NULL})


text:
Q: How to add an OnTouchListener over a gridView? So I have a layout that is made of GridView and I want to add an OnTouchListener to handle the event when the user swipes left or right, so I made a class that implements OnTouchListener it's called OnSwipeTouchListener and it's working really good but the problem is my gridView, the scroll is working fine and everything but when I click on an item it automatically chooses the first item in the row. any idea on how to fix this or another way to detect a left or right swipe and makes the gridview work fine, thanks.
P.S: the gridView works fine when I remove the onTouchListener.
The OnSwipeTouchListner:
public class OnSwipeTouchListener implements OnTouchListener {

private final GestureDetector gestureDetector;

public OnSwipeTouchListener(Context context) {
    gestureDetector = new GestureDetector(context, new GestureListener());
}

public void onSwipeLeft() {
}

public void onSwipeRight() {
}

public boolean onTouch(View v, MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
}

private final class GestureListener extends SimpleOnGestureListener {

    private static final int SWIPE_DISTANCE_THRESHOLD = 100;
    private static final int SWIPE_VELOCITY_THRESHOLD = 100;

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        float distanceX = e2.getX() - e1.getX();
        float distanceY = e2.getY() - e1.getY();
        if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
            if (distanceX > 0)
                onSwipeRight();
            else
                onSwipeLeft();
            return true;
        }
        return false;
    }
}
}

calling it in the main activity:
gridView.setOnTouchListener(new OnSwipeTouchListener(this){
        public void onSwipeRight() {
        }
        public void onSwipeLeft() {
            }
    });

A: Try using setOnItemClickListener
gridView.setOnItemClickListener(

new OnItemClickListener(){
    public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {

    }
});
);