text:
Q: How would I write numpy.tensordot in c++? I'm trying to replicate numpy.tensordot in c++. The example in the numpy documentation shows a nested loop that I can get to work, but what if instead of
c = np.tensordot(a,b, axes=([1,0],[0,1]))

I want to do:
c = np.tensordot(a,b, axes=([1,2],[0,1]))

What would that new nested loop look like in python?  And is there an easier/faster way of doing this operation in c++? Right now I'm using the same nested "for" loops with std::vector's in c++. I've seen a few libraries that might help, but I'm trying to use just the c++ standard library.
Here is that numpy example, and the link to the documentation: https://numpy.org/doc/stable/reference/generated/numpy.tensordot.html
Examples

A "traditional" example:

>>>
a = np.arange(60.).reshape(3,4,5)
b = np.arange(24.).reshape(4,3,2)
c = np.tensordot(a,b, axes=([1,0],[0,1]))
c.shape
(5, 2)
c
array([[4400., 4730.],
       [4532., 4874.],
       [4664., 5018.],
       [4796., 5162.],
       [4928., 5306.]])
# A slower but equivalent way of computing the same...
d = np.zeros((5,2))
for i in range(5):
  for j in range(2):
    for k in range(3):
      for n in range(4):
        d[i,j] += a[k,n,i] * b[n,k,j]
c == d
array([[ True,  True],
       [ True,  True],
       [ True,  True],
       [ True,  True],
       [ True,  True]])

Thank you

A: I find rewriting to np.einsum first is helpful as the resulting for loop code looks quite similar conceptually:
a = np.random.rand(16, 8, 2)
b = np.random.rand(8, 2, 1)

c =  np.tensordot(a, b, axes=([1,2],[0,1]))

# same thing written with einsum
c_ein = np.einsum("ijk,jko->io", a, b)

# same thing done with for loops,
# notice how we can use the same letters and indexing as einsum
c_manual = np.zeros((16, 1))
for i in range(16):
    for o in range(1):
        # j and k are summed since they don't appear in output
        total = 0
        for j in range(8):
            for k in range(2):
                total += a[i, j, k] * b[j, k, o]
        c_manual[i, o] = total

assert np.allclose(c, c_ein, c_manual)


text:
Q: Summarize a table with R I am working on a dataframe...these are the first lane
           n      Sex área         perímetro  breed
1         54922    2 165.447       91.636       1
2         54922    2 295.479       85.899       1
3         54922    2  90.824       40.798       1
4         54922    2 385.859      110.012       1
5         54922    2  37.062       24.430       1
6         54922    2 189.638       87.498       1
7         54922    2  20.066       21.923       1
8         54923    2  19.807       23.540       1
9         54923    2 189.212       80.037       1
10        54923    2 342.065      110.022       1

I want to summarize this table by making mean of column 4and 5 (area and perimeter) by merging row of each repetition of the same individual (n).
 Can anybody suggest some function?

A: By merging, do you mean grouping by individual?
dplyr package:
library(dplyr)
df %>%
  group_by(n) %>%
    summarise(área = mean(área),
              perímetro =mean(perímetro))

Output:
Source: local data frame [2 x 3]

      n     área perímetro
1 54922 169.1964  66.02800
2 54923 183.6947  71.19967

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dialogflow: reference to output context in intent (ie what's this NodeJS Client Library for?) In my NodeJS Dialogflow fulfillment, I want to reference an output context parameter from an intent from 2 requests ago within the session.
The queryResult of the latest request doesn't have that data. And the samples only seem to process WebhookRequest and WebhookResponse (
reference: https://dialogflow.com/docs/reference/api-v2/rest/v2beta1/WebhookResponse  )
If I can access https://dialogflow.com/docs/reference/api-v2/rest/v2beta1/projects.agent.sessions.contexts/get I may be able to do it. But I don't quite understand if that implies mixing https://github.com/dialogflow/fulfillment-webhook-nodejs/blob/master/functions/index.js  with this Client Library:
https://github.com/googleapis/nodejs-language .
In other words, it's not clear to me what the purpose of https://github.com/googleapis/nodejs-language is. Is nodejs-language intended to substitute actions-on-google fulfillments (in the format of https://github.com/dialogflow/fulfillment-webhook-nodejs/blob/master/functions/index.js ) ?

A: There is a lot going on here, and it isn't quite clear why you think things fit together the way you do.
The nodejs-language library is used to access Google's Natural Language API that runs as part of the Google Cloud Machine Learning API family. This is a completely separate product from the Google Assistant, Actions on Google, and Dialogflow systems. It is meant as an API for people who are looking for a pre-trained AI that can do things like sentiment and syntax analysis. It is not meant as a substitute for any part of the AoG or Dialogflow platform.
As long as the context set two requests ago was set with a lifetime more than 2, and wasn't cleared in between, then it still should be valid and sent to your fulfillment webhook. Since it sounds like you're using Dialogflow V2, you should be able to get all the currently valid contexts as part of the request that is sent to your fulfillment webhook by looking at the queryResult.contexts object in the request body.
If you're using the fulfillment-webhook-nodejs library that you referenced in your post, this should be available to you in the inputContexts variable.


text:
Q: Exchangelib read emails from a service account without personal login I would like to read the inbox of a shared service account. The service account inbox is a shared inbox and does not have a password per-se. I can log in and read my personal inbox using this:
from exchangelib import DELEGATE, Account, Credentials
import pytz
from datetime import datetime, date, time
now = datetime.now() # current date and time
timestr = now.strftime("%m-%d-%Y, %H.%M.%S")

credentials = Credentials(
    username='me@company.org',
    password='Password1'
)
a = Account(
    primary_smtp_address='me@company.org',
    credentials=credentials,
    autodiscover=True,
    access_type=DELEGATE
)
print('im in')
key = 'Filter Word'
midnight = datetime.combine(datetime.today(), time.min, pytz.UTC)
for item in a.inbox.filter(datetime_received__gte=midnight, subject__icontains=key).order_by('-datetime_received')[
            :30]:
    print(item.subject)

I think the answer to my question lies somewhere in the credentials portion. I have been able to read the shared inbox by using my personal credentials and inputting the inbox address in the primary_smtp_address field. Like this:
    credentials = Credentials(
    username='me@company.org',
    password='Password1'
)
a = Account(
    primary_smtp_address='sharedinbox@company.org',
    credentials=credentials,
    autodiscover=True,
    access_type=DELEGATE
)

This works great, however, if (for some reason) my credentials no longer become valid at the company, I would like the script to still run. Is there a way to do this?

A: If you don't want to access the shared account using a personal account, you should create a service account in Exchange and use that to login instead.
You cannot access the shared account without some sort of authentication.


text:
Q: Sharepoint MOSS customised v's uncustomised If Microsoft built MOSS so that all data is written to the SQL Server database, why do all best practices for development suggest to keep files etc outside of the database, i.e. on the filesystem?
All the best

A: I would say that all best practices don't say that you should use the file system for storing files. It will always depend on the situation. Storing files on the file system is fine when you have a single server, but then you have to manage replication when the files need to be on more than one server. Backing up a database is typically easier than a database and files. All of these situations can be managed, but you need to be flexible.

A: This is a philosophical item. Transactional integrity is a benefit of storing the files in the DB. With that comes downsides such as ballooning transaction logs.
I would not be surprised if, in future versions of Sharepoint, MS gave you an option to store the files 'outside the database' by using the filestream feature of SQL 2008.

A: Because of performance issues: save a round-trip to the database just to fetch your page layout, in the detriment of performance.
On the other hand, using files on the local file system for performance reduces customization options.

A: Keeping the files in the database is necessary if you wish to have users of the website editing those files. SharePoint is designed for most of those files to be editable, so they are storable in the database.
If you as an application architect know that some high use files (page layouts, masterpages etc) are not going to be edited except by a solution release, you have the option to store the pages on the filesystem.
Storing on the files system has small improvement read in access performance as a database round trip is not required. The masterpage, for example is going to be needed for every page in the website, so having it stored on the file system is going to improve performance during high user demand.
The fact the SQL 2008 has the ability to manage files "outside" the database shows that this feature is not just desirable for SharePoint.

A: Keeping SharePoint pages uncustomized allows one instance of the page to be compiled on the first execution, then kept in memory and reused for all pages of the same kind. The reason why customized pages do not share this behavior is because they are unique, and once an ApplicationDomain loads a dll it can't be unloaded.  Therefore customized pages are parsed on every request.

A: Where did you get those "best practices"?
In my experience with MS and MOSS I should say that never heard of such best practices and except for a very particular case... I'd say that this is not a good practice.
Your deploy is not easy this way... admin users have to know where to find which file to modify, backups are like hell, etc
But, as I say... may be in a particular case It could be useful.

A: The SharePoint has a techniec called ghosing which is caching pagings in file system.


text:
Q: What does `a = b()` mean when both `a` and `b` are of class `X`? I'm reading an article on rvalue-references, but I've become confused by the following excerpt:
X foo();
X x;
// perhaps use x in various ways
x = foo();

Here, X is some user-defined type.
I know that X foo(); will call X's constructor, and I'm pretty sure X x; will not.
However, what does the line x = foo(); mean? Is there a constructor called? And what would x = foo; do?
Try as I might, I couldn't figure out the right words to look up in order to find out what this code means.

A:
I know that X foo(); will call X's constructor

No, it won't. It will declare (but not define) a function named foo, which takes no arguments, and returns an X.

and I'm pretty sure X x; will not.

Yes it will, if it has one. With the above corrections to your understanding, the answer to your question should be evident now, but:

However, what does the line x = foo(); mean?

It means call the function foo, and store the result in x.


text:
Q: Loading instrument I'm new to JAVA MIDI and i have come across a problem .I want to load a MIDI file then set a couple of labels with the name of each instrument that was used for each track.For example if the MIDI file has 5 tracks(each track has only one instrument ) then i will get 5 labels each one having the name of the instrument used on each track.
Is there any way to see what instrument was used for each track in a MIDI file(function,method...)?

A: *

*Get a Sequence for the MIDI file.

*Get the Track objects of the sequence.

*Get the MidiEvent objects of the track.

*Get the MidiMessage of the event.  That will contain the information on (among other things) an instrument change.

A: Once you have isolated each track in the arrangement, there are a two different ways to determine the instrument which should play it.
One is that a MIDI meta message with ID 0x04 will appear with the instrument name as a string. See this great page detailing the MIDI file format for details.
The second way is that a MIDI program change message will appear at the beginning of the track. Assuming that the MIDI files are set to use GM (general MIDI) instruments, you can associate data of the program change message to a GM instrument.
Note that program changes are allowed to appear anywhere in a MIDI track, and the sequencer should deal with them accordingly. Although most MIDI files you'll see in the wild won't use program changes in the middle of tracks, keep in mind that it is allowed by the standard and may occur.


text:
Q: Grafana - Loki data source receiving 400 Unauthorized error EKS 1.23, Prometheus-stack with Grafana v7.3.5
Installed Loki v2.7.3 and now trying to connect Grafana to Loki.
I added Loki datasource from Grafana and configured the loki-gateway service url:

Then I get the following error:
Loki: Bad Request. 400. Authentication to data source failed
From loki-gateway pod's logs:
10.7.60.60 - - [01/Mar/2023:14:18:53 +0000]  401 "GET /loki/api/v1/label?start=1677679732842000000 HTTP/1.1" 10 "-" "Grafana/7.3.5" "10.7.127.117, 10.0.60.21, 10.0.60.21"

NOTE: loki-gateway basicAuth is disabled by default, hence no need to add user & password to Loki data source in Grafana.
Tried:

*

*Enable loki-gateway basicAuth and pass the credentials through Grafana Loki Data Source.

*Skip tls verification
Both ended up with the same error.


text:
Q: BMP Header - MSDN vague, is my endianness wrong? I'm writing a program to create an image for some data from my chemistry lab. We're working on emissions from elements and such, and the data write-up to include examples of what the frequency bands looked like through the spectroscope. I thought it'd be neat to make a program to do it for me, as opposed to colored pencils, so it's all tidy and stuff. Also, I don't have colored pencils.
I'm storing the image data as RGB values in an int array, of length width*height of the image I want, width being 320, height is 50. In the end I'm writing them to file as 24 bit BGR-ordered pixels.
Before I write the data to file, I of course attempt to write the BMP header. MSDN had a chart to show the general ordering of the file sections, which included something about RBGQuads, but in the paragraph explanations didn't describe how to use them. I think they're optional? I find this chart showing what I expected was the only mandatory part of the header:
http://www.fastgraph.com/help/bmp_header_format.html, so I think I'm on the right track there.
So then I get to the endianness, because my files are always "damaged or corrupt" when trying to open with Paint or in the Windows image viewer.
All sources say BMP headers are little endian. I've tried swapping the order of the bytes both ways when I write and the files still can't be opened. Are there other common culprits for home-brewed corrupt files?
Here's where I store my header infos:
typedef struct
{
  char type[2];
  unsigned int fsize;
  unsigned short res1;
  unsigned short res2;
  unsigned int data_offset;
} BMPFILEHEADER;

typedef struct
{
  unsigned int sizebytes;
  int  width_pix;
  int  height_pix;                   // negative for top down.
  unsigned short  planes;            // must be 1
  unsigned short  bits_per_pix;
  unsigned int compression;          // zero for BI_RGB (uncompressed)
  unsigned int SizeImage;            // may be set to 0 for BI_RGB images.
  int  pix_per_meter_x;
  int  pix_per_meter_y;
  unsigned int color_used;           // set to 0
  unsigned int color_important;      // set to 0
} BMPINFOHEADER;

And of course I write them in that order. -- type is char[] because it has to be the values 'B' 'M' anyway.
First I tried writing them with fwrite():
  fwrite ( &header , 1 , 14 , fhandle );
  fwrite ( &headerext , 1 , 40 , fhandle );

And then I tried writing them like this:
  fputc ( 'B' , fhandle );
  fputc ( 'M' , fhandle );
  fw_little_end ( fhandle , &header.fsize , 4 );
  fw_little_end ( fhandle , &header.res1 , 2);
  fw_little_end ( fhandle , &header.res2 , 2);
  fw_little_end ( fhandle , &header.data_offset , 4);

where fw_little_end() looks like this:
void fw_little_end ( FILE * fhandle , void * data , int size )
{
  int i;
  char * cdata = data;
  for ( i = size; i > 0; i-- )
  {
    fputc ( *(cdata+i-1) , fhandle );
  }
}

It may be that originally it was written to file little endian and that my fw_() function is mis-named, but I've also tried it from size-0 and from 0-size just to be sure.
In case it sounds relevant, this is where the data is written:
  int shift1 = 256;
  int shift2 = 256*256;
  for ( i = 0; i < img_size; i++)
  {
    fputc ( (unsigned char) (data[i]%256) , fhandle ); // B
    fputc ( (unsigned char) (data[i]/shift1)%256 , fhandle ); // G
    fputc ( (unsigned char) (data[i]/shift2)%256 , fhandle ); // R
  } // theoretically B only needs the typecast, not the %256 but oh well lol.

The post is already long, hopefully I've included enough relevant code. I apologize because I know that there is a lot of info out there, it just doesn't make sense to me beyond this. If there's a better idiom for how to do these sorts of things, I'd love to be pointed in the right direction.
And so, I thank you for any and all input.

A: I am posting a direct answer:
/* ======================================================================================== */
BOOL SaveBitmap24(LPCTSTR pszFilename, LPBYTE pPixelColorTriplets, INT nWidth, INT nHeight)
{
    BOOL bState = FALSE;
    // sizes
    INT nOfsetToPixel = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPCOREHEADER);
    INT nPixelSize = nWidth * nHeight * 3;
    INT nFileSize = nOfsetToPixel + nPixelSize;
    // setup bitmap file header --------------
    BITMAPFILEHEADER bmFileHeader = { 0 };
    // "BM" signature
    bmFileHeader.bfType = 0x4D42;
    bmFileHeader.bfOffBits = nOfsetToPixel;
    bmFileHeader.bfSize = nFileSize;
    // setup bitmap info header --------------
    BITMAPCOREHEADER bmCoreHeader = { 0 };
    bmCoreHeader.bcSize = sizeof(BITMAPCOREHEADER);
    bmCoreHeader.bcWidth = nWidth;
    bmCoreHeader.bcHeight = nHeight;
    bmCoreHeader.bcBitCount = 24;
    bmCoreHeader.bcPlanes = 1;
    // write file -----------------------
    FILE *fileBitmap = fopen(pszFilename, _T("wb"));
    if (fileBitmap)
    {   fwrite(&bmFileHeader, sizeof(BITMAPFILEHEADER), 1, fileBitmap);
        fwrite(&bmCoreHeader, sizeof(bmCoreHeader), 1, fileBitmap);
        fwrite(pPixelColorTriplets, nPixelSize, 1, fileBitmap);
        fclose(fileBitmap);
        bState = TRUE;
    }
    return bState;
}


