Q:

How to display a rect shape created in a class?

I am working on a frogger game and am trying to create logs for the player to land on. To do this I decided to write a class that can do this for all logs created. I am having difficulty figuring out how to display these shapes as I cannot use the blit method. Any help would be greatly appreciated.
This is my code so far:
import sys, pygame, random
from pygame.locals import *

pygame.init()
screen_height = 750
screen_width = 750
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Frogger")
FPS = 200

player = pygame.image.load('frog.bmp')
player_rect = player.get_rect()
player_rect.left = 300 + 1
player_rect.top = screen_height - 74

#For player movement
up_movements = 0
down_movements = 0
left_movements = 0
right_movements = 0
up_movement = False
down_movement = False
left_movement = False
right_movement = False

x_logs = [1, 301, 601]
y_logs = [149, 224, 299, 374, 449, 524, 599, 674]
log_width = 74
log_height = 74
logs_created = []

class Log():

    def __init__(self, x, y, direction):
        self.x = x
        self.y = y
        self.direction = direction
        self.log = pygame.draw.rect(screen, (153, 102, 0),(self.x, self.y, log_width, log_height))

    def move_log(self):
        if self.direction == 'right':
            self.x += 5
        if self.direction == 'left':
            self.x -= 5
        self.log

    def draw_new_logs(self): # To address the issue of infinitely spawning in logs, put the if statements in the main game loop and only have it run this method if it meets the requirements
        if self.direction == 'right':
            if self.log.right > screen_width:
                logs_created.append(Log(-73, self.y, log_width, log_height))
            #Delete log if it exceeds boundary
            if self.log.left > screen_width:
                logs_created.remove(self.log)

        if self.direction == 'left':
            if self.log.left < 0:
                logs_created.append(Log(749, self.y, log_width, log_height))
            #Delete log if it exceeds boundary
            if self.log.right < 0:
                logs_created.remove(self.log)

for x in x_logs:
    for y in y_logs:
        if (y_logs.index(y) % 2) == 0:
            logs_created.append(Log(x, y, 'left'))
        else:
            logs_created.append(Log(x, y, 'right'))

while True:
    screen.fill((0, 119, 190))
    starting_area = pygame.draw.rect(screen, (32, 178, 170), (0, 675, screen_width, screen_height / 10))
    finish_area = pygame.draw.rect(screen, (32, 178, 170), (0,0, screen_width, screen_height / 10))
    screen.blit(player, player_rect)

    FPSCLOCK = pygame.time.Clock()

    for item in logs_created:
        item.move_log()

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        elif event.type == KEYDOWN:
            if event.key == K_UP:
                up_movement = True
            elif event.key == K_DOWN:
                down_movement = True
            elif event.key == K_LEFT:
                left_movement = True
            elif event.key == K_RIGHT:
                right_movement = True

        #Movements
    if up_movement == True:
        if player_rect.top > 1:
            if up_movements < 75:
                player_rect.y -= 15
                up_movements += 15
            else:
                up_movements = 0
                up_movement = False
        else:
            up_movement = False
            up_movements = 0
    if down_movement == True:
        if player_rect.bottom <= screen_height - 1:
            if down_movements < 75:
                player_rect.y += 15
                down_movements += 15
            else:
                down_movements = 0
                down_movement = False
        else:
            down_movement = False
            down_movements = 0

    if left_movement == True:
        if player_rect.left > 1:
            if left_movements < 75:
                player_rect.x -= 15
                left_movements += 15
                print(player_rect.left)
            else:
                left_movements = 0
                left_movement = False
    if right_movement == True:
        if player_rect.right <= screen_width - 1:
            if right_movements < 75:
                player_rect.x += 15
                right_movements += 15
            else:
                right_movements = 0
                right_movement = False

    pygame.display.update()
    FPSCLOCK.tick(FPS)

A:

pygame.draw.rect() does not construct some kind of drawable object (like a Surface), it draws a rectangle on a surface. You have to use pygame.draw.rect() instead of pygame.Surface.blit(), rather than instead of pygame.image.load().
The return value of pygame.draw.rect() is a pygame.Rect object. A pygame.Rect just contains the location and size of a rectangle.
Instead of drawing a rectangle in the constructor of Log, you have to add a draw method to the class Log, which draws a rectangle on the screen:
class Log():

    def __init__(self, x, y, direction):
        self.x = x
        self.y = y
        self.direction = direction

    def move_log(self):
        if self.direction == 'right':
            self.x += 5
        if self.direction == 'left':
            self.x -= 5

    def draw(self):
        pygame.draw.rect(screen, (153, 102, 0),(self.x, self.y, log_width, log_height))

Add the initial Log objects to the list logs_created, before the main application loop:
x_logs = [1, 301, 601]
y_logs = [149, 224, 299, 374, 449, 524, 599, 674]
logs_created = []

for x in x_logs:
    for y in y_logs:
        logs_created.append(Log(x, y, 'right'))

Move and draw all the Log objects in logs_created, in the main application loop:
while True:
    screen.fill((0, 119, 190))
    starting_area = pygame.draw.rect(screen, (32, 178, 170), (0, 675, screen_width, screen_height / 10))
    finish_area = pygame.draw.rect(screen, (32, 178, 170), (0,0, screen_width, screen_height / 10))
    screen.blit(player, player_rect)

    # draw logs
    for log in logs_created:
        log.draw()

    # [...]

    # move logs
    for log in logs_created:
        log.move()


Q:

Using Reflection to set a static variable value before object's initialization?

Is there anyway to set the value of a static (private) variable on an object that has not been initialized? The SetValue method requires an instance, but I'm hoping there's a way to get around this.

A:

For static values you can pass null for the instance parameter.
var type = typeof(SomeClass);
var field = type.GetField("SomeField", BindingFlags.NonPublic | BindingFlags.Static);
field.SetValue(null, 42);


Q:

Setting date using DialogFragment and Android Annotations

