text:
Q: How to sum cumulative days an account is active from a table with multiple date ranges per account? I have a transactional table that has account, TN number, provision status, transaction status, and date. An account is considered active if it has at least one TN number that provisioned successfully and no de-provision status.
Each account can be active for a period of time, then de-provision the last active TN and it becomes inactive. But that account can be active again if aTN is provisioned successfully.
I need to sum the cumulative days an account has been active with at least one TN in a provisioned state.
Here is a sample of my transaction table.
ACCOUNT TN_NUMBER   STATUS      TRANSACTION_STATUS  DATE
------- ---------   --------------  ------------------  ----------
1234    8005551212  Provisioned     Success     2019-05-17
1234    8665558989  Provisioned     Success     2019-05-25
1234    8005551212  De-provisioned  Success     2019-05-27
1234    8665558989  De-provisioned  Failed      2019-06-03
1234    8665558989  De-provisioned  Success     2019-06-05
1234    8005551212  Provisioned     Success     2019-06-01
5678    8005557777  Provisioned     Success     2019-01-01
5678    8005557777  De-provisioned  Success     2019-05-01

Account 1234 started 2019-05-17, deprovisioned the last TN on that account on 2019-06-05. (14 days active)
Then that account was active again starting 2019-06-01 and remains active. (61 days active).
Account 5678 was active 4 days.
This needs to be a daily query on 1.7 million accounts.

A: Use a cumulative sum to get the number of provisioned accounts at each point in time.  Then assign a "grouping" by counting the number of unprovisioned accounts less than each row:
select t.*,
       sum(case when num_provisioned <= 0 then 1 else 0 end) over (partition by account order by date) as grouping
from (select t.*,
             sum(case when transaction_status = 'Success' and status = 'Provisioned'
                      then 1
                      when transaction_status = 'Success' and status = 'Provisioned'
                      then 1
                      when transaction_status = 'Success' and status = 'Unprovisioned'
                      then -1
                      else 0
                 end) over (partition by account order by date) as num_provisioned
      from t
     ) t

With this information, it is then a matter of a couple of aggregations and a lead() (to get the next deprovisioning):
with g as (
      select t.*,
             sum(case when num_provisioned <= 0 then 1 else 0 end) over (partition by account order by date) as grouping
      from (select t.*,
                   sum(case when transaction_status = 'Success' and status = 'Provisioned'
                            then 1
                            when transaction_status = 'Success' and status = 'Provisioned'
                            then 1
                            when transaction_status = 'Success' and status = 'Unprovisioned'
                            then -1
                            else 0
                       end) over (partition by account order by date) as num_provisioned
            from t
           ) t
      )
select account,
       sum(datediff(day, min_date, coalesce(max_date, getdate()))) as num_days
from (select account, grouping, max(num_provisioned) as num_provisioned,
             min(date) as min_date, max(date) as max_date,
             lead(min(date)) over (partition by account order by min(date)) as next_min_date
      from g
      group by account, grouping
     ) g
where num_provisioned > 0
group by account;

A: You can use simple aggregation:
select  t1.Account,
        sum(datediff(day,t1.[date],t2.[date])) as NumDays
from #t1 as t1
    inner join #t1 as t2 ON t1.Account = t2.Account and t1.TN_NUMBER = t2.TN_NUMBER
where t1.status = 'Provisioned'
  and t1.TRANSACTION_STATUS = 'Success'
  and t2.status = 'De-provisioned'
  and t2.TRANSACTION_STATUS = 'Success'
  and t1.[Date] <= t2.[Date]
group by t1.Account

A: Can you check your question : 2019-06-05 is after 2019-06-01 so the account 1234 is provisioned without interruption from 2019-05-17 until today, and there is 4 monts (not days) between 2019-01-01 and 2019-05-01.
Here is my script. I think it's quicker if you have a lot of data.
WITH PRO AS (
    SELECT *
    FROM DBO.[TRANSACTION]
    WHERE STATUS = 'Provisioned'
            AND TRANSACTION_STATUS = 'Success' ),
DEPRO AS (
    SELECT *
    FROM DBO.[TRANSACTION]
    WHERE STATUS = 'De-provisioned'
            AND TRANSACTION_STATUS = 'Success' ),
-- Create interval for transactions
INTERVAL AS (
    SELECT T1.ACCOUNT, T1.DATE AS BEGIN_DATE, ISNULL(T2.DATE,CONVERT (DATE, GETDATE())) AS END_DATE
    FROM PRO T1
    LEFT JOIN DEPRO T2
        ON T1.TN_NUMBER = T2.TN_NUMBER
            AND T1.DATE < T2.DATE ) ,
-- Create concatenated intervals
INTERVAL_CONCAT (ACCOUNT, BEGIN_DATE, END_DATE) AS (
    SELECT ACCOUNT,BEGIN_DATE, END_DATE
    FROM INTERVAL
    UNION ALL
    SELECT I1.ACCOUNT, I2.BEGIN_DATE, I1.END_DATE
    FROM INTERVAL I1
    INNER JOIN INTERVAL_CONCAT I2
        ON I1.ACCOUNT = I2.ACCOUNT
            AND I1.BEGIN_DATE < I2.END_DATE
            AND I1.END_DATE > I2.END_DATE ),
-- Remove duplicates
INTERVAL_RN AS (
    SELECT *, RN=ROW_NUMBER()OVER(PARTITION BY ACCOUNT, BEGIN_DATE, END_DATE ORDER BY  ACCOUNT)
    FROM INTERVAL_CONCAT ),
INTERVAL_WO_DUP AS (
    SELECT ACCOUNT, BEGIN_DATE, END_DATE
    FROM INTERVAL_RN
    WHERE RN=1 ),
-- Remove underlying intervals
INTERVAL_CLEANING AS (
    SELECT *
    FROM INTERVAL_WO_DUP
    EXCEPT
    SELECT I2.*
    FROM INTERVAL_WO_DUP I1
    INNER JOIN INTERVAL_WO_DUP I2
        ON I2.BEGIN_DATE < I1.END_DATE
            AND I2.BEGIN_DATE>= I1.BEGIN_DATE
            AND I2.END_DATE <=I1.END_DATE
            AND NOT (I2.BEGIN_DATE = I1.BEGIN_DATE AND I2.END_DATE=I1.END_DATE))

SELECT ACCOUNT, SUM(DATEDIFF(D,BEGIN_DATE,END_DATE)) AS PROVISIONED_DURATION
FROM INTERVAL_CLEANING
GROUP BY  ACCOUNT

ResultSet with your data
ACCOUNT PROVISIONED_DURATION
------- --------------------
1234    95
5678    120


text:
Q: detect if the arrow button from QScrollBar is pressed Is there a signal that I can emit if the arrow button of the QScrollBar is pressed? As far as I know there is only the sliderPressed() signal. I want, if it exists, another solution from valueChanged() signal.

A: I had the same problem and solved it connecting the same callback function to sliderReleased() and valueChanged() and checking in the function if the slider is "down" (meaning pushed) with isSliderDown():
    slider = QtGui.QScrollBar()
    slider.valueChanged.connect(slider_callback)
    slider.sliderReleased.connect(slider_callback)

    def slider_callback():
       if slider.isSliderDown():
          pass
       else:
          print("now i am updating")

A: All signals QScrollBar emits (inherited from QAbstractSlider) related o slider/value changed:
void    actionTriggered ( int action )
void    rangeChanged ( int min, int max )
void    sliderMoved ( int value )
void    sliderPressed ()
void    sliderReleased ()
void    valueChanged ( int value )

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regex permutations with repetition I had to list all possible 4 digit combinations from 3 given digits.
Every digit should be used at least once. If numbers are (1,2,4), the option 1122 is not valid as it does not use number 4.
My ugly piece of code looked like this:
String s="";
for(int i=1000;i<5000;i++){
   s=String.valueOf(i);
   if(s.contains("1")&&s.contains("2")&&s.contains("4")
          &&!s.contains("3")&&!s.contains("5")&&!s.contains("6")&&!s.contains("7")
          &&!s.contains("8")&&!s.contains("9")&&!s.contains("0")){
   System.out.println(s);
   }
}

And it listed 36 combinations, which is correct answer.
Can you please suggest me a regular expression that will work instead of that condition?

A: The possible combinations are:
1241
1242
1244

I simply used 3 of the required digits (1, 2, 4) which leaves us with only one digit to fill. Since we have 3 digits to choose from, there is only three possible combinations.
To get all permutations, shuffle around all the digits in each number and eliminate duplicates. There is plenty of articles about how to get permutations, e.g. Permutation of array. To eliminate duplicates you can use a Java Set.

A: The following regex would test that your numbers are 4 digits long, composed of 1, 2 and 4 with at least one occurrence of each, using lookaheads :
^(?=.*1)(?=.*2)(?=.*4)[124]{4}$

A solution without using lookaheads would be possible but also extremely uninteresting as you would have to list the third of every permutation (you would only gain the opportunity to describe that one specific spot can contain either of the three symbols).
As others said, using this regex with your current code would still be a very inefficient way to generate your desired permutations.


text:
Q: Centering a variable-width grid after resizing the page Here is an image of what I want to do in CSS:
image.
Any ideas?

A: Initial issue
Centering an element that has no explicit width
This prevents the usual solution of margin: 0 auto; from being an option.
Greater issue
There's no unused space for centering the wrapper in its container
An element is said to be shrink-wrapped if its width is determined by the width of its content. If the content changes in size, the width of the element changes likewise. This is the default behavior for elements that are inline, inline-block, or floated.
When content in a shrink-wrapped parent wraps around to the next row, the parent stops being shrink-wrapped; it now occupies the full width of its own container. Technically, the parent is centered, since it completely fills the container, but its content is not centered. And unless the parent has a noticeable bg color or wallpaper image, the parent will appear to not be centered either.
This also applies to some of the more advanced features, like CSS3 flexbox, apparently preventing that from being an option as well.
Solution
Media queries
It turns out there is a simple CSS solution. The basic issue is that a single layout grid of this sort can't support a wide range of screen sizes and still center the content. But with the help of CSS3 media queries, a variety of layout grids can be created, with the appropriate one chosen based on the screen size.
For example, a layout grid with 1 column is created, as well as one with 2 columns, and one with 3 columns, and so forth, for as many columns as may be needed. Whichever grid fits the current screen size, that's the one that's used. The layout grids might be identical except for the fixed width each one is given, a width that's just large enough to fit the number of columns. Since each grid has a fixed width, it becomes trivial to center them horizontally using margin: 0 auto;.
In other words, rather than trying to force a single layout to handle the full range of browser sizes, create many layouts, and choose the one that can easily handle the current browser size.

A: Put all the divs within another div and make the margin auto on both sides.
See this comprehensive example: Problem centering div with css

A: Just give CSS property to wrapper as
#wrapper{
margin: 0px auto;
}

The above code will align center automatically when you resize the browser window. This is the process of adding responsiveness to your page.

A: The div you want to center must have a width and you have to make set the margin auto.
Here is an example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Example</title>

A: Being too lazy to implement Media Queries (and the multiple scenarios to account for), I implemented a simple solution. Put the images in an unordered list (where li {display: inline-block}) and then (text-align: center) the wrapper. Adjust your margins etc. later to make it pretty.


text:
Q: Recycle view OnitemclickListener How I can handle click of item RecycleView?
I found way write in adapter in ViewHolder,
but how I can handle these same click in activity,
 public ViewHolder(View itemView) {
itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d("TAG", "Element " + getPosition() + " clicked.");
                }
            });

And I tried
  AdapterViewCompat.OnItemClickListener clickListener = new AdapterViewCompat.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterViewCompat<?> adapterViewCompat, View view, int i, long l) {
          Toast.makeText(getActivity(), "You click " + i, Toast.LENGTH_LONG);
      }
  };
  recycleView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          Toast.makeText(getActivity(), "You click now", Toast.LENGTH_LONG);
          Log.i("Screen Two ", v.getVerticalScrollbarPosition() + "");
      }
  });
    recycleView.setOnClickListener((View.OnClickListener) clickListener);
  recycleView.setOnLongClickListener(new View.OnLongClickListener() {
      @Override
      public boolean onLongClick(View v) {
          return false;
      }
  });

But they do not work, although in Activity
help me.

A: You have to create a custom listener for your adapter to propagate the click event to your activity. There is no such thing as OnItemClickListener in RecyclerView.


text:
Q: How to store graphics in a separate folder from the web page I have the following file and directory structure:
site\
site\index.html
site\background.jpg
site\CSS\
site\CSS\main.css
site\Graphics\
site\Graphics\background.jpg

*NOTE: background.jpg is on the disk in two places.
The problem is the image does not load from the Graphics folder, only the main (site) folder.
HTML:

                Left Col

                Right Col

    Footer

CSS:
* {
    margin: 0px;
}
.floatClear {
    clear: both;
}

.headerGraphics {
    display: inline;
}

#header {
    background: #023489;
    text-align: center;
}

#logoCompany {
    display: inline;
}
#contentParent {
    height: 2200px;
    width: 100%;
    background-image: url(background.jpg);
 }
#leftPane {
    background: yellow;
    float: left;
    margin: 100px 0 0 10%;
    opacity: .5;
    width:40%;
}
#rightPane {
    background: green;
    float: right;
    margin: 100px 10% 0 0;
    opacity: .5;
    width:40%;
}
#footer {
    width:100%;
}

I've tried:
background-image: url(background.jpg) works.
background-image: url(..\Graphics\background.jpg) does NOT work.
background-image: url(Graphics\background.jpg) does NOT work.

Anyone know how to get this to work?

A: Try this:
background-image: url('../Graphics/background.jpg');

For further reference on relative file paths check out this w3schools page html_filepaths

A: In the path, just include the "\" in front of anything that is inside (or is itself) a subdirectory.
If it's a file in the same folder and you use the "\" it won't work because it has been instructed to check lower (it will look at your file like it's trying to check a subfolder).  If it's supposed to be in the lower folder, just include the "\" before each of the folders (in order, of course) and before the file name.


text:
Q: Nullpointer exception while loading image from url I am developing an application with rest web service. By getting the json response from server, am parsing it and populating it in a custom list view using adapter. In that json response there are url's to download image to display in list items.  Every thing has been done and working fine, except loading image from url there is Nullpointer exception.
I have done debugging also, logcat shows as follows
    java.lang.NullPointerException
    at android.widget.AbsListView.obtainView(AbsListView.java:2269)
    at android.widget.ListView.measureHeightOfChildren(ListView.java:1244)
    at android.widget.ListView.onMeasure(ListView.java:1156)
    at android.view.View.measure(View.java:15172)
    at android.widget.RelativeLayout.measureChild(RelativeLayout.java:602)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:415)
    at android.view.View.measure(View.java:15172)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:15172)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
    at android.view.View.measure(View.java:15172)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2
    at android.view.View.measure(View.java:15172)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1848)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1100)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1273)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:998)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4212)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
    at android.view.Choreographer.doCallbacks(Choreographer.java:555)
    at android.view.Choreographer.doFrame(Choreographer.java:525)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
    at android.os.Handler.handleCallback(Handler.java:615)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4745)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)
    Force finishing activity com.shopping/.views.JsonListView

Can some one help me to find the reason why getting this exception.
Edit:
     int loader = R.drawable.fb_icon;
 // ImageLoader class instance
 ImageLoader imgLoader = new ImageLoader(_Context);

 imgLoader.DisplayImage(imageUrl, loader, holder.productImage);
     public void DisplayImage(String url, int loader, ImageView imageView)
     {
        stub_id = loader;
        imageViews.put(imageView, url);
        Bitmap bitmap=memoryCache.get(url);
        if(bitmap!=null)
           imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(loader);
        }
      }

A: Write below line into your adapter's getview() method.
imageLoader.DisplayImage(url[position], imageview1);

and see below lazy loading link for more information and if you have any query regarding that then tell me.
Lazy Loading Listview


text:
Q: How can I store a selected radio button's text in localStorage? Can anyone help me how to set the radio button selected text in localStorage? Here is my code but I'm getting undefined value at every time:
GENDER:
<input type="radio" id="radiobtn1" name="gender" value="0"/>
MALE
<input type="radio" id="radiobtn1" name="gender" value="1"/>
FEMALE

jQuery code; I'm getting selected value when trying to write the code like this:
var tempgender = $("input:checked + label").text();
console.log("gender selcte value:" + tempgender);

But when trying to save selected value in localstorage by writing this code then getting "undefined value".
window.localStorage.setItem("tempgender",$("input:checked + label").text());`

What am I doing wrong?

A: code is correct but i think localstorage is not supported by your browser , do perform before using localstorage
if(typeof(Storage)!=="undefined")
{
  alert("storage is supported and you can store data in it");
}
else
{
 alert("Get new version of browser or use browser which support storage");
}

for further details you can check : Store data locally with HTML5 Web Storage


text: Q: How to create a save game file editor How do I create a save game file editor? I'd like some help , perhaps even some collaborators would be great. I don't know how to program and am totally new to this. I've opened up my save game file using the Acode editor app and the NMM app. Also opened up a terminal and attempted to open the file in there , but get inacessable or file not found


text:
Q: Powershell using hashtable and foreach loop to set appsettings via appcmd I am trying to modify the web.config of a site by adding several appsetttings. To make this code more reusable and whatnot I would like to use a hashtable to store the key-value pairs and then loop over them. I am getting errors when trying to inject the key and value into the call to appcmd. Here is my code:
$env:myWebsite = "myWebsite"
$appcmd = "C:\windows\system32\inetsrv\appcmd.exe"

$settings = @{
    "test1"="C:\Temp\test";
    "test2"="true";
    "test3"="C:\Temp\"
}

foreach($s in $settings.GetEnumerator()){
    & $appcmd --% set config "%myWebsite%" /section:appSettings /+"[key='$($s.Name)',value='$($s.Value)']"
}

When I try and execute this it is not injecting s.Name and s.Value


text:
Q: Make children stretch to fill their parent but display scrollbar for each child when overflowed I've got a view that has 3 columns that need to span the entire height of the view.
If the contents of each column don't take up the entire height of the view then I'd like there to not be a scrollbar for that column (though I still want a border on the left/right side of the column that spans the entire height of the view).
If the contents of a column do take up the entire height of the view (or overflow the view) then I'd like a scrollbar for each column that is overflowing its height.
So say if each column doesn't have many items, then there'd be no scrollbars. If column 2 is the only column with a lot of content then there might be only one scrollbar for the middle column. If all 3 columns have a lot of content and are overflowing the view then I'd like 3 independent scrollbars for each column.
Here's what I've got so far, but I can't seem to figure out how to get each column to get their own scrollbar rather than just the main scrollbar for the entire window.

.parent {
  display: flex;
  justify-content: center;
  color: white;
  background-color: darkred;
  margin: 0;
  min-width: 100vw;
  min-height: 100vh;
  overflow-x: hidden;
}

.child-column {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: darkblue;
  width: 200px;
  margin-left: 20px;
  margin-right: 20px;
  border: 1px solid black;
  overflow-y: auto;
}

.gran-child-item {
  background-color: darkgoldenrod;
  width: 100px;
  height: 100px;
  border: 1px solid black;
}

 Left

 Center

 Right

Fiddle-1
UPDATE
The code above was a smaller piece of my entire website (I didn't want to make my example too complicated, but it appears it was too simple). I was hoping the header/sidebar/footer structure would play nice and I could just drop a solution in, but it appears I need to explain the whole website structure to get it to work... Like many websites, I have a header and sidebar that stay fixed to the top and side of my website, I also have a footer which needs to stay at the bottom of the page. The way I did this before was by putting flex-grow: 1 on the main page content div and it'd force the footer to the bottom. It appears this now makes my page grow and not let the columns each have their own scrollbars.
Below is some revised code showing how I do the header/sidebar/footer and includes @Michaels edits, though it now doesn't do the column scrolling the way I'd like.
To add some more info: there are many different pages that are displayed on my website MOST all of the pages are long and expand past the height of my view and therefore have a single scrollbar on the right side of the page. What prompted my SO question was a new page I needed to add that has these 3 columns that all need their own scrollbars. So If the header/sidebar/footer can all be structure to support both kinds of page then that'd be great.

* {
    box-sizing: border-box;
}

html, body {
    display: flex;
    flex-grow: 1;
    color: white;
    background-color: darkred;
    margin: 0;
    height: 100vh;
}

.header {
    position: fixed;
    width: 100%;
    height: 50px;
    background-color: darkgreen;
}

.sidebar {
    position: fixed;
    width: 100px;
    height: calc(100vh - 50px);
    left: 0;
    top: 50px;
    background-color: darkcyan;
}

.footer {
    height: 50px;
    background-color: darkmagenta;
}

.page-container {
    display: flex;
    flex-direction: column;
    flex-grow: 1;
    margin-left: 100px;
    margin-top: 50px;
}

.page-content {
    display: flex;
    flex-grow: 1;
}

.column {
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: darkblue;
    width: 200px;
    margin-left: 20px;
    margin-right: 20px;
    height: 100%;
    border: 1px solid black;
    overflow-y: auto;
}

.item {
    flex-shrink: 0;
    background-color: darkgoldenrod;
    width: 100px;
    height: 100px;
    border: 1px solid black;
}

 header

 sidebar

 Left

 Center

 Right

 footer

Fiddle-2
Any help would be greatly appreciated!

A: Works with a few modifications:

/* include padding and borders in length calculations */
* {
  box-sizing: border-box;
}

.parent {
  display: flex;
  justify-content: center;
  color: white;
  background-color: darkred;
  margin: 0;

  /* min-width: 100vw; */ /* unnecessary; container is block level
                             element and takes full width by default */

  /* min-height: 100vh; */ /* if you make it min-height, container will
                              just expand with content and overflow
                              can't be triggered */

  height: 100vh; /* new */

  /* overflow-x: hidden; */ /* unnecessary */
}

.child-column {
  height: 100%; /* new; full height of parent container */
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: darkblue;
  width: 200px;
  margin-left: 20px;
  margin-right: 20px;
  border: 1px solid black;
  overflow-y: auto;
}

.gran-child-item {
  flex-shrink: 0; /* disable default shrink behavior;
                     otherwise items shrink (vertically,
                     in this case) to avoid overflowing container */
  background-color: darkgoldenrod;
  width: 100px;
  height: 100px;
  border: 1px solid black;
}

 Left

 Center

 Right

jsFiddle


text:
Q: Convert integer of MYYYY into Date in ssrs I have a field that is a bunch of integers formatted like so:
92014
102014

I would like to convert the field into a datetime of the first of each month. So the newly formated field would be:
9/01/2014 00:00:00
10/01/2014 00:00:00

(or however datetimes would actually get formatted). Can anyone help?

A: This is how you can accomplish this in an expression:
DateTime.ParseExact(IIF(LEN(Trim(Fields!StringDate.Value)) < 6, "0" & Fields!StringDate.Value,Fields!StringDate.Value),"Myyyy",System.Globalization.CultureInfo.InvariantCulture)


text:
Q: Группировка вёрстки по папкам (Android) При росте проекта в папке layouts накопилось большое количество файлов с разметкой. Это естественно вызывает определённые неудобства.
Можно ли их каким-то образом корректно сгруппировать по подпапкам?


text:
Q: How to set high value clustered feature to the front? Here is the clustered vector layer I just added to the map.
var defaultStyle = new OpenLayers.Style({
        strokeColor     : "#FFFFFF",
        strokeOpacity   : 1,
        strokeWidth     : 2,
        fillColor       : settings.color,
        fillOpacity     : 0.9,
        cursor          : "pointer",
        pointRadius     : "${point_radius}",
        pointerEvents   : "visiblePainted",
        label           : "${label}",
        fontColor       : "#000000",
        fontSize        : "12px",
        fontFamily      : "verdana",
        fontWeight      : "bold",
        labelAlign      : "center"
    }, {
        context: {
            label: function(feature) {
                var sumValue = 0;
                if(feature.attributes.count>1) {
                    for (var i=0; i<feature.cluster.length; i++) {
                        sumValue++;
                    }
                    return sumValue;
                }else{
                    return 1;
                }
            },
            point_radius: function(feature) {
                var pix = 10;
                if(feature.cluster) {
                    pix =Math.min(feature.attributes.count, 30) * 2.5 + 8;
                }
                return pix;
            }
        }
    });

    var onSelectStyle = new OpenLayers.Style({
        strokeColor     : "#000000",
        fontColor       : "#FFFFFF",
        pointerEvents   : "visiblePainted",
        fontSize        : "15px"
    });

    var strategy = new OpenLayers.Strategy.Cluster({distance: 30, threshold: 2});

    var ly=new OpenLayers.Layer.Vector(GSMapLayerName,{
            strategies: [strategy],
            styleMap:new OpenLayers.StyleMap({
                        "default":defaultStyle,
                        "select": onSelectStyle
                    }),
            displayInLayerSwitcher:false
        });
    map.addLayer(ly);

I am getting the below output

Look at the image the feature which have 9 is behind the 3 and 5. This is not a good to view.
 So, How can I set this feature to the front of all other features?
Note: I am using Openlayers 2.11
Thanks for any reply.

A: What if you try to add zIndex to the style with ${point_radius} as value?
Otherwise, check out http://dev.openlayers.org/examples/ordering.html

A: Here is the solution
    var defaultStyle = new OpenLayers.Style({
        strokeColor     : "#FFFFFF",
        strokeOpacity   : 1,
        strokeWidth     : 2,
        fillColor       : settings.color,
        fillOpacity     : 0.9,
        cursor          : "pointer",
        pointRadius     : "${point_radius}",
                                            graphicZIndex   : "${point_radius}"
        pointerEvents   : "visiblePainted",
        label           : "${label}",
        fontColor       : "#000000",
        fontSize        : "12px",
        fontFamily      : "verdana",
        fontWeight      : "bold",
        labelAlign      : "center"
    },
    ...................
    ......................

   var ly=new OpenLayers.Layer.Vector(GSMapLayerName,{
            strategies: [strategy],
            styleMap:new OpenLayers.StyleMap({
                        "default":defaultStyle,
                        "select": onSelectStyle
                    }),
            displayInLayerSwitcher:false,
            // enable the indexer by setting zIndexing to true
            rendererOptions: {zIndexing: true}
        });
    map.addLayer(ly);

Just add graphicZIndex : "${point_radius}" to the style and add rendererOptions: {zIndexing: true} to the layer.


text:
Q: Migrate KVM virtual machines on premises to AWS I have a few virtual machines on KVM.
I think at least 2 ways:

*

*Migrate everything KVM host with their virtual machines.

*Migrate every Virtual Machine to AWS as an instance.

Is that feasible? Could be that process non-disrupting?
What is the best way to do that?

A: Usually you would go for (2), since an EC2 instance is already a VM itself. It would also be much easier to manage later on.
Doing that without disruption might be possible, but I guess it'd be not that easy.
You might want to check out AWS CloudEndure, maybe that's helpful for your use case (haven't tried it by myself).


text:
Q: Unix Epoch Timestamp to Human readable Date time and back conversions In Erlang, i can get the Unix Epoc Timestamp by the code below:

{MegaSecs, Secs, MicroSecs} = now().
UnixTime = MegaSecs * 1000000 + Secs.

OR (as suggested by some sites)

calendar:datetime_to_gregorian_seconds(calendar:universal_time())-719528*24*3600.

However that conversion has occured for the result of erlang:now(). What if i have a given date time value in the format: "YYYY-MM-DD HH:MI:SS" e.g. "2012-12-30 15:13:40"
The time being in 24 hour format. This website gives the complete picture of what i need to be able to do in erlang.
How can i interchangeably convert from human readable formats to unix epoch timestamps and vice versa "at will", in my code. Such that if in my programs i store the timestamps as Unix Epochs, at the time of reading them, i can retrieve the human readable format automatically from the unix timestamp value or viceversa.

A: You can use this lib: https://github.com/selectel/tempo

tempo is a library for parsing and formatting dates in Erlang. It provides a clean and nice interface to libc's strptime and strftime functions, which are unfortunately missing from Erlang's standard library.

A: As well as tempo there's qdate:
https://github.com/choptastic/qdate
Would be interested to hear comparisons :)


text:
Q: Mac: How to sync specific address book contacts with a business partner? I have a mac and an iPhone. My friend has a mac and an iPhone. We both use those devices privately and for our shared business.
I wonder what's the best and easiest way to sync address book contacts with each other over the cloud. I thought of using Google Contacts to do so but I cant figure out how to only sync certain contacts.
E.g. imagine this. We have an "intelligent group" in our address book called "business" where all our business contacts are in. And we want to share this group with each other.
It would be best if it would sync completely wirelessly between our two accounts and phones.
Imagine I save a new number and contact on my iphone (associated with my "business" group - I want my friend to have this contact on his phone as well.
Any suggestions? I guess this is not possible right now? Any app recommendations that do stuff like that?
Thank you in advance,
Matt

A: My boss and I do this for work.
We made a separate Gmail account and used Gmail's built-in mobile exchange server.
On our phones, we named the account "Work Syncing" so that whenever we add a contact to our phone, we manually go to that contact group and add them, as opposed to "On my iPhone" or "iCloud."
Also note: Google documentation says that to prevent gmail from syncing all your contacts, you have to say "Delete existing contacts."  I'm not sure about that.
When I did it, I already had iCloud syncing all of my contacts so when I added gmail exchange, it made a separate group called "Work Syncing."  Thus as a precaution, I would recommend syncing with iCloud first.  It will then take ownership of all the contacts on your phone, so Gmail will make a separate contact group.  Then you can enable in your settings whether you want new contacts to default to your iCloud or gmail account.
On the iPhones - How to setup Google mobile exchange
On the mac - How to setup contact sync in Lion

A: Does it have to be a free solution? If not, I think I'd go with Full Contact--it's a cloud contact manager (vcard, social media, email) and the biz version lets you share certain lists with others in your organization.
http://www.fullcontact.com/business/


text:
Q: Why does an exe called in Excel VBA not output a file? So I have a Macro-enabled Excel/VBA Workbook with a button which writes a .txt file and then calls a .exe in the same directory.  The .exe is written in C++ and is supposed to output another file.
The problem I'm having is that for some reason when the Excel Workbook calls the C++ .exe, the executable processes the information from the .txt just fine, but the output file doesn't ever show up. But, if I have the workbook simply make the .txt file, and then I execute the C++ program myself then the program outputs the file correctly.
It seems that calling the .exe from the Excel/VBA workbook is causing the .exe not to output a file.
Here is the Excel/VBA code
Open (ActiveWorkbook.Path & "\excel.txt") For Output As #1
Print #1, MyString
Close #1
ActiveWorkbook.FollowHyperlink (ActiveWorkbook.Path & "\MyProgram.exe"),
NewWindow:=True

And the C++ is split among multiple files but the key part which may be causing issue is below
ofstream OutputFile;
int Sequence[12];
...
...
OutputFile.open("Output.solution");
for (int i=1;i<12;i++)
    OutputFile << Int_to_String(Sequence[i]) << " ";
OutputFile.close();

So how can I get the C++ executable to output the "Output.solution" file when being called from Excel VBA? Just to be clear - if I run the C++ program separately it does output the file.
Edit: When executing the .exe separately, the proper information is put into the "Output.solution" file in the same directory, but when calling from Excel/VBA, the .exe instead places an empty "Output.solution" into the My Documents folder.
How can I make this file appear back in the original directory when calling from Excel/VBA? and how can I ensure it will actually fill the file with information as it does when called outside excel?

A: Are you sure that your current directory is what you think it is?
It may be that it's somewhere other than your workbook path in which case the output files will be created there rather than where you expect.
Easiest way to check this is to execute the C++ program without the path:
ActiveWorkbook.FollowHyperlink ("MyProgram.exe"), NewWindow:=True

and see if it complains bitterly about not finding the executable.
Another way is to use a known location (temporarily) for the output file:
OutputFile.open("c:\\knowndir\\Output.solution");

and check that it's created. If it is, then there's nothing wrong with your executable, you're just in a directory different to what you think.
Also, search your entire disk for the Output.solution file. If you're in a different directory that's where the file will be created.
If it turns out that is the problem, probably the easiest solution is to change the directory before running the executable. VBA has a chdir command for just this purpose. You may need to change it back afterwards depending on your needs and you can use curdir for this.

A: Your best bet is to use a tool like SysInternal's Process Monitor to see if the file write is occurring at all, and if not, why not.
My guess is that you're probably falling foul of the executable running in a different directory to the directory you expect it to run from. Try outputting to an absolute location (or calling SetCurrentDirectory first) to see if this helps.


text:
Q: How to perform sql group by week and count of users who are created >= the week (Not just in that week)? Example:
| Week | UserId |
| ---- | ------ |
| 0    | A      |
| 0    | B      |
| 0    | C      |
| 1    | D      |
| 1    | E      |
| 1    | F      |
| 2    | G      |
| 3    | H      |
| 3    | I      |

Now I want the table like below
| Week | Users |
| ---- | ------ |
| 0    | 9      |
| 1    | 6      |
| 2    | 3      |
| 3    | 2      |

Now I could use
SELECT
    *
FROM
    (week_3_users AS
    (
        SELECT DISTINCT User_ID
        FROM users
        WHERE week >= 3
    ),
    week_2_users AS
    (
        SELECT DISTINCT User_ID
        FROM users
        WHERE week >= 2
    ),
    week_1_users AS
    (
        SELECT DISTINCT User_ID
        FROM users
        WHERE week >= 1
    ),
    week_0_users AS
    (
        SELECT DISTINCT User_ID
        FROM users
        WHERE week >= 0
    )
    SELECT
        (SELECT COUNT(*) FROM week_0_users) AS week_0_count,
        (SELECT COUNT(*) FROM week_1_users JOIN week_0_users USING (User_ID)) AS    week_1_count,
        (SELECT COUNT(*) FROM week_2_users JOIN week_0_users USING (User_ID)) AS week_2_count,
        (SELECT COUNT(*) FROM week_3_users JOIN week_0_users USING (User_ID)) AS week_3_count
)

That returns:
| week_0_count | week_1_count | week_2_count | week_3_count |
| ------------ | ------------ | ------------ | ------------ |
| 9            | 6            | 3            | 2            |

But I don't want to repeat that for N number of weeks.
Please suggest of I can do it to get desired output

A: You can use a cumulative sum:
select week, count(*),
       sum(count(*)) over (order by week desc)
from t
group by week
order by week;

A:
But I don't want to repeat that for N number of weeks.
Please suggest of I can do it to get desired output

Below is for BigQuery Standard SQL
execute immediate (
select 'select ' ||
    string_agg('max(if(week =' || week || ',users,null)) week_' || week || '_count', ', ' order by week) || '''
  from (
  select week, sum(count(*)) over (order by week desc) users
  from `project.dataset.users_table`
  group by week)'''
from (select distinct week from `project.dataset.users_table`)
);

If/when applied to sample data from your example - output is


text:
Q: get result same time in multiple table I have table like below and I try to find how to
get the result is article id array or article rows,
sametimes match tag 'hiphop','rock','single' in ArticleTag0 and ArticleTag1 table.
Right now I use below code,
get each article id array tagged in different tag type,
e.g if article id rows tagged in Article x Tag0 is [0, 2, 4, 6] and Article x Tag1 is [0, 4, 9],
then compare each array get the number both in above two array get , [0, 4].
I'm wondering is there any better query select them one time?  consider performance
table
    CREATE TABLE IF NOT EXISTS "Article"(
    "ArticleId" SERIAL NOT NULL,
    "PublishDate" timestamp without time zone,
    "Active" bit NOT NULL,
    PRIMARY KEY ("ArticleId")
    );

    CREATE TABLE IF NOT EXISTS "Tag0"(
    "TagId" SERIAL NOT NULL,
    "Name" varchar,
    "Active" bit NOT NULL,
    PRIMARY KEY ("TagId")
    );

    CREATE TABLE IF NOT EXISTS "Tag1"(
    "TagId" SERIAL NOT NULL,
    "Name" varchar,
    "Active" bit NOT NULL,
    PRIMARY KEY ("TagId")
    );

    CREATE TABLE IF NOT EXISTS "ArticleTag0"(
    "ArticleTagId" SERIAL NOT NULL,
    "ArticleId" integer NOT NULL,
    "TagId" integer NOT NULL,
    FOREIGN KEY ("ArticleId") REFERENCES "Article" ("ArticleId") ON DELETE CASCADE ON UPDATE CASCADE,
    FOREIGN KEY ("TagId") REFERENCES "Tag0" ("TagId") ON DELETE CASCADE ON UPDATE CASCADE,
    PRIMARY KEY ("ArticleTagId")
    );

    CREATE TABLE IF NOT EXISTS "ArticleTag1"(
    "ArticleTagId" SERIAL NOT NULL,
    "ArticleId" integer NOT NULL,
    "TagId" integer NOT NULL,
    FOREIGN KEY ("ArticleId") REFERENCES "Article" ("ArticleId") ON DELETE CASCADE ON UPDATE CASCADE,
    FOREIGN KEY ("TagId") REFERENCES "Tag1" ("TagId") ON DELETE CASCADE ON UPDATE CASCADE,
    PRIMARY KEY ("ArticleTagId")
    );

code
user input params
inputGenres (Tag0) - [ 'hiphop', 'rock' ]
inputReleaseType (Tag1) - [ 'single' ]
    ...
    // inputGenres
    var inputGenresArticleIdList = [];

    if (inputGenres[0] == 'all') {
      var query = 'SELECT * FROM "Article"';
      var params = [];

      var selectArticle = yield crudDatabase(db,query,params);
      if (typeof selectArticle.error !== 'undefined') {
        response.meta.code = '500';
      } else {
        for (var i = 0; i < selectArticle.result.rows.length; i++) {
          inputGenresArticleIdList.push(selectArticle.result.rows[i].ArticleId);
        }
      }
    } else {
      var query = 'SELECT DISTINCT ON ("ArticleId") * FROM "ArticleTag0" LEFT OUTER JOIN "Tag0" ON ("ArticleTag0"."TagId" = "Tag0"."TagId") WHERE "Name" IN (';
      for (var i = 0; i < inputGenres.length; i++) {
        if (i > 0) {
          query += ',';
        }
        query += '$' + (i + 1);
      }
      query += ')';
      var params = inputGenres;

      var selectArticleTag0 = yield crudDatabase(db,query,params);
      if (typeof selectArticleTag0.error !== 'undefined') {
        response.meta.code = '500';
      } else {
        for (var i = 0; i < selectArticleTag0.result.rows.length; i++) {
          inputGenresArticleIdList.push(selectArticleTag0.result.rows[i].ArticleId);
        }
      }
    }
    console.log(inputGenresArticleIdList);
    // end: inputGenres

    // inputReleaseType
    var inputReleaseTypeArticleIdList = [];

    if (inputReleaseType[0] == 'all') {
      var query = 'SELECT * FROM "Article"';
      var params = [];

      var selectArticle = yield crudDatabase(db,query,params);
      if (typeof selectArticle.error !== 'undefined') {
        response.meta.code = '500';
      } else {
        for (var i = 0; i < selectArticle.result.rows.length; i++) {
          inputReleaseTypeArticleIdList.push(selectArticle.result.rows[i].ArticleId);
        }
      }
    } else {
      var query = 'SELECT DISTINCT ON ("ArticleId") * FROM "ArticleTag4" LEFT OUTER JOIN "Tag4" ON ("ArticleTag4"."TagId" = "Tag4"."TagId") WHERE "Name" IN (';
      for (var i = 0; i < inputReleaseType.length; i++) {
        if (i > 0) {
          query += ',';
        }
        query += '$' + (i + 1);
      }
      query += ')';
      var params = inputReleaseType;

      var selectArticleTag4 = yield crudDatabase(db,query,params);
      if (typeof selectArticleTag4.error !== 'undefined') {
        response.meta.code = '500';
      } else {
        for (var i = 0; i < selectArticleTag4.result.rows.length; i++) {
          inputReleaseTypeArticleIdList.push(selectArticleTag4.result.rows[i].ArticleId);
        }
      }
    }
    console.log(inputReleaseTypeArticleIdList);
    // end: inputReleaseType

    ... then loop each array and compare

A: Generally it's better to do the job with one SQL statement: it is less complicated, it saves roundtrips to the server and back, it makes use of database's algorithms and optimizations.
You can get the result you want using the following statement:
select *
from   "Article" a
where  exists (
         select 1
         from   "ArticleTag0" at0,
                "Tag0" t0
         where  at0."ArticleId" = a."ArticleId"
         and    t0."TagId" = at0."TagId"
         and    t0."Name" in ('hiphop','rock')
       )
and    exists (
         select 1
         from   "ArticleTag1" at1,
                "Tag1" t1
         where  at1."ArticleId" = a."ArticleId"
         and    t1."TagId" = at1."TagId"
         and    t1."Name" in ('single')
       );

You still need to change literals (like 'hiphop') to bind variables ($i), of course. 'All' option for tags can be done by substituting appropriate exists(...) block with true.

But I would suggest a little redesign of your schema. How about representing tags of an article by an array?
create table article(
  articleId   serial primary key,
  publishDate timestamp without time zone,
  active      boolean, -- clearer that 'bit'
  genres      text[],  -- array of genre tags
  releases    text[]   -- array of release tags
);

Benefits:

*

*No need for intermediate tables (like ArticleTag0) between articles and tags.

*Simpler queries.

*Possibility to use overlap operation of arrays with index support.

Lets insert some values:
tags=# insert into article(publishDate,active,genres,releases) values ('2015-09-01',true,'{"hiphop"}','{"single"}');
INSERT 0 1
tags=# insert into article(publishDate,active,genres,releases) values ('2015-10-01',true,'{"rock","blues"}','{"album"}');
INSERT 0 1
tags=# insert into article(publishDate,active,genres,releases) values ('2015-11-01',true,'{"pop"}','{"ep"}');
INSERT 0 1

tags=# select * from article;
 articleid |     publishdate     | active |    genres    | releases
-----------+---------------------+--------+--------------+----------
         1 | 2015-09-01 00:00:00 | t      | {hiphop}     | {single}
         2 | 2015-10-01 00:00:00 | t      | {rock,blues} | {album}
         3 | 2015-11-01 00:00:00 | t      | {pop}        | {ep}
(3 rows)

The query now is as simple and clear as possible (&& operator means 'overlaps'):
tags=# select * from article where genres && '{"hiphop","rock"}' and releases && '{"single"}';
 articleid |     publishdate     | active |  genres  | releases
-----------+---------------------+--------+----------+----------
         1 | 2015-09-01 00:00:00 | t      | {hiphop} | {single}
(1 row)

Also it simplifies construction of the query text: use select * from article where genres && $1 and releases && $2; and generate appropriate strings for $1 and $2.
To speed up the query you can create two GIN indexes which support && operator for arrays:
create index on article using gin(genres);
create index on article using gin(releases);


text:
Q: How to decompress/deflate PDF Stream Working with the 2016-W4 pdf, which has 2 large streams (page 1 & 2), along with a bunch of other objects and smaller streams. I'm trying to deflate the stream(s), to work with the source data, but am struggling. I'm only able to get corrupt inputs and invalid checksums errors.
I've written a test script to help debug, and have pulled out smaller streams from the file to test with.
Here are 2 streams from the original pdf, along with their length objects:
stream 1:
149 0 obj
<< /Length 150 0 R /Filter /FlateDecode /Type /XObject /Subtype /Form /FormType
1 /BBox [0 0 8 8] /Resources 151 0 R >>
stream
x+TT(T0�B ,JUWÈS0Ð37±402V(NFJS�þ¶
«
endstream
endobj
150 0 obj
42
endobj

stream 2
142 0 obj
<< /Length 143 0 R /Filter /FlateDecode /Type /XObject /Subtype /Form /FormType
1 /BBox [0 0 0 0] /Resources 144 0 R >>
stream
x+T�ç�ã
endstream
endobj
143 0 obj
11
endobj

I copied just the stream contents into new files within Vim (excluding the carriage returns after stream and before endstream).
I've tried both:

*

*compress/flate (rfc-1951) – (removing the first 2 bytes (CMF, FLG))

*compress/zlib (rfc-1950)
I've converted the streams to []byte for the below:
package main

import (
    "bytes"
    "compress/flate"
    "compress/gzip"
    "compress/zlib"
    "fmt"
    "io"
    "os"
)

var (
    flateReaderFn = func(r io.Reader) (io.ReadCloser, error) { return flate.NewReader(r), nil }
    zlibReaderFn  = func(r io.Reader) (io.ReadCloser, error) { return zlib.NewReader(r) }
)

func deflate(b []byte, skip, length int, newReader func(io.Reader) (io.ReadCloser, error)) {
    // rfc-1950
    // --------
    //   First 2 bytes
    //   [120, 1] - CMF, FLG
    //
    //   CMF: 120
    //     0111 1000
    //     ↑    ↑
    //     |    CM(8) = deflate compression method
    //     CINFO(7)   = 32k LZ77 window size
    //
    //   FLG: 1
    //     0001 ← FCHECK
    //            (CMF*256 + FLG) % 31 == 0
    //             120 * 256 + 1 = 30721
    //                             30721 % 31 == 0

    stream := bytes.NewReader(b[skip:length])
    r, err := newReader(stream)
    if err != nil {
        fmt.Println("\nfailed to create reader,", err)
        return
    }

    n, err := io.Copy(os.Stdout, r)
    if err != nil {
        if n > 0 {
            fmt.Print("\n")
        }
        fmt.Println("\nfailed to write contents from reader,", err)
        return
    }
    fmt.Printf("%d bytes written\n", n)
    r.Close()
}

func main() {
    //readerFn, skip := flateReaderFn, 2 // compress/flate RFC-1951, ignore first 2 bytes
    readerFn, skip := zlibReaderFn, 0 // compress/zlib RFC-1950, ignore nothing

    //                                                                                ⤹ This is where the error occurs: `flate: corrupt input before offset 19`.
    stream1 := []byte{120, 1, 43, 84, 8, 84, 40, 84, 48, 0, 66, 11, 32, 44, 74, 85, 8, 87, 195, 136, 83, 48, 195, 144, 51, 55, 194, 177, 52, 48, 50, 86, 40, 78, 70, 194, 150, 74, 83, 8, 4, 0, 195, 190, 194, 182, 10, 194, 171, 10}
    stream2 := []byte{120, 1, 43, 84, 8, 4, 0, 1, 195, 167, 0, 195, 163, 10}

    fmt.Println("----------------------------------------\nStream 1:")
    deflate(stream1, skip, 42, readerFn) // flate: corrupt input before offset 19

    fmt.Println("----------------------------------------\nStream 2:")
    deflate(stream2, skip, 11, readerFn) // invalid checksum
}

I'm sure I'm doing something wrong somewhere, I just can't quite see it.
(The pdf does open in a viewer)

A: Binary data should never be copied out of / saved from text editors. There might be cases when this succeeds, and it just adds oil to the flame.
Your data that you eventually "mined out" from the PDF is most likely not identical to the actual data that is in the PDF. You should take the data from a hex editor (e.g. try hecate for something new), or write a simple app that saves it (which strictly handles the file as binary).
Hint #1:
The binary data displayed spread across multiple lines. Binary data does not contain carriage returns, that's a textual control. If it does, that means the editor did interpret it as text, and so some codes / characters where "consumed" to start a new line. Multiple sequences may be interpreted as the same newline (e.g. \n, \r\n). By excluding them, you're already at data loss, by including them, you might already have a different sequence. And if the data was  interpreted and displayed as text, more problems may arise as there are more control characters, and some characters may not appear when displayed.
Hint #2:
When flateReaderFn is used, decoding the 2nd example succeeds (completes without an error). This means "you were barking up the right tree", but the success depends on what the actual data is and to what extent was it "distorted" by the text editor.

A: Okay, confession time...
I was so caught up in trying to understand deflate that I completely overlooked the fact that Vim wasn't saving the stream contents correctly into new files. So I spent quite a bit of time reading the RFC's, and digging through the internals of the Go compress/... packages, assuming the problem was with my code.
Shortly after I posted my question I tried reading the PDF as a whole, finding the stream/endstream locations, and pushing that through deflate. As soon as I saw the content scroll through the screen I realized my dumb mistake.
+1 @icza, that was exactly my issue.
It was good in then end, as I have a much better understanding of the whole process than if it would have just worked the first go around.

A: Extracting objects from PDF can be tricky depending on the filters used. The filter can also have additional options which need to be handled correctly.
For someone interested in extracting an object without taking care of the low-level details of the process.
To get a single object from a PDF and decode it can be done as follows:
package main

import (
    "fmt"
    "os"
    "strconv"

    "github.com/unidoc/unipdf/v3/core"
    "github.com/unidoc/unipdf/v3/model"
)

func main() {
    objNum := 149 // Get object 149
    err := inspectPdfObject("input.pdf", objNum)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        os.Exit(1)
    }
}

func inspectPdfObject(inputPath string, objNum int) error {
    f, err := os.Open(inputPath)
    if err != nil {
        return err
    }

    defer f.Close()

    pdfReader, err := model.NewPdfReader(f)
    if err != nil {
        return err
    }

    isEncrypted, err := pdfReader.IsEncrypted()
    if err != nil {
        return err
    }

    if isEncrypted {
        // If encrypted, try decrypting with an empty one.
        // Can also specify a user/owner password here by modifying the line below.
        auth, err := pdfReader.Decrypt([]byte(""))
        if err != nil {
            fmt.Printf("Decryption error: %v\n", err)
            return err
        }
        if !auth {
            fmt.Println(" This file is encrypted with opening password. Modify the code to specify the password.")
            return nil
        }
    }

    obj, err := pdfReader.GetIndirectObjectByNumber(objNum)
    if err != nil {
        return err
    }

    fmt.Printf("Object %d: %s\n", objNum, obj.String())

    if stream, is := obj.(*core.PdfObjectStream); is {
        decoded, err := core.DecodeStream(stream)
        if err != nil {
            return err
        }
        fmt.Printf("Decoded:\n%s", decoded)
    } else if indObj, is := obj.(*core.PdfIndirectObject); is {
        fmt.Printf("%T\n", indObj.PdfObject)
        fmt.Printf("%s\n", indObj.PdfObject.String())
    }

    return nil
}

A full example: pdf_get_object.go
Disclosure: I am the original developer of UniPDF.


text:
Q: Azure web deploy HTTP Error 500.30 - ANCM In-Process Start Failure I have just deployed my .net core and react project on Azure using web deploy and published using Windows instead of Linux. I seem to be getting a HTTP Error 500.30 here are the error logs below, I have used the pre configured identity server 4 when making the application but I assume the error has something to do with this, anyone know of a fix for this?
Error log
Error log 2

A: I'll assume that this app works in your development environment, so I think this is a configuration error.
ASP.NET Core have 3 default environments: development, staging and production; and you have differents appsettings for each of them (appsettings.json wich is the base, appsettings.Development.json, appsettings.Stating.json and appsettings.Production.json).
My theory is you have the configuration related to IdentityServer only in appsettings.Development.json, so this is not beign loaded in production environment.
Include the configuration in appsettings.json or appsettings.Production.json an check it out.
If you're deploying the app to Azure AppService you could include the config in the AppSettings section.
Check more about config and enviroments:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1

A: I've solved the problem it did have something to do with my appsettings.json where i needed to include     "Key": {
"Type": "Development"
},


text:
Q: Error: Invalid: Unrecognized filesystem type in URI when loading parquet file from url using arrow package I'm pretty new to parquet file format and I'm using the read_parquet() (in the arrow package) to load parquet file (stored in my Dropbox share folder) into R. However, I received the following error message

library(arrow)
 df <- read_parquet("https://www.dropbox.com/s/mysgf4sojpjgyp7/part-394.parquet?dl=1")

Error: Invalid: Unrecognized filesystem type in URI: https://www.dropbox.com/s/mysgf4sojpjgyp7/part-394.parquet?dl=1

What might cause this problem here and do I need to partition the url link beforehand?

A: The file reading functions in the arrow package do not yet support HTTP[S] URIs. We hope to add this feature in a future release (ARROW-7594). In the meantime:
If you have Dropbox installed on the computer where you're running this, use the local path to the file instead of the HTTPS URI.
If you do not have Dropbox installed, then download the file first, like this:
myfile <- tempfile()
download.file(
  "https://www.dropbox.com/s/mysgf4sojpjgyp7/part-394.parquet?dl=1",
  myfile,
  mode = "wb"
)
df <- read_parquet(myfile)


text:
Q: Remote form inside other remote form in Rails 3 disables nested form What I have is a remote form inside another remote form like this:
<%=form_for @myobj,:as=>:myobj,:url=>{:controller=>"my_controller",:action=>"first_action"},:remote=>true do |f|%>
   <%=form_for @myotherobj,:as=>:myotherobj,:url=>{:controller=>"my_controller",:action=>"second_action"},:remote=>true do |ff|%>
      <%=ff.submit "second"%>
   <%end%>
   <%=f.submit "first"%>
<%end%>

But then I click the second submit it doesn't do a remote call, It does a normal call with leads me to an error Missing Template because my action only responds to JS (Ajax Calls)

A: Nested forms are invalid html.
The browsers behaviour is undefined what to do in such a case. It's just like trying to use IDs multiple times inside a html document. It will normally be the earliest occurrence of the ID that will be selected by a document.getElementById, and here you are finding the outermost (earliest) form is the one that is submitting.
If (at least) one of the forms is being submitted with javascript, then it would probably be better to create the form elsewhere and copy the values, or move the form elements prior to submitting.


text:
Q: Broken macOS High Sierra log system? With /usr/bin/log I can get information about the mail services from macOS's log system. E.g. /usr/bin/log show --start '2019-08-07 12:50:59' --end '2019-08-07 13:00:59' --predicate '(process == "smtp") || (process == "smtpd") || (process == "postscreen") || (process == "qmgr")' -info
I use run this via a script every night to get a semi-normal postfix log from macOS's log system.
#!/bin/bash

#LOGDIR=/tmp # For testing
LOGDIR=/var/log
LOGFILE="$LOGDIR/tmpmail.log"
LOGDATEFILE="$LOGDIR/maillog.lastrun"
LOCKDIR="$LOGDIR/maillog.lock"

if mkdir "$LOCKDIR"
then
    # Lock acquired
    # Remove LOCKDIR when the script finishes, or when it receives a signal
    trap 'rm -rf "$LOCKDIR"' 0    # remove directory when script finishes

    ENDDATE=$(date -v-1S +"%Y-%m-%d %T")
    echo >&2 "Adding mail log data to $LOGFILE until cutoff $ENDDATE"
    if [ ! -f "$LOGDATEFILE" ]
    then
        /usr/bin/log show --end "$ENDDATE" --predicate '(process == "smtp") || (process == "smtpd") || (process == "postscreen") || (process == "qmgr")' -info >> "$LOGFILE"
    else
        STARTDATE=`cat "$LOGDATEFILE"`
        echo >&2 "Adding mail log data to $LOGFILE from previous cutoff $STARTDATE"
        /usr/bin/log show --start "$STARTDATE" --end "$ENDDATE" --predicate '(process == "smtp") || (process == "smtpd") || (process == "postscreen") || (process == "qmgr")' -info >> "$LOGFILE"
    fi
    /bin/echo -n "$ENDDATE" >"$LOGDATEFILE"

else
    # Another one is already running or the lock was not cleaned up
    echo >&2 "Cannot acquire lock on $LOCKDIR. Giving up"
    exit 0
fi

This used to work perfectly, and I had no need for my logs for a long while. Now I have, and I find out that the log extraction has become erratic. To be precise: while I can see a few messages being delivered (or greylisting-bounced) in the log, there are many that I know that have been delivered (they are in the user's mail box), but that do not show up in the log. I cannot think of a rational explanation.
Could it be that the database of macOS's log system is hosed and how do I find out?


text:
Q: How to add a select all option to select component in CDE for a students projects we are working with Pentaho CDE to create a dashboard.
At first it works fine, but now we are hanging at the point adding more than one Select Component.
We inserted the Parameters of the Select Components to the SQL-Queries in the Where statement but now we have the problem, that it is not possible to select all elements in one select component and only one in the others. The sample space is getting smaller and smaller the more parameters we add because we can't find out how to select all option in one select component and send this all to the query.
Is it possible in CDE to add an "select all elements option" to the select component? Or even to deactivate a select component and send this deactivation to the SQL-Query?
We noticed that there is a multiple select component but we were not able to handle the custom parameter needed for it.
It would be fine if it works with the select components.
Thanks in advance for your support.

A: Use SQL expression CASE:

SELECT * FROM table  WHERE
        cities LIKE (case when ${city} = 'ALL' then '%' ELSE ${city} end)

A: Two approaches:

*

*On your single select query add (possibly hardcoding) a "All" option and have some JS logic learn how to handle it;

*Use multi select components. However, bear in mind that the parameter values on a multi select component are stored as an array in javascript, whereas the parameter value will be passed as a comma separated list to the query. So, if you want to use a multi select parameter in a SQL query you will most likely use it inside a IN condition.
Finally, check your pentaho.log file. The errors and exceptions will be logged there.

A: If you dont want use like.
SELECT * from table_name where column_name = case when ${param} = 'ALL' then column_name else ${param} end


text:
Q: Rotation by Shell or Washer method. So even after going to my profs office I could not find out what I did wrong in this simple integration rotation (washer) problem.
Image of Graph
I'm given two curves x = y^2 and y = x^2 and I am instructed to rotate this along y=1. To start I convert x = y^2 into y = √x and set them equal to each other. I find that they meet at (1,1) and (0,0). Next I write out my area function considering the fact that if I create a washer to handle the problem my big R will equal (1 - x^2) and my little r will be
$$ r= (1 - √x) $$
$$ A(x) = π[(1 - x^2)^2 - (1 - √x)^2] = π[1 - x^4 - 2x^2 - 1 -x +2x^(1/2)] $$
$$= \int_0^1  \pi[- 1/5x^5 - 2/3x^3 + 1/2x^2 +4/3x^(3/2)] (1,0) $$
$$ = \pi[-1/5 - 2/3 + 1/2 + 4/3] = \pi[-26/30 + 55/30] = 29\pi/30 $$
However this is not the correct answer. I've stared at this problem for some time and I know someone will be able to quickly point me in the right direction! Sorry if my formatting is awful, I sincerely appreciate it. I also provided the correct graphs that I used to solve this problem.
Image of Graph
Very simple error may be, help from a second set of eyes would be greatly appreciated!

A: With the method of washers, the inner radius of the solid is given by $$g(x) = 1-\sqrt{x}, \quad 0 \le x \le 1.$$  The outer radius is $$f(x) = 1 - x^2, \quad 0 \le x \le 1.$$  Then, at a given $x$-value, a washer of differential thickness $dx$ has differential volume $$dV = \pi(f(x)^2 - g(x)^2) \, dx = \pi ((1-x^2)^2 - (1 - \sqrt{x})^2) \, dx.$$  It is perhaps simpler to observe that $$f(x)^2 - g(x)^2 = (f(x) + g(x))(f(x) - g(x)),$$ so that $$f(x) - g(x) = (1-x^2) - (1-\sqrt{x}) = x^{1/2} - x^2, \\ f(x) + g(x) = 2 - x^{1/2} - x^2,$$ so the integral to be evaluated is $$V = \int_{x=0}^1 dV = \pi \int_{x=0}^1 (x^{1/2} - x^2)(2 - x^{1/2} - x^2) \, dx.$$  Now expanding the product, we get $$V = \pi \int_{x=0}^1 2x^{1/2} - x - 2x^2 + x^4 \, dx.$$ Integrating term by term gives $$V = \pi \left[ \frac{4}{3}x^{3/2} - \frac{x^2}{2} - \frac{2}{3}x^3 + \frac{x^5}{5} \right]_{x=0}^1 = \pi \left(\frac{4}{3} - \frac{1}{2} - \frac{2}{3} + \frac{1}{5} \right) = \frac{11\pi}{30}.$$


text:
Q: How to display Russian language in Tkinter text widget? (Currently only seeing unicode) Does anybody know what my problem is?
I'm starting some work on tkinter and when I copy/paste a bit of Russian Text to my tkinter text widget it looks like this

Here is the original text

Лиса вышла холодной ночью.
Он молился, чтобы луна дала ему свет.
Ибо в ту ночь ему предстояло пройти много миль.

Can someone help me correctly display this text on tkinter?
some information.

*

*I am using a conda environment

*python 3.7

*OS is CentOS

Steps to reproduce my environment.

*

*setup a conda environment (my python version is 3.7)
https://docs.conda.io/projects/conda/en/latest/user-guide/getting-started.html

*set conda environment as interpreter in pycharm

*code

import tkinter as tk

window = tk.Tk()
txt_align = tk.Text(master=window)
txt_align.grid(sticky="nsew", padx=5, pady=5)

window.mainloop()

if you want you can also do
text = "Лиса вышла холодной ночью. Он молился, чтобы луна дала ему свет. Ибо в ту ночь ему предстояло пройти много миль."
txt_align.insert(tk.END, text)
print(text)

but my results stay the same unfortunately.

*copy russian text
Лиса вышла холодной ночью.
Он молился, чтобы луна дала ему свет.
Ибо в ту ночь ему предстояло пройти много миль.

*paste it into tkinter text box
things I've tried:

*

*I tried importing codecs and opening my text file containing the Russian text that way with encoding = utf-8

More info:
When I 'get' the text from the text widget and print to console, it displays Russian just fine.
-English,French works just fine but Korean, Chinese, arabic all display in this weird format
Thank you!


text:
Q: How to add list to column by SQLite kotlin query android I have 5 columns in the database, 4 of which I fill out a request from the network. I'm trying to add data to the database specifically in these 4 columns via @QUERY, because when trying to do this via @Insert (onConflict = OnConflictStrategy.REPLACE), the value in the 5th column is set to default.
I would like to insert the entire list into the column through sqlite, that is, into the "id" List <Int>, in the "first_name" List <String>, etc. ? Is this possible, if so, what would the correct syntax look like? At the moment I am filling in the data through a for loop.
Here is the request:
@Query("INSERT INTO friends_table (id, first_name, last_name, photo) VALUES (:id, :firstName, :lastName, :photo)")

suspend fun insertAll(
        id: Int,
        firstName: String,
        lastName: String,
        photo: String
    )

A: For correct working out "@Insert (onConflict = OnConflictStrategy.REPLACE)" it is required to mark id with annotation "@PrimaryKey"
You entity model.
@Entity
class EmployeeEntity(
        @PrimaryKey
        id: Int,
        firstName: String,
        lastName: String,
        photo: String
)

@Insert (onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(entities: List<EmployeeEntity>)

Link for primary key
Link for entity


text:
Q: how do i sort a file second column in python code This is my text file. I want to sort second column by ascending order. How do I sort this in python code?
Test file content:
ghj sfs
dtj fsf
zzz hdh
abc kdk
bcd jdd
csf jkd
sfa aaa
ser jld
afr zzz
awr kld
fas ljl
afr lfl
faw kks

A: You may do
# Read
with open("filename.txt") as fic:
    lines = [line.rstrip().split() for line in fic] # read each line

# Sort
lines = sorted(lines, key=lambda x:x[1])

# Write again
with open("filename.txt", "w") as fic:
    fic.writelines([" ".join(line) + "\n" for line in lines]) # write each line

Other way to read
lines = []
with open("filename.txt") as fic:
     for line in fic:
        line = line.rstrip().split()
        lines.append(line)

Other way to write
with open("filename.txt", "w") as fic:
    for line in lines:
        fic.write(" ".join(line) + "\n")


text:
Q: Ofbiz Websocket Example setup not connecting wss I am trying to setup websocket environment by setting up ofbiz 16.11.04 build and from catalina.properties, i set websocket=true.
I tried to get into "Example", i am getting following error

Firefox can't establish a connection to the server at
  wss://localhost:8443/example/ws/pushNotifications

is there any setup I am missing or anyone facing this issue

A: I fixed that recently, please check https://s.apache.org/k4Vo and http://svn.apache.org/viewvc?view=revision&revision=r1819814
For convenience, here is the patch
--- framework/catalina/ofbiz-component.xml  2018/01/02 12:25:33 1819813
+++ framework/catalina/ofbiz-component.xml  2018/01/02 12:26:29 1819814
@@ -22,6 +22,7 @@
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ofbiz.apache.org/dtds/ofbiz-component.xsd">
     <resource-loader name="main" type="component"/>
+    <classpath type="dir" location="config"/>
     <entity-resource type="model" reader-name="main" loader="main" location="entitydef/entitymodel.xml"/>

     <container name="catalina-container" loaders="main" class="org.apache.ofbiz.catalina.container.CatalinaContainer">


text:
Q: Asset and theme I'm trying to figure out why after adding in the this asset line it turns into the line below it but shows a 404 file not found when in fact it does exist.
Asset::css('theme::bootstrap/bootstrap.css');
http://dev.myurl/application/themes/mytheme/assets/css/bootstrap/bootstrap.css" rel="stylesheet">

A: try this:
<?php
Asset::css('bootstrap/bootstrap.css');
echo Asset::render();
?>


text:
Q: Double free issue with global map compiled in to multiple shared objects I have a huge map that is needed in multiple shared objects ..
//mymap.h
extern const std::unordered_map<int, std::string> gMAP;
std::string getname(int i) { return gMAP[i]; }

//mymap.cpp
extern const std::unordered_map<int, std::string> gMAP = {
  {1, "one" },
  {2, "two" },
  {3, "three" },
  ...
}

And then I have library1 (lib1.so):
//CMakeLists.txt lib1.so
add_library(lib1 SHARED lib1.cpp mymap.cpp)

//lib1.cpp
#include "mymap.h"
void lib1_dosomething(int i) { std::cout << getname(i) << std::endl; }

And then I have library2 (lib2.so):
//CMakeLists.txt lib2.so
add_library(lib2 SHARED lib2.cpp mymap.cpp)

//lib2.cpp
#include "mymap.h"
void lib1_dosomething(int i) { std::cout << getname(i) << std::endl; }

This is simply pseudo code of our complex and much bigger system. Note that not all the libraries in our system need the map. Only very few (which is why I went for compiling in the project itself).
My understanding of making it this way is as follows:

*

*Each library that compiles "mymap.cpp" has a 'new' instance of the map

*There shall be no conflicts when all the libraries are loaded into memory when the system runs. And each library creates the global map when it is loaded and destroys it when it is unloaded from memory.

So my first question is: Is this understanding correct ?
But, I see a problem during the shutdown of our system. I noticed that each library creates an instance as expected, and destroys its instance during unloading. But one library seems to call the destructor of the std::unordered_map twice. And as a result we see a deallocation error (double free or corruption (!prev)), which i cannot explain why and what is causing this. Any ideas ?
I am thinking of compiling the map in a shared library of itself, so that we only have absolutely one instance throughout the system, but i want to understand why I see the "double free or corruption (!prev)" error.


text:
Q: Create SharePoint 2016 dev and test environment (cloning) Our company decided to organize the environment for development and testing for SharePoint 2016.
At first I thought to clone a half of VMs of servers of a farm of sharepoint in our normal test vlan with RODC and just to rename servers. But I was told what so won't work. Then we decided to create the complete copy of a production environment in completely isolated vlan the only thing that this IP will change.
Сloned one of our ADC there. There in isolated vlan it now the complete copy of our productive ADC and the master of all FSMO of roles.
Сloned all servers of a farm SharePoint there.
Now we have a complete copy of our productive farm of sharepoint (all names of servers are identical to original) except for IP addresses.
on local ADC I of course corrected appropriate dns of record.
The SQL server works normally all bases are available.
But sharepoint for some reason doesn't work!
Prompt in what there can be a reason (can machines were copied and joined in a missequence or something else).
generally such scenario can work?
I know that the simplest option for the organization of the test environment it "new installation" but can somebody so already tried and it worked?

A: If SharePoint doesn't work, because it should, there are a few things to check:

*

*Are all your servers part of your test-domain, and can you sign in to SharePoint Servers using a domain account? i.e. TESTAD\SPFarm instead of .\Administrator?

*Can you access SQL Server from SharePoint Servers? Either you install SQL Server Management Studio Client and access your SQL Server with computername\instance-id only (not FQDN).

*Do you use SQL-Alias on your SharePoint Servers (you should) and are they pointing to the new IP-address of the SQL Server? Run cliconfg from CMD and check

*Obviously you have pinged your Domain Controller and SQL Server from SharePoint Servers, but have you tried accessing ports as well with telnet? See TCP/IP Ports of SharePoint 2013 for reference

*Can you access the farm using PowerShell? Running SharePoint Management Shell will tell you quickly.

*The domain accounts your using, do they exist in your TEST-AD, or they didn't follow over to they new environment?

Still in trouble and nothing works? Try to create a new farm on one of your servers on another instance of your SQL Server, and see where that leads you.


text:
Q: Skip random rows from a table I have a table that has the column header in row 2 with the actual data starting in row 5. My question is how to read the table skipping rows 1, 3 and 4 and assign row 2 as column header?
I'm using something like below. However, would like to understand if there are better ways.
headers <- read.table("file_1", skip=1, header=F, sep =',', nrows=1, as.is=T)
df <- read.table("file_1", skip=3, header=F, sep =',')
colnames(df) <- headers

A: Not very different, but you could scan the header row and read.table for the remainder.
You are probably facing something like this.
tb <- ' 1   1  1  1  1  1  1  1  1  1   1
2  X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
3   3  3  3  3  3  3  3  3  3   3
4   4  4  4  4  4  4  4  4  4   4
5   5  5  5  5  5  5  5  5  5   5
6   6  6  6  6  6  6  6  6  6   6
7   7  7  7  7  7  7  7  7  7   7
8   8  8  8  8  8  8  8  8  8   8
9   9  9  9  9  9  9  9  9  9   9
10 10 10 10 10 10 10 10 10 10  10'

scan your file, state what=character(), how many lines are skipped and nlines to read in the column names r1. For the data r2, read.table and skip= all unneeded stuff. Skip first element each, since it's the indices. Finally use r1 to setNames of r2, and type.convert.
r1 <- scan(text=tb, what=character(), skip=1, nlines=1)[-1]
r2 <- read.table(text=tb, skip=4)[-1]

res <- r2 |>
  setNames(r1) |>
  type.convert(as.is=TRUE)

res
#   X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
# 1  5  5  5  5  5  5  5  5  5   5
# 2  6  6  6  6  6  6  6  6  6   6
# 3  7  7  7  7  7  7  7  7  7   7
# 4  8  8  8  8  8  8  8  8  8   8
# 5  9  9  9  9  9  9  9  9  9   9
# 6 10 10 10 10 10 10 10 10 10  10

Note: It depends a little on how the data is stored in the file and you probably have to customize the skip='s.


text:
Q: How to run Jsch multiple commands from shell-channel using String input instead of console I am writing a program using JSch library, and have to open a shell channel and execute few commands that are stored in String.
I need to feed the input commands from String variable rather than console.
I have come across a post Jsch : Command Output unavailable
In code given, its working fine for commands like pwd,whoami etc, but its going for a hang when i am trying to do a sudo -u hiveuser -i.
Here is the code:
public static void main(String[] args) throws Exception
    {
        JSch jsch = new JSch();
        String host = "my.host.server";
        String user = "myLoginId";
        String pswd = "myPASSword";

        Session session=jsch.getSession(user,host, 22);
        session.setPassword(pswd);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setConfig("PreferredAuthentications","publickey,keyboard-interactive,password");
        session.connect();
        System.out.println("Connected");

        Channel channel = session.openChannel("shell");
        OutputStream ops = channel.getOutputStream();
        PrintStream ps = new PrintStream(ops);
        channel.connect();
        ps.println("sudo -iu hiveuser");
        ps.println(pswd);
        ps.println("hive");
        ps.println("desc table myHiveTable;");
        ps.flush();
        ps.close();

        InputStream in = channel.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        System.out.println("Opening...");

        String jarOutput;
        while ((jarOutput = reader.readLine()) != null)
            System.out.println(jarOutput);
        reader.close();
        channel.disconnect();
        session.disconnect();

    }

A: You could try echoing in the password:
echo password | sudo -iu hiveuser --stdin


text:
Q: can ActorRef be used as Map key I was trying to use the ActorRef as key of Map, but this seems not a correct choice
with actor passed through context:
persistor = context.actorOf(persistenceProps)

the key value seems changed.
what is the reason ?
[case1-primary] Primary actor: Actor[akka://Step5PrimaryPersistenceSpec/user/case1-primary#533153706]
[case1-primary] Primary persi: **Actor[akka://Step5PrimaryPersistenceSpec/user/case1-primary/$a#728170290]**
[case1-primary] Primary sending persist message: Actor[akka://Step5PrimaryPersistenceSpec/user/case1-primary/$a#728170290] <- Persist(foo,Some(bar),0)
[case1-primary] Primary Retry message Persist(foo,Some(bar),0) -> Actor[akka://Step5PrimaryPersistenceSpec/user/case1-primary/$a#728170290]
[case1-primary] Persisted ack +1 **Actor[akka://Step5PrimaryPersistenceSpec/system/testActor3#-426557875]** 0

Tried using ActorPath, same thing: seems persistor  is not referenced but instead newly created in side Primary. don't know why
The message passing are all okay, its just the "key" is different makes my code treat them as different actor

A: Looking at the source code for the abstract class ActorRef shows that it implements hashCode and equals as well as extending java.lang.Comparable[ActorRef], so it should work fine as a key in both hashed and sorted maps as well as in hashed and sorted sets.


text:
Q: Prove the solution of differential equation is an odd function and can't be extended on $\mathbb{R}$
Prove that the solution to Cauchy's problem
$$
\begin{cases}
y'=y^2+x^2\\
y(0)=0
\end{cases}
$$
is an odd function, and that this solution can't be extended on $\mathbb{R}$.

I tried to substitute $y(x)$ with $-y(-x)$ and check if cancels out:
$$
\begin{align}
(-y(-x))'=(-y(-x))^2+x^2\\
y'(-x)=y^2(-x)+(-x)^2 && \text{substiute } t=-x\\
y'(t)=y^2(t)+t^2
\end{align}
$$
I think that proves the first part.

As for the second part of the question:
let $y$ be a solution to the Cauchy's problem, then:
$$
\begin{align}
y'=y^2+x^2\\
y'\leq y^2\\
\int \frac{dy}{y^2}\leq \int dx\\
\frac{-1}{y}\leq x+c\\
\frac{1}{y}\geq -x+c\\
y\geq \frac{1}{-x+c} \stackrel{x\rightarrow c}{\longrightarrow}\infty
\end{align}
$$
therefore $y$ does not extend on $\mathbb{R}$. Is that correct?

A: You almost got it correctly:

*

*You have only proven that $-y(-x)$ is also a solution. You need to patch this result together with a uniqueness result to achieve that $-y(-x)$ is in fact equal to $y(x)$.

*You got two mistakes with the inequality signs but they cancel each other out...
$$
\begin{align}
y'=y^2+x^2\\
y'\color{red}{\geq} y^2\\
\int \frac{dy}{y^2}\geq \int dx\\
\frac{-1}{y}\geq x+c\\
\frac{1}{y}\leq -x+c\\
y\color{\red}{\geq} \frac{1}{-x+c} \stackrel{x\rightarrow c}{\longrightarrow}\infty
\end{align}
$$
Additionally, to achieve the last line, you should give an explanation why $y>0$, which is straightforward for $x>0, y(0)=0$ and $y'(x)>0$.


text:
Q: I need help to verify my answer. Analyze the running time for the function int func2(int n) {
    int i, j;
    int sum;
    arr = new int[n];

    for (i = 0, j = 1; i < n; i++, j *= 2) {
        arr[i] = j;
    }

    sum = 0;
    for (i = 0; i < n; i++) {
        for (j = 1; j <= arr[i]; j++) {
            sum += (i + j);
        }
    }

    delete []arr;
    return sum;
}

My thinking:
1st loop  runs n times. so running time is theta of N.  0(n) +
2nd loop
inner loop runs. j times which j= 1+ 2 + 4 + 8.   thats the sum of n(n+1) (2n+1)/6 ==> theta n^3
so Total Running time =  0(n)+ 0(n^3)
Please comment on my answer and let me know if my logic is correct or I am missing something. I am very new to programming.

A: The first loop is O(n).
After running the first loop,
arr = [1, 2, 4, 8, ... , 2^(n-1)]

So, the second loop is
O(1+2+4+ ... +2^(n-1)) = O(2^n - 1) = O(2^n)

Total complexity is
O(n + 2^n) = O(2^n)

A: The 1st loop is O(n), the 2nd is O(n) and the 3rd is 1+2+4+... = 2^n - 1.
Therefore, the total is O(n) + O(n 2^n) = O(n 2^n).


text:
Q: basic graylog search - have input pulling sophos xg logs, cannot do a simple search on data that is clearly present short version:
I try and search on something that is clearly logged, namely: "roblox" which is in the last line of log message

it does not find it:

I've tried all your obvious "roblox" "roblox" but it either matches everything or nothing. How can I make this search work please?


text:
Q: Select Shape on SlideMaster in PowerPoint 2007 I am working on a plugin for PowerPoint ,which interacts with it when PowerPoint in SlideMaster view.
Depends on content, I need to select Shapes on either SlideMaster or on CustomLayouts.
I have managed to Select them on CustomLayouts, but I did not manage to do that, when Shapes are located on SlideMaster.
I tried to use following approaches:
First approach
presentation.Designs[1].SlideMaster.Shapes[1].Select();

This approach works only when user manually selects a particular slide master.
Otherwise i get the exception:

"Shape (unknown member) : Invalid request. To select a shape, its view must be active."

Second approach
presentation.Application.ActiveWindow.View.Slide = document.Designs[2].SlideMaster;

When I use this approach I get the following exception:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

I did not find any ways to activate a SlideMaster to select shapes on it.
Are the any ways to do that?
Thank you in advance.

A: To select anything in PowerPoint, you need to manage the window's view. This will allow you to select the first shape on the slide master by switching the view first:
For PowerPoint 2007:
CommandBars.ExecuteMso ("ViewSlideMasterView")
DoEvents
ActivePresentation.SlideMaster.CustomLayouts(1).Select
SendKeys ("{UP}")

The non-SendKeys method that should work but doesn't on 2007 (tested OK on PowerPoint 2016):
ActiveWindow.ViewType = ppViewMasterThumbnails
With ActiveWindow.View.Slide
  .Shapes(1).Select
End With

As an aside, do you actually need to select the object? Depending on what you're doing with it, you might not even need to select it and hence don't need to manage window views. For example, if you want to copy it or format it, you don't need to select it. If you want to group it with something else then you do need to select it first.


text:
Q: Comparing two samples in mixtools I have 16 experiments performed under different conditions and I would like to compare them between each other. Each experiment has 5-6 samples (cells). Each cell produces hundreds of data points each (adhesion force data). When I make a histogram of the log adhesion force it seems I have a skewed distribution. I have fitted this distribution using 2 or 3 Gaussian curves using the mixtools in R. Any idea how I can determine statistically if one experiment has larger adhesion forces than another?
For example in the attached pictures I am showing four histograms that compile the information of adhesion forces with silicon. Each histogram has associated a value of sigma, mu and lambda. I would like to know, for example, if the adhesion with silicon in 1 is statistically different from the adhesion in gold.


text:
Q: Pandas for loop on index I have a pandas dataframe that is indexed by some non-unique non-contiguous id numbers.

x
  class 'pandas.core.frame.DataFrame'
  Int64Index: 814061 entries, 8536896 to 8498857
  Data columns (total 1 columns):
  received    814061  non-null values
  dtypes: datetime64ns

x['received'] are timestamps that aren't all the same length.
x.ix[i] might have len() == 20
x.ix[j] might have len() == 32.

for any x.ix[i] I can fit the timestamps into a [0,1] range with
df['totalseconds'] = x.ix[i]['received']-x.ix[i]['received'].min()
y = x.ix[i]['received'].max()-x.ix[i]['received'].min()
z = timedelta.total_seconds(y)
df['seconds'] = df['totalseconds'].apply(lambda x: x / timedelta64(1, 's'))
df['norm'] = df['seconds']/z

I am trying to normalize my timeperiods for each index in x. But am having trouble for some reason.
tldr; How do I get all my timestamps into a [0, 1] range, by index id?


text:
Q: Ruby on Rails Regex Invalid I'm trying to create a regex for correct username validation in Ruby on Rails but for some reason I am doing something incorrect where all username inputs are invalid.  I am allowing for upper-case characters, lower-case characters, numbers, and underscores.
Ruby on Rails name validation regex code:
validates :name, :format => {:with => /\A[A-Za-z\d_]\z/}

What am I doing wrong?
Thanks

A: validates :name, :format => {:with => /^[A-Za-z0-9\_]+$/}

Nice page to test regular expressions in ruby: http://rubular.com/

A: # \A[A-Za-z\d_]\z
#
# Options: ^ and $ match at line breaks
#
# Assert position at the beginning of the string «\A»
# Match a single character present in the list below «[A-Za-z\d_]»
#    A character in the range between "A" and "Z" «A-Z»
#    A character in the range between "a" and "z" «a-z»
#    A single digit 0..9 «\d»
#    The character "_" «_»
# Assert position at the very end of the string «\z»

This is your expression. Do you really want to match a single character?
I believe that :
/^\w+$/

this is what you are looking for. \w is a shorthand character class for what you have written. The above regex will match a string which consists only of A-Za-Z0-9_


text:
Q: OSStatus error -4 I am creating document based app and I have strange problem - I can't open files which I saved. Each time I receive this error: "The document /name/ could not be opened". Here is output from NSError: The operation couldn't be completed. (OSStatus error -4.)
Error Domain=NSOSStatusErrorDomain Code=-4 "kCFMessagePortTransportError / kCSIdentityDeletedErr / unimpErr:  /  / unimplemented core routine"

And my document class:
import Cocoa

class Document: NSDocument {
var saved: String = ""
let encoding = NSUTF8StringEncoding
override init() {
    super.init()
    // Add your subclass-specific initialization here.
}

override func windowControllerDidLoadNib(aController: NSWindowController) {
    super.windowControllerDidLoadNib(aController)
    // Add any code here that needs to be executed once the windowController has loaded the document's window.
}

override class func autosavesInPlace() -> Bool {
    return true
}

override func makeWindowControllers() {
    // Returns the Storyboard that contains your Document window.
    let storyboard = NSStoryboard(name: "Main", bundle: nil)
    let windowController = storyboard.instantiateControllerWithIdentifier("Document Window Controller") as! WindowController
    self.addWindowController(windowController)

}

override func dataOfType(typeName: String) throws -> NSData {
    saved = "tekst"
    let dict: [String : AnyObject] = ["saved" : saved]

    let data: NSData = NSKeyedArchiver.archivedDataWithRootObject(dict)
    return data

}

override func readFromData(data: NSData, ofType typeName: String) throws {
    let dict: NSDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(data)! as! NSDictionary
    print(dict.objectForKey("saved")!)
    print("^^")

    let e = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
    print("localized desc: ")
    print(e.localizedDescription)
    throw e
}
}

I really can't find any solution.


text:
Q: Compute and fill an array in parallel As part of a signal processing task, I am doing some computation per frequency step.
I have a frequencies list of length 513.
I have a 3D numpy array A of shape (81,81,513), where 513 is the number of frequency points. I then have a 81x81 matrix per frequency.
I want to apply some modification to each of those matrices, to end up with a modified version of A I'll name B here, which will also be of shape (81,81,513).
For that, I start pre-allocating B with :
B = np.zeros_like(A)

I then loop over my frequencies and call a dothing function like:
for index, frequency in enumerate(frequencies):
   B[:,:,index] = dothing(A[:,:,index])

The problem is that dothing takes a lot of time, and ran sequentially over 513 frequency steps seems endless.
So I wanted to parallelize it. But even after reading a lot of docs and watching a lot of videos, I get lost in all the libraries and potential solutions.
Computations at all individual frequencies can be done independently. But in the end I need to assign everything back to B in the right order.
Any idea on how to do that?
Thanks in advance
Antoine

A: Here I would use a shared array using shared_memory, as there's no need to protect write access if no two loop iterations ever use the same memory address. I eliminated the second array to shorten the example (only construct a single shared array), and I re-ordered the array shape to better preserve memory-aligned access.
from multiprocessing import Pool
from multiprocessing.shared_memory import SharedMemory
import numpy as np
import numpy.typing as npt
from typing import Any
from time import sleep

def dothing(arr: np.ndarray, t_func: Any) -> np.ndarray:
    sleep(.05) #simulate hard work
    return arr * 2

def dodothing(args: tuple[int, Any]):
    global arr
    index = args[0]
    t_func = args[1]
    arr[index] = dothing(arr[index], t_func) #write result back to self to avoid need for 2 shared arrays

def init(shm: SharedMemory, shape: tuple[int, ...], dtype: npt.DTypeLike):
    global arr
    arr = np.ndarray(shape, dtype=dtype, buffer=shm.buf)

if __name__ == "__main__":
    _A = np.ones((513,81,81), np.float64) #source data

    t_funcs = ["some transfer function"] * _A.shape[0] #added example of passing some data + an index

    nbytes = _A.size * _A.itemsize
    dtype = _A.dtype
    shape = _A.shape

    shm = SharedMemory(create=True, size=nbytes)

    A = np.ndarray(shape, dtype=dtype, buffer=shm.buf)

    A[:] = _A[:] #copy contents into shared A

    with Pool(initializer=init, initargs=(shm, shape, dtype)) as pool:
        pool.map(dodothing, enumerate(t_funcs)) #enumerate returns tuple[int,Any] each loop

    print(A.sum()/_A.sum()) #prove we multiplied all elements by 2

    shm.close()
    shm.unlink()

multiprocessing.Pool is a bit funny sometimes in what can be a valid argument to a target function, so I tend to share things like Lock, Queue, shared_memory etc. via the pool's initialization function, which accepts arguments just like Process does.


text:
Q: Get domain names from IP addresses from access.log Actually I want to see people from which domain access my website. I want to generate the domain names from IP addresses in the Apache access.log file.
How can I do this? There are around 54 log files. I concatenate all the files into one.
This is a Unix server. I have to use a apache log file analyzer. So i use webalizer but it is does not resolve IP to domain names.

A: I wrote a simple script for this a long while back. It's less than perfect and has a few failure modes, but does well enough for casual inspection. I've never been bothered to improve it, but perhaps someone else will.
#!/bin/bash

while read junk
do
        echo -n "$junk "
        dig +short -x $junk
done

Use it as such:
cut -f 1 -d ' ' access.log | sort | uniq | ips.sh

A: If you are using Windows you can parse the concatenated log file with a script, performing "nslookup" on each IP.
if wscript.arguments.count > 0
then
  logname = wscript.arguments(0)
  set fs = wscript.createobject("scripting.filesystemobject")
  set readstream = fs.opentextfile(logname, 1, 0, 0)
  while not readstream.atendofstream str = readstream.readline ' parse str with RegEx object to get IP
    set shell = wscript.createobject("wscript.shell")
    shell.run "nslookup " & ip & " > temp.txt", 0
    set lookupstream = fs.opentextfile("temp.txt", 1, 0, 0)
    lookup = lookupstream.readall ' parse lookup info
    lookupstream.close
  wend
  readstream.close


text:
Q: see the below code but getCoulmnName is not taking index i?help me package pack;

import java.sql.*;

class Rsmd {
    public static void main(String args[]) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection(
                    "jdbc:oracle:thin:@10.23.0.100:1521:esgdb10", "scott",
                    "tiger");

       PreparedStatement ps = con.prepareStatement("select * from employee");
                        ResultSet rs = ps.executeQuery();
                        ResultSetMetaData rsmd = rs.getMetaData();
            System.out.println                              ("Totalcolumns: "rsmd.getColumnCount ());
            int x = 0;
            x = rsmd.getColumnCount();
            for (int i = 0; i < x; i++) {
                System.out.println("Column Name of 1stcolumn: "+ rsmd.getColumnName(i));
System.out.println("Column Type Name of column: "
                        + rsmd.getColumnTypeName(i));/*here it is not taking index i */
 /* i want to display all the column name of a record*/
            }
            con.close();

        } catch (Exception e) {
            System.out.println(e);
        }

    }
}

In the above code, used oracle driver and i wanted to display all column names of a record.for this i used index-i but the getColumnName is not supporting index-i.pls help me.

A: ResultSetMetaData.getColumnName(int) is one-based.
So your iteration should start at 1 and end at getColumnCount(), inclusive:
int x = rsmd.getColumnCount();
for (int i = 1; i <= x; i++) {
    System.out.println("Column Name of 1stcolumn: " + rsmd.getColumnName(i));
    System.out.println("Column Type Name of column: " + rsmd.getColumnTypeName(i));
}