text:
Q: SQL QUERY Select employee who under a specific boss A challenging question, i have table like below
EmployeeID    BossID
pic http://img16.imageshack.us/img16/7659/20130430113245.jpg
any idea to create the query so that when certain employee go in , it will query all employee under him and who is his boss

A: Try this query
You have to use CTE as Sohail has mentioned.
WITH DirectReports (bossId, EmpID, Level)
AS
(
-- Anchor member definition
    SELECT bossId, empId,
        0 AS Level
    FROM tbl
    WHERE empId = 2
    UNION ALL
-- Recursive member definition
    SELECT e.bossId, e.empId,
        Level + 1 AS Level
    FROM tbl e
    INNER JOIN DirectReports AS d
        ON e.bossId = d.empId
)
-- Statement that executes the CTE
SELECT *
FROM DirectReports;

SQL FIDDLE
| BOSSID | EMPID | LEVEL |
--------------------------
|      1 |     2 |     0 |
|      2 |     4 |     1 |
|      4 |     5 |     2 |
|      4 |     6 |     2 |

A: You should create the query using the CTE(Common table expression). For help you can read Recursive Queries
Below is just similar example you can modify as per your need but it would help.
This is a table structure.
CREATE TABLE [dbo].[Categories](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[CategoryName] varchar NULL,
[ParentId] [bigint] NULL)
This is the hierarchical query. I just created a view for it because I need to filter it more in my scenario.
    CREATE VIEW [dbo].[CategoriesWithNameHierarchy] AS WITH Categories_Tree AS
        (SELECT c.id AS 'Id' ,
            0 AS 'Level',
            c.CategoryName AS 'CategoryName',
            cast(c.CategoryName AS varchar(30)) AS 'CNameHierarchy'
           FROM Categories c
   WHERE ParentId IS NULL
   UNION ALL SELECT ChildCategories.Id AS 'Id',
                    (1 + ct.[Level]) AS 'Level',
                    ChildCategories.CategoryName AS 'CategoryName',
                    cast(ct.CNameHierarchy + '>' + ChildCategories.CategoryName AS varchar(30)) AS 'CNameHierarchy'
   FROM Categories ChildCategories,
                   Categories_Tree ct
   WHERE ChildCategories.ParentId = ct.Id)
SELECT *
FROM Categories_Tree

Hope this would help.


text:
Q: appengine-maven-plugin configuration options like jvm flags Since version 1.7.4. of Google App Engine the official appengine-maven-plugin is released by Google.
It has a task appengine:devserver to start the local development server.
This plugin seems not to have any Maven configuration options.
I wonder how I can
a) provider jvm flags
b) to disable new version check (when working offline)
Note that until now I was using the unofficial net.kindleit maven-gae-plugin like:
<plugin>
    <groupId>net.kindleit</groupId>
    <artifactId>maven-gae-plugin</artifactId>
    <version>0.9.4</version>
    <configuration>
        <disableUpdateCheck>true</disableUpdateCheck>
        <javaAgent>${env.REBEL_HOME}/jrebel.jar</javaAgent>
        <jvmFlags>
            <jvmFlag>-noverify</jvmFlag>
            <jvmFlag>-Ddatastore.backing_store=${project.basedir}/local_db.bin</jvmFlag>
            <jvmFlag>-Ddatastore.default_high_rep_job_policy_unapplied_job_pct=20</jvmFlag>
            <jvmFlag>-Drebel.spring_data_plugin=true</jvmFlag>
        </jvmFlags>
        <wait>true</wait>
    </configuration>
    <dependencies>
        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-tools-sdk</artifactId>
            <version>${com.google.appengine.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-api-1.0-sdk</artifactId>
            <version>${com.google.appengine.version}</version>
        </dependency>
    </dependencies>
</plugin>

A: I wrote the plugin, so I guess this is my fault.  The configuration is well supported for appcfg operations (like update/rollback/etc.), but I need to fix a few things obviously for the development server.  I'll get onto that and there should be an update soon.
UPDATE : I've pushed a snapshot build that supports configuration for the devserver target.  It's in 1.7.5-SNAPSHOT.
YOU WILL NEED TO READ THIS TO USE SNAPSHOT BUILDS : http://code.google.com/p/appengine-maven-plugin/

A: It looks like 1.7.5 of both the SDK and Maven plugin are now available from the normal Maven repository thus it should be sufficient to simply update those dependencies to the 1.7.5 version and omit the declaration of the SNAPSHOT repository.  The 1.7.5 maven-appserver-plugin does seem to support jvmFlags like the following:
<configuration>
    <jvmFlags>
        <jvmFlag>-Ddatastore.default_high_rep_job_policy_unapplied_job_pct=20</jvmFlag>
    </jvmFlags>
</configuration>

Yea!
Thank you to MattStep and the Google team!

A: Having exactly that issue myself. Checking the actual sources for the plugin, the DevAppServerRunner has zero support for passing extra arguments of any kind to the dev server. It looks like the best way to do it at the moment is to use the unofficial plugin.
source for DevAppServerRunner.java


text:
Q: Connecting an 8051 to a 2V SRAM I just ordered some serial ram to use with my microcontroller. My micro is actually AT89C2051-24PU and runs on 4-6VDC.
The ram 23K256-I/P (according to the datasheet) runs on 2.7 to 3.6VDC.
From my schematic, I'm trying to control the RAM with GPIO pins P1.5 through P1.7 and read the status with P1.4.
I use a diode for the return data to prevent excessive voltage from the P1.4 pin from entering the RAM (or am I being too paranoid here?)
R1 and R2 is meant to be a voltage divider so that VCC for the ram is within limits.
I believe the 8051 GPIO pins only have the values high-impedance and ground, so I added pull-up resistors to the lower voltage to give a default value of 1 to the RAM input pins (unless I set any of the values to zero in the 8051 code).
Is the schematic satisfactory, and is there a better way to do this than to rely on resistors and the diode? I don't want to overheat and possibly burn the RAM chip. The simpler the circuit, the better.


text:
Q: Safari on iOS 11.4 not sending cookies on POST requests I've been using the same code for years and things have been working very well on every browser so far:
$.ajax({
    url: '/test.php',
    data: parameters,
    dataType: 'html',
    type: 'post'
})

However, since my users started to upgrade to iOS 11.4, those who use the Private mode of Safari are having an issue with "being disconnected" from my website.
This is because ajax POST requests aren't sending any Cookies, apparently. A whole new session is created as part of that POST request (new cookies created, etc).
However, that doesn't affect anything on the GET requests themselves. They stay with the same cookies (and therefore same session), even though new cookies were set as part of the ajax POST request. It's like those ajax POST requests are "sandboxed", not affecting anything else.
Any ideas? Is this a bug on Safari on iOS 11.4 ?

A: We worked through a similar issue and figured out that it was actually related to Service Workers. From what I can tell, it's a bug in the latest version of Safari's implementation of Service Workers that causes some cookies not to be passed on POST in Private mode. For now, we have disabled our Service Worker and site functionality has returned to normal for those users.
Not sure if this is your problem or not, but it sounds very similar. Hope this helps!


text:
Q: How to make a picture clickable and then flip to a different picture? Android Studio Like in the picture of this url ( http://i.stack.imgur.com/L18ox.jpg)  (which I do not own). So basically a touch command to flip the picture to a different picture and if it matches to stay flipped but if it does not match to flip back.
Can someone please help me out. I am new to this so sorry if I stepped on anyone's toes.

A: Use a GridView and handle the onClick event for the grid items. There is FlipAnimation (gitHub) which you can apply on the item in the onClick event.

A: I think you need to use a frame layout and in the onClick() ,make the the first image Disappear and the second one appear.That will do.

A: 1.Layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <RelativeLayout
        android:id="@+id/layout_front"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="visible">
        <!--add your front layout components-->
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/layout_back"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone">
        <!--add your back layout components-->
    </RelativeLayout>
</RelativeLayout>

2.Animation class
    public class FlipAnimation extends Animation {
    private Camera camera;
    private View fromView;
    private View toView;
    private float centerX;
    private float centerY;
    private boolean forward = true;

    /**
     * Creates a 3D flip animation between two views.
     *
     * @param fromView First view in the transition.
     * @param toView   Second view in the transition.
     */
    public FlipAnimation(View fromView, View toView) {
        this.fromView = fromView;
        this.toView = toView;

        setDuration(700);
        setFillAfter(false);
        setInterpolator(new AccelerateDecelerateInterpolator());
    }

    /**
     * To reverse direction of flip animation
     */
    public void reverse() {
        forward = false;
        View switchView = toView;
        toView = fromView;
        fromView = switchView;
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        centerX = width / 2;
        centerY = height / 2;
        camera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation transformation) {
        final double radians = Math.PI * interpolatedTime;
        float degrees = (float) (180.0 * radians / Math.PI);
        if (interpolatedTime >= 0.5f) {
            degrees -= 180.f;
            fromView.setVisibility(View.GONE);
            toView.setVisibility(View.VISIBLE);
        }

        if (forward)
            degrees = -degrees; //determines direction of rotation when flip begins

        final Matrix matrix = transformation.getMatrix();
        camera.save();
        camera.rotateY(degrees);
        camera.getMatrix(matrix);
        camera.restore();
        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);
    }
}

3. A method to flip a view on user action.
public static void flipCard(View view) {
        View rootLayout = view.findViewById(R.id.layout_root);
        View cardFace = view.findViewById(R.id.layout_front);
        View cardBack = view.findViewById(R.id.layout_back);
        FlipAnimation flipAnimation = new FlipAnimation(cardFace, cardBack);
        if (cardFace.getVisibility() == View.GONE) {
            flipAnimation.reverse();
        }
        rootLayout.startAnimation(flipAnimation);
    }

4. OnClick example.
Utility.flipCard(rootView//your root view here);

A: Maybe my new library FlipView can help. It includes basic flip animation and extends ViewFlipper. I mean a fully customizable library where you will be able to swap any kind of views and layouts with any kind of animation and shapes you desire (and much more), included the Gmail image flipping.
Please have a look.


text:
Q: Read-only directory on Windows? Is it possible to create read only directory on windows so I can't create files/directories in it? I've denied all permissions for all users, set folder read-only and I can still create files and access that folder from cygwin or programmatically (Java). It effectively just denies accessing it from windows explorer and cmd.

A: You can do following these steps to set permission

*

*Right-click the folder > Properties

*Security tab > Advanced

*Click On change permission.

*Select entry and click on edit button and you can add new entry for new user

*If you want to restrict checked on deny check box whatever you want to restrict and then click ok

*if you add new entry then you have also option to set allow deny option aur also full control option .

*if you want to permission will apply on objects subfolders too then checked on be below box you will see then click ok

Hopefully, these steps may help you


text:
Q: Build a bash command with conditional parameters and cuote parameters I need to build a bash command in a script depending on some cuote or normal parameters. For example:
BAYES)
    class="weka.classifiers.bayes.BayesNet"
    A="-D -Q weka.classifiers.bayes.net.search.local.K2 -- -P 1 -S BAYES -E"
    B="weka.classifiers.bayes.net.estimate.SimpleEstimator -- -A 0.5" ;;
LOGISTIC)
    class="weka.classifiers.functions.Logistic"
    A="-R 1.0E-8 -M -1 -num-decimal-places 4" ;;
SIMPLELOG)
    class="weka.classifiers.functions.SimpleLogistic"
    A="-I 0 -M 500 -H 50 -W 0.0" ;;
SMO)
    class="weka.classifiers.functions.SMO"
    A="-C 1.0 -L 0.001 -P 1.0E-12 -N 0 -V -1 -W 1 -K"
    A1="weka.classifiers.functions.supportVector.PolyKernel -C 250007 -E 1.0" ;;
IBK)
    class="weka.classifiers.lazy.IBk"
    A="-K 1 -W 0 -A "
    A1="weka.core.neighboursearch.LinearNNSearch -A"
    A2="weka.core.EuclideanDistance -R first-last" ;;
KSTAR)
    class="weka.classifiers.lazy.KStar"
    A="-B 20 -M a" ;;
...
java -Xmx"$mem"m -cp "$WEKA_INSTALL_DIR/weka.jar"  $class -s $i -t "$file" $A "$A1" $B "$B1"

However, my problem is that in some conditions, when $A1 is empty, the "$A1" parameter is not valid. The same with "$B1". And the parameter could be in any combination ($A1 with $B1, $A1 without $B2, ...).
Also I've tried include $A1 in $A as following:
A="-C 1.0 -L 0.001 -P 1.0E-12 -N 0 -V -1 -W 1 -K \"weka.classifiers.functions.supportVector.PolyKernel -C 250007 -E 1.0\""

and execute:
java -Xmx"$mem"m -cp "$WEKA_INSTALL_DIR/weka.jar"  $class -s $i -t "$file" $A

but this doesn't work.

A: You cannot safely and reliably store multiple arguments in a single string; you need to use arrays; this is their intended use case. Make sure to initialize any arrays that won't be used, so that they "disappear" when expanded.
# If A is undefined, "${A[@]}" is an empty string.
# But if A=(), then "${A[@]}" simply disappears from the command line.
A=()
B=()
A1=()
A2=()

case $something in

BAYES)
    class="weka.classifiers.bayes.BayesNet"
    A=(-D -Q weka.classifiers.bayes.net.search.local.K2 -- -P 1 -S BAYES -E)
    B=(weka.classifiers.bayes.net.estimate.SimpleEstimator -- -A 0.5);;
LOGISTIC)
    class="weka.classifiers.functions.Logistic"
    A=(-R 1.0E-8 -M -1 -num-decimal-places 4);;
SIMPLELOG)
    class="weka.classifiers.functions.SimpleLogistic"
    A=(-I 0 -M 500 -H 50 -W 0.0) ;;
SMO)
    class="weka.classifiers.functions.SMO"
    A=(-C 1.0 -L 0.001 -P 1.0E-12 -N 0 -V -1 -W 1 -K)
    A1=(weka.classifiers.functions.supportVector.PolyKernel -C 250007 -E 1.0) ;;
IBK)
    class="weka.classifiers.lazy.IBk"
    A=(-K 1 -W 0 -A)
    A1=(weka.core.neighboursearch.LinearNNSearch -A)
    A2=(weka.core.EuclideanDistance -R first-last);;
KSTAR)
    class="weka.classifiers.lazy.KStar"
    A=(-B 20 -M a) ;;
esac

and always quote parameter expansions.
java -Xmx"$mem"m -cp "$WEKA_INSTALL_DIR/weka.jar" \
  "$class" -s "$i" -t "$file" "${A[@]}" "${A1[@]}" "${B[@]}" "${B1[@]}"

A: SOLUTION:
I solved all my problems using only a parameter A like this:
BAYES)
    class="weka.classifiers.bayes.BayesNet"
    A=(-D -Q weka.classifiers.bayes.net.search.local.K2 -- -P 1 -S BAYES -E weka.classifiers.bayes.net.estimate.SimpleEstimator -- -A 0.5);;
SMO)
    class="weka.classifiers.functions.SMO"
    A=(-C 1.0 -L 0.001 -P 1.0E-12 -N 0 -V -1 -W 1 -K "weka.classifiers.functions.supportVector.PolyKernel -C 250007 -E 1.0");;

java -Xmx"$mem"m -cp "$WEKA_INSTALL_DIR/weka.jar"  $class -s $i -t "$file" "${A[@]}"

A: From your question, I did:

*

*Initialized the variables

*Completed the case statement

*Removed some not required double quotes

*Defined some variables for which you did not provide values for

*backslash your double quotes if you must have then in the java command

If you need double quotes for certain variables, put these in the variables.  This way you will not have "" in your java command if the variables is empty.  I did this for A1 in case IBK.
This will get you started, modify as required:
#!/bin/bash
#

mem="512"
WEKA_INSTALL_DIR='/opt/weka'
class=""
i="value-of-i"
A=""
A1=""
B=""
B1=""
file="SOMEFILE"

case $1 in
    'BAYES')
        class="weka.classifiers.bayes.BayesNet"
        A="-D -Q weka.classifiers.bayes.net.search.local.K2 -- -P 1 -S BAYES -E"
        B="weka.classifiers.bayes.net.estimate.SimpleEstimator -- -A 0.5"
        ;;
    'LOGISTIC')
        class="weka.classifiers.functions.Logistic"
        A="-R 1.0E-8 -M -1 -num-decimal-places 4"
        ;;
    'SIMPLELOG')
        class="weka.classifiers.functions.SimpleLogistic"
        A="-I 0 -M 500 -H 50 -W 0.0"
        ;;
    'SMO')
        class="weka.classifiers.functions.SMO"
        A="-C 1.0 -L 0.001 -P 1.0E-12 -N 0 -V -1 -W 1 -K"
        A1="weka.classifiers.functions.supportVector.PolyKernel -C 250007 -E 1.0"
        ;;
    'IBK')
        class="weka.classifiers.lazy.IBk"
        A="-K 1 -W 0 -A "
        A1="\"weka.core.neighboursearch.LinearNNSearch -A\""
        A2="weka.core.EuclideanDistance -R first-last"
        ;;
    'KSTAR')
        class="weka.classifiers.lazy.KStar"
        A="-B 20 -M a"
        ;;
    *)
        # default options
        ;;
esac

echo java -Xmx${mem}m -cp $WEKA_INSTALL_DIR/weka.jar  $class -s $i -t $file $A $A1 $B $B1

Example:
./test.bash LOGISTIC
java -Xmx512m -cp /opt/weka/weka.jar weka.classifiers.functions.Logistic -s value-of-i -t SOMEFILE -R 1.0E-8 -M -1 -num-decimal-places 4

./test.bash IBK
java -Xmx512m -cp /opt/weka/weka.jar weka.classifiers.lazy.IBk -s value-of-i -t SOMEFILE -K 1 -W 0 -A "weka.core.neighboursearch.LinearNNSearch -A"


text:
Q: Choosing to keep or bin continuous variables for communicating regression results I am using logistic regression in a work setting (e.g. subscription conversion in a technology product). I would like to communicate about what independent variables a team should focus on to increase an outcome variable.
The independent variables of this regression include both continuous and categorical variables. Let's say we have these independent variables:

*

*is_cat (Categorical)

*Day_active (Continuous)

*Avg_items (Continuous)
If we run the regression with these variables "as is", communicating the variable coefficients relative to each other could be confusing. Increasing Avg_items by 1 may have a much smaller impact than increasing day_active by 1, but increasing Avg_items by X may lead to the same impact as increasing day_active by 1. This insight is somewhat hidden though since a stakeholder just looking at the coefficients might conclude increasing day_active by 1 has a higher ROI than focusing on Avg_items, even though that may not be true.
Also, it's non-intuitive comparing the coefficients of a categorical and continuous variable, especially for prioritization.
Another choice is to change Day_active and Avg_items into categorical variables so that the variables become unitless and therefore coefficients more readily comparable.
I've seen people transform continuous variables into categorical ones by looking at the distribution of the variable and splitting it at the knee in the distribution or just using quantiles, etc. Seems reasonable.
The obvious downside is that we could be losing a lot of information binning the continuous variables into categorical ones. I guess we could compare regression diagnostics between a model with the continuous variables and one with just categorical variables to quantify how much we are losing. But the loss may be worth it if it makes the results easier to explain and understandable by stakeholders.
Does this all make sense? Or are there other ideas I should be considering for communicating drivers of a product outcome using regression, or communicating headroom?

A: Dichotomozing and binning continuous variables is a poor poor idea.  Not only are the splits more or less arbitrary, but splitting continuous variables leads to residual confounding and decreases the degrees of freedom in the model (maybe not a problem in your particular example, you likely have oodles of data).  This can lead to poorer measures of model performance (like calibration).
Additionally, splitting the predictors can fool the analyst into believing noise is signal. Here is an example.  Below, I've simulated binary data and a continuous predictor.  I've binned the predictor into 5 bins and computed the means in each bin.  When I simulated that data, I made sure that as the predictor increased then so too would $E(y \vert x)$.  However, when I plot the binned data, I see a different story.  It would appear the data have a non-linear effect -- something that would fail to generalize to new data.

You seem to be vexed by apparent confusion in the interpretation of model coefficients.  Without sounding flippant, I would assume it is part of your job to explain to stakeholders what these coefficients mean, rather than leaving them to do it.  If the insight you mention is hidden, it might be worthwhile to elucidate it.
Alternatively, you can eschew model coefficients completely as their effect is somewhat obfuscated and depends on the baseline risk.  A log odds ratio of 2.0 be associated with a massive risk difference if the comparitor's risk is moderate, or it can be associated with a paltry risk difference if the outcome is certain (near 0 or 1).  Consequently, I usually report probabilities of various scenarios to try to communicate how interventions might affect risk.
For example, I might say something like "If customers had one more item in their basket on average, we might expect a p% change in probability of sign up from x% to x+p%".  This might even be a good opportunity to do some visualizing.  Because you can not realistically intervene and change predictors in an enormous way, I find this approach sufficient.
All in all, needlessly categorizing hurts rather than helps. If you're having trouble explaining model coefficients, my advice would be to take a different approach and report model probability estimates under various scenarios. Skip coefficients entirely.

A: +1 to Demetri's answer.
Skip model coefficients altogether. (Better: put them in an appendix, in case someone asks for them, and to show you did your homework.) As you write, they are hard to interpret and can be gotten wrong. But more importantly, nobody cares about your coefficients, anyway! What people care about is the impact on the observable.
So pick a few reasonable scenarios and twiddle your predictors in a meaningful (!) way. For instance, take an average user, or a modal one, and report what would be predicted happen to this user should Day_active or Avg_items be changed in a meaningful way. If your Days_active typically spans months or years, then a change by a single day will not mean much - but a change by one month or three months will mean something. If your Avg_items is in the low singletons, then increasing this by a single unit will be a meaningful change.
Also keep in mind how easy it is to affect these predictors. If it is equally easy or expensive to change Day_active by 30 days or Avg_items by 1 unit, then these changes are comparable and meaningful.
Note how the initial step of picking a scenario already amounts to a kind of binning. And that is fine in this context. Other scenarios to pick would be users on the high end of the observable (can we actually influence high-value users any more, or are they already at a "ceiling"?), or users on the low end (likely a "long tail" that only interacted once - there will likely be a large number of such users, is it worthwhile to try to reactivate them?).
Yes, this means that you need to consider the wider picture, not just your model, but also the business implications and costs or your report, and what baseline scenarios are "interesting" to look at. And in my opinion, that is how it should be. Part of our job as statisticians or data scientists is to help other people understand our results. For that, we need to understand their language and take much of the translation task on our shoulders.


text:
Q: Trailing slash when Tab auto complete in Windows 7 PowerShell I couldn't find any answer in Google search how to add a trailing slash "/" at the end of auto completion when Tab key is pressed in Windows 7 PowerShell. On my Ubuntu the slash is at the end whenever you press Tab key.

A: I recommend that you give PSReadline a try as it will do this during auto-complete along with much, much more.  I've written up a blog post on PSReadline's capabilities. I highly recommend PSReadline.


text:
Q: How can I exclude asterisk in a regex expression Noob question:
I want to find all lines that have a single quote anywhere, followed immediately by the word select
'select
followed by any number of spaces
and after the spaces, not followed by an asterisk.
I thought [^*]  would be the tail end, but I can't even get that working.
Any help?

A: You can use the following regex.
'select\s+[^*\s]

Example: https://regex101.com/r/oS2aS4/1


text: Q: Buying ASUS ROG Strix 1000W 80 PLUS Gold Power Supply I am currently in Egypt and Egypt operates on a 220V supply voltage and 50Hz. I am planning to buy ASUS ROG Strix 1000W 80 PLUS Gold Power Supply from the US using Amazon and its specifications are found here. I just need to make sure that this power supply will work safely in Egypt. Its input voltage is 100-240V ac, and hence, it can safely work with an input voltage of 220V. However, I can't find its input frequency specs. So is it safe to buy it?


text:
Q: Avoid duplicate functions for each member variable I wrote helper functions for setting vertex properties. As you can see the 3 functions are basically the same, except that each function sets a different member variable of the vertices. As it is against the DRY principle and looks ugly I would like to combine them.
void setPositions(const int offset, const sf::Vector2f (&positions)[vertexCount]) {
    int index = ensureSizeAndGetIndex(offset);
    for(int i = 0; i < vertexCount; i++) {
        vertices[index + i].position = positions[i];
    }
}

void setTexCoords(const int offset, const sf::Vector2f (&texCoords)[vertexCount]) {
    int index = ensureSizeAndGetIndex(offset);
    for(int i = 0; i < vertexCount; i++) {
        vertices[index + i].texCoords = texCoords[i];
    }
}

void setColors(const int offset, const sf::Color (&colors)[vertexCount]) {
    int index = ensureSizeAndGetIndex(offset);
    for(int i = 0; i < vertexCount; i++) {
        vertices[index + i].color = colors[i];
    }
}

Things I considered:

*

*Templates wouldn't work here as they don't handle member variables

*I could combine the first two functions by passing a bool flag of which variable to use. But that wouldn't help for the third function.

*I could add pointers to the member variables of the vertex class and an enum to choose from, but that would be too much (performance) overhead

*Lambdas maybe, meta programming maybe?

Just would be interested for the cleanest solution here.

A: If texCoords, position and color are the same type, the solution is very simple. Class member pointers.
Assuming that the class in question looks something like this:
class V {
public:

   int texCoords;
   int position;
   int color;
};

Then each one of your member functions becomes a wrapper that supplies the appropriate class member pointer. For example, setTexCoords becomes
void setTexCoords(const int offset, const sf::Vector2f (&texCoords)[vertexCount]) {
  setCommon(offset, texCoords, &V::texCoords);
}

The other two wrappers are analogous, and the common code becomes:
void setCommon(const int offset, const sf::Vector2f (&texCoords)[vertexCount],
               int V::*member) {
    int index = ensureSizeAndGetIndex(offset);
    for(int i = 0; i < vertexCount; i++) {
        vertices[index + i].*member = texCoords[i];
    }
}

Class member pointers look like regular pointers, and they share the same principle, but they're not traditional pointers, and it is necessary to fully understand how they work. For more information see your C++ book.


text:
Q: How can send array as an data using ajax Please see attached jsfiddle link, I need to collect data from multiple forms and combined the data as Single data array send it to server(spring mvc controller) to persist using ajax.post
Please let me know best way to do it, will my array be converted to Json by ajax call or I have to do some magic on it.
Thanks
http://jsfiddle.net/6jzwR/1/
<form id="form1" name="formone" class="myclass">
    <input type="text" id="txt11" name="txt11" value="name1" />
    <input type="text" id="txt12" name="txt12" value="name2" />
