text:
Q: Is this gradient an isomorphism on its range? Consider the gradient (in the weak sense) as an operator $\nabla \colon H^1(\Omega)/\mathbb{R} \to [L^2(\Omega)]^d$, where $\Omega \subset \mathbb R^d$ is a domain with a smooth boundary and $d\in\{2,3\}$ is the space dimension.
Here, $[L^2(\Omega)]^d$ denotes the space of tuples or triples of square integrable functions and $H^1(\Omega)$ is the space of $L^2(\Omega)$ functions with weak derivatives in $L^2(\Omega)$. Then $H^1(\Omega)/\mathbb R$ is made up by the equivalence classes of functions that differ only by a constant.
Is this $\nabla$ an homeomorphism on its range, i.e. is it injective and is its image closed in $[L^2(\Omega)]^d$?
EDIT thanks to @5pm for the hints

A: Summarizing the hints by @5pm, we can state:
Since the norm in $H^1(\Omega)/\mathbb{R}$ is equivalent to the $L^2$-norm of the gradient, one has that the $\nabla$ as defined above is bounded from below. Thus, $\nabla$ is injective and, as it is linear, also closed.


text:
Q: PendingIntent with old extra and onCreate() don't call for singleTask Activity My Single Task Activity is not created in a new task and onCreate is not called while I set the flag FLAG_ACTIVITY_NEW_TASK in the intent. Then create the Pending intent with id 0 and PendingIntent.FLAG_CANCEL_CURRENT. What can I do?
Intent notificationIntent = new Intent(getApplicationContext(), CommentPhotoActivity.class);

notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.putExtra("posteid", pId);

PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

NotificationCompat.Builder notificationBuilder = null;
//Preciser que La notif n'a pas été ouverte
//  session.createOpenNotifCmt(false);
if(pathImg.equals("")) {
      //  notificationBuilder = new NotificationCompat.Builder(getApplicationContext()).setContentTitle("Commentaire: " + emeteur).setSmallIcon(R.drawable.ic_launcher).setContentIntent(contentIntent).setContentText(cmt).setDeleteIntent(mBroadcastIntentController);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
           notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), "my_channel_01");
           notificationBuilder.setContentTitle("Commentaire: " + emeteur).setSmallIcon(R.drawable.ic_launcher).setContentIntent(contentIntent).setContentText(cmt);//.setDeleteIntent(mBroadcastIntentController);
    } else {
           notificationBuilder = new NotificationCompat.Builder(getApplicationContext()).setContentTitle("Commentaire: " + emeteur).setSmallIcon(R.drawable.ic_launcher).setContentIntent(contentIntent).setContentText(cmt);
    }
}

Manifest:
 <activity
        android:name=".Activities.CommentPhotoActivity"
        android:label="@string/title_activity_comment_photo"
        android:screenOrientation="portrait"
        android:launchMode="singleTask"
        android:theme="@style/CustomActionBarTheme">

    </activity>

    <service
        android:name=".Services.SocketService"
        android:enabled="true"
        android:exported="true" />

When I click on notification and Activity is open I need to change the discussion(all discussions have same activity). To do that you have to go through onCreate.
CommentActivity
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_comment_photo);

    if (BuildConfig.DEBUG)
        Log.v(TAG5,"onCreate");

     data = getIntent();

    mGroupManager = new GroupeManager(this);
    postemanager = new PosteManager(this);
    manager = new CommentManager(this);
    groupemanager = new GroupeManager(this);
    mixpanel = MixpanelAPI.getInstance(this, projectToken);
    session = new SessionManager(this);

    if (BuildConfig.DEBUG)
        Log.v(PosteAdapter.TAG1, "go discussion: ParcelableExtra" + data.getParcelableExtra("yuyu"));
    // Determiner la provenance de l intent pour extraire les données
    if (data.getParcelableExtra("yuyu") != null) {
        p = postemanager.getPostFromPostEmmetIdNew(((Poste) data.getParcelableExtra("yuyu")).getIdpostemet());
        poste_id = p.getId();
        if (BuildConfig.DEBUG)
            Log.v(PosteAdapter.TAG1, "go discussion: id=" + p.getId() + " Txt=" + p.getTx() + "IdPostEmet" + p.getIdpostemet());

        if (BuildConfig.DEBUG) {
            Log.v(TAG6, "POST"+p.getTx()+"POST STATE READ: " + p.getVisited());
        }
    } else {
        //Notif Open
    //    session.createOpenNotifCmt(true);
        poste_id = data.getIntExtra("posteid", 0);
        if (BuildConfig.DEBUG) {
            Log.v(SocketService.TAG2, "2: posteid" + data.getIntExtra("posteid", 0));
        }
        p = postemanager.getPost(poste_id);
    }

      ....................

    contactmanager = new ContactManager(this);
    manager = new CommentManager(this);
    allComments = manager.getAllComments(poste_id);
    adapter = new CommentAdapter(this, allComments);

    listCmtView.setLayoutManager(new LinearLayoutManager(this));
    listCmtView.setAdapter(adapter);
    listCmtView.setItemViewCacheSize(10);
    listCmtView.setDrawingCacheEnabled(true);
    listCmtView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);

    listCmtView.smoothScrollToPosition(0);

    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linq SqlMethods NOT Like I want all the fields witch dont start with 3 numbers. With the following code I get all the lines that start with a number, I want to have the inverted result.
var LEResult = (from t1 in dtClone.AsEnumerable() //TWT
                select t1).Where(q => SqlMethods.Like(q["BillingPeriod"].ToString(), "%[0-9][0-9][0-9]"));

How can I do this with Linq?

A: Use this:
var LEResult = (from t1 in dtClone.AsEnumerable() //TWT
                select t1).Where(q => !SqlMethods.Like(q["BillingPeriod"].ToString(), "%[0-9][0-9][0-9]"));

SqlMethods.Like returns bool so you only need to add ! to negate


text:
Q: pass stopped searching linked directories I use pass (standard unix password manager) and it stopped searching linked directories, eg:
> pass find test
Search Terms: test
├── mine -> /mnt/params/.password-store/mine  [recursive, not followed]
(...)

> ls -l /home/kossak/.password-store/mine         10:44:32
lrwxrwxrwx 1 kossak kossak 32 2017-01-19  /home/kossak/.password-store/mine -> /mnt/params/.password-store/mine

> ls -ld /mnt/params/.password-store/mine
drwx------ 2 kossak kossak 4096 2021-05-06  /mnt/params/.password-store/mine

Folder mine is not recursive, it is a link to different folder. It was working some time ago, but now it stopped.
Any ideas how to fix it?
I'm using:

*

*pass v1.7.4

*Linux Manjaro


text:
Q: Python: Custom Exception Class deriving from ValueError My question seems rather simply, but I didn't find any post to this particular issue. I need my own custom exception class deriving from ValueError to print the expected type (standard error msg) as well as the type that was entered (with custom text).
class MyOwnException(ValueError):
  ...

try:
    raise MyOwnException ( int('str') ) #not sure what to do here, as I only want to
                                        #raise the exception if incorrect value type
except MyOwnException as e:
        print "Error: Expected type", e.expType() #int
        print "Error: Entered type", e.entType()  #string

To add to the above and raising my custom exception via the built-in ValueError:
class MyOwnException(ValueError):
  def __init__(self, value):
    self.value = value
  print "Error: Expected type", type(self.value) #int
  print "Error type", self.value #how to return expected value type?

try:
    int('str')
except ValueError as e:
    raise MyOwnException(e)

I would very much appreatiate any help in this regard. Thanks very much!
Cheers, Manuel

A: It's generally the case that when raising custom exceptions, you have to catch a more generic exception and re-raise a different one. So for example,
>>> class MoofiError(ValueError):
...     pass
...
>>> try:
...     int('a')
... except ValueError:
...     raise MoofiError, 'you did something wrong, fool'
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
__main__.MoofiError: you did something wrong, fool

A: The int function will always return a ValueError, rather than your custom type.
In order to throw a different exception, you would have to wrap int to catch ValueError and then raise an exception of your choice (which could include the failing value, as you want).

A: This code creates a new exception class
class MyOwnException(ValueError): pass

However nothing will make someone else's code raise your exception - you can only raise it in yours.


text:
Q: Альтернатива ADM Всем привет, столкнулся с такой проблемой. Вопрос: Есть ли альтернатива Android Device Monitor ? Мне нужно скопировать файл с девайса. У меня в виртуальном девайсе (genymotion) сохраняется база данных, мне ее нужно скопировать на локальный диск и открыть. Как это можно организовать? Спасибо

A: ADB из коммандной строки умеет это
http://developer.android.com/tools/help/adb.html#copyfiles


text:
Q: Nested jQuery Cycle? I am trying to build a slide show with jQuery cycle plug in.
In the slide show there are contents and inside the contents there is basic image gallery.
Timeout of cycle which image gallery uses is fewer than the contents timeout. So content waits for 15 second and the image gallery will have 5 pics with 3 seconds timeout which makes 15 second then the content changes.
Everything sounds ok but when i execute the page, it cycles the content and the first image gallery. But when it jumps to second content it doesn't cycle the image gallery.
I have tried to put $('#cycleImages').cycle({... this code block above the image gallery repeater but it didnt work out.
How can i get these nested cycles work together?
Thank you

And this is my html mark up

            <asp:Repeater ID="rptContent" runat="server">
                <ItemTemplate>

("Type.Name") %>

("Title") %>

                                <asp:Repeater ID="rptBigPictures" DataSource='<%#Eval("Images") %>' EnableViewState="false"
                                    runat="server">
                                    <ItemTemplate>
                                        <asp:Image ID="imgProfile" runat="server" ImageUrl='<%#Eval("Path") + ".jpg" %>' />
                                    </ItemTemplate>
                                </asp:Repeater>

                </ItemTemplate>
            </asp:Repeater>

A: If I'm getting your concept this should work.  One thing you will need to do to make it look right is to have a fixed width and height of cycleContent with overflow:hidden.
Edit I changed the second jquery selector to use the class.  So the markup no longer has cycleImages as an id.  Since you will be repeating it, you should use a class to select the elements.
jQuery(function($) {
    $('#cycleContent').cycle({
        fx: 'scrollRight',
        timeout: 15000
    });
    $('.cycleImages').cycle({
        fx: 'fade',
        speed: 500,
        timeout: 3000,
        pause: 1
    });
});

The CSS I'm using is this, note the width and height are the sizes of my test images.
#cycleContent
{
    width: 77px;
    height: 94px;
    overflow: hidden;
}

And the markup, just so for clarity.

A: What about this ?
(I am not shure but...) end: function() { ... }
should work properly
$(document).ready(function() {
    $('.cycleImages').cycle(); // <- class in here
    var slideshow = $('#cycleContent').cycle({ // <- ID in here
        fx: 'scrollRight',
        speed: 'fast',
        timeout: 0,
        before: function() {
            $(this).cycle({ // <- new call of the inner
                fx: 'fade',
                speed: 'fast',
                timeout: 3000,
                autostop: true,
                end: function(){ slideshow.cycle('next'); } // <- new call of the outer
            });
        }
    });
});

So you don´t need to worry about numbers of elements in the inner cycles, 3 or 5 or what, don´t care.
Greetinx, Michael


text:
Q: How can I preserve views and controllers across restart of an application in iPhone? I am building up a game and want to give user a continue functionality when he restarts the application. So I want to know how to code or what to do to start an application where it left last time.
Is there any sample code available in app center which explains how can this be possible.
Tnx in advance.

A: Use NSUserDefaults. I don't know how you're app is structured, but that way, you can store some amount of information when the app quits. Next time when you launch, you can check to see if a value exists (NSUserDefaults behaves like NSDictionary), and if it does, start up from there.
Jeff LaMarche has a tutorial on saving the state for tab bar controllers on his blog.

A: I think you could use a form of persistent storage, like NSUserDefaults, where you could save the application's state, and reload it after each restart. I'm thinking about loaded Nib names and specific controls' properties, depending on your application's logic.


text:
Q: Load JSON object including escaped json string I'm trying to load a JSON object from a string (via Python). This object has a single key mapped to an array. The array includes a single value which is another serialized JSON object. I have tried a few online JSON parsers / validators, but can't seem to identify what the issue with loading this object is.
JSON Data:
    {
      "parent": [
        "{\"key\":\"value\"}"
      ]
    }

Trying to load from Python:
>>> import json
>>> test_string = '{"parent":["{\"key\":\"value\"}"]}'
>>> json.loads(test_string)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting , delimiter: line 1 column 15 (char 14)

A: If you try out your string in the REPL, you'll see pretty quickly why it doesn't work:
>>> '{"parent":["{\"key\":\"value\"}"]}'
'{"parent":["{"key":"value"}"]}'

Notice the \ have gone away because python is treating them as escape sequences ...
One easy fix is to use a raw string:
>>> r'{"parent":["{\"key\":\"value\"}"]}'
'{"parent":["{\\"key\\":\\"value\\"}"]}'

e.g.
>>> import json
>>> test_string = r'{"parent":["{\"key\":\"value\"}"]}'
>>> json.loads(test_string)
{u'parent': [u'{"key":"value"}']}


text:
Q: How to pass the REG QUERY value to if, then statement I'm trying to create a batch file to check for Office 2010 Bitness. If it's x86 I want to install the x86 version of an application, and if not the x64 version.
I am running a REG QUERY to find this information out.
REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Office\14.0\Outlook /v Bitness
How do I pass the value across to my If/Then/Else Statement?
IF (value) EQU x86 ??? THEN
) ELSE (

A: @echo off
for /f "skip=2 tokens=3 delims= " %%R in ('REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Office\14.0\Outlook /v Bitness') do (
 set "reg_value=%%R"
)
echo %reg_value%
if "%reg_value%" EQU "x86" (
  do something
) else (
 do something else
)

A: Something like this can work, but you didn't provide the output so I guessed it says x86.  You'll have to check that the key exists to start with.
REG QUERY "HKEY_LOCAL_MACHINE\Software\Microsoft\Office\14.0\Outlook" /v Bitness  |find "x86" >nul
if not errorlevel 1 echo found x86


text:
Q: Spring @Value split empty string to a List I using @Value("#{'${names}'.split(',')}") to loading List from properties file.
But if the value of names in properties file is unset like this
names=

then Spring will initialize a list with size 1, not size 0, and the only element in this list is a empty string, that's weird.
I want to know is this a bug, or Im using it wrong? Im using spring 3.2.3 btw.
Thanks.

A: It's not bug of spring,is is a defect of method split in String class,example:
"".split(",");

the result length is 1,and contain a empty string;

A: Other solution if you don't want to use external libraries is to use elvis expression. Maybe not very elegant but works.
@Value("#{'${names}'.empty?(new java.util.ArrayList()):'${names}'.split(',')}")


text:
Q: Multiple entries in to table variable using Output INTO clause My use case is as below  :
Create table Emp
(
    id int ,
    fname varchar(100),
    lname varchar(100)
)

declare @aud table (prop varchar(1000),[oldval] varchar(100),[toval] varchar(100))

INSERT INTO EMP(id, fname, lname)
OUTPUT 'fname', '', inserted.fname INTO @aud (prop, [oldval], [toval])
VALUES (1,'malcolm','dsouza')

SELECT * FROM @aud

I want the data to be formed like:
prop   oldval   toval
------------------------
fname           malcolm
lname           dsouza

I know we cannot have have multiple inserts using OUTPUT INTO clause, but is there any other way I can form a data for inserted rows as column based?

A: You need to try below steps:

*

*OUTPUT clause simply inserts the rows in to the table variable i.e., one row to one row mapping. You need to modify your table definition accordingly.

*Now, You can use CROSS APPLY to get the result you want.
**TEST SETUP**
Create table  #Emp(
id int ,
fname  varchar(100),
lname varchar(100)
)

TEST
declare @aud table(oldfname varchar(100),fname varchar(100),oldlname varchar(100), lname varchar(100));

INSERT INTO #EMP(id,fname,lname)
OUTPUT '' as oldfname,inserted.fname, '' as oldlname, inserted.lname INTO @aud
values (1,'malcolm','dsouza');

SELECT property, oldval, newval as oldValue
FROM @aud
CROSS APPLY
( values('fname',oldfname,fname),('lname',oldlname, lname)) as t(property,oldVal, newVal)

Result Set
+----------+--------+----------+
| property | oldval | oldValue |
+----------+--------+----------+
| fname    |        | malcolm  |
| lname    |        | dsouza   |
+----------+--------+----------+


text:
Q: Bazel - Get current OS and CPU type as variables to be used in build rules In our current setup, we use Bazel as the overall build tool, but for individual Java projects, we use Maven for building them. An example build rule for a Java project will look like this:
genrule (
    name = "build-core",
    srcs = [
        ":deps-core",
    ],
    outs = [
        "core-1.0.jar",
    ],
    cmd = "rm -rf $(@D)/src && cd project/ && umask 0000"
        + " && mvn -U clean install -Djavacpp.platform=linux-x86_64 -pl :core"
        + " && cp core/target/core-1.0.jar ../$(@D)"
)

As you can notice, we are currently hardcoding the -Djavacpp.platform to linux-x86_64. Is there a way to get this value automatically from Bazel, maybe as a variable, so that we can use the same build rules to build on MacOSX and Windows systems too?

A: It would be better to build all of the libraries with Bazel directly, then you would get this behaviour for free. See Migrating from Maven to Bazel.
However, if this is not an option, you can access some of this information using Make Variables:
genrule(
  name = "g",
  outs = [
    "g.txt",
  ],
  cmd = "echo \"$(TARGET_CPU) $(COMPILATION_MODE) $(JAVA) $(JAVABASE)\" > $@",
  toolchains = [
    "@bazel_tools//tools/jdk:current_java_runtime",
  ],
)

I could not find the operating system in these variables, however.
Perhaps a better idea is to use select statements:
genrule(
  name = "f",
  outs = [
    "f.txt",
  ],
  cmd = select({
    "@bazel_tools//src/conditions:darwin": "echo 'macOS' > $@",
    "//conditions:default": "echo 'Linux' > $@",
  }),
)

You would then write a different cmd for each platform.


text:
Q: Searching dataset by multiple tags Maybe the title of this question is a little bit odd because I simply have no idea what I'm looking for.
I have some data e.g. a string and multiple tags associated with it. Now I would like to have the ability to search through my data with a string.

Edit: The Problem is not the string comparison or the substring
  search! The Problem is the connection from the result to the data
  object.

Here a Movie example:
"Title1" tags: "genre1" "genre2" "actor1" "actor2"
"Title2" tags: "genre2" "actor2" "actor3"
"Title3" tags: "genre2" "genre3" "actor1" "actor3"

Search for "genre2" -> "Title1", "Title2", "Title3"
Search for "Title1" -> "Title1"
Serach for "actor1" -> "Title1", "Title3"

Other examples:

*

*YouTube: Search for a Video ...

*Amazon: Search for "tv" but "tv" does not have to be in the title.

The only thing in my mind is a multimap pointing to a list of all possibilities. Then I have to compare the search string with all keys and tada. But I can not believe that this is a good solution because I would have an insane amount of lists...
Can anyone give me an idea of what I'm looking for and maybe how I can implement this? I use c++ with Qt. I don't know if Qt could help me in any way.
Edit: I could add all keyword together like this:
"Title1 genre1 genre2 actor1 actor2"
"Title2 genre2 actor2 actor3"
"Title3 genre2 genre3 actor1 actor3"

Create a map with this key to the data object. Then I only have to do a string search and get all strings where the search string is a substring of the key.
But is this a good solution? What if I want to prioritize a match in the title?

A: If its a a lot of data, or you expect to migrate the data to another computer, I'd go with Qt's built in SQL functionality.

A: Severel Month later I decided to work on this problem again and finally, I have a solution. It took me ~ 4 h to get everything working. I'm using now Toxi-Tagging with SQLite in Qt. I had this Idea from this post and looked also into other possibilities. Here is a page with multible options and a small comparison: Link
Here is my Solution:
Create the Database and add Values to it. Then you can do a simple substring search like this:
SELECT Data.* FROM Data
INNER JOIN DataTag ON DataTag.DataID=Data.ID
INNER JOIN Tag ON DataTag.TagID=Tag.ID WHERE Tag.Tag LIKE "%substring%"
GROUP BY Data.ID

Sidenote: If your Tag list is really large it is probably beneficial to use FTS3 or FTS4. Here is more info.
Create Database:
QString scom;
QSqlQuery query;

scom = "CREATE TABLE Data ("
       "ID INTEGER PRIMARY KEY,"
       "Data1 VARCHAR(120) NOT NULL UNIQUE,"
       "Data2 INTEGER NOT NULL,"
       "Data3 INTEGER NOT NULL);";

if(!query.exec(scom))
{
    qDebug() << "Error creating table Data";
}

scom = "CREATE TABLE Tag ("
       "ID INTEGER PRIMARY KEY,"
       "Tag VARCHAR(120) NOT NULL UNIQUE);";

if(!query.exec(scom))
{
    qDebug() << "Error creating table Tag";
}

scom = "CREATE TABLE DataTag ("
       "DataID INTEGER,"
       "TagID INTEGER,"
       "FOREIGN KEY(DataID) REFERENCES Data(ID)"
       "FOREIGN KEY(TagID) REFERENCES Tag(ID));";

if(!query.exec(scom))
{
    qDebug() << "Error creating table DataTag";
}

scom = "CREATE UNIQUE INDEX index_name ON Tag (Tag)";

if(!query.exec(scom))
{
    qDebug() << "Error could not create index on Tag Tag";
}

Adding Values to the Database:
QString scomadddata, scomaddtag, scomadddatatag, scomsearchtag;
QSqlQuery query;

scomadddata = "INSERT INTO Data (ID, Data1, Data2, Data3) "
              "VALUES (NULL, ?, ?, ?)";

query.prepare(scomadddata);
query.addBindValue(data1);
query.addBindValue(data2);
query.addBindValue(data3);

if(!query.exec())
{
    qDebug() << "Error adding values to Data";
    qDebug() << query.lastError();
}

QVariant dataid = query.lastInsertId();

scomsearchtag = "SELECT ID FROM Tag WHERE Tag = ";
scomaddtag = "INSERT INTO Tag (ID, Tag) VALUES (NULL, ?)";
scomadddatatag = "INSERT INTO DataTag (DataID, TagID) VALUES (?, ?)";

for(int i = 0; i < tags.count(); ++i)
{
    QVariant tagid;

    // Search if Tag allready exists
    if(!query.exec(scomsearchtag + "\"" + tags[i] + "\""))
    {
        qDebug() << "Error searching for Tag";
        qDebug() << query.lastError();
    }

    if(query.next())
    {
        tagid = query.value(0);
    }
    else
    {
        // Add Tag to Tag Table
        query.prepare(scomaddtag);
        query.addBindValue(tags[i]);

        if(!query.exec())
        {
            qDebug() << "Error adding values to Tag";
            qDebug() << query.lastError();
            continue;
        }

        // Get Tag ID
        tagid = query.lastInsertId();
    }

    // Link Tag ID with Data ID
    query.prepare(scomadddatatag);
    query.addBindValue(dataid);
    query.addBindValue(tagid);

    if(!query.exec())
    {
        qDebug() << "Error adding values to DataTag";
        qDebug() << query.lastError();
    }
}


text:
Q: How to make current line bold in VS Code editor? In VS Code, if my caret cursor is on a given line is it possible for the code on that line alone to become bold?
Similar to how putting the following in settings.json allows for highlighting of the background of current line, per this and this:
    "workbench.colorCustomizations": {
      "editor.lineHighlightBackground": "#404040"
    },

Or how putting this would make all text bold, per this question:
"editor.fontWeight": "bold"

Except instead of a background modification I'd like to bold the font/text/code itself, and instead of all text, just the current line.  (The bolded text need not be selected, just on the same line as the caret.)
Thanks.

A: It seems unlikely, since VSCode is a text editor, not a word processor. If your document is in markdown mode, and you have the right extension installed, Cmd/Ctrl-B does markdown.extension.editing.toggleBold, but it does that by adding/removing characters to the selected text.  E.g. for me "This is a test" becomes "**This is a test**", which is interpreted as bold.
If you want to "tag" lines of code to say they're important, something like bookmarks might work?  https://marketplace.visualstudio.com/items?itemName=alefragnani.Bookmarks

A: Another "not really an answer, but might be helpful" link. If you choose the whole line to "mark" it would make that line bold, or a different style.
https://marketplace.visualstudio.com/items?itemName=ryu1kn.text-marker

*

*Features

*Highlight/Unhighlight text from both command palette or right-click
menu

*Update existing highlight rules from the right-click menu

*Jump to the next/previous location of the same highlighted pattern
Highlight text using a regular expression


text:
Q: How to find JNDI name in JBoss-7? Please find the scenario below,
@Stateless(name = "TestManager")
@Remote(TestInterfaceRemote.class)
@Local(TestInterfaceLocal.class)
public class TestManagerBean implements TestInterfaceLocal, TestInterfaceRemote {}

The following JNDI name for the TestManagerBean class which is printed in server.log file if the server log level is INFO. By using this JNDI, I am able to access the bean in the EJB client program.
java:global/Sample/Demo/TestManager!net.juniper.jmp.test.TestInterfaceRemote
My question is,
How to find same JNDI names in JBoss-7 setup? Do we have any console to know the all JNDI's in JBoss?
I tried to find JNDI names by using jconsole mode but there's only EJB name not fully qualified JNDI name on it.
Could you please give me an IDEA if we have an option to know JNDI names in JBoss-7?

A: In JBoss EAP 6.2.0.GA (JBoss AS 7.3.0.Final) the web administration console provides a JNDI View:


text:
Q: Crontab commands not executed correctly I asked for some help with speedtest-cli a few days ago and now I need help with the following:
I made this crontab:
0 * * * * (date +"%A, %d.%m.%Y %X Uhr" >> /home/pi/speedtest/speed.txt; /usr/bin/speedtest-cli --server 3645 --simple >> /home/pi/speedtest/speed.txt; echo "\n" >> /home/pi/speedtest/speed.txt)
10 * * * * (speedtest-cli --server 3645 --share; grep -Po 'Share results: \K.*' >> /home/pi/speedtest/latest.txt)

(look here to see it better formatted: https://hastebin.com/holugehuvo.js)
I'll explain, what I want to do with it: So the first command should print the current date and time in my region format into a text file. The output of speedtest-cli --server 3645 --simple should be appended to the same file and after that should be a new line so that I can see the next output (output one hour later) correctly formatted.
An output of the command speedtest-cli --server 3645 --simple would be something like that:
Ping: xx.xx ms
Download: 53.09 Mbit/s
Upload: 7.92 Mbit/s

This should be repeated every hour.
And the second cron should grep the http:// address returned by the command and print that into a file called latest.txt.
An example output for speedtest-cli --server 3645 --share would be sth like that:
Retrieving speedtest.net configuration...
Testing from Provider (xx.xxx.xxx.xxx)...
Retrieving speedtest.net server list...
Selecting best server based on ping...
Hosted by Citycom Telekommunikation GmbH (Graz) [xx.xx km]: xx.xxx ms
Testing download speed................................................................................
Download: 52.88 Mbit/s
Testing upload speed....................................................................................................
Upload: 7.62 Mbit/s
Share results: http://www.speedtest.net/result/7799311524.png

I just need that http:// address because I want to read that in PHP and display this png on my local web page so that I know what was my last speed test.
Both commands should run once per hour, I used a little offset so that the speed is not influenced by the other speedtest made in the first command.
I need both outputs because I want to monitor my last speeds AND have that image accessible with PHP.
I know that this was/is a long question, but I want to give you many details so that it's easier to understand what I wanted to do.
Thank you for your help.

A: There are several points of improvement here:

*

*Usage of %:
You have to escape it and write it as \%

The "sixth" field (the rest of the line) specifies the command to be run.  The entire command portion of the line, up to a newline or a % character, will be executed by /bin/sh or by the shell specified in the SHELL variable
     of the cronfile.  A % character in the command, unless escaped with a backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input.
source: man 5 crontab

*Compound commands
You write multiple commands in a single crontab command as
( command1; command2 ) >> /path/to/output

While this works, it must be mentioned that this will spawn a sub-shell and is a bit an overkill. You might consider not to do so using:
{ command1; command2; } >> /path/to/output

or if you do not want command2 to execute if command1 failed, you could do:
command1 && command2 >> /path/to/output

*Usage of pipe: Your second command should use a pipe (|)
speedtest-cli --server 3645 --share | grep -Po 'Share results: \K.*' >> /home/pi/speedtest/latest.txt


text:
Q: Image upload button not showing in magento WYSIWYG editor for limited access users In magento 1.9 we have two types or users

*

*Administrator

*Content Manager

Administrator user has full rights whereas content manager users have limited access. Now if a content manager user want to add image in product description using wysiwyg then there is no image upload/browse option.
But for the administrator user who has full access can see the image upload/browse button in wysiwyg editor.
Please check the following screenshots for better understanding

Please help me to show image upload button in product description wysiwyg editor for limited access users as well.

A: You must provide below access in your user role Resources
CMS -> Media Gallery


text:
Q: Rust Lifetimes with mpsc::Sender> and threads I'm creating a multi-threaded application where I create a receiving channel and a structure to hold the sending channel (to be used later by the implementation). However, the type I'm sending through the channel has a lifetime specification. This type is websocket::message:Message
from the rusts-weboscket library. Because of this specification, rust can't seem to correctly infer lifetimes when it gets passed through a thread.
Here's a rust playground example of this error:
https://play.rust-lang.org/?gist=7e37547d1c811185654f10a6a461e1ef&version=stable&backtrace=1
Now, I have tried using crossbeam to scope the lifetime, and this seems to solve that immediate issue, but in practically just delegates the lifetime specification issue somewhere else.
In my code I get the error:
   $ cargo check
   Compiling rump v0.1.0 (file:///home/alainh/UPenn/CIS198/Rump)
transport.rs:200:42: 200:57 error: cannot infer an appropriate lifetime for autoref due to conflicting requirements [E0495]
transport.rs:200         self.sender.send(self.serializer.encode(message));
                                                          ^~~~~~~~~~~~~~~
transport.rs:199:5: 202:6 help: consider using an explicit lifetime parameter as shown: fn send<T: Encodable>(&'a mut self, message: &T) -> WampResult<()>
transport.rs:199     fn send<T: Encodable>(&mut self, message: &T) -> WampResult<()> {
transport.rs:200         self.sender.send(self.serializer.encode(message));
transport.rs:201         Ok(())
transport.rs:202     }
error: aborting due to previous error
Could not compile `rump`.

The line in question is this one:
https://github.com/aehernandez/Rump/blob/ad717c7ef11857e94d0e1c02539667c8034676c4/src/transport.rs#L199
At this point I'm unsure how to exactly solve this lifetime issue. I don't want to keep delegating it somewhere else. Is there a good solution to this?

A: When you spawn a thread it can potentially live forever; certainly outliving your Transport<'a> type for any lifetime 'a other than 'static (the error messages are very confusing though). When you call thread::spawn with a closure, that closure must have the 'static lifetime, which is only true if 'a == 'static.
As you are not actually sending an object with a lifetime across the channel, consider using the 'static lifetime explicitly:
impl Connector for Transport<'static> {
    ...
}

Playpen
Edit:
Manually annotating the types for the sender and receiver
    let (tx, rx): (mpsc::Sender<Message<'a>>, mpsc::Receiver<Message<'a>>) = mpsc::channel();
    let tx_send: mpsc::Sender<Message<'a>> = tx.clone();

shows you a much more sensible error
<anon>:27:22: 27:35 error: the type `[closure@<anon>:27:36: 29:10 tx_send:std::sync::mpsc::Sender<Message<'a>>]` does not fulfill the required lifetime [E0477]
<anon>:27         let handle = thread::spawn(move || {
                               ^~~~~~~~~~~~~
note: type must outlive the static lifetime
error: aborting due to previous error
playpen: application terminated with error code 101

Playpen


text:
Q: MVC Connection Error : The underlying provider failed on Open I am new to ASP.NET MVC4. I'm trying to connect database using entity framework but didn't succeeded.
connection string is as follows
<add name="EmployeeContext" connectionString="Data Source=192.168.1.101;Initial Catalog=MVCPrac;User ID=sa;Password=anything"  providerName="System.Data.SqlClient"/>

I am fetching data using following code:
public ActionResult Details(int id)
    {
        EmployeeContext empContext = new EmployeeContext();
        Employee emp = empContext.Employees.Single(emps => emps.EmployeeId == id);
        return View(emp);
    }

I am Getting error as follows:
System.Data.Entity.Core.EntityException was unhandled by user code
Message=The underlying provider failed on Open.
Source=EntityFramework
StackTrace:
   at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
   at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection(Boolean shouldMonitorTransactions)
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass3.<GetResults>b__1()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__3[TResult](IEnumerable`1 sequence)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
   at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.Single[TSource](IQueryable`1 source, Expression`1 predicate)
   at MVC_Trials.Controllers.EmployeeController.Details(Int32 id) in C:\Users\administrator.CRC\Documents\Visual Studio 2010\Projects\MVC Trials\MVC Trials\Controllers\EmployeeController.cs:line 19
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
InnerException: System.Data.SqlClient.SqlException
   Message=Cannot open database "MVC_Trials.Models.EmployeeContext" requested by the login. The login failed.
Login failed for user 'Test\Administrator'.
   Source=.Net SqlClient Data Provider
   ErrorCode=-2146232060
   Class=11
   LineNumber=65536
   Number=4060
   Procedure=""
   Server=.\SQLEXPRESS
   State=1
   StackTrace:
        at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
        at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
        at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
        at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
        at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject)
        at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)
        at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
        at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
        at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
        at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
        at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
        at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
        at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
        at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
        at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
        at System.Data.SqlClient.SqlConnection.Open()
        at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__36(DbConnection t, DbConnectionInterceptionContext c)
        at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
        at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
        at System.Data.Entity.Core.EntityClient.EntityConnection.<Open>b__2()
        at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
        at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
        at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
        at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
   InnerException:

I didn't understand why its giving Login failed for user 'Test\Administrator'. error.
EmployeeContext.cs code
public class EmployeeContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
}

Please help me out. Thanks in advance.

A: You are not specifying the connection string to use for your context so it's using the default one. Add this to your context, it is a default constructor which will pass the name of the connection string to the base context class.
public EmployeeContext() : base("EmployeeContext")
{
}

A: You have the stack track, but what you need to see is the Inner Exception Message that is going to tell you what is really wrong and what is causing the exception to be thrown.


text:
Q: What are the algorithm details of FindRoot? The Help page of FindRoot says: "by default, FindRoot uses Newton's method (Newton-Raphson) to solve a nonlinear system". But I still have the following puzzles:

*

*How will the Jacobian be calculated in each iteration: symbolically or using finite difference approximation only?

*Is there any damping method of the step being used when the Jacobian at any step is invertible?

A: You can control how the Jacobian is calculated via the Jacobian option:
Grid[Module[{s = 0, e = 0},
    {#,
     FindRoot[ArcTan[1000 Cos[x]], {x, 1}, StepMonitor :> s++,
      EvaluationMonitor :> e++, Jacobian -> #, Method -> {"Newton"}],
     "Steps" -> s,
     "Evaluations" -> e
    }] & /@ {"Symbolic", "FiniteDifference"}]

Note the Sparse suboption of this option described on the linked Documentation page (see also this tutorial page for additional examples of use), it works both with "Symbolic" and "FiniteDifference" methods. The DampingFactor option may be also of help.
You can also find useful this MathGroups answer by Oliver Ruebenkoenig (Wolfram Research).


text:
Q: gnuplot abbreviation reference Where are the gnuplot abbreviations specifically documented?
For example:- the single letter "l" command.
 > help l
gives a big list and does not identify what the single letter "L" command is expanded to.
This question comes from reading posted example scripts & is related to Looking up gnuplot abbreviations which does not clarify how the single letter abbreviations are disambiguated.
Many thanks, hope the answer helps others

A: Autoextracted list of gnuplot command abbreviations from source code

       bi - bind
       ca - call
       cl - clear
     eval - evaluate
       ex - exit
        f - fit
        h - help
       hi - history
        l - load
      low - lower
        p - plot
       pa - pause
       pr - print
 printerr - printerror
        q - quit
       ra - raise
       re - reread
      ref - refresh
      rep - replot
      res - reset
       sa - save
      scr - screendump
       se - set
       sh - show
      she - shell
       sp - splot
       st - stats
       sy - system
      und - undefine
      uns - unset
       up - update

Many thanks to https://superuser.com/users/257269/hastur for the inspiration!
I trust this reference is useful.
The exact abbreviation priority may vary with each version of gnuplot.  It was extracted from the tarball with the following sh script (or similar).
# Extract file --to-stdout -O
# Specifically select the command table
# Grep commands
# Remove { } syntax, commas & double quotes
# Print abbr & full command
# sort
tar -xv -O -f /opt/local/var/macports/distfiles/gnuplot/5.0.3/gnuplot-5.0.3.tar.gz  gnuplot-5.0.3/src/tables.c | \
  sed -n '/command_ftbl\[\]/,/invalid_command/p'                        | \
  grep '\$'                                                             | \
  sed 's/{//g ; s/}//g ; s/,/ /g ; s/"//g'                              | \
  awk '{split ($1,a, "$"); printf ("%10s - %s \n", a[1],a[1]a[2] ) }'   | \
  sort -bf

The commands are stored in the array command_ftbl[], command options etc are in other tables, but once you know the command, the documentation usually makes the option abbreviations clear.


text:
Q: For continuous function $f$, prove: $\int_{0}^{x} \; \left[\int_{0}^{t}f(u) \;du \right] \;dt=\int_{0}^{x} f(u)(x-u)du$ I'd love your help with proving that:

For continuous function $f$, $$\int_{0}^{x} \left[\int_{0}^{t}f(u) \; du \right] \; dt = \int_{0}^{x} f(u)(x-u)du$$

I'm not quite sure what I should do with this.
From Newton-Leibniz theorem I get that the left side of the equation is $(F(t)-F(0))x$, while on the right side I wanted to do an integration by parts, but I'm not sure how or if it is the direction.
Thanks a lot for the help.

A: You should integrate by parts the LHside with differential factor $\text{d} t$.
In fact, since $f$ is continuous then $F(t):=\int_0^t f(u)\ \text{d} u$ is of class $C^1$ and its derivative is $f(t)$; hence:
$$\begin{split} \int_0^x \left[\int_0^t f(u)\ \text{d} u\right]\ \text{d} t &= t\ \int_0^t f(u)\ \text{d} u\Bigg|_0^x - \int_0^x t\ f(t)\ \text{d} t\\ &= x\int_0^x f(t)\ \text{d} t -\int_0^x t\ f(t)\ \text{d} t\\ &= \int_0^x (x-t)\ f(t)\ \text{d} t\; ,\end{split}$$
which is the claim.

A: HINT
There are couple of ways.
The first one is to change the order of integration using Fubini's theorem and this immediately gives you the answer.
The second way is a bit roundabout. Consider $$F(x) = \int_0^x \int_0^t f(u) du dt - \int_0^x f(u) (x-u) du. $$ Prove that $F'(x) = 0$ using Leibniz integration rule and hence $F(x) = F(0) = 0$ giving us the desired result.

A: Let $$\begin{align}F(x)&=\int_{0}^{x}f(u)(x-u)\,du \\&= x \int_{0}^x f(u)\,du -\int_{0}^x uf(u)\,du.\end{align}$$
Now, we know how to take the derivative of all these terms, $x$ and the two integrals, so we can compute:
$$\begin{align}F'(x) &= \int_0^x f(u) \,du + xf(x) - xf(x) \\&= \int_0^x f(u) \,du.\end{align}$$
But that means that $$\begin{align}F(x) &= C + \int_0^x F'(u) \,du \\&= C + \int_0^x \left(\int_0^u f(t)\,dt\right)\,du\end{align}$$ for some constant $C$.  But clearly, using $x=0$, $C=0$, so you are done.


text:
Q: Consulta sobre Base de Datos - Sacar dos datos que más se repiten por cada inicial de un nombre tengo un problemilla con una base de datos, a ver si me podéis echar un cable.
Tengo una base de datos de trabajadores, que tienen nombre, id... Estos trabajadores se repiten a lo largo de la tabla.
Lo que necesito es que por cada inicial me saque los dos nombres que más se repiten, es decir:

*

*(A) Antonio se repite 1 vez, Álvaro 7 y Alberto 5

*(B) Berto 3, Billy 6 y Borja 8
Y así sucesivamente
Lo que tengo es:
SELECT Nombre as Nombre, COUNT(*) AS VecesRepetido
FROM lista
GROUP BY Nombre
HAVING COUNT(Nombre) >1;

Con esto me saca todos los nombres que se repiten en la lista, ordenados alfabéticamente. Pero me saca TODOS los que se repiten, que pueden ser 6 nombres que empiecen por la A, y no los dos que más lo hacen.
Entonces el programa me debería sacar
Álvaro 7, Alberto 5, Billy 6, Borja 8.

Gracias, un saludo!

A: Algo así podría servirte. Utiliza SUBSTR para recoger la primera letra de cada nombre. Y después haces otra select para hacer que sólo muestre 2.
SELECT Nombre, Inicial,
FROM(
SELECT Nombre as Nombre, SUBSTR(Nombre,1,1) as Inicial, COUNT(*) AS VecesRepetido
FROM lista
GROUP BY Nombre, Inicial HAVING COUNT(Nombre) >1;
)
WHERE COUNT(Inicial) < 3;


text:
Q: Overflow-y not working when overflow-x is hidden? I have a DIV that contains several other divs. I need divs to be able to peek out of the parent vertically, but not horizontally.
I thought using overflow-x and overflow-y would solve this little problem, but I can only get either x and y to show, or get them both to hide.
My CSS and HTML:

.game {
  position:absolute;
  width:400px; height:300px;
  top:100px; left:100px;
  background-color:#cccccc;

  overflow-x:hidden;
  overflow-y:visible;
}

.block1 {
  position:absolute;
  width:100px; height:100px;
  top:-50px; left:150px;
  background-color:#ffcccc;
}

.block2 {
  position:absolute;
  width:100px; height:100px;
  top:150px; left:-50px;
  background-color:#ccffcc;
}

See this JSFiddle: both child divs are cut off, even though overflow-y is set to visible.

A: Structural Change Needed
This gets what you want if it works otherwise (I don't know if the html/css changes affect other aspects of your game). It solves it by layering the "game" so that its vertical direction fills the entire screen, and then your "window" (grey area) is set by a child div. This allows the overflow: hidden horizontally, but not have it vertically.
See fiddle.
HTML

CSS
html, body { height: 100%; margin: 0;}
.game {
    position:absolute;
    width:400px;
    height:100%;
    top: 0;
    left:100px;
    overflow:hidden;
}
.game > div {
    position: absolute;
    top: 100px;
    height: 300px;
    width: 100%;
    background-color:#cccccc;
}

.block1 {
    position:absolute;
    width:100px; height:100px;
    top:-50px; left:150px;
    background-color:#ffcccc;
}

.block2 {
    position:absolute;
    width:100px; height:100px;
    top:150px; left:-50px;
    background-color:#ccffcc;
}

A: try Changing your game class to
.game {
     width:400px; height:300px;
    top:100px; left:100px;
    background-color:#cccccc;
    overflow-x:hidden;
    overflow-y:auto;
}

Thanks,
Dhiraj


text:
Q: Switch statement: number to enum value / 1002 = MyEnum.NewYorkID Well, I want to make this work
public static void main(String[] args) {

    int cityId = 1234;

    switch (cityId) {
        case MOSCOW:
            System.out.println("Moscow");
            break;

        case SOCHI:
            break;
}

public enum Test {
    MOSCOW,
    NEWYORK,
    SOCHI
}

So I want to link Test enum with city ids, is that possible? What is the best pattern for this situation?
Thank you!

A: The only problem with your code is that you need to switch on Test not int.
ie:
public static void main(String[] args) {

    Test city = SOCHI;

    switch (city) {
        case MOSCOW:
            System.out.println("Moscow");
        break;

       case SOCHI:
           break;
}

public enum Test{
    MOSCOW,
    NEWYORK,
    SOCHI
}

A: You can't mix that in a switch. Either you pass a Test enum into the switch statement, or use the constant ids in the case statements.
I'd suggest having a mapping cityId <-> Test instance and converting before calling the switch.
Something like
Map<Integer, Test>` mapping = ...;
mapping.put(1234, Test.MOSCOW ); //note the use of autoboxing

...

mapping.get(cityId); //note the use of autoboxing

Edit: note that you could put this mapping into the enum, add a cityId field to the enum and automatically fill the mapping from the array returned by values(), much like Chris' suggestion.
public enum Test {
   MOSCOW(1001),
   NEWYORK(1002),
   SOCHI(1234);

   private final int cityId;

   private Test(int cityId) {
    this.cityId = cityId;
   }

   ...

   private static Map<Integer, Test> mapping = new HashMap<Integer, Test>();

   static { //executed when the class is loaded
     for( Test t : values() ) {
        mapping.put(t.getCityId(), t);
     }
   }

   public static toTest(int cityId) {
     return mapping.get(cityId);
   }
}

That's something we often do for similar things.

A: You can add a cityId field in your enum:
public enum Test {
    MOSCOW(1001),
    NEWYORK(1002),
    SOCHI(1234);

    private final int cityId;

    private Test(int cityId) {
        this.cityId = cityId;
    }

    public int getCityId() {
        return cityId;
    }

    public static Test valueOf(int cityId) {
        /*
         * Using linear search because there's only a small handful
         * of enum constants. If there's a huge amount (say, >20),
         * a map lookup is better.
         */
        for (Test value : values()) {
            if (value.cityId == cityId)
                return value;
        }
        throw new IllegalArgumentException("Unknown city ID: " + cityId);
    }
}

Then you can indeed switch on the enum value:
switch (Test.valueOf(cityId)) {
case MOSCOW:
    // ...
}


text:
Q: Creating a Path/Imagemap from a Transparent PNG with Raphael JS I'm working on a Raphael JS project and need to display some transparent PNGs with only the parts that are non-transparent to be clickable. Is there a way to:

*

*Upon mouse click, pull out the alpha of the current position.
or

*Generate a path which can be be used to define the clickable region (i.e. http://raphaeljs.com/australia.html)

A: As raphael is for vector graphics, it is the wrong tool for your problem with png. I think canvas is what you looking for. Load your image in an canvas (the canvas doesent need to be pushed in the DOM). On click check the coords and get the pixel out of the canvas.
But maybe it will be easier to convert you png to vector graphics and use raphael instead.


text:
Q: How do I return value from inner function without creating chain of return? function xyz() {
    function abc() {
        function haha() {
            return 5;
        }
         return haha();
    }
    return abc();
}
console.log(xyz());

I get '5' in console. Thats ok. Its a simple code of larger problem where there is lots of nested functions. I dont want to return one after the other. Is there any way, I can return from any function and return it to original function caller.

A: function xyz() {
    function abc() {
        return 5;
    }
    return abc()
}
console.log(xyz());

A: Add a return the from abc function call
function xyz() {
    function abc() {
        return 5;
    }
    return abc();

}
console.log(xyz());

Or return an IIFE (Immediately Invoked Function Expression)
function xyz() {
  return (function abc() {
      return 5;
  })();

}

console.log(xyz())

A: ok maybe you need call backs. I don't get the context of what you are trying to do but I'll just try.
function logTheAnswer (a) {
    console.log(a)
}

function add(a, b, cb) {
    cb(a + b)
}

add(1,2,logTheAnswer)

now you can nest the call backs indefinitely though try to keep it a minimum as you will experience call back hell.

A: Sorry to say but your question is a bit confusing without a proper output representation. But you can use callback functions with which you can easily manage your nested calls and returns.
function myFunc3(a, b, callback3){
    callback3(a+b);
}
function myFunc2(a, b, c, callback2){
    myFunc3(a+c, b, function(result2){
        callback2(result2);
    })
}
function myFunc1(){
    myFunc2(a,b,c, function(result1){
        console.log(result1);
    })
}


text:
Q: Why am I getting object error 91 when I use printform function in vba Im having a problem where when I am openning up a userform and printing it out as well as printing out an excel sheet is gives me the error

Object error 91

This is the code for the command button that starts loads the Userform and unloads the current userform
Private Sub CommandButton1_Click()
    Cells(10, 2).Value = stageBox.Value
    Cells(11, 2).Value = materialBox.Value
    Cells(12, 2).Value = POBox.Value
    Cells(13, 2).Value = MPIBox.Value
    Cells(14, 2).Value = LPIBox.Value
    Unload Me
    UserForm1.Show

End Sub

After it opens it it runs this
Dim Batch As String
Dim Draw As String
Dim Rev As String
Dim ScrapQR As String
Dim goodQty As String
Dim desc As String
Dim scrapQty As String
Dim stage As String
Dim material As String
Dim po As String
Dim mpi As String
Dim lpi As String

Sub UserForm_Initialize()
    Call gatherData
    Call popData
    Call printStuff
    Unload Me
End Sub

Sub gatherData()

    Batch = Cells(1, 2).Value
    Draw = Cells(3, 2).Value
    Rev = Cells(4, 2).Value
    ScrapQR = Cells(8, 2).Value
    goodQty = Cells(6, 2).Value
    scrapQty = Cells(7, 2).Value
    desc = Cells(2, 2).Value
    stage = Cells(10, 2).Value
    material = Cells(11, 2).Value
    po = Cells(12, 2).Value
    mpi = Cells(13, 2).Value
    lpi = Cells(14, 2).Value

End Sub

Sub popData()
    BatchBox.Text = Batch
    DrawBox.Text = Draw
    DescBox.Text = desc
    RevBox.Text = Rev
    GoodBox.Text = goodQty
    ScrapBox.Text = scrapQty
    DateBox = Date
    QRBox.Text = ScrapQR
    sBox.Text = Cells(10, 2).Value
    matBox.Text = Cells(11, 2).Value
    PBox.Text = Cells(12, 2).Value
    MBox.Text = Cells(13, 2).Value
    LBox.Text = Cells(14, 2).Value

End Sub

Sub printStuff()

    Dim fileName As String

    fileName = "Surface_Finish_" & Batch

    'Print Sheet1 exactly one page wide and tall
    With Worksheets("Surface Finish").PageSetup
        .Zoom = False
        .FitToPagesTall = 1
        .FitToPagesWide = 1
    End With

    Worksheets("Surface Finish").ExportAsFixedFormat _
        Type:=xlTypePDF, _
        fileName:="N:\Buckets\Sdata\Dyllon_Dunton\" & fileName, _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=False, _
        IgnorePrintAreas:=False, _
        From:=1, _
        To:=1, _
        OpenAfterPublish:=False

    PrintForm

End Sub

Any help would be greatly appreciated

A: You can not use unload command until you use .show, please remove this one.
Private Sub CommandButton1_Click()
    Cells(10, 2).Value = stageBox.Value
    Cells(11, 2).Value = materialBox.Value
    Cells(12, 2).Value = POBox.Value
    Cells(13, 2).Value = MPIBox.Value
    Cells(14, 2).Value = LPIBox.Value
    Unload Me ' this one..................................
    UserForm1.Show

End Sub


text:
Q: Под фиксированное меню на старте скрола частично прячется контент, как это побороть? Есть прилипающее меню, идущее за блоком header (header имеет фиксированную высоту). Проблема в том что идущий сразу же контент, на старте скрола частично прячется под самим меню. Как это возможно побороть? Пробовал добавлением и padding и margin, все безрезультатно.
Код jquery меню:

$(window).scroll(function(){
        if ($(window).scrollTop()>$("header").height()-$("my-nav").height()){
            $(".my-nav").addClass("stickly");
        }
        else
        {
            $(".my-nav").removeClass("stickly");
        }
    });

Вот проект

A: Вот как пример, особо не стилизовал, но серый блок отлично прилипает к потолку при этом контент не прыгает. Линк на codepen. И сам код:
var distance = $('h1').offset().top,
    heightTitle = $('h1').outerHeight(true)
    $window = $(window);

$window.scroll(function() {
    if ( $window.scrollTop() >= distance ) {
       $('h1').addClass('sticked')
       $('html').css('margin-top', heightTitle)
    }
  else {
       $('h1').removeClass('sticked')
       $('html').css('margin-top', '0')
  }
});


text:
Q: AngularJs: How to use web worker with makepdf There is a solution here that explains how to use web worker with makepdf. However, I want to know how to apply this solution to angular using requirejs.
I have tried to use ngwebworker along with requireJs, as the RequireJS within webworker, but I had no success. Can someone help me?
EDIT:
To make it easier to visualize the problem, I will put on this edit the code that it is not working:
                                           $scope.exportToPDF = function(){

                    var list = $rootScope.orderedData;
                        var body = [];

                            var headers = new Array();
                            headers.push({ text: 'A', fillColor: '#0075E5', color: '#ffffff'});
                            headers.push({ text: 'B', fillColor:#0075E5', color: '#ffffff'});
                            headers.push({ text: 'C', fillColor:#0075E5', color: '#ffffff'});
                            headers.push({ text: 'D', fillColor:#0075E5', color: '#ffffff'});
                            headers.push({ text: 'E', fillColor:#0075E5', color: '#ffffff'});
                            headers.push({ text: 'F', fillColor:#0075E5', color: '#ffffff'});
                            body.push(headers);

                            for (var key in list)
                            {
                                if (list.hasOwnProperty(key)){
                                    var position = list[key];
                                    var fila = new Array();
                                    fila.push( { text: position.a.toString(), fillColor: '#ffffff' } );
                                    fila.push( { text: position.b.toString(), fillColor: '#ffffff'}  );
                                    fila.push( { text: position.c.toString(), fillColor: '#ffffff'} );
                                    fila.push( { text: position.d.toString().substring(0,5) + "...", fillColor: '#ffffff'}  );
                                    fila.push( { text: position.e.toString(), fillColor: '#ffffff'} );
                                    body.push(fila);
                                }
                            }
                            var dd = {
                                    background: [{
                                        width: 30,
                                        alignment: 'left'
                                    }],
                                      pageOrientation: 'landscape',
                                      footer: function(currentPage, pageCount) { return currentPage.toString() + '/' + pageCount;},
                                      info: {
                                            title: 'Title',
                                            author: 'Me'
                                          },
                                content: [
                                          { text: 'Text', style: 'header' },
                                    {
                                        style: 'tableHeader',
                                        table:
                                        {
                                            dontBreakRows: true,
                                            headerRows: 1,
                                            widths: ['5%', '10%', '10%', 'auto', '15%', 'auto', 'auto', '10%', '10%', 'auto', '4%', '10%'],
                                            body: body
                                        }
                                    }
                                ],
                                styles: {
                                    header: {
                                        fontSize: 18,
                                        bold: true,
                                        margin: [0, 0, 0, 10],
                                        alignment: 'center'
                                    },
                                    subheader: {
                                        fontSize: 16,
                                        bold: true,
                                        margin: [0, 10, 0, 5]
                                    },
                                    tableExample: {
                                        margin: [0, 5, 0, 15]
                                    },
                                    tableHeader: {
                                        bold: true,
                                        fontSize: 9,
                                        color: 'black',
                                        margin: [0, 5, 0, 15]
                                    }
                                },
                                defaultStyle: {
                                },
                            };
                              var obj =  pdfMake.createPdf(dd) // FAST PROCESS!

                              var myWorker = Webworker.create(downloadIt);

                              myWorker.run(obj).then(function(body) {
                                });

                   function downloadIt(obj) {
                       obj.download("Title.pdf"); // REALLY SLOW PROCESS THAT SHOULD BE IN BACKGROUND
                   }

                   }

The problem is that to transfer an object to a web worker, they suggest to use JSON.parse and JSON.stringify. However, if I use that on my object, I will loose the method "download". Is there a way to send this object to my function downloadIt without loosing the method download of pdfmake object?


text:
Q: Do I need to use a selector with jQuery .load()? I have the following:
function callback_function(a,b,c) {
    var aa = a;
    var bb = b;
    $('#content').html("xxx");
}

$('#content').load(href, "", function (a, b, c) { callback_function(a, b, c) });

What I want to do is to put the value "xxx" into the html of the div#content. Can someone explain how to do this? I think it will work with the code in the callback_function but then if that works then will the actual .load() also put some data into #content?
Do I even need something to the left of the .load() if I am doing everything in the callback_function(). I hope this makes sense. Please note it's not production ready. I realize I need to rename parameters, do error checks and such.d
Please note I want to use .load not .ajax. as I am using the following wrapper. Sorry in advance that it's a lot of code:
$.fn.loadWithEffect = function()
{
    // Add effect layer
    this.addEffectLayer({
        message: $.fn.loadWithEffect.defaults.message
    });

    // Rewrite callback function
    var target = this;
    var callback = false;
    var args = $.makeArray(arguments);
    var index = args.length;
    if (args[2] && typeof args[2] == 'function')
    {
        callback = args[2];
        index = 2;
    }
    else if (args[1] && typeof args[1] == 'function')
    {
        callback = args[1];
        index = 1;
    }

    // Custom callback
    args[index] = function(responseText, textStatus, XMLHttpRequest)
    {
        // Get the effect layer
        var refElement = getNodeRefElement(this);
        var layer = $(refElement).next('.loading-mask');
        var span = layer.children('span');

        // If success
        if (textStatus == 'success' || textStatus == 'notmodified')
        {
            // Initial callback
            if (callback)
            {
                callback.apply(this, arguments);
            }

            // Remove effect layer
            layer.stop(true);
            span.stop(true);
            var currentMarginTop = parseInt(span.css('margin-top'));
            var marginTop = parseInt(span.css('margin-top', '').css('margin-top'));
            span.css({'marginTop':currentMarginTop+'px'}).animate({'opacity':0, 'marginTop':(marginTop-40)+'px'}, {
                'complete': function()
                {
                    layer.fadeAndRemove();
                }
            });
        }
        else
        {
            span.addClass('error').html($.fn.loadWithEffect.defaults.errorMessage+'
'+$.fn.loadWithEffect.defaults.retry+' / '+$.fn.loadWithEffect.defaults.cancel+'');
            span.children('a:first').click(function(event)
            {
                event.preventDefault();

                // Relaunch request
                $.fn.load.apply(target, args);

                // Reset
                span.removeClass('error').html($.fn.loadWithEffect.defaults.message).css('margin-left', '');
            });
            span.children('a:last').click(function(event)
            {
                event.preventDefault();

                // Remove effect layer
                layer.stop(true);
                span.stop(true);
                var currentMarginTop = parseInt(span.css('margin-top'));
                var marginTop = parseInt(span.css('margin-top', '').css('margin-top'));
                span.css({'marginTop':currentMarginTop+'px'}).animate({'opacity':0, 'marginTop':(marginTop-40)+'px'}, {
                    'complete': function()
                    {
                        layer.fadeAndRemove();
                    }
                });
            });

            // Centering
            span.css('margin-left', -Math.round(span.outerWidth()/2));
        }
    };

    // Redirect to jQuery load
    $.fn.load.apply(target, args);

    return this;
};

A: instead of load() use ajax():
$.ajax({
   url : href,
   success:function(data){
      callback_function(a, b, c) });
    }
})

A: Just change your code so you do not do the selection twice:
function callback_function(a,b,c) {
    var aa = a;
    var bb = b;
    $(this).html("xxx"); //<-- key!
}

$('#content').load(href, callback_function);

or use .ajax instead of .load:
function callback_function(a,b,c) {
    var aa = a;
    var bb = b;
    $("#content").html("xxx");
}
$.ajax({
   url : href,
   success: callback_function
});


text:
Q: using googlemaps api to geocode addresses using php and mysqli I'm trying to update a field in a mysqli database. I am trying to use the googlemaps api to fill in the lat/lng geocode into the database. I know googlemaps has a usage limit, but I made a project in the Google developers console and made an API key. But nothing I do is working -- I still get the OVER_QUERY_LIMIT error. (I went over the limit, I guess, in trying to troubleshoot my code.)
Is this a lost cause? Do I have to look up the lat/lng of each address by hand? How can I get the googlemap lat/lngs for each of my (400-odd) addresses?
Here is my php code:
include_once ('constants_test.php');
   // connect to database
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    if (mysqli_connect_errno()) {
            printf("Connect failed: %s", mysqli_connect_error());
            exit();
    }

    date_default_timezone_set('America/New_York');
    $q = "SELECT provider_ID, location FROM `data` where point = ''";
    $result = $mysqli->query($q);

    while($row = $result->fetch_array(MYSQLI_ASSOC)) {
         $location = $row['location'];
         $provider = $row['provider_ID'];
         set_time_limit ( 120 );
         geocode($location, $provider);
    }

    function geocode($address, $provider){

    // url encode the address
    $address = urlencode($address);

    // google map geocode api url
    $url = "http://maps.google.com/maps/api/geocode/json?address={$address}&sensor=false";

    // get the json response
    $resp_json = file_get_contents($url);

    // decode the json
    $resp = json_decode($resp_json, true);
    echo $resp['status'];
    // response status will be 'OK', if able to geocode given address
    if($resp['status']=='OK'){

        // get the important data
        $lati = $resp['results'][0]['geometry']['location']['lat'];
        $longi = $resp['results'][0]['geometry']['location']['lng'];
        $formatted_address = $resp['results'][0]['formatted_address'];

        // verify if data is complete
        if($lati && $longi && $formatted_address){
            $new_location = "(" . $lati . "," . $longi . ")";
            $mysqli2 = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); //open db conn
            $new_q = "Update `data` set point = '" . $new_location . "' where provider_ID = '" . $provider . "'";
            echo $new_q;

            $result2 = $mysqli2->query($new_q);

        }else{
            return false;
        }

    }else{
        return false;
    }
}


text:
Q: Rotate the root of a BVH animation around Y axis by an angle Even if you are not familiar with BVH file format, maybe you could help me on how to combine two rotations.
I just take the root's rotation (copying x,y,z values) from BVH file that the channels of the root as set like this:
CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation
And I want to rotate the root by some degrees could be 0 up to 360, around y axis (0,1,0). This rotation works at some frames. However, at most of the frames, the root is rotated strangely (it is like a gimbal lock has happened).
This is the code I use. C# in Unity. I just want to apply the root's rotation around y axis correctly.
I can confirm that the code works fine (correct BVH animation) when adding 0 degrees rotation around y axis. So, the error has to be in the combination of those 2 rotations (qBefore and YawRotationQuaternion).
private Vector3 getFinalRootRotation(Vector3 rotationFromBvh, float angle)
{
    // [INITIALIZE]: Convert Euler to Quaternion for each axis.
    Quaternion qX = Quaternion.AngleAxis(rotationFromBvh.x, Vector3.right);
    Quaternion qY = Quaternion.AngleAxis(rotationFromBvh.y, Vector3.up);
    Quaternion qZ = Quaternion.AngleAxis(rotationFromBvh.z, Vector3.forward);
    Quaternion qBefore = qY * qX * qZ; // Multiply them in the correct order.
                                       // Order in BVH file is ZXY.

qY*qX*qZ has exaclty the same euler x,y,z results as Quaternion.Euler(rotationFromBvh)
    // [CREATE ROTATION AROUND Y]: Get the quaternion of rotating around y axis.
    Quaternion YawRotationQuaternion = Quaternion.AngleAxis(angle, Vector3.up);

    // [APPLY ROTATION AROUND Y]
    Quaternion qAfter = qBefore * YawRotationQuaternion;

    // [RETURN IN XYZ FORM]
    return qAfter.eulerAngles;
}

My goal is to create a new BVH that has the new root's rotation. This is the part of the code where I write the new rotation in the file. This code is tested and creates a BVH file ok.
private string CreateMLine(Vector3 rootPosition, Vector3 rootRotation, List<Vector3> rotations)
{
    StringBuilder s = new StringBuilder();
    // Apply root's translation and rotation.
    s.Append(rootPosition.x + " " + rootPosition.y + " " + rootPosition.z + " ");
    s.Append(rootRotation.z + " " + rootRotation.x + " " + rootRotation.y + " ");

    for(int i=1; i<rotations.Count; i++) // start at 1 ==> skip rotation of the root.

    {
        s.Append(rotations[i].z + " " + rotations[i].x + " " + rotations[i].y + " ");
    }
    s.Append("\n");
    return s.ToString();
}

A: I'ld say you get the values of the BVH in the order Zrotation Xrotation Yrotation for a good reason.
From Quaternion.eulerAngles:

A rotation that rotates euler.z degrees around the z axis, euler.x degrees around the x axis, and euler.y degrees around the y axis (in that order).

So I think the mistake lies in
Quaternion qBefore = qY * qX * qZ;

which uses an incorrect order.

it should rather be
Quaternion qBefore = qZ * qX * qY;

I'ld suggest to use Quaternion.Euler instead

Returns a rotation that rotates z degrees around the z axis, x degrees around the x axis, and y degrees around the y axis.

Quaternion qBefore = Quaternion.Euler(rotationFromBvh.x, rotationFromBvh.y, rotationFromBvh.z);

A: Physically, quaternion multiplication means applying rotation from right to left.
q1 * q2 means rotate by q2 and then q1
So if you want to apply a rotation after another, put it on the left hand side.
In you case, it should be:
Quaternion qAfter = YawRotationQuaternion * qBefore;


text:
Q: How use python subprocess.call, sending copy of stdout to logfile, while detecting result of first command My python script needs to invoke a program, detect if it failed (eg, result != 0) and send the output of the program to both stdout like normal plus a log file.
My default shell is bash. I'm using Python 2.7.9
To send output to both stdout and a file I'd normally use tee:
result = subprocess.call('some_program --an-option  | tee -a ' + logfile , shell=True)

However, the pipe in bash will return true even if the first command fails, so this approach fails to detect if the command fails.
If I try to use set -o pipefail in the command (so that the result will indicate if the first command fails) like this:
result = subprocess.call('set -o pipefail && some_program --an_option  | tee -a ' + logfile , shell=True)

I get the error /bin/sh: 1: set: Illegal option -o pipefail
Is there a way in python to invoke a command, send the output to both the normal stdout console and a logfile, and still detect if the command failed?
Note: we have to continue sending some_program's output to stdout since stdout is being sent to a websocket.

A:
I get the error /bin/sh: 1: set: Illegal option -o pipefail

Pass executable='/bin/bash' otherwise /bin/sh is used.
You could implement tee in pure Python:
#!/usr/bin/env python2
import sys
from subprocess import Popen, PIPE

chunk_size = 1 << 13
p = Popen(["some_program", "--an-option"], stdout=PIPE, bufsize=1)
with p.stdout, open('logfile', 'ab') as logfile:
    for chunk in iter(lambda: p.stdout.read(chunk_size), b''):
        sys.stdout.write(chunk)
        logfile.write(chunk)
if p.wait() != 0:
    raise Error

A: My preference would to to send stdout to a pipe, and then read the pipe in the Python code. The Python code can write to stdout, a file, etc as required. It would also enable you to set shell=False as setting it to True is a potential security issue, as mentioned in the documentation.

A:
However, the pipe in bash will return true even if the first command
  fails, so this approach fails to detect if the command fails.

That is not true.
But I think you mean: the 'some_program --an-option  | tee -a ' + logfile exit status code always is 0 even though fails in any command part.
Well, using multiple commands (when using && or ||) or connecting  multiple commands together via pipes causes unreliable exit status code when returned.
Regardless, in the command: some_program --an-option  | tee -a ' + logfile  logfile is not written if some_program fails. So you don't need to worry regarding exit code.
Anyway the best way to do pipe along with subprocess is creating Popen objects ans handling stdout and stdin:
import subprocess as sp
STATUS_OK = 0
logfile = '/tmp/test.log'
commands = {
    'main' :   'ls /home',
    'pipe_to': 'tee -a ' + logfile
}

process = sp.Popen(commands['main'], shell=True, stdout=sp.PIPE)
# explicitly force waits till command terminate, set and return exit status code
process.wait()

if process.returncode == STATUS_OK:
    stdoutdata = process.communicate()[0]
    # pipe last command output to "tee" command
    sp.Popen(commands['pipe_to'], stdin=sp.PIPE, shell=1).communicate(stdoutdata)
else:
    # do something when command fails 'ls /hom' (in this case) fails
    pass

That is it!
I the last Popen we invoke Popen.communicate() to send the last output from ls command to tee command STDIN.
In the Python doc there's a tiny tutorial called Replacing shell pipeline, maybe you want take a look.


text:
Q: Is it okay to blacklist one of the files in the node modules during npm run build: prod? One of the files in my node modules is causing a issue, specifically showing this error: 'Module parse failed: You may need an appropriate loader to handle this file type.' Is it okay to exclude this file during build? Any drawbacks? Should we exlude all node modules during build? Please someone explain this to me. If I exlude this file, I can able to build the application successfully.

A: If a you or a module/package that you import/require relies on the module that errors you can't just exclude it from the build. If this is not the case you should be able to fix the error by deleting your node_modules folder and package.lock file and running npm i.
If the actual error persists, you need to modify your webpack config to include a loader for that file type. If you are using create-react-app you will have to npm run-script eject to do this. You should Google the loader you need for the filetype you have.


text:
Q: Choose which array to loop over I am creating a javascript function to build the html for a calendar (in a
) for the current month. One of the parameters of the function is whether to write out the days of the week or use their initials. The full names and initials are both contained in arrays. The function will loop over one of the arrays to build the table cells that contain the days of the week. What is the best way to pick which array to loop over? Or should I be constructing this code in an entirely different way?
Code to illustrate my question:
buildCalendar(useFullNames){
    var fullNames = ['Sunday', 'Monday'], // etc.
        initials = ['S', 'M'],
        calString = '
';

    if(useFullNames) {
        // use fullNames array in the loop
    }
    else {
        // use initials array in loop
    }

    for(i=0; i<7; i++)
    {
        // Need to loop over the array picked above
        calString += '' + relevantArray[i] + '	';
    }

    calString += '
';
}

A: var relevantArray = useFullNames ? fullNames : initials;

A: What about something like this (pseudocode):
buildCalendar(dayOfWeekFormat){ //dayOfWeekFormat: "fullNames or "initials"
    var dayOfWeekFormat = {
       fullNames: ['Sunday', ..., 'Saturday'],
       initials: ['S', ..., 'Sat']
    }
    var calString = '
';

    for(i=0; i<7; i++)
    {
        // Need to loop over the array picked above
        calString += '' + daysOfWeek[dayOfWeekFormat][i] + '	';
    }

    calString += '
';
}

relevantArray is an awful variable name. It doesn't tell you anything about what's in it.

A: Well, like you have it set up, set the relevantArray variable
buildCalendar(useFullNames){
    var fullNames = ['Sunday', 'Monday'], // etc.
        initials = ['S', 'M'],
        calString = '
',
        relevantArray;

    if(useFullNames) {
        // use fullNames array in the loop
        relevantArray = fullNames;
    }
    else {
        // use initials array in loop
        relevantArray = initials;
    }

    for(i=0; i<7; i++)
    {
        // Need to loop over the array picked above
        calString += '' + relevantArray[i] + '	';
    }

    calString += '
';
}


text:
Q: I would like to get a detailed explanation on how we can upload file to google drive from an hybrid application using javascript I am developing a hybrid mobile application which requires a file upload to google drive via javascript. It's working fine for me with web application. But come to mobile side it require a redirect url. How can we achieve that?
This is my code.
But using the same code on mobile(Hybrid) applications it need redirect URL. The authorization part is not working. I did not get back the token.
<button id="authorize-button" style="visibility: hidden">Authorize</button>
<script type="text/javascript">

    var clientId = 'client_id';
    var apiKey = ' ----';
    var scopes = 'https://www.googleapis.com/auth/drive.file'

    function handleClientLoad() {
        // Step 2: Reference the API key
        gapi.client.setApiKey(apiKey);
        window.setTimeout(checkAuth, 1);
    }

    function checkAuth() {
        gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: true }, handleAuthResult);
    }

    function handleAuthResult(authResult) {
        console.log(authResult);
        var authorizeButton = document.getElementById('authorize-button');
        if (authResult && !authResult.error) {
            authorizeButton.style.visibility = 'hidden';
            makeApiCall();
        } else {
            authorizeButton.style.visibility = '';
            authorizeButton.onclick = handleAuthClick;
        }
    }

    function handleAuthClick(event) {
        // Step 3: get authorization to use private data
        gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: false }, handleAuthResult);
        return false;
    }

    // Load the API and make an API call.  Display the results on the screen.
    function makeApiCall() {
      ///  gapi.client.load('drive', 'v2', RetrieveARSettingsAttachment);
      gapi.client.load('drive', 'v2', makeRequest);
    }
</script>
    <script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>


text:
Q: Suggestions for optimizing this java code with Math functions I have the following java code. I am trying to optimize the function
        while(pStart < audio.length) {

        int pEnd = Math.round(pStart + winSize*Fs);

        int windowEnd = Math.min(pEnd, audio.length);
        double[] window = new double[fftSize*2];

        for(int i = pStart; i < windowEnd; i++) {
            window[(i-pStart)*2] = audio[i];
        }

        fft.complexForward(window);

        double fftVal;
        for(int i = 0; i < fftSize/2; i++) {

            fftVal = Math.sqrt((window[i*2] * window[i*2])  + (window[i*2+1] * window[i*2+1] ));

            powerAll[i][index] = 20 * Math.log10(
                    Math.abs(fftVal) / (windowEnd - pStart));
        }
        index++;

        pStart = pStart + windowSlide;

    }

Timing as per trace files:
Total 2500 ms
fft ~500 ms
self ~900 ms
second for loop ~900 ms
So, my focus is to optimize the second for loop as for now. I cannot change the fft function.
On the same issue, I am not sure, why the tracer reports "self" to be 900 ms.

A: Your code is an easy target for parallelization. You could either:

*

*do it by hand, calculating the subarray indices to pass to each thread;

*use ForkJoin which handles many aspects for you;

*use Java 8 which has just been released and write this as a parallelStream processing task.

My choice would certainly be number 3, if nothing else then for the fun of it.
I took some time to measure your code on my setup, using jmh. It takes 14 nanoseconds per entry of the window array. Given the amount of calculation done I think this is already a great result and couldn't be improved by any significant margin.

A: The original code can be simplified by applying math properties of log function.
Consider the following function extracted from the original code:
double original( double[] window, int i, int windowEnd, int pStart ) {
    double fftVal = Math.sqrt(
            ( window[ i * 2 ] * window[ i * 2 ] )
                    + ( window[ i * 2 + 1 ] * window[ i * 2 + 1 ] )
    );
    return 20 * Math.log10(
            Math.abs( fftVal ) / ( windowEnd - pStart ) );
}

Basically, we have the following function in the pseudo-code:
x = sqrt(w[2i]^2 + w[2i+1]^2)
return 20 * log( abs(x) / ( windowEnd - pStart ) )

*

*abs is not required, because the value of the sqrt() is non-negative.

*log(X/Y) == log(X) - log(Y)

*log(sqrt(X)) = 0.5 log(X)

*log(windowEnd - pStart) can be precalculated and cashed

The simplified variant with explanations of each step:
double variant( double[] window, int i, int windowEnd, int pStart ) {

    // w[2i]^2 + w[2i+1]^2
    double temp1 = window[ i * 2 ] * window[ i * 2 ]
            + window[ i * 2 + 1 ] * window[ i * 2 + 1 ];

    // apply log(sqrt(X)) == log(X^0.5) == 0.5 log(X)
    double temp2 = 0.5 * Math.log10( temp1 );

    // calculate the value of Math.log10( windowEnd - pStart )
    // (and cache it outside of the function)
    double tempConst3 = Math.log10( windowEnd - pStart );

    // apply log(X/Y) == log(X) - log(Y)
    double temp4 = temp2 - tempConst3;

    return 20 * temp4;
}

A: The simple optimizations that you can do is to store the value of window[i*2] and window[i*2+1] in a variable and use them in the sqrt() method which will reduce the number of array accesses.
Other than that, if you could say what you are trying to do, we might be able to help you better.


text:
Q: I can't seem to resolve java.io.FileNotFoundException (Too many open files in system) Disclaimer. First I am NOT a SU.  I'm a mid level computer user with a bit of experience.  I can write some basic code, have used computers for 20+ years.  MSDOS, to Windows through the years now I'm on OS X.  I've searched high and low for a few weeks now and so have decided to come to the big guns to ask for assistance.  I hope you're OK with this.
Firstly I'm on OS X 10.11.6.
I have been having an issue with my Crashplan backup software and was working through it with their support people.  It all came down to the error:
java.io.FileNotFoundException (Too many open files in system)

I read about and found I had to increase the number of open files allowed on my system.  I did this creating and changing the values of files located in /Library/LaunchDaemons.
I created two files:
limit.maxfiles.plist and limit.maxproc.plist
Within limit.maxfiles.plist I placed:
    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
        "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>Label</key>
    <string>limit.maxfiles</string>
    <key>ProgramArguments</key>
    <array>
      <string>launchctl</string>
      <string>limit</string>
      <string>maxfiles</string>
      <string>54000</string>
      <string>54000</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>ServiceIPC</key>
    <false/>
  </dict>
</plist>

and within limit.maxproc.plist I placed:
    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple/DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  <plist version="1.0">
    <dict>
      <key>Label</key>
        <string>limit.maxproc</string>
      <key>ProgramArguments</key>
        <array>
          <string>launchctl</string>
          <string>limit</string>
          <string>maxproc</string>
          <string>4096</string>
          <string>4096</string>
        </array>
      <key>RunAtLoad</key>
        <true />
      <key>ServiceIPC</key>
        <false />
    </dict>
  </plist>

I restarted and checked this had taken affect by running launchctl limit maxfiles at the terminal.  This showed that it was in effect.
I started crashplan again and it gave the same error.  I checked with the crashplan people and they basically said tough, that's the problem, go fix it (which is fair enough I think).
So, I kept upping the number of files allowed to be open until I got to 900000000). Yes, that's a total of 900 million files allowed open.  More than I have on my total drive.  The error still persists.  Checking with launchctl limit maxfiles it shows that it is in effect.
So, that's left me stumped.  I then looked around and found that I can run a command like so ulimit -S -n 900000 which will give some other part of the system more files to play with.  I'm not sure how that works, but I checked it ulimit -a and it was in effect.  Same problem with Crashplan though.
So now I'm not sure what to do so I've come to ask the people who know OS's better than most.  Can anyone offer some guidance as to what I can try to resolve this?
Thanks so much.

A: Maybe this actually answers the question for you.  Paste the following into a Terminal window:
while true; do
    sudo lsof |
       awk '{ files[$1]++ } END { for (key in files) { print key, files[key] } }' |
       sort -n -k 2 | tail -10
    sleep 60;
done

What that is going to do:

*

*while true - Until you interrupt it, e.g., Control-C

*lsof - List all the open files on the system and the name of the
process (command) that has those files open

*awk - Count the number of the open files by process

*sort - Sort that list by number of open files

*tail - Report the 10 processes with the most files open

*sleep - Wait a minute and do the whole thing again

You should either see the culprit immediately or it will start moving toward the end of the list before too long.


text:
Q: Returning boolean from DB2 using JPQL As a part of a compound JPQL query I am using a subselect
(select count(obj)=0 from TABLE_NAME obj where obj.id = outerObject.id)

It is supposed to return boolean telling if the object is deleted in TABLE_NAME. It works great when running with H2, but fails with syntax error when running with DB2 9.7.0.4.
I have tried executing some similar bare sql queries on both databases and H2 executes all of them without problems, but I am not able to return boolean anyhow in DB2, for example
SELECT count(*)=0 from TABLE_NAME

fails with syntax error as well as
SELECT 1=0 from TABLE_NAME

IBM says that the boolean type was introduced in 9.7 but I am confused about usages. The page http://www-01.ibm.com/support/knowledgecenter/SSEPGG_9.7.0/com.ibm.db2.luw.apdv.sqlpl.doc/doc/c0053651.html says that

The Boolean data type can only be referenced as: (...) Return type

But it also says

The Boolean data type cannot be returned in a result set.

Is it possible to execute a boolean returning query in DB2 or do I have to return count(*) to Java and check if its zero on the Java side?

A: You can replace it with exists query:
WHERE NOT EXISTS (select obj from TABLE_NAME obj where obj.id = outerObject.id)

also the count(obj) value of 0 should be interpreted as false so you can simply negated

A: You can create a udf (user defined function) that parses the boolean value and returns a string
Create function bool_to_char (boolean value) return char (5)
Begin
 Declare ret char (5) default 'false';
 If (value is true) then
  Set ret = 'true';
  End if;
  Return ret;
 End@

The you call the same select with the function
Select bool_to_char (xxx) from ....