text:
Q: issues running a face_recogition file using editors and cmd When I run the code below in jupyter, it is excellent, I get the results I want.
real = fr.load_image_file("image.jpg")
unknown = fr.load_image_file("image2.jpg")

# encodings
real_encoding = fr.face_encodings(real)[0]
unk = fr.face_encodings(unknown)[0]

result = fr.compare_faces([real_encoding], unk)

print(result)

but when I copy and paste the same code to an editor(atom the one I am using), and then run it using command prompt, I get an error as shown below
Traceback (most recent call last):
  File "face_recognizer.py", line 13, in <module>
    real_encoding = fr.face_encodings(real)[0]
IndexError: list index out of range

I activated the environment in which I was running the cmd.
Can someone advise me where I maybe going wrong?

A: There was no face captured in the photo.
That is why it throws an exception.


text:
Q: How can I fill an existing table with search relevant entries I currently have some trouble figuring out on how to "refresh" my table when a user enters a search input.
Right now my page pulls the collection from my MongoDB and then iterates over the array of objects. To this point everything works fine:
// Pulls Data from DB
imports: function() {
var importReturn = imports.find({}).fetch();
return importReturn;
}

//Then Iterates over return value and creates an table row for each entry.
//This #each block is also nested in another template.
{{#each imports}}
  {{> tableRowAdmin}}
{{/each}}

Now I added a search bar that until now delivers an object matching to the search entry. But I'm really stuck on how to re-render my template..
//The search bar is within a separated template from the table row template
Template.overviewAdmin.events({
'input .searchInput': function(e){
    var val = event.target.value;
    var object = imports.find(
         {$or:[
    {title: {'$regex': val, $options: 'i' }},
    {"supplier.name": {'$regex': val, $options: 'i'}},
    {"supplier.id": {'$regex': val, $options: 'i'}}
]}
        ).fetch();
    console.log(object);
}
})

//CHANGES:
//Initializing ReactiveVar in global context
var reactiveQuery = new ReactiveVar({});

//Helper Function:
imports: function() {
var importReturn = imports.find(reactiveQuery.curValue).fetch();
return importReturn;
}

//Event:
'input .searchInput': function(e){
    var val = event.target.value;
    console.log(val);
    reactiveQuery.set(
         {$or:[
    {title: {'$regex': val, $options: 'i' }},
    {"supplier.name": {'$regex': val, $options: 'i'}},
    {"supplier.id": {'$regex': val, $options: 'i'}},
]}
        )
    console.log(reactiveQuery);

}

A: The usual implementation is to take advantage of reactivity.
I guess the very first part of your shown code is a helper? In that case, simply use a ReactiveVar instead of {} in your imports.find(). Of course you can initialize your reactive variable with an empty object.
Then simply update (set()) your reactive var with your query string, and reactivity will take care of the rest.
That being said, beware of triggering reactivity too often due to updating on each user input.

Edit after question rev 2:
What does reactiveQuery.curValue gives exactly?
Any reason why not using reactiveQuery.get()?
I believe the reactivity works only when you use the standard get() and set() methods.

redpajama_set_name: RedPajamaStackExchange


text:
Q: unable to install kvm on ubuntu 16.04.02 lts dependencies Ubuntu 16.04.2 LTS (GNU/Linux 4.4.0-70-generic x86_64)
cmd:sudo apt-get update && sudo apt-get dist-upgrade -y

error:
etting up qemu-system-common (1:2.5+dfsg-5ubuntu10.9) ...
insserv: Service mountkernfs has to be enabled to start service qemu-system-x86
insserv: exiting now!
update-rc.d: error: insserv rejected the script header
dpkg: error processing package qemu-system-common (--configure):
 subprocess installed post-installation script returned error exit status 1
dpkg: dependency problems prevent configuration of qemu-system-x86:
 qemu-system-x86 depends on qemu-system-common (>> 2.0.0+dfsg-7~); however:
  Package qemu-system-common is not configured yet.

dpkg: error processing package qemu-system-x86 (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of qemu-kvm:
 qemu-kvm depends on qemu-system-x86 (= 1:2.5+dfsg-5ubuntu10.9); however:
  Package qemu-system-x86 is not configured yet.

dpkg: error processing package qemu-kvm (--configure):
 dependency problems - leaving unconfigured
No apport report written because the error message indicates its a followup error from a previous failure.
                                                                                No apport report written because the error message indicates its a followup error from a previous failure.
                                                    No apport report written because MaxReports is reached already
                                                                                dpkg: dependency problems prevent configuration of python-vm-builder:
 python-vm-builder depends on qemu-kvm | qemu-kvm-extras; however:
  Package qemu-kvm is not configured yet.
  Package qemu-kvm-extras is not installed.

dpkg: error processing package python-vm-builder (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of ubuntu-vm-builder:
 ubuntu-vm-builder depends on python-vm-builder; however:
  Package python-vm-builder is not configured yet.

dpkg: error processing package ubuntu-vm-builder (--configure):
 dependency problems - leaving unconfigured
Setting up libapparmor-perl (2.10.95-0ubuntu2.6) ...
No apport report written because MaxReports is reached already
                                                              Setting up apparmor (2.10.95-0ubuntu2.6) ...
Installing new version of config file /etc/init.d/apparmor ...
Installing new version of config file /etc/init/apparmor.conf ...
update-rc.d: warning: start and stop actions are no longer supported; falling back to defaults
Processing triggers for systemd (229-4ubuntu16) ...
Processing triggers for ureadahead (0.100.0-19) ...
Errors were encountered while processing:
 qemu-system-common
 qemu-system-x86
 qemu-kvm
 python-vm-builder
 ubuntu-vm-builder
E: Sub-process /usr/bin/dpkg returned an error code (1)

A: I had a similar problem and solved with:
sudo update-rc.d mountkernfs.sh defaults
sudo apt-get -f install


text:
Q: Accessing each character in a string in an index in a list I am taking an input fro the user in a list format using:
b=list(map(str,input().strip().split()))

If I give the input as 'abc', all of it is stored at index 0.
I want each character of the string to be stored in a different index, how do I do that?
Output for the statement print(b[0]) is:
abc

What I want is:
a

Thanks in advance!

A: An easy way is to convert it to a list directly:
b=list(input()) # input "abc"
print(b) # ['a', 'b', 'c']
print(b[0]) # a

A: you can do if you have one string :
b = [str(i) for i in input()]
Or if you have a lot of string separated with space :
b = [str(i) for i in input().split()]
like if your input is "abc" or "abc def"
#input "abc" b = ["a","b","c"]
#input "abc def" b = ["a","b","c","d","e","f"]
So what it does is taking every character in the string different that " " and appending it to the list and then you can access every element that you want.

A: If you give multiple strings in one input
In [185]: b=list(map(lambda x: list(x)[0],input().strip().split()))
hi bye

In [186]: b
Out[186]: ['h', 'b']


text:
Q: Mock Single Dependent Function in Jest I have a module which contains two functions where function A calls function B. I only want to mock function B because it's doing some hard to test logic, but keep function A unmocked.
Functions:
export functionB = () => {

}

export functionA = () => {
    return functionB()
}

I know I can update the original file like this but this seems messy to me.
functionB = () => {

}

functionA = () => {
    return exportFunctions.functionB()
}

const exportFunctions = {
  functionA,
  functionB
};

export default exportFunctions;

I'm doing:
jest.mock("functions", () => ({
      ...(jest.requireActual("functions") as object),
      functionB: jest.fn()
}))

But when I test functionA, it's still calling the actual functionB implementation which makes sense. But I don't know how to inject a new definition of functionB into the call without rewriting the function in a mock. Is this possible?
Thanks in advance!


text:
Q: Creating single variable to consolidate multiple classes I have a dictionary (dict1)
dict1={
    'lala':{
            'name':'lala',
            'lula':0xcafecafe,
            },
    'mene':{
            'name':'mene',
            'lula':0xdeadbeef,
            },}

After that i created a register class to parse in the information
class register:
    def __init__(self,name):
        self.name = dict1[name].get('name')
        self.data = dict1[name].get('lula')

    def self_add(self):
        value = self.data + self.data
        print('self_add value : {}'.format(value))

and create a for loop to populate the it
for name, info in dict1.items():
    reg_class = register(name)
    vars()[reg_class.name]=reg_class ##work
    vars()['base_path'+'.'+reg_class.name]= reg_class ## not working

however, when i use vars()[reg_class.name]=reg_class it is working
>>> mene.data
3735928559
>>> hex(mene.data)
'0xdeadbeef'

but when i use vars()['base_path'+'.'+reg_class.name]= reg_class it is not working
>>> base_path.mene.data
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'base_path' is not defined

How can i do that correctly?


text:
Q: как редактировать сообщение бота отправленное в ответ на команду (discord.py) @bot.command()
async def roulette(ctx, message):
    print(message)
    await ctx.send('{0} выпадает'.format(randint(1,6)))
    for i in range(0, 10):
        print(message)
        await message.edit(content=i) # на этой строке возникает ошибка
        sleep(0.2)

Мысль этого вопроса - изменение последнего отправленного сообщения ботом и исправление ошибки.
Заранее спасибо :3

A: Ваша функция принимает 2 аргумента - ctx и message.
Первый (ctx) в функцию передает библиотека Discord-py, когда вы вызываете функцию. Это контекст команды. Из него можно получить канал, сообщение, автора, сервер и другую информацию.
Второй аргумент (message) принимает значение первого слова после !roulette, где ! - префикс вашего бота. То есть, при отправке команды !roulette сообщение1 сообщение2, в переменную message будет записана строка 'сообщение1'.

Ошибка возникает потому, что вы пытаетесь отредактировать не сообщение, а переменную message, которая является простой строкой типа str.
Чтобы все работало корректно, вам нужно создать объект сообщения при его первой отправке:
msg = await ctx.send('{0} выпадает'.format(randint(1,6)))

А затем изменять уже этот объект:
await msg.edit(content=i)


text:
Q: MacBook Wifi dies, computer needs to be restarted I've been having a problem where my wifi dies frequently, and won't turn on again until the computer is restarted.  By "dies" I mean no wifi networks are visible - when you click the WIFI icon, it asks if you want to "Turn on Wifi" even though you never turned it off.  If you click "turn on wifi" nothing happens.  So I've been restarting the computer a lot. It's a 2013 Macbook Pro running OSX Yosemite, but the wifi problem existed before upgrading to Yosemite. I believe it's a hardware problem.
Has anyone else had this issue, and if so, how did you resolve it?

A: Solution that avoids having to restart the computer:
Go to terminal and type
sudo ifconfig en0 down

And enter your password. This will cause the WIFI card to restart and (for me) the connection to be restored.

A: Get your Airport Card replace or you risk your data.
This problem is only going to get worse over time, later causing the Mac to lock up then to a point the Mac will hang during boot.
Every force shutdown you risk losing your files on the delicate HFS+ file system.


text:
Q: Dynamically add new WTForms FieldList entries from user interface I have a flask + wtforms app where I want users to be able to input both a parent object, and an arbitrary number of child objects. I'm not sure what the best way to dynamically create new child form input fields from the user interface.
What I've got so far
Below is a complete working example. (Note: this is an artificial example to highlight all the working parts inside a single .py file, which makes for some pretty messy code. Sorry.)
from flask import Flask, render_template_string
from flask_wtf import FlaskForm
from wtforms import FieldList, FormField, StringField, SubmitField
from wtforms.validators import InputRequired

# Here I'm defining a parent form, AuthorForm, and a child form, BookForm.
# I'm using the FieldList and FormField features of WTForms to allow for multiple
# nested child forms (BookForms) to be attached to the parent (AuthorForm).
class BookForm(FlaskForm):
    title = StringField('title', validators=[InputRequired()])
    genre = StringField('genre', validators=[InputRequired()])

# I'm defining a min_entry of 1 so that new forms contain a blank BookForm entry
class AuthorForm(FlaskForm):
    name = StringField('name', validators=[InputRequired()])
    books = FieldList(FormField(BookForm), min_entries=1)
    submit = SubmitField('Save')

# Here's my Jinja template
html_template_string = """

    <title>stackoverflow example</title>

        <form action="" method="post" role="form">
            {{ form.hidden_tag() }}
            {{ form.name.label }} {{ form.name() }}
            {% for book in form.books %}

                {{ book.title.label }} {{ book.title() }}
                {{ book.genre.label }} {{ book.genre() }}
                {{ book.hidden_tag() }}

            {% endfor %}
            {{ form.submit() }}
        </form>

"""

# Alright, let's start the app and try out the forms
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'

@app.route('/', methods=['GET', 'POST'])
def index():
    form = AuthorForm()
    if form.validate_on_submit():
        for book in form.books.data:
            print(book)
    return render_template_string(html_template_string, form=form)

if __name__ == '__main__':
    app.run()

Where I get stuck
I know how to create new child entries (BookForm entries) on the server side. I could just pass empty dictionaries to my form, and WTForms would generate the inputs for me:
...
form = AuthorForm()
form.books.append_child({})
form.books.append_child({})
form.books.append_child({})
...

Bam, now my page has input fields for three books, and I could've prepopulated their data.
WTForms is generating the form input content before the page is rendered. It works out all the ID's necessary for each input, etc.
If I want a user to be able to click a button and add new instances of BookForm inputs from the user side, after the page has been rendered … how do I go about it? Do I have to manually construct the input fields myself in JavaScript, using what was generated by WTForms as a reference? This seems messy and prone to breakage, or at least to ugly code.
Is there a way for WTForms to render the HTML for new inputs as needed, managing the uniqueness of input tag ID's and such? I could post something back to the server to append blank entries to the form and re-render the page, but that would lose me all of my existing user input, so it doesn't really work. This Stackoverflow question suggests the same thing in the comments, and the same objection is raised.
If this has to be done the ugly manual way, then I can manage that. I just don't want to take a poor approach when there's a better (and maybe even official) solution to this.

A: Sorry for reviving this question, but I wanted to point out that one can implement a similar strategy without using javascript. The idea is to pre-process the form data on submit and then reload the form with the processed data (using the built-in capabilities of wtforms to recreate a form from its data).
One way of doing it can be as follows. Add an extra input field to the form and define an update_self method:
class AuthorForm(FlaskForm):
    name = StringField('name', validators=[InputRequired()])
    books = FieldList(FormField(BookForm), min_entries=1)
    submit = SubmitField('Save')
    addline = SubmitField('Add new line')  # This is the new input

    def update_self(self):
        # read the data in the form
        read_form_data = self.data

        # modify the data as you see fit:
        updated_list = read_form_data['books']
        if read_form_data['addline']:
            updated_list.append({})
        read_form_data['books'] = updated_list

        # reload the form from the modified data
        self.__init__(formdata=None, **read_form_data)
        self.validate()  # the errors on validation are cancelled in the line above

Note: formdata=None is necessary to prevent the FlaskForm to automatically read the data in the form. If you omit it, the form will receive formdata when running the .__init__ method and hence ignore your newly processed data.
In the template, display the new input:
{{ form.addline() }}

In the definition route, call the update_self method as first thing on submit:
@app.route('/', methods=['GET', 'POST'])
def index():
    form = AuthorForm()

    if form.validate_on_submit():
        form.update_self()  # This reloads the form with the processed data
        for book in form.books.data:
            print(book)

    return render_template_string(html_template_string, form=form)

I hope this helps!

A: I understand PERFECTLY what your question, to use pure Flask to achieve this.
But I was at your same situation a couple of months back. And after a lot of research and odd and redundant methods, I found, implementing it will be not only painstaking, but long and hard and any small change or debugging efforts just breaks the whole thing.
I know this isnt exactly what you asked. But, if you are looking to do this through Flask+ jQuery. I'll show you some of the work I did to dynamically load data from HTML front-end via views, hope this can be helpful to you, IF you change your mind and decided to incorporate some jQuery.
This is my form, using HTML and Jinja2 :
<form method="POST" action="">
            {{ form.hidden_tag() }}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">XYZ</legend>

                    {{ form.standard.label(class="form-control-label") }}
                    {{ form.standard(class="form-control form-control-lg") }}

                    {{ form.wps.label(class="form-control-label") }}
                    {{ form.wps(class="form-control form-control-lg") }}

            ...
            </fieldset>

                {{ form.submit(class='btn btn-outline-success') }}

        </form>

This is the view this calls this form :
@app.route("/newqualification/<welder_id>", methods=['GET', 'POST'])
def newqualification(welder_id=None):
    form = #passformhere

        #writemethod.

    return render_template('xyz.html', title='xyz', form=form)

And this is the little helpful jQuery Script I wrote which you can include in the HTML via

Using jQuery and the getJSON() method, i am able to send a request to this view :
@app.route("/modifywps", methods=['POST', 'GET'])
def modifywps():
    application_standard_id = request.args.get('std') # gets value from the getJson()

   # process it however you want..

    return #whatever you want.

So every time there is a change, data is read dynamically off the site, sent to a Flask view, processed there with whatever you want, sent back the the same getJSON() and inserted right into the form!!
Voila, you have dynamically used jQuery+Flask to manipulate whatever you want to do, using your new best friend, JSON.
After a lot of research, i found the simplest way to do what you want above, is through jQuery.
Learn getJSON() and post() methods in jQuery, incorporate it into your HTML and you have your answer.
And also jsonify() which i believe you can import in Python via import json.
Feed a list to jsonify() which you can use to return as the view in the same getJSON() you used to send the data.


text:
Q: Run function on enter press I have a jQuery button function that works properly and executes the code inside, what I want is when I press the Enter on the search box, it will execute the same function inside the onclick one. I don't want to copy paste the entire code of my function to the on Enter press event because that will be the wrong way to do it. This is the click event:
$("#checkScout").click(function(e){
 ...
}

And this is the one I tried with the on enter press
var enterKey = document.getElementById("addChannelsToScout");
enterKey.addEventListener("keydown", function (e) {
    if (e.keyCode === 13) {
        $("#checkScout").click(function (e);
    }
});

A: it should be just
$("#checkScout").click();

so
$('#addChannelsToScout').keydown(function (e) {
    if (e.which == 13) {
        $("#checkScout").click();
        //$("#checkScout").trigger('click');
    }
})

Demo: Fiddle

A: Try:
$("#checkScout").trigger('click');

Trigger Performance

A: Change:
 $("#checkScout").click(function(e);

To:
  $("#checkScout").click();

Your code:
var enterKey = document.getElementById("addChannelsToScout");
    enterKey.addEventListener("keydown", function (e) {
        if (e.keyCode === 13)
        {
          $("#checkScout").click();//modified here
        }
    });

A: just this will work $("#checkScout").click();
var enterKey = document.getElementById("addChannelsToScout");
    enterKey.addEventListener("keydown", function (e) {
        if (e.keyCode === 13)
        {
          $("#checkScout").click();
        }
    });

A: actually you need to trigger the event. since it is already been handled it will perform the task that you have written in the event
Check Triggers here http://api.jquery.com/trigger/
$("#checkScout").trigger("click");


text:
Q: Why is select() ignoring the timeout value? I'm new to networking and I want to write a simple, Client-side TCP/IP script; however, I encounter an issue when using select() to receive the server's answer.
I want to use select because I need the timeout functionality. I am using select() in a custom function with a non-zero timeout value, generating a DLL out of it, then calling the function in a client main().
Everything works as intended, except the timeout. Either I receive the message instantly (which is good), or the select() function times out instantly (which is not). It seems to me like the timeout value is not taken into account at all.
Here is the code I am using. I included the function in which select() is placed, as well as the client-side implementation.
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <Windows.h>
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <time.h>

#pragma comment(lib, "Ws2_32.lib")

int ReceiveClientMessage()
{
  int iResult = -1;

  FD_SET ReadSet;
  int Socket_notifs = 0;
  struct timeval timeout;

  timeout.tv_sec = 20000000;
  timeout.tv_usec = 0;
  FD_ZERO(&ReadSet);
  FD_SET(socket_Client, &ReadSet);

  Socket_notifs = select(0, &ReadSet, NULL, NULL, &timeout);
  if (Socket_notifs == SOCKET_ERROR)
  {
    printf("Select returned with error %d\n", WSAGetLastError());
    return 1;
  }
  printf("Select successful\n");

  if (Socket_notifs > 0)
  {
    int receiving_buffer_length = DEFAULT_BUFLEN;
    char receiving_buffer[DEFAULT_BUFLEN] = "";

    // Start receiving
    iResult = recv(socket_Client, receiving_buffer, receiving_buffer_length, 0);
    if (iResult > 0)
      // Message received, display save yada yada
    else
      // Error receiving
  }
  else if (Socket_notifs == 0)
  {
    // Timeout
    printf("Select timed out\n\n");
    return 2;
  }
  else
  {
    // Other issue with select
    printf("Unknown error with Select\n\n");
    return 3;
  }

  return 0;
}

//----------------------------------------------------------------
// Client main()

string message, response;

while (true)
{
  /* Part where we send a message, irrelevant here */

  // Receive a message on client side
  iResult = -1;
  iResult = ReceiveClientMessage();
  cout << iResult << endl;
  if (iResult != 0)
    // Error, clean up and break
  else
    // Display message
}

I tried to remove most irrelevant parts of my code, and only left the parts relevant to the select, timeout and receive implementation.
I have already tried setting various values for timeout.tv_sec and timeout.tv_usec (from 20 to 20000000), in case it wasn't a value in seconds or something, without results. Sometimes I send a message, and instantly see the "Select timed out" prompt (which, from my understanding, should not happen). Any idea on how to solve this (either by finding out why the timeout values are not taken into account, or by using another method that has a timeout functionality)?


text:
Q: 5 columns - 3 fixed width columns & 2 fluid I'm looking to create a fluid layout, with 3 fixed width columns & 2 fluid.
5 columns in total.
I've had a play with 'display: table-cell;', which worked in Chrome but Broke in FF.

section.how-to .steps { max-width:1400px; width:100%; padding:10px 3%; box-sizing: border-box; height:350px}
section.how-to .steps > div {  display: table-cell;}
section.how-to .steps .step {  min-width:262px}
section.how-to .steps .filler {  height:200px; width:50%}

Could anyone suggest a cross browser approach. (Webkit, FF, IE8 +)
Thanks Cam

A: Hi I have come up with a solution that seems to work in all major browsers:
jsFiddle
Html

        col 1

                    col 2

                    col 3

col 4

        col 5

CSS
.container {padding:0 62px;} /*I have used 62px - just change to 262px (all 62s below too);*/
.fixedWidth {width:62px; height:200px; background-color:red;} /*height and bg-color just to show what's happening*/

#LeftColumn {float:left; margin-left:-62px;}
#RightColumn {float:right; margin-right:-62px;}
#CenterColumn {float:left; width:100%;}

.centerColumn {width:50%; float:left; background-color:blue; position:relative;}
#CenterLeft {z-index:2;}
#CenterRight {z-index:1;}
#CenterLeft .padded {padding-right:31px;} /*padding should be half width of fixed column*/
#CenterLeft .content {float:left;}
#CenterLeft .fixedWidth {float:right; margin-right:-62px;}
#CenterRight .padded {padding-left:31px;} /*padding should be half width of fixed column*/
.content {width:100%;}

.clearSpacer {clear:both; height:0; overflow:hidden;}


text:
Q: java.io.IOException: request to write '' bytes exceeds size in header of '' bytes for entry '' I am creating a tar.Gzip file using GZIPOutputStream and I have added an another logic in that if any Exception caught while compressing file then, my code will retry three times.
When I am throwing an IOException to test my retry logic it throwing a below Exception:
java.io.IOException: request to write '4096' bytes exceeds size in header of '2644' bytes for entry 'Alldbtypes'
I am getting Exception at line: org.apache.commons.io.IOUtils.copyLarge(inputStream, tarStream);
private class CompressionStream extends GZIPOutputStream {
    // Use compression levels from the deflator class
    public CompressionStream(OutputStream out, int compressionLevel) throws IOException {
        super(out);
        def.setLevel(compressionLevel);
    }
}

public void createTAR(){
    boolean isSuccessful=false;
    int count = 0;
    int maxTries = 3;
    while(!isSuccessful) {
        InputStream inputStream =null;
        FileOutputStream outputStream =null;
        CompressionStream compressionStream=null;
        OutputStream md5OutputStream = null;
        TarArchiveOutputStream tarStream = null;
        try{
            inputStream = new BufferedInputStream(new FileInputStream(rawfile));
            File stagingPath = new File("C:\\Workarea\\6d22b6a3-564f-42b4-be83-9e1573a718cd\\b88beb62-aa65-4ad5-b46c-4f2e9c892259.tar.gz");
            boolean isDeleted = false;
            if(stagingPath.exists()){
                isDeleted =  stagingPath.delete();
                if(stagingPath.exists()){
                    try {
                        FileUtils.forceDelete(stagingPath);
                    }catch (IOException ex){
                        //ignore
                    }
                }
            }
            outputStream = new FileOutputStream(stagingPath);
            if (isCompressionEnabled) {
                compressionStream = new
                        CompressionStream(outputStream, getCompressionLevel(om));
            }
            final MessageDigest outputDigest = MessageDigest.getInstance("MD5");
            md5OutputStream = new DigestOutputStream(isCompressionEnabled ? compressionStream : outputStream, outputDigest);
            tarStream = new TarArchiveOutputStream(new BufferedOutputStream(md5OutputStream));
            tarStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
            tarStream.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
            TarArchiveEntry entry = new TarArchiveEntry("Alldbtypes");
            entry.setSize(getOriginalSize());
            entry.setModTime(getLastModified().getMillis());
            tarStream.putArchiveEntry(entry);
            org.apache.commons.io.IOUtils.copyLarge(inputStream, tarStream);
            inputStream.close();
            tarStream.closeArchiveEntry();
            tarStream.finish();
            tarStream.close();
            String digest = Hex.encodeHexString(outputDigest.digest());
            setChecksum(digest);
            setIngested(DateTime.now());
            setOriginalSize(FileUtils.sizeOf(stagingPath));
            isSuccessful =true;
        } catch (IOException e) {
            if (++count == maxTries) {
                throw new RuntimeException("Exception: " + e.getMessage(), e);
            }
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(Exception("MD5 hash algo not installed.");
        } catch (Exception e) {
            throw new RuntimeException("Exception: " + e.getMessage(), e);
        } finally {
            org.apache.commons.io.IOUtils.closeQuietly(inputStream);
            try {
                tarStream.flush();
                tarStream.finish();
            } catch (IOException e) {
                e.printStackTrace();
            }
            org.apache.commons.io.IOUtils.closeQuietly(tarStream);
            org.apache.commons.io.IOUtils.closeQuietly(compressionStream);
            org.apache.commons.io.IOUtils.closeQuietly(md5OutputStream);
            org.apache.commons.io.IOUtils.closeQuietly(outputStream);
        }

    }
}

A: Case solved. This Exception java.io.IOException: request to write '4096' bytes exceeds size in header of '2644' bytes for entry 'Alldbtypes' thrown when the size of the file that going to be zipped is incorrect.
TarArchiveEntry entry = new TarArchiveEntry("Alldbtypes");
entry.setSize(getOriginalSize());

In my code getOriginalSize() is getting updated again at the end so in retry the original size became change and original size is now zipped file size so it was throwing this Exception.


text:
Q: Display a list of sub-pages on the current page based on the WP menu I have created a menu under Appearance > menus called "Sidebar Menu Collection"
This is their heirarchy
Material
- marble
- onyx
- slate
- granite

Applications
- benchtops
- floors
- walls

products
- Slab
- pavers
- cladding

So when I am on the page "Material" I would like to have a list of its child menu (marble,onyx,slate,grantite) only.
If I'm in "Applications" page it would show (benctops,floors,walls). And so on, I would like to add a featured image on every child list based on the page featured image.
Also this will be applicable only to the parent menu (Material,Applications,Products) and if your on the sub-menu no list will be shown

A: Hello use below code will only show childs of specific pages
wp_list_pages( $args = '' ) {
    $defaults = array(
        'depth'        => 1,
        'show_date'    => '',
        'date_format'  => get_option( 'date_format' ),
        'child_of'     => $post->ID,
        'exclude'      => '',
        'title_li'     => __( 'Pages' ),
        'echo'         => 1,
        'authors'      => '',
        'sort_column'  => 'menu_order, post_title',
        'link_before'  => '',
        'link_after'   => '',
        'item_spacing' => 'preserve',
        'walker'       => '',
    );

A: Already had an answer to this, came from this post.
This is working perfectly, the only problem I have now is how to add a featured image on every link.
// add hook
add_filter( 'wp_nav_menu_objects', 'my_wp_nav_menu_objects_sub_menu', 10, 2 );
// filter_hook function to react on sub_menu flag
function my_wp_nav_menu_objects_sub_menu( $sorted_menu_items, $args ) {
  if ( isset( $args->sub_menu ) ) {
    $root_id = 0;

    // find the current menu item
    foreach ( $sorted_menu_items as $menu_item ) {
      if ( $menu_item->current ) {
        // set the root id based on whether the current menu item has a parent or not
        $root_id = ( $menu_item->menu_item_parent ) ? $menu_item->menu_item_parent : $menu_item->ID;
        break;
      }
    }

    // find the top level parent
    if ( ! isset( $args->direct_parent ) ) {
      $prev_root_id = $root_id;
      while ( $prev_root_id != 0 ) {
        foreach ( $sorted_menu_items as $menu_item ) {
          if ( $menu_item->ID == $prev_root_id ) {
            $prev_root_id = $menu_item->menu_item_parent;
            // don't set the root_id to 0 if we've reached the top of the menu
            if ( $prev_root_id != 0 ) $root_id = $menu_item->menu_item_parent;
            break;
          }
        }
      }
    }
    $menu_item_parents = array();
    foreach ( $sorted_menu_items as $key => $item ) {
      // init menu_item_parents
      if ( $item->ID == $root_id ) $menu_item_parents[] = $item->ID;
      if ( in_array( $item->menu_item_parent, $menu_item_parents ) ) {
        // part of sub-tree: keep!
        $menu_item_parents[] = $item->ID;
      } else if ( ! ( isset( $args->show_parent ) && in_array( $item->ID, $menu_item_parents ) ) ) {
        // not part of sub-tree: away with it!
        unset( $sorted_menu_items[$key] );
      }
    }

    return $sorted_menu_items;
  } else {
    return $sorted_menu_items;
  }
}

Usage
wp_nav_menu( array(
  'menu'     => 'Menu Name',
  'sub_menu' => true
) );


text:
Q: Custom Function not working on Stripping Text I have the need to clean-up a pandas dataframe, in which there are several columns that need some data to be removed or stripped. To make a cleaner code I'm trying to create a function that can make some cleaning and return a new columns with only the stripped info I need.
As can be seen in the following code, I have tried to rewrite the code in different ways (also using lambda functions), but unfortunately I have found no fortune. I always get the error 'str' object has no attribute 'str'
import pandas as pd

def cleaner(x):
    x = str(x)
    x = x.str.split('/').str[1]
    return x

data = ["First/A", "Second/B", "Third/C"]

dataframe = pd.DataFrame(data)

dataframe.columns = ["Source"]

dataframe["Destination"] = dataframe["Source"].apply(cleaner)

What I'm expecting is to get a new column (destination) with only the "A", "B" "C" value.

A: There is no need to specify .str for variable x since it is a string object.
def cleaner(x):
    x = str(x)
    #x = x.str.split('/').str[1]
    x = x.split('/')[1]
    return x

dataframe["Destination"] = dataframe["Source"].apply(cleaner)

Moreover, this can easily be reduced to,
dataframe["Destination"] = dataframe["Source"].str.split('/').str[1]

A: Try this:
import pandas as pd

def cleaner(x):
    x = x.split('/')[1]
    return x

data = ["First/A", "Second/B", "Third/C"]

dataframe = pd.DataFrame(data)

dataframe.columns = ["Source"]

dataframe["Destination"] = dataframe.apply(lambda x: cleaner(x['Source']), axis=1)


text:
Q: Magento Block Coming with empty output I have created simple News Module. which serves functionality from frontend as well as backend. Admin functionality works fine.
But in frontend,

*

*I have two pages.
i) News List page
ii) News Detail Page

Here News list page is working perfect. But the News detail page is coming with empty result.
I can get the result from database tables using model but could not render it to the template file.
Config File
<?xml version="1.0"?>

<config>
    <modules>
        <Magentostudy_News>
            <version>1.0.0.0.1</version>
        </Magentostudy_News>
    </modules>
    <global>
        <models>
            <magentostudy_news>
                <class>Magentostudy_News_Model</class>
                <resourceModel>news_resource</resourceModel>
            </magentostudy_news>
            <news_resource>
                <class>Magentostudy_News_Model_Resource</class>
                <entities>
                    <news>

magentostudy_news

                    </news>
                </entities>
            </news_resource>
        </models>
        <helpers>
            <magentostudy_news>
                <class>Magentostudy_News_Helper</class>
            </magentostudy_news>
        </helpers>
        <blocks>
            <magentostudy_news>
                <class>Magentostudy_News_Block</class>
            </magentostudy_news>
        </blocks>
        <resources>
            <magentostudy_news_setup>
                <setup>
                    <module>Magentostudy_News</module>
                    <class>Mage_Core_Model_Resource_Setup</class>
                </setup>
            </magentostudy_news_setup>
        </resources>

    </global>
    <frontend>
        <routers>
            <magentostudy_news>
                <use>standard</use>
                <args>
                    <module>Magentostudy_News</module>
                    <frontName>news</frontName>
                </args>
            </magentostudy_news>
        </routers>
        <layout>
            <updates>
                <magentostudy_news>
                    <file>magentostudy_news.xml</file>
                </magentostudy_news>
            </updates>
        </layout>
    </frontend>
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <Magentostudy_News before="Mage_Adminhtml">Magentostudy_News_Adminhtml</Magentostudy_News>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>
    <adminhtml>
        <layout>
            <updates>
                <magentostudy_news>
                    <file>magentostudy_news.xml</file>
                </magentostudy_news>
            </updates>
        </layout>
    </adminhtml>
    <default>
        <news>
            <view>
                <enabled>1</enabled>
                <items_per_page>20</items_per_page>
                <days_difference>3</days_difference>
            </view>
        </news>
    </default>
</config>

Index Controller
<?php
 /**
 * News frontend controller
 *
 * @author Magento
 */
class Magentostudy_News_IndexController extends Mage_Core_Controller_Front_Action
{
    /**
     * Pre dispatch action that allows to redirect to no route page in case of disabled extension through admin panel
     */
    public function preDispatch()
    {
        parent::preDispatch();

        if (!Mage::helper('magentostudy_news')->isEnabled()) {
            $this->setFlag('', 'no-dispatch', true);
            $this->_redirect('noRoute');
        }
    }

    /**
     * Index action
     */
    public function indexAction()
    {
        $this->loadLayout();

        $listBlock = $this->getLayout()->getBlock('news.list');

        if ($listBlock) {
            $currentPage = abs(intval($this->getRequest()->getParam('p')));
            if ($currentPage < 1) {
                $currentPage = 1;
            }
            $listBlock->setCurrentPage($currentPage);
        }

        $this->renderLayout();
    }

    /**
     * News view action
     */
    public function viewAction()
    {
        $newsId = $this->getRequest()->getParam('id');
        if (!$newsId) {
            return $this->_forward('noRoute');
        }

        /** @var $model Magentostudy_News_Model_News */
        $model = Mage::getModel('magentostudy_news/news');
        $model->load($newsId);

        if (!$model->getId()) {
            return $this->_forward('noRoute');
        }

        Mage::register('news_item', $model);

        Mage::dispatchEvent('before_news_item_display', array('news_item' => $model));

        $this->loadLayout();
        $itemBlock = $this->getLayout()->getBlock('news.item');
        if ($itemBlock) {
            $listBlock = $this->getLayout()->getBlock('news.list');
            if ($listBlock) {
                $page = (int)$listBlock->getCurrentPage() ? (int)$listBlock->getCurrentPage() : 1;
            } else {
                $page = 1;
            }
            $itemBlock->setPage($page);
        }
        $this->renderLayout();
    }
}

Block File: Item.php
<?php
/**
 * News Item block
 *
 * @author Magento
 */
class Magentostudy_News_Block_Item extends Mage_Core_Block_Template
{

    /**
     * Current news item instance
     *
     * @var Magentostudy_News_Model_News
     */
    protected $_item;

    /**
     * Return parameters for back url
     *
     * @param array $additionalParams
     * @return array
     */
    protected function _getBackUrlQueryParams($additionalParams = array())
    {
        return array_merge(array('p' => $this->getPage()), $additionalParams);
    }

    /**
     * Return URL to the news list page
     *
     * @return string
     */
    public function getBackUrl()
    {
        return $this->getUrl('*/', array('_query' => $this->_getBackUrlQueryParams()));
    }

    /**
     * Return URL for resized News Item image
     *
     * @param Magentostudy_News_Model_News $item
     * @param integer $width
     * @return string|false
     */
    public function getImageUrl($item, $width)
    {
        return Mage::helper('magentostudy_news/image')->resize($item, $width);
    }
}

Layout File: Magentostudy_news.xml
<?xml version="1.0"?>

    <layout version="0.1.0">

        <default>
             <reference name="footer_links">
                 <action method="addLink" translate="label title" module="magentostudy_news" ifconfig="news/view/enabled">
                     News
                     <url>news</url>
                     <title>News</title>
                     <prepare>true</prepare>
                 </action>
             </reference>
        </default>

        <magentostudy_news_index_index translate="label">
            News Page
            <reference name="root">
                <action method="setTemplate">
                    <template>page/2columns-right.phtml</template>
                </action>
                <action method="setHeaderTitle" translate="title" module="magentostudy_news">
                    <title>Site News</title>
                </action>
            </reference>

            <reference name="content">
                <block type="magentostudy_news/list" name="news.list" template="magentostudy/news/list.phtml">
                    <block type="page/html_pager" name="news.list.pager" as="news_list_pager" />
                </block>
            </reference>
        </magentostudy_news_index_index>

        <magentostudy_news_index_view translate="label">
            News Item Page
            <reference name="root">
                <action method="setTemplate">
                    <template>page/2columns-right.phtml</template>
                </action>
            </reference>
            <reference name="content">
                <block type="magentostudy_news/news" name="news.item" template="magentostudy/news/item.phtml" />
            </reference>
        </magentostudy_news_index_view>

    </layout>

News/item.phtml
<?php
/**
 * News template for separate item
 *
 * @author Magento
 */
/**
 * @var $this Magentostudy_News_Block_Item
 * @see Magentostudy_News_Block_Item
 */
?>
<?php $_newsItem = $this->helper('magentostudy_news')->getNewsItemInstance();
?>

<?php echo $this->getMessagesBlock()->getGroupedHtml() ?>

<?php echo $this->escapeHtml($_newsItem->getTitle()) ?>

        <?php echo $this->formatDate($_newsItem->getTimePublished(),
Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM) ?> |
        <?php echo $this->escapeHtml($_newsItem->getAuthor()) ?>

    <?php if ($imageUrl = $this->getImageUrl($_newsItem, 400)): ?>

<img src="<?php echo $imageUrl ?>" alt="<?php echo $this->escapeHtml($_newsItem->getTitle()) ?>" />

    <?php endif; ?>

<?php echo $_newsItem->getContent() ?>

        <a href="<?php echo $this->getBackUrl() ?>">
             <?php echo Mage::helper('magentostudy_news')->__('Return to list') ?>

A: Why do you have setPage in your view?
    $this->loadLayout();
    $itemBlock = $this->getLayout()->getBlock('news.item');
    if ($itemBlock) {
        $listBlock = $this->getLayout()->getBlock('news.list');
        if ($listBlock) {
            $page = (int)$listBlock->getCurrentPage() ? (int)$listBlock->getCurrentPage() : 1;
        } else {
            $page = 1;
        }
        $itemBlock->setPage($page);

Have you tried removing it?
    $this->loadLayout();
    $itemBlock = $this->getLayout()->getBlock('news.item');
    /* if ($itemBlock) {
        $listBlock = $this->getLayout()->getBlock('news.list');
        if ($listBlock) {
            $page = (int)$listBlock->getCurrentPage() ? (int)$listBlock->getCurrentPage() : 1;
        } else {
            $page = 1;
        }
        $itemBlock->setPage($page);
    */


text:
Q: Text Scraping using Python: Regex I have a dynamic text which looks something like this
my_text = "address ae fae daq ad, 1231 asdas  landline 213121233 -123    mobile 513121233 cell (132) -142-3127
           email sdasdas@gmail.com , sdasd as@yahoo.com - ewqas@gmail.com"

The text starts with an 'address'. As soon as we see 'address' we need to scrape everything from there until either 'landline'/'mobile'/'cell' appears. From there on, we want to scrape when all the phone text (without altering spaces in between). We start from the first occurrence of either 'landline'/'mobile'/'cell' and stop as soon as we find 'email' appear.
Finally we scrape the email part (without altering spaces in between)
'landline'/'mobile'/'cell' can appear in any order and sometimes some may not appear.
For example, the text could have looked like this as well.
my_text = "address ae fae daq ad, 1231 asdas
           cell (132) -142-3127 landline 213121233 -123
           email sdasdas@gmail.com , sdasd as@yahoo.com - ewqas@gmail.com"

There's a little more engineering that needs to be done to form arrays of subtext contained in address, phones and email text.
Subtexts of addresses are always separated with commas (,).
Subtexts of emails can be separated with commas (,) or hyphens (-).
My output should be a JSON dictionary which looks something like this:
resultant_dict = {
                      addresses: [
                                  { address: "ae fae daq ad" }
                                , { address: "1231 asdas" }
                               ]
                    , phones: [
                                  { number: "213121233 -123", kind: "landline" }
                                , { number: "513121233", kind: "mobile" }
                                , { number: "(132 -142-3127", kind: "cell" }
                             ]
                    , emails: [
                                  { email: "sdasdas@gmail.com", connector: "" }
                                , { email: "sdasd as@yahoo.com", connector: "," }
                                , { email: "ewqas@gmail.com", connector: "-" }
                              ]
}

I am trying to achieve this thing using regular expressions or any other way in Python. I can't figure out how to write this as I am a novice programmer.

A: This is not a good job for regular expressions since the components you want to parse out of the input can appear in any order and any number.
Consider using a lexing and parsing library such as the pyPEG parsing expression grammar.
Another approach would use str.split() or re.split() to split the input text into tokens. Then scan through those tokens looking for your keywords like address, cell, and ,, accumulating the following tokens until the next keyword. This approach lets split() do the first part of the tokenizing work, leaving you to do the rest of the lexical work (by recognizing keywords) and the parsing work manually.
The manual approach is more instructive but more verbose and less flexible. It goes like this:
text = """address ae fae daq ad, 1231 asdas
           cell (132) -142-3127 landline 213121233 -123
           email sdasdas@gmail.com , sdasd as@yahoo.com - ewqas@gmail.com"""

class Scraper:
    def __init__(self):
        self.current = []
        self.current_type = None

    def emit(self):
        if self.current:
            # TODO: Add the new item to a dictionary.
            # Later, translate the dictionary to JSON format.
            print(self.current_type, self.current)

    def scrape(self, input_text):
        tokens = input_text.split()
        for token in tokens:
            if token in ('address', 'cell', 'landline', 'email'):
                self.emit()
                self.current = []
                self.current_type = token
            else:
                self.current.append(token)
        self.emit()

s = Scraper()
s.scrape(text)

This emits:
address ['ae', 'fae', 'daq', 'ad,', '1231', 'asdas']
cell ['(132)', '-142-3127']
landline ['213121233', '-123']
email ['sdasdas@gmail.com', ',', 'sdasd', 'as@yahoo.com', '-', 'ewqas@gmail.com']

You'll want to use re.split() to make it split 'ad,' into ['ad', ','], add code to handle tokens like ,, and use a library to convert the dictionary to JSON format.

A: This will work as long as there are no spaces in your emails
import re
my_text = 'address ae fae daq ad, 1231 asdas  landline 213121233 -123    mobile 513121233 cell (132) -142-3127  email sdasdas@gmail.com , sdasdas@yahoo.com - ewqas@gmail.com'

split_words = ['address', 'landline', 'mobile', 'cell', 'email']
resultant_dict = {'addresses': [], 'phones': [], 'emails': []}

for sw in split_words:

    text = filter(None, my_text.split(sw))
    text = text[0].strip() if len(text) < 2 else text[1].strip()
    next_split = [x.strip() for x in text.split() if x.strip() in split_words]

    if next_split:
        text = text.split(next_split[0])[0].strip()

    if sw in ['address']:
        text = text.split(',')
        for t in text:
            resultant_dict['addresses'].append({'address': t.strip()})

    elif sw in ['landline', 'mobile', 'cell']:
        resultant_dict['phones'].append({'number': text, 'kind': sw})

    elif sw in ['email']:

        connectors = [',', '-']
        emails = re.split('|'.join(connectors), text)
        text = filter(None, [x.strip() for x in text.split()])

        for email in emails:

            email = email.strip()
            connector = ''
            index = text.index(email) if email in text else 0

            if index > 0:
                connector = text[index - 1]

            resultant_dict['emails'].append({'email': email, 'connector': connector})

print resultant_dict


text:
Q: Fetch Data From Mysql Table Using WSO2-DSS Wso2  DSS Fetch Data From Table
Please Help

I have a table named "Address". I want to fetch the all details(all coulmns) from this table using service created through wso2 dss.

I have to get the responce in json format.

I Have tried it ,but not getting the result

pls help

A: You can check the wso2dss documentation on how to create a DSS and how to return a JSON message. If you face any issue, please post the error stack.
WSO2 DSS distribution comes with default RDBMS sample. you can try that too.

A: As told by ratha, you can try the sample & understand how it is created. or else you post your table schema and anyone can post xml of that service.
For JSON reponse you need not worry much, you just need to pass one "Accept:application/json" header while calling dss service. first try to get output from dss service.


text:
Q: How to let the program wait to receive the serial port data? Edited:
I am working on a program that will receive data from serial port, the data will end in "\r\n". I am using Data_Received event to receive the data from the serial port.
Below is my program, I am try to avoid to use Thread.Sleep and use thread to wait for the data fully receive, but the step always jump to the return "Error" step.
I would like to know how to let the program to wait for the data fully receive before it jump to the return "Error" step?
It will be fine if don't use thread and if someone have a better method to do.
using System;
using System.Windows.Forms;
using System.IO.Ports;

namespace SerialPortExample
{

public partial class Form1 : Form
{

string port1ReceivedMessage = string.Empty;

internal delegate void SerialDataReceivedEventHandlerDelegate(
                 object sender, SerialDataReceivedEventArgs e);

SerialPort comPort = new SerialPort();

string InputData = string.Empty;
delegate void SetTextCallBack(string text);

public Form1()
{
    InitializeComponent();

   comPort.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

}

~Form1()
{
    comPort.Close();
}

public string SendDataAndReadData()
{
    port1ReceivedMessage = string.Empty;

    string sendData = "?";
    Send(sendData); // To send data

    Thread t = new Thread(ThreadProc);
    t.Name = "Thread_1";
    t.Start();

    //Thread.Sleep(1000);

    if(!string.IsNullOrEmpty(port1ReceivedMessage) && port1ReceivedMessage.Contains("\n"))
    {
        event_1.Set();
        return port1ReceivedMessage;
    }

    return "Error";

}

private void ThreadProc()
{

    event_1.WaitOne();

}

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    InputData = comPort.ReadExisting();

    if(InputData != string.Empty)
    {
      try
      {

      this.BeginInvoke(new SetTextCallBack(SetText), new object[] { InputData });
      }
     catch (TimeoutException timeoutEx)
     {
        //Skip exception handling codes
     }
     catch (Exception ex)
     {
        //Skip exception handling codes
     }
    }
}

private void SetText(string text)
{
    port1ReceivedMessage += text;
}

private void portOpenButton_Click(object sender, EventArgs e)
{
    comport = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
    comport.ReadTimeout = 2000;
    if (!comport.IsOpen)
    {
        comport.Open();
    }

 }

private void sendButton_Click(object sender, EventArgs e)
{
   SendDataAndReadData();
}

private void Send(string text)
{
    // Skip some text formatting codes
    comPort.Write(text);
}

}

A: The DataRecieved event fires somewhat randomely.  You won't always get the whole string when it fires.  Thankfully, you know what your message looks like once you have the whole thing. You need to build up your string until you see a /r/n then do what you need to do once you know you have the whole string.
private StringBuilder sb;
private SerialPort sp;

public void init_state_machine()
{
    sp = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
    sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);

    sb = new StringBuilder();
    sb.Clear();
}

private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    string currentLine = "";
    string Data = sp.ReadExisting();

    Data.Replace("\n", ""); //remove new lines

    foreach (char c in Data)
    {
        if (c == '\r')
        {
            currentLine = sb.ToString();
            sb.Clear();

            Console.WriteLine(currentLine);
        }
        else
        {
            sb.Append(c);
        }
    }
}

As for sending, you can just do your send and when the device responds your DataRecieved event will fire.  The DataRecieved event is already in its own thread so you don't need to handle all the threading stuff you are trying to do.

A: Please read:
If you must use .NET System.IO.Ports.SerialPort.
That is a blog post from Ben Voigt written 2014 on sparxeng.com.
Excerpt:

To put it mildly, System.IO.Ports.SerialPort was designed by computer scientists operating far outside their area of core competence.  They neither understood the characteristics of serial communication, nor common use cases, and it shows.  Nor could it have been tested in any real world scenario prior to shipping, without finding flaws that litter both the documented interface and the undocumented behavior and make reliable communication using System.IO.Ports.SerialPort (henceforth IOPSP) a real nightmare.

and

The worst offending System.IO.Ports.SerialPort members, ones that not only should not be used but are signs of a deep code smell and the need to rearchitect all IOPSP usage:

*

*The DataReceived event (100% redundant, also completely unreliable)

*The BytesToRead property (completely unreliable)

*The Read, ReadExisting, ReadLine methods (handle errors completely wrong, and are synchronous)

*The PinChanged event (delivered out of order with
respect to every interesting thing you might want to know about it)

and

And the one member that no one uses because MSDN gives no example, but is absolutely essential to your sanity:

*

*The BaseStream property

Despite that blame from Ben Voigt, we are using the BytesToRead property and the ReadExisting() including Thread.Sleep(). We avoid DataReceived() and ReadLine(). That was our workaround, we didn't know the BaseStream property as well.
For new projects I would recommend to use the BaseStream property.


text:
Q: How To Reload Table? I have 2 views we are dealing with.  Main View, and Sub View.
Main View's tablecell's string shows the count of the number of objects in that cell's subView.  When I delete a cell from the subview, and go back to the mainView, the string that shows the count should go down by 1.  Right now this string is not changing until I restart the app.
Any ideas how I can fix this?  The count is being pulled from a NSFetch.
Edit: Added Code
- (void)configureCell:(TDBadgedCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    NSDate *today = [NSDate date];
    NSDate *thisWeek  = [today dateByAddingTimeInterval: -604800.0];
    NSDate *thisMonth = [today dateByAddingTimeInterval: -2629743.83];
    else if (indexPath.row == 2)
    {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        self.predicate = [NSPredicate predicateWithFormat:@"(timeStamp >= %@) AND (timeStamp <= %@)", thisWeek, today];
        [fetchRequest setPredicate: predicate];
        [fetchRequest setEntity:[NSEntityDescription entityForName:@"Session" inManagedObjectContext:managedObjectContext]];
        NSError *error = nil;
        NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
        NSLog(@"Fetch error: %@", error);

        cell.badgeString = [NSString stringWithFormat:@"%i", [results count]];
        [fetchRequest release];
    }
    else if (indexPath.row == 3)
    {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        self.predicate = [NSPredicate predicateWithFormat:@"(timeStamp >= %@) AND (timeStamp <= %@)", thisMonth, today];
        [fetchRequest setPredicate:predicate];
        [fetchRequest setEntity:[NSEntityDescription entityForName:@"Session" inManagedObjectContext:managedObjectContext]];

        NSError *error = nil;
        NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
        NSLog(@"Fetch error: %@", error);

        cell.badgeString = [NSString stringWithFormat:@"%i", [results count]];
        [fetchRequest release];
    }
    else if (indexPath.row == 4)
    {
        cell.badgeString = [NSString stringWithFormat:@"%i", [[self.fetchedResultsController fetchedObjects] count]];
    }

A: If your data is in fact being updated correctly on the model side of things, you should be able to call
[tableView reloadData];

and everything will update correctly. You can probably put this in viewWillAppear.
Hope this helps.

A: You need to be sure that you're getting the proper handle on the tableview, if you've made an accessor for your tableview in the header file then you need to call it by that name in the viewWillLoad method.


text:
Q: How to remove any special character from .csv files using java im trying to get minmax values from a csv, but some of the values on the csv is giving me a NumberExpectedException here is the code im using

 private static void minMaxValue(String path) {
        try (Stream<String> stream = Files.lines(Paths.get(path)).skip(1)) {
            DoubleSummaryStatistics statistics = stream
                    .map(s -> s.split(",")[3])
                    .mapToDouble(Double::valueOf)
                    .summaryStatistics();
            System.out.println("Lowest:: " + statistics.getMin());
            System.out.println("Highest:: " + statistics.getMax());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

and the time im running the method i sorrounded it with a try/catch but it stills is not the solution, i want to replace or ignore all special characters, this is the line that give me error:
Brittany Smith,Programme researcher broadcasting/film/video,Sawyer-Nelson,2901,0.98,8913 Mckay Loop Johnfurt CO 90828
                                                               ^

A: To replace all special characters with emptyString you may achieve easy using:
str = str.replaceAll("[^a-zA-Z0-9]", " ");

this way, you will have only letters and digits

A: Posting on the basis that your actual problem is caused by the wrong number of separators. That of course is speculation since we haven't seen your actual input. The following would avoid an error of that sort but won't help with diagnosis (streams are unhelpful with errors)
private static void minMaxValue(String path) {
    try (Stream<String> stream = Files.lines(Paths.get(path)).skip(1)) {
        DoubleSummaryStatistics statistics = stream
            .map(s -> s.split(","))
            .filter(s -> s.length == 6) // Don't use magic numbers like this ;)
            .map(s -> s[3])
            .mapToDouble(Double::valueOf)
            .summaryStatistics();
        System.out.println("Lowest:: " + statistics.getMin());
        System.out.println("Highest:: " + statistics.getMax());
    } catch (IOException e) {
        e.printStackTrace();
    }
}


text:
Q: Java SE 1.8 disappears after installation in MacOS Mojave Download from https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html, choose "Java SE Development Kit 8u231" for Mac.
I can install Java SE 1.8 successfully, also added this to .bashrc
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_231.jdk/Contents/Home

Start a new terminal, "java -version" gives proper info.
The problem is, after certain period of time (not sure, say 1 hour), "java -version" would return error, cannot find java and ask me install again. If i do "which java", it's there.
Reinstall fixes it, then happens again after some time.
Seems there're similar posts on this, but not sure if my case is a little bit different, since it did install successfully in the beginning.
Any suggestions ? Thx !

A: ok, it's our company policy, i downloaded the java version online, which is not approved by our IT.
After installed the IT approved version, it's working now.


text:
Q: how to make padding between textfield enter image description herei want make padding betwenn this
Container(
                  child: Column(
                    children: \<Widget\>\[

                      //  Radio(value: 1, groupValue: 'Null', onChanged: (index) {}),
                      // Expanded(
                      //   child: Text('A domicile'),
                      // ),
                      // Radio(value: 1, groupValue: 'Null', onChanged: (index) {}),
                      // Expanded(
                      //   child: Text('En consigne'),
                      // ),

                      TextField(

                        decoration: InputDecoration(

                          labelText: '  Ref Expedéteur',
                          labelStyle: TextStyle(
                            color: Color.fromARGB(255, 0, 0, 0),
                            fontFamily: 'Segoe UI',
                          ),
                          enabledBorder: OutlineInputBorder(

                            borderSide: BorderSide(

                                width: 3,
                                color: Color.fromARGB(255, 136, 136, 136)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(

                            borderSide: BorderSide(
                                width: 3, color: const Color(0xffff4848)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          errorBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3,
                                color: Color.fromARGB(255, 66, 125, 145)),
                          ),
                        ),

                      ),
                      TextField(
                        decoration: InputDecoration(
                          labelText: '  Nombre de colis',
                          labelStyle: TextStyle(
                            color: Color.fromARGB(255, 0, 0, 0),
                            fontFamily: 'Segoe UI',
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3,
                                color: Color.fromARGB(255, 136, 136, 136)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3, color: const Color(0xffff4848)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          errorBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3,
                                color: Color.fromARGB(255, 66, 125, 145)),
                          ),
                        ),
                      ),
                      TextField(
                        decoration: InputDecoration(
                          labelText: '  Poids',
                          labelStyle: TextStyle(
                            color: Color.fromARGB(255, 0, 0, 0),
                            fontFamily: 'Segoe UI',
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3,
                                color: Color.fromARGB(255, 136, 136, 136)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              width: 3,
                              color: const Color(0xffff4848),
                            ),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          errorBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3,
                                color: Color.fromARGB(255, 66, 125, 145)),
                          ),
                        ),
                      ),
                      TextField(
                        decoration: InputDecoration(
                          labelText: '  Taille de colis',
                          labelStyle: TextStyle(
                            color: Color.fromARGB(255, 0, 0, 0),
                            fontFamily: 'Segoe UI',
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 2,
                                color: Color.fromARGB(255, 136, 136, 136)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 2, color: const Color(0xffff4848)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          errorBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 2,
                                color: Color.fromARGB(255, 66, 125, 145)),
                          ),
                        ),
                      ),

                      // Padding(padding: const EdgeInsets.all(2.0),
                      // child:Column(
                      //   children: \[
                      //        Radio(value: 1, groupValue: 'Null', onChanged: (index) {}),
                      //   Expanded(
                      //   child: Text('Paye'),
                      // ),
                      //   \],
                      // ),
                      // ),
                      TextField(
                        decoration: InputDecoration(
                          labelText: '  Ref Expedéteur',
                          labelStyle: TextStyle(
                            color: Color.fromARGB(255, 5, 5, 5),
                            fontFamily: 'Segoe UI',
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3,
                                color: Color.fromARGB(255, 136, 136, 136)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3, color: const Color(0xffff4848)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          errorBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3,
                                color: Color.fromARGB(255, 66, 125, 145)),
                          ),
                        ),
                      ),
                      TextField(
                        decoration: InputDecoration(
                          labelText: '  Nombre de colis',
                          labelStyle: TextStyle(
                            color: Color.fromARGB(255, 0, 0, 0),
                            fontFamily: 'Segoe UI',
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3,
                                color: Color.fromARGB(255, 136, 136, 136)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3, color: const Color(0xffff4848)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          errorBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3,
                                color: Color.fromARGB(255, 66, 125, 145)),
                          ),
                        ),
                      ),
                      TextField(
                        decoration: InputDecoration(
                          labelText: '  Poids',
                          labelStyle: TextStyle(
                            color: Color.fromARGB(255, 0, 0, 0),
                            fontFamily: 'Segoe UI',
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3,
                                color: Color.fromARGB(255, 136, 136, 136)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3, color: const Color(0xffff4848)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          errorBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3,
                                color: Color.fromARGB(255, 66, 125, 145)),
                          ),
                        ),
                      ),
                      TextField(
                        decoration: InputDecoration(
                          labelText: '  Taille de colis',
                          labelStyle: TextStyle(
                            color: Color.fromARGB(255, 0, 0, 0),
                            fontFamily: 'Segoe UI',
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3,
                                color: Color.fromARGB(255, 136, 136, 136)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3, color: const Color(0xffff4848)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(40),
                            ),
                          ),
                          errorBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                width: 3,
                                color: Color.fromARGB(255, 66, 125, 145)),
                          ),
                        ),
                      ),

this is my code its work in side padding but i want padding inside text field
im begginner in flutter
this is my code its work in side padding but i want padding inside text field  im begginner in flutter
this is my code its work in side padding but i want padding inside text field  im begginner in flutter
                    \],
                  ),
                ),

A: What do you mean by padding inside TextField? The padding inside the TextFields looks right to me, maybe you were trying to say that you want to add some kind of spacing between the TextFields? If that's the case, you have multiple options, I find this one the simplest one:
TextField(...)
SizedBox(height: 12)
TextField(...)
SizedBox(height: 12)
...

You get the idea...
I would also recommend you to extract those TextField widgets into a private widget that receives X number of parameters, this way you avoid repeating so much code and everything would look cleaner and more readable.
Something like:
class _CustomTextField extends StatelessWidget {
  const _CustomTextField({
    Key? key,
    required this.label,
  }) : super(key: key);

  final String label;

  @override
  Widget build(BuildContext context) {
    return TextField(
      decoration: InputDecoration(
        labelText: label,
        labelStyle: const TextStyle(
          color: Color.fromARGB(255, 5, 5, 5),
          fontFamily: 'Segoe UI',
        ),
        enabledBorder: const OutlineInputBorder(
          borderSide: BorderSide(
            width: 3,
            color: Color.fromARGB(255, 136, 136, 136),
          ),
          borderRadius: BorderRadius.all(Radius.circular(40)),
        ),
        focusedBorder: const OutlineInputBorder(
          borderSide: BorderSide(width: 3, color: Color(0xffff4848)),
          borderRadius: BorderRadius.all(Radius.circular(40)),
        ),
        errorBorder: const OutlineInputBorder(
          borderSide: BorderSide(
            width: 3,
            color: Color.fromARGB(255, 66, 125, 145),
          ),
        ),
      ),
    );
  }
}

And then you use it like this:
_CustomTextField(label: 'Label 1')
SizedBox(height: 12)
_CustomTextField(label: 'Label 2')
SizedBox(height: 12)
...

You can even try to add the SizedBox inside the _CustomTextField!

A: wrap every TextField widget with a Container widget, and specify the margins and padding you want like this :
  Container(
     margin: EdgeInsets.symmetric(vertical: 10.0), // 10 vertical margin
      TextField(
       decoration: InputDecoration(
         labelText: '  Taille de colis',
         labelStyle: TextStyle
         color: Color.fromARGB(255, 0, 0, 0),
         fontFamily: 'Segoe UI',
          ),
         enabledBorder: OutlineInputBorder(
         borderSide: BorderSide(
         width: 3,
         color: Color.fromARGB(255, 136, 136, 136)),
         borderRadius: BorderRadius.all(
         Radius.circular(40),
          ),),),

A: *

*If you want inside padding in TextField then you can use "contentpadding" inside InputDecoratation(contentPadding : EdgeInseta.all(6))
TextField(
 textAlign: TextAlign.left,
 decoration: InputDecoration(
   hintText: 'Enter Something',
   contentPadding: EdgeInsets.all(20.0),
 ),
)

*And you want around of TextField  or  TextFormField  then you can Wrap with Padding Widget example.

Padding(
         padding: const EdgeInsets.all(8.0),
          child: TextFormField(
           autofocus: false,
            enableSuggestions: true,
            autocorrect: true,
            style: const TextStyle(
               fontFamily: fontFamilySourceSansPro, color: black, fontSize: 16),
           validator: validateCustomerAddress,
           controller: _cusAdd2,
            focusNode: _nodeCusAdd2,
            autovalidateMode: autoValidateMode,
            keyboardType: TextInputType.streetAddress,
           textInputAction: TextInputAction.next,
            decoration: getTextFieldBorderLightGrayDecoration("Address 2*"),
          ),
        );


text:
Q: Parse via Swift with Complex Queries Im having some difficulty with creating complex queries in Parse. What I'm looking to achieve is searching the _Users class and not returning myself as a result and if an Invite already exists in the Invites class, show Pending text rather than Add Button and if both myself and user have already accepted invite, dont show them at all.
I've achieved some of it but I'm not sure i'm doing it the most efficient way. For instance, I first query the _User class and find any users that match the search terms, then loop through and if the objectId == currentUser().objectId, skip that record. Then I run another query in that loop on each record to see if there are any pending invites, if so, i set a flag to true for Pending however i've done that search not in the background because i was having isses with the first query block finishing before the second and my flag not getting set first. So would I then do a third query to see if the field is accepted? Or is there a way to make this all one big query? My code is below for the searching:
func performSearchForText(text: String, completion: SearchComplete) {
        state = .Loading
    // Query Parse

    var containsDisplayName = PFQuery(className:"_User")
    containsDisplayName.whereKey("displayName", containsString: text)

    var containsUsername = PFQuery(className: "_User")
    containsUsername.whereKey("username", containsString: text)

    var query = PFQuery.orQueryWithSubqueries([containsUsername, containsDisplayName])
    query.findObjectsInBackgroundWithBlock {
        (results: [AnyObject]?, error: NSError?) -> Void in
        //self.state = .NotSearchedYet
        var success = false

        if error == nil {
            // Found results
            // Set Result state to either Results or NoResults
            if let results = results {
                //println(results)
                if results.count == 0 {
                    self.state = .NoResults
                } else {
                    // Read Results into UserSearchResult Array
                    // Dont show self in results
                    // If user has already accepted a request, dont show
                    // If they have already invited, show Pending instead of button

                    var userSearchResults = [UserSearchResult]()
                    var searchResult = UserSearchResult()

                    for result in results {
                        if result.objectId != PFUser.currentUser()?.objectId {
                            // Query invites table to see if they already are accepted with user
                            // or if a pending invite exists
                            // Set invite or accepted respectively
                            var invitedQuery = PFQuery(className: "Invites")
                            invitedQuery.whereKey("pending", equalTo: true)
                            invitedQuery.whereKey("inviteToUser", equalTo: result.objectId!!)
                            var invitedQueryResults = invitedQuery.findObjects()
                            if invitedQueryResults?.count > 0 {
                                self.pendingInvite = true
                            }

                            searchResult.displayName = result["displayName"] as! String
                            searchResult.emailAddress = result["username"] as! String
                            searchResult.inviteUserID = result.objectId!!
                            searchResult.invited = self.pendingInvite
                            searchResult.accepted = false
                            userSearchResults.append(searchResult)
                        }
                    }

                    if userSearchResults.count > 0 {
                        self.state = .Results(userSearchResults)
                    } else {
                        self.state = .NoResults
                    }

                }
                    success = true
                }

            dispatch_async(dispatch_get_main_queue()) {
                UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                completion(success)
            }
        } else {
            // Error, print it
            println(error)
        }
    }
}

A: Unless there's a lot more to your invites table, I'd suggest removing it and adding an "invitePending" field to your user table.
Then you can just further refine your other queries by using wherekey("invitePending", equalTo: true).
Additionally, you can do something like this at the start so you don't have to check for currentUser in the query completion block:
containsDisplayName.whereKey("objectId", notEqualTo: PFUser.currentUser()!.objectId!)

But you definitely don't need the invites table if it isn't storing lots of other info. If you have to keep it as a separate table, using a pointer (for 1 to 1) or a PFRelation (for 1 to many) would save you the headache of that inner query.


text:
Q: What is the best Java-based Mailing List application allowing opt-in/opt-out I'm looking for a java-based (preferable) mailing list application that allows users to opt-in/opt-out of mailing lists.  Open-source is preferable but not mandatory.
This product would be used to send email notifications to subscribed people when certain events happen in another application - i.e.  when a new record is saved and approved with certain attributes, a message is sent to one or more mailing lists.
It should be able to handle multiple mailing lists and must have an interface for sending new messages programatically without the need to use it's web/gui interface.
A last resort would be to develop our own application to perform this functionality.

A: I would recommend using a hosted service for email marketing. Sure, you may find just the right software for the job. The main issue is deliverability. A mailing service increases the chances of your mail reaching the destination. It also provides very useful reports of how many opened and who clicked what. IMHO, the price of those services is very much justified.
I'm using MailChimp and I'm happy with their service. They have an easy to use API, so you can control your campaigns programatically. I'm invoking it from Java and I'm in the process of packing my code to post it online.

A: My recommendation would be to handle opt-in and opt-out operations in a web application, store addresses per "list" in whatever database you prefer and just use the JavaMail API to handle the actual email functionality. It's trivial, much easier to integrate into an existing app, and you'll be much happier later on when you have to maintain this system.


text:
Q: Styleable cannot be resolved Here is the code I am using:
public ASSwitch(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray sharedTypedArray = context.getTheme().obtainStyledAttributes(
            attrs,
            R.styleable.ASSwitch,
            0, 0);

       try {
           onText = sharedTypedArray.getText(R.styleable.ASSwtich_onText, null);

       } finally {
           sharedTypedArray.recycle();
       }
}

Here is the attrs.xml file (added to values folder):
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ASSwitch">
        <attr name="onText" format="string" />
        <attr name="offText" format="string" />
        <attr name="onState" format="boolean" />
        <attr name="toogleDrawable" format="string" />
        <attr name="frameDrawable" format="string" />
    </declare-styleable>
</resources>

The answers in these questions couldn't fix the problem. Please don't consider my question as duplicate.

*

*Android Hello, Gallery tutorial -- "R.styleable cannot be resolved"

*Android: How to Declare Styleable in R.java?

*R.styleable can not be resolved, why?

*R.styleable cannot be resolved

Update: It seems that I was importing the wrong R class. It shall be the application's R class not android.R.

A: Check your imports:

*

*Wrong: Android.R

*Correct: com.example.yourproject.R
I had the same error when made this customized view. Maybe when follow the guiding step, the helper tool automatically inserts this wrong import.

A: It seems that I was importing the wrong R class. It shall be the application's R class not android.R


text:
Q: How Big a Conference?
What is the least number of people that should attend a conference so that there are 3 mutual friends and 3 mutual strangers?

I know this is not hard but I saw somewhere that it should be 6, but I was arguing that it should be 5 since we if there are 3 people that know one another and another 2 that are complete strangers we can take one from the 3 friends to make 3 mutual strangers. Is my argument correct?


text:
Q: Hide NavBar but show status bar with background My nav bar is setup to hide on scroll but it also takes the background color of my status bar with it when it goes, leaving white status bar text on top of my content as I scroll. I want it to look similar to the way many apps do it where if my navbar and status bar have an orange background with white text, when the scroll happens and the navbar hides, the status bar retains the orange background.
Update1:
Tried adding a subview of 20 to the view but its not showing up. I may be missing something since this is my first attempt at creating an app without IB.
I put this code into my TableViewController. I tried tableview., view. and super.view. and none of them seemed to work.
let statusBarBG = UIView()
        statusBarBG.backgroundColor = UIColor.rgb(248, green: 148, blue: 6)
        super.view?.addSubview(statusBarBG)
        super.view?.addContstraintsWithFormat("V:|[v0(20)]", views: statusBarBG)
        super.view?.addContstraintsWithFormat("H:|[v0]|", views: statusBarBG)

Update 2:
So after trying a few things, my view appears but its under the navbar and scrolls with the tableview which causes it to disappear when the user scrolls.
FeedTVController:UITableViewController
 let statusBarBG = UIView(frame: CGRect(x: 0.0, y: -44, width: UIScreen.mainScreen().bounds.width, height: 20))
            statusBarBG.backgroundColor = .redColor()  //UIColor.rgb(248, green: 148, blue: 6)
            self.view?.addSubview(statusBarBG)

App Delegate:
let feedController = FeedTVController()
        let navigationController = UINavigationController(rootViewController: feedController)
        let tabBarController = TabBarController()
        tabBarController.setViewControllers([vc1, vc2, vc3], animated: true)
        window?.rootViewController = tabBarController

A: After looking around for a whole day I couldn't find a proper solution for this case. Thinking in a logical way I came up with a solution, I hope that helps the people having the same issue.
By default there is no Status Bar background view so we need to create one and place it under the Status Bar but above the Navigation Bar:
On viewDidLoad()

    self.navigationController?.hidesBarsOnSwipe = true

    /* creates a View using the navigation bar frame to place under the status bar but above the navigation bar */

    let statusBarView = UIView()
    statusBarView.backgroundColor = .blue
    statusBarView.frame = UIApplication.shared.statusBarFrame
    UIApplication.shared.keyWindow?.addSubview(statusBarView)

A: Change the background color of your SuperView (ViewController View) to orange(or whatever color you want as default for statusbar.

A: There's no code so there are two ways you could be hiding your navBar:
If you're hiding a subclass manually so it's hiding relative to how much the user scrolls up (like Facebook): Then instead of hiding your navigation bar all the way, hide it with 20 points from its bottom left on the screen.
If you're hiding navBar with the built-in animated hide: Then add a subview that's connected to the top of the container and is 20 points high with the same background color, so when navigationbar goes away, the subview is at the top.


text:
Q: Interpreting Siege results with Nginx I am trying to compare the performance of a clutch of web servers using Siege. Whilst the results from all the other servers are easy to understand I am having some difficulty understanding the figures returned for Nginx
I had rather naively assumed that
Transactions = Successful + Failed
This is indeed the case but only when I get Siege to fetch one single static resource (an image) from the server. When I get it to fetch the results of running a PHP script (which does a number of CPU intensive calculations) what I get is more like what is shown below

I The siege does not report any dropped or failed socket connections.  I'd be most grateful to anyone who might be able to explain the reasons for the apparent discrepancy.