</form>
<form id="form1" name="formtwo" class="myclass">
    <input type="text" id="txt21" name="txt21" value="name3" />
    <input type="text" id="txt22" name="txt22" value="name4" />
</form>
<input type="button" id="button" value="Click Me" />

(function ($) {
    $(document).ready(function () {
        alert("serialize data :" + $('.myclass').length);
        var mydata = null;
        $('#button').on('click', function (e) {

            $('.myclass').each(function () {
                alert("serialize data :" + $(this).serialize());
                if ((mydata === null) || (mydata === undefined)) {
                    mydata = $(this).serializeArray();
                    alert("My data is null");
                } else {
                    mydata = $.merge(mydata, $(this).serializeArray());
                    alert("My data final data after merger " + test);
                }
            });

        });
    });
}(jQuery));

A: Try this:
var array = $('input[type="text"]').map(function() {
    return $(this).val();
}).get();

alert(JSON.stringify(array));

Demo.

A: You can put all the forms' data in an array and join them with &
var formdata = []
$('.myclass').each(function(){
    formdata.push($(this).serialize());
});
var data = formdata.join('&');

http://jsfiddle.net/6jzwR/3/


text:
Q: performance difference between while (each) and foreach in Perl The hash that I tested contains around 70000 colleges and each college contains around 20 students.
I tried it 5 times and following are the results. There is considerable difference in foreach performance and while (each) performance. Why is that so?
Code with while loop:
while ( my ($college_code, $college_info_hr) = each (%{$college_data_hr}) ) {
    while ( my ($student_num, $student_info_hr) = each (%{$college_info_hr->{'students'}}) ) {
        if($student_num < 104000) { ## Delete the info of students before 2004.
            delete $college_info_hr->{'students'}{$student_num};
        }
    }
}

Code with foreach loop:
foreach my $college_code (keys %{$college_data_hr}) {
    foreach my $student_num (keys %{$college_data_hr->{$college_code}{'students'}}) {
        if($student_num < 104000) { ## Delete the info of students before 2004.
            delete $college_data_hr->{$college_code}{'students'}{$student_num};
        }
    }
}

When the number of colleges are 70,000 then the execution times are:
For the code with while loop (Interval time is in seconds):
Interval time: 2.186621
Interval time: 2.058644
Interval time: 2.055645
Interval time: 2.101637
Interval time: 2.124632
For the code with foreach loop: (Interval time is in seconds)
Interval time: 1.341768
Interval time: 1.436751
Interval time: 1.346529
Interval time: 1.302775
Interval time: 1.356765
When the number of colleges are 248,000 then the execution times are:
(execution times for while loop)
Interval time: 9.084427
Interval time: 8.438684
Interval time: 9.329338
Interval time: 9.169687
(execution times for foreach loop)
Interval time: 5.502048
Interval time: 6.386692
Interval time: 5.596032
Interval time: 5.620144

A: The foreach version only dereferences the $college_data_hr->{$college_code}{'students'} hashref once per college, so is faster than the while version which needs to do it once per student.
The foreach version will likely use more memory though, as it needs to build temporary lists containing the keys for each hash.
Data::Alias might help you speed up the while solution. I've not benchmarked this, but it should be fairly fast...
use Data::Alias;

while ( my ($college_code, $college_info_hr) = each %$college_data_hr ) {
    alias ( my %students = %{$college_info_hr->{'students'}} );
    while ( my ($student_num, $student_info_hr) = each %students ) {
        if ($student_num < 104000) { ## Delete the info of students before 2004.
            delete $students{$student_num};
        }
    }
}

A: Each pass through the while loops requires a number of operations (All but the enter and leave apply to your code.)
>perl -MO=Concise,-exec -e"my ($college_code, $college_info_hr) = each (%{$college_data_hr})"
1  <0> enter
2  <;> nextstate(main 2 -e:1) v:{
3  <0> pushmark s
4  <#> gv[*college_data_hr] s
5  <1> rv2sv sKM/DREFHV,1
6  <1> rv2hv[t4] lKRM/1
7  <1> each lK/1
8  <0> pushmark sRM*/128
9  <0> padsv[$college_code:2,3] lRM*/LVINTRO
a  <0> padsv[$college_info_hr:2,3] lRM*/LVINTRO
b  <2> aassign[t5] vKS
c  <@> leave[1 ref] vKP/REFC
-e syntax OK

Included in there is the copying of the values into $college_code, $college_info_hr. On the plus side, they're not strings.
Your foreach loop does NONE of that. The only thing that happens every pass is to change what $college_code is aliased to. Very quick. The downside, of course, is that it will use more memory.

An alternative:
for my $college_code (keys %$college_data_hr) {
    my $students = $college_data_hr->{$college_code}{students};
    delete @$students{ grep $_ < 104000, keys %$students };
}

A: The problem is Perl can't make some optimization which is common in many compiled programming languages. As ikegami pointed out, each while cycle you copy data out from hash and you also do many unnecessary hash look-ups. There is some benchmark code you can play around.
#!/usr/bin/env perl

use 5.10.0;
use strict;
use warnings;
use Benchmark qw(:hireswallclock :all);
use Clone qw(clone);

my $data = {
    map +( $_ => { students => { map +( $_ => undef ), 103991 .. 104010 } } ),
    1 .. 70000
};
my $college_data_hr;

sub sum_time {
    my $t = shift;
    $t = timesum( $t, $_ ) for @_;
    return $t;
}

sub my_cmp_these {
    my %bench = @_;
    my %times;
    for ( 1 .. 10 ) {
        push @{ $times{$_} }, do {
            $college_data_hr = clone($data);
            timeit( 1, $bench{$_} );
            }
            for keys %bench;
    }
    $_ = sum_time(@$_) for values %times;
    cmpthese( \%times );
}

my_cmp_these(
    orig_while => sub {
        while ( my ( $college_code, $college_info_hr )
            = each( %{$college_data_hr} ) )
        {
            while ( my ( $student_num, $student_info_hr )
                = each( %{ $college_info_hr->{'students'} } ) )
            {
                if ( $student_num < 104000 )
                {    ## Delete the info of students before 2004.
                    delete $college_info_hr->{'students'}{$student_num};
                }
            }
        }
    },
    new_while => sub {
        while ( my ( undef, $college_info_hr ) = each( %{$college_data_hr} ) )
        {
            my $s = $college_info_hr->{'students'};
            while ( my ( $student_num, undef ) = each(%$s) ) {
                if ( $student_num < 104000 )
                {    ## Delete the info of students before 2004.
                    delete $s->{$student_num};
                }
            }
        }
    },
    orig_foreach => sub {
        foreach my $college_code ( keys %$college_data_hr ) {
            foreach my $student_num (
                keys %{ $college_data_hr->{$college_code}{'students'} } )
            {
                if ( $student_num < 104000 )
                {    ## Delete the info of students before 2004.
                    delete $college_data_hr->{$college_code}{'students'}
                        {$student_num};
                }
            }
        }
    },
    new_foreach => sub {
        foreach my $college_info ( values %$college_data_hr ) {
            my $students = $college_info->{'students'};
            delete @$students{ grep $_ < 104000, keys %$students };
        }
    },
    ikegami_foreach => sub {
        for my $college_code ( keys %$college_data_hr ) {
            my $students = $college_data_hr->{$college_code}{students};
            delete @$students{ grep $_ < 104000, keys %$students };
        }
    },
);

Results on mine notebook:
                s/iter orig_while new_while orig_foreach ikegami_foreach new_foreach
orig_while        1.56         --      -25%         -31%            -35%        -40%
new_while         1.17        33%        --          -8%            -14%        -21%
orig_foreach      1.08        44%        8%           --             -6%        -14%
ikegami_foreach   1.01        54%       16%           7%              --         -8%
new_foreach      0.927        68%       26%          16%              9%          --

Result for 248,000
                s/iter orig_while new_while orig_foreach ikegami_foreach new_foreach
orig_while        6.19         --      -27%         -30%            -33%        -38%
new_while         4.54        36%        --          -5%             -8%        -16%
orig_foreach      4.31        44%        5%           --             -4%        -11%
ikegami_foreach   4.16        49%        9%           4%              --         -8%
new_foreach       3.83        62%       19%          13%              9%          --


text:
Q: Scrub through memory arbitrarily while avoiding Read Access Violations I'm writing a debugging tool that takes a memory address from another process and displays the memory there and also all of the memory around it.  Ordinarily, reading memory like this can cause a Read Access Violation depending on the address, but I don't want to crash if the user scrubs into memory the process doesn't own, or picks a weird address.
Given an address, even something sure to fail like 0x00000000, how can I try to access it without aborting my program if it's in violation?

A: VirtualQueryEx can be used to iterate all pages of any process you have access to in order to check page protection.
QueryWorkingSetEx is similar but filtered to paged in memory, otherwise known as the working set, and can provide more detailed information.
ReadProcessMemory is, at its most basic, a memcpy wrapped in an exception handler from kernel. You won't ever crash using this (properly) and can check GetLastError to see why any failures happened.


text:
Q: How to pass parameters to a cmdlet from C# I have some powershell scripts that I want to call from C#.
From the commandline I would do this:
Import-Module c:\provisioning\newModule.psm1 –Force
Get-MTMailbox -customerID custid0001

This works and gives the correct result.
I want to call my scripts from C#:
InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new string[] { "C:\\provisioning\\newModule.psm1" });
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();

PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.AddCommand("Get-MTMailbox").AddArgument("-customerID custid0001");
// Also tried this. Still ignored.
//ps.AddParameter("-customerID", "custid0001");
ps.Invoke();
Collection<PSObject> results = ps.Invoke();
foreach (PSObject psObject in results)
{
    Console.Write("Result: "+psObject.ToString());
    if (psObject.BaseObject is System.Collections.Hashtable)
    {
        Hashtable ht = (Hashtable) psObject.BaseObject;
        foreach (DictionaryEntry keypair in ht)
        {
            Console.WriteLine(keypair.Key+" "+keypair.Value);
        }

    }
}

The command runs, but my arguments are always ignored.
I'm very new to C# so maybe I don't know what to search for.
What's the correct way to pass arguments to a cmdlet in C#?

A: try with this:
ps.AddParameter("customerID", "custid0001");

You do not need the - to specify the argument name


text:
Q: SO & MSO visual design for answered vs accepted questions inconsistent with other SE sites (Sorry if there's too much overlap with this question, but since it covers similar territory with a different thrust, I'm keeping this one separate for now.)
A friend of mine frequently complains that SO is headed the same way Usenet did after the AOLers joined up twenty years ago -- there's so much newbie traffic that good questions get ignored. I don't quite agree, but further discussion teased out an issue that might actually be relevant: there does seem to be a trend in that questions which have received at least one answer tend to get less attention than unanswered questions, and I think that visual design might have something to do with that.
Regarding answer status, at least, we have three states for a question:

*

*No answers

*One or more answers, none accepted

*One or more answers, author has accepted an answer

I'd argue that the distinction between the second and third states is more important than that between the first two: A question without an accepted answer may (and often very much does) need further attention and better answers -- that is, it needs attention just as much as an unanswered question does -- whereas it's usually less worthwhile to put more effort into problems that have already been solved.
Right now, those states look like this on SO (in a "desktop" browser):

The color inversion (from dark text on light background to light text on dark background) is high visual contrast change, particularly when compared to the change between white-on-dark and yellow-on-dark text. "Skimming" a question list, it's much easier to sort out the unanswered from the answered questions than to sort accepted from unaccepted... but is that what we want?
Other SO sites do this differently, perhaps better (quoting the aforelinked MSO post):

In order from the left: Home improvement, Gaming, English, Android, Cooking, Super User, Stats, Role-playing games

In all of those, the presence of answers triggers a subtle change of text color, and accepting answers trigger a higher-contrast change of background. Here, it's easier to sort out the questions that might still need an answer from those with an accepted answer.
This is also true in Stack Overflow's mobile version:

I don't have the mastery of the site API needed to gather data that might support or refute this argument, but I suspect that making answered-but-not-accepted questions stand out more or less from unanswered questions might have an effect. Perhaps it even has something to do with the (perceived) tendency for good questions to get ignored after they get one (lame) answer?
Perhaps it'd regardless be helpful to use low and high visual contrast transitions for the same meaning across all StackExchange sites?


text:
Q: get two characters, count and print from a .txt file The program I wrote is terrible so if anyone can make a different py and give me some pointers well thanks a bunch!
What I would like help on is to print only the first two characters of a word and if those same characters repeat hold them to a count. It's like a Zipf distribution but for the first two letters for every word. The example is how I would like the output. Here is an example from this text and its for show!
text file = "Here is an example from this text and its for show!"
an 2
He 1
is 1
ex 1
fr 1
th 1
te 1
it 1
fo 1
sh 1
total 11
 file = open("C:\python37\paradise.txt", 'r')

 while 1:

     # read by character
     char = file.read(2)
     if not char:
         break

     print(char)

 file.close()

A: You don't have to read character by character because that will require a lot of effort. Here's a better way:
# dictionary to store count of each word (2 characters) eg. "an": 2
wordDict = {}

file = open("paradise.txt", 'r')
# read each line in file
for line in file:
    # read each word in line
    for word in line.split():
        # get only first two letters of word
        word = word[:2]
        # If word is not in dictionary then add it
        if word not in wordDict:
          wordDict[word] = 1
        # else increment the count
        else:
          wordDict[word] += 1

file.close()

# print all values
for key, val in wordDict.items():
  print(key, val)

# print total
print(f"Total: {sum(wordDict.values())}")

Explanation:
To store the count, we create a dictionary where keys are the words and values are their counts. E.g:
{
  "an": 2,
  "He": 1
}

Then, we read the file content line by line. We split the line into words and get the first two letters of each word.
Next, we add those words in our dictionary wordDict with their respective counts.
Note:
It is suggested to open files using with keyword.
with open('paradise.txt') as file:
    ...

This way, file is closed automatically.

A: I would create a result list results=[] to which the two-letter chunks are added. Then I would count the occurrences of unique items in the result list.
Is that what you want?
Here is the link which will help you count unique items in a Python list:
How do I count unique values inside a list
The answer by Vidul is what relates to your question:
"In addition, use collections.Counter to refactor your code:
from collections import Counter

words = ['a', 'b', 'c', 'a']

Counter(words).keys() # equals to list(set(words))
Counter(words).values() # counts the elements' frequency

Output:

['a', 'c', 'b']
[2, 1, 1]

"
The words list in Vidul's example would be results in yours.

A: You can do this simply by loading the whole text file into an array of separate words using space as a delimiter.
Once you have all the words in an array you can loop through the array and only return the first 2 letters of each word using an array operator [:2]. From here you can add each set of 2 to a dictionary and count up.
Example code below that works as well as the output:
filePath = "C:\\Users\\Oddity\\Documents\\Python\\STACKEXCHANGE\\test.txt"

## Read file into list of each word as a seperate entry
data = []
with open(filePath, 'r') as file:
    data = file.read().replace('\n', ' ').split(' ')

    ## Loop through each word and retreive the first two characters
    ## then update the dict
    characters = {}
    for each in data:
        if each[:2] in characters:
            characters[each[:2]] += 1
        else:
            characters[each[:2]] = 1

    print(characters)

    file.close()

Output:
{'He': 2, 'is': 2, 'an': 4, 'ex': 2, 'fr': 2, 'th': 2, 'te': 2, 'it': 2, 'fo': 2, 'sh': 2}

A: file = open("C:\python37\paradise.txt", 'r')
wordDictionary = {}
keys = []
para = file.read()
for line in para:
   for word in line,split():
     letters =word[0:2]
     if letters in keys:
        wordDictionary[letters]++
     else:
        keys.append(letters)
        wordDictionary[letters]=1
print (wordDictionary)
file.close()

This is a very simple way in which I open the file, read it and then iterate through every word. Then I get the first 2 letters. Then I check if those are in the keys of the dictionary(I maintaned a separate list). If yes I added one else I created a new record

A: I hope this would solve :

Click here to copy the code
Output:
 He : 1
 is : 1
 an : 2
 ex : 1
 fr : 1
 th : 1
 te : 1
 it : 1
 fo : 1
 sh : 1


text:
Q: Connect signal from Glade to Gjs/Seed code I want to use the connect_signals method to bind my Glade signals to Gjs/Seed methods.
But I always get the following error : Argument 'user_data' (type void) may not be null
Does anyone know how to use the connect_signals method?
Gjs/Seed file
Gtk.init(null, 0);
let builder = new Gtk.Builder();
builder.add_from_file( "ui.glade" );

builder.connect_signals(this);

Gtk.main();

function on_button_ok_clicked() {
    print("ok");
};

Glade file
<?xml version="1.0" encoding="UTF-8"?>
<interface>
  <object class="GtkWindow" id="window">
    <child>
      <object class="GtkButton" id="button_ok">
        <signal name="clicked" handler="on_button_ok_clicked" swapped="no"/>
      </object>
    </child>

A: I could not get connect_signals to work due to the void* user_data, but connect_signals_full does work for some mysterious reason :-)
const SignalHandlers = new Lang.Class({
    Name: 'SignalHandlers',

    _init: function () {},

    your_switch_active_notify_cb: function (object) {
      print("switch is active:" + object.get_active());
    },

    _connector: function(builder, object, signal, handler) {
      object.connect(signal, Lang.bind(this, this[handler]));
    },
});

function buildPrefsWidget() {
  let win = new Gtk.Table(), ui = new Gtk.Builder();

  ui.add_from_file(Me.dir.get_path() + "/prefs.ui");
  ui.get_object("content-table").reparent(win);

  let signal_handlers = new SignalHandlers();
  ui.connect_signals_full(Lang.bind(signal_handlers, signal_handlers._connector));

  return win;
}


text:
Q: Putting back a missing column from a data.frame into a list of dta.frames My LIST of data.frames below is made from my data. However, this LIST is missing the scale column which is available in the original data.
I was wondering how to put back the missing scale column into LIST to achive my DESIRED_LIST?
Reproducible data and code are below.
m3="
scale study   outcome time ES bar
2       1       1      0   1  8
2       1       2      0   2  7
1       2       1      0   3  6
1       2       1      1   4  5
2       3       1      0   5  4
2       3       1      1   6  3
1       4       1      0   7  2
1       4       2      0   8  1"
data <- read.table(text = m3, h=T)

LIST <-         list(data.frame(study=c(3,3)    ,outcome=c(1,1)    ,time=0:1),
                     data.frame(study=c(1,1)    ,outcome=c(1,2)    ,time=c(0,0)),
                     data.frame(study=c(2,2,4,4),outcome=c(1,1,1,2),time=c(0,1,0,0)))

DESIRED_LIST <- list(data.frame(scale=c(2,2)    ,study=c(3,3)    ,outcome=c(1,1)    ,time=0:1),
                     data.frame(scale=c(2,2)    ,study=c(1,1)    ,outcome=c(1,2)    ,time=c(0,0)),
                     data.frame(scale=c(1,1,1,1),study=c(2,2,4,4),outcome=c(1,1,1,2),time=c(0,1,0,0)))

A: In base R, you could do:
lapply(LITS, \(x)merge(x, data)[names(data)])


text:
Q: Having a difficult time understanding indentation for HAML I've been trying to learn HAML by putting together a simple middleman app, but I keep running into syntax error. I'm using a bootstrap theme and followed a video tutorial, but it seems like I'm running into "illegal nesting" problems.
.container
    .jumbotron
        %blockquote
        %p Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.
            %small
            Someone famous in
            %cite{:title => "Source Title"} Source Title

"Haml::SyntaxError at /
Illegal nesting: content can't be both given on the same line as %p and nested within it."
I've been messing around with it to try and understand how the identation works, but have no clue. I can make the blockquote show up if I dont have a container.
Advice please!

A: .container
    .jumbotron
        %blockquote
        %p
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.
            %small
            Someone famous in
            %cite{:title => "Source Title"} Source Title

Rule of thumb: if element has childs, it shouldn't have some text on the same line
P.S. I strongly recommend you 2 spaces indentation


text:
Q: Why is break() not working in this loop? (but stop is) I am trying to build a matrix model which ends if certain conditions are invoked - however for some reason the break() command isn't working, although stop() does. Unfortunately stop() is not what I need as I need to run the model a number of times.
The first break command in the model works, but I have left it in with dth>100 so that you can see for yourselves
    n.steps <- 200
ns <- array(0,c(14,n.steps))
ns[13,1]<-rpois(1,3)
ns[14,1] <- 1
k<-0

for (i in 1:n.steps){
  k<-k+1
  ns[13,1]<-rpois(1,2)
  death<-sample(c(replicate(1000,
                            sample(c(1,0), prob=c(surv.age.a, 1-surv.age.a), size = 1))),1)
  ns[14,k] <- death

  if (death == 0) {
    dth <- sample(1:100, 1)
    if (dth > 100) {
      ns[14,k]<-0
      print("stop.1")
      break()

    } else {

      while (death == 0) {
        if (ns[13, k] > 0) {
          rep.vec[i]<-ns[13,k]

          ns[13, k] <- ns[13, k] - 1
          ns[14,k+1]<-1
          print("replace")

        } else {

          if (ns[13, k] == 0) {
            print("stop.2")
            ns[14,k+1]<-0
            break()
          }
        }
      }
    }
  }
}