I have problem with writing date I selected in DatePicker with Dialog Fragment.
I`m trying to do this using Android Annotations. Problem is, I have to implement behavior for setting this date to TextView on OnDateSet function in DatePickerFragment class.
How can I choose in which TextView, which @Click should write?
Code below:
@EActivity(R.layout.activity_main_search)public class SearchActivity extends FragmentActivity{

private int mFYear, mFMonth, mFDay, mTYear, mTMonth, mTDay;

 (R.id.main_search_city)
EditText cityET;

@ViewById(R.id.main_search_price)
EditText priceET;

@ViewById(R.id.main_search_from)
TextView dateFromTV;

@ViewById(R.id.main_search_to)
TextView dateToTV;

public static class DatePickerFragment extends DialogFragment
    implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {

        }
}

@AfterViews
public void setCurrentdateonView(){
     final Calendar c = Calendar.getInstance();
     mFYear = c.get(Calendar.YEAR);
     mFMonth = c.get(Calendar.MONTH)+1;
     mFDay = c.get(Calendar.DAY_OF_MONTH);

     dateFromTV.setText(new StringBuffer().append(mFDay).append("-").append(mFMonth).append("-").append(mFYear).append(""));
     dateToTV.setText(new StringBuffer().append(mFDay).append("-").append(mFMonth).append("-").append(mFYear).append(""));
 }

@App
HApplication mApp;

@Click(R.id.main_search_from_btn)
public void showFromDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");

}

@Click(R.id.main_search_to_btn)
public void showToDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");
}

@Click(R.id.main_search_btn)
public void openSearch(){
    //SearchActivity_.intent(this).city(cityET.getText().toString()).start();
    ListActivity_.intent(this).city(cityET.getText().toString()).price(priceET.getText().toString()).start();
}}

Functions that should realise that date writing are:
@Click(R.id.main_search_from_btn)
    public void showFromDatePickerDialog(View v)
it should write date to dateFromTV
and
@Click(R.id.main_search_to_btn)
    public void showToDatePickerDialog(View v)
it should write date to dateToTV
I SOLVED THE PROBLEM.
What I needed was flags, which were set on each button @Click and then in onDateSet case switch with flag number check. Maybe it will help someone, because it took me whole day to figure it out...

A:

The Click annotation is just for triggering the dialog.
You should implement a callback method through listener interfaces described here:
http://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents
EDIT: I implemented a version for myself, here is the code:
MainActivity.java:
    package com.example.datepickerexample;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TextView;

import com.example.datepickerexample.DatePickerFragment.DatePickerDialogListener;

public class MainActivity extends FragmentActivity implements
        DatePickerDialogListener {
    TextView lbl_from, lbl_to, cpn_from, cpn_to;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        cpn_from = (TextView) findViewById(R.id.cpn_from);
        cpn_to = (TextView) findViewById(R.id.cpn_to);
        lbl_from = (TextView) findViewById(R.id.lbl_from);
        lbl_to = (TextView) findViewById(R.id.lbl_to);
    }

    public void showFromDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean("isFromDate", true);
        newFragment.setArguments(bundle);
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }

    public void showToDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean("isFromDate", false);
        newFragment.setArguments(bundle);
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }

    @Override
    public void onDatePicked(DialogFragment dialog, Calendar c,
            boolean isFromDate) {
        String strdate = null;

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

        if (c != null) {
        strdate = sdf.format(c.getTime());
        }
        if (isFromDate) {
            lbl_from.setText(strdate);
        } else {
            lbl_to.setText(strdate);
        }
    }

}

activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/cpn_from"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_margin="6dp"
        android:text="@string/from_date" />

    <TextView
        android:id="@+id/lbl_from"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@id/cpn_from"
        android:layout_toRightOf="@id/cpn_from" />

    <Button
        android:id="@+id/btn_from"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/cpn_from"
        android:onClick="showFromDatePickerDialog"
        android:text="@string/pick_from_date" />

    <TextView
        android:id="@+id/cpn_to"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn_from"
        android:layout_margin="6dp"
        android:text="@string/to_date" />

    <TextView
        android:id="@+id/lbl_to"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn_from"
        android:layout_alignBaseline="@id/cpn_to"
        android:layout_toRightOf="@id/cpn_to" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/cpn_to"
        android:onClick="showToDatePickerDialog"
        android:text="@string/pick_to_date" />

</RelativeLayout>

DatePickerFragment.java:
package com.example.datepickerexample;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;

public class DatePickerFragment extends DialogFragment implements
        DatePickerDialog.OnDateSetListener {

    public interface DatePickerDialogListener {
        public void onDatePicked(DialogFragment dialog, Calendar c,
                boolean isFromDate);
    }

    // Use this instance of the interface to deliver action events
    DatePickerDialogListener mListener;

    boolean isFromDate;

    public static DatePickerFragment newInstance(boolean isFromDate) {
        DatePickerFragment instance = new DatePickerFragment();

        instance = new DatePickerFragment();
        Bundle args = new Bundle();
        args.putBoolean("isFromDate", isFromDate);
        instance.setArguments(args);
        return instance;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            isFromDate = getArguments().getBoolean("isFromDate");
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        Calendar c = Calendar.getInstance();

        c.set(year, month, day);
        mListener.onDatePicked(this, c, isFromDate);
    }

    // Override the Fragment.onAttach() method to instantiate the
    // NoticeDialogListener
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the NoticeDialogListener so we can send events to the
            // host
            mListener = (DatePickerDialogListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString()
                    + " must implement NoticeDialogListener");
        }
    }
}


Q:

GLSL 1.30 is not supported

I have run my gl program successfully on my ubuntu system with a good graphics card. However, when I run it in an old intel machine with graphics mobile 4-series, I get these errors:
QGLShader::compile(Vertex): 0:1(10): error: GLSL 1.30 is not supported. Supported version are: 1.10, 1.20 and 1.00 ES
QGLShader::compile(Fragment): 0:1(10): error: GLSL 1.30 is not supported. Supported version are: 1.10, 1.20 and 1.00 ES

I think some keywords in my vertex and fragment shader files should be changed to old version. Could any one suggest me the old keywords.
Vertex Shader file:
#version 130

uniform mat4 mvpMatrix;

in vec4 vertex;
in vec2 textureCoordinate;

out vec2 varyingTextureCoordinate;

void main(void)
{
    varyingTextureCoordinate = textureCoordinate;
    gl_Position = mvpMatrix * vertex;
}

Fragment Shader file:
#version 130

uniform sampler2D texture;

in vec2 varyingTextureCoordinate;

out vec4 fragColor;

void main(void)
{
    fragColor = texture2D(texture, varyingTextureCoordinate);
}

A:

Run the feature deprecation list on page 2 of the GLSL 1.30 spec backwards:

#version 130 -> #version 120
in -> attribute
out -> varying
Remove fragColor declaration, replace fragColor usage with gl_FragColor

Vertex shader:
#version 120
uniform mat4 mvpMatrix;
attribute vec4 vertex;
attribute vec2 textureCoordinate;
varying vec2 varyingTextureCoordinate;
void main(void)
{
    varyingTextureCoordinate = textureCoordinate;
    gl_Position = mvpMatrix * vertex;
}

Fragment shader:
#version 120
uniform sampler2D texture;
varying vec2 varyingTextureCoordinate;
void main(void)
{
    gl_FragColor = texture2D(texture, varyingTextureCoordinate);
}


Q:

Гоголь-моголь

С детства все знают, что такое гоголь-моголь. Но вот что это за название? Или это просто игра слов и звуков?

A:

При кажущейся схожести названия с фамилией Гоголь писатель никакого отношения к сему десерту не имеет. Фасмер говорит о заимствовании слова из англ. hug-mug, hugger-mugger или объясняет близкое польск. kogel-mogel – то же из нем. Kuddelmuddel "мешанина". На Грамоте.ру дается немецкое соответствие Gogel-Mogel. Есть еще легенда  о канторе из Могилёва по фамилии Гогель, потерявшем голос. Чтобы вылечить горло, он придумал такой рецепт: «Взять сырую яичку, кокнуть в кружку, покрошить чернухи (то есть чёрного хлеба), посолить и взболтать». Он принимал лекарство понемногу, маленькой ложечкой. А поскольку Гогель из Могиля (Могилева) был человеком небогатым, то оно служило ему также и сытным завтраком. В другой версии этой же легенды присутствует графиня Бронислава Потоцкая, которая несколько модернизировала рецепт, заменив хлеб на мёд, и переименовала его из «гугель-моголь» в «гугол-моголь». (см. http://www.russianfood.com/reading/?post_id=227/) Мне больше нравится версия заимствования от Фасмера. Не наша это еда, и названия тоже не наши.


Q:

Testing WebServiceCallout with HttpCalloutMock

I am trying to use the new HttpCalloutMock following the guide here.
This is a new feature, and I was hoping to make some better test cases for using web-service callouts that respond with a SOAP Message.
However, after setting up the HttpCalloutMock response, I've since discovered that the TestMethod continues to throw: TypeException: Methods defined as TestMethod do not support Web service callouts, test skipped
I would assume this is being thrown from the imported on the WS Callout definition at WebServiceCallout.invoke(), since this isn't a simple HTTPRequest is it even going to be possible to test my web-service callouts?
    @isTest
global class ApiListMtgListMeetingsResultTest implements HttpCalloutMock {
    // Implement this interface method

global HTTPResponse respond(HTTPRequest req) {
    system.debug('Mock ApiListMtgListMeetingsResult');
    HttpResponse res = new HttpResponse();
    res.setHeader('Content-Type', 'text/xml;charset=UTF-8');
    res.setBody('<soap:Envelope>...</soap:Envelope>');
    res.setStatusCode(200);
    return res;
}

}

In the guide, setting the Test.Mock seems to capture any HTTP callouts via HttpRequest.send(), no explicit settings required.
Update
I guess I should clarify, I am trying to use HttpCalloutMock to respond to a call from:
WebServiceCallout.invoke()

A:

Without delving too deep, I've found such new feature errors to be stemming from old Api version on the class. Make sure you set the api version to 26.
None of the new features will be available unless the class is on the latest Api version. Try using the new String methods in a class with Api version less than 26!

A:

Thanks to this blog post from @metadaddy - I realized there is ANOTHER INTERFACE specifically for Webservices callouts.


Q:

How can I simply modify the path for the entire requests package within a libraries folder in my appengine project

I've been working with AppEngine for a little while now and always have a bit of friction when using external libraries where I need to modify each import statement to reflect the fact that the library is not in the base directory of the project.
For example, my directory structure might look like (with the requests library installed)
/myapp/app.yaml
/myapp/main.py
/myapp/libraries/requests/packages/
/myapp/libraries/requests/__init__.py
/myapp/libraries/requests/adapters.py
etc...

However appengine expects something like
/myapp/app.yaml
/myapp/main.py
/myapp/requests/packages/
/myapp/requests/__init__.py
/myapp/requests/adapters.py
/myapp/requests/api.py
etc...

I then need to go in to each of the requests files to modify the imports to something like
from libraries.requests import adapters

rather than simply
import adapters

which may be within api.py. If I do not modify it I get an import error e.g.
ImportError: No module named adapters

I have looked at the following How to import modules in Google App Engine? which suggests modifying the path (though the application is different in their code) using
sys.path.append(os.path.join(os.path.dirname(__file__), 'libraries'))

To translate this to my issue I could put something like
sys.path.append(os.path.dirname(__file__))

at the start of each __init__.py file within libraries. However it strikes me that there must be a more efficient way, and in keeping with DRY - but I cannot seem to find it. I've tried simply including it in the top most __init__.py file within libraries and then again in the top most __init__.py file within each package. This does not work for sub-packages though unfortunately. Is there a way to make one change to fix this?

A:

I have all my third party libs in a lib dir
The I just  include
sys.path.insert(0,'./lib')
in appengine_config.py which is loaded before any of your code.
If find it needs to be inserted at the beginning of sys.path rather than at then end if you use specific versions of libs like webob that are not part of the appengine available versions.
Then you don't have to modify any of the libraries etc....
This is pretty standard python behaviour.  In a normal desktop install situation you are installing vie easy_install which sticks stuff in places like site-packages and setups paths etc....  but if you aren't using any of that, and you can't with appengine you have to do the path manipulation yourself.


Q:

Zero Day Policies implementation

I'm new here, and sorry if my english is a little bit broken it's not my main language.
I'm trying to put together a document/ppt for my startup with a Zero Day policy structure.
But I'm not finding real implemented flows, information, or something I can base this from (anything is helpfull)
What I found on my research mainly focus on specific discussing how heartbleed or the cve work.
I want to put something very straightforward but would love different point of views or examples if there are like:

We will be suscribed to receive every update automatically from the different applications, OS that we own
Critical updates will be reviewed, researched and implemented at top on 48 hours on all the servers
Medium/Urgent updates will be reviewed, researched and implemented at top on 1 week on all servers
Low Updates will be reviewed and implemented at most on the same month
A Team will monitor the audits logs of ports that are reporting status that are receiving suspected activity once a week on a internal meeting and define if new meassures have to be implemented
ETC

A:

The point of zero-day attacks is that they use vulnerabilities which are not known at the time they get exploited. You can thus not create a policy specifically for zero-days. But hardening the security in general also reduces the risk or at least the impact of a zero-day. Because the zero-day exploit is just the way the attacker enters the network or takes over a system or account. The actual harm against the network is not done by the exploit itself, but by the attacker using other tools and methods from its achieved privileges on the computer and in the network for espionage, sabotage, ransom etc.
Therefore the protection you add must be based on the assumption that the attacker has already successfully entered your network using the zero-day exploit, i.e. that he is actually inside your network and that you need to reduce the harm he can do there.
This means of course being up-to-date with patching since otherwise you likely have problems already with the way more common known attacks than just with the uncommon zero-day attacks. This means monitoring your infrastructure for suspicious activity, which of course means that you know what should be normal and what is suspicious in the first place. Strict and narrow separation and segmentation at network and application level and proper user permissions can help a lot to restrict the harm a successful attacker could do in your network - no matter if he came in by using a zero-day or not. And for the harm you could not prevent you need recovery strategies, like having a backup with a working restore.
In other words: know what should happen in your network and implement techniques (like microsegmentation, zero-trust, ...) to enforce and monitor the expected behavior. Expect some harm and be able to recover from it. The better you understand what should happen and the better you enforce it, the less harm an attacker can do in your network even if he has successfully infiltrated some computer/user in the network. It is not that firewalls, IDS, antivirus, SIEM etc don't help - but these are tools to enforce and monitor expected behavior and not magic wands you just need to wave. Don't expect to successfully fight zero-days by adding security on top of a chaotic network you don't understand or which behaves differently than you believe.


Q:

cannot change default rails error message

I have the following validation for my Profile model:
validates :category, presence: true,
  inclusion: {in: categories, message: "Please choose a category from the list."}

And the following in my en.yml file:
en:
  active_record:
    errors:
      models:
        profile:
          attributes:
            category:
              blank: "Category must be present."

Yet, for some reason, the error  message that is displayed is still the default:
can't be blank

how do I make the locale file work and change the error message?

A:

In your en.yml file you should be using activerecord, not active_record.


Q:

Getting the class name which triggered the event

I have a tag with below HTML :
Create Account
I am using a common click handler of the 3 button with Class create_account , member_login , product_service
Now inside the handler , I want the class name which triggered the click event, in best possible way (with minimal condition)
 $('.create_account , .member_login , .product_services').click(function(){

    console.log($(this).attr('class'));

    /**

      In case , user click on button with class `create_account` , I get in console

      `create_account singup  header-icon` , which is correct,

       **but I want `create_account` i.e is the class which triggered the Click event**

    */

 });

A:

I would just create a separate click handler for each class, like so:

// Define all the required classes in an array...
var selectors = ["create_account", "member_login", "product_services"];
// Iterate over the array
$.each(selectors, function(index, selector) {
    // Attach a new click handler per-class. This could be a shared function
    $("."+selector).click(function(e) {
        e.preventDefault();
        alert(selector); // Logs individual class
    });
});

Create
Login
Services

If you want you can abstract the shared logic out into another function, like this Fiddle


Q:

cursor: pointer doesn't work on :after element?

I'm viewing the below example in Chrome and can't seem to get cursor: pointer to work on the :after element of li. Is there a way to get around this?
http://jsfiddle.net/qKMPQ/2/

A:

Instead of setting the cursor: pointer on the :after element, set it on the entire li and it will show up on both.
Edit:
For those of you trying to have different cursors on the li and its :after pseudo-element, you simply need to explicitly define the cursor property of the content inside the li. See this updated fiddle: http://jsfiddle.net/qKMPQ/20/

ul { list-style-type: none; }
li { cursor: pointer; }
a {
    background: red;
    float: left;
    width: 100px;
    height: 100px;
    cursor: help;
    display: block; }
li:after {
    content: "";
    background: yellow;
    float: left;
    width: 100px;
    height: 100px;
    display: block; }


Q:

How to specify html page globally in Jboss?

We have a filter that redirects user to error.html, if the user is not authorized. Right now, we are keeping error.html page inside the WAR, but is there any way to make the html file public so that every war file can access this error page? It would be still better, if we make this html page as a jar and keep it in server/default/lib.
Here is the sample that is used in filter.

 `reqDespacher = request.getRequestDispatcher("error.html")`

and the accessing url is
http://localhost/Context_root/error.html

Any help would be appreciated.

A:

In JBoss5 or JBoss6, you can copy and then define this custom error.html inside the /deployer/jbossweb.deployer/web.xml of the server instance that you are running. This will require a reboot of the JBoss instance. Example for error code 404:
<error-page>
            <error-code>404</error-code>
            <location><relative_path_to_error_html_file_under_jbossweb.deployer_folder></location>
</error-page>

Secondly, instead of re-directing request by specifying a page manually like you are doing currently, you should use the <error-page> and <error-code> deployment directive to define custom error pages. See specify-the-default-error-page-in-web-xml-in-servlet for a detailed example on how to add error-code directives on web.xml.
For JBoss AS7 global error page configuration take a look at how-to-customize-jboss-as7-404-page .


Q:

How to hide JSON data by creating a div

In order to hide the JSON data (so that it can be faded in later), I modified the a1.start function by creating div called "loading," but in the Javascript Console in Chrome, there is

Uncaught SyntaxError: Unexpected token ILLEGAL

in the HTML:  a1.start($("#cakeHook"),"a1data.json");
<!doctype html>

    <title>Cake Baby Bakery</title>

    <link href="css/bootstrap.css" rel="stylesheet"/>
    <link href="css/basica1.css" rel="stylesheet"/>

a1.start
a1.start = function(hookElementSelection, dataurlForJsonFile) {

jQuery('
', {
id: 'loading',
text: 'Loading...'
}).appendTo('hookElementSelection');

$('hookElementSelection).hide();

    a1.products = {};
    a1.recipes = {};
    a1.suppliers = {};
    a1.bakedRecipes = [];

    //make an ajax call and wait for success
    $.ajax({url:dataurlForJsonFile}).success(function(data) {

        //get the recipe data
        parseJSONData(data);

        //put the recipes on the page
        $.each(a1.recipes, function(i, recipe) {
            recipe.render(hookElementSelection);
        });
        renderCalculator(hookElementSelection); //add in the final calculation logic
    });
};

A:

When you try to use the variable, you are using a string instead:
.appendTo('hookElementSelection')

should be:
.appendTo(hookElementSelection)

Then you have an unterminated string when you try to use the variable again:
$('hookElementSelection).hide();

should be:
hookElementSelection.hide();


Q:

hidden images when scroll uitableview in iphone

I am doing this code
but when i scroll the uitableview image will disappear what i want i want when image once load then it will not disapper.
Please tell me what can i do in this.
__block NSData *image = nil;
dispatch_queue_t imageQueue = dispatch_queue_create("queueForCellImage", NULL);
dispatch_async(imageQueue, ^{
    NSString *thumbnailURL = @"http://www.bizfy.com/demo/biscoot/a1.png";
    image = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:thumbnailURL]];
    dispatch_async(dispatch_get_main_queue(), ^{
        cell.imageView.image = [UIImage imageWithData:image];
        [cell setNeedsLayout];
    });
});
dispatch_release(imageQueue);

A:

You should store the images in an NSArray, NSDictionary or even in the file system. Instead of only setting cell.imageView, try to store in a NSMutableArray or save to the disk, and in the next time cellForRowAtIndexPath is called, you access the image where you stored it.
Some code with the NSMutableDictionary solution, assuming you are using ARC (try to understand):
In your interface file, you declare a NSMutableDictionary *dictionaryImages;
In your implementation file, initiate it in viewDidLoad method: dictionaryImages = [NSMutableDictionaryImages dictionary];
Now, where you download your images, you also should insert the image in your dictionary (I'm not posting all your code, just the relevant parts from that piece)
NSString *thumbnailURL = @"http://www.bizfy.com/demo/biscoot/a1.png";
UIImage *imageForDictionary = [UIImage imageWithData:image];
[dictionaryImages setObject:imageForDictionary forKey:thumbnailURL];

And then, when cellForRowAtIndexPath is called, you associate it to the image (of course, if you have access to the thumbnailURL):
NSString *thumbnailURL = **get it from somewhere**;
UIImage *imageFromDictionary = [dictionaryImages objectForKey:thumbnailURL];
cell.imageView.image = imageFromDictionary;


Q:

How to sum over duplicates?

I have a list of the form:
{{1, 0, 1}, {2, 1, 2}, {1, 0, 3}, {2, 4, 2}, {2, 1, -1}, {1, 0 ,0}}

that I would like to sort such that I calculate the sum over the third column whenever the first two columns are equal.  I.e. in this case the output would be
{{1, 0, 1 + 3 + 0}, {2, 1, 2 + (-1)}, {2, 4, 2}}

or
 {{1, 0, 4},{2, 1, 1},{2, 4, 2}}

Is there an elegant way to do this?

A:

Flatten[{#[[1, {1, 2}]], Total[#[[All, 3]]]}] & /@ GatherBy[yourList, #[[{1, 2}]] &]

(*  {{1, 0, 4}, {2, 1, 1}, {2, 4, 2}} *)

How this works:
GatherBy[yourList, #[[{1, 2}]] &]

this gathers elements of your list based on matching the first and second elements in each sub-list (#[[{1, 2}]] &)
Once common elements are gathered (collected) you can total/sum all the third elements by mapping them onto Total

A:

 lists = {{1, 0, 1}, {2, 1, 2}, {1, 0, 3}, {2, 4, 2}, {2, 1, -1}, {1, 0, 0}}

Reap/Sow:
 Reap[Sow[#[[3]], {#[[{1, 2}]]}] & /@ lists, _,  Append[#1, Total@#2] &][[2]]

ReplaceRepeated:
 lists //. {a___, {x_, y_, z_}, b___, {x_, y_, w_}, c___} :> {a, {x, y, z + w}, b, c}

Cases + DeleteDuplicates:
 DeleteDuplicates@Cases[lists, {w : PatternSequence[_, _], _} :>
         {w, Total@(Last /@ Cases[lists, {w, _}])}]

all give

{{1, 0, 4}, {2, 1, 1}, {2, 4, 2}}

Update: In versions 10+, you can also use Merge:
KeyValueMap[Append]@Merge[Tr][Most @ # -> Last @ #& /@ lists]

{{1, 0, 4}, {2, 1, 1}, {2, 4, 2}}


Q:

Resetting saved states in eclipse rcp

I'm saving some UI settings in a state of my view. In this case I'm saving the current column order of a table in a comma-seperated string.
@Override
public void saveState(final IMemento memento) {
    int[] columnOrder = tableViewer.getTable().getColumnOrder();
    StringBuilder order = new StringBuilder();
    for (int i = 0; i < columnOrder.length; i++) {
        order.append(columnOrder[i]);
        order.append(",");
    }
    IMemento viewMemento = memento.createChild(MyView.ID);
    viewMemento.putString("viewColumnOrder", order.toString());
    super.saveState(memento);
}

Is there a way to reset the state programmatically to the initial value? I tried to reset the perspective, but that didn't work. Also resetting the Workbench did not help me.

A:

There is no API to do this.
On Eclipse 4 starting the RCP with the -clearPersistedState flag should discard the saved state.
On Eclipse 4 the XML version of the IMemento is saved in the view MPart persisted state under the memento key - but this is an internal implementation detail which may change at any time.


Q:

Swift / How to parse the correct element from a web blog with NSXMLParser

I'm trying to download specific information from a web blog with the following code:
    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {

        if elementName == "item" {
            currentEvent = EventPosts()
            return
        }

        if elementName == "eventDate" {
            parsedElement = "eventDates"
        }
    }

    func parser(parser: NSXMLParser, foundCharacters string: String) {

        let str = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

        if parsedElement == "eventDates" && str != "" {
            if currentEvent.eventDates.isEmpty {
                currentEvent.eventDates = str
                    print(currentEvent.eventDates)
        }
    }

The issue is, that the parser downloads 1 element from "eventDates" from the web blog feed and 3 elements of the "title" and I don't get why...
Any idea how to fix this issue? Help is very appreciated.
Edit: the ouput is
04.03.16 (thats an element of eventDate)
DJanes Delight 17.03.16 (thats an element of title)
Geiles Leben ab 04.03.16 (thats an element of title)
Wildstyle jeden Samstag (thats an element of title)

but it should be:
04.03.16
03.03.16
02.03.16
01.03.16

A:

It seems you never reset the parsedElement variable once it is used which will cause the outer if statement in func parser to always be true once it has been set
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {

    if elementName == "item" {
        currentEvent = EventPosts()
        return
    }

    if elementName == "eventDate" {
        parsedElement = "eventDates"
    }
}

func parser(parser: NSXMLParser, foundCharacters string: String) {

    let str = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

    if parsedElement == "eventDates" && str != "" {
        if currentEvent.eventDates.isEmpty {
            currentEvent.eventDates = str
            parsedElement = ""
                print(currentEvent.eventDates)
    }
}

While this solution might work in the most basic case you might want to read up on XML SAX parsing. There are a lot of explanations for Java out there but it is the same principle.


Q:

how to make a button go from MainActivity page to another (Android)

I noticed that even though I made a new xml named drink, there is no ".java" file with it. Do I need to make one or do i add it on to MainActivity.java?
This code is in my MainActivity.java and the Intent line is saying that drink cannot be resolved to a type.
public void calculate(View view){
   Log.i("clicks","You Clicked B1");
   Intent i=new Intent(MainActivity.this, drink.class);
   startActivity(i);
}

This is in my manifest:
<activity
    android:name=".drink">
</activity>

This is a post before I knew android. I didn't realize you have to make the java file and xml file.

A:

This code is in my MainActivity.java and the Intent line is saying
  that drink cannot be resolved to a type.

This means that you don't have a "drink" class. you have to create a new class called "drink" that extends Activityin the application package.


Q:

Unique constraints on TEXT columns in JPA using MySQL InnoDB

We need to store a long UTF-8 string into a MySQL database which has to be checked for uniqueness. This is the current configuration:
@Column(unique = true,length = 8000,columnDefinition="TEXT")
private String text;

but since MySQL needs an index prefix to be specified for both BLOB and TEXT fields, this fails with the following error:
BLOB/TEXT column 'path' used in key specification without a key length

How can I properly configure my ORM mapping to support such use case?

A:

Have you considered calculating a hash value for your text string?  Then you could store the hash value and just check for uniqueness on the hash value.  Any collisions you get with the hash value you then check the actual text strings.  If they are different then you include a sequence value. if not you've found your error.  So your table is
Hash, Sequence (unique within the same Hash value), TextString
and your unique index is
Hash, Sequence
To test for uniqueness calculate the Hash value and attempt to store it with a zero sequence.  If you can't store it at sequence zero then compare the text string at sequence zero.  If they are the same you found a duplicate text.  If they are different attempt to store at sequence 1.  Repeat until you find a duplicate text string at that sequence number or you don't fail on storing it in the database with the next available sequence number.
The trick is figuring out a hash algorithm that doesn't give you very many duplicates and can handle a long text string. Even better would be a great ORM that could do this for you.


Q:

Pandas DataFrame: query with variables

I'm working on a DataFrame query using 2 variables.
The first variable is the column label and the second is a list of values.
What I want to do is select all row where that column has a value contained in that list. The strange thing is that if I write the column label as a string there is no error, while referencing the variable containing the column label gives the following error:
Traceback (most recent call last):
  File "C:\Python\Python36\lib\site-packages\pandas\indexes\base.py", line 2134, in get_loc
    return self._engine.get_loc(key)
  File "pandas\index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)
  File "pandas\index.pyx", line 151, in pandas.index.IndexEngine.get_loc (pandas\index.c:4238)
  File "pandas\index.pyx", line 388, in pandas.index.Int64Engine._check_type (pandas\index.c:8171)
KeyError: False

This is the working code:
rhs_values_list = df1["RHS"].tolist()
query = "shoe_size in @rhs_values_list"
result_set = df2.query(query)

while this rises the above error:
rhs_values_list = df1["RHS"].tolist()
col = "shoe_size"
query = "@col in @rhs_values_list"
result_set = df2.query(query)

Is there something wrong with second version of the query?

A:

What you are doing is executing the actual query with @col in the string, not the value you bound to that variable.  You can use string interpolation e.g:
  rhs_values_list = df1["RHS"].tolist()
    col = "shoe_size"
    query = "{} in @rhs_values_list".format(col)
    result_set = df2.query(relaxed_query)


Q:

Showing minor tic grid in gnuplot with manually defined major tics

I've been trying to graph the following data
1, 2050
2, 21246
3, 208557
6, 20971520
10, 306184192
12, 1.75922E+14

Using gnuplot, using the following ytics.
set ytics ( "1 kb" 1000, \
"10 kb" 10000, \
"100 kb" 100000, \
"1 mb" 1000000, \
"10 mb" 10000000, \
"100 mb" 100000000, \
"1 gb" 1000000000, \
"10 gb" 10000000000.0, \
"100 gb" 100000000000.0, \
"1 tb" 1000000000000.0, \
"10 tb" 10000000000000.0, \
"100 tb" 100000000000000.0, \
"1 pb" 1000000000000000.0, \
"10 pb" 10000000000000000.0 )

I can't get gnuplot to show the minor grid on this graph.
As I want the y axis to be logarithmic, it would be good to show the minor tics.
Between 1000 and 10000, I'd like minor tics every 1000. From 10000 to 100000, I'd like it to be 1e4 and so on.
How does one do this?

A:

In order to understand the solution, there are some steps involved:

Automatic major tics: All minor tics are drawn
set yrange [1:100]
set logscale y
set mytics 10
plot x

Manually set major tics: The minor tics aren't drawn
set yrange [1:100]
set logscale y
set ytics ('one' 1, 'ten' 10, 'hundred' 100)
set mytics 10
plot x

Overwrite major tics with your own text (note the add): minor tics work!
set yrange [1:100]
set logscale y
set ytics add ('one' 1, 'ten' 10, 'hundred' 100)
set mytics 10
plot x

So, in your case it should be enough to use set ytics add ... and set mytics 10. You must also make sure, that you have a major tic every decade (set ytics 10), and also set the yrange manually for that many major tics:
set yrange [1e3:1e16]
set ytics 10
set mytics 10

set ytics add ( "1 kb" 1000, \
"10 kb" 10000, \
"100 kb" 100000,\
"1 mb" 1000000, \
"10 mb" 10000000,\
"100 mb" 100000000,\
"1 gb" 1000000000, \
"10 gb" 10000000000.0,\
"100 gb" 100000000000.0,\
"1 tb" 1000000000000.0, \
"10 tb" 10000000000000.0, \
"100 tb" 100000000000000.0, \
"1 pb" 1000000000000000.0, \
"10 pb" 10000000000000000.0 )

set logscale y
plot 'file.txt'

The result with 4.6.4 is:


Q:

Load File in XAP

I had a number of CSV files embedded within a Silverlight DLL (as Resource).  I need to move these into the XAP (as Content rather than resource).  The trouble is Application.GetResourceStream always seems to return null when I try and access the files.  I have tried a number of ways to achieve this but can't seem to do it.  How do you reference the CSV files from code behind?
Thanks in advance.

A:

How to Get Files From Resources in Silverlight 2.0

StreamResourceInfo sr = Application.GetResourceStream(new Uri("MyImage.png", UriKind.Relative));
BitmapImage bmp = new BitmapImage();
bmp.SetSource(sr.Stream);


Q:

Replace every other occurence with different replacements

I have a string that looks something like this:
$post = "Test $asd$ lol test asd $test$";

I want it to become:
$post = "Test [bb]asd[/bb] lol test asd [bb]test[/bb]";

Which is the easiest/best way to accomplish this? Note that the number of $ occurrences differs from time to time. The basic idea is to replace every other occurrence with [b] respectively [/bb].
I hope you understand.

A:

try this :
<?php
$str  = $post = 'Test $asd$ lol test asd $test$';
echo preg_replace('/\$(\w+)\$/','[bb]$1[/bb]',$str);
?>

Output :
Test [bb]asd[/bb] lol test asd [bb]test[/bb]


Q:

Fetch specific property in hibernate One-to-many relationship

I have two pojo classes with one-to-many relationship in hibernate
CustomerAccountEnduserOrderDetails.class
@Entity @Table(name="customer_account_enduser_order_details")
public class CustomerAccountEnduserOrderDetails  implements Serializable{

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
private Long id;

@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name = "product_id", insertable = false, updatable = false)
private CustomerCmsProduct customerCmsProduct;
}

Second is CustomerCmsProduct.class
@Entity
@Table(name="customer_cms_product")
@JsonIgnoreProperties(ignoreUnknown = true)
public class CustomerCmsProduct {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id")
    private Long id;

    @Column(name="name")
    private String name;

    @Column(name="offer_price")
    private String offerPrice;

    @Column(name="original_price")
    private String originalPrice;

    @Column(name="discount")
    private String discount;
}

Here if I fetch the object of CustomerAccountEnduserOrderDetails class,then  i will get the CustomerCmsProduct class also , my problem is that here i want the specific column of CustomerCmsProduct table (not all by default i am getting all) like only id and originalPrice.
How i can do like that projection here?

A:

In the service layer or at a webservice layer( if this is a web project) Create two different classes other than @Entity as DTO(Data Transfer Objects) which helps is data transfer from one layer to the other.
public class CustomerAccountEnduserOrderDetailsPojo {
    private List<CustomerCmsProductPojo> productPojoList = new ArrayList<> ();
    // getter and setter
}

public class CustomerCmsProductPojo {}

Follow the below steps

Retrieve the @Entity class data by executing the query from service layer.
Iterate over all the fields and copy only required fields to pojo layer
Expose the data to other layers using service method.

This way, we can avoid changing the custom hibernate behavior as it is linked with many parameters like cache, one to many queries that are fired per iteration.
And also, do any customization that you want in this layer. Hope this is multi layered project where you have different layers which servers different purpose.


Q:

How to use a Constant value of a class field in a layout?

I would like to use some java class constant value in my XML layout. Is that possible?
java class
public class ConstantKey {

   public static final String COUNTRY_CODE            = "+00";
   public static final STRING COUNTRY_NAME            = "USA";

}

Xml layout
    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="ConstantKey.COUNTRY_NAME"/>

A:

You could:
1) If the strings are constant all through, you could add them as string resources inside strings.xml. This way they're accessed from both layout or java code.
2) If the values depend on a network call or are dynamically computed, I suggest using DataBinding in andorid, check my answer here for small implementation example.


Q:

Is there an authentic source for such a partial hair covering for women?

I'm aware that per 'Iqar HaDin (baseline Halakhah), Qitzur Shulhhan 'Arukh - Yalqut Yosef  writes that a woman may reveal two finger-breadths of her hair (where her hair connects to her head) while covering her hair.
Nevertheless, I see many women in Israel partially uncovering their hair in the fashion below. Is there an authentic tradition/source for such a covering?

A:

You mean that the head is covered, but the hair hanging down beneath it is visible.
There is some room for discussion about this. The biblical source for hair-covering is the Sotah, and it says "the Kohen shall uncover the woman's head" (not "her hair.")
Rabbi Yehuda Herzl Henkin thus writes in Tradition 37:3:

Nevertheless, R. Feinstein could permit more than a tefah outside
  the hairline simply by following his own line of reasoning. Since the
  Torah specifies uncovering the sota’s head and not her hair, the kohen
  needed to uncover only the hair on the woman’s head, and not what
  hung down on her neck and shoulders. Consequently, no Torah obligation can be derived for a married woman to cover hair outside her hair-
  line.

See Rabbi Henkin's article for much more on the subject.
I'm not saying it's permissible, but there is certainly room for discussion about it.

A:

Assuming these aren't falls (i.e. half wigs), they would match up with the way the שלטי גיבורים, a commentary on the Ran, explains hair-covering in Shabbat 64b as I wrote here.

And again in his conclusion:


Q:

Kotlin cast generic class to Unit

How can I cast a generic class to Unit?

resultType is Unit

private fun <R : Any> Deferrable<R>.resolve(result: String?, resultType: Class<R>) {
        when  {
            resultType is Unit -> send(Unit)
            null -> throw NullPointerException("result is expected to be of type ${resultType}")
            else -> send(Json.parse(result, resultType))
        }
    }

A:

So, I found the solution
@Suppress("UNCHECKED_CAST")
private fun <R : Any> Deferrable<R>.resolve(result: String?, resultType: Class<R>) {
    when {
        resultType.isInstance(Unit) -> send(Unit as R)
        result == null -> throw NullPointerException("result is expected to be of type $resultType")
        else -> send(Json.parse(result, resultType))
    }
}


Q:

CSS4 Tag - Misnomer or Useful?

Today I created a tag named css4, under the impression that CSS4 was the appropriate abbreviation for CSS Level 4 modules that are currently being implemented into modern browsers. Immediately after doing so, I stumbled upon a resource that suggested that there is no such thing as "CSS4," and that there never will be.
Excerpt from A Word About CSS4:

There has never been a CSS4. There will never be a CSS4. CSS4 is not a thing that exists.
The term "CSS3" refers to everything published after CSS 2.1.
CSS is on its last version as a language as a whole, so it would be appropriate to just drop the number entirely and refer to everything from now on as just "CSS".

However, a quick Google search of "CSS4" returns a full page of results such as this one referring to the new features in the Level 4 modules, so while it may be technically correct that there is no true "CSS4," it seems to be a popular abbreviation for CSS Level 4 modules.
I think Wikipedia makes a good, unbiased explanation of the situation, so I'll include that here for reference.
Excerpt from Wikipedia's Cascading Stylesheet Sheets article:

There is no single, integrated CSS4 specification, since it is split into separate modules. However, there are "level 4" modules.
Since CSS3 split the CSS language's definition into modules, the modules have been allowed to level independently. Most modules are level 3 - they build on things from CSS 2.1. A few level 4 modules exist (such as Image Values, Backgrounds & Borders, or Selectors), which build on the functionality of a preceding level 3 module. Others define entirely new functionality, such as Flexbox.
So, while no monolithic CSS4 will be worked on after CSS3 is finished completely, the level 4 modules can collectively be referred to as CSS4.

So after reading all of this, I've been going back-and-forth about the usefulness of a "CSS4" tag. On one hand, it's technically inaccurate to call CSS Level 4 modules CSS4, but on the other hand it is a popular abbreviation for it.
As these features become available in browsers, I'm sure many people will have questions about them, so having a tag for them seems prudent, but I leave it up to Meta to decide the future of such a tag!

A:

See my answer to this question for an elaboration on the first source that you quoted. Note that I take the first source as authoritative because it's written by a member of the CSSWG.
I can see how "CSS4" may be a popular abbreviation for "CSS level 4 module"; however, the problem with collectively referring to all level 4 modules as "CSS4" or "CSS level 4" becomes clear when you consider the fact that CSS3 (or "CSS level 3", according to its proper definition) brings about completely new modules, such as Flexbox, Animations, Transforms, Transitions, Grid Layout, and Variables, that all start at level 1, yet are still (correctly) referred to as "CSS3".
The reason they all start at level 1 is because the features described are completely new to CSS, rather than extending existing CSS2.1 features. But, obviously, the next level after 1 is 2, not 4. Would these level 2 modules be considered "CSS4" modules as well, or not? What about the eventual level 3 and 4 revisions of those modules? It seems nobody among authors has thought of these things because it's never come up in real-world discussion outside of WG meetings. This could potentially be super confusing in tags when the time comes that people begin asking questions about these new features.
The "most right" thing to do that I can think of is to make css4 a synonym of css31, since essentially any new module past the original CSS2.1 standard, no matter what its level number is, is part of the collective CSS3 standard. Attempting to use css4 in a question would simply have it silently and painlessly changed to css3 without any major consequences, except more people being educated on what each term properly refers to (and does not refer to).
Besides, in the grand scheme of things it's not the level number that matters, but browser implementations that decide which features are specced in which modules. Having any distinction beyond "CSS3" is unnecessary and would only serve to confuse readers.

1 There's actually already a debate going on about whether [css3] should even exist separately from [css], although there hasn't been a proper meta thread on this yet so I'm not going to go into that here.

A:

Well, the masses who used them never understood what "mp3" files were named for. We call the place where we plug in the network cable a "RJ-45", and 9 pin serial connectors were commonly called DB-9. Many things were immediately popularly called the incorrect (official) name because the natural language evolution evokes an obvious name that is immediatly understood and commonly spontaneously used upon first needing to refer to this new thing.
People will try using a tag of css4. If that's rejected, they won't know what it should be. So make it automatic: css4 is a synonym that's automatically shown as css-level-4.

A:

I've gone ahead and removed the css4 tag from the question
So yeah, today I discovered that this tag existed and my first instinct was to remove the tag from that question. I then had a search here on meta to see if there had been any discussion about CSS4.
Why?
Almost 3 months on and that question you answered is the only one using the css4 tag.

Furthermore, the question was already appropriately tagged as css-selectors, whose wiki has, since 2013 stated:

Future Implementations:

W3C CSS Selectors Level 4 Working Draft

In fact, it was I who added that in there - bit of a coincidence that I find myself here a year and a half on!
I think the css-selectors tag alone suitably covers level 4 selectors which, after all, is the reason you added the css4 tag in the first place.


Q:

Save user inputs to database table asp.net

I am working on a school project where we are supposed to save user inputted data to a database we created within the project. I created a database, called 'db1', in the App_Data folder of my project, and created a table along with it, called 'Video_Games.' My code is somewhat of a Frankenstein's Monster, where it is from examples from my textbook as well as online examples.
Protected Sub btnTable_Click(sender As Object, e As EventArgs) Handles btnTable.Click
    Dim strTitle As String = txtTitle.Text
    Dim strConsole As String = txtConsole.Text
    Dim strYear As String = txtYear.Text
    Dim strESRB As String = txtRating.Text
    Dim strScore As String = txtScore.Text
    Dim strPublisher As String = txtPublisher.Text
    Dim strDeveloper As String = txtDeveloper.Text
    Dim strGenre As String = txtGenre.Text
    Dim strPurchase As String = calDate.SelectedDate.ToString

    Dim conn As SqlConnection
    Dim cmd As SqlCommand

    Dim cmdString As String = "INSERT INTO Video_Games(Title, Console, Year, ESRB, Score, Publisher, Developer, Genre, Purchase)
                                VALUES (@strTitle, @strConsole, @strYear, @strESRB, @strScore, @strPublisher, @strDeveloper, @strGenre, @strPurchase)"

    conn = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db1;Integrated Security=True;User Instance=True")
    cmd = New SqlCommand(cmdString, conn)

    cmd.Parameters.AddWithValue("@strTitle", strTitle)
    cmd.Parameters.AddWithValue("@strConsole", strConsole)
    cmd.Parameters.AddWithValue("@strYear", strYear)
    cmd.Parameters.AddWithValue("@strESRB", strESRB)
    cmd.Parameters.AddWithValue("@strScore", strScore)
    cmd.Parameters.AddWithValue("@strPublisher", strPublisher)
    cmd.Parameters.AddWithValue("@strDeveloper", strDeveloper)
    cmd.Parameters.AddWithValue("@strGenre", strGenre)
    cmd.Parameters.AddWithValue("@strPurchase", strPurchase)

    conn.Open()

    cmd.ExecuteNonQuery()

    conn.Close()

End Sub

Ther error I am getting is from the "conn.Open()" line is:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL
Judging by the error, I am assuming that it has to do with my 'conn = New SqlConnection' line, but I cannot find how to make it work. Thank you for any help you are able to give.

A:

I figured it out, took a completely different direction actually; I went the Access database rout instead of SQL. Thank you all for aiding and providing support. The code I used was:
Protected Sub btnDisplay_Click(ByVal sender As Object, ByVal e As System.EventArgs)

    Dim strTitle As String = txtTitle.Text
    Dim strConsole As String = txtConsole.Text
    Dim strYear As String = txtYear.Text
    Dim strESRB As String = txtRating.Text
    Dim strScore As String = txtScore.Text
    Dim strPublisher As String = txtPublisher.Text
    Dim strDeveloper As String = txtDeveloper.Text
    Dim strGenre As String = txtGenre.Text
    Dim strPurchase As String = calDate.SelectedDate.ToString
    Dim strDate As Date = calDate.SelectedDate
    Dim intYear As Integer = CInt(strYear)

    If strDate > Date.Today Then
            Response.Write("<script>alert('Error: The selected date must be today or earlier')</script>")
        Else
        lblDisp2.Text = "Data Saved to Database"

        Dim connection As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\db1.accdb"
        Dim query As String = "INSERT INTO [Video_Games](Title, Console, Year_Released, ESRB, Score, Publisher, Developer, Genre, Purchase)
                                VALUES (@strTitle, @strConsole, @strYear, @strESRB, @strScore, @strPublisher, @strDeveloper, @strGenre, @strPurchase)"

        Dim con As New OleDbConnection(connection)
        Dim cmd As New OleDbCommand()
        cmd.CommandText = query
        cmd.CommandType = CommandType.Text
        cmd.Connection = con

        cmd.Parameters.AddWithValue("@strTitle", strTitle)
        cmd.Parameters.AddWithValue("@strConsole", strConsole)
        cmd.Parameters.AddWithValue("@strYear", strYear)
        cmd.Parameters.AddWithValue("@strESRB", strESRB)
        cmd.Parameters.AddWithValue("@strScore", strScore)
        cmd.Parameters.AddWithValue("@strPublisher", strPublisher)
        cmd.Parameters.AddWithValue("@strDeveloper", strDeveloper)
        cmd.Parameters.AddWithValue("@strGenre", strGenre)
        cmd.Parameters.AddWithValue("@strPurchase", strPurchase)

        con.Open()
        Dim dr As OleDbDataReader = cmd.ExecuteReader()
        Dim dt As New DataTable()
        dt.Load(dr)
        con.Close()
    End If

End Sub


Q:

How can i add sequence no using awk to any input file?

Suppose i am having following data in a file name Details.txt:
0154 Raghav Sharma 26 Indore
0159 rakh   patid  24 Pune
0159 rakh   patid  24 Pune
0018 sai    kanak  28 mumbai
0159 rakh   patid     Pune
0159 sarak  jatid     Pune

now i have applied following awk command for generating 4 digit sequence no:
awk 'BEGIN{a=1;OFS="    "}/^/{$1=sprintf("%04d",a);++a;print $0; next;}{print $0}' Details.txt

output:
0001 0154 Raghav Sharma 26 Indore
0002 0159 rakh   patid  24 Pune
0003 0159 rakh   patid  24 Pune
0004 0018 sai    kanak  28 mumbai
0005 0159 rakh   patid Pune
0006 0159 sarak  jatid Pune

the formatting of last two rows are disturbed.Please suggest a way,so that
proper formatting along with correct sequence no can be maintained.

A:

You want to avoid recomputing $0; if you do, multiple spaces will be condensed to a single space:
$ cat Details.txt
0154 Raghav Sharma 26 Indore
0159 rakh   patid  24 Pune
0159 rakh   patid  24 Pune
0018 sai    kanak  28 mumbai
0159 rakh   patid     Pune
0159 sarak  jatid     Pune

$ gawk '{printf "%04d %s\n", NR, $0}' Details.txt
0001 0154 Raghav Sharma 26 Indore
0002 0159 rakh   patid  24 Pune
0003 0159 rakh   patid  24 Pune
0004 0018 sai    kanak  28 mumbai
0005 0159 rakh   patid     Pune
0006 0159 sarak  jatid     Pune


Q:

Can Silverlight downloads be zipped to speed up the download?

When Silverlight downloads the assemblies in your app can it be made to download them as zipped files and then uncompress them before running? This would speed up the download time for a large application.

A:

afaik silverlight 2 xap files are already zip compressed. So unless I misunderstood you there should not be much optimization through compression. (Edit: See other posts and comments on how to optimize through re-compression. Thanks!)
More Info: Structure of the xap file
What you could do is dynamically load additional assemblies after a small "bootstrap" version of your program distracts the user long enough to load the rest. ;)
Dynamically Loading an Assembly

A:

The Silverlight 2 .xap file format is already compressed, if you rename it to .zip you'll be able to open it in Windows Explorer for example.
The default compression is not as optimal as it can be however and so there are a few free utilities you can use to reduce the filesize of the .xap often dramatically.
Here are the best links:
http://web-snippets.blogspot.com/2008/11/another-one-on-repacking-xaps-to-reduce.html
http://blogs.msdn.com/delay/archive/2008/11/04/smaller-is-still-better-a-simple-step-continues-to-shrink-the-download-size-of-silverlight-2-applications.aspx
http://blogs.telerik.com/ValeriHristov/Posts/08-05-13/Increasing_the_compression_ratio_of_the_XAP_files.aspx


Q:

How to make mysqli connect function?

I'm having a problem with a function that connects me to the database using mysqli. What I'm aiming to have is to just type getConnected(); where I need the connection.
This is the code:
function getConnected()
{
    $host = 'localhost';
    $user = 'logintest';
    $pass = 'logintest';
    $db = 'vibo';

    $mysqli = new mysqli($host, $user, $pass, $db);

    if ($mysqli->connect_error) {
        die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
    }
}

This is the error I get when I try to use $mysqli after calling getConnected():

Notice: Undefined variable: mysqli in C:\xampp\htdocs\xampp\loginsystem\index.php on line 19

A:

As some users have suggested (and is the best way), return the mysqli instance
function getConnected($host,$user,$pass,$db) {

   $mysqli = new mysqli($host, $user, $pass, $db);

   if($mysqli->connect_error)
     die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

   return $mysqli;
}

Example:
$mysqli = getConnected('localhost','user','password','database');


Q:

Possible to create JavaFX Application object?

Would it be possible to make an Application object from javaFX?
public class Constructor
{
    public Constructor()
    {
        Application a = new Application()
        {
            @Override
            public void start(Stage window) throws Exception
            {

            }
        };
        a.launch();
    }
}

It currently gives me this when I try to run it:

Exception in thread "main" java.lang.RuntimeException: Error: class net.whiteautumn.lightcast.Constructor is not a subclass of javafx.application.Application

This, I presume, is caused by the class Constructor not extending Application.
Any way of getting around this or is that the only way to ever launch JavaFX applications?
EDIT:
I know how to start a javaFX application. What I want to to make an application and have it in an object. Is this possible or no?

A:

Application.launch() is a static method, therefore a.launch() is equivalent to Application.launch(). This means that it will try to launch an application of the class that calls it, which is Constructor class.
The correct way to do it is:
private static class MyApp extends Application
{
    @Override
    public void start(Stage window) throws Exception
    {

    }
};

Application.launch(MyApp.class, null);


Q:

Terminal: Adding logic to 'find' directories containing either [criteria A] or [criteria B]

I have inherited a vast media archive without a unifying organizational scheme. Its contents date back at least 10 years. I have been asked to find a needle in this hay stack, and I have some guesses as to that needle's name. But I don't know its name for certain. I want to use a single find command in the Terminal to search for alternate names. And I want to include a second set: possible file extensions. In pseudocode, here's what I mean: find [in a given directory] [files and folders whose name matches (*guess1* OR *guess2*) AND whose name matches (*.extension1 OR *.extension2)]. How should I express this in the Terminal?

A:

You can do this using ls and grep with regular expressions
ls | grep -E "(guess1|guess2)(\.extension1|\.extension2)"

Or if you need to recursively look into folders:
ls -R | grep -E "(guess1|guess2)(\.extension1|\.extension2)"


Q:

Font Changing to Inherited Font on Screensize Change

I'm attempting to make a simple site mobile responsive using "@media only screen", but one of my titles is reverting to an inherited font rather than continuing to use the CSS defined font.
//HTML
<head>
<meta name="viewport" content="width=device-width; initial-scale=1.0;">
<link rel="stylesheet" href="squirrelcss.css"  type="text/css">
<link href="https://fonts.googleapis.com/css?
family=Open+Sans:400,400i,700|Pacifico" rel="stylesheet">
</head>

<body>
<h4> Short Title </h4>
</body>

//CSS
[class*="h4"]{
font-size: 5vw;
}

@media only screen and (min-width: 800px){
h4{
font-family: 'Pacifico', cursive;
font-size: 2vw;
color:#474644;
margin-left: auto;
margin-right: auto;
margin-top: 0;
margin-bottom: 0;}}

On Inspect mode in Google Chrome, it indicates that upon a smaller screen size, h4 is inheriting it's font from it's container element, col-8.
.col-8{
font-family:'Open Sans', sans-serif;
}

Every other element on the site is correctly changing when the screen size is lowered below the defined 800px, including other text, and I've repeatedly cleared my cache throughout the process to no avail. !important seems to have no effect either.
What can I do to cause the h4 element to keep displaying the 'Pacifico' font instead of the inherited font?

A:

What can I do to cause the h4 element to keep displaying the 'Pacifico' font instead of the inherited font?
Just set font-family: 'Pacifico', cursive; to your h4 element outside of the @media statement. This way no matter the size of your page, Pacifico (as long as it has loaded) will be the font.
//HTML
  <head>
    <meta name="viewport" content="width=device-width; initial-scale=1.0;">
    <link rel="stylesheet" href="squirrelcss.css"  type="text/css">
    <link href="https://fonts.googleapis.com/css?
    family=Open+Sans:400,400i,700|Pacifico" rel="stylesheet">
    </head>

    <body>
    <div class="col-8">
    <h4> Short Title </h4>
    </div>
    </body>

//CSS
 h4{
    font-family: 'Pacifico', cursive;
    }

    .col-8{
    font-family:'Open Sans', sans-serif;
    }

    @media only screen and (min-width: 800px){
    h4{
    font-size: 2vw;
    color:#474644;
    margin-left: auto;
    margin-right: auto;
    margin-top: 0;
    margin-bottom: 0;}}


Q:

Setting logging levels using a variable

I haven't quite got the hang of Python enough to figure this out on my own, so I'm asking for help.
I have various logging messages scattered throughout my python module. I would like the code calling the module to be able to set the debug level by doing:
module.DEBUG = INFO
for instance. But I'm not able to translate that into work. I've got global variable "DEBUG", and I would like it to be interpreted in the following line, rather than DEBUG acting as a literal string, which is what I think is happening:
 logging.basicConfig(format='%(levelname)s - %(message)s', level=logging.DEBUG)

How can I make that string be treated as a variable instead of a literal (if that's what is happening?)
Thanks!
--Matt

A:

If you would like the calling code control the logging level on your module, you should consider accepting the log level as a parameter in your module. Below is some sample code on how you can do that:
import logging

class MyModule(object):
"""
Sample module to demonstrate setting of loglevel on init
"""

    def __init__(self, logLevel):
        #logLevel, a string, should be one of the levels of the logging modules. Example: DEBUG, INFO, WARNING etc.

        #Translate the logLevel input string to one of the accepted values of the logging module. Change it to upper to allow calling module to use lowercase
        #If it doesn't translate default to something like DEBUG which is 10
        numeric_level = getattr(logging, logLevel.upper(), 10)

        logging.basicConfig(filename='example.log', level=numeric_level)

    def testLogger(self):
        #logging object that you defined the level in init is used here for some sample logging
        logging.debug('see this at debug level')
        logging.info('see this at info and debug')
        logging.warning('see this at warn, info and debug')

if __name__ == "__main__":
    MM= MyModule('info')
    MM.testLogger()


Q:

User authentication design, are users people?

The application is written in Ruby on Rails but the problem I am facing is more a design matter than language related.
the system provides service to a number of users to maintain a registry. So it relates persons to things. As such it has a model called Person representing owners and it has a model called User representing those who manage the registry.
Now a new requirement has arisen to allow People to log in and be able to change personal details which it was not required for the original design.
The question is how to refactor the application to allow this new requirement in?
One easy solution is to create Users for each person who request login credentials and link user to person entity but that is not very DRY as some fields such as firstname, surname etc. are in both classes and in particular, that is precisely the data people will be able to change. Besides User and Person are stored in separate tables.
The other possibility I was considering is to make one to extend the other but having data in separated tables it makes it a bit messy. Additionally the logical extension would be User <- Person as an user is (generally) a person but thinking on the implementation Person <- User is quite a lot easier.
One last option could be to scrap User and move login credentials into Person leaving logon fields empty for those who won't log in and half of the fields empty for those just login in.
Can you think of a better solution?

A:

You could think about how this should ideally work if you were to write the application bottom-up, and then figure out how to make a reasonable compromise between that and your current setup. Here are some generic inputs.
As authentication is involved, you need an "Identity" that can be authenticated. This can be e.g. an email address and an associated password, with email verification.
An Identity can potentially be associated to multiple "Roles" and someone authenticated with the identity can choose which role to perform, e.g. "I am now an administrator" vs. "I am now a regular site user", and the role defines the user's current rights for the logged in identity. Or if you don't need that level of complexity, you can say that an Identity is a (single) Role.
You need some tracking between possible "Rights" and the Role the user is performing. E.g. the simplest setup could be the Identity or Role has some boolean can_edit_profile or can_modify_registry properties.
Whenever a user attempts to perform an action which requires certain Rights, it is simply a matter of looking up the corresponding rights set for the Role being performed by the user, to check whether the user is allowed to proceed.
For your application this may just involve adding a 'can_change_registry' property for your user objects, and check whether that property is True for any code accessing that part of the site.


Q:

mysql selection first letter of each word in a cell

I would like to return the first letter of each word in a MySQL column called 'initials'.
For example, my table may look like this:
|             project_unit              | initials |
+---------------------------------------+----------+
|      Mbita Clinic Rehabilitation      |   MCR    |
| Management Strategy for Thrips Cowpea |   MSTC   |

Any suggestions?

A:

You can use below mentioned function to achieve your requirement.
 DELIMITER $$
CREATE FUNCTION split_string(split_string varchar(255),my_delimiter varchar(1)) RETURNS varchar(10)
BEGIN
DECLARE temp_string varchar(255);
DECLARE occurance INT;
DECLARE i INT;
DECLARE temp_result varchar(10);
DECLARE final_result varchar(10);
SET temp_result = '';
SET occurance=length(split_string)-length(replace(split_string,' ',''))+1;
  IF occurance > 0 then
    set i=1;
    while i <= occurance do
        set temp_string = (select SUBSTRING_INDEX(SUBSTRING_INDEX(split_string, my_delimiter, i),my_delimiter ,-1));
        set temp_result = CONCAT(temp_result, SUBSTRING(temp_string,1,1));
      set i=i+1;
    end while;
  ELSE
        set temp_result = SUBSTRING(split_string,1,1);
  END IF;
  set occurance=0;
  SET final_result = temp_result;
  RETURN (final_result);
END $$
DELIMITER ;

You can use it like this :
SELECT Projcect_unit, split_string(Projcect_unit,' ') as initials FROM main_table;


Q:

Jupiterlab print DataFrame nicely

If you let the a Dataframe at the end of a cell you get a nice table that react to the mouse (mouse-over makes the line blue). Considering that I want to print a set of DataFrames like that, how may I do it?

A:

You can use display function
from IPython.display import display

and in your targeted cell
display(df1)
#
# Some code here
#
display(df2)


Q:

Formula for Calculating bandwidth

Really confused with bandwidth calculation formula.
Referring to the bandwidth detection question Check the bandwidth rate in Android i am trying to calculate bandwidth as following.
long startTime = System.currentTimeMillis();
HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
long contentLength = httpEntity.getContentLength();
long endTime = System.currentTimeMillis();
float bandwidth = contentLength / ((endTime-startTime) / 1000); // In the refereed question it is "((endTime-startTime) * 1000)" don't know why multiplication.

What i need is current bandwidth in bits (not bytes or kbytes). I don't know using above formula if it is calculating bandwidth in bytes or bits.
also if download time is 0 seconds then what should be the bandwidth is it downloaded content length.
can someone please suggest correct formula to calculate bandwidth in bits.

A:

First of all for precision's sake, you should use 1000.0 to convert to seconds since you are assigning your bandwidth to a float variable:
float bandwidth = (contentLength / (endTime-startTime)) / 1000.0;

Now since your contentLength is measured in bytes, you need to convert to bits (Kb, Mb, etc). There are 8 bits to each byte and socontentLength*8 converts bytes to bits.
Kilo->Mega->Giga ->... scale conversion for the unit of bits is on the order of 1000 which means converting bits to Megabits requires a division by 1000*1000. All this put together should yield:
int bits = contentLength * 8;
int megabits = contentLength / (1000*1000); //Megabits
float seconds = endTime-startTime / 1000.0;
float bandwidth = (megabits / seconds);  //Megabits-per-second (Mbps)

EDIT #1: If bandwidth is denominated by Bytes/Time (like KB/s for example), scale conversion is on the order of 1024
int bytes = contentLength;
int kilobytes = contentLength / 1024; //Kilobytes

EDIT #2: The definition of "Mega" and "Kilo" etc. when talking in terms of bandwidth can  be somewhat ambiguous I am realizing. Often times 1024 (210) and 1000 (103) may be used interchangeably (most likely an accident). For many cases 1024 may be favored as the order of magnitude when calculating bandwidth as memory storage space on computers is measured in base 2. However network bandwidth is usually controlled by the clock speed of a CPU which regulates the transmission of bits, and this rate is measured in hertz (MHz to be exact) which is on the order of magnitude of 1000, not 1024. However in most cases, these two numbers are close enough to not produce significant error.

A:

Based on your link that you gave its commented that its // Bandwidth : size(KB)/time(s) so just multiply it by 1024 to get bytes or 1024*8 to get it in bits, And if the download time is 0 then technically nothing has been downloaded because speed is amout/time
1.For calculating in bits just use
float bandwidth = contentLength / ((endTime-startTime) *(1000*1024*8));

2.If the dowload time is 0 then nothing has been downloaded so we cannot suggest the bandwith
EDIT 2
CALCULATION
Thats just simple math
If you have kb per second like 1 kb/ per 1 second
so speed is 1 kbps => 1*(1024 bytes)/ 1* (1000000000 nano seconds)
so its 0.000001024 bytes per nano seonds
now in bits would be 1*(1024 * 8 bits)/ 1* (1000000000 nano seconds)
so its 0.000008192 bits per nano seconds
now if you want it in seoncds then just multiply it by 1000000000
so its 0.000008192 * 1000000000 = 8192 bits per second
and (0.000008192/8) * 1000000000 = 1024 bytes per second or 1 kbps

A:

public static String internetSpeed(long msecs, long bytes)
{
    long  secs  = msecs / 1000;
    long  bits  = bytes * 8;
    float speed = bits / secs;

    long  Kbit  = 1024;
    long  Mbit  = Kbit * 1024;
    long  Gbit  = Mbit * 1024;

    if (speed < Kbit )                  return String.valueOf(speed)        + " bit-sec" ;
    if (speed > Kbit && speed < Mbit)   return String.valueOf(speed / Kbit) + " Kbit-sec";
    if (speed > Mbit && speed < Gbit)   return String.valueOf(speed / Mbit) + " Mbit-sec";
    if (speed > Gbit)                   return String.valueOf(speed / Gbit) + " Gbit-sec";
    return "???";
}

You can call this method like
....
System.out.println(internetSpeed((endTime-startTime), contentLength));
....


Q:

An efficient way to score two tests in an R data.table

Suppose I have the following data.table with answers to two different tests, red and blue:
library(data.table)
dt <- data.table(
  class = rep("math", 4),
  test = c("red", "red", "blue", "red"),
  student = 1:4,
  q1_answer = c("a", "a", "b", "a"),
  q2_answer = c("b", "c", "b", NA),
  q3_answer = c("c", "c", "c", NA)
)
# dt
#   class test student q1_answer q2_answer q3_answer
#1:  math  red       1         a         b         c
#2:  math  red       2         a         c         c
#3:  math blue       3         b         b         c
#4:  math  red       4         a      <NA>      <NA>

The answer keys for the blue and red tests are the following:
red_answer_key <- c("a", "b", "c")
blue_answer_key <- c("b", "c", "d")

How could I score the two tests so I would have the score column in the following table?
#   class test student q1_answer q2_answer q3_answer score
#1:  math  red       1         a         b         c     3
#2:  math  red       2         a         c         c     2
#3:  math blue       3         b         b         c     1
#4:  math  red       4         a      <NA>      <NA>     1  # count NA as incorrect

A:

One option:
key_list <- list(
  red = red_answer_key,
  blue = blue_answer_key
)
dt_long <- dt[, melt(.SD, id.vars = c("class", "test", "student"))]
dt_scores <- dt_long[, .(score = sum(value == key_list[[test]])), keyby = .(student, test)]
# Join back inz
dt[, score := dt_scores[.SD, on = .(student, test), score]]

#    class test student q1_answer q2_answer q3_answer score
# 1:  math  red       1         a         b         c     3
# 2:  math  red       2         a         c         c     2
# 3:  math blue       3         b         b         c     1
# 4:  math  red       4         a      <NA>      <NA>    NA


Q:

How to inspect the contents of a container of a pod deployed with Kubernetes

I run an .NET Core 2.1 in a container. It writes logs to a file within the container. I am able to run a docker exec bash command to inspect the log file, locally.
This application is then deployed with Kubernetes to a pod with more than one container.
How can I inspect the log file within each one of these containers?

A:

You can exec into container within pod:
kubectl -n <namespace> exec -it <pod name> -c <container name> bash

But the better approach is to make your application stream logs to stdout or stderr, so you can access it directly with:
kubectl -n <namespace> logs <pod name> -c <container name>


Q:

Random variable exercise

given the random variables $X$ and $Y$, such that
$Pr\{X=1\} = Pr\{X=2\} = Pr\{X=3\} = Pr\{X=4\} = Pr\{X=5\} = \frac15$
and
$Pr\{Y=1\} = \frac12$, $Pr\{Y=2\} = Pr\{Y=3\} = Pr\{Y=4\} = Pr\{Y=5\} = \frac18$,
where $Pr\{\}$ represents the probability that a random variable takes on a certain value, compute:
1) $Pr\{X > Y\}$;
2) the probability that $X + Y$ is odd;
3) the conditional probability of "$X$ is even" given "$X + Y$ is odd".
Could you help me to solve this problem?
Thank you!

A:

1) Hint: As $\Pr(X>x) = 1-\frac{x}{5}$, can you find $\Pr(X>Y) = \sum_{x=2}^{5} \Pr(X>x)\Pr(Y=y)\quad$  (assuming $X\perp Y$)
2) Hint: $\newcommand{\odd}{\operatorname{odd}}\newcommand{\even}{\operatorname{even}} \Pr(\odd(X+Y)) = \Pr(\odd(X),\even(Y)) + \Pr(\even(X),\odd(Y))$
3) To evaluate $\Pr(\even(X)\mid \odd(X+Y))$ use the definition of conditional probability (and the above).


Q:

Objective Pascal - How do you ensure that you call a decendant's methods when cast as an acestor?

I'm currently creating a small RPG engine. I've just gotten to the point of implementing a class tree for the game's objects and I'm not 100% sure which method directives I should use where and in what cases.
I've looked over the Free Pascal Complier's reference guide and various other internet resources but I'm still not confident.
The way I'm planning to implement the handling of game objects requires that categories of game objects have a common base class and will be stored in an array of that class, thus casting them as an ancestor.
What I mainly need to understand is how to ensure that when I call a class cast as one of it's ancestors that it calls the overloaded/overridden/reintroduced method of the actual class rather than that of the ancestor's.
Thanks for your time!
I'm quite happy to clarify/re-word anything here if I'm not being clear enough.

A:

You're not "casting" when you put them into an array of their parent class, and you shouldn't be; that's not how inheritance and polymorphism works.
You create a virtual method in the parent (ancestor), and then each child inherits the parent's method and overrides it with their own specific behavior. When you call the parent method, polymorphism makes sure the proper method gets called.
Here's a quick (trivial) example of how something like this should be constructed. It's in the form of a console application, so that you can actually run it to see the output.
program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
  // Base class
  TAnimal=class
    procedure Sit; virtual;   // Virtual keyword *necessary* for things to work
    procedure Speak; virtual;
  end;

  // Descendent classes
  TDog=class(TAnimal)
    procedure Sit; override;    // Override keyword required here
    procedure Speak; override;
  end;

  TCat=class(TAnimal)
    // No implementation of Sit, because cats don't sit on command
    procedure Speak; override;  // Override required here also
  end;

  // Array type to hold them, so we don't have to typecast anything
  TAnimalArray = array of TAnimal;

// Implementation of classes

{ TAnimal }
procedure TAnimal.Sit;
begin

end;

procedure TAnimal.Speak;
begin
  // Parent does nothing
end;

{ TCat }
procedure TCat.Speak;
begin
  inherited;
  WriteLn('Meow.');
end;

{ TDog }
procedure TDog.Sit;
begin
  inherited;
  WriteLn('Sitting down now.');
end;

procedure TDog.Speak;
begin
  inherited;
  Writeln('Woof! Woof!');
end;

// Test code to demonstrate use of inheritance and polymorphism
var
  Animals: TAnimalArray;
  i: Integer;
  Pet: TAnimal;   // Variable that holds parent type (TAnimal)

const
  NumberOfAnimals = 5;

begin
  SetLength(Animals, NumberOfAnimals);

  // Fill array with a mix of both dogs and cats
  for i := 0 to High(Animals) do
  begin
    if Odd(i) then
      Animals[i] := TDog.Create
    else
      Animals[i] := TCat.Create;
  end;

  // Loop to use each one regardless of which type, by just accessing the
  // virtual Speak method they overrode from their parent class

  for Pet in Animals do
  begin
    Pet.Speak;
    Pet.Sit;     // Call method only defined for TDog
  end;

  WriteLn('');  // Blank line in console to separate loops.

  // If FreePascal doesn't support the enumeration (for..in) method, do it
  // using a counter:

  for i := 0 to High(Animals) do
  begin
    Animals[i].Speak;
    Animals[i].Sit;     // Call method only defined for TDog
  end;

  // In real life code, you'd loop through the array and free each one here.
  // In this test code, we're exiting right away, and there's really no point
  Readln;
end.

The above produces the output:
Meow.
Woof! Woof!
Sitting down.
Meow.
Woof! Woof!
Sitting down.
Meow.

Meow.
Woof! Woof!
Sitting down.
Meow.
Woof! Woof!
Sitting down.
Meow.

You can find a fairly complete discussion of Delphi's implementation of OOP at the docwiki. Although it's not FreePascal, much of it is compatible, and so it should be somewhat equivalent. I'm not aware of any documentation like it for FPC.


Q:

How is physicalism true?

Assumptions:

Human auras exist.
There is a subset of the population who are capable of discerning their properties, by whatever means.
Machines can not sense human auras.

Following these assumptions, how is physicalism true?

Physicalism is the thesis that everything is physical, or as contemporary philosophers sometimes put it, that everything supervenes on, or is necessitated by, the physical.

EDITED IN RESPONSE TO COMMENTS

A:

I can smell peach-flavored oolong tea and tell you what it is; a machine cannot (not yet, anyway).
This has nothing to do with mind-body duality.  We simply haven't built chemosensors as diverse and sensitive as those in our noses.
Auras are, logically, just like the smell of peach-flavored oolong tea (except for not having good evidence that they actually exist).


Q:

Using Subqueries to Define Column Alias

I have two tables which I have simplified below for clarity. One stores data values while the other defines the units and type of data. Some tests have one result, others may have more (My actual table has results 1-10):
Table 'Tests':
ID            Result1        Result2        TestType(FK to TestTypes Type)
----------    ------------   -----------    -----------
1001           50            29             1
1002           90.9          NULL           2
1003           12.4          NULL           2
1004           20.2          30             1

Table 'TestTypes':
Type        TestName         Result1Name    Result1Unit   Result2Name     Result2Unit   ..........
-------     ---------        ------------   -----------   ------------    -----------
1           Temp Calib.      Temperature    F             Variance        %
2           Clarity          Turbidity      CU            NULL            NULL

I would like to use the ResultXName as the column alias when I join the two tables. In other words, if a user wants to see all Type 1 'Temp Calib' tests, the data would be formatted as follows:
Temperature      Variance
------------     -----------
50 F             10.1%
20.2 F           4.4%

Or if they look at Type 2, which only uses 1 result and should ignore the NULL:
Turbidity
----------
90.9 CU
12.4 CU

I have had some success in combining the two columns of the tables:
SELECT CONCAT(Result1, ' ', ISNULL(Result1Unit, ''))
FROM Tests
INNER JOIN TestTypes ON Tests.TestType = TestTypes.Type

But I cannot figure out how to use the TestName as the new column alias. This is what I've been trying using a subquery, but it seems subqueries are not allowed in the AS clause:
SELECT CONCAT(Result1, ' ', ISNULL(Result1Unit, '')) AS (SELECT TOP(1) Result1Name FROM TestTypes WHERE Type = 1)
FROM Tests
INNER JOIN TestTypes ON Tests.TestType = TestTypes.Type

Is there a different method I can use? Or do I need to restructure my data to achieve this? I am using MSSQL.

A:

Yes, this can be fully automated by constructing a dynamic SQL string carefully. The key points in this solution and references is listed as follows.

Count the Result variables (section 1.)
Get the new column name of ResultXName by using sp_executesql with the output definition (section 2-1)
Append the clause for the new column (section 2-2)

N.B.1. Although a dynamic table schema is usually considered a bad design, sometimes people are simply ordered to do that. Therefore I do not question the adequacy of this requirement.
N.B.2. Mind the security problem of arbitrary string execution. Additional string filters may be required depending on your use case.
Test Dataset
use [testdb];
GO

if OBJECT_ID('testdb..Tests') is not null
    drop table testdb..Tests;
create table [Tests] (
    [ID] int,
    Result1 float,
    Result2 float,
    TestType int
)
insert into [Tests]([ID], Result1, Result2, TestType)
values (1001,50,29,1),
       (1002,90.9,NULL,2),
       (1003,12.4,NULL,2),
       (1004,20.2,30,1);

if OBJECT_ID('testdb..TestTypes') is not null
    drop table testdb..TestTypes;
create table [TestTypes] (
    [Type] int,
    TestName varchar(50),
    Result1Name varchar(50),
    Result1Unit varchar(50),
    Result2Name varchar(50),
    Result2Unit varchar(50)
)
insert into [TestTypes]([Type], TestName, Result1Name, Result1Unit, Result2Name, Result2Unit)
values (1,'Temp Calib.','Temperature','F','Variance','%'),
       (2,'Clarity','Turbidity','CU',NULL,NULL);

--select * from [Tests];
--select * from [TestTypes];

Solution
/* Input Parameter */
declare @type_no int = 1;

/* 1. determine the number of Results */

declare @n int;

-- If there are hundreds of results please use the method as of (2-1)
select @n = LEN(COALESCE(LEFT(Result1Name,1),''))
          + LEN(COALESCE(LEFT(Result2Name,1),''))
FROM [TestTypes]
where [Type] = @type_no;

/* 2. build dynamic query string */

-- cast type number as string
declare @s_type varchar(10) = cast(@type_no as varchar(10));
-- sql query string
declare @sql nvarchar(max) = '';
declare @sql_colname nvarchar(max) = '';
-- loop variables
declare @i int = 1;  -- loop index
declare @s varchar(10);  -- stringified @i
declare @colname varchar(max);  -- new column name

set @sql += '
select
    L.[ID]';

-- add columns one by one
while @i <= @n begin

    set @s = cast(@i as varchar(10));

    -- (2-1) find the new column name
    SET @sql_colname = N'select @colname = Result' + @s + 'Name
        from [TestTypes]
        where [Type] = ' + @s_type;

    EXEC SP_EXECUTESQL
        @Query = @sql_colname,
        @Params = N'@colname varchar(max) OUTPUT',
        @colname = @colname OUTPUT;

    -- (2-2) sql clause of the new column
    set @sql += ',
      cast(L.Result' + @s + ' as varchar(10)) + '' '' + R.Result' + @s + 'Unit as [' + @colname + ']'

    -- next Result
    set @i += 1
end

set @sql += '
    into [ans]
    from [Tests] as L
    inner join [TestTypes] as R
        on L.TestType = R.Type
    where R.[Type] = ' + @s_type;

/* execute */

print @sql;  -- check the query string

if OBJECT_ID('testdb..ans') is not null
    drop table testdb..ans;
exec sp_sqlexec @sql;

/* show */
select * from [ans];

Result (type = 1)
| ID   | Temperature | Variance |
|------|-------------|----------|
| 1001 | 50 F        | 29 %     |
| 1004 | 20.2 F      | 30 %     |

/* the query string */

select
    L.[ID],
      cast(L.Result1 as varchar(10)) + ' ' + R.Result1Unit as [Temperature],
      cast(L.Result2 as varchar(10)) + ' ' + R.Result2Unit as [Variance]
into [ans]
from [Tests] as L
inner join [TestTypes] as R
    on L.TestType = R.Type
where R.[Type] = 1

Tested on SQL Server 2017 (linux docker image, latest version) on debian 10


Q:

imshow when you are plotting data, not images. Realtion between aspect and extent?

I am plotting a 2D data array with imshow in matplotlib. I have a problem trying to scale the resulting plot. The size of the array is 30x1295 points, but the extent in units are:
    extent = [-130,130,0,77]
If I plot the array without the extent, I get the right plot, but if I use extent, I get this plot with the wrong aspect.
It is a pretty beginner question, but there is always a first time: How I can control the aspect and the size of the plot at the same time?
Thanks,
Alex
P.D. The code is, for the right case:
    imshow(np.log10(psirhoz+1e-5),origin='lower')
and for the wrong one:
    imshow(np.log10(psirhoz+1e-5),origin='lower',
    extent =[z_ax.min(),z_ax.max(),rho_ax.min(),rho_ax.max()])
I hope this clarify a bit things.

A:

I'm guessing that you're wanting "square" pixels in the final plot?
For example, if we plot random data similar to yours:
import numpy as np
import matplotlib.pyplot as plt

data = np.random.random((30, 1295))

fig, ax = plt.subplots()
ax.imshow(data, extent=[-130,130,0,77])
plt.show()

We'll get an image with "stretched" pixels:

So, first off, "aspect" in matplotlib refers to the aspect in data coordinates.  This means we have to jump through a couple of hoops to get what you want.
import numpy as np
import matplotlib.pyplot as plt

def main():
    shape = (30, 1295)
    extent = [-130,130,0,77]

    data = np.random.random(shape)

    fig, ax = plt.subplots()
    ax.imshow(data, extent=extent, aspect=calculate_aspect(shape, extent))
    plt.show()

def calculate_aspect(shape, extent):
    dx = (extent[1] - extent[0]) / float(shape[1])
    dy = (extent[3] - extent[2]) / float(shape[0])
    return dx / dy

main()

A:

In this case, pyplot.matshow() might also be useful:
from matplotlib import pyplot as plt
import numpy as np
dat = np.array(range(9)).reshape(3,3)
plt.matshow(dat)
plt.show()

result: