text:
Q: Aplicativo fechando na interação com o usuário após ser resumido Estou brincando com um aplicativo que controla o flash do meu celular, porém o mesmo dá force close assim que o usuário interage com o aplicativo, após ele ter sido resumido.
Por Exemplo:

*

*Abri o aplicativo

*Ativei e desativei a lanterna

*Desliguei a tela

*Liguei a tela e desbloqueei o telefone

*Tentei ativar a lanterna

*force close
Meu código:
package com.bravosix.lanterna;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

public class Tela_Lanterna extends Activity {

    private boolean isFlashOn;
    private Camera mCamera;
    private ImageButton mImageButton;
    private PackageManager mPackage = null;
    // private AlertDialog mNoCameraAlert;
    private Parameters mParameters;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.layout_lanterna);

        mPackage = this.getPackageManager();
        mImageButton = (ImageButton) findViewById(R.id.toggle_img);
        mImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toggleFlash();
            }
        });

        mCamera = Camera.open();
        mParameters = mCamera.getParameters();

        if (!verificarFlash(mPackage)) {
            Toast.makeText(this, "Dispositivo não possui flash!",
                    Toast.LENGTH_SHORT).show();
            return;
        }

    }

    private void toggleFlash() {
        if (!isFlashOn) {
            mParameters = mCamera.getParameters();
            mParameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
            mCamera.setParameters(mParameters);
            mCamera.startPreview();
            mImageButton.setImageResource(R.drawable.btn_ligado);
            isFlashOn = true;
        } else if (isFlashOn) {
            mParameters = mCamera.getParameters();
            mParameters.setFlashMode(Parameters.FLASH_MODE_OFF);
            mCamera.setParameters(mParameters);
            mCamera.stopPreview();
            mImageButton.setImageResource(R.drawable.btn_desligado);
            isFlashOn = false;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isFlashOn) {
            toggleFlash();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mCamera != null) {
            mCamera.release();
            mCamera = null;
        }
    }

    private boolean verificarFlash(PackageManager mPackage) {
        if (mPackage.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_lanterna, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_configs) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Meu logcat:
04-22 15:46:47.994: E/AndroidRuntime(29553): FATAL EXCEPTION: main
04-22 15:46:47.994: E/AndroidRuntime(29553): Process: com.bravosix.lanterna, PID: 29553
04-22 15:46:47.994: E/AndroidRuntime(29553): java.lang.NullPointerException
04-22 15:46:47.994: E/AndroidRuntime(29553):    at com.bravosix.lanterna.Tela_Lanterna.toggleFlash(Tela_Lanterna.java:52)
04-22 15:46:47.994: E/AndroidRuntime(29553):    at com.bravosix.lanterna.Tela_Lanterna.access$0(Tela_Lanterna.java:50)
04-22 15:46:47.994: E/AndroidRuntime(29553):    at com.bravosix.lanterna.Tela_Lanterna$1.onClick(Tela_Lanterna.java:35)
04-22 15:46:47.994: E/AndroidRuntime(29553):    at android.view.View.performClick(View.java:4456)
04-22 15:46:47.994: E/AndroidRuntime(29553):    at android.view.View$PerformClick.run(View.java:18462)
04-22 15:46:47.994: E/AndroidRuntime(29553):    at android.os.Handler.handleCallback(Handler.java:733)
04-22 15:46:47.994: E/AndroidRuntime(29553):    at android.os.Handler.dispatchMessage(Handler.java:95)
04-22 15:46:47.994: E/AndroidRuntime(29553):    at android.os.Looper.loop(Looper.java:136)
04-22 15:46:47.994: E/AndroidRuntime(29553):    at android.app.ActivityThread.main(ActivityThread.java:5102)
04-22 15:46:47.994: E/AndroidRuntime(29553):    at java.lang.reflect.Method.invokeNative(Native Method)
04-22 15:46:47.994: E/AndroidRuntime(29553):    at java.lang.reflect.Method.invoke(Method.java:515)
04-22 15:46:47.994: E/AndroidRuntime(29553):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-22 15:46:47.994: E/AndroidRuntime(29553):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-22 15:46:47.994: E/AndroidRuntime(29553):    at dalvik.system.NativeStart.main(Native Method)

Não entendi o por que do erro ser NullPointerException.

A: Julgo que o seu problema está na forma como você gere o "activity lifecycle".
Faça o seguinte:
Passe o código que tem em onStop para onPause
@Override
protected void onPause() {
    super.onPause();
    if (isFlashOn) {
        toggleFlash();
    }
    if (mCamera != null) {
        mCamera.release();
        mCamera = null;
    }

Passe a parte do código referente à camera que está em onCreatepara onResume
@Override
protected void onResume() {
    super.onResume();
    if (mCamera == null) {
        mCamera = Camera.open();
    }
    if(mPackage == null){
        mPackage = this.getPackageManager();
    }
    mParameters = mCamera.getParameters();
    if (!verificarFlash(mPackage)) {
        Toast.makeText(this, "Dispositivo não possui flash!",
                Toast.LENGTH_SHORT).show();
        finish();
    }
}


text:
Q: UEFI SSD hidden from Linux? I have a HP Prodesk 600 G3, and I were able to install Fedora 28 on the nvme SSD. When I put the computer in BIOS mode, then I wasn't able to see the UEFI Fedora SSD anymore from the BIOS or from a booted USB stick.
When I restored the BIOS to factory defaults, ie UEFI mode, then I could see the fedora SSD again from UEFI, but I can't see the device when I boot from an USB stick.
When in UEFI mode, I can start Grub, and with ls see the 3 GPT partitions.
Problem
Since the Fedora is somehow broken, I can't boot it up. Not even in single user mode.
When in UEFI mode I can't see the fedora SSD from a booted USB stick.
When in BIOS mode, the Fedora SSD is gone from both the BIOS and a booted USB stick.
Question
I am guessing if I were able to erase the Fedora SSD with all zeroes, then I would be able to see the SSD again from BIOS mode.
Could TPM somehow play a role in this?
Does anyone have an idea how to solve this?

A: The important part is, that it is an NVME SSD: It needs driver support to be seen by the OS and the firmware. Your firmware obviously doesn't have the necessary bits baked into BIOS, but it does have in UEFI (This is quite normal: NVME wasn't invented, when BIOS was the standard firmware model).
If you boot with a USB stick, you might need to load those drivers manually - they are quite often not part of a standard rescue image. Try modprobe nvme on any modern distro (Ubuntu Bionic Server is known to work).
I had to overcome a similar problem: One of the servers I am responsible for wouldn't boot from NVME at all, the only solution was to put /boot on a tiny slice of one of the SAS disks.

A: I also had the same problem, when changed the boot mode to UEFI and SSD was not visible from Linux (Arch).  Then I enabled Enabled Attempt Legacy Boot from BIOS and then it detected.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQLite3 in Adobe Plugin extensions I have developed a plugin for Adobe Illustrator and I am trying to use sqlite3 or better-sqlite3 node packages instead of mySQL. But I am getting following errors on Mac and Windows.
Windows (using sqlite3)

Uncaught Error: A dynamic link library (DLL) initialization routine failed.

Mac (using better-sqlite3)

Uncaught Error: dlopen(...): no suitable image found.
  Did find: [...] code signature in (...) not valid for use in process using Library Validation: mapped file has no cdhash, completely unsigned? Code has to be at least ad-hoc signed.

Is it possible to use sqlite3 or better-sqlite3 in Adobe plugins?

A: Welcome here,
This is not possible because Sqlite3 and all its wrapper uses Node C++ Addon and not js package. C++ addons are not supported by CEP as per the official word.
Link for the reference
https://github.com/Adobe-CEP/CEP-Resources/issues/70


text:
Q: How to access data in block which is passed from controller I have a controller and I have created block using createBlock method in controller and have passed a userid to it

$block =  $this->_pageFactory->create();
$block->getLayout()
  ->createBlock('Magecomp\Crud\Block\GetUserById','magecompcrud.edituser',['data'=>['userid'=>$userid]]);

Now how can I access this userid in blcok or blcok method

A: you can use setData after createBlock
example

$block->getLayout()->createBlock()->setData('key',value)

To retrieve data from block

$block->getData('key');


text:
Q: How to Make an Android 3D Carousel Drawable I'm trying to create a 3D carousel in Android (Java) but I can't quite get it to work. This is the kind of carousel I'm aiming for:

I've tried several long and complicated ways of doing this, including drawing paths by hand that use a ton of math, but it's never quite right.
The idea that feels closest is to draw a carousel of images in the x-y plane by calculating their positions on a circle, and then "flipping" that plane so the carousel is now in the x-z direction. That seems to almost work (though the corners don't quite touch), but the squares are lying flat and I need them to stand up on their outermost edge. I can't figure out how to do that final rotation though in a way that doesn't undo the previous rotations by the camera.
Here is what my result looks like visually currently:

Am I going about this complete the wrong way? Am I close but need to just change a couple of things? I'm honestly not sure. Please help me figure out how to do this better!
Here is my drawable code:
public class CarouselCard extends Drawable {

    Paint paintBackground = null;

    /* CONSTRUCTOR */

    public CarouselCard() {
        super();
        invalidateSelf();
    }

    @Override
    public void draw(Canvas canvas) {

        if (paintBackground == null) {    // Just starting
            paintBackground = new Paint();
            paintBackground.setStyle(Paint.Style.FILL);
            paintBackground.setColor(Color.BLUE);
        }

        int HALF_CHORD_WIDTH = 150;
        float RADIUS = 200;

        float INTERIOR_ANGLE = 30;

        INTERIOR_ANGLE %= 360;
        int numObjects = (int) (360 / INTERIOR_ANGLE);

        for (int i = 0; i < numObjects; i++) {

            float theta = INTERIOR_ANGLE * i;
            double rad = Math.toRadians(theta);

            float circleX = (float) (RADIUS * Math.sin(rad));
            float circleY = (float) (RADIUS * Math.cos(rad));

            canvas.save();
            canvas.translate(canvas.getWidth() / 2, canvas.getHeight() / 2);

            Camera camera = new Camera();
            camera.save();

            camera.rotateX(80); // Approximates 90 but keeps it visible since flat
            camera.rotateZ(theta);

            camera.applyToCanvas(canvas);
            camera.restore();

            if (i % 4 == 0) paintBackground.setColor(Color.YELLOW);
            if (i % 4 == 1) paintBackground.setColor(Color.GREEN);
            if (i % 4 == 2) paintBackground.setColor(Color.BLUE);
            if (i % 4 == 3) paintBackground.setColor(Color.GRAY);

            paintBackground.setAlpha(128);

            canvas.drawRect(circleX-HALF_CHORD_WIDTH, circleY-HALF_CHORD_WIDTH,
                    circleX+HALF_CHORD_WIDTH, circleY+HALF_CHORD_WIDTH, paintBackground);

            canvas.restore();
        }
    }

    @Override
    public void setAlpha(int alpha) {}

    @Override
    public void setColorFilter(ColorFilter colorFilter) {}

    @Override
    public int getOpacity() {
        return PixelFormat.UNKNOWN;
    }
}

Alternatively, I can get everything facing the right way and oriented correctly, but only if they're all co-located at the center of the carousel. I'm not sure how to shift them appropriately while still maintaining the transformations that make this picture possible:

This image was produced by adjusting the above for-loop like so:
for (int i = 0; i < numObjects; i++) {

    if (i % 4 == 0) paintBackground.setColor(Color.YELLOW);
    if (i % 4 == 1) paintBackground.setColor(Color.GREEN);
    if (i % 4 == 2) paintBackground.setColor(Color.BLUE);
    if (i % 4 == 3) paintBackground.setColor(Color.GRAY);
    paintBackground.setAlpha(128);

    float theta = INTERIOR_ANGLE * i;

    canvas.save();
    canvas.translate(canvas.getWidth() / 2, canvas.getHeight() / 2);

    Camera camera = new Camera();
    camera.save();

    camera.rotateY(theta);

    camera.applyToCanvas(canvas);
    camera.restore();

    canvas.drawRect(
            -HALF_CHORD_WIDTH,
            -HALF_CHORD_WIDTH,
            HALF_CHORD_WIDTH,
            HALF_CHORD_WIDTH,
            paintBackground);

    canvas.restore();
}

A: I was able to create the following carousel:

The code for it is:
@Override
public void draw(Canvas canvas) {

    if (paintBackground == null) {    // Just starting
        paintBackground = new Paint();
        paintBackground.setStyle(Paint.Style.FILL);
        paintBackground.setColor(Color.BLUE);
    }

    // ######## CRUCIAL - START - Modify constants with care!

    // Decreasing chord denominator makes carousel bigger, while increasing it
    // makes front side contain more squares (but gets smaller)

    float HALF_CHORD_WIDTH = canvas.getWidth()/31f; // Width of each square
    float RADIUS = HALF_CHORD_WIDTH; // Radius of carousel
    float CAMERA_MULT = HALF_CHORD_WIDTH/10f;

    // ######## CRUCIAL - END

    float INTERIOR_ANGLE = 30;

    INTERIOR_ANGLE %= 360;
    int numObjects = (int) (360 / INTERIOR_ANGLE);

    for (int i = 0; i < numObjects; i++) {

        if (i % 4 == 0) paintBackground.setColor(Color.YELLOW);
        if (i % 4 == 1) paintBackground.setColor(Color.GREEN);
        if (i % 4 == 2) paintBackground.setColor(Color.BLUE);
        if (i % 4 == 3) paintBackground.setColor(Color.GRAY);
        paintBackground.setAlpha(128);

        float theta = INTERIOR_ANGLE * i;
        double rad = Math.toRadians(theta);

        float circleX = (float) (RADIUS * Math.sin(rad));
        float circleZ = (float) (RADIUS * Math.cos(rad));

        canvas.save();
        canvas.translate(canvas.getWidth() / 2, canvas.getHeight() / 2);

        Camera camera = new Camera();
        camera.save();

        camera.translate(circleX*CAMERA_MULT, 0, -circleZ*CAMERA_MULT);
        camera.rotateY(theta);

        camera.applyToCanvas(canvas);
        camera.restore();

        canvas.drawRect(
                -HALF_CHORD_WIDTH,
                -HALF_CHORD_WIDTH,
                HALF_CHORD_WIDTH,
                HALF_CHORD_WIDTH,
                paintBackground);

        canvas.restore();
    }
}


text:
Q: add remove class transition scrollheight I noticed that with CSS transitions is possible to restart the animation at any point,
now I want to create a button that toggles the height of its parent animating it between

*

*its "closed" height (e.g. 50px)

*and its normal (full expanded) height

$('.panel-trigger').each(function() {

    var $parent = $(this).parent();

    if (!$parent.hasClass('closed')) {
        $parent.css('height', $parent[0].scrollHeight);
    }else{
        $parent.css('height', '50px');
    }

    $(this).on('click', function() {

        if ($parent.hasClass('closed')) {

            $parent.css('height', $parent[0].scrollHeight);
            $parent.removeClass('closed');

        } else {
            $parent.addClass('closed');
            $parent.css('height', '50px');
        }
    });

});

The code is actually working on my osx chrome 46.0.2490.80,
but I am not sure if it is the good way to achieve that result.
I would like to know if there is a more simple and efficent way to do it
Any help is really appreciated

A: Try
        $parent.css('height', $parent[0].scrollHeight );


text:
Q: WCF Rest Service Error : httpsGetEnabled = false and still shows the error to configure its value I have a wcf service and following is the error i receive:
The HttpsGetEnabled property of ServiceMetadataBehavior is set to true and the HttpsGetUrl property is a relative address, but there is no https base address.  Either supply an https base address or set HttpsGetUrl to an absolute address.
My web.config settings is as below :
<system.serviceModel>
<services>
  <service name="TBServiceProvider" behaviorConfiguration="ServiceBehaviour">
    <endpoint address="" binding="webHttpBinding"
              contract="ITBServiceProvider" behaviorConfiguration="web">
    </endpoint>
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <serviceMetadata httpsGetEnabled="false"/>
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" >
  <baseAddressPrefixFilters>
    <add prefix="http://www.xyz.com:8000"/>
  </baseAddressPrefixFilters>
</serviceHostingEnvironment>

The above settings work perfectly fine on localhost, but when it is uploaded to the server, the above mentioned error occurs. Please let me know what can be done to make the service work on hosting server.
Thanks

A: In IIS, base address prefix is not needed. You can delete this parameter.
Then you should replace httpsGetEnabled by httpGetEnabled. You don't need to specify httpsGetEnabled, if you don't expose your service on TLS.
Finally, can you add a screenshot of your service displayed in Internet Explorer on your server, and on a remote computer.

A: Update in web.config file
 <system.serviceModel>
 <behaviors>
  <serviceBehaviors>
    <behavior name="">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="Web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<bindings>
  <webHttpBinding>
    <binding>
      <security mode="None" />
    </binding>
  </webHttpBinding>
</bindings>
<services>
  <service name="TBSERVICe">
    <endpoint address=""
              binding="webHttpBinding"
              behaviorConfiguration="Web"
              contract="ITBSERVICE" />
  </service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

Addition in TBSERVICE.svc file
    Factory="System.ServiceModel.Activation.WebServiceHostFactory"

These mentioned settings worked well for hosting webservice on server.
My issue was also regarding the files are not updated when any changes are made on them, ie project files like .svc and web.config were still accepted from some temporary storage by hosting server. Would always prefer to place on atleast 2 servers then.
Thanks


text:
Q: How to get email notifications from email client? Is there any programmatic way to get email notification in my application from the built in android email client? Do I have to write my own email client if I want to add custom features like auto-reply and stuffs like it or I can extend some notification framework from any existing application?

A: Is there any programmatic way to get email notification in my application from the built in android email client?
Which "built in android email client"? Across all Android devices, there is more than one "android email client" programs that are "built in".
If you are referring to the Email application from the Android open source project, it has no documented APIs or broadcasts.

Do I have to write my own email client
  if I want to add custom features like
  auto-reply and stuffs like it or I can
  extend some notification framework
  from any existing application?

You are welcome to add those features to open source email clients, or to convince those email clients to expose enough hooks to allow you to add those features as a third-party application.


text:
Q: Video Streaming Python 3 adaptation failling - need help to adapt few lines I've almost been successful in adapting a Python 2 code for video and html streaming to Python 3 (actually, the streaming works for html files). Unfortunately, I was unsuccessful to adapt the central part marked inside the following code. I'll greatly appreciate some help
import cv2
from PIL import Image
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
import time

class CamHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        #self.path handles the path of the request typed by the client in his browser or his other client program.
        #For example, the client may have typed http://127.0.0.1:8080/cam.mjpg or http://127.0.0.1:8080/file.html.
        #Here, we check only the suffix of the path to serve the client.
        if self.path.endswith('.mjpg'):
            self.send_response(200)
            self.send_header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary')
            self.end_headers()

            while True:
                try:
                    rc, img = capture.read()
                    if not rc:
                        continue
                    imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
                    jpg = Image.fromarray(imgRGB)
               #-----------------------------------------------------
              #This fragment of code does not work for Python 3:

                    #tmpFile = StringIO() #Python 2, don't work with Python3
                    #jpg.save(tmpFile, 'JPEG') #Python 2, replaced by
                    self.wfile.write(bytes('--jpgboundary', 'utf8'))
                    self.send_header('Content-type', 'image/jpeg')
                    #self.send_header('Content-length', str(tmpFile.len)) #Python 2, replaced by
                    self.send_header('Content-length', str(jpg.size[0]*jpg.size[1])) #this seems to be bad

                    self.end_headers()

                    jpg.save(self.wfile, 'JPEG') #makes Python3 crashes
                    time.sleep(0.04)
               #end of not working fragment
               #-----------------------------------------------------

                except KeyboardInterrupt:
                    break
            return

        if self.path.endswith('.html'): # The streaming here works for Python 3:
            self.send_response(200)
            self.send_header('Content-type','text/html')
            self.end_headers()
            self.wfile.write(bytes('<html><head>Hello world</head><body>', 'utf8'))
            return

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

def main():

    global capture

    capture = cv2.VideoCapture(0)
    capture.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
    capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)
    capture.set(cv2.CAP_PROP_SATURATION, 0.2)

    try:
        server = ThreadedHTTPServer(('localhost', 8080), CamHandler)
        print('server started', flush = True)
        server.serve_forever()

    except KeyboardInterrupt:
        capture.release()
        server.socket.close()

#----------------------------------------------------------------------------

if __name__ == '__main__':
    main()


text:
Q: Relational Database One Relationship triggers another relationship Thanks in advance.
I am learning and designing a RDBMS of an organization with 2 departments .
Its pretty straightforward but the problem arises when an action in one department leads to action in the other department . Suppose department one does survey of consumers and this survey causes department 2 to introduce a product. The trouble is I have no idea how to connect this relationships of surveying and introducing new products together. I am learning RDBMS on my own.

A: I believe you are asking how to model a scenario where you can track a department's actions to the records that they create, whether that record is a product or a survey.  I have attached a diagram and will attempt to explain the relationships.
Each department can have a number of different actions.  These actions can be shared across departments.  Every DepartmentAction can have an associated ActionEntity.  This ActionEntity shares a 1 to 0..1 relationship with both Product and Survey.  Finally, every product and survey can also have the department's id that created the record.


text:
Q: Numpy->Cython conversion: Compile error:Cannot convert 'npy_intp *' to Python object I have the following code that is to be propperly converted to cython:
from numpy import *

## returns winning players or [] if undecided.
def score(board):
    scores = []
    checked = zeros(board.shape)
    for i in xrange(len(board)):
        for j in xrange(len(board)):
            if checked[i,j] == 0 and board[i,j] !=0:
                ... do stuf

my attempt at conversion to cython:
import numpy as np
cimport numpy as np

@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)

## returns winning players or [] if undecided.
def score(np.ndarray[int, ndim=2] board):
    scores = []
    cdef np.ndarray[int, ndim = 2 ] checked
    checked = np.zeros(board.shape)
    for i in xrange(len(board)):
        for j in xrange(len(board)):
            if checked[i,j] == 0 and board[i,j] !=0:
                ... do stuf

But when I compile I get :
$ python setup.py build_ext --inplace
running build_ext
cythoning newgox.pyx to newgox.c

## returns winning players or [] if undecided.
def score(np.ndarray[int, ndim=2] board):
    scores = []
    cdef np.ndarray[int, ndim = 2 ] checked
    checked = np.zeros(board.shape)
                       ^
------------------------------------------------------------

newgox.pyx:58:28: Cannot convert 'npy_intp *' to Python object
building 'newgox' extension

Also, I'm not sure this is the right way to work with lists in cython:
scores = []
if some_stuff_is_true:
    scores.append(some_integer)

EDIT:
Thanks, the code now compiles but when I run it I get the error:
File "newgox.pyx", line 63, in newgox.score (newgox.c:1710)
    def score(np.ndarray[np.int, ndim=2] board):
ValueError: Buffer dtype mismatch, expected 'int object' but got 'long'

I tied these two options:
ctypedef np.int_t DTYPE_t
DTYPE = np.int