A: Try this (only showing the relevant portions):
for (i in 1:n.steps){

   # ...

       break.out.of.for <- FALSE
       while (death == 0) {
        if (ns[13, k-1] > 0) {
            # ...
        } else {
          if (ns[13, k] == 0) {
            # ...
            break.out.of.for = TRUE
            break
        }
       }
       if (break.out.of.for) {
         break
       }
}


text:
Q: using ta.pivothigh inside a for loop in pinescript I wanted to check if certain previous candles are pivot high or not..
to figure out the code i first tried to see if the below simple code works but it doesnt and i cant figure out why!  this code should find how many candles has passed from the last pivot high of [4,0] ( 4 candles left and 0 candles right) and lookback range is 30 candles . ... but it doesnt work properly. just sometimes it gives correct answers. could someone tell me why?
//@version=5
indicator("pivot")
b=0
for i=0 to 30
    b:=i
    if high[i]==ta.pivothigh(high[i],4,0)
        break
plot(b)

A: The ta.pivothigh only returns the value when current candle is actual pivothigh
So you will have to save the pivothigh in a variable eg. hi and then use it inside the loop
//@version=5
indicator("pivot")
var hi=0.0
hi:=ta.pivothigh(high,4,0)

var b=0
b:=0
for i=0 to 100
    b:=i
    if high[i]==hi[i]
        break
plot(b,color=color.red)


text:
Q: Azure QueueClient MaxConcurrentCalls Not Working I have been tasked to improve the performance of a worker role which processes the messages from the queue.
It uses queueclient.OnMessage model with MaxConcurrentCalls setting as 1.
During the processing there is thread.sleep for 5 minutes and that will hamper the overall performance i.e. if I have 10 messages in the queue it will take at least 45 minutes before it processes the 10th message
I thought if I change MaxConcurrentCalls to let's say 5 then it should process 5 messages in parallel and reduce the waiting time by 25 minutes but that's not working :(
Also I tried to use OnMessageAsync with MaxConcurrentCalls but no luck. below is the snippet I tried,
.OnMessageAsync( async (brokeredMessage) =>
{
    bool shouldAbandon = false;
    try
    {
        logger.Debug("Rcvd:" + brokeredMessage.SequenceNumber);
        SomeTask(brokeredMessage);
        await brokeredMessage.CompleteAsync();
    }
    catch (Exception ex)
    {
        logger.Error(String.Format("An Error occured {0}", ex.ToString()));
        shouldAbandon = true;
    }
    if (shouldAbandon)
    {
        await brokeredMessage.AbandonAsync();
    }
}, new OnMessageOptions { AutoComplete = false, MaxConcurrentCalls = 10 });

private void SomeTask(BrokeredMessage bm)
{
    logger.Debug("id: " + bm.MessageId + "on thread: " + Thread.CurrentThread.ManagedThreadId);
    Thread.Sleep(30 * 1000);
    logger.Debug("seq: " + bm.SequenceNumber);
    logger.Debug("body: " + bm.GetBody<string>());
}

Last option I can think is to start a new Task on OnMessage event. There are couple of things I'll need to take care of (making sure completed tasks are removed from the collection/main thread and pass a object from BrokeredMessage because BrokeredMessage is disposed so I can't use on the Task thread) and I have sanity tested it as well but I'm not convinced that this is the best solution.

A: Replace SomeTask implementation with the following:
async Task SomeTask(BrokeredMessage bm)
{
     logger.Debug("id: " + bm.MessageId + "on thread: " + Thread.CurrentThread.ManagedThreadId);
     await Task.Delay(30 * 1000).ConfigureAwait(false);
     logger.Debug("seq: " + bm.SequenceNumber);
     logger.Debug("body: " + bm.GetBody<string>());
}

When Thread.Sleep is mixed with async on the same thread (in your case), it causes thread to 'stall' all the tasks. Since there's no UI work, prefer to use .ConfigureAwait(false) on async operation to allow scheduler to manage what thread to execute on.


text:
Q: RejectedExecutionException not thrown immediately? I have an executor that runs some runnables:
ThreadPoolExecutor pool = new ThreadPoolExecutor(
                    5,
                    15,
                    15000,
                    TimeUnit.MILLISECONDS,
                    new ArrayBlockingQueue<Runnable>(100)
                );

            try{
                for(int i = 0; i<=300; i++){
                        Logger.info("Queue size:{}", pool.getQueue().size());
                        pool.execute(new Runnable(){
                            @Override
                            public void run() {
                              object.method()
                            }
                        });
                }
            }
            catch(RejectedExecutionException e){
                Logger.error(e.getMessage());
            }

However, the queue is at 100 through several iterations before the RejectedExecutionException is thrown. The output is "Queue Size:100" about 11 times before the exception is thrown. Looking at documentation, that exception should be thrown when the queue size reaches its limit. Any ideas why it doesn't throw the exception immediately?
EDIT: Also meant to say that I'm sleeping the thread created in run() for a few seconds for testing so that the queue will back up.

A: Figured this out. The issue was that I have a maxPoolSize set at 15, with a corePool of 5. When the 5 are busy, tasks are added to the queue. When the queue fills up, more threads (up to the maxPoolSize) are created. So my queue was still full and then the threads created. I changed
ThreadPoolExecutor pool = new ThreadPoolExecutor(
                5,
                15,
                15000,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(100)
            );

to:
ThreadPoolExecutor pool = new ThreadPoolExecutor(
                15,
                15,
                15000,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(100)
            );

and the exception was thrown correctly.


text:
Q: How to write in jsonDecode? {
  "success": true,
  "msg": {
    "name": "xxxx",
    "Id": "123",
  }
}

How can I decode this format of response when i recieve from api?
its getting error when i used
**

Map<String, dynamic> map = json.decode(response.data);

**
error:  Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'

A: You need to decode the body not data.
Map resultMap = jsonDecode(request.body);

Access it like this
resultMap['success']


text:
Q: How to get the last object from a query? I have the following:
// In the service
me: Ember.computed('token', function() {
  return this.container.lookup('service:store').findRecord('user', 63);
}

// In the template - Works
{{this.currentSession.me.profile.firstName}}

Above works as expected. However, if I replace findRecord with query and throw it a filter param:
// In the service
me: Ember.computed('token', function() {
  return this.container.lookup('service:store').query('user', { filter: { token: this.get('token') } });
}

// In the template - Works
{{this.currentSession.me.lastObject.profile.firstName}}

The lastObject is required, since the result from query is a collection. I am wondering if it is possible to get this work without doing lastObject. i.e.
{{this.currentSession.me.profile.firstName}}

I tried to put the lastObject in the computed property, like:
return this.container.lookup('service:store').query('user', { filter: { token: this.get('token') } }).lastObject;

To no avail. Any thoughts?

A: Try this:
return this.container.lookup('service:store').query('user', { filter: { token: this.get('token') } }).then(function(users){
  return users.get('lastObject');
});


text:
Q: will it change .aspx.cs file to take data from html element after converting asp controls into html? my question was that when I send the request to the web server, of course, the web server will take the request and give me a page that will be in the HTML format so I want to know when the web server will execute asp server-side controls into HTML format than in the Testing. aspx.cs file will be changed as well? it means these two lines int no1 = Convert.ToInt32(textbox1.Text);
int no2 = Convert.ToInt32(textbox2.Text);
these two lines will be converted into like this int no1=Convert.ToInt32(Response["textbox1"]);
int no1=Convert.ToInt32(Response["textbox2"]); these two lines will be converted like this or not
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Testing.aspx.cs" Inherits="login.Testing" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

                       Enter the Number 1:<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>

                       Enter the Number 2:<asp:TextBox ID="textbox2" runat="server"></asp:TextBox>

                           <asp:Button ID="button1" runat ="server" Text="Add" Height="38px" OnClick="Unnamed1_Click" Width="101px" />

    </form>

--------------------------------------------------------------
Testing.aspx.cs

using System;
using System.Collections.Generic;
using System. Linq;
using System. Web;
using System.Web.UI;
using System.Web. UI.WebControls;

namespace login
{
    public partial class Testing: System.Web. UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Unnamed1_Click(object sender, EventArgs e)
        {
            int no1 = Convert.ToInt32(textbox1.Text);
            int no2 = Convert.ToInt32(textbox2.Text);
            int result;
            result = no1 + no2;
            Response.Write(result);
        }
    }

}


text:
Q: iPhone is not playing animation sprites properly ? I have tested this on Android and it works great but on iPhone it seems very laggy, i have assumed it was an error with image preloading so after firing in a simple jquery preloader it still seems to give issues.
The images are huge maxing at 25025px by 80px
I wonder if you can see something i am missing ?
http://www.prosperitymedia.co.uk/test/
To view the issue view the site on your iphone / itouch.
As a side note i am using a plugin called Spritely

A: Ok i tested on another phone
It's not that spritely can't display the animation, is the iPhone who is trying to cache all frames, frame by frame and then display.
As you have all alphabet and rougly hundreds of frames this process is too slow.
If you test http://www.spritely.net on your iPhone you will see that the birds are loading frame by frame (and that is 3 frames) and at the end all works ok because Safari has all frames.
My guess is you need to reduce the frames and the number of animations for smart phones as they don't have that much memory.

A: So this was a tricky situation to overcome but here are our exact workings.  We found that it wasn't performance related issues with the iphone due to the number of sprites, what was happening was the browser was crashing due to loading and animating the images at the same time.
So to stop this from happening we had to preload our images using a plugin for jQuery which evidently didn't work very well.
In the end we wrote a custom function to write the images to the DOM and then <img onload="customFunction" /> to attach that to a div via the jQuery .css() function.
Whilst this image loading was taking place we used a preloading (loading) screen to inform the user that there was something happening.
I hope this helps anyone in the future with a similar problem.


text:
Q: How to save handle object hierarchy to disk in matlab I have some big handle objects hierarchy, for example
classdef A < handle
    b;
    c;
end

classdef B < handle
    d;
    e;
end

classdef C < handle
    f;
    g;
end

a = A;

where a,b,c,d,e,f are all instances of their respective classes. Eventually, there are basic data types (vectors or scalars of, say, double).
I need the save of a to hold all the information about a,b,c,d,e,f, in a way that can be restored later.
Runtime is not an issue for me right now.
Development time is an issue.
How can I easily create a save of the top A type object to disk? (a deep copy, to disk).
I want it to happen automatically (built in), somewhat like java's serialize maybe, without me having to change some save method for every change I make in the classes' structure.

A: When saving objects with MATLAB using the built-in save, it will automatically save a "deep-copy" in that it saves all properties of the object and if any of those properties are also objects or arrays of object, they will themselves be serialized. The objects can then easily be loaded again using the built-in load function. It is worth noting that in order for an object of a custom class to be loaded properly, the class definition must be on the path when calling load.
save('output.mat', 'a')
fromdisk = load('output.mat');

If you want to customize the saving or loading functionality of your class, you can overload the saveobj and loadobj methods, respectively.


text:
Q: In Spelunky HD what secret levels are there and how do I find them? In the 360 version of Spelunky (not the PC version, which is different) what secret levels are there and how do you get to them?

A: Real last step:
During Olmec, the final boss,move around until the book writhes at it's face the most. (it starts slow ,then speeds up as you get closer). Defeat Olmec over that spot. There will be a door. This door has no step, so jetpacks or capes make no difference. You must use Olmec's face as a step as he sinks into the lava to get to hell. This is impossible without the book, as the door will not appear if you do not have it.
The worm is much larger than a standard level. In a pool of acid inside is the Crysknife. It one-hit-kills ANYTHING. Be sure to retrieve it. Also, in the green background decoration with a silhouette, whip it to free a secret character.
At the top inside of the haunted castle is a secret character. Whip the coffin to free him.
The mothership is reverse and drops you off at 3-3, although it appears at 3-4. Within are alien lords and the alien queen, whom guards a very destructive plasma cannon.Break open the distinct alien pod in the background to unlock a secret character.
The black market entrance does NOT appear on most levels.Only one chance to enter appears on 2-1, 2-2, or 2-3.

A: There are six found so far, but there may be more. I've only found the first four, so credit has to go to Todd Schlickbernd and SnapDragon for the last two.

*

*Black Market - there's a hidden door (use bombs or the mattock) on most levels that goes here. The huge eye (from the gold key chest in the mines) helps find them.

*Worm - on any level with one of those floating pink spiky things that you can jump on (mostly in the jungle levels) throw a stunned damsel so that they stick to it and then jump on yourself. After a few seconds you will both be swallowed by the worm. Strangely, you still get the kiss for doing this :-)

*Haunted Castle - when you get the "Dead are Restless" message at the start of a jungle level keep an eye out for a large grave with a buried skeleton wearing a crown. Destroy the ground below the skeleton king to find a secret door. Also look out for any graves with ASH written on them - destroy the ground below for a boomstick :-D

*Mothership - on the final ice level there's two exits. The one at the top goes to the mothership. You will need lots of rope or the jetpack.

*City of Gold - really hard to get to this one:

*

*You must get the eye from the mines, I don't think finding the Black Market otherwise is enough.

*You must get to the Black Market and either buy the golden ankh or kill all the shopkeepers.

*On one of the ice levels (3rd section) there's a giant stone head with an ankh symbol on it. You must die near this, without using bombs.

*You will appear inside the stone head next to a golden pointy crown

*In the temple area kill an Anubis, they will drop the Sceptre:

*Finally walk over the large golden block with a hole in it - if you have everything

*Hell - I haven't made it here yet, so I'm going by the guides of others:

*

*Get to the City of Gold

*Recover the Necronomicon:

*This will spawn a new Anubis. This one spawns lots of red skeletons. You must kill him.

*During Olmec, the final boss,move around until the book starts as it's face the most. (it starts slow ,then speeds up as you get closer). Defeat Olmec over that spot. There will be a door. This door has no step, so jetpacks or capes make no difference. You must use Olmec's face as a step as he sinks into the lava to get to hell. This is impossible without the book, as the door will not appear if you do not have it.


text:
Q: Why does io.WriterTo's WriteTo method return an int64 rather than an int? Most of the output methods in Go's io package return (int, error), for example io.Writer's Write([]byte) method and the io.WriteString(io.Writer, string) function. However, a few of the output methods, such as io.WriterTo's WriteTo method, return (int64, error) instead. This makes it inconvenient to implement WriteTo in terms of Write or WriteString without storing an intermediate value and type converting it from int to int64. What is the reason for this discrepancy?

A: It's possible that WriteTo copies more than int32 bytes of data.
With the io.Readerand io.Writer interfaces, the amount of data is limited by the size of the given slice, which has a length limited by int for the current architecture.

A: The signature of the Writer.Write() method:
Write(p []byte) (n int, err error)

It writes the contents of a slice. Quoting from the spec: Slice types:

A slice is a descriptor for a contiguous segment of an underlying array...

As we all know, the slice has an underlying array. Quoting again from the Spec: Array types:

The length is part of the array's type; it must evaluate to a non-negative constant representable by a value of type int.

So the maximum length of an array is limited by the maximum value of the int type (which is 2147483647 in case of 32 bit and 9223372036854775807 in case of 64 bit architectures).
So back to the Writer.Write() method: since it writes the content of the passed slice, it is guaranteed that the number of written bytes will not be more that what fits into an int.
Now WriteTo.WriteTo() method:
WriteTo(w Writer) (n int64, err error)

A slice or array is nowhere mentioned. You have no guarantees that the result will fit into an int, so the int64 is more than justified.
Example: BigBuffer
Imagine a BigBuffer implementation which temporarily writes data into an array or slice. The implementation may manage multiple arrays so that if one is full (e.g. reached max int), continues in another one. Now if this BigBuffer implements the WriteTo interface and you call this method to write the content into an os.File, the result will be more than max int.


text:
Q: Store a specific hour but in datetime type SQL Server I have a table that have two columns, one is called HourFrom and HourTo, this hours can be changed. I dont want the type to be nvarchar the only thing that needs to store is for example 08:00 or 23:00.
Is there a way to design the table with functions that only shows the hour instead of creating (for example) a Store Procedure that saves the datetime with this functions?
The reason behind this is because I have an entity in my backend where these two members are Datetime as they should be and dont want to mix types and doing weird castings or using split,indexOf, etc.

A: You can use time(0), data may look like 03:06:12, 08:45:00. I have no idea how you going to use the data. Eg, if in where clause, where HourFrom between '03:00:00' and '04:00:00', does it matter if HourFrom contains minute and second?


text:
Q: How can I launch an application with PowerToys Run after changing the application file path? I have an application in a folder on my Desktop. After changing the name of the folder, PowerToys Run cannot find it at the old address and is unable to run it from the most relevant search result.
In this screenshot of the Run window, if I click on the highlighted first result I get this error message.
Run window:

Error message:

...however clicking on the fourth result will open the app.
How can I change an application file path and have PowerToys Run find the correct path / update its search results?

A: The Microsoft Windows Power Toys app Run Command just uses the Windows Path.
Power Toys Run
$ control>system>admin shows all settings of the path 'Control Panel > System and Security > Administrative Tools'.

Just set your Windows path as you need
You can also include the full path when you run the App

A: You might have run into the bug reported in
Unable to recognize new apps #4802.
The advice in that post was to clear the cache at
%userprofile%/appdata/local/microsoft/powertoys/powertoys run/Cache
and restart PowerToys Run (or reboot).


text:
Q: WSO2 ESB doesn't process Put request from API store We are using WSO2 ESB 4.7.0 and WSO2 API Manager 1.6.0
I have an API defined the ESB which takes a PUT request and processes it to a back end system and sends back the response as success.
The API works fine if I use the soap client or Advanced Rest Client.
Request URL: http://:/CurriculumAdmin/Terms/2010/Classes/11513/LMSURL?LMSURL=KRanthiPUTARCAPI
Response:
Status 200 OK
But if I create a API using the WSO2 API manager and use the try it option from there, I get a 202 response
Request URL:
https://:/TestURL/v1.0/Terms/2010/Classes/11513/LMSURL?LMSURL=KranthiTestAPI
Where TestURL/v1.0 is the context root /resource for my API.
Response:
Response Body

Response Code
202
I could see that the response comes till the ESB , but the ESB doesn't do anything with the request and simply sends a response code of 202 back..
Any suggestions / help are highly appreciated.
Thanks
Kranthi

A: This issue occurs due to a parameter that is set by default by the WSO2 API Manager.
Go to /usr/local/wso2/wso2am-1.6.0/repository/deployment/server/synapse-configs/default/api
Open the .xml file of the corresponding API and remove the following line.
<property name="POST_TO_URI" value="true" scope="axis2"/>

This parameter is set by API manager by default. WSO2 will make a fix to their product API manager in release 1.8.0 to NOT set this property as default.
ESB Logs Before the change :
TID: [0] [ESB] [2014-10-27 11:16:18,068] DEBUG {org.apache.synapse.transport.http.wire} -  >> "PUT http://:/CurriculumAdmin/Terms/2010/Classes/11513/LMSURL?LMSURL=www HTTP/1.1[\r][\n]" {org.apache.synapse.transport.http.wire}
Observer the hostname and portnumber appearing in the request sent to ESB
ESB Logs After the change :
TID: [0] [ESB] [2014-10-27 11:24:54,478] DEBUG {org.apache.synapse.transport.http.wire} -  >> "PUT /CurriculumAdmin/Terms/2010/Classes/11513/LMSURL?LMSURL=www HTTP/1.1[\r][\n]" {org.apache.synapse.transport.http.wire}
Hostname and portnumber are removed from the URL.
This works fine and hence the issue is resolved. Hope its useful for someone ..
Thanks
Kranthi


text:
Q: Variance of random variable with distribution $2(x+1)^{-3}$ I have to calculate $Var(X)$, with $f(x)= 2(x+1)^{-3}$ for $x>0$
I have tried using $Var(X) = E(X^2) - E(X)^2$
for $E(X)$ i managed to get $1$ from the integral, however the integral i get for $E(X^2): 2(ln(x+1) + (4x+3)/(2x^2+4x+2))$ is diverging
Any help would be appreciated, thanks


text:
Q: Angular custom filter causing recursion depth error In my Angular app, I have a field called listing.desired_majors which is an array of major ids, as an example: [3, 20, 24].
These ids refer to the primary keys of a model of university majors that I have.  I'm trying to write a filter in Angular to convert this array of ids to an array of the majors' titles by iterating through the array and requesting each major's title using the majors service factory.  Note that this only needs to happen once--the data being filtered here will never be updated after page render.
However, when I include the filter in a template, I get a recursive error that goes ad infinitum, and I can't figure out why.  What's particularly odd is not only that it throws a depth error, but that the browser then continues to throw this error again and again until it crashes.  I've refactored the filter four or five times now, and I've tried including a bind-once directive I found on Stack Overflow, but that didn't help either.  Can you tell what the issue is here?  Is it that Angular keeps calling the filter over and over again because the data is bound using {{ }}?  If that is the issue, why is this causing a depth error?
The template:

{{ listing.desired_majors | majorIdsToObjects:'title' | joinBy:','}}

The filter:

angular.module('myApp')
    .filter('majorIdsToobjects', ['majors', function (majors) {
        return function (items, returnAttr) {
            var filtered = [];

            var getMajor = function (major) {
                majors.get({majorId: major},
                    function (res) {
                        if (returnAttr == null) {
                            filtered.push(res);
                        } else {
                            filtered.push(res[returnAttr]);
                        }
                    }, function (res) {
                        //TODO: handle error
                    });
            };

            angular.forEach(items, function (item) {
                getMajor(item);
            });

            return filtered;
        }
    }]);

For reference, here is the joinBy filter:
# this is in coffeescript
angular.module('campusJobApp').filter 'joinBy', ->
  (input, delimiter) -> (input || []).join delimiter || ', '

Here is a screenshot of the error.  Keep in mind that this error appears hundreds of times until the browser crashes: