text:
Q: android - setOnItemClickListener is not working I try using setOnItemClickListener on my GridView with some Buttons but it doesn't work.
This is my CustomGrid adapter:

package com.example.omar.soundboard;
/**
 * Created by Omar on 10/02/2015.
 */
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;

import java.util.ArrayList;

public class CustomGrid extends BaseAdapter
{
    private Context mContext;
    private ArrayList<String> arr;

    public CustomGrid(Context c, ArrayList<String> arr)
    {
        mContext = c;
        this.arr = arr;
    }

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

    @Override
    public Object getItem(int position)
    {
        return arr.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View grid;
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
        {
            grid = new View(mContext);
            grid = inflater.inflate(R.layout.grid_single, null);
            Button btn = (Button) grid.findViewById(R.id.button);
            btn.setLayoutParams(new RelativeLayout.LayoutParams(100,75));
            btn.setPadding(1,1,1,1);
            btn.setText(arr.get(position));
        }
        else
        {
            grid = (View) convertView;
        }
        return grid;
    }
}

This is the grid_single.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Prova"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

This is the activity code:
package com.example.omar.soundboard;

    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.Button;
    import android.widget.GridView;
    import android.widget.Toast;

    import java.util.ArrayList;

    public class MainActivity extends ActionBarActivity {

        private GridView grid;
        private ArrayList<String> nomi;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            nomi = new ArrayList<String>();
            nomi.add("Cosimo");
            nomi.add("Angela");
            nomi.add("Prova");
            nomi.add("Prova2");
            final CustomGrid adapter = new CustomGrid(this, nomi);
            grid = (GridView)findViewById(R.id.gridSound);
            grid.setAdapter(adapter);
            grid.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(MainActivity.this, "Test", Toast.LENGTH_LONG).show();
                }
            });
        }

This is the activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="0dp"
    android:paddingRight="0dp"
    android:paddingTop="0dp"
    android:paddingBottom="0dp" tools:context=".MainActivity">

    <GridView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/gridSound"
        android:numColumns="3"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

I'm testing it on Android 2.3.3, the buttons are displayed but when I press on one of them nothing happens!
Can someone help me? I can't figure out what's the problem.


text:
Q: Extract text between two characters (multiline input) If I have the text:
aaaaaaaaa
#some info
other rows
end row#
another info

How could I extract only the text between the characters # obtaining only:
some info
other rows
end row

I was trying with sed in this way:
echo -e "aaaaaaaaa\n#some info\nother rows\nend row#\nanother info" |
sed -n -e '/\#/,/\#/p'

but it gives me also the character #. Is there a way to remove # using sed?

A: You can use perl:
echo -e "aaaaaaaaa\n#some info\nother rows\nend row#\nanother info" |\
perl -0777 -ne '/#([^#]*)#/ && print $1,"\n"; '

Explanation:

*

*-0777 slurp the whole file as one line (enables multiline matching)

*/#([^#]*)#/ match non-# characters [^#] between too # and with the brackets add it as first matching group.

*&& print $1,"\n" if found, print first matching group and a final newline.

A: Slight adaption to your sed one liner:
echo -e "aaaaaaaaa\n#some info\nother rows\nend row#\nanother info" |
sed -n '/^#/,/#$/ {s/#//;p;}'

Output:
some info
other rows
end row

redpajama_set_name: RedPajamaStackExchange


text:
Q: How create a base64 string from a canvas Windows Phone 8.1(Universal app) I have an application capturing a signature, I already drawing the signature now I want to capture the information and create a base64 string.

A: Sorry here is the code that worked for me, is not perfect. Feel free to review and if you find anything please provide feedback. Thanks
In this example the canvas name is Display
    private async Task<string> generateBase64Bitmap()
    {
        // Initialization

        try
        {
            // Initialization.
            Size canvasSize = this.Display.RenderSize;
            Point defaultPoint = this.Display.RenderTransformOrigin;
            // Sezing to output image dimension.
            this.Display.Measure(canvasSize);
            this.Display.UpdateLayout();
            this.Display.Arrange(new Rect(defaultPoint, canvasSize));
            // Convert canvas to bmp.
            var bmp = new RenderTargetBitmap();
            await bmp.RenderAsync(this.Display, (int)(this.Display.ActualWidth / 4), (int)(this.Display.ActualHeight / 4));
            // Setting.
            var bitmap = (RenderTargetBitmap) bmp;

            //var bytes = (await bitmap.GetPixelsAsync()).ToArray();
            return await toBase64(bitmap);

        }
        catch (Exception ex)
        {
            //this.ShowMessage(ex.ToString(), "Error");
        }
        return string.Empty;
    }

    private async Task<string> toBase64(RenderTargetBitmap bmp)
    {
        var img = (await bmp.GetPixelsAsync()).ToArray();

        var encoded = new InMemoryRandomAccessStream();
        var encoder = await BitmapEncoder.CreateAsync(
            BitmapEncoder.PngEncoderId, encoded);
        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight,
            (uint)bmp.PixelWidth, (uint)bmp.PixelHeight, 96, 96, img);
        await encoder.FlushAsync();
        encoded.Seek(0);

        //read bytes
        var bytes = new byte[encoded.Size];
        await encoded.AsStream().ReadAsync(bytes, 0, bytes.Length);

        return Convert.ToBase64String(bytes);
    }

To call the method use(add async to your method):
string encodedImgBase64 = await generateBase64Bitmap();


text:
Q: Cucumber Extent Report - Capture screenshot and add exception log I had tried to search on internet about capture screenshot and add exception to extent report when fail but not could understand.
What is the difference between spark and html report?
Hope someone can provide example code. Thanks.

A: If you are using cucumber with protractor, you can attach screenshot on failed scenario step you can use it like this
import { browser } from 'protractor';
import { After } from 'cucumber';

After(async function (scenario) {
    if (scenario.result.status === Status.FAILED) {
        const screenshot = await browser.takeScreenshot();
        this.attach(screenshot, "image/png");
    }
});


text:
Q: Create websocket connection from requests session in python I need to receive data from a website over a websocket connection. Access to the websocket is only given after logging into the website. Using a session in python requests I am able to post my login information to the login page and authenticate my details. Websocket-client would be used for the creating the websocket connection to the website however the websocket connection created would not be through the login session.
How can I create a websocket connection after logging in through requests?
I found a similiar question here but it has not been answered
Python - Websockets Unable to validate my session
This is my code so far (simplified a bit).
import requests
from bs4 import BeautifulSoup
import base64
import random
import websocket

headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'}

payload = {
    'username': 'username',
    'password': 'password'}

session = requests.Session()

r = session.get("https://www.example.com/login", headers=headers)

soup = BeautifulSoup(r.content, 'html.parser')
payload['token'] = soup.find('input', attrs={'name': 'token'})['value']

r = session.post("https://www.example.com/login", data=payload, headers=headers)
r = session.get("https://www.example.com/", headers=headers)

headers['Sec-WebSocket-Key'] = str(base64.b64encode(bytes([random.randint(0, 255) for _ in range(16)])), 'ascii')
headers['Sec-WebSocket-Version'] = '13'
headers['Upgrade'] = 'websocket'

ws = websocket.WebSocketApp('wss://www.example.com/streaming/',
                            header=headers,
                            #session=session????)
ws.run_forever()

A: After much searching I eventually found the source of the problem. I was using Chrome Dev Tools to view the network packets when accessing the website through chrome browser, however Chrome Dev Tools does not show cookies for a websocket request. Firefox Developer Tools does show the cookies for a websocket request and I only discovered what cookies were being sent when I used Firefox.
The solution is to extract the cookies for the Requests Session, and pass these cookies to the WebSocketApp. That way the websocket server can verify you are logged in.
cookies = session.cookies.get_dict()
ws = websocket.WebSocketApp('wss://www.example.com/streaming/',
                        header=headers,
                        cookie="; ".join(["%s=%s" %(i, j) for i, j in cookies.items()]))


text:
Q: Prove that for every x > Z > 0 f(x) < 9.5 It is known that for some $f(x)$, $$ \lim_{x\to \infty} f(x) = -10 $$

Prove that  $\exists Z > 0$ such that for $ x > Z , f(x) < -9.5 $
I'd love to hear your suggestions on how I should do this, I'm really new to calculus
and I don't really have a clue how to prove this..
Can someone show me the process of solving this?
Thanks a lot guys!

A: By definition $\lim_{x\rightarrow\infty}f\left(x\right)=-10$ if for
every $\epsilon>0$ some $Z_{\epsilon}\in\mathbb R$ can be found such that $x>Z_{\epsilon}\Rightarrow\left|f\left(x\right)-(-10)\right|<\epsilon$.
So if $\epsilon\leq0.5$ then $x>Z_{\epsilon}\Rightarrow f\left(x\right)<-9.5$
We can take e.g. $\epsilon=0.4$. Then $x>Z_{0.4}\Rightarrow f\left(x\right)<-9.5$
Now choose some positive $Z$ that is not smaller than $Z_{0.4}$.


text:
Q: Positive Lookbehind with commas separated list I am a Java developer and I am new to Regex, I have similar problem as here in Stackoverflow . I have 2 issues,

*

*SKIP does not work in Java

*I started following the second approach as per this Regex link but my use case is as below,

if I have a string like,
It is very nice in summer and in summer time we swim, run, tan

It should extract based on Positive lookbehind, "summer time we", it should extract, [smim, run, tan] as an array.
I am stuck here, please help.

A: In Java, a regex cannot by itself return an array.
But, this regex will return the values you want using a find() loop:
(?<=summer time we |\G(?<!^), )\w+

It is almost identical to the second answer that you referred to.
In Java 9+, you can create array like this:
String s = "It is very nice in summer and in summer time we swim, run, tan";
String[] results = Pattern.compile("(?<=summer time we |\\G(?<!^), )\\w+")
                          .matcher(s).results().map(MatchResult::group)
                          .toArray(i -> new String[i]);
System.out.println(Arrays.toString(results));

Output
[swim, run, tan]

In Java 5+, you can do it with a find() loop:
String s = "It is very nice in summer and in summer time we swim, run, tan";
List<String> resultList = new ArrayList<String>();
Pattern regex = Pattern.compile("(?<=summer time we |\\G(?<!^), )\\w+");
for (Matcher m = regex.matcher(s); m.find(); )
    resultList.add(m.group());
String[] results = resultList.toArray(new String[resultList.size()]);
System.out.println(Arrays.toString(results));


text:
Q: CSS Transition property not working I'm having a problem with the css transition property, can anyone help me out?
HTML:

HOVER ME

aaa

         aaa

        aaa

        aaa

CSS:
.slide {
    height: 0px;
    visibility: hidden;
    width:100px;
    background-color: blue;
    -webkit-transition: height 2s ease;
    transition: height 2s ease;
}

div:hover > .slide {
    height: auto;
    visibility: visible;
}

Codepen: http://codepen.io/anon/pen/VLEGYr

A: Like stated, it won't work with display property. Furthermore, animation with height: auto won't work too. A display less and height:auto less version below.
.slide {
  max-height: 0;
  transition: max-height 0.2s;
  overflow: hidden;
  background-color: blue;
}

*:hover > .slide {
  max-height: 500px;
  transition: max-height 0.2s;
}

A: Try this :

.slide {

  max-height: 0;
  width:100px;
  background-color: white;
  -webkit-transition: all 2s ease;
  transition: all 2s ease;
}

div:hover > .slide {
  max-height: 200px;
  background-color: blue;
}

HOVER ME

aaa

  aaa

  aaa

  aaa

http://jsfiddle.net/bqef5kpm/1/


text:
Q: How to create a game board on Python I want to recreate Game Fifteen in Python, but I'm stuck on drawing a board in two dimensions. I did this before in C and I tried using lists again like the following:
numbers = d * d - 1
global blankx, blanky, board
blankx = d - 1
blanky = d - 1

for i in range(d):
    for j in range(d):
        board[i][j] = numbers
        numbers -= 1
board[blankx][blanky] = d * d

Where d is the dimension, blankx and y are the coordinates for the blank space in the bottom right corner. It says however:
'list index out of range' on line board[i][j] = numbers
I don't get why though, any tips?

A: In Python, accessing an index of a list does not automatically extend the list to the minimum requisite length. You will have to either initialize an empty board, or create and populate it together. I'd recommend a list comprehension:
board = [[d*d-1-i-d*j for i in range(d)] for j in range(d)]

This is equivalent to the following explicit loop, which adds new items to each list with append():
board = []
for i in range(d):
    row = []
    for j in range(d):
        row.append(d*d-1-i-d*j)
    board.append(row)

A: board = [[i*d + j + 1 for i in range(d)] for j in range(d)]
board[blankx][blanky] = d * d


text:
Q: Change docker storage driver on Mac OS X I installed the docker toolbox on my Mac OS X and I need to change the docker storage driver from aufs to devicemapper, because aufs causing problems.
I found the offical documentations of docker and tried it the way explained here, but DOCKER_OPTS="--storage-driver=devicemapper" doesn't work for me.
docker info still tells me Storage Driver: aufs.
I didn't managed to find the file located at /etc/default/docker as well.
For the record, I need to changed it in order to run CodeClimate CLI properly.

A: You can use the --engine-storage-driver flag when you create a new VM with docker-machine to choose a storage driver.
$ docker-machine create -d virtualbox \
    --engine-storage-driver devicemapper \
    foobarmachine

docs reference

A:
Modifying the storage-driver is not supported on Docker Desktop for Mac and Docker Desktop for Windows, and only the default storage driver can be used.

Docker documentation


text:
Q: Create React Native App ScrollView Example Errors I created CRNA app following CreateNative GetStarted steps by issuing in terminal
npm install -g create-react-native-app

This creates app AwesomeProject and inside is App.js file which is the app.  I replace the content of this file with the content of the demo on how to use ScrollView that is located at http://facebook.github.io/react-native/docs/using-a-scrollview.html
Here is the code I copied from the link above
import React, { Component } from 'react';
import { AppRegistry, ScrollView, Image, Text } from 'react-native';

export default class IScrolledDownAndWhatHappenedNextShockedMe extends Component {
  render() {
      return (
        <ScrollView>
          <Text style={{fontSize:96}}>Scroll me plz</Text>
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Text style={{fontSize:96}}>If you like</Text>
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Text style={{fontSize:96}}>Scrolling down</Text>
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Text style={{fontSize:96}}>What's the best</Text>
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Text style={{fontSize:96}}>Framework around?</Text>
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Text style={{fontSize:80}}>React Native</Text>
        </ScrollView>
    );
  }
}

// skip these lines if using Create React Native App
AppRegistry.registerComponent(
  'AwesomeProject',
  () => IScrolledDownAndWhatHappenedNextShockedMe);

However, this shows error at the terminal like below and on device it shows that the module ./img/favicon.png is unknown.  I tried adding img directory and favicon.png file in it to the root of AwesomeProject as well as inside the node_modules but the error still exists.

Please note that I just started learning about ReactNative yesterday and I am going through examples one by one but this ScrollView example is failing.  Please kindly provide clear explanation how to resolve this.
The terminal shows "10:13:14 PM: Failed building JavaScript bundle" as soon as CRNA app starts.

A: You need to add the img directory with the favicon.png relative to the file that specifies the requirement.
Lets assume you have a src/index.js with a line like import favicon from './img/favicon.png' or const icon = require('./img/favicon.png'), then your file needs to be at src/img/favicon.png.

A:
Just Try this if it worked then you don't have img folder where the
  image name of favicon.png. if it works then change this image url to
  local image url. That should works.

import React, { Component } from 'react';
import { ScrollView, Image, Text } from 'react-native';

export default class IScrolledDownAndWhatHappenedNextShockedMe extends Component {
  render() {
      return (
        <ScrollView>
          <Text style={{fontSize:96}}>Scroll me plz</Text>
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Text style={{fontSize:96}}>If you like</Text>
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Text style={{fontSize:96}}>Scrolling down</Text>
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Text style={{fontSize:96}}>What's the best</Text>
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Text style={{fontSize:96}}>Framework around?</Text>
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Image source={'https://pbs.twimg.com/profile_images/763061332702736385/KoK6gHzp.jpg'} />
          <Text style={{fontSize:80}}>React Native</Text>
        </ScrollView>
    );
  }
}


text:
Q: Why can push mp4 into a rtmp stream instead of rtsp stream? I build stream server with nginx, and can push the MP4 into a rtmp stream with :
ffmpeg -re -i /mnt/hls/m7.mp4  -vcodec libx264 -vprofile baseline -g 30 -acodec aac -strict -2 -f flv rtmp://127.0.0.1/live

Now I want to push it with rtsp format:
ffmpeg -re  -i /mnt/hls/m7.mp4  -f rtsp -rtsp_transport tcp rtsp://127.0.0.1/live

Error info encountered:
[tcp @ 0x55c7d6a157c0] Connection to tcp://127.0.0.1:554?timeout=0 failed: Connection refused
Could not write header for output file #0 (incorrect codec parameters ?): Connection refused
Error initializing output stream 0:0 --
[aac @ 0x55c7d65b6500] Qavg: nan
[aac @ 0x55c7d65b6500] 1 frames left in the queue on closing
Conversion failed!

A: It is not that seems that you remove or missing the correct encoding value.
No rtsp server build on my vps,only rtmp server ebedded in nginx on my vps.
url="https://github.com/aler9/rtsp-simple-server/releases/download/v0.18.2/rtsp-simple-server_v0.18.2_linux_amd64.tar.gz"
curl  -L $url -O
tar -xzf rtsp-simple-server_v0.18.2_linux_amd64.tar.gz
./rtsp-simple-server

Now we can push rtsp stream on the server with ffmpeg:
ffmpeg -re  -i /mnt/hls/m7.mp4  -f rtsp -rtsp_transport tcp rtsp://127.0.0.1/live

It works fine!.


text:
Q: WordPress frontend AJAX call to trash post failing My users have the ability to create an instance of a custom post from their accounts, and then I would like for them also to be able to delete them.  Within a section of their account all the posts they have made are listed, and each has a "delete" button like so:
<a href="#" class="deleteMR" data-id="<?php echo $post->ID ?>">delete
Then in an external JS file I have:
jQuery(".deleteMR").click(function (e) {
   e.preventDefault();
   rid = $(this).attr("data-id");
   var data =  {
      action: 'delete_request',
      requestid: rid,
   }
   jQuery.post(my_ajax_object.ajaxurl, data, function(response) {
      if(response.success) {
         alert('It worked');
      } else {
         alert('It failed');
      }
    });
});

And then in my functions.php I have:
add_action('wp_ajax_delete_request', 'delete_request');
function delete_request() {

   $requestid = $_REQUEST['requestid'];
   wp_trash_post(requestid);

   wp_send_json_success(true);

   wp_send_json_error(console.log(response));
}

When the button is clicked, the JavaScript correctly triggers (and I have checked its picking up the correct post ID with console.log's), the function in functions.php is at least acknowledged but the return is always "failed" and the post is not trashed.  If I output $response instead I just seem to get the first 10% of the code of the page that this whole thing is triggered from.
I cannot figure out what I am doing wrong, can anyone help? Thanks.

A: There's couple of things wrong with your code. Please see the comments I added in the code below.
add_action('wp_ajax_delete_request', 'delete_request');
function delete_request() {

   $requestid = $_REQUEST['requestid'];
   // missing $ from variable name
   wp_trash_post(requestid);
   // always returns a success response
   wp_send_json_success(true);
   // error response never gets returned as success response is sent first.
   // also console.log is javascript, use var_dump or print_r instead
   wp_send_json_error(console.log(response));
}

If you write you're code like this, I think the post trashing should work.
add_action('wp_ajax_delete_request', 'delete_request');
function delete_request() {

  // check nonce wp_verify_nonce()
  // send nonce with your ajax request
  // get nonce from wp_create_nonce() added to your site with wp_localize_script()

  // check capabilities with current_user_can();

  if ( ! empty( $_POST['requestid'] ) && is_numeric( $_POST['requestid'] ) ) {

    $trashed = wp_trash_post( intval( $_POST['requestid'] ) );

    if ( $trashed ) {
      wp_send_json_success('Trashing post succeeded');
    } else {
      wp_send_json_error('Trashing post failed');
    }

  } else {

    wp_send_json_error('Post id missing');

  }

}

A: FWIW the issue was resolved by me moving the ajax specific JS to it's own file and then enqueuing it in it's own function separate from the one that enqueues all my other JS files.  Couldn't tell you how it fixed it, but it did.


text:
Q: Failed to read the request form. Missing content-type boundary after convert request from curl or postman during send zip file I would like to send a zip file using Python Requests. How to correct my code to send the zip file correctly?
My Curl request working fine and returns 200
curl -X 'POST'   \
'https://xxx/bulk'   \
-H 'accept: application/json;odata.metadata=minimal;odata.streaming=true'
-H 'Authorization: Basic xxx'
-H 'Content-Type: multipart/form-data'
-F 'File=@/home/dominik/ok/batch.zip;type=application/x-zip-compressed'

My Postman request returns 200. But the Python code from the Postman generator doesn't work.

Python code
headers = {
    'accept': 'application/json;odata.metadata=minimal;odata.streaming=true',
    'Content-Type': 'multipart/form-data',
    'Authorization' : 'Basic xxx'}

def send_zip(zip_path, url, headers):
    start_time = time.perf_counter()
    zip_to_send = {'file': ('batch.zip', open(zip_path, 'rb'), 'application/x-zip-compressed')}
    response = requests.request('POST', url, headers=headers, files=zip_to_send)
    print(response.text, response.status_code)
    end_time = time.perf_counter()
    total_time = end_time - start_time
    print(f'Total time to send zip: {total_time}')

my code returns
Failed to read the request form. Missing content-type boundary

I know about curlconverter but it returns the code with the file error
  headers = {'accept': 'application/json;odata.metadata=minimal;odata.streaming=true',
    'Authorization': 'Basic xxx,
    # requests won't add a boundary if this header is set when you pass files=
    # 'Content-Type': 'multipart/form-data',
    }
  fils = {'File': open('/hoome/ok/batch.zip;type=application/x-zip-compressed', 'rb'),}
  response = requests.post('https://xxx/bulk', headers=headers, files=files, )


text:
Q: Selenium Problem extracting Google business description I seem to be struggling with this issue for a couple of days and could really use some help. I am trying to scrape Google busineses information with Python beautifulsoups and Selenium and I want to extract the business description that is available for some of them:

As you can see not all of the text is shown so I need to click "More". That is where the problem comes, no matter what I do I can't seem to click it. I tried:

*

*Waiting after I get url with Selenium so elements load

*Getting element by class

*Getting element by xpath

*Clicking element via js executed code

*Checking if element is in iframe(seems like it is not)

*Setting browser to max size, setting browser headless option on and of

*Switching between Firefox and Chrome

EDIT: Code I tried using:
url = 'https://www.google.com/search?q=' + quote(''.join(company) + ' ' + ''.join(location))
    chrome_options = webdriver.FirefoxOptions()
    chrome_options.headless = True
    chrome_options.add_argument("--lang=en-GB")
    chrome_options.add_argument("--window-size=1100,1000")
    chrome_options.add_argument('--user-agent="Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166"')
    browser = webdriver.Firefox(executable_path='C:/geckodriver.exe', options=chrome_options)
    from selenium.webdriver.support import expected_conditions as EC
    browser.maximize_window()
    wait = WebDriverWait(browser, 10)
    browser.get(url)  # open a new tab in the new window
    wait.until(EC.element_to_be_clickable((By.XPATH, "//a[@href and .='More']"))).click()
    # browser.find_element_by_class_name('bJpcZ').click()
    html = browser.page_source
    browser.close()
    soup = BeautifulSoup(html, 'lxml')

If anyone feels like he/she knows a solution please pass it over :)

A: driver.maximize_window()
wait=WebDriverWait(driver,10)
driver.get("https://www.google.com/search?rlz=1C1NDCM_enCA792CA792&sxsrf=APq-WBsY3Q1E1ge_7PuFaovaxQ_Orvk8-w:1645162032562&q=dungeness+pest+control&spell=1&sa=X&ved=2ahUKEwjfuLGUwoj2AhUaHDQIHUtpCOkQBSgAegQIARAy&biw=1366&bih=663&dpr=1")  # open a new tab in the new window
wait.until(EC.element_to_be_clickable((By.XPATH,"//a[@href and .='More']"))).click()

Simply click the a tag with the text more.
There is a //div[@data-long-text] however where you could just .get_attribute("data-long-text") instead.
Import:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


text:
Q: UnicodeEncodeError: 'ascii' codec can't encode characters in position 23-24: ordinal not in range(128) I am trying to parse csv that contains the text below text (test.csv)
"legalgroup_text"   "Aktiebolag"    "Aktiebolag"    "LGAKTIEBOLAG"
"legalgroup_text"   "Allmän försäkringskassa"   "Allmän försäkringskassa"   "LGALLMAENFOERSAEKRINGSKASSA"

I am using encoding iso-8859-1, since the file contains swedish character
import codecs
import csv

with codecs.open('test.csv', encoding='iso-8859-1') as label_file:
    data = csv.reader(label_file, delimiter='\t')
    for row in data:
        print(row)

I am getting error
Traceback (most recent call last):
File "/mnt/ashraful/PycharmProjects/Test/test.py", line 6, in <module>
    for row in data:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 23-24: ordinal not in range(128)

I also tried with encoding utf-8, but getting error
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 25: ordinal not in range(128)

A: Give up on Python 2 and use Python 3. That by itself (no other changes, I just tested) will fix the issue.


text:
Q: How to release the memory used by a string on a map I have the declared two maps. First in each is a symbol. The outs maps the symbol to an ofstream, and the message_strs maps the symbol to a string which concatenates the messages received for the symbol. The objective is to store in the message_strs as many of the messages so as to reduce the number of times I have to write to file. I've tried both ways and this way is much faster. Here are the declerations:
std::map<std::string, std::shared_ptr<std::ofstream>> outs;
std::map<std::string, std::string> message_strs;

When the length of the string is large enough, (500000) I write it to the ofstream and the erase the string like this:
*outs[symbol] << message_strs[symbol];
message_strs[symbol] = "";

I am monitoring memory usage from task manager. I notice that when the write happens there's no reduction in my programs process memory. Do I have to do something in addition to just setting the string on the map to empty string to free the memory?

A: Deallocations are generally handled in the C runtime, and not passed thrhough to the OS.


text:
Q: Getting html script when running a unit test in yii2 framework When I run the test in the console, I am getting HTML and CSS code. The other tests are running fine I have issue only with this one... Can any one help?
thank you
This is my DemoFeature
namespace app\tests\fixtures;

use yii\test\ActiveFixture;

class DemoFixture extends ActiveFixture{

    public $modelClass = '\website\models\DemoForm';
}

and this is my DemoTest
namespace app\tests\unit;

use app\tests\fixtures\DemoFixture;
use website\models\DemoForm;

class DemoTest extends \Codeception\Test\Unit{

    protected function _before() {
        parent::_before();
    }

    public function _fixtures() {
        return ['demo' => DemoFixture::className()];
    }

    protected function _after() {

    }

    public function testDemoProcess(){

        $demo = new DemoForm;

        $demo->name = 'Sample Name';
        $demo->company = 'cloudadic'.rand(115, 54785);
        $demo->email = 'demo'.rand(115, 547).'@example.com';
        $demo->message = 'Sample Company';
        $this->assertTrue($demo->save());

    }
}


text:
Q: pragmatic cross platform (and very fast to make it - actually - work) "throwaway" code: which language/tools? my development style brings me to write a lot of throw-away "assisting" code,
whether for automatic generation of code parts, semi-automated testing, and generally to build dummies, prototypes or temporary "sparring partners" for the main development; I know I'm not the only one...
since I frequently work both under windows and Unicies, I'd like to non-exclusively focus on a single "swiss army knife" tool that can work in both the environments with limited differences, that would allow me to do usual stuff like text parsing, db access, sockets, nontrivial filesystem and process manipulation
until now under unix I've used a bit of perl and massive amounts of shell scripts, but the latter are a bit limited and perl... despite being very capable and having modules for an incredible array of duties, sincerely I find it too "hostile" for me for something that goes beyond 100 lines of code.
what would you suggest?
scripting is not a requirement, it would be ok to use more static-styled languages IF it makes development faster (getting programs to actually do their work and possibly in a human readable state) and if it doesn't become nightmarish to handle errors/exception and to adapt to dynamic environments (e.g. I don't like to hardwire data /db table structure in my code, especially by hand).
I've been intrigued by python, ruby, but maybe groovy (with its ability to access the huge class library and his compact syntax) or something else is better suited
thanks a lot in advance!
(meanwhile, on a completely different note, scala looks really tempting just for the cleanliness of it, but that's - probably - a completely different story, unless you tell me the opposite...?)

A: Python is arguably one of the best choices. Its biggest benefit is that it has a huge built-in library for doing all sorts of stuff. It is also mature, very cross-platform, actively developed, and has many support options (mailing lists, newsgroups, etc).
In addition, it has a built-in GUI toolkit (tkinter) for those times when you need to write a quick GUI to get input from a user or display output from a running process. And if you don't like tkinter, there are other cross-platform GUI toolkits available.

A: I suggest Python.
For me it has a sweet spot of good libraries, documentation, community, cross-platform functionality, and ease of writing/reading.
It fills a similar niche to Perl's, but if you find Perl to be 'hostile' for longer scripts, you will probably like Python, especially when compared to Ruby, which feels more Perl-y, IMHO.
As an aside, all of these are quite easy to just try out - why not do that?
Then you can decide for yourself instead of trusting the questionable wisdom of an online forum (:

A: I think that Python and Ruby are your best bets, depending on exactly how you think and code.
I personally find Python EXTREMELY readable and its syntax is highly intuitive. I've heard Python described as "pseudo-code plus colons."
On the other hand, once you get around its slightly bizarre syntax, Ruby makes for high-speed development. It's built around DRY principles and convention-before-configuration, which is great for rapid prototyping.
There are other languages--especially Haskell and the Lisp dialects--that can make for super-rapid prototyping, but they don't have as large a supportive community, so there's a shortage in library and discussion supply.


text:
Q: How can one prove that an operation $*$ over a group $Z$ is associative if there are multiple solutions to it? Given that an operation $*$ is applied over the group Z (the group of integers), and $\forall  a, b, c \in \mathbb{Z}$, the following is true:
$if \space a < 0,\space then \space \space a * b = b$
$ if \space a >= 0, \space then \space \space a * b = a$
My idea was to use the possible solutions that the two expressions can have. For the first expression, the solution of $(a * b) * c$, is equal to one of the followings:
(1) $a * c$
(2) $b * c$
Therefore, all of the possible solutions of (1) and (2) are [a, c, b, c]. As we reapeat the proccess with the second expression $a * (b * c)$, we get [a, b, a, c]. The probability to get 'c' in the first expression $(a * b) * c$ was higher (2 / 4) than the probability to get 'c' in the other one (1 / 4). Therefore, the operation over the group, is not associative. Or more accurate, the solutions lists were not equal.
This question is part of University homework of a beginners Mathematics course, and I'll be glad to learn from you what are the additional ways to think about the challenge ?, and NOT to know the solution to it.

A: I would complete this table and check whether the last two columns are identical
 a<0?  b<0? a*b  b*c (a*b)*c a*(b*c)
  T     T    b    c      c     c
  T     F    b
  F     T    a
  F     F    a


text:
Q: Force XML using XSD to mimic radio button behavior I have an application that has 6 radio buttons in a group on a form. Settings on this form can be exported into XML and re-imported. Before commencing the re-import session I want to validate the XML file using an XSD, to make sure that if the user edited the XML, he did it right. I plan to do it using an XSD if possible.
Since radio buttons on the GUI must have a single buutton and only a single button selected I want to mimic this behavior using an XSD. I want to receive XSD schema errors if there are multiple options set to True in the XML or there are none.
Is it possible to achieve this using XSD, or do I need to code this type of validation in the application?

A: Enumerations naturally mirror the exclusive nature of radio buttons and will work in both XSD 1.0 and 1.1:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="RadioButton">
    <xsd:simpleType>
      <xsd:restriction base="xsd:string">
        <xsd:enumeration value="v1"/>
        <xsd:enumeration value="v2"/>
        <xsd:enumeration value="v3"/>
        <xsd:enumeration value="v4"/>
        <xsd:enumeration value="v5"/>
        <xsd:enumeration value="v6"/>
      </xsd:restriction>
    </xsd:simpleType>
  </xsd:element>
</xsd:schema>


text:
Q: Hiding Window Titlebars (like the hiding the taskbar) Users can configure the Windows taskbar to slide out of view (hidden) and can explicitly motion (summon) for the taskbar when needed.
Is there an example of similar capability with the titlebar of a window?
It occupies valuable real-estate and (in my view) not the best use of space.


text:
Q: Identify 3rd Friday in a sequence of Dates The code below has a list of dates and if the the date is the last day in he month, for all the dates in dataset (not on the calendar), then it flags the date as the last day in the month.
data = data.frame(day  = seq(as.Date("2014-01-01"),as.Date("2016-05-10"),"day"), weekday = weekdays ( seq(as.Date("2014-01-01"),as.Date("2016-05-10"),"day")))
excludeDays <- c("Saturday", "Sunday")
data <- subset(data, !weekdays(data$day) %in% excludeDays) #exclude weekend
setDT(data)
data[, LastDayInMonth := day == max(day), by = list(year(day),month(day)  )]
head(data,100)

I also need to add a column that flags (TRUE/FALSE) any Friday in the data that is the 3rd Friday in the month. Any idea on that?
for example 2014-01-17, 2014-02-21,......2014-05-16 etc... are 3rd fridays.
Thank you.

A: data[, numWeek := 1:.N, by = .(year(day), month(day), weekday)]

data[numWeek == 3 & weekday == "Friday"]

Or to add as a column:
data[, is3rdFriday := numWeek == 3 & weekday == "Friday"]

If you're looking for 3rd Friday in the calendar, as opposed to the 3rd Friday in your data, then you can do it even simpler:
data[, is3rdFriday := (mday(day) - 1) %/% 7 + 1 == 3 & weekday == "Friday"]

A: Try this - without data.table:
library(lubridate)
library(dplyr)
data <- data.frame(day  = seq(as.Date("2014-01-01"),
                              as.Date("2016-05-10"),"day"),
                  weekday = weekdays(seq(as.Date("2014-01-01"),
                                         as.Date("2016-05-10"),"day")))
data$year_month <- floor_date(data$day, unit = 'month')
fri3 <- filter(data, weekday == 'Friday') %>%
  group_by(year_month) %>% slice(3)

data$Third_Fri <- data$day %in% fri3$day

You can remove year_month later

A: Another way to do it:
data[, is3Friday:=cumsum(weekday=="Friday"), by=substring(day, 1, 7)]
data[, is3Friday:=ifelse(weekday=="Friday" & is3Friday==3, TRUE, FALSE)]

data[is3Friday==TRUE]
           day weekday LastDayInMonth is3Friday
 1: 2014-01-17  Friday          FALSE      TRUE
 2: 2014-02-21  Friday          FALSE      TRUE
 3: 2014-03-21  Friday          FALSE      TRUE
 4: 2014-04-18  Friday          FALSE      TRUE
 5: 2014-05-16  Friday          FALSE      TRUE
 6: 2014-06-20  Friday          FALSE      TRUE

A: To cover the corner case when the data starts in the middle of the month you can try this:
occ <- 3L   # 3rd occurrence of selected weekday
data[, ThirdFridayInMonth := weekday == "Friday" &
       as.integer(day - lubridate::floor_date(day, "month")) %/% 7L + 1L == occ]

This works also for other weekdays in the month, e.g., to flag every first Monday.
Edit: Explanation as requested.
The basic idea is that the 1st Friday in each month must be one of the first 7 days of each month, the 2nd Friday must be one of the days 8 to 14 and so forth. So, lubridate::floor_date(day, "month") computes the first day of the month day is located in. Now, you build the difference which is a difftime object which needs to be converted into an integer. If day happens to be the first of a month this is 0. Now you use integer division %/% which returns 0 for the first 7 days of the month, 1 for the second 7 days, etc. which is then adjusted by adding 1.
Edit 2: Improved code
While writing the explanation, I recognized that the code can be further improved.
We can use the day of month directly which saves us from computing the difference in dates and subsequent conversion to integer:
data[, ThirdFridayInMonth := weekday == "Friday" &
       (mday(day) - 1) %/% 7L + 1L == occ]

Here, I use mday (part of data.table package) instead of as.integer(format(day, "%d")).


text:
Q: Get result of ShowCategoriesDialog in Outlook In my code I open categorize dialog like this:
item.ShowCategoriesDialog();

Is it possible to determine whether user clicked "OK" or "Cancel" in the dialog?
Currently I compare item's categories before and after showing the dialog, but maybe there is a better way.

A: No, it is not. The Outlook object model doesn't provide anything for that.


text:
Q: Borders created with background colors disappear when bootstrap included I have a HTML table in which a background color is set on each cell. As a result, the contrast between two bg colors appears as a border. Please refer to accepted solution at
Borders around every cell and table
This is a follow up question.
Now I need to include bootstrap in my application. However, as soon as I include bootstrap CSS the border appearance disappears (even if I don't include any bootstrap class). How can I include bootstrap and still have a border like appearance around each cell.
Here is the fiddle with bootstrap included
https://jsfiddle.net/hqkw4x1s/1/
and below is the original code, without reference to bootstrap css (this gives a border like appearance due to bgcolors)

.lab {
 HEIGHT: 18px; FONT-WEIGHT: normal; TEXT-ALIGN: left; PADDING-LEFT: 4px; PADDING-RIGHT: 3px; BACKGROUND-COLOR: #e6f6f6
}

.val {
 PADDING-BOTTOM: 1px; PADDING-TOP: 1px; PADDING-LEFT: 2px; PADDING-RIGHT: 3px; BACKGROUND-COLOR: white
}
  <FORM>

                       Country

                          <INPUT name="A" id="A" type=checkbox CHECKED>
                          A
              <INPUT name="B" id="B" type=checkbox CHECKED>
                          B

                       States

                                      <SELECT>
                                         <OPTION value="p" selected>P</OPTION>
                                         <OPTION value="q">Q</OPTION>
                                         <OPTION value="r">R</OPTION>
                                      </SELECT>

                       Ownership

                                   <TEXTAREA style="WIDTH: 95%" rows=1 cols=20></TEXTAREA>

                       Partnership
                       <INPUT  type=text xHeight="32px">

                       Accounts Payable

                          <INPUT type=text>

                       Start Date

                          <INPUT type=text xHeight="32px">

        </FORM>

A: Please update below table tag.Here you just need to use the bootstrap standard class to achieve this.
Instead

Should be:


text:
Q: write to child process twice after nonblocking read I have a python loop that reads from multiple child processes (without blocking). Sometimes I have to write to that child process. The first write goes through but if I perform a non-blocking read then write to the child process again, the second write never seems to go through to the child process.
I believe if I perform a regular blocking read (process.stderr.readline()), the second read will go through. Any help?
Python loop
# create mock process
childprocesses = []
p = subprocess.Popen(['./cprogram'],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE)
childprocesses.append(p)
loop_4eva()

# the loop
def loop_4eva():
    for process in childprocesses:
        if(process.poll() is None):
            process.stdin.write("first write\n")
            output = non_block_read(process.stderr).strip()
            print output
            process.stdin.write("second write\n")
            output = non_block_read(process.stderr).strip()
            print output

def non_block_read(output):
    fd = output.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    try:
            return output.readline()
    except:
            return ''

A child process (c program)
void main(){
    char buffer[256];
    while(1){
        fgets(buffer, 256, stdin);//read/buffer one line from stdin
        fprintf(stderr, "read: %s", buffer);//buffer includes '\n'
    }
}

Output (python prints...)

read: first write
  //nothing else

A: stdin is line buffered in C. You will probably need to disable buffering in the child process to make this work. You'll also want to add a process.stdin.flush() to ensure you aren't getting buffered on the writer side.


text:
Q: CancellationSource not working when executing Regex I have a Regex which might lead to dead loop when dealing some files.
Although I should fix this problem sooner or later, to make it safe, I want to run it in a cancel-able tasks.
I've read some answers here, but none of the following solutions worked. Any help?
    public static Task<CodeFile> CreateCodeFile(string fileName)
    {
        var fileInfo = new FileInfo(fileName);
        foreach (var codeFileFactory in CodeFileFactories)
        {
            var cancellationTokenSource = new CancellationTokenSource();
            cancellationTokenSource.CancelAfter(1000);
            var task = new Task<CodeFile>(() => TryToCreateCodeFile(codeFileFactory, fileInfo),
                cancellationTokenSource.Token);
            task.RunSynchronously(); //Get lost here.
            if (!task.Wait(1000))
                cancellationTokenSource.Cancel();

            File.WriteAllTextAsync("FailedLog.txt",
                File.ReadAllTextAsync("FailedLog.txt") + "\r\n" + fileName);
            cancellationTokenSource.Dispose();
            return task;
        }

        return null;
    }

or:
    public static async Task<CodeFile> CreateCodeFile(string fileName)
    {
        var fileInfo = new FileInfo(fileName);
        foreach (var codeFileFactory in CodeFileFactories)
        {
            var cancellationTokenSource = new CancellationTokenSource();

            try
            {
                cancellationTokenSource.CancelAfter(1000);
                var codeFile = await Task.Run(() => TryToCreateCodeFile(codeFileFactory, fileInfo),
                    cancellationTokenSource.Token); //Get lost here.
                if (codeFile != null)
                    return codeFile;
            }
            catch (TaskCanceledException)
            {
                File.WriteAllTextAsync("FailedLog.txt",
                    File.ReadAllTextAsync("FailedLog.txt") + "\r\n" + fileName);
            }
            finally
            {
                cancellationTokenSource.Dispose();
            }
        }

        return null;
    }

And here is the function to be called:
    private static CodeFile TryToCreateCodeFile(ICodeFileFactory codeFileFactory, FileInfo fileInfo)
    {
        var codeFile = codeFileFactory.CreateByName(fileInfo);
        return codeFile;
        //Somewhere deeper, .net Regex.Matches() caused the dead loop which I cannot control.
    }

In this topic CancellationTokenSource.CancelAfter not working, I read something like "Your Sleep method is ignoring the CancellationToken." Does it happen in my case?

A: Cancellation tokens implement cooperative cancellation, which means the code being "cancelled" must cooperate, by actively checking the status of the token. Regex.Matches does not have overload which accepts the token, which means it can't be cancelled this way.
Tasks in general can't be magically cancelled. Code which task executes must do that explictly (with something like token.ThrowIfCancellationRequested()), your code doesn't do that so token doesn't do anything useful. Passing token to Task.Run is documented like this:

A cancellation token that can be used to cancel the work if it has not
yet started. Run(Action, CancellationToken) does not pass
cancellationToken to action.

So yes, if task is not started that will cancel it, not quite useful in your case.
If you perform some long running operation which does not accept and handle cancellation tokens (and you are not able to handle cancellation yourself, by checking token every now and then) - then you can't cancel it with them.
In your case I'd suggest Regex.MatchTimeout


text:
Q: How to get IP when using SimpleXMLRPCDispatcher in Django Having a code inspired from http://code.djangoproject.com/wiki/XML-RPC :
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
from django.http import HttpResponse

dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) # Python 2.5

def rpc_handler(request):
    """
    the actual handler:
    if you setup your urls.py properly, all calls to the xml-rpc service
    should be routed through here.
    If post data is defined, it assumes it's XML-RPC and tries to process as such
    Empty post assumes you're viewing from a browser and tells you about the service.
    """

    if len(request.POST):
        response = HttpResponse(mimetype="application/xml")
        response.write(dispatcher._marshaled_dispatch(request.raw_post_data))
    else:
        pass # Not interesting
    response['Content-length'] = str(len(response.content))
    return response

def post_log(message = "", tags = []):
    """ Code called via RPC. Want to know here the remote IP (or hostname). """
    pass

dispatcher.register_function(post_log, 'post_log')

How could get the IP address of the client within the "post_log" definition?
I have seen IP address of client in Python SimpleXMLRPCServer? but can't apply it to my case.
Thanks.

A: Ok I could do it ... with some nifty tips ...
First, I created my own copy of SimpleXMLRPCDispatcher which inherit everything from it and overides 2 methods :
class MySimpleXMLRPCDispatcher (SimpleXMLRPCDispatcher) :
    def _marshaled_dispatch(self, data, dispatch_method = None, request = None):
        # copy and paste from /usr/lib/python2.6/SimpleXMLRPCServer.py except
        response = self._dispatch(method, params)
        # which becomes
        response = self._dispatch(method, params, request)

    def _dispatch(self, method, params, request = None):
        # copy and paste from /usr/lib/python2.6/SimpleXMLRPCServer.py except
        return func(*params)
        # which becomes
        return func(request, *params)

Then in my code, all to do is :
# ...
if len(request.POST):
    response = HttpResponse(mimetype="application/xml")
    response.write(dispatcher._marshaled_dispatch(request.raw_post_data, request = request))
# ...
def post_log(request, message = "", tags = []):
    """ Code called via RPC. Want to know here the remote IP (or hostname). """
    ip = request.META["REMOTE_ADDR"]
    hostname = socket.gethostbyaddr(ip)[0]

That's it.
I know it's not very clean... Any suggestion for cleaner solution is welcome!


text:
Q: Sorting cells in UITableView into sections, after TableView has been loaded Right, so my UITableView loads and puts all the cells in Alphabetical order. Information is then downloaded from a server and calculations are done, with the TableView being reloaded once everything is complete. Currently this is quite a simple procedure as once the information is downloaded from the server, the cells don't even move, they are left in their alphabetical order. Nothing really happens other than half of the information is filled in and small changes are made depending on the calculations. I was wondering if there was an easy way of putting the cells into sections depending on the calculations done after the download is complete? I did have an idea of creating 4 arrays (there will only be 4 sections ever) and once isLoading is set to no, changing the data source of the TableView to have sections, however, that sounds a bit... iffy. I know this is a theoretical question as opposed to a coding problem, but before I go and mess up my code, in what is sure to be a stupidly inefficient way of doing things, is there an easy way of "assigning" UITableViewCells to sections?
My main issue with my way of doing it is that should the user delete a cell, deleting the appropriate entry in Core Data will be a little tricky and prone to errors. This lead me on to another idea. What if I added an extra attribute to my Core Data entity. That attribute would be assigned and then saved once the calculations were done. The problem with this is that no existing databases would work. There has to be a neat way of achieving this.
Thanks for the help. If you need me to post any code just say so and I will.

A: You should be fine if you implement the data source methods related to sections.
For example:

*

*numberOfSectionsInTableView

*sectionIndexTitlesForTableView.

Any time the table data is reloaded (e.g., [self.tableView reloadData]), these methods will be called and the data will be placed into their sections.
Keep in mind that the cells are just the visual representation of your model, which in this case is your fetched data. The cells are not assigned to sections; they are simply created however you specify for your model (via the table view data source and delegate methods).
Regarding deletion of entries while using Core Data, I suggest taking a look at NSFetchedResultsController. The latter will monitor any changes to your table's data and message its delegate, your table view controller, when updates are made.
For example, a deletion would start with a call to the table view delegate like normal (i.e., via tableView:didEndEditingRowAtIndexPath). Within the latter, you would then delete the entry from core data (e.g., [self.myDatabase.managedObjectContext deleteObject:entity]). Assuming you initiated the NSFetchedResultsController w/ the same managed object context, the deletion would be automatically reflected back to your user.
If you're using a remote DB, however, you'll also have to perform a save (however you've implemented that) to ensure the DB is updated too.
Note also that if you use an NSFetchedResultsController, you don't need to implement the section data source methods since NSFetchedResultsController can handle that for you. Just define the key-path in your data model that will return the section name when initializing the NSFetchedResultsController.


text:
Q: jQuery modal window removes elements from my form jQuery, when i use it to create a modal window which contains form elemets,
it takes out those elements when i submit the form.
example of the form:
<form enctype="multipart/form-data" action="/system/article/add/" class="from" method="post">

    Title:

    <input class="formfield" id="article_title" name="article_title" value="" type="text">

    Url:

    <input class="formfield" id="url" name="url" value="" type="text">

        Photo title:
        <input class="formfield" id="photo_title" name="photo_title" value="" type="text">
        Photo thumb:
        <input type="file" name="photot" id="photot" class="formfield">
        Include lighbox?
        <input name="photo_checkbox" value="0" type="hidden">
        <input class="checkbox" id="photo_checkbox" name="photo_checkbox" value="1" type="checkbox">
        Photo:
        <input type="file" name="photo_big" id="photo_big" class="formfield">

</form>

exaple of JS:


text:
Q: Autodesk forge Create App not functioning I filled out the entire form in all the required fields to create an application on the Autodesk site for their APIs. And the 'Create App' button endless loads with a few errors thrown in the browser console (errors tied to their 'create.js' script). Not sure if the feature for creating an app on the Autodesk site is my input error or my account/user type? I do have an active free trial which supposedly allows me to utilize the 'Create App' feature of the site for their APIs.
Any input on why this isn't working would be greatly appreciated.

A: That's very odd.  It sounds like a glitch.
You should be seeing something like this: https://learnforge.autodesk.io/#/account/
However, if your browser has somehow a partial file set, then maybe it keeps loading the bad files.
One thing you can try is to clear your browser cache.
Again, sorry it's happening - it sounds very weird.
Let me know if clearing the cache fixes it.  (or try incognito mode in your browser, or try a different browser).


text:
Q: Sending emails from different address I have a system (Meteor) where employees log in.
I would like to send and email to clients from the system and set sender email depending on who is logged in.
(I know what email server/username/password employee has)
Eg. When John is log in, he should have an option to send and email from john@test.com, but when James is log in he should have an option to send and email from james@test.com
How can I achieve this? How to dynamically change mail_url?


text:
Q: How to add multiple segments to a Google Analytics API report? How can I add multiple segments to a report using the Google Analytics API plugin for Google Sheets?
Thanks

A: Depending on the API version, this either IS or IS NOT possible.
v3 doesn't support multiple segments, you would have to make a dedicated request for each segment.
v4 does support multiple segments, I've used it within R with this package: http://code.markedmondson.me/googleAnalyticsR/ . Name the segments before submitting the API.


text:
Q: Excel VBA - Loop with Increment How do you reference a cell every four rows from a source sheet and then have it placed in the output sheet? Each cell has different values. Thank you in advance

A: This should do the job. Make sure that you make the required customisations before you try it in your workbook.
Sub TransferData()

    Dim WsS As Worksheet, WsT As Worksheet      ' Source & Target
    Dim Rl As Long                              ' Last row
    Dim Rs As Long, Cs As Long                  ' Source: Row, Column
    Dim Rt As Long, Ct As Long                  ' Target: Row, Column

    Set WsS = Worksheets("Source")              ' change name as required
    Set WsT = Worksheets("Source")              ' I used the same sheet for my test

    With WsT
        Ct = 4                      ' specify the column to write to (here column D)
        Rt = .Cells(.Rows.Count, Ct).End(xlUp).Row + 1
    End With

    Application.ScreenUpdating = False
    With WsS
        Cs = 1                      ' specify the column to read from (here column A)
        Rl = .Cells(.Rows.Count, Cs).End(xlUp).Row
        For Rs = 2 To Rl Step 4                 ' start from row 2
            WsT.Cells(Rt, Ct).Value = .Cells(Rs, Cs).Value
            Rt = Rt + 1
        Next Rs
    End With
    Application.ScreenUpdating = True
End Sub


text:
Q: R - Pair row from one dataframe to another and repeat I have struggled to describe in words to google and stack a possibly painfully simple problem - so apologies in advance for asking something that may very well be answered already. Any help would be greatly appreciated!
Summary:
I am trying to get each row/observation in df1 to "pair" with each row/observation in df2.
dataframes:
FirmName <- c("johns carpets Ltd", "Sarahs Fences Co.", "Eddys DIY", "Lauras Accounting LLP", "Sams Shoes Ltd")
ID <- c('JCL', 'SFC', 'ED', 'LAL', 'SSL')
df1 <- data.frame(FirmName, ID)

FirmGroup <- c("UK-based", "Positive cashflow", "Up for sale")
GroupID <- c(3,4,1)
df2 <- data.frame(FirmGroup, GroupID)

i.e.:
df1

  FirmName             ID
1 Johns Carpets Ltd    JCL
2 Sarahs Fences. Co    SFC
3 Eddys DIY            ED
4 Lauras Account LLP   LAL
5 Sams Shoes Ltd       SSL

df2

  FirmGroup          GroupID
1 UK-based           3
2 Positive cashflow  4
3 Up for sale        1

Desired output
df3

   FirmName               ID   FirmGroup          GroupID
1  johns carpets Ltd      JCL  UK-based           3
2  Sarahs Fences Co.      SFC  UK-based           3
3  Eddys DIY              ED   UK-based           3
4  Lauras Accounting LLP  LAL  UK-based           3
5  Sams Shoes Ltd         SSL  UK-based           3
6  johns carpets Ltd      JCL  Positive cashflow  4
7  Sarahs Fences Co.      SFC  Positive cashflow  4
8  Eddys DIY              ED   Positive cashflow  4
9  Lauras Accounting LLP  LAL  Positive cashflow  4
10 Sams Shoes Ltd         SSL  Positive cashflow  4
11 johns carpets Ltd      JCL  Up for sale        1
12 Sarahs Fences Co.      SFC  Up for sale        1
13 Eddys DIY              ED   Up for sale        1
14 Lauras Accounting LLP  LAL  Up for sale        1
15 Sams Shoes Ltd         SSL  Up for sale        1

I have first tried using leftjoin (vlookup) or Rep() but is getting me no where as there is nothing to match them against and Rep() just seems to repeat in set blocks rather than "pairing". Again, thanks in advance for looking!

A: Using merge you could do:
merge(df1, df2)
#>                 FirmName  ID         FirmGroup GroupID
#> 1      johns carpets Ltd JCL          UK-based       3
#> 2      Sarahs Fences Co. SFC          UK-based       3
#> 3              Eddys DIY  ED          UK-based       3
#> 4  Lauras Accounting LLP LAL          UK-based       3
#> 5         Sams Shoes Ltd SSL          UK-based       3
#> 6      johns carpets Ltd JCL Positive cashflow       4
#> 7      Sarahs Fences Co. SFC Positive cashflow       4
#> 8              Eddys DIY  ED Positive cashflow       4
#> 9  Lauras Accounting LLP LAL Positive cashflow       4
#> 10        Sams Shoes Ltd SSL Positive cashflow       4
#> 11     johns carpets Ltd JCL       Up for sale       1
#> 12     Sarahs Fences Co. SFC       Up for sale       1
#> 13             Eddys DIY  ED       Up for sale       1
#> 14 Lauras Accounting LLP LAL       Up for sale       1
#> 15        Sams Shoes Ltd SSL       Up for sale       1


text:
Q: Managing volumes of books I would like to compile all of the books in a series at the same time. This would:

*

*Guarantee that everything compiled with consistency.

*Easily allow for cross-references between books.

*Allow counters from one book to be conveniently carried to the next.

With the book document class, one can assign parts, chapters, and sections. Is there a way to assign volumes? E.g.:
\book{This is the book's title}
    \part{This is the part's title}
        \chapter{This is the chapter's title}
\book{This is the second book's title}

A: I do this using pdftk and the perl script shown below. One advantage of this approach is that you can have certain content reproduced in each volume. For example, I have pages numbered sequentially across volumes, and a single index and table of contents which are reproduced in all volumes. That way, if you have volume 2, you can look up something in the index and find out that it's on p. 37 of volume 1.
If you have material (e.g., a quick reference page) that you want to end up on the final page of a printed book, there is a mechanism for that as well. Typically the number of pages in a printed book is a multiple of 8, so you need to add blank pages to get the material to end up on the very last interior page.
It reads your .ref file (here assumed to be save.ref) to find the labels used to mark the beginning or end of a section. That way you don't have to keep updating the page numbers of the split-points by hand.
#!/usr/bin/perl

use strict;

my $input_file = $ARGV[0];
my $vol = $ARGV[1];
my $output_file = $ARGV[2];

# reads save.ref and splits.config
#
# format of splits.config:
#    v1,v2,label1,offset1,label2,offset2,mod8
#    (v1,v2)=(1,1) means only include these pages in volume 1
#    (v1,v2)=(2,2) means only include these pages in volume 2
#    (v1,v2)=(1,2) means include these pages in both volumes
#    label1=latex label of beginning of range, or null
#    offset1=offset from label1; if label1 is null string and offset is +, then take offset1 as page number; if label1 is 'end' and offset is '', take last page
#    label2,offset2=similar for end of range
#    mod8=if not null, force it to start on a page of the output pdf that equals this, modulo 8
#      You typically want the output pdf to have a number of pages that is a multiple of 8. So, e.g., if LM has three pages of data, etc., at the end,
#      set mod8 to 5, so that the third page will equal 7 mod 8.

my %refs = ();
open(F,"<save.ref") or die "error opening save.ref for input";
while (my $line = <F>) {
  chomp $line;
  if ($line =~ /([^,]*),([^,]*),([^,]*)/) {
    my ($label,$name,$page) = ($1,$2,$3);
    $refs{$label} = $page;
  }
}
close(F);

open(F,"<splits.config") or die "error opening splits.config for input";
my @pages = ();
my $n = 0;
while (my $line = <F>) {
  chomp $line;
  if ($line =~ /([^,]*),([^,]*),([^,]*),([^,]*),([^,]*),([^,]*),([^,]*)/) {
    my ($v1,$v2,$l1,$o1,$l2,$o2,$m) = ($1,$2,$3,$4,$5,$6,$7);
    my $p1 = find_page($l1,$o1);
    my $p2 = find_page($l2,$o2);
    #print "pages $p1-$p2\n";
    my $chunk = 0;
    if ($vol>=$v1 && $vol<=$v2) {
      if ($p1%2 != 1) {push @pages,"B1"; ++$chunk}
      if ($m ne '') {
        while (($n+$chunk)%8!=$m) {push @pages,"B1"; ++$chunk}
      }
      push @pages,"$p1-$p2";
      if ($p2 ne 'end') {
        $chunk += (($p2-$p1)+1);
        if ($chunk%2!=0) {push @pages,"B1"; ++$chunk}
      }
      print "input $p1-$p2 -> output ",($n+1),"-",($p2 eq 'end' ? 'end' : $n+$chunk),"\n";
      $n += $chunk;
    }
  }
}
close(F);

my $c = "pdftk $input_file B=../share/misc/blank_page.pdf  cat ".join(' ',@pages)." output $output_file";
print "$c\n";
system $c;

sub find_page {
  my $l = shift;
  my $o = shift;
  if ($l eq '') {return $o}
  if ($l eq 'end') {return 'end'}
  if (!exists $refs{$l}) {die "label $l doesn't exist in save.ref"}
  return $refs{$l}+$o;
}

sub barf {
  my $message = shift;
  print STDERR "splits.pl: $message\n";
  print STDERR "You will need to edit splits.config.\n";
  exit(-1);
}

A: As others have said you can use xr to manage cross references between documents. If you want counters to be preserved, I'm not sure if there is a ready made package on ctan but it is easy to save the state of the counters at the end of one document and reset them at the start of the next.
for example if you latex b1 and then b2 using the following the equations and tables in b2 will carry on from where they left off in b1.
%savecounters.sty

\def\savecounters#1{%
\newwrite\SC@counters
\immediate\openout\SC@counters=\jobname-counters.tex
\AtEndDocument{
\@for\c:=#1\do{
\immediate\write\SC@counters{\noexpand\setcounter{\c}{\arabic{\c}}}
}
}
}

b1.tex
\documentclass{book}

\usepackage{savecounters}

\savecounters{equation,table}

\begin{document}

\begin{table}
Table
\caption{a table}
\end{table}

\begin{equation}
1=1
\end{equation}

\begin{equation}
1=2
\end{equation}

\end{document}

b2.tex
\documentclass{book}
\input{b1-counters}
\begin{document}

\begin{table}
Table
\caption{a table}
\end{table}

\begin{equation}
1=1
\end{equation}

\begin{equation}
1=2
\end{equation}

\end{document

}

A: Guarantee that everything compiles with consistency
You will have consistent documents when you avoid redundancy. Check your files
carefully if you define the same properties or styles twice (e.g. colours,
lengths, abbreviations, …).
Move all mutual elements to dedicated environment files and include those in
your books. You can find more information about this on the ConTeXt wiki -
Project Structure and the ConTeXt magazine #1101.
Content files not containing any style information and the style information that is shared between the individual volumes leads to consistency.
Easily allow for cross-references between books
Cross-references are supported by default. You either prepend the
reference with filename:: or you can use the more generic command
\useexternaldocument. Example:
% file: crossref.tex
\useexternaldocument [introduction] [intro.tex]
\starttext
    Here comes a reference to the intro:
    \in{chapter}[intro::sec:intro] on \at{page}[intro::sec:intro]

    Or, more generic, using useexternaldocument:
    \in{chapter}[introduction::sec:intro] on \at{page}[introduction::sec:intro]
\stoptext

% file: intro.tex
\starttext
    \null\page
    \startchapter [title=Intro, reference=sec:intro]
    \stopchapter
\stoptext

Here's a screenshot from the file crossref.tex:

Remember to use a double colon for cross-referencing, in contrast to the more common variant of using a single one for in-document references.
Allow counters from one book to be conveniently carried to the next
I don't think this is natively supported. But you can misuse the referencing
mechanism, since it supports counting and cross-document access. Of course,
you are again free to use the \useexternaldocument feature. Example:
% file: savecounter.tex
\starttext
    Here I store a number that can be obtained in the
        other file:
    \reference [mycount] {42}
\stoptext

% file: crosscounter.tex
\useexternaldocument [cross] [savecounter.tex]
\starttext
    And here is the number from the savecounter file:
    \getreference [text] [savecounter::mycount]

    Using the useexternaldocument mechanism:
    \getreference [text] [cross::mycount]
\stoptext

Here's a screenshot from the file crosscounter.tex:

Since the reference mechanism saves more information than we need, we provide an argument in brackets containing text, which retrieves the value that was saved before as the second argument of the \reference command.
And again: Remember to use a double colon for the cross-document reference.
You can create an interface to define, change and
retrieve the counters if you like. The low-level ommands look
quite ugly in the document and are even semantically wrong.

A: Using the memoir document class you have a new "sectional unit" \book that serves your purposes. Refer to Chapter 6 of the documentation, particularly, Sections 6.2 SECTIONAL DIVISIONS, 6.3 NUMBERING, and 6.4 BOOK AND PART HEADINGS.

A: There  is no need to compile the books all at once: the xr package easily allows for cross-references between books, and it allows counters from one book to be conveniently carried to the next. With hyperref, links will work between different books.


text:
Q: Can't write Double word on STM32F429 using HAL driver I am trying to write uint64_t(double word) variable into the flash memory, without success though. Here is the code.
#define APPLICATION_START_ADDRESS                                   0x8008000

void flashErase(uint8_t startSector, uint8_t numberOfSectors)
{
    HAL_FLASH_Unlock();

    Flash_eraseInitStruct.TypeErase     = FLASH_TYPEERASE_SECTORS;
    Flash_eraseInitStruct.VoltageRange  = FLASH_VOLTAGE_RANGE_3;
    Flash_eraseInitStruct.Sector        = startSector;
    Flash_eraseInitStruct.NbSectors     = numberOfSectors;

    if(HAL_FLASHEx_Erase(&Flash_eraseInitStruct, &Flash_halOperationSectorError) != HAL_OK)
    {
        Flash_raiseError(errHAL_FLASHEx_Erase);
    }

    HAL_FLASH_Lock();
}

int main(void)
{
    HAL_Init();
    main_clockSystemInit();
    __IO uint64_t word =  0x1234567890;

    flashErase(2, 1);
//  flashProgramWord(aTxBuffer, APPLICATION_START_ADDRESS, 2 );
    HAL_FLASH_Unlock();
    HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, APPLICATION_START_ADDRESS, word);
}

I get error flag raised PGSERR and PGAERR. The erase operation goes without problems. But programming returns ERROR.
Some Ideas?

A: There is no STM32F249, did you mean STM32F429?
In order to use 64 bit programming, VPP (BOOT0) has to be powered by 8 - 9 Volts. Is it?
See the Reference Manual Section 3.6.2

By the way,
__IO uint64_t word =  0x1234567890;

would not work as (presumably) expected. It is a 32 bit architecture, integer constants will be truncated to 32 bits, unless there is an L suffix. U wouldn't hurt either, because the variable is unsigned. __IO is unnecessary.
uint64_t word =  0x1234567890UL;


text:
Q: How to get timestamp and do maths on it without caring about the day? I am trying to do some maths with timestamps (or rather without timestamps, but I think I need to use timestamps) in Perl, which is not a language I am very familiar with. I'm particularly unfamiliar with date an time functions of it.
Basically I have a function that takes 5 integers as arguments.
sub calculateEndTime {
    my ($hour, $minute, $second, $roundingInterval ,$buffer)
    ...
}

The maths I want to do is probably irrelevant but is simply:

*

*Round the minutes to the nearest $roundingInterval. E.g if it's 15, round to the nearest quarter hour. I used the below to do it.

    my $nearestInterval = round($minute / $roundingInterval) * $roundingInterval;
    $hour = $hour + 1 if $nearestInterval == 60; #That's gonna screw up future calculations
    $nearestInterval = 0 if $nearestInterval == 60;

*If the given hour, minute, second is within $buffer minutes (default 5 minutes) either side of the rounded time, return the initial ($hour, $minute, $second).

This is where it kind of fell apart, I need a timestamp to check this, manually is going to be a pain to check if hours tick over etc. So how do I create a timestamp from just an hour, minute and second when I don't care about the date? Just give it the current date or some other placeholder?

A: Work with just seconds. Then all you need is
my $rounded = round( $time / $internal ) * $interval;

if ( abs( $rounded - $time ) < $buffer ) {
   $rounded = $time;
}

sub to_time {
   my $hours   = shift;
   my $minutes = shift;
   my $seconds = shift;

   my $time = ( $hour * 60 + $minutes ) * 60 + $seconds;

   return $time;
}

sub from_time {
   my $time = shift;

   my $seconds = $time % 60;  $time = ( $time - $seconds ) / 60;
   my $minutes = $time % 60;  $time = ( $time - $minutes ) / 60;
   my $hours   = $time;

   return ( $hours, $minutes, $seconds );
}

sub calculate_end_time {
   my ( $hours, $minutes, $seconds, $interval, $buffer ) = @_;

   my $time = to_time( $hours, $minutes, $seconds );

   $interval *= 60;
   $buffer   *= 60;

   my $rounded = round( $time / $internal ) * $interval;

   if ( abs( $rounded - $time ) < $buffer ) {
      $rounded = $time;
   }

   return from_time( $rounded );
}


text:
Q: How to write SQL Query to join two tables with mappings table and get formatted output with only one row per result? I have three tables.

Table: "Foods"
-----------
ID    Name
-----------
1     Apple
2     Strawberry
3     Celery
4     Peanuts
5     Toffee

Table: "Tags"
------------
ID     Name
------------
A      Sweet
B      Fruit
C      Crunchy

Table: "Mappings"
-------------------------
ID    TagID     FoodID
-------------------------
101   A          1
102   A          2
103   A          5
104   B          2
105   C          1
106   C          3
107   C          4
108   C          5

I'm trying to run a query and get results that are formatted like this:
** DESIRED RESULTS OUTPUT FORMAT **
------------------------------------------------------
ID    Name          IsSweet     IsFruit     IsCrunchy
------------------------------------------------------
1     Apple               1           1             1
2     Strawberry          1           1             0
3     Celery              0           0             1
4     Peanuts             0           0             1
5     Toffee              1           0             1

Here is the query I'm currently using that is not working how I would like:
SELECT foods.id, foods.name,
  IF(tags.name = "Sweet", 1, 0) IsSweet,
  IF(tags.name = "Fruit", 1, 0) IsFruit,
  IF(tags.name="Crunchy", 1, 0) IsCrunchy,
  from Foods, Tags, Mappings
    where Foods.ID = Mappings.FoodID and Mappings.TagID = Tags.ID

I'm getting results like the following, where every food item is repeated N times, once for each tag that exists.
** ACTUAL RESULTS I'M GETTING **
------------------------------------------------------
ID    Name          IsSweet     IsFruit     IsCrunchy
------------------------------------------------------
1     Apple               1           0             0
1     Apple               0           1             0
1     Apple               0           0             1
2     Strawberry          1           0             0
2     Strawberry          0           1             0
3     Celery              0           0             1
4     Peanuts             0           0             1
5     Toffee              1           0             0
5     Toffee              0           0             1

How can I write my query to get the results formatted how I would like? I've tried Outer Joins, and tried to use CASE/WHEN statements or  GROUP BY but I haven't figured it out yet.
Can anyone offer some direction for me please?

A: Apply max:
   SELECT foods.id, foods.name,
        max(IF(tags.name = "Sweet", 1, 0)) IsSweet,
        max(IF(tags.name = "Fruit", 1, 0)) IsFruit,
        max(IF(tags.name="Crunchy", 1, 0)) IsCrunchy
   from Foods, Tags, Mappings
   where Foods.ID = Mappings.FoodID and Mappings.TagID = Tags.ID
   group by foods.id, foods.name

A: Never use commas to separate list of tables. Always use JOINS like:
SELECT foods.id, foods.name,
  MAX(IF(tags.name = "Sweet", 1, 0)) IsSweet,
  MAX(IF(tags.name = "Fruit", 1, 0)) IsFruit,
  MAX(IF(tags.name="Crunchy", 1, 0)) IsCrunchy,
  from Foods
  left join Mappings on Foods.ID = Mappings.FoodID
  left join Tags on Mappings.TagID = Tags.ID
  group by foods.id

This makes it really clear and efficient how the tables are related. Other the result is a cartesian product and the where just filters its output (which is the wrong result).
Welcome to Stack Overflow.
Edit: left joins as per dissussion

A: First, never use commas in the FROM clause.  Always use proper, explicit, standard JOIN syntax.
Second, you can simplify your logic by using the fact that MySQL treats boolean values as integers.
Third, you need GROUP BY:
And finally, the standard delimiter for strings in SQL is the single quote.  Although MySQL supports double quotes as well, you should get used to using single quotes.
So:
select f.id, f.name,
       max(t.name = 'Sweet') as IsSweet,
       max(t.name = 'Fruit') as IsFruit,
       max(t.name = 'Crunchy') as IsCrunchy
from Foods f join
     Mappings m
     on f.ID = m.FoodID join
     Tags t
     on t.ID = m.TagID
group by f.id, f.name


text:
Q: Using striped tabs without header ionic I'm using striped tabs without header, and i'm having this blank space between tabs and content.
so I want to know if I can override the ion-view css, and to fix this blank space.

here is my code :
CODEPEN CODE + DEMO
<ion-tabs class="tabs-striped tabs-top tabs-background-dark tabs-color-energized">

        <ion-tab title="hier"ui-sref="help">
           <ion-nav-view name="help"></ion-nav-view>
        </ion-tab>

        <ion-tab title="aujourd'hui" ui-sref="home">
            <ion-nav-view name="home"> </ion-nav-view>
        </ion-tab>

 <ion-tab title="demain" ui-sref="contact">
            <ion-nav-view name="contact"></ion-nav-view>
        </ion-tab>

    </ion-tabs>

i'm using this css code to put the striped bar up :
.tabs-top >.tabs, .tabs.tabs-top
{
    top: 0 !important;
}

A: Try this:
.has-tabs-top {
  top: 50px!important;
}

You should play with the value to match your needs.


text:
Q: Error en el else en python No entiendo por qué me sale error en el else. Si alguien me puede ayudar se lo agradeceré.
x = 1+4*3+8/2*4+5**2
if x%2==0:
 x=x+1
print(x)
else:
x=x+2
print(x)

A: en Python, la identación no es opcional, un código con errores de identación, es un código que no funciona (en el mejor de los casos).
x = 1 + 4 * 3 + 8 / 2 * 4 + 5**2
if x % 2 == 0:
    x = x + 1
    print( x )
else:
    x = x + 2
    print( x )

Esta es la forma correcta de identar tu código, a lo que está dentro del if o del else se le aplica una sangría.


text:
Q: css filter brightness on image but not text overlay I'm trying to show dimmed images unless on hover, while keeping the overlay text pure white all the time.  I have the following:
css:
.transition-item
{
    filter: brightness(75%);
}

.transition-item:hover
{
    filter: brightness(100%) !important;
}

.image-item img
{
  width: 200px;
}

.category-caption
{
    position: relative;
    width: 200px;
    height: 70px;
    margin-top: -91px;
    z-index: 10;
    text-align: center;
  color: white;
}

html:

Testing

While the brightness effects work, it also effects the image.  Can also be seen as a jsfiddle
I have tried moving the text overlay out of being a child of 'transition-item'. like so:

Testing

It keeps the text pure white, but upon direct hover on the text, the brightness effect on the image is lost.
Is there a way to get the brightness on the image and the pure white text of the overlay working together?
My fallback would be to use 2 different static images already saved with different brightness and switch them using display: none.
I have seen some similar questions and approaches, but none with solutions as specific as I need.
Thanks in advance.

A: you can also reset filter on h2 on :hover

.transition-item,
.transition-item:hover h2 /* added lukily it starts from a parent set at 100% */{
  filter: brightness(75%);
}

.transition-item:hover {
  filter: brightness(100%);
}

.image-item img {
  width: 200px;
}

.category-caption {
  position: relative;
  width: 200px;
  height: 70px;
  margin-top: -91px;
  z-index: 10;
  text-align: center;
  color: white;
}

Testing

or hover selecting only img ?

.transition-item img{
  filter: brightness(75%);
}

.transition-item:hover img {
  filter: brightness(100%);
}

.image-item img {
  width: 200px;
}

.category-caption {
  position: relative;
  width: 200px;
  height: 70px;
  margin-top: -91px;
  z-index: 10;
  text-align: center;
  color: white;
}

Testing


text:
Q: Get URL To Add Inline Style I'm using Blogger and on the "Preview" post page, it is hiding an element with 'display:none'. What I am trying to do, is use javascript to apply 'display:block' to that element during the "Preview".
I have to use javascript, because Blogger doesn't have any kind of XML conditional statement I can use; and default styling cannot be changed.
The URL looks something like this: https://myblogexample.blogspot.com/b/post-preview?token=XXXXXXXXXXXXXXXXXXXXXXXXXX&type=POST
The token is obviously always random. So how can I grab the part of the URL and apply an inline style to a particular element? My javascript skills suck, but this is what I came up with, and it doesn't work...
$(document).ready(function(){
    if((window.location.protocol + "//" + window.location.host + "/b/post-preview) = document.getElementById('Main-Section').style.display = 'block'})
});

A: Your javascript code is not valid, it can't be parsed by the browser.
You are asking to show some part of the page when you are in the page "yourbloghost.com/b/post-preview?token=something", right?
You can do this with something like:
$(document).ready(function(){
    if (window.location.pathname == "/b/post-preview")
    {
        document.getElementById('Main-Section').style.display = 'block';
    }
});

or also:
$(document).ready(function(){
    if (window.location.pathname == "/b/post-preview")
    {
        $("#Main-Section").show();
    }
});


text:
Q: captcha image in zend framework I have the following code,but what I got is broken link ! I have installed GD library and the proper font ! but nothing work ,so how to I can use image captcha in zendframework without broken link ,what the wrong ?
$captcha = new Zend_Form_Element_Captcha('Captcha',array(
        'captcha' => array('captcha' => 'Image', 'wordLen' => 6,
        'timeout' => 300, 'width' => 300, 'height' => 100,
        'imgUrl' => '/captcha',
        'imgDir' => APPLICATION_PATH . '/../public/captcha',
        'font' => APPLICATION_PATH . '/../public/fonts/LiberationSansRegular.ttf')));

//sorry

A: Try using:
'/public/captcha'

Instead of:
APPLICATION_PATH . '/../public/captcha'

--
What I did in my application was add a couple of lines in the main index.php file to have direct access to the public folder using a constant variable:
// Define path to public directory
defined('PUBLIC_PATH')
    || define('PUBLIC_PATH', realpath(dirname(__FILE__) . '/../public'));

Then just use:
PUBLIC_PATH . '/captcha'

A: I found the problem.. It comes from : )
        if ( in_array( strtolower( ini_get( 'magic_quotes_gpc' ) ), array( '1', 'on' ) ) ) {
        $_POST = array_map( 'stripslashes', $_POST );
        $_GET = array_map( 'stripslashes', $_GET );
        $_COOKIE = array_map( 'stripslashes', $_COOKIE );
        }

A: APPLICATION_PATH . '/../public/captcha' must exist and apache/php must have write access to it.


text:
Q: Time-out w/ Gradle deploy of Spring-based web application to WAS Liberty I am trying to write a simple Spring-based web service to run on WAS Liberty 8.5.5.9.  The application is a Gradle project, and I build and deploy the application with the command gradle clean build deploy.  However, this fails with the following message:
[ant:deploy] CWWKM2006I: Deploying application .../userSetting.war to the dropins folder.
[ant:deploy] CWWKM2010I: Searching for CWWKZ0001I.*userSetting in
             /home/lavin/WASLiberty/usr/servers/defaultServer/logs/messages.log.
             This search will timeout after 30 seconds.
[ant:deploy] CWWKM2011E: Timed out searching for CWWKZ0001I.*userSetting in
             /home/lavin/WASLiberty/usr/servers/defaultServer/logs/messages.log.
:deploy FAILED

I do see userSetting.war in the dropins/ folder, but I run into problems trying to start the application, so I assume the deployment is broken.
Can someone please explain what the problem is and how to fix?

A: The tooling here is waiting for up to 30 seconds to see the CWWKZ0001I message, which is the "application XYZ started" message ID.  Since the build script did not find this message in 30 seconds, there are 2 possibilities:

*

*The application failed to start (probably the case)

*The application is taking longer than 30s to start (probably not the case, unless your .war application is massive)

I'll assume that the application simply failed to start, in which case you will want to check the server logs to figure out why the application failed to start. As the console indicates, the message.log can be found at /home/lavin/WASLiberty/usr/servers/defaultServer/logs/messages.log

On a side-note, Liberty 8.5.5.9 is rather old, and the Liberty team has made specific efforts to better support Spring applications since then. In particular, check out this blog post:
Open Liberty Spring Boot Starter
In case you haven't heard of OpenLiberty before, its an open-source subset of WAS Liberty (meaning anything that works on OpenLiberty will work on WAS Liberty).


text:
Q: Tcp Client is not sending second response packet I am working on a tracking device and it is working perfectly when it sends the packet and the server acknowledge it but there is a case when the device needs two acknowledgements against one packet.
I am sending both of two but I don't know why the device is not accepting it because after that the device is sending the login packet.
Note: Login packet is the packet which is sent by the device at the beginning of the connection and also when the device does not receive the desired acknowledgement.Can somebody help me in this matter?
Here is the server side code.
    public async Task ParseAvlDataAsync(TcpClient client, NetworkStream stream , byte[] array)
        {
            var resp = Utils.GetInformationContent(array);
            if (resp.Item2)
            {
                string imei = Utils.BytesToString(resp.Item1);
                Console.WriteLine("IMEI received: " + imei);
                Console.WriteLine("--------------------------------------------");
                var response = Utils.CreateResponse(array);
                await stream.WriteAsync(response, 0, response.Length).ConfigureAwait(false);
                Console.WriteLine("Login response sent");
                while (client.Connected)
                {
                    stream = client.GetStream();
                    byte[] buffer = new byte[client.ReceiveBufferSize];
                    await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);

                        //it can be Location data, status info, alarm data
                        //if it is location data then response will not be sent to the server
                        Console.WriteLine(string.Format("Get {0} Packet", (PROTOCOL_NUMBER)buffer[3]));
                        if ((PROTOCOL_NUMBER)buffer[3] != PROTOCOL_NUMBER.LOCATION_DATA && (PROTOCOL_NUMBER)buffer[3] != PROTOCOL_NUMBER.STRING_INFO)
                        {
                            if (Utils.IsVaidProtocol((PROTOCOL_NUMBER)buffer[3]))
                            {
                                //send first response for every packet
                                response = Utils.CreateResponse(buffer);
                                if ((PROTOCOL_NUMBER)buffer[3] == PROTOCOL_NUMBER.ALARM_DATA)
                                {
                                    //send second response of alarm packet
                                    Utils.SendAlarmSecondResponse(client, buffer);
                                }
                                await stream.WriteAsync(response, 0, response.Length).ConfigureAwait(false);
                                Console.WriteLine(string.Format("{0} response sent.", (PROTOCOL_NUMBER)buffer[3]));
                            }
                            else
                            {
                                client.Close();
                                client.Dispose();
                                Console.WriteLine("Invalid packet recieved : " + buffer[3]);
                                Console.WriteLine(Utils.BytesToString(buffer));
                            }
                        }

                        if (Utils.IsVaidProtocol((PROTOCOL_NUMBER)buffer[3]) && (PROTOCOL_NUMBER)buffer[3] != PROTOCOL_NUMBER.LOGIN_MESSAGE)
                        {
                            Parser.Parse((PROTOCOL_NUMBER)buffer[3], imei, stream, buffer);
                        }
                        else if ((PROTOCOL_NUMBER)buffer[3] != PROTOCOL_NUMBER.LOGIN_MESSAGE)
                        {
                            client.Close();
                            client.Dispose();
                            Console.WriteLine("Invalid protocol : " + (PROTOCOL_NUMBER)buffer[3]);
                        }
                }
            }

        }

   public async static void SendAlarmSecondResponse(TcpClient client , byte[] buffer)
        {
            try
            {
                NetworkStream stream = client.GetStream();
                UInt16 sendCRC = 0;
                int messageLength = buffer[2];
                //skip start bytes, message length.  then go back 4 bytes (CRC and serial number)
                byte[] serialNumber = buffer.Skip(2 + 1 + messageLength - 4).Take(2).ToArray();

                int alarmDataAddressPacketLen = alarmDataAddressResponse.Length - 5;
                alarmDataAddressResponse[2] = (byte)(alarmDataAddressPacketLen & 0xFF);

                serialNumber.CopyTo(alarmDataAddressResponse, alarmDataAddressPacketLen - 1);

                sendCRC = CRCBytes(alarmDataAddressResponse.Skip(2).Take(alarmDataAddressPacketLen - 1).ToArray());

                alarmDataAddressResponse[alarmDataAddressPacketLen + 1] = (byte)((sendCRC >> 8) & 0xFF);
                alarmDataAddressResponse[alarmDataAddressPacketLen + 2] = (byte)((sendCRC) & 0xFF);
                await stream.WriteAsync(alarmDataAddressResponse, 0, alarmDataAddressResponse.Length).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

A: TCP is not message-oriented, it's stream-oriented.
You are likely reading more than one of your application-level "packets" into buffer, and you only parse the first, then throw the rest of the buffer away.
The inverse can also happen; there's no guarantee that you read a full application-level packet with a single read call.


text:
Q: Memory utilization in %(Percentage) in Sun Solaris? I would like to get the memory utilization in sun solaris system in % percentage format.
vmstat 1 1 | tail -1 | awk 'a=`/usr/sbin/prtconf|fgrep Memory|awk '{print $3*1024}'{ print 100-($5/$a)*100}'

Getting below error:
awk: syntax error near line 1
awk: bailing out near line 1

Also, please suggest if any alternative possible for this query?

A: Using Solaris awk (which would not have the -v switch or allow setting variables), and using your original query to start with, you can do:
Percentage of free memory:
a=$(/usr/sbin/prtconf | /usr/bin/awk '/Memory/ {print $3*1024}'); vmstat 1 1 | tail -1 | awk "{print (\$5/$a)*100}"

Percentage of used memory:
a=$(/usr/sbin/prtconf | /usr/bin/awk '/Memory/ {print $3*1024}'); vmstat 1 1 | tail -1 | awk "{print 100-(\$5/$a)*100}"

Assign the variable in shell first, then execute the vmstat query using shell variable substitution.  This requires using the double quotes in the awk and making sure to escape the awk variable.  You also do not need to use fgrep and awk together, awk can do both.
Tested on my Opensolaris I have available, so YMMV.

A: echo ::memstat | mdb -k

Will produce percent usage of memory by kernel, zfs, users and free.
You need to be root.