and then continue to:
board = zeros((5,5), dtype = DTYPE)
def score(np.ndarray[DTYPE, ndim=2] board):

or just in both declarations:
    ...  np.int ...

This results in the same error, but with signature:
 ValueError: Buffer dtype mismatch, expected 'int' but got 'long'

Thanks bellamyj, but your suggested code won't compile,
$ python setup.py build_ext --inplace
running build_ext
cythoning newgox.pyx to newgox.c
building 'newgox' extension
gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c newgox.c -o   build/temp.macosx-10.6-intel-2.7/newgox.o

newgox.c:238:31: error: numpy/arrayobject.h: No such file or directory
newgox.c:239:31: error: numpy/ufuncobject.h: No such file or directory
newgox.c:356: error: expected '=', ',', ';', 'asm' or '__attribute__' before '__pyx_t_5numpy_int8_t'
newgox.c:365: error: expected '=', ',', ';', 'asm' or '__attribute__' before '__pyx_t_5numpy_int16_t'
newgox.c:374: error: expected '=', ',', ';', 'asm' or '__attribute__' before '__pyx_t_5numpy_int32_t'

And it continues to enumerate all other types as well.
Then is tells me this:
newgox.c:978: error: expected ')' before '*' token
newgox.c:979: error: expected ')' before '*' token
newgox.c:980: error: expected ')' before '*' token
newgox.c:983: error: expected declaration specifiers or '...' before 'PyArrayObject'
newgox.c:984: error: expected declaration specifiers or '...' before 'PyArrayObject'
newgox.c:985: error: expected ')' before '*' token
newgox.c:987: error: '__pyx_t_5numpy_int32_t' undeclared here (not in a function)
newgox.c: In function '__pyx_pf_6newgox_7score':
newgox.c:1638: error: 'PyArrayObject' undeclared (first use in this function)
newgox.c:1638: error: (Each undeclared identifier is reported only once
newgox.c:1638: error: for each function it appears in.)
newgox.c:1638: error: '__pyx_v_checked' undeclared (first use in this function)
newgox.c:1659: error: '__pyx_t_5' undeclared (first use in this function)
newgox.c:1721: error: expected expression before ')' token
newgox.c:1723: error: expected expression before ')' token
newgox.c:1747: error: expected expression before ')' token
newgox.c:1766: error: expected expression before ')' token
newgox.c:1813: error: expected expression before ')' token
newgox.c:1846: error: expected expression before ')' token
newgox.c:1846: error: too many arguments to function '__pyx_f_6newgox_check_life'
newgox.c:2009: error: expected expression before ')' token
newgox.c:2009: warning: assignment makes pointer from integer without a cast
newgox.c:2012: error: expected expression before ')' token
newgox.c:2032: error: expected expression before ')' token
newgox.c: At top level:
newgox.c:2088: error: expected declaration specifiers or '...' before 'PyArrayObject'
newgox.c: In function '__pyx_f_6newgox_check_life':
newgox.c:2124: error: '__pyx_v_board' undeclared (first use in this function)
newgox.c:2160: error: 'PyArrayObject' undeclared (first use in this function)
newgox.c:2160: error: expected expression before ')' token
newgox.c:2160: error: too many arguments to function '__pyx_f_6newgox_liberty'
newgox.c:2420: error: too many arguments to function '__pyx_f_6newgox_check_life'
newgox.c: At top level:
newgox.c:2583: error: expected declaration specifiers or '...' before 'PyArrayObject'
newgox.c: In function '__pyx_f_6newgox_liberty':
newgox.c:2610: error: '__pyx_v_board' undeclared (first use in this function)
newgox.c: At top level:
newgox.c:2859: error: expected ')' before '*' token
newgox.c: In function '__pyx_pf_5numpy_7ndarray___getbuffer__':
newgox.c:2999: error: 'PyArray_Descr' undeclared (first use in this function)
newgox.c:2999: error: '__pyx_v_descr' undeclared (first use in this function)
newgox.c:3062: error: 'PyArrayObject' undeclared (first use in this function)
newgox.c:3062: error: expected expression before ')' token
newgox.c:3071: error: 'npy_intp' undeclared (first use in this function)
newgox.c:3114: error: expected expression before ')' token
newgox.c:3114: error: 'NPY_C_CONTIGUOUS' undeclared (first use in this function)
newgox.c:3154: error: expected expression before ')' token
newgox.c:3154: error: 'NPY_F_CONTIGUOUS' undeclared (first use in this function)
newgox.c:3184: error: expected expression before ')' token
newgox.c:3184: warning: assignment makes pointer from integer without a cast
newgox.c:3240: error: expected expression before ')' token
newgox.c:3240: error: subscripted value is neither array nor pointer
newgox.c:3249: error: expected expression before ')' token
newgox.c:3249: error: subscripted value is neither array nor pointer
newgox.c:3262: error: expected expression before ')' token
newgox.c:3271: error: expected expression before ')' token
newgox.c:3291: error: expected expression before ')' token

And some more.
Notice it says :
newgox.c:2160: error: too many arguments to function '__pyx_f_6newgox_liberty'
newgox.c:2420: error: too many arguments to function '__pyx_f_6newgox_check_life'

But my call from score/1 to check_life is:
life, newly_checked = check_life(i,j,board,[])

And it is received like this:
# helper functions of score/1
cdef check_life(int i, int j, np.ndarray[int, ndim=2] board, checked):
    ...
    return life, checked

Finally, what kind of data type is the "i4" that you use?

A: I don't think tuple unpacking works in Cython like it does in Python.  You have to specify the size of checked using (board.shape[0], board.shape[1]).
You also need to specify the datatype of checked.  By default np.zeros returns a float64.  You need to change that to an int32 to be compatible with the declared type.
Here's a modified version that should run.
def score(np.ndarray[int, ndim=2] board):

    cdef np.ndarray[np.int32_t, ndim = 2] checked
    checked = np.zeros((board.shape[0], board.shape[1]), dtype='i4')

    for i in xrange(len(board)):
        for j in xrange(len(board)):
            if checked[i,j] == 0 and board[i,j] !=0:
                ... do stuff

To answer the second part of your question - yes you can append to lists within Cython functions.  However, as I understand it this involves Python function calls, so it won't be any faster than the same operations within Python.
Update 1:
I believe those errors are because the compiler can't find the NumPy header files.  Update your setup.py to include the path to those files.  The path should be output by the np.get_include() function.
import numpy as np
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

setup(
      cmdclass={'build_ext': build_ext},
      ext_modules = [
              Extension("new_gox",
                        ["new_gox.pyx"],
                        include_dirs=[np.get_include()])
                    ]
     )

The dtype i4 is a 32 bit integer.  It's equivalent to np.int32.
I'm not sure what's going on with the 'too many arguments' errors.  If you're calling that function from within Python, it needs to be declared as either def or cpdef.  Functions declared with cdef can only be called from Cython.  This is described here in the Cython docs.

A: np.intp is same as (void *)
define its type like this:
ctypedef np.npy_intp SIZE_t              # Type for indices and counters

source:
NPY_INTP == The enumeration value for a signed integer type which is the same size as a (void *) pointer. This is the type used by all arrays of indices.
So for example in cython...
Struct in header file.h file:
struct Cudamat_Struct1 {
    float * dataHost;
    float * dataDevice;
    int onDevice;
    int onHost;
    (void *) shape;
    int size;
    int isTrans; // 0 or 1
    int ownsData;

};

In cython file.pxd file:
cdef extern from "file.h":
    cdef cppclass c_Cudamat_Struct "Cudamat_Struct":
        float *dataHost
        float *dataDevice
        bint onDevice
        bint onHost
        SIZE_t * shape
        int size
        bint isTrans
        bint ownsData

Finally in cython function:
cdef pycublas_thrust_2d():
    cdef c_Cudamat_Struct1* mat = new c_Cudamat_Struct1()

    cdef int N = 10

    cdef np.ndarray[ndim=2, dtype=F32t] arrHost = np.ones((1,10),dtype=F32)

    cdef int size = 10

    cdef F32t[:,:] arrHost_ = arrHost

    cdef F32t * arrHostPtr = &arrHost[0,0]

    mat.dataHost = arrHostPtr
    mat.shape = arrHost.shape
    mat.size = size


text:
Q: Ninject in an Action Filter I have created a custom Action Filter and am binding it with Ninject's BindFilter method:
public class ExtendModelAttribute : FilterAttribute {}

public class ExtendModelFilter : IActionFilter
{
    private IKernel kernel;
    public ExtendModelFilter(Func<IKernel> kernel)
    {
        this.kernel = kernel;
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // TODO:
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
    }
}

I am binding my filter like so:
 kernel.BindFilter<ExtendModelFilter>(FilterScope.Action, 0).WhenActionMethodHas<ExtendModelAttribute>();

Everything so far is working great. What I want to accomplish is the following:
[ExtendModel]
public ActionResult Index()
{
    return View(new IndexModel());
}

What I want the ExtendModel filter to do is determine what type of Model is being used and then find the correct dependency:
public interface IModelExtender<TModel> {
    void Extend(TModel model);
}

public class IndexModelExtender : IModelExtender<IndexModel> {
    public void Extend(IndexModel model)
    {
        // extend the model here with anything extra that is required
    }
}

I'm not sure how to write the code in the action filter to get an instance of IModelExtender:
public void OnActionExecuted(ActionExecutedContext filterContext)
{
    // TODO:
    // I Need to look at the filterContext Model to determine which
    // type of IModelExtender<T> to create:
    // For Example, when [ExtendModel] is applied on the Index() method above
    // then I need it to resolve to IndexModelExtender
}

Maybe what I want to do isnt' even possible? Since I don't know at compile time what T is, is there any way to do what I want?
EDIT
Here is an example of what a ModelExtender might do:
public class IndexModelExtender : IModelExtender<IndexModel>
{
    public IndexModelExtender(IFooRepository fooRepository, IBarRepository barRepository)
     {
        // ...
     }

