text:
Q: How to sort vector of pair by both first and second value? This is the output of my sorted vector of pair<int, char>:
6 X
6 E
6 C
5 D
4 D
4 B
2 A

But I want it to be sorted by the integer in descending order and alphabetically ascending where the integer is the same. Like this:
6 C
6 E
6 X
5 D
4 D
4 B
2 A

Here is my code:
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<pair<int, char>> v;
    v.push_back(make_pair(5, 'D'));
    v.push_back(make_pair(2, 'A'));
    v.push_back(make_pair(6, 'C'));
    v.push_back(make_pair(4, 'B'));
    v.push_back(make_pair(4, 'D'));
    v.push_back(make_pair(6, 'X'));
    v.push_back(make_pair(6, 'E'));

    sort(v.rbegin(), v.rend());

    for (auto x: v)
        cout << x.first << " " << x.second << endl;

    return 0;
}

A: You can write it manually:
sort(v.begin(), v.end(),
  [](auto a, auto b) {
    return a.first > b.first || (a.first == b.first && a.second < b.second);
  }
);


text:
Q: Calling procedure in function Can you call a PL/SQL procedure from inside a function?
I haven't come across with the practical example.So if anyone has come across with this please share.

A: Yes. You can call any pl/sql program from inside any other pl/sql program. A function can call a function, a procedure can call a procedure which calls a function, a function can invoke a TYPE BODY...do an INSERT..which causes a TRIGGER to fire.
A simple (not really practical) example.
Using the HR schema where you have an EMPLOYEES table which includes columns EMPLOYEE_ID, FIRST_NAME, and LAST_NAME.
I have a function that takes in an INTEGER which we use to look up an EMPLOYEE record. We take their first and last names, and concat them together, and return the value back in UPPERCASE text.
Before we do that however, we call a procedure which does nothing but take a 5 second nap using the DBMS_LOCK package.
The code:
create or replace procedure do_nothing_comments (x in integer, y in integer)
is
begin
 null;
 -- yeah, this is a dumb demo
 dbms_lock.sleep(5);
end;
/

create or replace FUNCTION upper_name (
    x IN INTEGER
) RETURN VARCHAR2 IS
    upper_first_and_last VARCHAR2 (256);
BEGIN
    SELECT upper (first_name)
           || ' '
           || upper (last_name)
      INTO upper_first_and_last
      FROM employees
     WHERE employee_id = x;

    do_nothing_comments (1, 2); -- here we are calling the procedure
    RETURN upper_first_and_last;
END;

/
Now let's invoke the function.
DECLARE
  X NUMBER;
  v_Return VARCHAR2(200);
BEGIN
  X := 101;

  v_Return := UPPER_NAME(
    X => X
  );
  :v_Return := v_Return;
END;

/
I'm going to do this in SQL Developer using the Execute feature with the function open:

I get the answer back...it just takes 5 seconds longer than it really needed to.

A: Here you go:
create or replace function demo
    return varchar2
as
begin
    dbms_output.put_line('Hello');
    return 1;
end demo;

redpajama_set_name: RedPajamaStackExchange


text:
Q: What punctuation mark should be used before the choices when asking a question starting with "which"? In the following question:

Which is more expensive_ the apple or the orange?

What punctuation should I use in place of the underscore?
I have thought of a few possibilities.

Which is more expensive? The apple or the orange?

When I read it without punctuation, I kinda raise my tone in both "expensive" and "orange", so I guess I should put question marks in both places?

Which is more expensive, the apple or the orange?

The two parts belong to a single question, so there should be a single question mark at the end?

Which is more expensive - the apple or the orange?

I faintly remember that I saw something like this in books. My memory could be wrong though.
Which should be used and why?

A: Either of these is fine:
Which is more expensive, the apple or the orange?
Which is more expensive - the apple or the orange?

In the second version above, it should be a dash (longer) rather than a hyphen (shorter), and the point is to draw attention to this part of the sentence. See http://blog.apastyle.org/apastyle/2010/09/computer-editing-tip-em-dashes.html
However, the following format is not okay, because The apple or the orange? is a fragment:
Which is more expensive? The apple or the orange?


text:
Q: Process builder & schedule action issue We have two Process builders on Opportunity (both when a record is created or edited). The first one is executed when the  stageName is equals to 2 and update a datetime field (stageNameDate) with the run datetime . The second PB is executed when stageName is not equals to 5 and schedule an action to send an email 10 days after the stageNameDate field.
If the opp is created with stage equals to 2 the email is sent in that moment by the second PB instead of wait 10 days. The stageNameDate field is set correctly by the first PB, it is equals to the opp created date.
Why the email is sent immediately instead of schedule the action??

First PB

Second PB


text:
Q: R - streamR package - using filterStream to capture all tweets? I need to capture all the tweets from a very small rural community (that does not generate many tweets overall) in a given period of time. Providing keywords might very well filter out most of the few tweets.
Is there a way to use filterStream() to capture all tweets from a geocoded area, regardless of the tweets content ? In other words, is it possible to use filterStream without providing a specific string or string vector containing keywords to track ? I couldn't find anything about generic queries in the help files or the twitter API doc.
 Thank you

A: Yes, you can leave the "track" argument empty and just add the coordinates that define the geographic box around the area you are interested in with the "locations" argument.
For example:
filterStream("tweetsUS.json", locations = c(-125, 25, -66, 50),
   timeout = 300, oauth = my_oauth)

captures tweets sent from the US. To know more about how this works, you can check the documentation for this parameter here.


text:
Q: Having trouble building custom web scraper I'm trying to build a custom web scraper using request, cheerio and async on node.js.
I can't figure out why I get some undefined values inside the companies argument causing the waterfall to crash.
I know it's a little bit messy code but it's mostly readable. I think my problem might came from the callback calls.
async.waterfall([
  function(callback){
    var base_url = 'http://www.architonic.com/fr/pmfairexh/imm-cologne/8550409/';
    _.times(3, function(n){
      var url = base_url+(n+1);
      request(url, function (error, response, html) {
        if (error)
          callback(url);
        if (!error && response.statusCode == 200) {
          var $ = cheerio.load(html);
          var links_companies = $('#sheet_content_inside > ul > li > div h2 > a'),
              //links_companies = $('a', li_companies),
              companies = [];

          //console.log(colors.blue(url), links_companies.length);
          links_companies.each(function(i, a) {
            companies.push({name: $(this).attr('title'), url_from: url, next_url: $(this).attr('href')});
          });
          callback(null, companies);
        }
      });
    });
  },
  function(companies, callback){
    async.map(companies, function(c, cb){
      var url = c.next_url;
      if(!_.isUndefined(url))
      request(url, function (error, response, html) {
        console.log(url, c.name);
        if (error)
          cb(url);
        if (!error && response.statusCode == 200) {
          var $ = cheerio.load(html),
              profile_link = $('#head_main_content > div > div:nth-child(4) > h6 > a'),
              cons = (typeof profile_link == 'undefined')?  "WHAT?" : profile_link.attr('href');
              //console.log("url founded: "+cons);
              // if(typeof profile_link == 'undefined')
              //   cb(c);
              c.origin_url = c.url_from;
              c.next_url = profile_link.attr('href');
              c.url_from = url;
              c.profile_url = c.next_url;
              //console.log(c);
              // if (!_.isUndefined(c.next_url))
                cb(null, c);
              // else
              //   cb(c);
              //return _.extend({}, c, {profile_url: profile_link.attr('href'), origin_url: c.url_from});
        }
      });
    }, function(err, _companies){
      callback(null, _companies);
    });
  },
  function(companies, callback){
    async.map(companies, function(c, cb){
      var url = c.next_url;
      console.log(colors.green(url), colors.red(c.name));
      // if (_.isUndefined(url))
      //   return cb(c);
      if(!_.isUndefined(url))
        request(url, function (error, response, html) {
          //console.log(url, c.name);
          if (error)
            cb(url);
          if (!error && response.statusCode == 200) {
            var $ = cheerio.load(html),
                left_zone = $('#sheet_content_inside > div.margin_top_20 > div.left'),
                right_zone = $('#sheet_content_inside > div.margin_top_20 > div.right.width_195');
            //console.log(left_zone.html(), right_zone.html());
            var name = $('span[itemprop="name"]', left_zone).text(),
                s_address = $('span[itemprop="streetAddress"]', left_zone).text(),
                p_code = $('span[itemprop="postalCode"]', left_zone).text(),
                city = $('span[itemprop="addressLocality"]', left_zone).text(),
                country = $('span[itemprop="addressCountry"]', left_zone).text();

            console.log(name, s_address, p_code, city, country);
            cb(null, c);
          }
        });
    }, function(err, _companies){
      callback(null, _companies);
    });
  }
  ], function(err, companies){
    console.log(colors.warn("end"), companies.length);
    console.log(err);
    console.log(companies);
});

A: Until you find the real culprit you can cleanse the companies array  Before passing it over to next function or before every async.map. Like this;
companies = _.compact(companies)

This will make sure list is clean of nulls and undefines


text:
Q: Git Pull Request - Csproj - Duplicate package reference entries I am getting into a weird situation, every time I do a nuget package update for a specific package and then create a pull request for it.
The update of the package works fine, no problem there, but when I do the pull request, the package reference in the .csproj file gets duplicated, as in:
<PackageReference Include="[package_name]" Version="[old_version]" />
<PackageReference Include="[package_name]" Version="[new_version]" />
Did anyone encounter this issue? What would the reason and the solution? Thanks.


text:
Q: How to avoid appending -Djboss.node.name value to JSESSIONID We migrated our application from JBoss 5.1.0 GA to WildFly 8.2.0. I observed that the value of "-Djboss.node.name"(node1) is appending to the JSESSIONID cookie which is causing major problem in my application.
In my application we have a SessionListener class in which we are storing the sessionids to a static map and while doing any operations we are validating the session id from the map and loading the appropriate data.
Please find the below code.
In web.xml
<listener>
  <listener-class>com.project.session.ProjectSessionListener</listener-class>
</listener>

and the code in ProjectSessionListener is
public class ProjectSessionListener extends SeamListener {
private static final Map<String, HttpSession> sessionMap = new HashMap<String, HttpSession>();
...............................
@Override
public void sessionCreated(final HttpSessionEvent event) {
super.sessionCreated(event);
final HttpSession session = event.getSession();
final String sessionId = session.getId();
sessionMap.put(sessionId, session);
 }
}

While adding the sessionid to sessionMap there is no .node1 appended to the session(ABCD1234), so the sessionid was saved without .node1 in the Map, but the login page was loaded successfully.
When we click on Log-in I observed that .node1 was appended to the JSESSIONID9(ABCD1234.node1) and while validating we are trying to get the session date using without .node1 which is obviously return null and causing the exception.
I tried
1)  removing the  -Djboss.node.name from WildFly confuguration, in this case it is appending my pc name(ABCD1234.sreenath-WIN-7).

2) Removing <cache name="distributable" passivation-store-ref="infinispan" aliases="passivating clustered"/> from standalone .xml

Is there any way to avoid appending the extra characters to JSESSIONID on WildFly?

A: You should never under any circumstances rely upon the value returned by javax.servlet.HttpSession.getId(). The servlet specification makes no promises regarding it's value, other than uniqueness. It's value can and occasionally will change during the life of the session. This is particularly true in a clustered environment.
If you need a key for session association then you should create your own (java.util.UUID.randomUUID()) and store it as a session attribute.


text:
Q: How to calculate Parkinson's Historical Volatility I want to calculate volatility of stock prices.
I found information here, but I'm not sure if I'm doing right.
These are sample data:
Date,High,Low
2001-11-15,137.0,134.0
2001-11-16,140.0,133.0
2001-11-19,140.0,137.0
2001-11-20,140.0,136.0

And I calculate in condition n=3.
daily valiation of 2001-11-15 is:
(1 / (4 * ln(2))) * ln(137/134)^2
+ (1 / (4 * ln(2))) * ln(140/133)^2
+ (1 / (4 * ln(2))) * ln(140/137)^2

and valiation of 2001-11-16 is:
(1 / (4 * ln(2))) * ln(140/133)^2
+ (1 / (4 * ln(2))) * ln(140/137)^2
+ (1 / (4 * ln(2))) * ln(140/136)^2

Is this calculation right?
If wrong, where can I find example of calculation of volatility with some data?
What I could find were all only formulars without numbers.

A: I believe it is partially correct. The summation term is missing $\frac{1}{n}$ and I assume you left out the square root intentionally. Also, I believe since it is historical volatility, you should be using dates going backward and not forward.
ivolatility.com also describes classic historical volatility using the same summation range as Parkinson's volatility. This other site also describes the two historical volatility metrics using the same summation range. So both the classic estimator and the Parkinson estimator have their summation over the same period of time. They just sum over (very) different terms.
Classic historical volatility is carefully described here and here. They both use historical dates and not dates going forward. So the Parkinson volatility should be
$$
ParkinsonVolatility_{2001-11-19} = \sqrt{\frac{\frac{1}{4 * ln(2)} * (ln\frac{140}{137})^2 + \frac{1}{4 * ln(2)} * (ln\frac{140}{133})^2 + \frac{1}{4 * ln(2)} * (ln\frac{137}{134})^2}{3}}
$$


text:
Q: LinqPad Syntax for adding foreign key constraint This is the SQL I used in LinqPad:
CREATE TABLE Category
(
    catID int NOT NULL,
    catName NVARCHAR(150) NOT NULL,
    catDesc NVARCHAR(150) NULL,
    catCount int NOT NULL ,
    CONSTRAINT category_pk PRIMARY KEY (catID)
);

CREATE TABLE InventoryTBLC
(
    itemID int NOT NULL IDENTITY(1,1) CONSTRAINT PK_items PRIMARY KEY,
    itemName NVARCHAR(150) NOT NULL,
    itemDesc NVARCHAR(150) NULL,
    itemQuantity int,
    itemPrice int,
    imagePath NVARCHAR(300),
    correctInsert NVARCHAR(300),
    realImage image,

    CONSTRAINT FK_category FOREIGN KEY (catID) REFERENCES Category(catID)
);

But I get the following error:

Invalid column ID. [ catID ]

Can someone help me with the LinqPad syntax?

A: If you want to use a column as the foreign key, you have to list that column in your table definition first! Adding the foreign key constraint does NOT add that column to your table!
And this is in no way Linqpad specific - this is standard SQL behavior.
So either you need to add catId to your second table like this:
CREATE TABLE InventoryTBLC
(
    itemID int NOT NULL IDENTITY(1,1) CONSTRAINT PK_items PRIMARY KEY,
    itemName NVARCHAR(150) NOT NULL,
    itemDesc NVARCHAR(150) NULL,
    itemQuantity int,
    itemPrice int,
    imagePath NVARCHAR(300),
    correctInsert NVARCHAR(300),
    realImage image,
    catID int NOT NULL,   -- this column *MUST* exist to be used as FK

    CONSTRAINT FK_category
        FOREIGN KEY (catID) REFERENCES Category(catID)
);

or then maybe you want to use one of the other pre-existing columns in InventoryTBLC as your FK column?


text:
Q: Navigation to a route within Nuxt.js Universal app, causes errors. Using Contentful headless cms I am currently trying to generate the routes and this is returning with just the home at the moment.
When I go to website.com/work/_slug = Failed to execute 'appendChild' on 'Node'
Here is my generate routes code, I am using contentful

generate: {
      routes: async function () {
        const entries = await client.getEntries({ content_type: "Project" });
        const routes = []
        entries.items.forEach(item => {
          routes.push(`/work/${item.fields.slug}`)
        })
        return routes
      }
    },


text:
Q: Xcode make imprinted UITextField that expands automatically I want to let a user add a title to a book cover. I want the textfield (not the text) look embossed which would be quite simple using a appropriate image behind the textfield. BUT I want to textfield to expand when the user types more than one line.
Can you add an embossed effect (that is inner shadow to one half and outer glow to the other have) to a ui textfield programmatically?
Do you need to use an image that resizes? How would that work?

A: UItextField is specifically one-line only. Use UItextView for multiline, and you can change its height depending on text...


text:
Q: MongoDB $in - only one value and no others Wasn't really sure how to title this question, but hope the explanation is clearer
I have a document like
{
_id: "User1",
skills: [
          {
           ty: "coding",
           inf: "c"
          },
          {
           ty: "design",
           inf: "photoshop",
          },
          {
           ty: "language",
           inf: "french",
          },
          {
           ty: "language",
           inf: "german",
          },
        ]
},
{
_id: "User2",
skills: [
          {
           ty: "coding",
           inf: "c"
          },
          {
           ty: "coding",
           inf: "scala",
          },
          {
           ty: "spreadsheet",
           inf: "excel",
          },
          {
           ty: "language",
           inf: "english",
          },
        ]
}

And so on, my problem is to select users with only "coding" skills.
Here is what I tried
db.collection.find({"skills.ty":{$nin:["language","design","spreadsheet"]}})

The problem here is that there is no fixed set of skills. Right now its only (language,design,coding,spreadsheet), but there maybe more in the future.
How do I write a query to get users with only one type of skill, irrespective of how many others there are? i.e. get people who have only coding skills, but no other
An extrapolation, how to find people with "coding" skills in "c" and "c++" but no others?
i.e. get people who have coding skills in c and c++ and no other coding skills, these users may have other skills like design
Do I need to write functions for these or is there a query I can write?

A: What's wrong with  db.collection.find({"skills.ty":"coding"}) ?


text:
Q: How to obtain width and height of image after rotating it? How can I get the width and height of the image after rotating it using imagerotate() in PHP?
Here is my code:
<?php
// File and rotation
$filename = 'test.jpg';
$degrees = 180;

// Content type
header('Content-type: image/jpeg');

// Load
$source = imagecreatefromjpeg($filename);

// Rotate
$rotate = imagerotate($source, $degrees, 0);

// Output
imagejpeg($rotate);

// Free the memory
imagedestroy($source);
imagedestroy($rotate);
?>

But what I want to do before doing the output, is that I want to get the width and height of the rotated image. How can I do that?

A: I'm sure you can do something similar to this:
$data = getimagesize($filename);
$width = $data[0];
$height = $data[1];

Another option is this:
list($width, $height) = getimagesize($filename);

A: imagerotate returns an image ressource. Hence you cannot use getimagesize which works with an image file.
Use
$width = imagesx($rotate);
$height = imagesy($rotate);

instead.


text:
Q: how can i get array item on laravel? i have 3 item arrray that's look like this

i want to get my data as 3 item array, here is my controller
 public function editView($crewprogrammemoid){
    $getplacement =  PlacementMemo::where('crewprogrammemo_id', $crewprogrammemoid)->get();
    dd(collect($getplacement);
 }

when i'm using this $getplacement =  PlacementMemo::where('crewprogrammemo_id', $crewprogrammemoid)->first(); i got the exact array, but just one, how can i get the 3 array or 3 collection item?? how do i solve that?
Edit
what i want is array like this, and bellow that,

this is when i use $getplacement =  PlacementMemo::where('crewprogrammemo_id', $crewprogrammemoid)->first();, it just 1 array, i would like to have all array but when i use get the looks like in image 1

A: this is the last item in the array.
$getplacement =  PlacementMemo::where('crewprogrammemo_id', $crewprogrammemoid)->get()->last();

this is all 3 items in array.
$getplacement =  PlacementMemo::where('crewprogrammemo_id', $crewprogrammemoid)->get();


text:
Q: How to add options to bloomberg bdh query using api in python I have the following excel-formula:
=@BDH("TSLA US Equity";"IVOL_Delta";start_date;end_date;IVOL_MATURITY=Maturity_90D;IVOL_DELTA_LEVEL=DELTA_LVL_25;IVOL_DELTA_PUT_OR_CALL=IVOL_CALL;days=a;Sort=D;cols=2;rows=1826).
Where the security is TSLA US Equity, the field is IVOL_Delta, start date and end dates speaks for itself, and the options is the remaining.
It works just fine in Excel.
I would like to use the API for python instead, but I don't know how to translate the options to a feasible input, I have tried both as dictionary and as list (could have messed something up though).
I tried the following code without luck (it works if the if I delete the dict and "options=opt" lines):
import pandas
from blp import blp

bquery = blp.BlpQuery().start()

opt = {"IVOL_DELTA_LEVEL":"DELTA_LVL_25"}

bquery.bdh(
    ["TSLA US Equity"],
    ["PX_LAST","IVOL_Delta","VOLUME_TOTAL_CALL"],#,"OPT_DELTA_MID_RT"
    start_date="20210801",
    end_date="20210819",
    options = opt,
)

Thanks in advance!

A: The output in Excel of this formula:
=BDH("TSLA US Equity","PX_LAST,IVOL_Delta,VOLUME_TOTAL_CALL",D2,D3,"IVOL_MATURITY","Maturity_90D","IVOL_DELTA_LEVEL","DELTA_LVL_25","IVOL_DELTA_PUT_OR_CALL","IVOL_CALL")
is:

You can get the same data using the xbbg package. There are plenty of wrappers for Bloomberg in Python, but this one is my personal favourite (pip install xbbg)
from xbbg import blp
from datetime import datetime

df = blp.bdh('TSLA US Equity',['PX_LAST','IVOL_Delta','VOLUME_TOTAL_CALL'],datetime(2021,8,1),datetime(2021,8,19),
                 IVOL_DELTA_LEVEL='DELTA_LVL_25',
                 IVOL_MATURITY='MATURITY_90D',
                 IVOL_DELTA_PUT_OR_CALL='IVOL_CALL')

print(df)

Output:
           TSLA US Equity
                  PX_LAST IVOL_Delta VOLUME_TOTAL_CALL
2021-08-02       709.6700    50.4803         1049494.0
2021-08-03       709.7400    50.3468          678750.0
2021-08-04       710.9200    50.0790          661374.0
2021-08-05       714.6300    49.7532          551532.0
2021-08-06       699.1000    47.7234          918211.0
2021-08-09       713.7600    47.6382          469777.0
2021-08-10       709.9900    46.8017          448640.0
2021-08-11       707.8200    46.3517          431084.0
2021-08-12       722.2500    46.7595          882608.0
2021-08-13       717.1700    47.3414         1028457.0
2021-08-16       686.1700    48.3680          639570.0
2021-08-17       665.7100    50.4111          716804.0
2021-08-18       688.9900    49.4700          732574.0
2021-08-19       680.7001        NaN               NaN

Which matches Excel (save for the live price on today's date).
EDIT: Adding support for Days and Sort
It is helpful to know that there is not a 1-1 mapping between the options on the Excel BDH call and the underlying Bloomberg API. This document describes the mapping:
https://data.bloomberglp.com/professional/sites/10/2017/03/BLPAPI-Core-Developer-Guide.pdf Page 92.
So the BDH Days=A converts to Days='ALL_CALENDAR_DAYS'. But I would suggest that if you don't want weekends, using Days='NON_TRADING_WEEKDAYS'
As for Sort, the document says this:  "Some parameters in the BDH() function, such as "Sort", are unavailable in the API schema, as they are unique to the Bloomberg Excel add-ins". ie the Excel addin does the sorting, not the underlying API. Fortunately it is simple to just reverse the received DataFrame if you want to.
Amended code:
df = blp.bdh('TSLA US Equity',['PX_LAST','IVOL_Delta','VOLUME_TOTAL_CALL'],datetime(2021,8,1),datetime(2021,8,19),
                 IVOL_DELTA_LEVEL='DELTA_LVL_25',
                 IVOL_MATURITY='MATURITY_90D',
                 IVOL_DELTA_PUT_OR_CALL='IVOL_CALL',
                 Days = 'NON_TRADING_WEEKDAYS').iloc[::-1]

With result:
           TSLA US Equity
                  PX_LAST IVOL_Delta VOLUME_TOTAL_CALL
2021-08-19         673.47    50.1950          461203.0
2021-08-18         688.99    49.4700          732574.0
2021-08-17         665.71    50.4111          716804.0
2021-08-16         686.17    48.3680          639570.0
2021-08-13         717.17    47.3414         1028457.0
2021-08-12         722.25    46.7595          882608.0
2021-08-11         707.82    46.3517          431084.0
2021-08-10         709.99    46.8017          448640.0
2021-08-09         713.76    47.6382          469777.0
2021-08-06         699.10    47.7234          918211.0
2021-08-05         714.63    49.7532          551532.0
2021-08-04         710.92    50.0790          661374.0
2021-08-03         709.74    50.3468          678750.0
2021-08-02         709.67    50.4803         1049494.0


text:
Q: Logo as home link So, I'll try to keep this short. I am making a navigation and I want my logo to act as the homepage link. Like this:

However, I'm having trouble with it. Any help would be appreciated!
Code at codepen:
`http://codepen.io/aaronmtx/pen/NRYqOm`

A: Is the codepen for an example or is that the site you are talking about that should be working?
To make a logo a homepage link you just put an href around the image and set the path to "/".
Example:

In your codepen, the # sign in the links is a standard kind of "change me later with the right path" symbol that just links to the top of the current page. You need to change all of those to be a path. / is your root or home page. Anything after that will navigate to other pages.
So you will end up with / for the home page, /services or /services.html etc. depending on your folder and file names.

Services

Portfolio

Contact

This would make the image a link and upon click it would navigate to the root. Obviously replace your image with the correct logo path.
If that doesn't help, can you clarify by adding your code with file names and folder structure?
Hope this helps!


text:
Q: What pattern to employ for locking SQL Server record while editing its data I'm having trouble developing the right strategy for opening connections, beginning transactions, and committing/rolling back/closing connections. The context is an ASP.NET WebForms application. A client can bring up a record to make edits, and I'd like other clients to be locked out of updating that record during the edit operation.
Other clients should be able to read the last committed version of that record. The approach I'm using right now for an edit operation is to open a connection and begin a transaction at IsolationLevel.RepeatableRead, which is doing what I want in terms of locking.
However, I'm not immediately closing the connection...instead, I keep the connection and transaction open while the client is actively editing the values in the record so that I hold the lock. Once the edits are done and the client either commits or rolls back the changes, then I close the connection.
Here's the bones of the class that represents a record in the database:
public class DBRecord : IDisposable
{
    private OleDbTransaction tran; // holds the open transaction
    private Dictionary<string, object> values = new Dictionary<string, object>();
    private bool disposedValue = false;

    public DBRecord (bool forUpdate) {
        OleDbConnection conn = new OleDbConnection(<connection string>);

        try {
            conn.Open();
            tran = conn.BeginTransaction (forUpdate ? IsolationLevel.RepeatableRead : IsolationLevel.ReadCommitted);
            OleDbCommand comm = new OleDbCommand("SET XACT_ABORT ON", conn, tran);
            comm.ExecuteNonQuery();
            comm = new OleDbCommand("SELECT * FROM " + DBTable + " WHERE KEY = ?", conn, tran);
            comm.Parameters.Add(new OleDbParameter("@Key", Key));

            using (OleDbDataReader rdr = comm.ExecuteReader())
            {
                while (rdr.Read())
                {
                    for (int i = 0; i < rdr.FieldCount; i++)
                    {
                        mvoValues.Add(rdr.GetName(i), rdr.GetValue(i));
                    }
                }
            }
        } catch {
            conn.Close();
            throw;
        }

        if (!forUpdate) {
            // don't need to keep the record locked
            tran.Commit();
            conn.Close();
        }
    }

    public UpdateField(string field, object newValue) {
        // this is only called if the object was instantiated with forUpdate true
        OleDbCommand comm = new OleDbCommand("UPDATE " + DBTable + " SET " + field + " = ? WHERE " + KeyField + " = ?", tran.Connection, tran);
        comm.Parameters.Add(new OleDbParameter("@Value", newValue));
        comm.Parameters.Add(new OleDbParameter("@Key", Key));

        try {
            oCommand.ExecuteNonQuery();
        } catch {
            OleDbConnection conn = tran.Connection;
            tran.Rollback();
            conn.Close();
        }
    }

    public void Commit()
    {
        OleDbConnection conn = tran.Connection;
        tran.Commit();
        conn.Close();
    }

    public void Rollback()
    {
        OleDbConnection conn = tran.Connection;
        tran.Rollback();
        conn.Close();
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                if ((tran != null) && (tran.Connection != null))
                {
                    try
                    {
                        OleDbConnection conn = tran.Connection;
                        /// release rowlocks we acquired at instantiation
                        tran.Rollback();
                        conn.Close();
                    }
                    catch (Exception)
                    {
                        // since  we're disposing of the object at this point, there's not much
                        // we can do about a rollback failure, so silently ignore exceptions
                    }
                }
            }

            disposedValue = true;
        }
    }
}

The database has "Allow Snapshot Isolation" and "Is Read Committed Snapshot On" set to true, and the connection string specifies MARS Enabled is true.
It's pretty clear to me that this isn't the right approach:

*

*It goes against everything I've read about connections--open as late as possible and close as quickly as possible.  However, I don't know of another way to keep the record locked from updates while a client is making edits.

*The bigger problem I'm having is when I terminate the browser while in the middle of an edit. Right now I'm in development, so I'm using VS 2015 and IIS Express. When I close the browser, the IIS Express process closes also. It appears that my Dispose() is never being called, because the processes remain open in my SQL Server Express instance. Clearly I need to somehow guarantee that the connections will close regardless of whether the server stops.
In a previous question related to databases I received a suggestion to cache a copy of the record data in local storage, track updates on that, then execute a new transaction when ready to commit the changes. That would definitely make my connections shorter and the update operation more atomic, but the record would not be locked. The solution there might be to create a "I'm being updated" field that a client could test-and-set at the beginning of an edit operation, but that seems like a hack, especially given that the database engine provides mechanisms for locking.
Intuitively what I'm trying to do here seems like a common enough use case that there should be a pattern already, but I'm apparently not asking Google the right questions because all I'm getting in my searches is how to employ a using block. Can anyone point me to the right way to do this? Thanks.

A: The correct pattern name is pessimistic offline locking for what you're looking for, https://dzone.com/articles/practical-php-patterns/practical-php-patterns-13 , which is what you were referring to about having a column with "I'm being updated".
You can review other solutions for locking,  https://petermeinl.wordpress.com/2011/03/14/db-concurrency-control-patterns-for-applications/ .
It's generally recommended that you use optimistic locking instead of pessimistic locking for multiple reasons. It does not require you to update the row prior to editing, it does not require you to leave a connection open like some of the pessimistic locking solutions, and it does not require implementing lock timeouts. It does however have the side effect that it's possible when the user goes to save their changes that they will be prompted if they want to overwrite or merge with changes that have happened since they began their edit.
These are not really the same as the locking built into SQL Server, although some of SQL Server's features can be used to help implement them.


text:
Q: Fourier analysis on linear spaces and general smooth manifolds Problem: Suppose we want to perform Fourier transform on a smooth function that is defined on an $m$-dimensional smooth submanifold of $\mathbb{R}^n$ ($1 \le m \le n-1$) i.e., we wish to obtain $\mathcal{F}f$ for $f: M \rightarrow \mathbb{C}$, where $dim(M) = m$. I have only learned about Fourier analysis for functions defined on $\mathbb{R}^n$ and not on manifolds. How do we define the Fourier transform here? By using coordinate functions $\{\phi_i\}$ and computing $\mathcal{F} \phi_i f \phi_i^{-1}$? Can we do this for functions defined on a hyperplane in $\mathbb{R}^n$? What about general manifolds?
This question is related to a previous question of mine: A property of the x-ray transform (see the answer to the question)
Any help is appreciated!


text:
Q: Getting steps from healthkit which was written by other applications Let's say we have some steps data in healthkit which was auto detected by iphone and written to healthkit. And we have some steps data was enetred by user manually. Now I can differentiate between these steps using this code
let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) // The type of data we are requesting

    let date = NSDate()
    let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let newDate = cal.startOfDayForDate(date)
    print(newDate)
    let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None) // Our search predicate which will fetch all steps taken today

    let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) { query, results, error in
        var steps: Double = 0

        //if result.metadata!["HKWasUserEntered"]! == 1{
        if results?.count > 0
        {
            for result in results as! [HKQuantitySample]
            {
                print("Steps \(result.quantity.doubleValueForUnit(HKUnit.countUnit()))")
                print()
                // checking and truncating manually added steps
                if result.metadata != nil {

                }
                else{
                    steps += result.quantity.doubleValueForUnit(HKUnit.countUnit())
                }

            }
            print(steps)
        }

        completion(steps, error)
        //}
    }

    executeQuery(query)

But Lets say if some other app writes some some step's data to healthkit like some fitness app.

Now I am able to read steps with device icon(auto recorded), but
 How can I read steps with UP icon as well ?
(UP) is and fitness application by JawBone.


text:
Q: JSON.parse and JSON.stringify are not idempotent and that is bad This question is multipart-
(1a) JSON is fundamental to JavaScript, so why is there no JSON type? A JSON type would be a string that is formatted as JSON. It would be marked as parsed/stringified until the data was altered. As soon as the data was altered it would not be marked as JSON and would need to be re-parsed/re-stringified.
(1b) In some software systems, isn't it possible to (accidentally) attempt to send a plain JS object over the network instead of a serialized JS object? Why not make an attempt to avoid that?
(1c) Why can't we call JSON.parse on a straight up JavaScript object without stringifying it first?
    var json = {   //JS object in properJSON format
        "baz":{
            "1":1,
            "2":true,
            "3":{}
        }
    };

    var json0 = JSON.parse(json); //will throw a parse error...bad...it should not throw an error if json var is actually proper JSON.

So we have no choice but to do this:
 var json0= JSON.parse(JSON.stringify(json));

However, there are some inconsistencies, for example:
JSON.parse(true); //works
JSON.parse(null); //works
JSON.parse({}); //throws error

(2) If we keep calling JSON.parse on the same object, eventually it will throw an error. For example:
var json = {   //same object as above
    "baz":{
        "1":1,
        "2":true,
        "3":{}
    }
};

var json1 = JSON.parse(JSON.stringify(json));
var json2 = JSON.parse(json1); //throws an error...why

(3) Why does JSON.stringify infinitely add more and more slashes to the input? It is not only hard to read the result for debugging, but it actually puts you in dangerous state because one JSON.parse call won't give you back a plain JS object, you have to call JSON.parse several times to get back the plain JS object. This is bad and means it is quite dangerous to call JSON.stringify more than once on a given JS object.
   var json = {
        "baz":{
            "1":1,
            "2":true,
            "3":{}
        }
    };

    var json2 = JSON.stringify(json);
    console.log(json2);

    var json3 = JSON.stringify(json2);
    console.log(json3);

    var json4 = JSON.stringify(json3);
    console.log(json4);

    var json5 = JSON.stringify(json4);
    console.log(json5);

(4) What is the name for a function that we should be able to call over and over  without changing the result (IMO how JSON.parse and JSON.stringify should behave)? The best term for this seems to be "idempotent" as you can see in the comments.
(5) Considering JSON is a serialization format that can be used for networked objects, it seems totally insane that you can't call JSON.parse or JSON.stringify twice or even once in some cases without incurring some problems. Why is this the case?
If you are someone who is inventing the next serialization format for Java, JavaScript or whatever language, please consider this problem.
IMO there should be two states for a given object. A serialized state and a deserialized state. In software languages with stronger type systems, this isn't usually a problem. But with JSON in JavaScript, if call JSON.parse twice on the same object, we run into fatal exceptions. Likewise, if we call JSON.stringify twice on the same object, we can get into an unrecoverable state. Like I said there should be two states and two states only, plain JS object and serialized JS object.

A: 1) JSON.parse expects a string, you are feeding it a Javascript object.
2) Similar issue to the first one. You feed a string to a function that needs an object.
3) Stringfy actually expects a string, but you are feeding it a String object. Therefore, it applies the same measures to escape the quotes and slashes as it would for the first string. So that the language can understand the quotes, other special characters inside the string.
4) You can write your own function for this.
5) Because you are trying to do a conversion that is illegal. This is related to the first and second question. As long as the correct object types are fed, you can call it as many times as you want. The only problem is the extra slashes but it is in fact the standard.

A:
We'll start with this nightmare of your creation: string input and integer output.
IJSON.parse(IJSON.stringify("5")); //=> 5
The built-in JSON functions would not fail us this way: string input and string output.
JSON.parse(JSON.stringify("5")); //=> "5"
JSON must preserve your original data types

Think of JSON.stringify as a function that wraps your data up in a box, and JSON.parse as the function that takes it out of a box.
Consider the following:
var a = JSON.stringify;
var b = JSON.parse;

var data = "whatever";

b(a(data)) === data; // true

b(b(a(a(data)))) === data; // true

b(b(b(a(a(a(data)))))) === data; // true

That is, if we put the data in 3 boxes, we have to take it out of 3 boxes. Right?
If I put my data in 2 boxes and take it out of 1, I'm not holding my data yet, I'm holding a box that contains my data. Right?
b(a(a(data))) === data; // false

Seems sane to me...

*

*JSON.parse unboxes your data. If it is not boxed, it cannot unbox it. JSON.parse expects a string input and you're giving it a JavaScript object literal

*The first valid call to JSON.parse would return an object. Calling JSON.parse again on this object output would result in the same failure as #1

*repeated calls to JSON.stringify will "box" our data multiple times. So of course you have to use repeated calls to JSON.parse then to get your data out of each "box"

*Idempotence

*No, this is perfectly sane. You can't triple-stamp a double-stamp.
You'd never make a mistake like this, would you?
var json = IJSON.stringify("hi");
IJSON.parse(json);
//=> "hi"

OK, that's idempotent, but what about
var json = IJSON.stringify("5");
IJSON.parse(json);
//=> 5

UH OH! We gave it a string each time, but the second example returns an integer. The input data type has been lost!
Would the JSON functions have failed us here?
var json = JSON.stringify("hi");
JSON.parse(json);
//=> "hi"

All good. And what about the "5" ?
var json = JSON.stringify("5");
JSON.parse(json));
//=> "5"

Yay, the types have been preseved! JSON works, IJSON does not.

Maybe a more real-life example:
OK, so you have a busy app with a lot of developers working on it. It makes
reckless assumptions about the types of your underlying data. Let's say it's a chat app that makes several transformations on messages as they move from point to point.
Along the way you'll have:

*

*IJSON.stringify

*data moves across a network

*IJSON.parse

*Another IJSON.parse because who cares? It's idempotent, right?

*String.prototype.toUpperCase — because this is a formatting choice

Let's see the messages
bob: 'hi'
// 1) '"hi"', 2) <network>, 3) "hi", 4) "hi", 5) "HI"

Bob's message looks fine. Let's see Alice's.
alice: '5'
// 1) '5'
// 2) <network>
// 3) 5
// 4) 5
// 5) Uncaught TypeError: message.toUpperCase is not a function

Oh no! The server just crashed. You'll notice it's not even the repeated calling of IJSON.parse that failed here. It would've failed even if you called it once.
Seems like you were doomed from the start... Damned reckless devs and their careless data handling!
It would fail if Alice used any input that happened to also be valid JSON
alice: '{"lol":"pwnd"}'
// 1) '{"lol":"pwnd"}'
// 2) <network>
// 3) {lol:"pwnd"}
// 4) {lol:"pwnd"}
// 5) Uncaught TypeError: message.toUpperCase is not a function

OK, unfair example maybe, right? You're thinking, "I'm not that reckless, I
wouldn't call IJSON.stringify or IJSON.parse on user input like that!"
It doesn't matter. You've fundamentally broken JSON because the original
types can no longer be extracted.
If I box up a string using IJSON, and then unbox it, who knows what I will get back? Certainly not you, and certainly not the developer using your reckless function.

*

*"Will I get a string type back?"

*"Will I get an integer?"

*"Maybe I'll get an object?"

*"Maybe I will get cake. I hope it's cake"

It's impossible to tell!
You're in a whole new world of pain because you've been careless with your data types from the start. Your types are important so start handling them with care.

JSON.stringify expects an object type and JSON.parse expects a string type.

Now do you see the light?

A: I'll try to give you one reason why JSON.parse cannot be called multiple time on the same data without us having a problem.
you might not know it but a JSON document does not have to be an object.
this is a valid JSON document:
"some text"

lets store the representation of this document inside a javascript variable:
var JSONDocumentAsString = '"some text"';

and work on it:
var JSONdocument = JSON.parse(JSONDocumentAsString);
JSONdocument === 'some text';

this will cause an error because this string is not the representation of a JSON document
JSON.parse(JSONdocument);
// SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

in this case how could have JSON.parse guessed that JSONdocument (being a string) was a JSON document and that it should have returned it untouched ?


text:
Q: How to write typescript executable file? Using babel-cli you could easily write some node-executable using es2015 syntax. For that you just need to add proper shebang #!/usr/bin/env babel-node.
For example,
#!/usr/bin/env babel-node

import fs from 'fs';

fs.readFileSync('./some-file.csv');

I am wondering how to do that using TypeScript?
UPDATE: Tried ts-node - getting awkward errors even for HelloWorld examples like
const say = (word: string) => {
    console.log(word);
}

say('hello');

it does not work via ts-node test.ts or using #!/usr/bin/env ts-node;
In both cases i'm getting
SyntaxError: Unexpected token :
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at Object.<anonymous> (/usr/local/lib/node_modules/ts-node/src/bin/ts-node.ts:110:12)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)

UPDATE Made ts-node work. It works only if file has .ts extension. For files without extension but with shebang - it does not work. Created github issue for the project that reflects needed behavior.

A: I believe you are looking for ts-node.
#!/usr/bin/env ts-node

...rest of script

Author confirms this usage working here:
https://github.com/TypeStrong/ts-node/issues/73
p.s. I'd call that an executable, not a binary.

A: Just to note things have moved on since the approach tried by @ValeriiVasin and the one recommended in @Paarth's answer.
Support for shebangs was officially added in ts-node v8.9.0. The recommended shebang string now includes the -script suffix:
#!/usr/bin/env ts-node-script

Scripts using fs.readFileSync("somefile.json") are working for me with this shebang.


text:
Q: Returning length of an array's element Hi I was wondering if it was possible for get the length of the elements of an array? I checked out the java docs and the only length I saw that was retrievable was the length of the array itself. My assignment is to use the lengths of the elements to randomize the colors of my bricks. If someone can point in the right direction of getting the lengths of getting the elements length that would be greatly appreciated. Here is my code:
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

@SuppressWarnings("serial")
public class legos2v2 extends JFrame {
private int startX;
private int startY;
private int legoWidth;
private int legoHeight;
private int baseLength;
private int arcWidth;
private int arcHeight;
private Color[] colors;

// Constructor
public legos2v2() {
    super("Jimmy's LEGOs");
    startX = 20;
    startY = 300;
    legoWidth = 50;
    legoHeight = 20;
    baseLength = 10;
    arcWidth = 2;
    arcHeight = 2;

    // Declare and Array of Colors
    Color[] colors = {Color.red, Color.blue, Color.yellow, Color.green,
            Color.pink, Color.black, Color.magenta, Color.orange,
            Color.cyan};

    // Get length of color
    System.out.println("Array Length = " + colors.length + "\n");

}
// The drawings in the graphics context
public void paintComponent(Graphics g) {

    // Call the paint method of the JFrame
    super.paint(g);

    int currentX = startX;
    int currentY = startY;

    Random random = new Random();

    // row = 0 is the bottom row
    for (int row = 1; row <= baseLength; row++) {
        currentX = startX;

        for (int col = 0; col <= baseLength - row; col++) {

            g.fillRoundRect(currentX, currentY, legoWidth, legoHeight, arcWidth, arcHeight);

            // Generate random integer from 0 to 8
            int randomIndex = random.nextInt(colors.length);

            g.setColor(this.colors[randomIndex]);
            //Error here   this.colors = colors[randomIndex];

            // Print random integers to screen
            System.out.println(randomIndex);

            currentX = currentX + legoWidth;
        }
        currentY -= legoHeight;
        startX += legoWidth / 2;
    }
}
// The main method
public static void main(String[] args) {
    legos2v2 app = new legos2v2();
    // Set the size and the visibility
    app.setSize(550, 325);
    app.setVisible(true);
    // Exit on close is clicked
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

A: What the teacher asks you to do is what I said in the comments:

*

*Initialize an array of colors:
Color[] colors = ...;

*Generate a random int between 0 (included) and the length of the array (excluded:
int randomIndex = random.nextInt(colors.length);

This returns an integer which is a valid index for the array of colors.

*pick the color at the random index:
 Color color = colors[randomIndex];

This avoids the need for the ugly chain of if blocks to generate a random color.
EDIT:

*

*replace Color[] colors = by this.colors = to initialize the instance variable instead of redefining a local variable with the same name

*As you were told to do in the other comments, move Random random = new Random(); before the first for loop

*As you were told to do in the other comments, override paintComponent() instead of overriding paint().


text:
Q: Don't know if this is a Complete Binary Tree? Okay I know what a complete binary tree means. It means, "All levels are completely filled except possibly the last level and the last level has all nodes as left as possible."
In an exam paper answers, it is saying this tree below isn't a complete binary tree.
   5
 /    \
3      6
     /
     5

Why isn't this a complete binary tree? The last level has a node that's on the far left as possible.


text:
Q: How to return an observable from a http service in angular2 Unfortunately as I was storing many results on the service, I'm now stuck with many {{myservice.somevalue}} (and myservice.someother) etc. sprinkled over my other components.
I believe it would be nicer to return from the service to a component.
This is the code that I have on the service:
getIssue(issueName: string) {
    return this.http.post(this.URL + 'issue/all', JSON.stringify({'issueName': issueName}))
                    .subscribe(data => this.somevalue = data.json(),
                                err => console.log(err));
}

So then on several other components I call functions like this.myservice.getIssue(issueName).
In the HTML I'd prefer to use {{somevalue}}.
What can I do to return a http observable from the http service?

A: class SomeService {
  someValue = new BehaviorSubject();

  getIssue(issueName: string) {
      return this.http.post(this.URL + 'issue/all', JSON.stringify({'issueName': issueName}))
                      .subscribe(data => this.somevalue.next(data.json()),
                                  err => console.log(err));
  }
}

In your component
class MyComponent {
  constructor(someService:SomeService) {
    someService.someValue.subscribe(val => {
      this.someValue = val;
    });
  }
}

For an alternative approach see also https://stackoverflow.com/a/36291681/217408


text:
Q: "unsigned char*" в managed byte array в ImageCopy.data лежат данные картинки.
IntPtr ptr(imageCopy.data);
int ss = strlen((char*)imageCopy.data);
Byte bytes[] = new Byte[ss];
System::Runtime::InteropServices::Marshal::Copy(ptr, bytes, 0, ss);

Выдает ошибки

*

*Error (active)   E0520   initialization with '{...}' expected for aggregate object

*Error    C2440   'initializing': cannot convert from 'unsigned char *' to 'unsigned char []

*Error    C2665   'System::Runtime::InteropServices::Marshal::Copy': none of the 16 overloads could convert all the argument types

A: Нужно поправить код... много поправок 1.IntPtr нужно кастить void*  2. Marshal::Copy - не ест обычные массивы, оно хочет array CLI-шный т.е. cli::array. Т.е. где-то так
int dataSize= strlen((char*)imageCopy.data)+1; /*Если ASCII-Z то +1 обязательно*/
array<byte>^ _Data=gcnew array<byte>(dataSize);
System::Runtime::InteropServices::Marshal::Copy(
   IntPtr( ( void * ) imageCopy.data),
  _Data,
  0,
  dataSize );

Источник https://stackoverflow.com/questions/6403005/copy-unmanaged-data-into-managed-array
P.S. strlen - делать картинке.... нельзя. Потому что это до первого нуля... что в результате будет..... обрезаные байты.  Такой метод можно применять к строкам, и то нужно писать int dataSize= strlen((char*)imageCopy.data)+1; потому что нужно учесть ноль в конце ASCII-z. dataSize для картинок определяется другими способами, и это можно обсудить в отдельном вопросе. Тут чисто как сделать Marshal::Copy. Для работы с строками хочу обратить внимание на метод Marshal::PtrToStringAnsi и Marshal::PtrToStringBSTR, что б не вышло много лишних преобразований.
Если не компилируется - подключить #include "stdafx.h" либу


text:
Q: @GeneratedValue Annotation, Constructor value I can not seem to find any documentaion on how to use the GeneratedValue annotation when it comes to initialising my object.
here is my id field for my object class, I have two other fields which I have left out
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@NotNull
@Column(name = "ID")
private BigDecimal id;

my constructors
public Pothole() {
}

public Pothole(BigDecimal id) {
    this.id = id;
}

public Pothole(BigDecimal id, byte[] image, Date pdate) {
    this.id = id;
    this.image = image;
    this.pdate = pdate;
}

What do I use for my id field?? Do I leave it empty
Pothole entity = new Pothole(???,decodedBytes, date);

A: Yes, you should leave it empty and when Hibernate will persist the entity in the database (ie, perform an insert statement), the id of the given entity will be valued by the database (in your case, the id column will provide the value).
The ìd` attribute will remain empty until the entity is persisted.

A: using the default constructor worked
 Pothole entity = new Pothole();
    entity.setImage(decodedBytes);
    entity.setPdate(date);


text:
Q: HIVE: how to insert data into column with datatype MAP (string:Array) I have a table CLASS1 as shown mentioned below
 hive> select * from class1;
 OK
 NULL   student_name    NULL    NULL    NULL
 5  david   60  70  80
 5  reena   55  40  80
 7  joseph  66  75  89
 Time taken: 0.659 seconds, Fetched: 4 row(s)
 hive> desc class1;
 OK
 class                  tinyint
 student_name           varchar(30)
 marks_english          int
 marks_maths            int
 marks_science          int
 Time taken: 0.553 seconds, Fetched: 5 row(s)

Now i wanted to insert this data in below format into a new table
    Class     name_marks
    5   {david:[60,70,80]}
    5   {reena:[55,40,80]}
    7   {joseph:[66,75,89]}

Can someone tell me how to create a new table and insert the data in the desired format?

A: Try this query:
create table new_table as
select class
     , MAP(student_name, ARRAY(marks_english, marks_maths, marks_science) as name_marks
  from old_table;


text:
Q: how to add tooltip on the entries and NOT on the combo in JFace ComboViewer I am loading my ComboViewer with over one thousand elements.
Some elements are longer than the width of underlying combo.
I want to add tooltip on the entries and NOT on the combo.
I want it in such a way that, when the list drops down and the user places the mouse pointer over one of the value, the entire text should be displayable via tooltip similar to the tooltip shown for a JFace TableViewer.

A: If you are using a ComboViewer and you provide your own CCombo instance, you can get children of the CCombo and one of them should be a List control that it shows as a dropdown menu. You can add your MouseTrackListener to this List control and show tooltip depending on which item the mouse is hovering.


text:
Q: Apache 2.4 + PHP-FPM + ProxyPassMatch I recently installed Apache 2.4 on my local machine, together with PHP 5.4.8 using PHP-FPM.
Everything went quite smoothly (after a while...) but there is still a strange error:
I configured Apache for PHP-FPM like this:
<VirtualHost *:80>
    ServerName localhost
    DocumentRoot "/Users/apfelbox/WebServer"
    ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/Users/apfelbox/WebServer/$1
</VirtualHost>

It works, for example if I call http://localhost/info.php I get the correct phpinfo() (it is just a test file).
If I call a directory however, I get a 404 with body File not found. and in the error log:
[Tue Nov 20 21:27:25.191625 2012] [proxy_fcgi:error] [pid 28997] [client ::1:57204] AH01071: Got error 'Primary script unknown\n'

Update
I now tried doing the proxying with mod_rewrite:
<VirtualHost *:80>
    ServerName localhost
    DocumentRoot "/Users/apfelbox/WebServer"

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/Users/apfelbox/WebServer/$1 [L,P]
</VirtualHost>

But the problem is: it is always redirecting, because on http://localhost/ automatically http://localhost/index.php is requested, because of
DirectoryIndex index.php index.html

Update 2
Ok, so I think "maybe check whether there is a file to give to the proxy first:
<VirtualHost *:80>
    ServerName localhost
    DocumentRoot "/Users/apfelbox/WebServer"

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/Users/apfelbox/WebServer/$1 [L,P]
</VirtualHost>

Now the complete rewriting does not work anymore...
Update 3
Now I have this solution:
<VirtualHost *:80>
    ServerName localhost
    DocumentRoot "/Users/apfelbox/WebServer"

    RewriteEngine on
    RewriteCond /Users/apfelbox/WebServer/%{REQUEST_FILENAME} -f
    RewriteRule ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/Users/apfelbox/WebServer/$1 [L,P]
</VirtualHost>

First check, that there is a file to pass to PHP-FPM (with the full and absolute path) and then do the rewriting.
This does not work when using URL rewriting inside a subdirectory, also it fails for URLs like http://localhost/index.php/test/
So back to square one.

Any ideas?

A: After hours of searching and reading Apache documentation I've come up with a solution that allows to use the pool, and also allow the Rewrite directive in .htaccess to work even when the url contains .php files.
<VirtualHost ...>

 ...

 # This is to forward all PHP to php-fpm.
 <FilesMatch \.php$>
   SetHandler "proxy:unix:/path/to/socket.sock|fcgi://unique-domain-name-string/"
 </FilesMatch>

 # Set some proxy properties (the string "unique-domain-name-string" should match
 # the one set in the FilesMatch directive.
 <Proxy fcgi://unique-domain-name-string>
   ProxySet connectiontimeout=5 timeout=240
 </Proxy>

 # If the php file doesn't exist, disable the proxy handler.
 # This will allow .htaccess rewrite rules to work and
 # the client will see the default 404 page of Apache
 RewriteCond %{REQUEST_FILENAME} \.php$
 RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_URI} !-f
 RewriteRule (.*) - [H=text/html]

</VirtualHost>

As per Apache documentation, the SetHandler proxy parameter requires Apache HTTP Server 2.4.10.
I hope that this solution will help you too.

A: All you need to do is to set:
 ProxyErrorOverride on

And do not forget to set the customer page by:
ErrorDocument 404 /path/to/error_page_file

A: Yet another solution (requires Apache >= 2.4.10) - Inside the vhost:
# define worker
<Proxy "unix:/var/run/php5-fpm-wp.bbox.nuxwin.com.sock|fcgi://domain.tld" retry=0>
    ProxySet connectiontimeout=5 timeout=7200
</Proxy>

<If "%{REQUEST_FILENAME} =~ /\.php$/ && -f %{REQUEST_FILENAME}">
    SetEnvIfNoCase ^Authorization$ "(.+)" HTTP_AUTHORIZATION=$1
    SetHandler proxy:fcgi://domain.tld
</If>

So here, the fcgi handler for PHP will be set only if the file exists and if its name matches with PHP file extension.
BTW: For those which would have idea to set the ProxyErrorOverride to On, be aware that this is really a bad idea. Usage of this directive is not without causing any issue. For instance, any PHP application sending HTTP code such as 503 would lead to unexpected result. Default error handler would be involved in any cases and for PHP applications that provide API, that is really a bad behavior.

A: This is what I've got. It seems to work OK. I put Drupal in a subdirectory and its rewrites work, directory indexes work, and PATH_INFO works.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} ^/((.*\.php)(/.*)?)$
RewriteCond %2 -f
RewriteRule . fcgi://127.0.0.1:9000/%1 [L,P]
RewriteOptions Inherit

I've tried to do something like this without rewrites ("If" and such), but I couldn't get anything to work.
EDIT: Note that if you were to implement this as a shared hosting provider, this could be a security issue. It would allow users to pass PHP scripts to an arbitrary fcgi proxy. If you had a seperate pool for every user, that would allow for elevation of privilege attacks.

A: I ran into this problem yesterday as well – Apache 2.4 moved out of Debian/experimental into Debian/unstable forcing me to deal with this new stuff; not on our production servers of course ;).
After reading what feels like millions of sites, Apache docs, bug reports and debugging output in the error log I finally got it to work. No, there's no support for FPM with sockets, yet. The default Debian config has been using sockets for some time now, so Debian users will have to change that too.
Here's what works for a CakePHP site and PHPMyAdmin (the latter needs some config if you're using the Debian packages though), so I can confirm that mod_rewrite still works as expected to do fancy URL rewriting.
Notice DirectoryIndex index.php, which might be the reason none of your configs worked for "folders" (at least that's what didn't work here).
I still get File not found. for directories, but only if there's no index file it can parse. Would love to get rid of that too, but it's not that critical as for now.

<VirtualHost *:80>
    ServerName site.localhost

    DocumentRoot /your/site/webroot
    <Directory />
            Options FollowSymlinks
            DirectoryIndex index.php
            AllowOverride All
            Require all granted
    </Directory>

    <LocationMatch "^(.*\.php)$">
            ProxyPass fcgi://127.0.0.1:9000/your/site/webroot
    </LocationMatch>

    LogLevel debug
    ErrorLog /your/site/logs/error.log
    CustomLog /your/site/logs/access.log combined
</VirtualHost>

The above vhost works perfectly well with an .htaccess in the root like this:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

I don't quite get what you mean by URL rewriting inside a subdirectory though (I'm only rewriting to the root's index.php).

(Oh, and you'll have to make sure Xdebug doesn't conflict with FPM on your system, out of the box they want to use the same ports.)

A: Best way to solve this is to turn on debugging logs for mod_proxy and mod_rewrite and php-fpm. In apache 2.4 you can now turn on debugging logs for specific modules only.
http://httpd.apache.org/docs/current/mod/core.html#loglevel
Per-module and per-directory configuration is available in Apache HTTP Server 2.3.6 and later
Maybe you're getting a double slash on directories?
Here's what I use and it works fine:
<LocationMatch ^(.*\.php)$>
  ProxyPass fcgi://127.0.0.1:9000/home/DOMAINUSER/public_html$1
</LocationMatch>

A: One thing I came across in my dealing with this issue, is that if you use the combination of:
chroot = /path/to/site
chdir = /

In your fpm pool configuration, don't pass the full path to the ProxyPass directive.
ProxyPass fcgi://127.0.0.1:9020/$1

But -ONLY- if the pool on that port is chrooted.

A: I'm not sure if the problem is related, but i've found a partialy working solution here:
https://stackoverflow.com/questions/44054617/mod-rewrite-in-2-4-25-triggering-fcgi-primary-script-unknown-error-in-php-fpm
The trick seems to be adding a ? char in the .htaccess RewriteRule, eg using:
RewriteRule ^(.*)$ index.php?/$1 [L,NS]

instead of:
RewriteRule ^(.*)$ index.php/$1 [L,NS]

The source of the problem seems to be a change in mod_rewrite of Apache 2.4.25. I've used Apache trace1 log level to observe a "loop" that pass $1 to php-fpm after index.php/$1 has been passed. The $1 generate the "AH01071: Got error 'Primary script unknown\n'" error.
Hope this little tidbit help someone to solve their problems.

A: A slightly modified version of @FrancescoA's answer that does not require mod_rewrite
<IfModule proxy_fcgi_module>
    <FilesMatch \.php$>
       <If "-f '%{REQUEST_FILENAME}'">
           SetHandler "proxy:unix:/path/to/socket.sock|fcgi://unique-domain-name-string/"
       </If>
     </FilesMatch>

     <Proxy fcgi://unique-domain-name-string>
        ProxySet connectiontimeout=5 timeout=240
     </Proxy>
</IfModule>

A: Linode has a great tutorial on this subject
Basically you setup a handler for the entire server that will catch any php scripts and pass them to fast-cgi.

A: i have the error also after switch to php-fpm + apache 2.4.6 for drupal instances
but I am using mpm event mod
just insert
DirectoryIndex index.php works for me
then my Vhost settings looks like below
<VirtualHost *:8080>
  ServerAdmin webmaster@localhost
  ServerName sever.com
  DocumentRoot /var/www/html/webroot
    ErrorLog logs/web-error_log
    CustomLog logs/web-access_log common
<IfModule mpm_event_module>
    ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/var/www/html/webroot/$1
</IfModule>
  <Directory /var/www/html/webroot>
     Options FollowSymlinks
     DirectoryIndex index.php
     AllowOverride All
     Require all granted
  </Directory>
</VirtualHost>

thanks
no need to revise drupal's default .htaccess file

A: I face the same problems on my server(centos 7.3.16 docker). After tracking the php-fpm log ,I found miss a sys lib.
 WARNING: [pool www] child 15081 said into stderr: "php-fpm: pool www: symbol lookup error: /lib64/libnsssysinit.so: undefined symbol: PR_GetEnvSecure"

then,I restall the nspr,it works.If you cannot find the solutions after trying any methods,you may try this.

yum -y install/reinstall nspr

A: This works with Wordpress 5.1.1 and newer together with PHP 7.3, FastCGI , proxy, also MariaDB/MySQL. Checked twice on my servers. Works like a charm.
First on CentOS/Fedora/Red Hat
sudo yum remove php*
sudo yum --enablerepo=extras install epel-release
sudo yum install php-fpm php-mysql php-gd php-imap php-mbstring
sudo grep -E '(proxy.so|fcgi)' /etc/httpd/conf.modules.d/00-proxy.conf
sudo mv /etc/httpd/conf.d/php.conf /etc/httpd/conf.d/php.conf_bak

Edit this file:
sudo nano /etc/php-fpm.d/www.conf

Paste this:
[www]

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses on a
;                            specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 127.0.0.1:9000
listen = /run/php-fcgi.sock

sudo ll /run/php-fcgi.sock

Should give srw-rw-rw-.
Or how to set up on Debian/Ubuntu
Tutorial:
source: https://emi.is/?page=articles&article=php-7-installation-and-configuration-for-apache-2.4-using-php-fpm-(debian,-repository)

sudo apt purge 'php*' or sudo apt-get purge 'php*'
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt install php7.3 php7.3-fpm php-mysql php-mbstring php-gd php-imap libapache2-mod-security2 modsecurity-crs
systemctl status php7.3-fpm
systemctl stop php7.3-fpm.service

sudo a2dismod php7.0 php7.1 php7.2 mpm_event mpm_worker
sudo a2enmod mpm_prefork
sudo a2enmod php7.3
sudo systemctl restart apache2 (httpd in CentOS)

The problem is that php 7.3 from Ondrej repo works only with mpm_prefork mode. He has git repo, so you can find him in net and ask him, will he make php 7.3 for mpm_worker and mpm_event.
The rest of configuration for Debian family distros is below:

sudo apt --assume-yes install php7.3-fpm
sudo systemctl stop php7.3-fpm.service
sudo rm /var/log/php7.0-fpm.log
sudo mkdir /var/log/php7.3-fpm/
sudo touch /var/log/php7.3-fpm/error.log
sudo mkdir /var/log/php7.3/
sudo touch /var/log/php7.3/error.log
sudo mkdir /var/tmp/php7.3/
sudo > /etc/php/7.3/fpm/php.ini
sudo > /etc/php/7.3/fpm/php-fpm.conf
sudo rm /etc/php/7.3/fpm/pool.d/www.conf
sudo touch /etc/php/7.3/fpm/pool.d/example.com.conf
sudo useradd --comment "PHP" --shell "/usr/sbin/nologin" --system --user-group php

sudo nano /etc/php/7.3/fpm/php.ini

paste

[PHP]
date.timezone = Europe/Prague
display_errors = Off
error_log = /var/log/php7.3/error.log
error_reporting = 32767
log_errors = On
register_argc_argv = Off
session.gc_probability = 0
short_open_tag = Off
upload_tmp_dir = /var/tmp/php7.3/

sudo nano /etc/php/7.3/fpm/php-fpm.conf

paste

[global]
error_log = /var/log/php7.3-fpm/error.log
include = /etc/php/7.3/fpm/pool.d/*.conf

sudo nano /etc/php/7.3/fpm/pool.d/example.com.conf

paste

[example.com]
group = php
listen = 127.0.0.1:9000
pm = ondemand
pm.max_children = 5
pm.max_requests = 200
pm.process_idle_timeout = 10s
user = php

sudo nano /etc/logrotate.d/php7.3-fpm

copy this to txt file:
/var/log/php7.3-fpm.log {
    rotate 12
    weekly
    missingok
    notifempty
    compress
    delaycompress
    postrotate
            /usr/lib/php/php7.3-fpm-reopenlogs
    endscript
}

remove it and then paste this instead of above:
/var/log/php7.3/*.log /var/log/php7.3-fpm/*.log
{
copytruncate
maxage 365
missingok
monthly
notifempty
rotate 12
}

Add directive
sudo nano /etc/apache2/sites-available/example.com.conf

<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias example.com
    ServerAdmin admin@example.com
    DocumentRoot /var/www/html/example.com/public_html
    DirectoryIndex index.php index.htm index.html index.xht index.xhtml
    LogLevel info warn
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    <FilesMatch "^\.ht">
    Require all denied
    </FilesMatch>

    <files readme.html>
    order allow,deny
    deny from all
    </files>

    RewriteEngine on
    RewriteCond %{SERVER_NAME} =example.com
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
    ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/var/www/html/example.com/public_html

    <Directory /var/www/html/example.com/public_html>
        Options Indexes FollowSymLinks Includes IncludesNOEXEC SymLinksIfOwnerMatch
        AllowOverride None
    </Directory>
</VirtualHost>

Then enable site:
sudo a2ensite /etc/apache2/sites-available/example.com.conf

Next edit SSL site (In this case certbot from Let's Encrypt has been installed and configured previously at the beginning of the SSL cert configuration).
sudo nano /etc/apache2/sites-available/example.com-le-ssl.conf

<IfModule mod_ssl.c>
    #headers for security man in the middle attack find how to enable this mod in Google
    LoadModule headers_module modules/mod_headers.so
    <VirtualHost *:443>
        Header always set Strict-Transport-Security "max-age=15768000"
        SSLEngine On
        ServerName example.com
        ServerAdmin admin@example.com
        DocumentRoot /var/www/html/example.com/public_html
        <Directory /var/www/html/example.com/public_html>
        Options Indexes FollowSymLinks Includes IncludesNOEXEC SymLinksIfOwnerMatch
        AllowOverride All
        Require all granted
        DirectoryIndex index.php
        RewriteEngine On
         <FilesMatch ^/(.*\.php(/.*)?)$>
           SetHandler "fcgi://example.com:9000/var/www/html/example.com/public_html"
          </FilesMatch>
        </Directory>
    # Log file locations
    #LogLevel info ssl:warn
    LogLevel debug
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # modern configuration
    SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf
    SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
    #SSLCipherSuite HIGH:!aNULL:!MD5
    SSLCipherSuite ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM$
    SSLHonorCipherOrder on
    SSLCompression off
    SSLSessionTickets off

    <FilesMatch "^\.ht">
    Require all denied
    </FilesMatch>

    <files readme.html>
       order allow,deny
       deny from all
    </files>

</VirtualHost>
    #Stapling OCSP for Let's Encrypt certs.
    SSLUseStapling          on
    SSLStaplingResponderTimeout     5
    SSLStaplingReturnResponderErrors        off
    SSLStaplingCache        shmcb:/var/run/ocsp(128000)
</IfModule>

sudo a2enmod proxy proxy_fcgi setenvif
sudo systemctl reload apache2.service
sudo chown --recursive root:adm /etc/php/
sudo chmod --recursive 0770 /etc/php/
sudo chown --recursive php:adm /var/log/php7.3/
sudo chown --recursive php:adm /var/log/php7.3-fpm/
sudo chmod --recursive 0770 /var/log/php7.3/
sudo chmod --recursive 0770 /var/log/php7.3-fpm/
sudo chown --recursive php:php /var/tmp/php7.3/
sudo chmod --recursive 0770 /var/tmp/php7.3/
sudo a2enconf php7.3-fpm
sudo systemctl enable php7.3-fpm.service
sudo systemctl start php7.3-fpm.service

Remember to add a port 9000 to a firewall on Debian/Ubuntu
sudo ufw allow 9000/tcp
sudo ufw status

On CentoOS / Fedora/ Red Hat
sudo firewall-cmd --zone=public --add-port=9000/tcp --permanent
sudo firewall-cmd --reload
sudo firewall-cmd --list-all
sudo firewall-cmd --state


text:
Q: Spritekit - SKSpriteNode video plays sometimes and not others using AVPlayer I have random videos playing in my app. They are of mp4 format. Using code below I select a random number which decides which video to play. It seems to play a lot of the time but other times just the sound plays with no video. I tested z value issues and it still does this even when there is no background or anything. Any help would be greatly appreciated, I tried compiling in many iOS versions including 9.2, issues still persist.  The not playing video and only sound is random and no patterns to them(sometimes quickly happens other times 40 plays or more), sound is embedded in the video.
-(SKVideoNode*)prepareHiVideo:(SKVideoNode*)videoNode withFileURL:
(NSURL*)fileURL
{
//AVPlayer
AVPlayer * avPlayer = [AVPlayer playerWithURL:fileURL];
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(hiFinishedPlaying:)
name:AVPlayerItemDidPlayToEndTimeNotification object:[avPlayer
currentItem]];

//SKVideo Node
videoNode = [SKVideoNode videoNodeWithAVPlayer:avPlayer];
videoNode.zPosition=4;
[videoNode setScale:.338];
return videoNode;
}
-(void)animatedHis {
SKVideoNode * node;
name.text = @"";
NSURL *fileURL;
AVPlayer * hiPlayer = [[AVPlayer alloc]init];
randomNumber = arc4random_uniform(9);
while (randomNumber==previousRandom)
{
randomNumber = arc4random_uniform(9);
}
if(randomNumber==0)
{

fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"GrizzlyBearHi" ofType:@"mp4"]];
node=[self prepareHiVideo:node withFileURL:fileURL];
node.name=@"Grizzly Bear Hi";
node.position=CGPointMake(self.frame.size.width/5.6, self.frame.size.height/1.17);
name=[SKLabelNode labelNodeWithFontNamed:@"Helvetica-Bold"];
name.zPosition=10;
name.fontColor = [UIColor whiteColor];
name.text=@"Grizzly Bear";
name.position=CGPointMake(self.frame.size.width/5.6, self.frame.size.height/1.35);

}

First of the 9 random numbers code above, I have all 9 numbers and
ifs in code.

After ifs:
node.zPosition=10;
name.fontSize = 18;
[self addChild:name];
[self addChild:node];
[node play];
previousRandom=randomNumber;

Cleanup code after video completes:
-(void)hiFinishedPlaying:(NSNotification *)notification
{
SKNode * node;

node = [self childNodeWithName:@"Grizzly Bear Hi" ];
if(node)
[node removeFromParent];

node = [self childNodeWithName:@"Beaver Hi" ];
if(node)
 [node removeFromParent];

 node = [self childNodeWithName:@"Goat Hi" ];
 if(node)
 [node3 removeFromParent];

node = [self childNodeWithName:@"Mountain Lion Hi" ];
 if(node)
 [node removeFromParent];

node = [self childNodeWithName:@"Bald Eagle Hi" ];
 if(node)
 [node removeFromParent];

node = [self childNodeWithName:@"Squirrel Hi" ];
 if(node)
 [node removeFromParent];

node = [self childNodeWithName:@"Wolf Hi" ];
if(node)
 [node removeFromParent];

node= [self childNodeWithName:@"Coyote Hi"];
if(node)
 [node removeFromParent];

node= [self childNodeWithName:@"Rabbit Hi"];
(if(node)
 [node removeFromParent];

A: My best guess is this might be causing you issues...
 node = [self childNodeWithName:@"Goat Hi" ];
 if(node)
 [node3 removeFromParent];

it could be that "Goat Hi" is still there on screen and on top of your newly created video node. Making it look like it isn't playing but you would still get sounds.
 node = [self childNodeWithName:@"Goat Hi" ];
 if(node)
 [node removeFromParent];

Should fix the problem if that is the case. Hopefully that helps.


text:
Q: Slash between authors in actual cite command not in italics Using jurabib and the package option authorformat=dynamic led to the effect, that the slash between two authors was not placed in italics, but upright. The effect can be seen when compiling this MWE:
\documentclass[]{scrartcl}
\usepackage[ngerman]{babel}
\usepackage{color}
\usepackage{filecontents}
\usepackage[authorformat={dynamic}]{jurabib}

\begin{filecontents}{literatur.bib}
@INCOLLECTION{HRG_III_2_Minne_und_Recht,
  author = {Christa Bertelsmeier-Kierst and Albrecht Cordes},
  title = {Minne und Recht},
  booktitle = {Handw\"orterbuch zur Deutschen Rechtsgeschichte},
    pages = {Sp.\,1537\,--\,1541},
  year = {2016},
  editor = {Albrecht Cordes and Hans-Peter Haferkamp and Heiner L\"uck and Dieter Werkm\"uller},
  volume = {III},
  address = {Berlin},
  howcited = {1},
  shorttitle = {Minne und Recht in: HRG~III, 2.\,Auflage},
  volumetitle = {Konfliktbew\"altigung\,--\,Nowgorod}
}
\end{filecontents}
\begin{document}

\textit{Bertelsmeier-Kierst}/\textit{Cordes} $\leftarrow$ Upright

\cite{HRG_III_2_Minne_und_Recht} $\leftarrow$ Cite

\textit{Bertelsmeier-Kierst/Cordes} $\leftarrow$ Italics

\bibliography{literatur}
\bibliographystyle{jurabib}

\end{document}

and it looks like this:

A: If you are adding the line \renewcommand*{\jbbtasep}{/} % bta  = between two authors sep which basically only redefines what is already defined, the result is changing to:


text:
Q: Soundcloud Player Modification I am building a website for a friend and he wants the Soundcloud player embedded with an image above it that changes each time a different song plays. Each track will have its own image that will show as the track is played in the Soundcloud player.
The image that is assigned to each track on Soundcloud does show in the embedded player, but only at a size of 150x150. I would like to disable this image and have a much larger image displayed above the player.
Does anybody know if this is possible and how I would go about doing such a thing. My knowledge of HTML and CSS is strong. However, other languages such as Javascript and PHP are fairly new to me, so please excuse any silly questions.
Thank you in advance!

A: The soundcloud widget has an show_artwork option. You could set this to false to hide the artwork in the player. Then you could retrieve the artwork in a larger format using the api (check for the artwork_url property of the track).


text:
Q: How to Do a http eavesdropper or proxy app on android The use case is that:

*

*all the applications on the android phone would connect to internet through a wifi.

*And I want to have an application that eavesdrops on the http traffic from all apps so that I can find what sites they visit.

*This application would be distributed as an apk and users would install this app on their phone.

How do I achieve this ?
I will tell what I tried:

*

*Used a Custom Vpn Service application where an activity triggers a service derived from VpnService.

*The Custom VpnService calls builder and sets Mtu, addRoute, addAddress, and then addDnsServer.

*Then the service reads from the file descriptor associated with the interface generated from builder's establish() call.

Now if the addRoute is called with ("0.0.0.0", 0), Iam able to intercept the traffic and see packet contents. But Iam not able to route the packets without creating udp tunnel to an external server which I dont want to do.
If the addRoute is called with the Wifi router IP, then routing automatically happens for all packets generated. But I am not able to intercept the packets on the file descriptor associated with the virtual interface. It simply doesnt receive any data on read() call.
What I want to do is:

*

*intercept the traffic to inspect the http headers

*at the same time, do routing as usual like a normal wifi connection does.

*Have everything self contained in the phone. There should be no external server.

*this appliction should not require any rooting or such. It should install the way a normal app does.

A: I would suggest 1) setting a proxy and 2) running an app which acts as one. The combination of these two won't require root privileges.
SETTING THE PROXY
This first point is probably the most tricky one. The only way of setting a software-level proxy (without requiring root) is by navigating to the Wi-Fi connection settings and manually set the proxy. However, there is an open-source application that can eventually bypass this particular step: ProxySettings.
INTERCEPTING THE TRAFFIC
In my opinion, your best bet is using SandroProxy, an open-source proxy application for Android. It is extremely well written, currently maintained and supported, and will allow you to intercept the HTTP traffic and even modify it. The code can be found here, while the example application can be found here.

This solution should fulfil all of your requirements:

*

*Intercept the traffic (even edit it): thanks to the proxy setting, all the network traffic goes through the proxy address, which corresponds to your application

*Edit is optional: everything will keep working as no proxy is set

*Everything is local: no need for external servers, your proxy is the installed application

*No root is required


text:
Q: Как развернуть див частично? я имею

1

2

3

4-1

5-2

6-3

7-4

8-5

9-1

10-2

11-3

12-4

90-5

100

таких много

Мне нужно чтобы изначально при загрузке страницы div id="2" class="slider"
был свернут
и былo показанo только N элементов .wow-ggg  (допустим три), а ниже была кнопочка ПОКАЗАТЬ ЕЩЕ,
И при нажатии показывалось не все сразу остальное а только K элементов .wow-ggg  (допустим пять) и при наличии непоказанных элементов эта кнопочка(ПОКАЗАТЬ ЕЩЕ../..свернуть все ..) оставалась пока все элементы не будут показаны, а в коне только  - ..свернуть все ...
Кнопку показать еще не могу вставить в разметку
Показать ещё
,    я могу это сделать только через .slider:after {
content: "Показать еще";
}
У меня есть такая конструкция https://jsfiddle.net/profy/xwosnjfu/201/ , но это кончено не совсем то что нужно, но которую я через CSS (скрол например) сделаю что-то похожее что мне нужно, ..... может найдется добрая душа для решения вышеописанной задачи, в сложных скриптах я не силен.
Спасибо.

A:
Кнопку показать еще не могу вставить в разметку
Показать ещё
, я могу это сделать только через
.slider:after { content: "Показать еще"; }

Если нет возможности вносить изменения в HTML, то можно же создать новый элемент (кнопку) посредством JavaScript. И фактически она у нас будет в HTML-документе. Пример:

var value = true
var more = document.createElement('button');
var textInBtnMore = document.createTextNode('Показать еще');
more.classList.add("more");
more.appendChild(textInBtnMore);
if (value) {
  document.body.appendChild(more);
}

var data = Array.from(document.querySelectorAll('.wow-ggg')),
  item = 0,
  step = 4;
item += step;
data.slice(step).forEach(e => e.style.display = 'none');
document.querySelector('.more').addEventListener('click', function(e) {
  var tmp = data.slice(item, item + step);
  tmp.forEach(ee => ee.style.display = 'block');
  item += step;
  if (tmp.length < 4)
    this.remove();
});
.slider {display: flex; flex-direction: row; flex-wrap: wrap; height: 24px; padding: 6px 0;}
.wow-ggg {margin: 1px; padding: 3px; background-color: lightgray;}

01

02

03

04

05

06

07

08

09

10

11

12


text:
Q: What modification to my spec file accomplishes the same thing as adding the command line option --onefile when using pyinstaller? I have a simple script, hello_world.py, and want to create a Windows 10 executable with the aid of Pyinstaller. I'm using Python 3.9, on a Mac (11.6.1) with a Windows 10 virtual machine along with the most recent version of Pyinstaller.
Of course, the simplest way to create the .exe as a single file is to type pyinstaller hello_world.py --onefile at the command line. This produces a folder, dist, which contains just the .exe itself.
However, for my more complicated application, I'll need to include many datas and hidden imports, which I do by modifying the spec file produced by typing pyinstaller hello_world and edit accordingly. Here's a simple example of a modified spec file for hello_world.py:
block_cipher = None

data=[('Desktop/my_image.png', '.')]

a = Analysis(['hello_world.py'],
         pathex=[],
         binaries=[],
         datas=[],
         hiddenimports=[networkx],
         hookspath=[],
         hooksconfig={},
         runtime_hooks=[],
         excludes=[],
         win_no_prefer_redirects=False,
         win_private_assemblies=False,
         cipher=block_cipher,
         noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
         cipher=block_cipher)

exe = EXE(pyz,
      a.scripts,
      [],
      exclude_binaries=True,
      name='hello_world',
      debug=False,
      bootloader_ignore_signals=False,
      strip=False,
      upx=True,
      console=True,
      disable_windowed_traceback=False,
      target_arch=None,
      codesign_identity=None,
      entitlements_file=None )
coll = COLLECT(exe,
           a.binaries,
           a.zipfiles,
           a.datas,
           strip=False,
           upx=True,
           upx_exclude=[],
           name='hello_world')

This is the spec file produced by first typing pyinstaller hello_world.py at the command line and then editing the resulting spec file by adding an image to the data and a single hidden import. (I chose networkx, not that it matters.)
Now typing pyinstaller produces a dist folder which contains another folder, hello_world as opposed to a dist folder containing just hello_world.exe. This isn't what I want.
I realize I can include other options at the command line to add data and hidden imports, but my actual application contains so many of these things that it's more efficient to work with the spec file.
So the ultimate question is what modification to my spec file achieves the same outcome as adding the --onefile option at the command line?

A: Thanks to the assistance of E.Fahlgren on the Pyinstaller"s Google Mailing list, I learned that the problem is resolved if one deletes coll and adds exclude_binaries=False to exe.


text:
Q: R: Adress objects deep inside lists with filter commands inside functions/loops (ExtremeBounds package) I am using the ExtremeBounds package which provides as a result a multi level list with (amongst others) dataframes at the lowest level. I run this package over several specifications and I would like to collect some columns of selected dataframes in these results. These should be collected by specification (spec1 and spec2 in the example below) and arranged in a list of dataframes. This list of dataframes can then be used for all kind of things, for example to export the results of different specifications into different Excel Sheets.
Here is some code which creates the problematic object (just run this code blindly, my problem only concerns how to deal with the kind of list it creates: eba_results):
library("ExtremeBounds")
Data <- data.frame(var1=rbinom(30,1,0.2),var2=rbinom(30,2,0.2),
               var3=rnorm(30),var4=rnorm(30),var5=rnorm(30))
spec1 <- list(y=c("var1"),
             freevars=c("var2"),
             doubtvars=c("var3","var4"))
spec2 <- list(y=c("var1"),
          freevars=c("var2"),
          doubtvars=c("var3","var4","var5"))
indicators <- c("spec1","spec2")

ebaFun <- function(x){
eba  <- eba(data=Data, y=x$y,
     free=x$freevars,
     doubtful=x$doubtvars,
     reg.fun=glm, k=1, vif=7, draws=50, weights = "lri", family = binomial(logit))}

eba_results <- lapply(mget(indicators),ebaFun) #eba_results is the object in question

Manually I know how to access each element, for example:
eba_results$spec1$bounds$type #look at str(eba_results) to see the different levels

So "bounds" is a dataframe with identical column names for both spec1 and spec2. I would like to collect the following 5 columns from "bounds":
type, cdf.mu.normal, cdf.above.mu.normal, cdf.mu.generic, cdf.above.mu.generic
into one dataframe per spec. Manually this is simple but ugly:
collectedManually <-list(
manual_spec1 = data.frame(
 type=eba_results$spec1$bounds$type,
 cdf.mu.normal=eba_results$spec1$bounds$cdf.mu.normal,
 cdf.above.mu.normal=eba_results$spec1$bounds$cdf.above.mu.normal,
 cdf.mu.generic=eba_results$spec1$bounds$cdf.mu.generic,
 cdf.above.mu.generic=eba_results$spec1$bounds$cdf.above.mu.generic),
manual_spec2= data.frame(
 type=eba_results$spec2$bounds$type,
 cdf.mu.normal=eba_results$spec2$bounds$cdf.mu.normal,
 cdf.above.mu.normal=eba_results$spec2$bounds$cdf.above.mu.normal,
 cdf.mu.generic=eba_results$spec2$bounds$cdf.mu.generic,
 cdf.above.mu.generic=eba_results$spec2$bounds$cdf.above.mu.generic))

But I have more than 2 specifications and I think this should be possible with lapply functions in a prettier way. Any help would be appreciated!
p.s.: A generic example to which hrbrmstr's answer applies but which turned out to be too simplistic:
exampleList = list(a=list(aa=data.frame(A=rnorm(10),B=rnorm(10)),bb=data.frame(A=rnorm(10),B=rnorm(10))),
               b=list(aa=data.frame(A=rnorm(10),B=rnorm(10)),bb=data.frame(A=rnorm(10),B=rnorm(10))))

and I want to have an object which collects, for example, all the A and B vectors into two data frames (each with its respective A and B) which are then a list of data frames. Manually this would look like:
dfa <- data.frame(A=exampleList$a$aa$A,B=exampleList$a$aa$B)
dfb <- data.frame(A=exampleList$a$aa$A,B=exampleList$a$aa$B)
collectedResults <- list(a=dfa, b=dfb)

A: There's probably a less brute-force way to do this.
If you want lists of individual columns this is one way:
get_col <- function(my_list, col_name) {
  unlist(lapply(my_list, function(x) {
    lapply(x, function(y) { y[, col_name] })
  }), recursive=FALSE)
}

get_col(exampleList, "A")
get_col(exampleList, "B")

If you want a consolidated data.frame of indicator columns this is one way:
collect_indicators <- function(my_list, indicators) {
  lapply(my_list, function(x) {
    do.call(rbind, c(lapply(x, function(y) { y[, indicators] }), make.row.names=FALSE))
  })[[1]]
}

collect_indicators(exampleList, c("A", "B"))

If you just want to bring the individual data.frames up a level to make it easier to iterate over to write to a file:
unlist(exampleList, recursive=FALSE)

Much assumption about the true output format is being made (the question was a bit vague).

A: There is a brute force way which works but is dependent on several named objects:
collectEBA <- function(x){
 df <- paste0("eba_results$",x,"$bounds")
 df <- eval(parse(text=df))[,c("type",
                            "cdf.mu.normal","cdf.above.mu.normal",
                            "cdf.mu.generic","cdf.above.mu.generic")]
 df[is.na(df)] <- "NA"
 df
 }
eba_export <- lapply(indicators,collectEBA)
names(eba_export) <- indicators


text:
Q: self._qs.unescape is not a function when using `gulp` with Twilio Here is global.js:
var accountSid=     "MY_ACCOUNT_SID";
var authToken=      "MY_AUTH_TOKEN";
var twilioClient=   require('twilio')(accountSid, authToken);
twilioClient.messages.list(function(err, data) {
    data.messages.forEach(function(message) {
        console.log(message.body);
        console.log("======");
    });
});

When I open a command line, navigate to the directory of global.js, and run gulp, a web page opens. But when I check the console, I see this error:
Uncaught TypeError: self._qs.unescape is not a function --- request.js:393
What must I fix for the function to loop thru messages on my Twilio account and log them?
Here are the contents of gulpfile.js:
/*
  gulpfile.js
  ===========
  Rather than manage one giant configuration file responsible
  for creating multiple tasks, each task has been broken out into
  its own file in gulp/tasks. Any files in that directory get
  automatically required below.

  To add a new task, simply add a new task file that directory.
  gulp/tasks/default.js specifies the default set of tasks to run
  when you run `gulp`.
*/

var requireDir = require('require-dir');

// Require all tasks in gulp/tasks, including subfolders
requireDir('./gulp/tasks', { recurse: true });

The ./gulp/tasks directory contains these .js files:
browserify.js
default.js
markup.js
publish.js
watchify.js
browserSync.js
dist.js
minifyCss.js
sass.js
watch.js
build.js
images.js
production.js
uglifyJs.js

Contents of ./gulp/tasks/default.js:
var gulp = require('gulp');

gulp.task('default', ['sass', 'images', 'markup', 'watch']);


text:
Q: SNMP protocol insert value or data to PostgreSQL Database Table First of all thank you to reach and read my question.
Level Difficult : Very Hard. :)
In one cabinet have 4 sensors, It is Tel-co Communication Cabinet that placed in higher location such as (hills, mountains and top building) we have 1000 cabinet  placed over my country Malaysia.
The 4 sensor such as :-

*

*Humidity Sensor Inside Cabin

*Humidity Sensor Outside Cabin

*Temperature Inside Cabin

*Temperature Outside Cabin

All 4 sensor required to sending value (every 15 minute) to database server currently I am used PostgreSQL and running OS Windows Server
Our Tel-Co (is our Client) provide a port from Card Controller Device through Lan Cable RJ45 to used SNMP Protocol. I dont need to care about the Card Controller/Electrical Device it is not my development, I only work with them
My objective is What or How to POST or Store the value of sensor to PostgreSQL using SNMP protocol. I already read about SNMP protocol, All explained in theory.
below is a Table Structure that i build in PostgreSQL

*

*dvc_id //device cabinet ID

*humscr_in //Humidity Sensor Inside Cabin

*humscr_out //Humidity Sensor Outside Cabin

*temp_in //Temperature Inside Cabin

*temp_out //Temperature Outside Cabin

*modfdate //DateTimeWithoutTimeZone use to capture interval date every 15 minute
BELOW IS AN OUTPUT, WHEN QUERY VALUE FROM PostgreSQL
10001 23 53 10 36 2017-03-25 15:15:00
10005 23 53 10 36 2017-03-25 15:15:00
10003 23 53 10 36 2017-03-25 15:15:00
10008 23 53 10 36 2017-03-25 15:15:00
10009 23 53 10 36 2017-03-25 15:15:00

I WANT TO KNOW HOW TO PROGRAM OR CONFIGURE OR INSTALL SNMP protocol SO THAT THE SENSOR WILL SEND VALUE AND INSERT INTO PostgreSQL, AS A CLIENT REQUIREMENT MUST USE SNMP PROTOCOL.

Please explain me steps by step because I am PHP Programmer. not all i know. I only web based program. advise me if i should hire someone else to sit down together with me. If im hire someone, what is work of scope or what position or role im required to hire that someone. What to To call? IT engineer? Computer Engineer? or else???


text:
Q: How to call a specific JavaScript function even if they have the same signatures? I have a specific situation. I hope you can help me..
I have two different html pages. I am parsing them and regenerating them as a single html page with Java. Each page contains many JavaScript functions and some of them have exactly the same function signature.
The problem is that I should not make any changes on the function definitions that I am parsing from that two different pages.
So, lets say
Page A has
function showMessage(){
alert("Page A");
}

Page B has
function showMessage(){
alert("Page B");
}

When I parse them, function definitions should stay as they are.
I tried to create namespaces for each page's JavaScript functions in the single HTML page and I tried to use object literals. But I should not make any changes in the function definitions. So, following code does not help me..
var NS1 = {
    showMessage: function() {

        alert("workss");
    }
}

Do you have any idea how i can solve this issue?
Thank you for your help..