     public void Extend(IndexModel model)
     {
         model.SelectList1 = new SelectList(fooRepository.GetFoos(), "Description", "Id");
         model.SelectList2 = new SelectList(barRepository.GetBars(), "Description", "Id");
     }
}

I want to avoid code like this in my controller:
 public ActionResult Index()
 {
     var model = new IndexModel();
     // populate select lists here
     return View(model);
 }

 [HttpPost]
 public ActionResult Index(IndexModel model)
 {
     if(!ModelState.IsValid ) {
        // populate the same stuff here
     }
  }

A: You will have to use reflection because the model type is known only at runtime and your extender is generic:
public class ExtendModelFilter : IActionFilter
{
    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        object model = null;
        if (filterContext.Result is ViewResultBase)
        {
            model = ((ViewResultBase)filterContext.Result).Model;
        }
        else if (filterContext.Result is JsonResult)
        {
            model = ((JsonResult)filterContext.Result).Data;
        }
        // TODO: you could continue with the else if here to take
        // into account some other action results that have the notion of model
        // like for example some custom action results that you might have written

        if (model == null)
        {
            // we have no model => nothing to extend
            return;
        }

        var extenderType = typeof(IModelExtender<>).MakeGenericType(model.GetType());
        var extender = DependencyResolver.Current.GetService(extenderType);
        var extend = extenderType.GetMethod("Extend");
        extend.Invoke(extender, new[] { model });
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
    }
}

You will also notice that I have refactored the custom action filter in order to use the current dependency resolver and make it NInject agnostic. You could of course keep the IKernel dependency if you prefer.


text:
Q: Is there ng-bootstrap/BS5 beta documentation? I am working on an experimental branch of my project with Bootstrap 5, making changes to my HTML and CSS as needed.
Some of my UI is plain Bootstrap and some is ng-bootstrap.  I can update the BS stuff with the code snippets from their new docs.
But the ng-bootstrap output looks just like the pre-updated Bootstrap. Will there be updated code for 12.x?  Is there any beta documentation, or do I just need to leave the styling broken until there is?
For example, here's how my toggle buttons looked in both BS and ng-bootstrap versions with Bootstrap 5 installed:

and after I updated the bootstrap 5 HTML:

but the NG one is still broken.  If this will be fixed with new ng-bootstrap snippets, I will need to wait.  I am just checking.


text:
Q: Having trouble summarising data in R studio I have a data set of species and how many were observed, however when I try to take the average for each species, I get the mean for the individual observation, so nothing is changing.
Along the top row of my data are the species names, and going down the column underneath them is the count. I am trying to summarize this data so I may plot it, but rather than the mean of the entire column being taken, it just takes the mean of the individual observation.

grassData <- read.csv("Dykebooke.csv", header = TRUE, sep = ",")
View(grassData)

summary.grass <- grassData %>% group_by(Cordgrass) %>%
  summarise(mean = mean(Cordgrass), variance = var(Cordgrass))

summary.lavender <- grassData %>% group_by(Lavender) %>%
  summarise(mean(Lavender), var(Lavender))

summary.goldenrod <- grassData %>% group_by(Goldenrod) %>%
  summarise(mean(Goldenrod), var(Goldenrod))

summary.crab <- grassData %>% group_by(Crab) %>%
  summarise(mean(Crab), var(Crab))

summary.iva <- grassData %>% group_by(Iva) %>%
  summarise(mean(Iva), var(Iva))

summary.grasshopper <- grassData %>% group_by(Grasshopper) %>%
  summarise(mean(Grasshopper), var(Grasshopper))

This is what I have done so far, but this is what it provides.

I have not used R in a few years so I am very rusty, any help is appreciated.


text:
Q: Deleting certain elements of a list This query is similar to a question I posted earlier.
Given
testList =
  {{"a", "b 3", "cd", "ef 23"}, {"z 12", "y", "x"}, {"z", "y"}, {"a", "b3"}};

I would like to create a rule that would delete 1st level elements of testList that do not contain a string representation of a number.  The result would be:
resultList = {{"a", "b 3", "cd", "ef 23"}, {"z 12", "y", "x"}, {"a", "b3"}};

A: One possibility:
Pick[#, Or @@@ StringContainsQ[DigitCharacter] /@ #] &@testList2

or
Select[testList2, Or @@ StringContainsQ[#, DigitCharacter] &]

A: Although I very much in favor of aardvark2012's answer using Pick, I would like to note that this can done with good old Table.
data = {{"a", "b 3", "cd", "ef 23"}, {"z 12", "y", "x"}, {"z", "y"}, {"a", "b3"}};
Table[If[Or @@ StringContainsQ[item, DigitCharacter], item, Nothing], {item, data}]

{{"a", "b 3", "cd", "ef 23"}, {"z 12", "y", "x"}, {"a", "b3"}}

A: If the OP really wants a Rule then anothe options is:
rule = Rule[
  PatternTest[Blank[List],
   Composition[
    Not,
    Apply[Or],
    Map[StringContainsQ[DigitCharacter]]
    ]
   ]
  , Nothing
  ]

Or
rule= _List?(Not@*Apply[Or]@*Map[StringContainsQ[DigitCharacter]]) -> Nothing

Then
testList /. rule
(* {{"a", "b 3", "cd", "ef 23"}, {"z 12", "y", "x"}, {"a", "b3"}} *)

(testList /. rule) == resultList
(* True *)


text:
Q: Email with Multiple Attachments using Graph API (>4 MB) I'm using Microsoft-Graph API version 1.4 and trying to send mail with multiple attachments (with size greater then 4MB) using following code..
val address = EmailAddress()
address.address = "vivek@domain.com"
val recipient = Recipient()
recipient.emailAddress = address

val message = MyMessage()
message.subject = "Test E-Mail"
message.body = getItemBody()
message.toRecipients = Collections.singletonList(recipient)

val att = FileAttachment()
att.contentBytes = File("/home/user/file.pdf").readBytes()
att.contentType = "text/pdf"
att.name = "file.pdf"
att.oDataType = "#microsoft.graph.fileAttachment"

val att2 = FileAttachment()
att2.contentBytes = "hello there! from second file".toByteArray(StandardCharsets.UTF_8)
att2.contentType = "text/plain"
att2.name = "hi2.txt"
att2.oDataType = "#microsoft.graph.fileAttachment"

message.addAttachment(att)
message.addAttachment(att2)

graphClient.me()
.sendMail(message,false)
.buildRequest()
.post();

In response, I'm getting following error..
{
    "status": "INTERNAL_SERVER_ERROR",
    "exception": "GraphServiceException",
    "message": "Error code: BadRequest\nError message: The maximum request length supported is 4MB.\n\nPOST https://graph.microsoft.com/v1.0/me/microsoft.graph.sendMail\nSdkVersion : graph-java-v1.4.0\nAuthorization : Bearer eyJ0eXAiOiJKV1QiLCJub25jZSI[...]\n{\"message\":{\"attachments\":[{\"contentBytes\":\"JVBERi[...]\n\n413 : Request Entity Too Large\n[...]\n\n[Some information was truncated for brevity, enable debug logging for more details]",
    "existing": null,
    "errorData": null,
    "tenant": null
}

Can anyone help me to send a mail with multiple attachment with size greater then 4MB.
Thanks

A: In order to add multiple attachments at once when their total size exceeds 4MB, you need:

*

*create the message (as a draft)

*create the attachment with an upload session

*upload the attachment using the session you just created (repeat for each attachment)

*send the draft email

Here is a code sample that does something along those lines
    String draftSubject = "Draft Test Message " + Double.toString(Math.random()*1000);
    User me = graphClient.me().buildRequest().get();
    Recipient r = new Recipient();
    EmailAddress address = new EmailAddress();
    address.address = me.mail;
    r.emailAddress = address;
    Message message = new Message();
    message.subject = draftSubject;
    ArrayList<Recipient> recipients = new ArrayList<Recipient>();
    recipients.add(r);
    message.toRecipients = recipients;
    message.isDraft = true;

    //Save the message as a draft
    Message newMessage = graphClient.me().messages().buildRequest().post(message);

    File file = new File("src/test/resources/largefile10M.blob");

    AttachmentItem attachmentItem = new AttachmentItem();
    attachmentItem.attachmentType = AttachmentType.FILE;
    attachmentItem.name = file.getName();
    attachmentItem.size = file.length();
    attachmentItem.contentType = "application/octet-stream";

    InputStream fileStream = OutlookTests.class.getClassLoader().getResourceAsStream("largefile10M.blob");

    long streamSize = attachmentItem.size;

    UploadSession uploadSession = graphClient.me()
                                .messages(newMessage.id)
                                .attachments()
                                .createUploadSession(attachmentItem)
                                .buildRequest()
                                .post();

    ChunkedUploadProvider<AttachmentItem> chunkedUploadProvider = new ChunkedUploadProvider<>(uploadSession, testBase.graphClient, fileStream,
            streamSize, AttachmentItem.class);

    // Do the upload
    chunkedUploadProvider.upload(callback);

    //Send the drafted message
    graphClient.me().mailFolders("Drafts").messages(newMessage.id).send().buildRequest().post();

Here is a sample implementation for the callback.
    IProgressCallback<AttachmentItem> callback = new IProgressCallback<AttachmentItem> () {
        @Override
        public void progress(final long current, final long max) {
            //Check progress
        }
        @Override
        public void success(final AttachmentItem result) {
            //Handle the successful response
        }

        @Override
        public void failure(final ClientException ex) {
            //Handle the failed upload
        }
    };


text:
Q: Using multiple hyperlinks as submit and input Need the three "Options" to be hyperlinks that submit the "choice" form. When submitted, I would like the value to be the text of the option selected (i.e. value=Option1, Option2 orOption3) and all three to have the same name. (i.e. name = Options)
I saw this and some other posts here, but did not work with my set up - many "hyperlink inputs" within the form.
I'm also using JQuery now, if it can be done using that library, I saw some posts on their forum about this but not sure about the answers....
Any help is appreciated.
<form action="cgi.exe" method=POST name="choice">

           Option1
           Option2
           Option3

</form>

A: You could just apply styles to your submit button to make it look like a link and avoid javascript altogether.
<input type="submit" style="background-color: #fff; border: 0; text-decoration: underline; color: #00c;" name="submit" value="Option1">

Otherwise, start here for help:
http://www.javascript-coder.com/javascript-form/javascript-form-submit-example.html

A: You'd attach a click event to the item that then submits the form:
$('yourItem').click(function(){$('yourForm').submit()})
However, you don't really have a form there. Either you'd want those to be proper form INPUT elements or perhaps you need to use some sort of AJAX call instead.


text:
Q: Filter Slider is not working unless I'm in the back end, changing the code I have filter sliders that change Contrast, Saturation, and Hue of a selected image. They were all working great a few months ago. WordPress updated a lot since December. Now they don't work.
While I'm in the back-end, I can get them to function perfectly by changing any little thing. I can move the position of the JavaScript or put in one letter and delete it from the JavaScript and it will suddenly work. In WordPress you have these HTML bubbles you put code in, and I can change any of the other 4 JavaScript sections within the same bubble and it'll start working again.
All 4 of the other (separated) processes within that bubble work just fine without prompting, though none of them are sliders like these.
I have tried changing the starting position of the JS up and down the page from the HTML and nothing corrected the sliders (though a higher starting position did cause my other buttons to fail).
I have tried adding document.ready() but that broke the sliders fully.
The HTML filter sliders:

            Contrast
                <input type="range" min="90" max="120" value="100" step="1" onchange="applyFilter()" data-filter="contrast" data-scale="%">

            Saturation
                <input type="range" min="70" max="200" value="100" step="1" onchange="applyFilter()" data-filter="saturate" data-scale="%">

            Color
                <input type="range" min="-22" max="22" value="0" step="1" onchange="applyFilter()" data-filter="hue-rotate" data-scale="deg">

The javascript to make them work:

A: After Digging through the code I found that I had this for a different photo-set on the same page. The variables are identical to the ones in my problem zone, but these are located lower on the page, so this set of controls worked.

Once I changed them to be unique to this photo-set they started working on the front-end and back-end.
Final Variable look:


text:
Q: Is it possible to stylize a tooltip with WIN32 API and GDI+ (C++) I'm writing down some code and I would like to warn the user about wrong moves using a tooltip. The max I can achieve using WIN32 <commctrl.h>
TOOLINFO structure is a classic rectangular tooltip on a single line. The result I'd like to reach is something like this:

Is there any way to do this using GDI+ and WIN32 API?
Thanks in advance!

A: To split your tooltip text onto multiple lines, send the control a TTM_SETMAXTIPWIDTH message to give it a maximum width. It will then wrap text automatically, or you can use \r\n to insert line breaks manually. This is described in detail here: How to Implement Multiple Line Tooltips.
Use the TTM_SETTITLE message to give your tooltip a title and an icon.


text:
Q: How do I align a title to the center of a video background in CSS3/HTML5? I want to place my title at the center of the video background.
can you help please?
I know how to place it using position:absolute but I am not sure that this is a correct solution!
Here is my css
* {
    box-sizing: border-box;
}

body {
    margin: 0;
}

#bg {
    width: 100%;
}

.header {
    background-color: #f1f1f1;
    text-align: center;
}

#h-content {
    position: absolute;
    top: 0px;
}

and this is html!
<!DOCTYPE html>

    <title>CSS Website Layout</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="public/css/main.css">

    <video id="bg" src="public/media/test.mp4" autoplay="true" loop="true" muted="true"></video>

Header

Resize the browser window to see the responsive effect.

Help me please!
I need to do that task without any frameworks or libraries like bootstrap, ect.

A: transform: translate(-50%, -50%) is the best bet for you, try this snippet.

* {
    box-sizing: border-box;
}

body {
    margin: 0;
}

#bg {
    width: 100%;
}

.header {
    background-color: #f1f1f1;
    text-align: center;
    position:relative
}

#h-content {
    position: absolute;
    top:50%;
    left:50%;
     transform: translate(-50%, -50%);
}

    <video id="bg" src="public/media/test.mp4" autoplay="true" loop="true" muted="true"></video>

Header

Resize the browser window to see the responsive effect.


text:
Q: Can SOAPUI Test both Sending and Receiving Requests at the same time? We have a need to send a SOAP message from within a testcase and also test what is sent to our mock service at the same time. So something like this:
Send SOAP Request -> Webservice
Response <- Webservice

20 or 30 seconds later
This is a different request coming to our Mock Service on SOAPUI
Mock Service <-Webservice

I want to have a test steps for both. Sending the request and getting a response and then expecting a request to our service.
Any ideas?
I started using the tool 1 day ago so I hope my lingo is understandlable.

A: I found that Mock request step actually does this. and I am able to add assertions and transfer those value to other steps.


text:
Q: Creating Persistent Drive Labels With UDEV Using /dev/disk/by-path I have a new BackBlaze Pod (BackBlaze Pod 2.0).
It has 45 3TB drives and they when I first set it up they were labeled /dev/sda through /dev/sdz and /dev/sdaa through /dev/sdas.
I used mdadm to setup three really big 15 drive RAID6 arrays.
However, since first setup a few weeks ago I had a couple of the hard drives fail on me.  I've replaced them but now the arrays are complaining because they can't find the missing drives.  When I list the the disks...
ls -l /dev/sd*

I see that
/dev/sda
/dev/sdf
/dev/sdk
/dev/sdp

no longer appear and now there are 4 new ones...
/dev/sdau
/dev/sdav
/dev/sdaw
/dev/sdax

I also just found that I can do this...
ls -l /dev/disk/by-path/
total 0
lrwxrwxrwx 1 root root 10 Sep 19 18:08 pci-0000:02:04.0-scsi-0:0:0:0 -> ../../sdau
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-0:1:0:0 -> ../../sdb
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-0:2:0:0 -> ../../sdc
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-0:3:0:0 -> ../../sdd
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-0:4:0:0 -> ../../sde
lrwxrwxrwx 1 root root 10 Sep 19 18:08 pci-0000:02:04.0-scsi-2:0:0:0 -> ../../sdae
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-2:1:0:0 -> ../../sdg
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-2:2:0:0 -> ../../sdh
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-2:3:0:0 -> ../../sdi
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-2:4:0:0 -> ../../sdj
lrwxrwxrwx 1 root root 10 Sep 19 18:08 pci-0000:02:04.0-scsi-3:0:0:0 -> ../../sdav
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-3:1:0:0 -> ../../sdl
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-3:2:0:0 -> ../../sdm
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-3:3:0:0 -> ../../sdn
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-3:4:0:0 -> ../../sdo
lrwxrwxrwx 1 root root 10 Sep 19 18:08 pci-0000:04:04.0-scsi-0:0:0:0 -> ../../sdax
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-0:1:0:0 -> ../../sdq
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-0:2:0:0 -> ../../sdr
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-0:3:0:0 -> ../../sds
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-0:4:0:0 -> ../../sdt
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-2:0:0:0 -> ../../sdu
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-2:1:0:0 -> ../../sdv
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-2:2:0:0 -> ../../sdw
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-2:3:0:0 -> ../../sdx
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-2:4:0:0 -> ../../sdy
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-3:0:0:0 -> ../../sdz

I didn't list them all....you can see the problem above.  They're sorted by scsi id here but sda is missing...replaced by sdau...etc...
So obviously the arrays are complaining.  Is it possible to get Linux to reread the drive labels in the correct order or am I screwed?
My initial design with 15 drive arrays is not ideal.  With 3TB drives the rebuild times were taking 3 or 4 days....maybe more.  I'm scrapping the whole design and I think I am going to go with 6 x 7 RAID5 disk arrays and 3 hot spares to make the arrays a bit easier to manage and shorten the rebuild times.  But I'd like to clean up the drive labels so they aren't out of order.  I haven't figured out how to do this yet.
Does anyone know how to get this straightened out?
Thanks,
Matt

A: My Solution
I'm not sure it's the best solution, and I'm still interested in other answers, but here's what I did.
I could not figure out how to force it to map based on the SCSI path (e.g. pci-0000:02:04.0-scsi-0:0:0:0).  So instead I am mapping based on the UUID, which is the drive models and serial numbers.  I just have to remember that when I swap drives I have to update the UDEV entries.

Finding the UUIDs
Used entries from the following commands to identify the current drive names, what SCSI PATH they were mapped to, and what their UUIDs were.
# ls -l /dev/disk/by-path
# /lib/udev/scsi-id -gu /dev/sdX

Created UDEV entries
I put entries like this into a new file I called /etc/udev/rules.d/59-persistent-disk.rules.  There are three rows of Three backplanes each so I did something like this.
# ROW 1 BACKPLANE 1
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0076306", SYMLINK+="pci24scsi00"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0073437", SYMLINK+="pci24scsi01"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0073085", SYMLINK+="pci24scsi02"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0072374", SYMLINK+="pci24scsi03"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0071564", SYMLINK+="pci24scsi04"

# ROW 1 BACKPLANE 2
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0077571", SYMLINK+="pci24scsi20"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0077346", SYMLINK+="pci24scsi21"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0074773", SYMLINK+="pci24scsi22"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0071238", SYMLINK+="pci24scsi23"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0076264", SYMLINK+="pci24scsi24"
.......etc

Creating the Arrays
Now that I have persistent device names I created five 9 drive arrays (RAID5 with one spare) as follows.  I used 1 drive per backplane in each array so I could lose an entire backplane (or even two) and the arrays would stay running.  Performance may suffer for doing it this way, but I bought this for archiving and offsite backups so performance isn't the primary concern.
mdadm --create --verbose /dev/md0 --level=5 --raid-devices=8 --spare-devices=1 /dev/pci24scsi00 /dev/pci24scsi20 /dev/pci24scsi30 /dev/pci44scsi00 /dev/pci44scsi20 /dev/pci44scsi30 /dev/pci64scsi00 /dev/pci64scsi20 /dev/pci64scsi30
mdadm --create --verbose /dev/md1 --level=5 --raid-devices=8 --spare-devices=1 /dev/pci24scsi01 /dev/pci24scsi21 /dev/pci24scsi31 /dev/pci44scsi01 /dev/pci44scsi21 /dev/pci44scsi31 /dev/pci64scsi01 /dev/pci64scsi21 /dev/pci64scsi31
mdadm --create --verbose /dev/md2 --level=5 --raid-devices=8 --spare-devices=1 /dev/pci24scsi02 /dev/pci24scsi22 /dev/pci24scsi32 /dev/pci44scsi02 /dev/pci44scsi22 /dev/pci44scsi32 /dev/pci64scsi02 /dev/pci64scsi22 /dev/pci64scsi32
mdadm --create --verbose /dev/md3 --level=5 --raid-devices=8 --spare-devices=1 /dev/pci24scsi03 /dev/pci24scsi23 /dev/pci24scsi33 /dev/pci44scsi03 /dev/pci44scsi23 /dev/pci44scsi33 /dev/pci64scsi03 /dev/pci64scsi23 /dev/pci64scsi33
mdadm --create --verbose /dev/md4 --level=5 --raid-devices=8 --spare-devices=1 /dev/pci24scsi04 /dev/pci24scsi24 /dev/pci24scsi34 /dev/pci44scsi04 /dev/pci44scsi24 /dev/pci44scsi34 /dev/pci64scsi04 /dev/pci64scsi24 /dev/pci64scsi34

Using LVM to Create VGs and LVs
These were my LVM steps to create the volumes so they could be iSCSI mounted remotely.
PVCREATE
pvcreate /dev/md0
pvcreate /dev/md1
pvcreate /dev/md2
pvcreate /dev/md3
pvcreate /dev/md4

VGCREATE
vgcreate VgArr0 /dev/md0
vgcreate VgArr1 /dev/md1
vgcreate VgArr2 /dev/md2
vgcreate VgArr3 /dev/md3
vgcreate VgArr4 /dev/md4
vgcreate VgArr5 /dev/md5

LVCREATE for iSCSI
Create the LVs but do not format or mount the volumes. They get formatted/mounted remotely
lvcreate -L100%FREE VgArr0 -n LvISCSI0

iSCSI
Edit the /etc/iet/ietd.conf and /etc/iet/initiators.conf
Map the iSCSI LUNs remotely on the other host


text:
Q: Badges and Bounties
You've earned the "Enthusiast" badge.
  See your profile.

That's what just popped up at SO, I went to see my profile and I don't have the Enthusiast badge so I went to the badges page to see what it was about and Enthusiast is also not there, what is going on?
Also in the other day I answered this question which was supposed to be a bounty question (200 or 250 points if I remember correctly), the 7 day period has passed, I didn't won the bounty and no one else seems to have won it either and the question doesn't even appear at the featured page anymore.
Am I missing something? Is this the expected behavior of SO or is something not working right?

A: For the Enthusiast badge, this blog post from Jeff should explain it: https://blog.stackoverflow.com/2009/06/enthusiast-and-fanatic-badges/
For your bounty question, the following post may explain it: In a bounty scenario, can an answer from before the bounty be automatically accepted?

A: Hell yeah you did. It's the woot! badge.
Welcome to the addict's world! Only a couple more days and I get me my Fanatic badge!
And bounties without any +2 answer just go away unto the ether, and the rep gets put back into the kitty to be doled out another day.

A:
Also in the other day I answered this question which was supposed to be a bounty question (200 or 250 points if I remember correctly), the 7 day period has passed, I didn't won the bounty and no one else seems to have won it either and the question doesn't even appear at the featured page anymore.

For the Bounty, an answer needs to be accepted by the end of the bounty period or the highest voted answer will be auto-accepted, as long as it has 2 or more upvotes.  None of the ansnwers on the post to which you refer met the second criteria to trigger an auto-accept.


text:
Q: Kinect v2 compatible usb controller I'm now trying to set up my kinect version 2
I installed Microsoft sdk and usb extension board (Renseas 720202)
Question is, Kinect can be detected before driver of usb board install.
In Kinect verifier program, usb controller are not compatible but can get
color image with low fps.
ahttp://ppt.cc/XvKOg   (Sorry I can't post more than two links. Plz remove 'a' and see the pic)
http://ppt.cc/kv38M
After install driver of usb board, I get nothing...
ahttp://ppt.cc/hbWAE
http://ppt.cc/Cw29u
I search that intel and Renaseas chips are compatible with Kinect v2.
What can I do? Thanks
update
In the end, I change computer which use intel chipset on mother board to solve the problem.


text:
Q: How to use mapStateToProps to get a value from the state based on a context value? I've an application when most of the data are stored in the store but the selected item is provided thought the usage of a React.Context.
React-Redux provide the connect api that accept a mapStateToProps function with state and props as a component.
What I would like, if it didn't break the hooks, is something like:
function mapStateToProps(state){
  const selectedItemId = useContext(MySelectedItemContext)
  return {
    item: state.items[selectedItemId]
  }
}

but of course it is not possible since I'm outside of the component and cannot invoke the useContext.
So, I tried to use the old API context:
function mapStateToProps(state, props){
  return {
    item: state.items[props.id]
  }
}
export default connect(mapStateToProps)((props) =>
  <MySelectedItemContext.Consumer>
  { selectedItemId => <Component id={selectedItemId} {...props}/> }
  </MySelectedItemContext.Consumer>)

but this still not works because the connect returns a new component that has the consumer inside instead of outside and id prop is not defined yet in mapStateToProps.
Any idea?

A: The best way is to remove mapStateToProps and use useSelector hooks and Redux selectors. But if you need mapStateToProps, then you can wrap your component that must be connected to Redux into another component that will get value from context and will pass it to a component that uses Redux.
// Use this component
export function ContextConsumerComponent() {
  const selectedItemId = useContext(SelectedItemIdContext);

  return <ReduxConsumerComponent id={selectedItemId} />;
}

function mapStateToProps(state, props) {
  return {
    item: state.items[props.id]
  }
}

const ReduxConsumerComponent = connect(mapStateToProps)((props) => {
  // props.item will be here
});


text:
Q: Eclipse plugin to compare zip files In projects I work on occasionally files are stored in an archive.  Editing things in eclipse is straight forward one installed the Eclipse Zip Editor Plugin.  However, I can't compare the changes made in the zipfile using the standard Team->compare functionality.  Are there any tricks to accomplish this within eclipse?

A: Eclipse has native comparison support for .zip archives and .jar files.  Select the two files you wish to compare, then right-click on one of them and choose Compare With > Each Other.


text:
Q: Sort based on specific field within a group I have a report which I need to Group by type but the rows under the group should be sorted based on specific field code. from the below eg. the Reason field needs to be sorted in the order  NSL,RWR,PAL,CON order within the grouping.
TYPE        DATE     NAME        CODE

**CEM**
Cem                              NSL
Cem                              RWR
Cem                              PAL
Cem                              CON

**FUN**
FUN                              NSL
FUN                              RWR
FUN                              PAL

 **IP**
IP                               NSL
IP                               RWR
IP                               PAL

A: The easiest way to do this is to create a formula "Priority" like this:
if CODE="NSL" then 1 else
(if CODE="RWR" then 2 else
(if CODE="PAL" then 3 else
(if CODE="CON" then 4 else 0)) )

and put in into the detail row of you report.
Then goto "Report" menù ->"Record Sort Expert" and sort the detail with your formula "Priority"


text:
Q: Creating XML with namespaces and schemas from an XElement A longwinded question - please bear with me!
I want to programatically create an XML document with namespaces and schemas.  Something like
<myroot
    xmlns="http://www.someurl.com/ns/myroot"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.someurl.com/ns/myroot http://www.someurl.com/xml/schemas/myschema.xsd">

    <sometag>somecontent</sometag>

</myroot>

I'm using the rather splendid new LINQ stuff (which is new to me), and was hoping to do the above using an XElement.
I've got a ToXElement() method on my object:
  public XElement ToXElement()
  {
     XNamespace xnsp = "http://www.someurl.com/ns/myroot";

     XElement xe = new XElement(
        xnsp + "myroot",
           new XElement(xnsp + "sometag", "somecontent")
        );

     return xe;
  }

which gives me the namespace correctly, thus:
<myroot xmlns="http://www.someurl.com/ns/myroot">
   <sometag>somecontent</sometag>
</myroot>

My question: how can I add the schema xmlns:xsi and xsi:schemaLocation attributes?
(BTW I can't use simple XAtttributes as I get an error for using the colon ":" in an attribute name...)
Or do I need to use an XDocument or some other LINQ class?
Thanks...

A: From this article, it looks like you new up more than one XNamespace, add an attribute in the root, and then go to town with both XNamespaces.
// The http://www.adventure-works.com namespace is forced to be the default namespace.
XNamespace aw = "http://www.adventure-works.com";
XNamespace fc = "www.fourthcoffee.com";
XElement root = new XElement(aw + "Root",
    new XAttribute("xmlns", "http://www.adventure-works.com"),
///////////  I say, check out this line.
    new XAttribute(XNamespace.Xmlns + "fc", "www.fourthcoffee.com"),
///////////
    new XElement(fc + "Child",
        new XElement(aw + "DifferentChild", "other content")
    ),
    new XElement(aw + "Child2", "c2 content"),
    new XElement(fc + "Child3", "c3 content")
);
Console.WriteLine(root);

Here's a forum post showing how to do the schemalocation.

A: Thanks to David B - I'm not quite sure I understand all this but this code gets me what I need...
  public XElement ToXElement()
  {
     const string ns = "http://www.someurl.com/ns/myroot";
     const string w3 = "http://wwww.w3.org/2001/XMLSchema-instance";
     const string schema_location = "http://www.someurl.com/ns/myroot http://www.someurl.com/xml/schemas/myschema.xsd";

     XNamespace xnsp = ns;
     XNamespace w3nsp = w3;

     XElement xe = new XElement(xnsp + "myroot",
           new XAttribute(XNamespace.Xmlns + "xsi", w3),
           new XAttribute(w3nsp + "schemaLocation", schema_location),
           new XElement(xnsp + "sometag", "somecontent")
        );

     return xe;
  }

It appears that concatenating a namespace plus a string eg w3nsp + "schemaLocation" gives an attribute called xsi:schemaLocation in the resulting XML, which is what I need.


text:
Q: How to resize canvasjs chart when its container's size changes dynamically? First look at this example https://codepen.io/merajahmed/pen/PJaeWR

window.onload = function () {

var chart = new CanvasJS.Chart("chartContainer", {
 animationEnabled: true,
 exportEnabled: true,
 theme: "light1", // "light1", "light2", "dark1", "dark2"
 title:{
  text: "Simple Column Chart with Index Labels"
 },
 data: [{
  type: "column", //change type to bar, line, area, pie, etc
  //indexLabel: "{y}", //Shows y value on all Data Points
  indexLabelFontColor: "#5A5757",
  indexLabelPlacement: "outside",
  dataPoints: [
   { x: 10, y: 71 },
   { x: 20, y: 55 },
   { x: 30, y: 50 },
   { x: 40, y: 65 },
   { x: 50, y: 92, indexLabel: "Highest" },
   { x: 60, y: 68 },
   { x: 70, y: 38 },
   { x: 80, y: 71 },
   { x: 90, y: 54 },
   { x: 100, y: 60 },
   { x: 110, y: 36 },
   { x: 120, y: 49 },
   { x: 130, y: 21, indexLabel: "Lowest" }
  ]
 }]
});
chart.render();

}
.sidebar {
    background-color: black;
    width: 150px;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
}

.sidebar h1 {
    color: white;
}

.portfolio {
    background-color: red;
    position: absolute;
    top: 0;
    left: 150px;
    right: 0;
    bottom: 0;

    -moz-transition: left 0.5s ease;
    transition: left 0.5s ease;
}

input[type=checkbox] {
   display: none;
}

input:checked ~ .portfolio {
    left: 0;
}

input:checked ~ label {
    left: 0;
}

label {
    z-index: 2;
    position: absolute;
    top: 0;
    left: 150px;
    background-color: blue;

    -moz-transition: left 0.5s ease;
    transition: left 0.5s ease;
}

    <input id="slide-sidebar" type="checkbox" role="button" />
        close

Settings

I want to resize chart to full width when I click close button, but chart width does not changes.
Since there is animation between resizing the chart container, I want chart to take full width of its container during animation period. Means, Chart should grow/shrink its width during animation.

A: The function that renders the chart is triggered by the onload event.
Simply extract that function definition, name it, for example, render, and trigger that same function for the onresize event.
https://codepen.io/anon/pen/JrZvQy
window.onload = render;
window.onresize = render;


text:
Q: Slick 3.0 Insert and then get Auto Increment Value I have written this code which works perfectly
class Items(tag: Tag) extends Table[Item](tag, "ITEMS") {
  def id = column[Long]("ITEMS_ID", O.PrimaryKey, O.AutoInc)
  def name = column[String]("ITEMS_NAME")
  def price = column[Double]("ITEMS_PRICE")
  def * = (id, name, price) <> ((Item.apply _).tupled, Item.unapply _)
}

object Shop extends Shop{
  val items = TableQuery[Items]
  val db = Database.forConfig("h2mem1")

  def create(name: String, price: Double) : Int = {
    val action = items ++= Seq(Item(0, name, price))
    val future1 = db.run(action)
    val future2 = future1 map {result =>
      result map {x => x}
    }
    Await.result(future2, Duration.Inf).getOrElse(0)
  }
}

This code works but the return value is number of records inserted. But I want to return the value of the AutoInc after the insert has been done.
i did google and found few articles
Slick 3.0.0 AutoIncrement Composite Key
Returning the auto incrementing value after an insert using slick
But somehow these do not answer the question cleanly.

A: Try this one instead:
def create(name: String, price: Double): Future[Int] = db.run {
    (items returning items.map(_.id)) += Item(0, name, price)
}

A: Here's the relevant documentation page, according to which, you should construct a query like this:
val insertQuery = items returning items.map(_.id) into ((item, id) => item.copy(id = id))

def create(name: String, price: Double) : Future[Item] = {
  val action = insertQuery += Item(0, name, price)
  db.run(action)
}


text:
Q: Database structure for house facilities I'm working on a new project. I really just started it and I am orientating myself on how I want to build the structure of the pages and of course the database.
The page will be about houses/ appartments and so on that you can rent (for like a week with family or a weekend with your friends).
The user can register, and add a house (it may be extended with the ability to add more houses).
So I came up with this base DB structure:
table users
-----------
user_id
user_email
user_password

table house
-----------
house_id
user_id
house_name
...
house_num_bedrooms
house_description

As you can see the table house has some attributes that all the houses have, like number of bedrooms, minimum and maximum number of people that can stay, and so on. Those 'fix attributes' are assigned in the table house.
Now the user must be able to select facilities, a part of the list:
Category: kitchen
- Microwave       [yes|no]
- Coffee machine  [senseo|2 pot|3 pot]
- Water boiler    [yes|no]
- Refrigerator    [yes|no]

Category: bedrooms
- number of bedrooms           [xx]
- number of 1-person-beds      [xx]
- number of 2-person-beds      [xx]
- number of 2-person boxspring [xx]

Behind the facilities are possibilities listed, so some facilities are either there or not, others is the number of the facilities (for examples, 26 bedrooms with 20 1-person-beds and 6 2-person-beds).
At the beginning I will already have a nice list of facilities (approx. 100).
The question is, what is the best way of saving this in a db, with a flexible database, or a table called facilities with all the facilities as columns?
How would you approach this?

A: With regard to facilities: you need one table in which are stored all the facilities - id and name (possibly along with a text field which contains extra information regarding that facility, like 2 euro/day) - and a join table, which joins houses and facilities. This table could also contain a 'number' field and a 'cost' field, although the latter is problematic as some facilities cost on a per day basis, like city tax, and some are on a per stay basis, like final cleaning. This is left as an exercise.
As it happens, I was just looking at apartments to rent in Florence, so I can easily give you an example.
APARTMENTS
id
daily price
name
address

FACILITIES
id
name
extra details

FACBYAPART // join table, find your own name
apartment
facility
quantity
cost

example data:
Apartments - 1, 82, Green Fig; 2, 95, Belfiore 2
Facilities - 1, Final cleaning; 2, Wifi; 3, single bed; 4, double bed
FacByApart - 1,1,1,40; 1,2,1,0; 1,3,1,0; 1,4,1,0; 2,1,1,0; 2,2,1,2; 2,3,2,0; 2,4,2,0.
The data shows that the Green Fig apartment has final cleaning (at a cost of 40 Euro), free wifi, one single bed and one double bed. Belfiore 2 has free final cleaning, wifi costs 2 euro, two single beds and 2 double beds.
This is the standard way of defining a database such as you need. Later on, you'll need a calendar table, which would have a date, an apartment, a price for that apartment on that date and the name of the person who has booked the apartment for that date (no value means that the apartment is free). Then you'll need a table for people who have booked ....

A: Here you go for the schema design along use case for your requirements:
APARTMENT
id:1;2
name:Valley View;City Center
address: Narayan Rd 50;Kanti Rd 30
daily price: 40;60

FACILITy
id:1;2;3;4;5;6;7;8
name:Double Bed;Kitchen Set;Double Bed BoxSpring;Car;Movie Theater;Refrigenator;Water boiler;Final Cleaning
remarks:;All kitchenware(refrigenerator, water boiler,cofee machine, microwave) Available;;;;;;;

APARTMENT_FACILITy
id:1;2;3;4;5;6;7
apartment_id:1;1;1;1;2;2;2
facility_id:1;2;4;5;1;6;7
quantity:2;1;1;1;1;1;1
cost:0;0;20;50;0;0;0
cost_frequency_days:0;0;1;7;0;0;0

APARTMENT_USER
id:1;2
email:abc@abc.com;xyz@abc.com
password;secret1_hash;secret2_hash

RENTAL_DETAILs
id:1;2;3;4
apartment_id;1
arrival_date:2015-01-10
departure_date:2015-01-13
apartment_user_id:1

Considerations:
Referred Apartment for both house and apartment. Users table holds email for username and password for the credentials, you can extend other fields as per your requirements. Add additional fields in other tables as per your requirements.

case #1-You have Valley View apartment at Naryanan Rd 50 and cost per day is $80, it offers 2 Double Beds and Kitchen. Additional Cost: Car - $20/day and Movie Theater $50/Week

case #2-You have City Center apartment at Kanti Rd 30 and cost per day is $30, it offers 1 Double Bed, Refrigenator and Water boiler.

Case #3-User abc@abc.com stay in Valley View Apartment for 4 days(2015-01-10 to 2015-01-13)=>40+80(Car-20X4days)+50(one week charge).


text:
Q: powerpoint 2010 vba - noncontiguous text selection I would like to select all characters in a Powerpoint textbox (Version 2010) that have a certain defined style (e.g. all bold characters). Manually, one can create a non-contiguous text selection in a single text box by simply holding the control key while selecting. With VBA, I failed so far. This is my very simple approach:
 Dim c As TextRange
 For Each c In ActiveWindow.Selection.ShapeRange(1).TextFrame.TextRange.Characters
  If c.Font.Bold Then c.Select
 Next c

While this all works nicely when going through this stepwise, the c.Select will always "unselect" what was selected before and there is no option to extend the selection (unlike with shape selections). I end up with just the last bold character being selected.
The selection itself is what I want as end result to give the user the option to further modify the font etc.
Does anyone have a suggestion (or is this not at all accessible via VBA?)
Thanks a lot


text:
Q: http status 408 in j_security_check using JBoss Currently I'm facing strange problem. I have one demo application which just authenticate user from database and shows welcome page.
The problem is if I keep login page open and then after restarting server, try to login using the same page which is opened earlier, screen shown me HTTP Status 408 - The time allowed for the login process has been exceeded. error.
I tried the suggested changed in HTTP Status 408 error during login with domain forwarding set up link but it's not working.
This is my login page :
<!DOCTYPE html>

        <title>Login</title>
        <meta charset="utf-8" />
        <meta http-equiv="Cache-Control" content="no-store,no-cache,must-revalidate"/>
        <meta http-equiv="Pragma" content="no-cache"/>
        <meta http-equiv="Expires" content="-1"/>

    <form method="post" action='<%= response.encodeURL("j_security_check") %>' id="login" >
        Username
        <input type="text" name="j_username" id="username" autofocus />

        Password
        <input type="password" name="j_password" id="password" />

        <button type="submit" class="primary" name="Submit">Log in</button>
    </form>

I tried to debug but request is not coming through server to controller. So I'm guessing something is wrong with jboss server. Any help will be appreciated. Thanks

A: In my case , I added to login page.
setInterval(function(){
        location.reload(true); //reload each 5 minutes
    },5*60*1000);

Hope this help.


text:
Q: Scala - access collection members within map or flatMap Suppose that I use a sequence of various maps and/or flatMaps to generate a sequence of collections. Is it possible to access information about the "current" collection from within any of those methods? For example, without knowing anything specific about the functions used in the previous maps or flatMaps, and without using any intermediate declarations, how can I get the maximum value (or length, or first element, etc.) of the collection upon which the last map acts?
List(1, 2, 3)
  .flatMap(x => f(x) /* some unknown function */)
  .map(x => x + ??? /* what is the max element of the collection? */)

Edit for clarification:

*

*In the example, I'm not looking for the max (or whatever) of the initial List. I'm looking for the max of the collection after the flatMap has been applied.

*By "without using any intermediate declarations" I mean that I do not want to use any temporary collections en route to the final result. So, the example by Steve Waldman below, while giving the desired result, is not what I am seeking. (I include this condition is mostly for aesthetic reasons.)
Edit for clarification, part 2:
The ideal solution would be some magic keyword or syntactic sugar that lets me reference the current collection:
List(1, 2, 3)
  .flatMap(x => f(x))
  .map(x => x + theCurrentList.max)

I'm prepared to accept the fact, however, that this simply is not possible.

A: Maybe just define the list as a val, so you can name it? I don't know of any facility built into map(...) or flatMap(...) that would help.
val myList = List(1, 2, 3)
myList
  .flatMap(x => f(x) /* some unknown function */)
  .map(x => x + myList.max /* what is the max element of the List? */)

Update: By this approach at least, if you have multiple transformations and want to see the transformed version, you'd have to name that. You could get away with
val myList = List(1, 2, 3).flatMap(x => f(x) /* some unknown function */)

myList.map(x => x + myList.max /* what is the max element of the List? */)

Or, if there will be multiple transformations, get in the habit of naming the stages.
val rawList    = List(1, 2, 3)
val smordified = rawList.flatMap(x => f(x) /* some unknown function */)
val maxified   = smordified.map(x => x + smordified.max /* what is the max element of the List? */)
maxified

Update 2: Watch it work in the REPL even with heterogenous types:
scala> def f( x : Int ) : Vector[Double] = Vector(x * math.random, x * math.random )
f: (x: Int)Vector[Double]

scala> val rawList    = List(1, 2, 3)
rawList: List[Int] = List(1, 2, 3)

scala> val smordified = rawList.flatMap(x => f(x) /* some unknown function */)
smordified: List[Double] = List(0.40730853571901315, 0.15151641399798665, 1.5305929709857609, 0.35211231420067435, 0.644241939254793, 0.15530230501048903)

scala> val maxified   = smordified.map(x => x + smordified.max /* what is the max element of the List? */)
maxified: List[Double] = List(1.937901506704774, 1.6821093849837476, 3.0611859419715217, 1.8827052851864352, 2.1748349102405538, 1.6858952759962498)

scala> maxified
res3: List[Double] = List(1.937901506704774, 1.6821093849837476, 3.0611859419715217, 1.8827052851864352, 2.1748349102405538, 1.6858952759962498)

A: It is possible, but not pretty, and not likely something you want if you are doing it for "aesthetic reasons."
import scala.math.max

def f(x: Int): Seq[Int] = ???

List(1, 2, 3).
  flatMap(x => f(x) /* some unknown function */).
  foldRight((List[Int](),List[Int]())) {
    case (x, (xs, Nil)) => ((x :: xs), List.fill(xs.size + 1)(x))
    case (x, (xs, xMax :: _)) => ((x :: xs), List.fill(xs.size + 1)(max(x, xMax)))
  }.
  zipped.
  map {
    case (x, xMax) => x + xMax
  }

// Or alternately, a slightly more efficient version using Streams.
List(1, 2, 3).
  flatMap(x => f(x) /* some unknown function */).
  foldRight((List[Int](),Stream[Int]())) {
    case (x, (xs, Stream())) =>
      ((x :: xs), Stream.continually(x))
    case (x, (xs, curXMax #:: _)) =>
      val newXMax = max(x, curXMax)
      ((x :: xs), Stream.continually(newXMax))
  }.
  zipped.
  map {
    case (x, xMax) => x + xMax
  }

Seriously though, I just took this on to see if I could do it. While the code didn't turn out as bad as I expected, I still don't think it's particularly readable. I'd discourage using this over something similar to Steve Waldman's answer. Sometimes, it's simply better to just introduce a val, rather than being dogmatic about it.

A: One somewhat-simple way of referencing prior output within the current map/collect operation is to use a named reference outside the map, then reference it from within the map block:
var prevOutput = ...  // starting value of whatever is referenced within the map
myValues.map {
  prevOutput = ... // expression that references prior `prevOutput`
  prevOutput       // return above computed value for the map to collect
}

This draws attention to the fact that we're referencing prior elements while building the new sequence.
This would be more messy, though, if you wanted to reference arbitrarily previous values, not just the previous one.

A: You could define a mapWithSelf (resp. flatMapWithSelf) operation along these lines and add it as an implicit enrichment to the collection.  For List it might look like:
// Scala 2.13 APIs
object Enrichments {
  implicit class WithSelfOps[A](val lst: List[A]) extends AnyVal {
    def mapWithSelf[B](f: (A, List[A]) => B): List[B] =
      lst.map(f(_, lst))

    def flatMapWithSelf[B](f: (A, List[A]) => IterableOnce[B]): List[B] =
      lst.flatMap(f(_, lst))
  }
}

The enrichment basically fixes the value of the collection before the operation and threads it through.  It should be possible to generify this (at least for the strict collections), though it would look a little different in 2.12 vs. 2.13+.
Usage would look like
import Enrichments._

val someF: Int => IterableOnce[Int] = ???

List(1, 2, 3)
  .flatMap(someF)
  .mapWithSelf { (x, lst) =>
    x + lst.max
  }

So at the usage site, it's aesthetically pleasant.  Note that if you're computing something which traverses the list, you'll be traversing the list every time (leading to a quadratic runtime).  You can get around that with some mutability or by just saving the intermediate list after the flatMap.


text:
Q: When Implementing IEqualityComparer Should GetHashCode check for null? When implementing IEqualityComparer<Product> (Product is a class), ReSharper complains that the null check below is always false:
public int GetHashCode(Product product)
{
  // Check whether the object is null.
  if (Object.ReferenceEquals(product, null))
    return 0;

  // ... other stuff ...
}

(Code example from MSDN VS.9 documentation of Enumerable.Except)
ReSharper may be wrong, but when searching for an answer, I came across the official documentation for IEqualityComparer<T> which has an example where null is not checked for:
public int GetHashCode(Box bx)
{
    int hCode = bx.Height ^ bx.Length ^ bx.Width;
    return hCode.GetHashCode();
}

Additionally, the documentation for GetHashCode() states that ArgumentNullException will be thrown when "The type of obj is a reference type and obj is null."
So, when implementing IEqualityComparer should GetHashCode check for null, and if so, what should it do with null (throw an exception or return a value)?
I'm interested most in .NET framework official documentation that specifies one way or another if null should be checked.

A: The documentation says that null values should never be hashable, and that attempting to do so should always result in an exception.
Of course, you're free to do whatever you want.  If you want to create a hash based structure for which null keys are valid, you're free to do so, in this case you should simply ignore this warning.

A: ReSharper is wrong.
Obviously code you write can call that particular GetHashCode method and pass in a null value. All known methods might ensure this will never happen, but obviously ReSharper can only take existing code (patterns) into account.
So in this case, check for null and do the "right thing".

Corollary: If the method in question was private, then ReSharper might analyze (though I'm not sure it does) the public code and verify that there is indeed no way that this particular private method will be called with a null reference, but since it is a public method, and one available through an interface, then
ReSharper is wrong.

A: ReSharper has some special case code here.  It will not warn about the ReferenceEquals in this:
if (ReferenceEquals(obj, null)) { throw new ArgumentNullException("obj"); }

It will warn about the ReferenceEquals in this:
if (ReferenceEquals(obj, null)) { return 0; }

Throwing an ArgumentNullException exception is consistent with the contract specified in IEqualityComparer(Of T).GetHashCode
If you go to the definition of IEqualityComparer (F12) you'll also find further documentation:
    // Exceptions:
    //   System.ArgumentNullException:
    //     The type of obj is a reference type and obj is null.
    int GetHashCode(T obj);

So ReSharper is right that there is something wrong, but the error displayed doesn't match the change you should make to the code.

A: There is some nuance to this question.
The docs state that IEqualityComparer<T>.GetHashCode(T) throws on null input; however EqualityComparer<>.Default - which is almost certainly by far the most used implementation - does not throw.
Clearly, an implementation does not need to throw on null it merely has the option too.
However, I'd argue that no implementation should ever throw on null here, it's just confusing, and a possible source of bugs. Exceptions are a pain in any case, being a non-local control flow mechanism, and that alone argues for using them when necessary only (i.e.: not here).  But additionally, for IEqualityComparer specifically, the docs state that whenever Equals(x, y) then GetHashCode(x) should equal GetHashCode(y) - and Equals does allow nulls, and is not documented as throwing any exceptions.
The invariant that equality implies hashcode equality makes implementing things relying on those hashcodes much simpler.  Having a gotcha with the null value is a design cost you should avoid paying without need.  And here there is no need, ever.
In short:

*

*do not throw from GetHashCode, even though it is allowed

*and do check for nulls; Resharper's warning is incorrect.

Doing this results in simpler code with fewer gotchas, and it follows the behavior of EqualityComparer<>.Default which is the most common implementation used.


text:
Q: How to convince boss to start using Codeigniter or YII at work? i work for a web development company and during the one year i have spent here, there were no improvements in the technologies we used to built our websites. I introduced jquery to them (buying the Novice to Ninja by Sitepoint) and now, i want to get rid of all these crappy PHP from scratch and use a PHP framework instead.
So what reasoning i can use to convince my boss to switch, and how to convice the other developers too?

A: It saves money

So what reasoning i can use to convince my boss to switch, and how to convice the other developers too?

Using a framework is like prefabricating pieces of a site. As long as you can work within that prefabrication it will speed development, reduce bugs and errors, and influence consistency between applications. All this boils down to it saves money.

A: Find another Job
The real problem here is culture. If you had to introduce the other developers to jQuery they don't know web development 101 and probably just don't give a damn about best practices. Maybe they just turn up work 8 hours and collect their pay, devoid of any passion for programming. When you try to get these people to learn anything they'll put up a lot of resistance rather than see the new tool as something interesting and time saving. I am looking for a new job because I think it's just easier to work along side like minded people. Maybe your feathers are too bright for the cage.
I'm in a similar situation right now. Funnily enough I want to switch off Codeigniter onto a better framework like Django, Rails or Symfony (better models, command-line and forms). Before I was hired some bad work was done in cowboy PHP, and the team is still frustrated maintaining those legacy projects. You can't escape it. It's hard enough to get a procedures manual or get everyone using a git repository for each project. But these two are slowly getting done. It could be another 5 years before I will be working 100% on Django/Rails the way things are going.
In my short career I've worked in one place which actually had a tone of documentation on how things are done, how to create a new project in a repo, how to copy it onto the production server and so on. Everyone followed the company way of doing things because the boss was a developer and made sure things were done properly.
In the mean time school up on some other languages or frameworks, it will make you more employable even if your knowledge never makes it into your current workplace.
I'm building a website with a co-worker in Django which I will later show my boss and put in my portfolio for head hunters to see.
Sneak it in the back door
The other option, which may just piss off your co-workers is to sneak your tool of choice in the back door by just ignoring them and using it anyway. If you get assigned a small project in which your the only developer that would be a good candidate.

A:
So what reasoning i can use to convince my boss to switch, and how to convice the other developers too?

Reasoning rarely works.
Examples work.
Build something, be successful.  Then explain your success by showing how the framework helped.

A: Whilst I totally agree with the other answers on here (and having tried most of them during my career) can I play devils advocate here for a sec?
Is it just a case of what the boss has now solves his business problems?
Is the company making money churning out what it always has done?
The boss is focused on the business aspect whilst the techies are focused on the technical stuff and it's often hard to provide a justifiable business case for introducing new technologies. Switching to a new technology just because it is new is rarely a solid reason.

A: I recently had to do this.  I was able to win the other developers over by saying that even if we didn't use a pre-built framework, we could build our own so we knew it inside and out.  We could also create a central repository (SVN) for our framework and each web project would be easier to maintain by separating the core framework code from project specific code.  The framework could be housed in a directory in the include_path to make all of the sites using the framework update at once or you could overwrite files as needed.

A: Explain your boss how he gains if you introduce this framework. Could be productivity gains that save money, lesser maintenance that saves time etc -- stuff he can then show to the higher management.


text:
Q: How to gracefully terminate an app on Android emulator with Eclipse (on Mac) I am trying to end my app gracefully on an Android emulator without causing a crash or killing the app.
Having read numerous posts on how to terminate or crash an app on Android, here's what I've tried:

*

*Switched the emulator to another app

*Clicked the Hang up on call button and Make a call button on the emulator

*Added finish(); System.exit(0); to my onPause event in the app

*Clicked on the root of my program in the Debug perspective in Eclipse and clicked the red square on the menu icon row to terminate, did same and disconnected as well.

Each time I start up the app after any of the above, the tracking code is considering the above chosen method a crash.
So I'm trying to figure out how to gracefully end my app and restart it without incurring a 'crash'.
Any ideas?
Big thanks


text:
Q: How can I escape "/" character in asciidoc inline anchors? I am trying to convert my website documents to asciidoc.But I have problem with asciidoc anchors.When I add / character into the anchor my anchors break down.
The following asciidoc code works:
[[en-USdocs...]]
*Tutorials:*
------------

The following asciidoc code does not work due to the / character.
[[en-US/docs...]]
*Tutorials:*
------------

Is there a way to escape that "/" character to allow anchor work properly?

A: I suspect having a / char in an anchor name is invalid HTML, but I think you can make this work with alternate markup.
Try [id="en-US/docs"] instead.
My AsciiDoc Preview plugin for Atom balks at it (Uncaught Error: Syntax error, unrecognized expression: #en-US/docs)... but it does seem to actually work. I have low confidence all browsers will respect it, however, though I realize you're just trying to reproduce existing functionality, and I think that should give you the same effect.