text:
Q: Divide two pandas columns of lists by each other I have a df like this:
col1        col2
[1,3,4,5]   [3,3,6,2]
[1,4,5,5]   [3,8,4,3]
[1,3,4,8]   [8,3,7,2]

Trying to divide the elements in the lists in col1 and col2 together to get what's in the result column:
col1        col2        result
[1,3,4,5]   [3,3,6,2]   [.33,1,.66,2.5]
[1,4,5,5]   [3,8,4,3]   [.33,.5,1.25,1.66]
[1,3,4,8]   [8,3,7,2]   [.33,1,.57,4]

Tried a lot of different approaches - but always get an error.
Attempts:
#attempt1
df['col1'].div(df['col2'], axis=0)

#attempt2
from operator import truediv

for i in df.col1:
     a = np.array(df['col1'])
     for t in df.col2:
         b = np.array(df['col2'])
         x = a/b
         print(x)

#attempt3
for i in df.index:
    a = col1
    b = col2
    x = map(truediv, a, b)

#attempt4
a = col1
b = col2
result = [x/y for x, y in zip(a, b)]
#then apply to df

#attempt5
a = col1
b = col2
result = a/b
print(percent_matched)
#then #apply to df

>>>TypeError: unsupported operand type(s) for /: 'list' and 'list'

Any ideas?

A: *

*Use .applymap to convert the columns to np.arrays

*Then use .div to divide the columns

*If result must be rounded, tack on .apply(lambda x: np.round(x, 3)), when calculating that column.

*

*np.round()

*df['result'] = df.col1.div(df.col2).apply(lambda x: np.round(x, 3))
import numpy as np
import pandas as pd

data = {'col1': [[1,3,4,5], [1,4,5,5], [1,3,4,8]], 'col2': [[3,3,6,2], [3,8,4,3], [8,3,7,2]]}

df = pd.DataFrame(data)

# convert columns to arrays
df = df.applymap(np.array)

# divide the columns
df['result'] = df.col1.div(df.col2)

A: You can use list comprehension with apply, this is conditional on both the lists being of same length
df['result'] = df.apply(lambda x: [np.round(x['col1'][i]/x['col2'][i], 2) for i in range(len(x['col1']))], axis = 1)

    col1            col2            result
0   [1, 3, 4, 5]    [3, 3, 6, 2]    [0.33, 1.0, 0.67, 2.5]
1   [1, 4, 5, 5]    [3, 8, 4, 3]    [0.33, 0.5, 1.25, 1.67]
2   [1, 3, 4, 8]    [8, 3, 7, 2]    [0.12, 1.0, 0.57, 4.0]

Edit: As @TrentonMcKinney suggested, this can be done without using LC. This solution capitalized on Numpy's vectorized operations,
df.apply(lambda x: np.round(np.array(x[0]) / np.array(x[1]), 3), axis=1)

A: df=df.apply(pd.Series.explode)#
df['result']=(df.col1.div(df.col2))
df.groupby(level=0)['result'].agg(list).reset_index()

A: If these are large, you're far better off converting these to np.arrays and then doing the divide:
df["col1"] = df["col1"].apply(np.array)
df["col2"] = df["col2"].apply(np.array)

df["output"] = df.col1/df.col2


text:
Q: How to shift a string to the right by n characters I was practicing coding and found this exercise on the internet:
Enter a string s and an integer n in the two lines respectively, and define a function to move the string s to the right by n bits, and to the left when n is a negative number.
If s is an empty string '', output '' regardless of n.
Sample input:
s ='123456'
n=3

Sample output:
Output result: 456123

I did this so far:
def shiftall(s, n, left, right):
    while left <= right:

        if s[left] < 0 and s[right] < 0:
            left += n

        elif s[left] > 0 and s[right] < 0:
            s[left], s[right] = \
                s[right], s[left]
            left += n
            right -= n

        elif s[left] > 0 and s[right] > 0:
            right -= n
        else:
            left += n
            right -= n

def display(s):
    for i in range(len(s)):
        print(s[i], end=" ")
    print()

if __name__ == "__main__":
    s = str(input('s='))
    n = int(input('n='))
    shiftall(s, 0, n - 1)
    display(s)

But getting error and can't tackle it:
Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\pythonProject\main.py", line 31, in <module>
    shiftall(s, 0, n - 1)
TypeError: shiftall() missing 1 required positional argument: 'right'

Any suggestions? EDITED MISTAKE OUTPUT*

A: It is __name__ and not name
Also you can do :
s = s[n:] + s[:n]

to shift the string.

A: if name == "__main__": should be if __name__ == "__main__":
__name__ is a special built-in python variable corresponding to the name of the current module.
EDIT: New error:
shiftall(s, 0, n - 1) is only provided 3 arguments:

*

*s

*0, and

*n-1

Did you forget the last argument, or did you mean shiftall(s, 0, n, 1)?
It looks like you are providing n as 0 and instead providing it as the value for 'right'

A: What exactly are the parameter left and right for? All the information is in the number n. Moreover, strings are immutable, so you cannot assign string indices like s[foo] = "b". You will have to return a new string from your function:
def shiftall(s, n):
    n %= len(s)  # make sure you are within the bounds of s
    return s[n:] + s[:n]

Then you can reassign your s with the function result:
s = "123456"
n = 3
s = shiftall(s, n)
print(s)
# 456123

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to allow aws programatic user to create resources using assume role I have created a policy X with ec2 and vpc full access and attached to userA. userA has console access. So, using switch role userA can create instance from console.
Now, userB has programatic access with policy Y with ec2 and vpc full access. But when I tried to create instance using Terraform got error.
Error: creating Security Group (allow-80-22): UnauthorizedOperation: You are not authorized to perform this operation. Encoded authorization failure message:
Even - aws ec2 describe-instances
gives error -
An error occurred (UnauthorizedOperation) when calling the DescribeInstances operation: You are not authorized to perform this operation.
Anyone can help me on this.
Thanks in advance.

A: To be honest there are a couple of mistakes in the question itself but I have ignored them and provided a solution to

*

*Create Resources using IAM user with only programmatic access having direct policies attached to it
In general, if you have an AWS IAM user who has programmatic access and already has the required policies attached to it then it's pretty straightforward to create any resources within the permissions. Like any normal use case.

*

*Create Resources using IAM user with only programmatic access with assuming a role that has required policies attached to it(role only)
providers.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
  }
}
## If you hardcoded the role_arn then it is not required to have two provider configs(one with hardcoded value is enough without any alias).

provider "aws" {
  region = "eu-central-1"
}

provider "aws" {

  alias  = "ec2_and_vpc_full_access"
  region = "eu-central-1"

  assume_role {
    role_arn = data.aws_iam_role.stackoverflow.arn
  }
}

resources.tf
/*
!! Important !!
* Currently the AWS secrets(AWS_ACCESS_KEY_ID & AWS_SECRET_ACCESS_KEY) used for authentication to terraform is
* from the user which has direct AWS managed policy [IAMFullAccess]  attached to it to read role arn.
*/

# If you have hardcoded role_arn in the provider config this can be ignored and no usage of alias provider config is required
## using default provider to read the role.
data "aws_iam_role" "stackoverflow" {
  name = "stackoverflow-ec2-vpc-full-access-role"
}

# Using provider with the role having aws managed policies [ec2 and vpc full access] attached
data "aws_vpc" "default" {
  provider = aws.ec2_and_vpc_full_access

  default = true

}

# Using provider with the role having AWS managed policies [ec2 and vpc full access] attached
resource "aws_key_pair" "eks_jump_host" {
  provider = aws.ec2_and_vpc_full_access

  key_name   = "ec2keypair"
  public_key = file("${path.module}/../../ec2keypair.pub")

}

# Example from https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance
# Using provider with the role having aws managed policies [ec2 and vpc full access] attached
data "aws_ami" "ubuntu" {
  provider = aws.ec2_and_vpc_full_access

  most_recent = true
  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  }
  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }
  owners = ["099720109477"] # Canonical

}

# Using provider with the role having aws managed policies [ec2 and vpc full access] attached
resource "aws_instance" "terraform-ec2" {
  provider = aws.ec2_and_vpc_full_access

  ami             = data.aws_ami.ubuntu.id
  instance_type   = "t2.micro"
  key_name        = "ec2keypair"
  security_groups = [aws_security_group.t-allow_tls.name]

}

# Using provider with the role having aws managed policies [ec2 and vpc full access] attached
resource "aws_security_group" "t-allow_tls" {
  provider = aws.ec2_and_vpc_full_access

  name        = "allow-80-22"
  description = "Allow TLS inbound traffic"
  vpc_id      = data.aws_vpc.default.id
  ingress {
    description      = "http"
    from_port        = 80
    to_port          = 80
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]
  }
}

For a full solution refer to Github Repo, I hope this is something you were looking and helps.


text:
Q: Optimizing spark-sql join with salted_key I have a data channel dataset, i am trying to find the similarity score using it essentially intersection over union of users_id across time of day, channel_id and day of week
my data format:
+--------------------+---+---+----------+
|             user_id|dow|tod|channel_id|
+--------------------+---+---+----------+
|               user1|  1| 10|       111|
|               user2|  6| 21|       111|
|               user1|  1| 19|       123|
|               user1|  1| 20|       124|
|               user3|  1| 21|       009|
|               user4|  1| 10|       900|
+--------------------+---+---+----------+

as data is heavily skewed on channel_id 111 i am using salting technique to run this faster, and below is my code:
val channel_view_by_time = sqlContext.sql("select distinct user_id, dow, tod, channel_id from user_agg_master_table where channel_id not in (111) ")
channel_view_by_time.createOrReplaceTempView("channel_view_by_time")

val uniondf = sqlContext.sql("select " +
  "distinct u1.user_id, u1.channel_id, u1.dow, u1.tod as tod1,  u2.tod as tod2 " +
  "from channel_view_by_time u1 " +
  "inner join channel_view_by_time u2 on u1.channel_id=u2.channel_id and u1.dow=u2.dow ")

val uniondf_t1t2 = uniondf
  .withColumn("t2" ,when('tod2 < 'tod1 ,  'tod1 ).otherwise('tod2).cast("int"))
  .withColumn("t1" ,when('tod2 < 'tod1 ,  'tod2 ).otherwise('tod1).cast("int"))
  .drop("tod2","tod1")

uniondf_t1t2.createOrReplaceTempView("uniondf_t1t2")

val similaritytable = sqlContext.sql("select  channel_id, dow, t1,t2,  " +
  "CASE " +
  "WHEN t1 == t2 THEN 1 " +
  "ELSE (count(user_id)-count(distinct user_id))/count(distinct user_id) " +
  "END as similarityscore " +
  "from uniondf_t1t2 group by channel_id, dow, t1,t2  ")

for channel_id 111 alone i am using salting technique:
val channel_view_by_time_popular = sqlContext.sql("select distinct user_id, dow, tod, channel_id from user_agg_master_table where channel_id in (111) ")
channel_view_by_time_popular.createOrReplaceTempView("channel_view_by_time_popular")
val explode_factor = conf.getInt("explode_factor")

//Using salting technique to optimize run time.
val df_salted = spark.sql("select concat(channel_id,'_', Floor(RAND(1234)*"+explode_factor+")) as salted_key, * from channel_view_by_time_popular ")
df_salted.createOrReplaceTempView("df_salted")

val mySeq = List.range(0, explode_factor.toInt, 1).map(x=>lit(x))
val exploded_df = channel_view_by_time_popular.withColumn("salted_key", explode(array(mySeq:_*)))
exploded_df.createOrReplaceTempView("exploded_df")

val optimized_df = sqlContext.sql("select " +
  "distinct u1.user_id, u1.channel_id, u1.dow, u1.tod as tod1,  u2.tod as tod2 " +
  "from df_salted u1 " +
  "inner join exploded_df u2 on u1.salted_key=concat(u2.channel_id, '_',u2.salted_key) and u1.dow=u2.dow ")

val uniondf_t1t2_popular = optimized_df
  .withColumn("t2" ,when('tod2 < 'tod1 ,  'tod1 ).otherwise('tod2).cast("int"))
  .withColumn("t1" ,when('tod2 < 'tod1 ,  'tod2 ).otherwise('tod1).cast("int"))
  .drop("tod2","tod1")

uniondf_t1t2_popular.createOrReplaceTempView("uniondf_t1t2_popular")

val similaritytable_popular = sqlContext.sql("select  channel_id, dow, t1,t2,  " +
  "CASE " +
  "WHEN t1 == t2 THEN 1 " +
  "ELSE (count(user_id)-count(distinct user_id))/count(distinct user_id) " +
  "END as similarityscore " +
  "from uniondf_t1t2_popular group by channel_id, dow, t1,t2  ")

finally, I take a union of both the result sets.
first part runs fine as data is uniformly distributed.
coming to the second part it completes 90% of tasks pretty quick but will be stuck in the last few tasks this is because there is abnormal distribution of data across tasks:
below is the distribution across tasks when explode_factor is 1:

below is the distribution across tasks when explode_factor is 10:

i could see the skewness of data distribution across tasks is decreased but, i cant increase explode_factor more than 10 as i am doing inner join and data will be increased in size resulting in further slowness.
i Also tried the join part with broadcast but no luck, it is even taking more time than salting technique:
val unionbroadcastdf =  channel_view_by_time.alias("t1")
  .join(broadcast(channel_view_by_time.alias("t2")),
    $"t1.channel_id" === $"t2.channel_id" and $"t1.dow" === $"t2.dow"
  ).select($"t1.user_id", $"t1.channel_id", $"t1.dow", $"t1.tod".alias("tod1"),  $"t2.tod".alias("tod2")).distinct()

Any other ways to improve performance. or any other logic to achive the same result. Please help.


text:
Q: php on trax: passing var to view? I'm very new to PHP on TRAX and the site's doc(s) aren't that great... How do i pass a var (say $monthago) to the view?

A: $this->VariableName = $VariableName;
so simple, I almost felt dumb asking the question :)


text:
Q: Parsing dates in .NET (String to Date) I am trying to parse a string into a date in .NET. I have the following code to do so:
Dim FromDateDate As Date = Date.ParseExact(FromDate, "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)

I discovered however, that this line does not work properly when I Pass 08/18/2010 it parses it to 1/18/2010 12:08:00 AM Can anyone tell me why this is and how to fix it?

A: You need:
Dim FromDateDate As Date = Date.ParseExact(FromDate, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)

The "mm" specifies minutes, "MM" is months.  See Custom Date and Time Format Strings for details.


text:
Q: Debugging a "Metro" UI...says .exe is missing, but it was never included Hey guys im pulling my hair out....I am using Visual Studio 2013 and cannot debug the source files found at http://www.codeproject.com/Articles/442856/Visual-Studio-Metro-Styles-for-WPF
Its a Modern UI application, I get the error message that ".exe cannot be found" which I understand will prevent building and debugging the solution. However. the .exe files are not even in the source folder at all!!
Is there any way to debug this, or actually create the .exe files this solution needs to build properly??? Thanks so much


text:
Q: jquery slideshow won't iterate over dom I found this Jquery slideshow snippet that works great for me except that it won't iterate over the DOM. Right now only the first slideshow in my document will work. I've searched all over and I am pretty sure I need to use .each() so that it will find all of the #slideframe DIVs in my document. Unfortunately I can't seem to use it properly. Any help in getting my portfolio up and running would be a great help!
you can see the "working" site here: LINK
Here is my JQUERY

Here is my HTML:

            <video class="image" src="NEW/PHOTOS/AW17_FW_INSTA_LOCKUP_LO.mp4" type="video/mp4" autoplay loop></video>

1 / 4

            MAC Cosmetics AW17 Fashion Week Branding

            ( Illustrations by culturesport.tv )

                1 / 4
                MAC Cosmetics AW17 Fashion Week Branding
                ( Illustrations by culturesport.tv )

A: You can't use an id more than once. You currently have id="slideframe" in more than one spot. jQuery is able to see the first instance only. Try changing slideframe to a class.

A: First, you should only use one ID per DOM element. So, if you want to refer to multiple slideframe elements, consider using a class identifier, such as in the following example:

(Note you would also want to update the #current and #total elements so that their IDs are not duplicated either.)
Then, in jQuery you would reference these slideframes as follows:
$('.slideframe')
Also, to your point: you would want to iterate over both slideframes so that, for example, calls to .last() would be relative to the correct slideframe.
var $frames = $('.slideframe');
$frames.each(function() {
   var currentFrame = $(this);
   var currentSlides = currentFrame.children();
   currentSlides.click(function () {

        // stores the currently-visible slide
        var $current = $(this);
        if ($current.is(currentSlides.last())) {
            $(".current", currentFrame.next()).text("1"); // note this assumes you have set DOM element to use class="current"
            $current.hide();
            currentSlides.first().show();
        }
        // else, hide current slide and show the next one
        else {
            $(".current", currentFrame.next()).text($current.next().index()+1); // note this assumes you have set DOM element to use class="current"
            $current.hide().next().show();
        }

    });
});


text:
Q: How to Print Python Lists as String I would like to know how to print python lists as String instead of list.
When I add the three lists I get the following result
['a', 'b', 'c', 'd', '0', '1', '!', '#']
I want this output:
abcd01!#
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']

print("Welcome to the PyPassword Generator!")
nr_letters= int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))

#Eazy Level - Order not randomised:
#e.g. 4 letter, 2 symbol, 2 number = JduE&!91

letter_pick = letters[0:nr_letters]
number_pick = numbers[0:nr_symbols]
symbol_pick = symbols[0:nr_numbers]

print (letter_pick+number_pick+symbol_pick)`

expecting
abcd01!#

instead of
['a', 'b', 'c', 'd', '0', '1', '!', '#']

A: You can use join to join all element of list.
print(''.join(letter_pick+number_pick+symbol_pick))

if you only want to print the data. Use this.
print(*(letter_pick+number_pick+symbol_pick), sep='')


text:
Q: Implement autofill service in android app I'm trying to build a password manager application. During the process I've come across a problem: implementing the autofill functionality that other password managers use in their app to let the user easily fill their credentials on a website or in an app. Does anyone know how I can implement this functionality in android studio?enter image description here

A: The first place you will need to start is the AutofillService guide :Build Autofill Service in order to understand: AndroidManifest requirements (BIND_AUTOFILL_SERVICE), permissions, and requirements for your implementation of Autofill service.
Code samples:

*

*Android Input samples (3 years old)

*Android PasswordStore (Best .kt Implementation)

Issues you will run into, targetSDK matching your emulator, and after Android 12 the Autofill Service settings menu seems unreachable through the OS but it is actually: Passwords & Accounts -> Aufofill Section and click Google to select a different one. .
Best of luck.


text:
Q: Resolved: Fix WSUS Server Cleanup crashing on deleting unneeded updates WSUS has always been the bane of every IT Admin existence.  How many threads do you find all with the same issue - the Server Cleanup wizard failing.  The text below worked for me.
I've tried multitudes of SQL scripts both from Microsoft and in the public domain, all with mixed results.  Last week our WSUS server again began coughing furballs so I paid the money and opened a support ticket.  The text below is exactly as received from MS support.  Step 8, in my case, took over a day and a half to complete - and even so with some errors.  I ignored those errors.  Step 9 was quick, but also a couple errors.  I ignored those errors as well (deadlock errors).  Once completed, I re-ran the Server Cleanup wizard and it ran perfect.  All were run within SQL Server Management Studio and using WID.
This is not a question, but my goal to try and help other admins resolve these chronic WSUS issues.  You mileage may very - I hope this helps some of you.
Please follow the below mentioned steps:

--------------------------------------------------------------------------------------------------------------------------------------------

1) Re-indexing:

USE SUSDB;
GO
SET NOCOUNT ON;

-- Rebuild or reorganize indexes based on their fragmentation levels
DECLARE @work_to_do TABLE (
    objectid int
    , indexid int
    , pagedensity float
    , fragmentation float
    , numrows int
)

DECLARE @objectid int;
DECLARE @indexid int;
DECLARE @schemaname nvarchar(130);
DECLARE @objectname nvarchar(130);
DECLARE @indexname nvarchar(130);
DECLARE @numrows int
DECLARE @density float;
DECLARE @fragmentation float;
DECLARE @command nvarchar(4000);
DECLARE @fillfactorset bit
DECLARE @numpages int

-- Select indexes that need to be defragmented based on the following
-- * Page density is low
-- * External fragmentation is high in relation to index size
PRINT 'Estimating fragmentation: Begin. ' + convert(nvarchar, getdate(), 121)
INSERT @work_to_do
SELECT
    f.object_id
    , index_id
    , avg_page_space_used_in_percent
    , avg_fragmentation_in_percent
    , record_count
FROM
    sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, 'SAMPLED') AS f
WHERE
    (f.avg_page_space_used_in_percent < 85.0 and f.avg_page_space_used_in_percent/100.0 * page_count < page_count - 1)
    or (f.page_count > 50 and f.avg_fragmentation_in_percent > 15.0)
    or (f.page_count > 10 and f.avg_fragmentation_in_percent > 80.0)

PRINT 'Number of indexes to rebuild: ' + cast(@@ROWCOUNT as nvarchar(20))

PRINT 'Estimating fragmentation: End. ' + convert(nvarchar, getdate(), 121)

SELECT @numpages = sum(ps.used_page_count)
FROM
    @work_to_do AS fi
    INNER JOIN sys.indexes AS i ON fi.objectid = i.object_id and fi.indexid = i.index_id
    INNER JOIN sys.dm_db_partition_stats AS ps on i.object_id = ps.object_id and i.index_id = ps.index_id

-- Declare the cursor for the list of indexes to be processed.
DECLARE curIndexes CURSOR FOR SELECT * FROM @work_to_do

-- Open the cursor.
OPEN curIndexes

-- Loop through the indexes
WHILE (1=1)
BEGIN
    FETCH NEXT FROM curIndexes
    INTO @objectid, @indexid, @density, @fragmentation, @numrows;
    IF @@FETCH_STATUS < 0 BREAK;

    SELECT
        @objectname = QUOTENAME(o.name)
        , @schemaname = QUOTENAME(s.name)
    FROM
        sys.objects AS o
        INNER JOIN sys.schemas as s ON s.schema_id = o.schema_id
    WHERE
        o.object_id = @objectid;

    SELECT
        @indexname = QUOTENAME(name)
        , @fillfactorset = CASE fill_factor WHEN 0 THEN 0 ELSE 1 END
    FROM
        sys.indexes
    WHERE
        object_id = @objectid AND index_id = @indexid;

    IF ((@density BETWEEN 75.0 AND 85.0) AND @fillfactorset = 1) OR (@fragmentation < 30.0)
        SET @command = N'ALTER INDEX ' + @indexname + N' ON ' + @schemaname + N'.' + @objectname + N' REORGANIZE';
    ELSE IF @numrows >= 5000 AND @fillfactorset = 0
        SET @command = N'ALTER INDEX ' + @indexname + N' ON ' + @schemaname + N'.' + @objectname + N' REBUILD WITH (FILLFACTOR = 90)';
    ELSE
        SET @command = N'ALTER INDEX ' + @indexname + N' ON ' + @schemaname + N'.' + @objectname + N' REBUILD';
    PRINT convert(nvarchar, getdate(), 121) + N' Executing: ' + @command;
    EXEC (@command);
    PRINT convert(nvarchar, getdate(), 121) + N' Done.';
END

-- Close and deallocate the cursor.
CLOSE curIndexes;
DEALLOCATE curIndexes;

IF EXISTS (SELECT * FROM @work_to_do)
BEGIN
    PRINT 'Estimated number of pages in fragmented indexes: ' + cast(@numpages as nvarchar(20))
    SELECT @numpages = @numpages - sum(ps.used_page_count)
    FROM
        @work_to_do AS fi
        INNER JOIN sys.indexes AS i ON fi.objectid = i.object_id and fi.indexid = i.index_id
        INNER JOIN sys.dm_db_partition_stats AS ps on i.object_id = ps.object_id and i.index_id = ps.index_id

    PRINT 'Estimated number of pages freed: ' + cast(@numpages as nvarchar(20))
END
GO

--Update all statistics
PRINT 'Updating all statistics.' + convert(nvarchar, getdate(), 121)
EXEC sp_updatestats
PRINT 'Done updating statistics.' + convert(nvarchar, getdate(), 121)
GO

-------------------------------------------------------------------------------------

2) Run the below query to get the number of superseded updates.

SELECT UpdateID FROM vwMinimalUpdate WHERE IsSuperseded = 1 AND Declined = 0

--------------------------------------------------------------------------------------

3) Run below query to delete all the superseded updates and run server cleanup wizard.

DECLARE @var1 uniqueidentifier
DECLARE @msg nvarchar(100)
DECLARE DU Cursor
FOR
SELECT UpdateID FROM vwMinimalUpdate WHERE IsSuperseded = 1 AND Declined = 0
Open DU
FETCH NEXT FROM DU INTO @var1
WHILE (@@FETCH_STATUS > -1)
BEGIN
 RAISERROR(@msg,0,1) WITH NOWAIT exec spDeclineUpdate @updateID=@var1,@adminName=N'domain\user',@failIfReplica=1
FETCH NEXT FROM DU INTO @var1
END
CLOSE DU
DEALLOCATE DU

---------------------------------------------------------------------------------------

4) Run the following SQL query on SQL against SUSDB database to get number of updates to cleaned up:

exec spGetObsoleteUpdatesToCleanup

----------------------------------------------------------------------------------------

5) Run the Below Query on SQL DB to Delete the updates and then run server cleanup wizard:

DECLARE @var1 INT
DECLARE @msg nvarchar(100)

CREATE TABLE #results (Col1 INT)
INSERT INTO #results(Col1) EXEC spGetObsoleteUpdatesToCleanup

DECLARE WC Cursor
FOR
SELECT Col1 FROM #results

OPEN WC
FETCH NEXT FROM WC
INTO @var1
WHILE (@@FETCH_STATUS > -1)
BEGIN SET @msg = 'Deleting ' + CONVERT(varchar(10), @var1)
RAISERROR(@msg,0,1) WITH NOWAIT EXEC spDeleteUpdate @localUpdateID=@var1
FETCH NEXT FROM WC INTO @var1 END
CLOSE WC
DEALLOCATE WC
DROP TABLE #results

------------------------------------------------------------------------------------------

6) Run the below query, To know no. of updates for XML length 5000 or more:

select
  u.UpdateID,
  r.RevisionNumber,
  r.RevisionID,
  lp.Title,
  pr.ExplicitlyDeployable as ED,
  pr.UpdateType,
  pr.CreationDate
 from
  tbUpdate u
  inner join tbRevision r on u.LocalUpdateID = r.LocalUpdateID
  inner join tbProperty pr on pr.RevisionID = r.RevisionID
  inner join tbLocalizedPropertyForRevision lpr on r.RevisionID = lpr.RevisionID
  inner join tbLocalizedProperty lp on lpr.LocalizedPropertyID = lp.LocalizedPropertyID
 where
  lpr.LanguageID = 1033
  and r.RevisionID in (
select
  t1.RevisionID
from
  tbBundleAll t1
  inner join tbBundleAtLeastOne t2 on t1.BundledID=t2.BundledID
where
  t2.RevisionID in(SELECT dbo.tbXml.RevisionID FROM dbo.tbXml
INNER JOIN dbo.tbProperty ON dbo.tbXml.RevisionID = dbo.tbProperty.RevisionID
where ISNULL(datalength(dbo.tbXml.RootElementXmlCompressed), 0) > 50000) and ishidden=0 and  pr.ExplicitlyDeployable=1)

--------------------------------------------------------------------------------------------------

7) If there are updates present the we decline them with the following cursor:

DECLARE @UpdateID nvarchar(100)
DECLARE @msg nvarchar(100)

CREATE TABLE #Updates (UpdateID nvarchar(100))

INSERT INTO #Updates(UpdateID)
select
  u.UpdateID
  from
  tbUpdate u
  inner join tbRevision r on u.LocalUpdateID = r.LocalUpdateID
  inner join tbProperty pr on pr.RevisionID = r.RevisionID
  inner join tbLocalizedPropertyForRevision lpr on r.RevisionID = lpr.RevisionID
  inner join tbLocalizedProperty lp on lpr.LocalizedPropertyID = lp.LocalizedPropertyID
 where
  lpr.LanguageID = 1033
  and r.RevisionID in (
select
  t1.RevisionID
from
  tbBundleAll t1
  inner join tbBundleAtLeastOne t2 on t1.BundledID=t2.BundledID
where
  t2.RevisionID in(SELECT dbo.tbXml.RevisionID FROM dbo.tbXml
INNER JOIN dbo.tbProperty ON dbo.tbXml.RevisionID = dbo.tbProperty.RevisionID
where ISNULL(datalength(dbo.tbXml.RootElementXmlCompressed), 0) > 50000) and ishidden=0 and  pr.ExplicitlyDeployable=1)

DECLARE UC Cursor
FOR
SELECT UpdateID FROM #Updates

OPEN UC
FETCH NEXT FROM UC
INTO @UpdateID
WHILE(@@FETCH_STATUS > -1)
BEGIN SET @msg = 'Declining ' + @UpdateID
RAISERROR(@msg,0,1) WITH NOWAIT EXEC spDeclineUpdate @updateID=@UpdateID,@adminName=N'mach14\administrator',@failIfReplica=1

FETCH NEXT FROM UC INTO @UpdateID END
CLOSE UC

DEALLOCATE UC
DROP TABLE #Updates

----------------------------------------------------------------------------------------------

8) Declining driver updates:-

USE SUSDB
GO
SELECT UpdateTypeID FROM tbUpdateType WHERE Name = 'Driver'
GO

delete from tbrevisionlanguage where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629'))
delete from tbProperty where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629'))
delete from tbLocalizedPropertyForRevision where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629'))
delete from tbFileForRevision where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629'))
delete from tbInstalledUpdateSufficientForPrerequisite where prerequisiteid in (select Prerequisiteid from tbPreRequisite where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629')))
delete from tbPreRequisite where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629'))
delete from tbDeployment where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629'))
delete from tbXml where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629'))
delete from tbPreComputedLocalizedProperty where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629'))
delete from tbDriver where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629'))
delete from tbFlattenedRevisionInCategory where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629'))
delete from tbRevisionInCategory where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629'))
delete from tbMoreInfoURLForRevision where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629'))
delete from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629')
delete from tbUpdateSummaryForAllComputers where LocalUpdateId in (select LocalUpdateId from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629')

delete from tbUpdate where UpdateTypeID = 'D2CB599A-FA9F-4AE9-B346-94AD54EE0629'

9) Delete Hidden Updates:

SELECT * FROM tbUpdate WHERE isHidden = 1

delete from tbrevisionlanguage where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1))
delete from tbProperty where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1))
delete from tbLocalizedPropertyForRevision where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1 ))
delete from tbFileForRevision where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1 ))
delete from tbInstalledUpdateSufficientForPrerequisite where prerequisiteid in (select Prerequisiteid from tbPreRequisite where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1 )))
delete from tbPreRequisite where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1 ))
delete from tbDeployment where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1 ))
delete from tbXml where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1 ))
delete from tbPreComputedLocalizedProperty where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1 ))
delete from tbDriver where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1))
delete from tbFlattenedRevisionInCategory where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1))
delete from tbRevisionInCategory where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1))
delete from tbMoreInfoURLForRevision where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1))
delete from tbBundleAtLeastOne where bundledid in (select bundledid from tbBundleAll where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1)))
delete from tbBundleAll where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1))
delete from tbSecurityBulletinForRevision where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1))
delete from tbKBArticleForRevision where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1))
delete from tbRevisionSupersedesUpdate where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1))
delete from tbBundleAtLeastOne where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1))
delete from tbEulaProperty where revisionid in (select revisionid from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1))
delete from tbRevision where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1)
delete from tbUpdateSummaryForAllComputers where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1)
delete from tbInstalledUpdateSufficientForPrerequisite where LocalUpdateId in (select LocalUpdateId from tbUpdate where ishidden=1)
delete from tbUpdate where ishidden = 1

------------------------------------------------------------------------------------------------------------------------------

Then open WSUS console and navigate to Options\Server Cleanup Wizard.
And run the wizard one by one.


text:
Q: Does $\int f_1\le\int f_2$ imply $\sup_g\int f_1g\le\sup_g\int f_2g$? in this special situation? Disclaimer: Please bear with me, the question isn't as complicated as it looks like, but I wasn't able to find any simplification for which no counterexample comes to my find.
Let $(E,\mathcal E,\lambda),(E',\mathcal E',\lambda')$ be measure spaces, $I$ be a finite nonempty set, $p,q_i$ be positive probability densities on $(E,\mathcal E,\lambda)$, $\varphi_i:E'\to E$ be bijective and $(\mathcal E',\mathcal E)$ measurable with $\lambda'\circ\varphi_i^{-1}=q_i\lambda$, $w_i:E\to[0,1]$ be $\mathcal E$-measurable with $\sum_{i\in I}w_i=1$ and $r:(E'\times I)^2\to[0,\infty)$ be $\left(\mathcal E'\otimes2^I\right)^{\otimes2}$-measurable with $\sum_{j\in I}\int\lambda'({\rm d}y')r((x',i),(y',j))=1$ for all $(x',i)\in E\times I$. Note that $$\tilde p(x',i):=\left(w_i\frac p{q_i}\circ\varphi_i\right)(x')\;\;\;\text{for }(x',i)\in E'\times I$$ is a probability density on $(E'\times I,\mathcal E'\otimes 2^I,\lambda'\otimes\zeta)$, where $\zeta$ denotes the counting measure on $(I,2^I)$. For simplicity, let $$\sigma((x,i),(y,j)):=r\left(\left(\varphi_i^{-1},i\right),\left(\varphi_j^{-1},j\right)\right)\;\;\;\text{for }(x,i),(y,j)\in E\times I.\tag1$$

I want to choose $(w_i)_{i\in I}$ and $r$ (everything else being fixed) minimizing the quantity $$\eta_{w,\:r}:=\sup_{\tilde g\in L^2\left(\tilde p\left(\lambda'\otimes\zeta\right)\right)}\Psi_{w,\:r}(\tilde g)\tag2,$$ where $$\Psi_{w,\:r}(\tilde g):={\sum_{i\in I}\int\lambda({\rm d}x)\sum_{j\in I}\int\lambda({\rm d}y)\min\left(w_i(x)p(x)q_j(y)\sigma((x,i),(y,j)),w_j(y)p(y)q_i(x)\sigma((y,j),(x,i))\right)\left|\tilde g\left(\varphi_i^{-1}(x),i\right)-\tilde g\left(\varphi_i^{-1}(y),j\right)\right|^2}.$$ Are we able to reduce this problem? For example, are we able to show that if $(\hat w_i)_{i\in I}$, $\hat r$ is another choice for $(w_i)_{i\in I}$, $r$ and \begin{equation}\begin{split}&{\sum_{i\in I}\int\lambda({\rm d}x)\sum_{j\in I}\int\lambda({\rm d}y)\min\left(w_i(x)p(x)q_j(y)\sigma((x,i),(y,j)),w_j(y)p(y)q_i(x)\sigma((y,j),(x,i))\right)}\\&\;\;\;\;\le{\sum_{i\in I}\int\lambda({\rm d}x)\sum_{j\in I}\int\lambda({\rm d}y)\min\left(\hat w_i(x)p(x)q_j(y)\hat\sigma((x,i),(y,j)),\hat w_j(y)p(y)q_i(x)\hat\sigma((y,j),(x,i))\right)}\end{split}\tag3,\end{equation} ($\hat\sigma$ being defined for $\hat r$ as in $(1)$), then $\eta_{w,\:r}\le\eta_{\hat w,\:\hat r}$?


text:
Q: Google One Tap Login on nextjs so i was implement this feature on my next app but weirdly enough when i using dark mode it will show like white border around the iframe but it dissapear on light mode and i using next-auth and tailwind and when i switch theme from light first to dark it didn't show it what should i do and its better to make own auth or next-auth already good
Demo gif

i want to remove the white background around it

A: Ok I found the solution its just to specify the color scheme this same like this post


text:
Q: Eclipse - properties to uppercase I have to change the case (to uppercase) for a lot of entries in a properties file. Is there an easy way to do this using the Eclipse properties editor? The standard (based on internet search) ctrl + shift + x key combination is not working.
Thanks!

A: ctrl + shift + x works for me on Photon, but here are a couple of alternative approaches:

*

*Select the text to be converted to upper case, then position the mouse over the selected text, right-click and from the context menu select Convert > To Upper Case.

*Select the text to be converted to uppercase then ctrl + alt + u. You can also use ctrl + alt + l to toggle to lower case.

To research why ctrl + shift + x is not working for you:

*

*List the current key bindings in Eclipse using Window > Preferences > General > Keys

*The list of key bindings will be displayed in the panel on the right. Click Binding in the header columns to sort the list by binding value.

*Scroll down and locate the entry for ctrl + shift + x, which should be for the To Upper Case command.

*If there are any conflicts they will be shown in the conflicts panel:

*Click the Help button in the bottom left corner of the screen for details on resolving conflicts with key bindings.

*To revert to Eclipse's default setting for the To Upper Case command:

*

*Select its entry in the list of commands.

*Click the Restore Command button.

*Click the Apply button.


text:
Q: Activating a tab through a javascript call (created from an unordered list) I have a tabbed menu created through CSS and an HTML unordered list as shown in this fiddle. When the link is clicked, I want to scroll down to menu item 2 and make it the selected (active) one. I got the scrolling part down but not sure how to activate the tab.
Could someone please share the Javascript/jQuery to do that?
Here is a snippet of my code, please see the fiddle for the rest..
Take me to menu item 3

Home

Menu 1

Menu 2

Menu 3

A: Simply remove the active class from all lis and add the same class to the li you're interested in:

$('a').click( function() {

    $("html, body").animate({ scrollTop: $('#menu2-tab').offset().top }, 1500);

  $(".nav li").removeClass("active");
  $(".nav li").eq(2).addClass("active");

} );
.nav {
 position: relative;
 width:100%;
 margin:0 auto;
}

.nav li{
 float:left;
 position:relative;
 display:block;
 background-color:#fcfcfc;
 border:solid 1px #e2e2e2;
 height:37px;
 line-height:37px;
 text-align:center;
 color:#aeaeae;
 text-transform:uppercase;
 font-family: 'latobold', Arial, Helvetica, sans-serif;
 font-size:13px;
 margin:0 -2px 0 0;

}

.nav.col3 li {
 width:33.3333%;
 *width:33.2222%;
}

.nav li:hover {
 text-decoration:none;
 cursor:pointer;
}

.nav li.active{
 z-index:50;
 font-family: 'latobold', Arial, Helvetica, sans-serif;
 border:solid 1px #e2e2e2;
 border-bottom:1px solid #fff;
 color:#6b7f12;
 background-color:#fff;

}

Take me to menu item 3

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

Here is some other content, you can ignore this.

Here is some other content, you can ignore this.

Here is some other content, you can ignore this.

Here is some other content, you can ignore this.

Here is some other content, you can ignore this.

Here is some other content, you can ignore this.

Home

Menu 1

Menu 2

Menu 3

A: You might want to try this:
Below is the HTML
Take me to menu item 3

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

    Here is some other content, you can ignore this.

Here is some other content, you can ignore this.

Here is some other content, you can ignore this.

Here is some other content, you can ignore this.

Here is some other content, you can ignore this.

Here is some other content, you can ignore this.

Here is some other content, you can ignore this.

Home

Menu 1

Menu 2

Menu 3

Below is the jquery code for selecting
$("a").each(function(){
    var _$this = $(this);
    _$this.click(function(){
        var id = _$this.attr("href");
        $("html, body").animate({ scrollTop: $(id).offset().top }, 1500);
        $(id).parent().find(".active").removeClass("active");
        $(id).addClass("active");
    });
});


text:
Q: httppost Android, values not pass to database for creating user I have been successful in creating an authentication using httppost from java Android code through php to mysql.  I'm having issues create a new user however.  I've checked multiple posts from other users, and I think it looks good.  Also, I've created a simple html form to test the php creation of new user, and that works too.
Any thoughts would be appreciated.  Here is my java code and PHP below that.  Thanks!
    try {
            // create new array list
            nameValuePairs = new ArrayList<NameValuePair>();

            // place them in an array list
            nameValuePairs.add(new BasicNameValuePair("username", user));
            nameValuePairs.add(new BasicNameValuePair("password", pass));

            // add array list to http post
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // assign executed form container to response
            response = httpclient.execute(httppost);

            // check status code,
            if (response.getStatusLine().getStatusCode() == 200) {
                // assign response entity to htpp entitiy
                entity = response.getEntity();

                // chekc if entity is not null
                if (entity != null) {

                    Log.i("RESPONSE",EntityUtils.toString(entity));

                    Intent intent = new Intent(CreateAccount.this,
                            MainActivity.class);
                    startActivity(intent);

                    // }

                    // display a taost saying login was a success
                    Toast.makeText(CreateAccount.this, user,
                            Toast.LENGTH_SHORT).show();
                    // }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            // display toast when there is a connection error
            Toast.makeText(getBaseContext(), "ConnectionError",
                    Toast.LENGTH_SHORT).show();
        }

PHP Code:
    //get form data

$user = mysql_real_escape_string($_POST['user']);

$pass = mysql_real_escape_string($_POST['pass']);

echo "INSERT INTO androidlogin (user, pass) VALUES ('$user','$pass')";

//insert data
$insert = mysql_query("INSERT INTO androidlogin (user, pass) VALUES  ('$user','$pass')");
if($insert){
$arr2 = array("user" => $user, "pass" => $pass);
echo json_encode($arr2);

}

A: When posting values are called "username" and "password"  whereas server checks for "user"  &  "pass". You have to use the same keys.


text:
Q: SQL Server Stored Procedure to Insert 3-Level Hierarchy Given business objects similar to:
public class MyBase
{
    public int Id { get; set; }
}

public class Parent : MyBase
{
    public List<Child> Children { get; set; }
    // Additional objects with 1:1 relationship
}

public class Child : MyBase
{
    public Parent Parent { get; set; }
    public List<Grandchild> Grandchildren { get; set; }
    // Some other properties
}

public class GrandChild : MyBase
{
    public Child { get; set; }
    // Some other properties including a timestamp
}

I'm trying to replace bulk insert functionality originally written with Entity Framework with ADO.Net and stored procedures due to the poor performance of EF in this scenario.
Not being a DB expert, I first oriented myself with
http://www.sommarskog.se/arrays-in-sql-2008.html
Using that guidance I was able to create a well-performing (relative to EF) stored procedure that inserts a Child along with its List<GrandChild>.
CREATE TYPE tvpInt32List AS TABLE (n int NOT NULL)

CREATE PROCEDURE uspInsertChild @parentId INT, @fk1Id INT, @fk2Id INT,
@listValues tvpInt32List READONLY
AS
DECLARE @id INT

BEGIN TRANSACTION

BEGIN TRY
    INSERT INTO dbo.Children VALUES(@fk2Id, @fk1Id, NULL, 0, 1, NULL, NULL, NULL, NULL, NULL, @fk1Id, @parentId)

    SET @Id = SCOPE_IDENTITY()

    INSERT INTO dbo.Grandchildren SELECT n, '', GETDATE(), @id FROM @listValues

    COMMIT TRANSACTION
END TRY

BEGIN CATCH
    ROLLBACK TRANSACTION
END CATCH

However, I would like to take this a step further and create a stored procedure that accepts data for a Parent object and then creates the associated List<Child>, and the List<GrandChild> for each Child.
I'm conceptually at a loss as to how to approach that in a stored procedure.
What strategy can I use to pass in that type of data structure and process it in the stored procedure?

A: Guess you write the stored procedure, in order to input parent and childs, one of the option would be to send your data in xml, which again could be extracted easily from your parent object and the utilize the power of Store procedure to do your transaction.


text:
Q: compiling s-functions for matlab I have been trying to make an s-function block in matlab with my c++ codes.I am using the following mexopts.bat file

@echo off
set MATLAB=%MATLAB%
set PATH=%PATH%;c:\cygwin\bin
set MW_TARGET_ARCH=win64
set COMPILER=x86_64-w64-mingw32-g++
set COMPFLAGS=-c -fexceptions "-I%MATLAB%\extern\include"
set OPTIMFLAGS=-O3
set DEBUGFLAGS=-g -Wall
set NAME_OBJECT=-o
set PRELINK_CMDS1=echo EXPORTS > mex.def & echo mexFunction >> mex.def
set LIBLOC="%MATLAB%\bin\win64"
set LINKER=x86_64-w64-mingw32-g++
set LINKFLAGS= -static-libgcc -shared mex.def -L%LIBLOC%
  -static-libstdc++
set LINKFLAGSPOST= -lmex -lmx -lmwlapack -lmwblas -lstdc++
set LINKOPTIMFLAGS=-O3
set LINKDEBUGFLAGS= -g -Wall
set LINK_FILE=
set LINK_LIB=
set NAME_OUTPUT=-o "%OUTDIR%%MEX_NAME%%MEX_EXT%"
set RSP_FILE_INDICATOR=
set POSTLINK_CMDS1=del mex.def

I am able to successfully compile sample mexfunction file from matlab using the 'mex' function,But when i try compiling an s-function(i took the example files with matlab) i get the following errror
C:\Program Files\MATLAB\R2012a\simulink\include/simstruc.h:357:3: error: #error Must define one of RT, NRT, MATLAB_MEX_FILE, SL_INTERNAL, or FIPXT_SHARED_MODULE

C:\Program Files\MATLAB\R2012a\simulink\include/simstruc.h:467:78: fatal error: rt_matrx.h: No such file or directory
compilation terminated.

I am sure the c++ files are correct ,coz i took them from matlab examples

A: All S-Functions require the following preprocessor symbols to be defined.
MATLAB_MEX_FILE
S_FUNCTION_LEVEL=2
S_FUNCTION_NAME=<your-sfun-name>

Add those to the COMPFLAGS in your batch file using the -D directive.


text:
Q: Mesos make check command produces error I am trying to install mesos using the following commands
$ wget http://www.apache.org/dist/mesos/0.28.2/mesos-0.28.2.tar.gz
$ tar -zxf mesos-0.28.2.tar.gz

instructions for stock Ubuntu 14.04
    # Update the packages.
    $ sudo apt-get update
# Install a few utility tools.
$ sudo apt-get install -y tar wget git

# Install the latest OpenJDK.
$ sudo apt-get install -y openjdk-7-jdk

# Install autotools (Only necessary if building from git repository).
$ sudo apt-get install -y autoconf libtool

# Install other Mesos dependencies.
$ sudo apt-get -y install build-essential python-dev libcurl4-nss-dev                      libsasl2-dev libsasl2-modules maven libapr1-dev libsvn-dev

Then the build commands
    # Change working directory.
    $ cd mesos
# Configure and build.
$ mkdir build
$ cd build
$ ../configure
$ make

# Run test suite.
$ make check

The last command make check produces this error
internal compiler error: killed (program cc1plus) please submit a full bug report,
with preprocessed source if appropriate.
see <file:///usr/share/doc/gcc-4.8/README.Bugs> for instructions.
make[3]: *** [test/mesos_tests-master_tests.o] Error 4
make[3]: Leaving directory '/home/manar/mesos-0.28.2/build/src'
make[2]: *** [check-am] Error 2
make[2]: Leaving directory '/home/manar/mesos-0.28.2/build/src'
make[1]: *** [check] Error 2
make[1]: Leaving directory '/home/manar/mesos-0.28.2/build/src'
make: *** [check-recursive] Error 1

Ubuntu version: 14.04

A: The reported error message comes from GCC. The reason GCC produced an error message is probably because the box ran out of RAM (compiling Mesos needs ~2GB of RAM). What are the hardware specs on the box?


text:
Q: Doesn't CMIS 1.1 work with Alfresco 5.0.d? I am trying to connect to an Alfresco 5.0.d Repository via CMIS 1.1 (apache chemistry 0.13) to read some data and create some objects, but I get exceptions in the repo.

*

*when I try to run a CQL query I get a NPE in org.alfresco.opencmis.CMISNodeInfoImpl:441

*when I try to create an object I get a NPE in org.alfresco.opencmis.mapping.SecondaryTypesProperty:44
In both cases it looks like the CMISConnector object is not fully initialized. All referenced beans are null. Is this a bug in Alfresco 5.0.d or have I missed some config ?
When I do the same against an Alfresco 5.0.c repository, it works fine. That's why I am not attaching any code.

A: Never mind, I had a funny Spring configuration that the CMISConnector instantiate 50+ times, but only one of those instances was complete.


text:
Q: Can I do a request from inside a WebAPI Controller (or BlazorComponent) using the current NTML context? So currently I am inside of a controller, and I want to call another controller with HttpClient.  But when I do, I get a 401:
async Task MakePdf()
{
    var client = HttpFactory.CreateClient();
    var response = await client.GetAsync(myUrl); // this gets a 401
}

I am already authenticated via Windows Authentication, but the request is apparently not sent with the same authorization.  Is there a way to give that client the same credentials as the context inside the controller it is called from?  This is all going to the same app.
This is using Kerberos:
{
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
  }
}

To clarify, I am logged in just fine, but if I send the request from inside a Controller or RazorComponent I will get a 401.


text:
Q: running different versions of a kernel Now the biggest disadvantage in running operating system virtualization is that the user is only able to run the same operating system on all virtualized instances. At least is it possible to run different versions of the same kernel ?

A: The kernel is in charge of managing and abstracting real resources (CPU, devices). So you cannot have several kernels at once on a machine.
What you might have is an hypervisor (which is a sort-of kernel), providing multiple virtual machines. On each of them, you would run a different kernel. You could for example use Xen as an hypervisor (and you could nest them).


text:
Q: /bin/sh: mpic++ command not found in Eclipse for Parallel Application Developers I'm trying to use Eclipse for Parallel Application Developers to do some MPI stuff but I can't get the program to compile.  Below is the error I'm getting in the console:
Description Resource    Path        Location        Type
/bin/sh: mpic++: command not found  prog            C/C++ Problem

I use mpic++ from the command line (bash shell) to successfully compile programs.  When I run the command using bourne shell I get an error.
/bin/sh mpic++
/usr/local/bin/mpic++: /usr/local/bin/mpic++: cannot execute binary file

When I use sudo I still get the same error.  But when I first change to the bourne shell then run the mpic++ command it works.
/bin/sh
sh-3.2$ mpic++
clang: error: no input files

I've been looking at ways to change the shell used by eclipse so I can use the bash shell because I can call mpic++ without any problems.  I've also tried launching eclipse with sudo but that didn't work.

A: I have compiled mpi in eclipse successfully. Please follow the steps:

*

*In terminal type:

$ which mpicxx
/usr/local/bin/mpicxx

You should get the mpicxx binary path as result. I have my mpicxx in /usr/local/bin/ directory.

*In eclipse, go to project properties:

*

*Set GCC C Compiler as: /usr/local/bin/mpicxx

*Also set GCC C+ Compiler as: /usr/local/bin/mpicxx

*Set MacOS X C++ Linker as: /usr/local/bin/mpicxx. Also set All options as -L/usr/local/lib


text:
Q: urllib2.URLError: I'm trying to upload a file to Google via the Adwords API and I'm using the script provided by Google here:https://github.com/googleads/googleads-python-lib
I'm getting the following error after a few minutes.  I've tried this on a smaller file and it works.  Not sure why it is breaking here.  Any ideas?
  File "./g_leads.sh", line 71, in <module>
    main(adwords_client, EMAILS)
  File "./g_leads.sh", line 43, in main
    response = user_list_service.mutateMembers([mutate_members_operation])
  File "/opt/stateadm/.local/lib/python2.7/site-packages/googleads/common.py", line 296, in MakeSoapRequest
    for arg in args])
  File "/opt/stateadm/.local/lib/python2.7/site-packages/suds/client.py", line 521, in __call__
    return client.invoke(args, kwargs)
  File "/opt/stateadm/.local/lib/python2.7/site-packages/suds/client.py", line 581, in invoke
    result = self.send(soapenv)
  File "/opt/stateadm/.local/lib/python2.7/site-packages/suds/client.py", line 613, in send
    reply = self.options.transport.send(request)
  File "/opt/stateadm/.local/lib/python2.7/site-packages/suds/transport/https.py", line 66, in send
    return HttpTransport.send(self, request)
  File "/opt/stateadm/.local/lib/python2.7/site-packages/suds/transport/http.py", line 82, in send
    fp = self.u2open(u2request)
  File "/opt/stateadm/.local/lib/python2.7/site-packages/suds/transport/http.py", line 132, in u2open
    return url.open(u2request, timeout=tm)
  File "/opt/python/lib/python2.7/urllib2.py", line 400, in open
    response = self._open(req, data)
  File "/opt/python/lib/python2.7/urllib2.py", line 418, in _open
    '_open', req)
  File "/opt/python/lib/python2.7/urllib2.py", line 378, in _call_chain
    result = func(*args)
  File "/opt/python/lib/python2.7/urllib2.py", line 1215, in https_open
    return self.do_open(httplib.HTTPSConnection, req)
  File "/opt/python/lib/python2.7/urllib2.py", line 1177, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error [Errno 32] Broken pipe>

A: Errno 32 Broken Pipe means the remote server closed the socket. I would guess the transfer is taking too long because the API documentation shows that they would return an error if the file itself is too big.
Conversely, this may be a intermittent issue at Google per this old thread.


text:
Q: Getting gibberish when sending push notification in Hebrew from java server to android phone using GCM I am using app engine to send push notification in Hebrew to smartphone using Google Cloud Messaging, but when i receive the message on phone the text is ??????? instead of Hebrew.
Here the code for preparing Post message to phone using JSON object:
                JSONObject obj=new JSONObject();
                JSONArray registrationsIDList = new JSONArray();

                Query newsQuery = new Query("Devices");
                List<Entity> results = datastore.prepare(newsQuery).asList(
                        FetchOptions.Builder.withDefaults());
                if(results!=null)
                {
                    for(int j=0;j<results.size();j++)
                    {
                        Entity entity=results.get(j);
                        if(entity!=null)
                        {
                            String ID=(String) entity.getProperty("Registration ID");
                            if(ID!=null)
                            {
                                registrationsIDList.put(ID);
                            }
                        }
                    }
                }

                LinkedHashMap data = new LinkedHashMap();
                data.put("Subject",subjects.get(i).getSubject());
                data.put("Writer", subjects.get(i).getWriter());
                data.put("SubjectDate", subjects.get(i).getLastCommentDateTime());
                data.put("SubjectLink", subjects.get(i).getSubjectLink());

                try {
                    obj.put("registration_ids", registrationsIDList);
                    obj.put("data", data);
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                //Sending message to GCM for devices

                try
                {
                    URL url = new URL("https://android.googleapis.com/gcm/send");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoOutput(true);
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Content-Type", "application/json ; charset=utf-8");
                    connection.setRequestProperty("Authorization", "key=*************************************");

                    OutputStream writer = connection.getOutputStream();
                    Entity tmp=new Entity("JSON");
                    tmp.setProperty("Message", obj.toString());
                    datastore.put(tmp);
                    writer.write(obj.toString().getBytes());
                    writer.close();

                    Entity device=new Entity("Messages Results");
                    device.setProperty("Response Code", connection.getResponseCode());
                    device.setProperty("Response Message", connection.getResponseMessage());
                    datastore.put(device);
                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                    } else {
                        // Server returned HTTP error code.
                    }
                } catch (MalformedURLException ex) {
                    // ...
                } catch (IOException ex) {
                    // ...
                }

Before sending the message, i checked that JSON object holds proper Hebrew text.
Here the code for receiving the message on phone:
@Override
protected void onMessage(Context arg0, Intent arg1) {
    Log.d("GCM", "RECIEVED A MESSAGE");
    String str = arg1.getExtras().getString("Subject");
    Log.d("GCM", str);
    String str1 =arg1.getExtras().getString("Writer");
    Log.d("GCM", str1);
    String str2 =arg1.getExtras().getString("SubjectDate");
    Log.d("GCM", str2);
    String str3 =arg1.getExtras().getString("SubjectLink");
    Log.d("GCM", str3);
}

Now the text is ????????????????? instead of Hebrew.
Any advice will be appreciated.

A: You need to use Unicode: .toString.getBytes("UTF8")


text:
Q: How to place the buttons in UIStackView next to other based on condition? I have a stackview  in which I am adding the buttons dynamically. But I need to add the buttons based on the condition like below:
if trim.contains("0"){
        print("contaim 0")
        let button1 = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 20))
        button1.setTitleColor(UIColor.blackColor(), forState: .Normal)
        button1.setTitle("No", forState: .Normal)
        button1.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
        button1.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
        myStackview.addSubview(button1)
    }
    if trim.contains("1") {
        print("contaim 1")

        let button2 = UIButton(frame: CGRect(x: 90, y: 0, width: 60, height: 20))
            button2.setTitleColor(UIColor.blackColor(), forState: .Normal)
            button2.setTitle("Less", forState: .Normal)
            button2.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
            button2.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
            myStackview.addSubview(button2)

    }
    if trim.contains("2"){
        print("contaim 2")

        let button3 = UIButton(frame: CGRect(x: 150, y: 0, width: 60, height: 20))
        button3.setTitleColor(UIColor.blackColor(), forState: .Normal)

        button3.setTitle("Half", forState: .Normal)
        button3.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
        button3.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
        myStackview.addSubview(button3)
    }
    if trim.contains("3"){
        print("contaim 3")
        let button4 = UIButton(frame: CGRect(x: 210, y: 0, width: 60, height: 20))

        button4.setTitleColor(UIColor.blackColor(), forState: .Normal)

        button4.setTitle("On", forState: .Normal)
        button4.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
        button4.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
        myStackview.addSubview(button4)
    }
    if trim.contains("4"){
        print("contaim 4")
        let button5 = UIButton(frame: CGRect(x: 270, y: 0, width: 60, height: 20))

        button5.setTitleColor(UIColor.blackColor(), forState: .Normal)

        button5.setTitle("With", forState: .Normal)
        button5.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
        button5.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
        myStackview.addSubview(button5)
    }
    if trim.contains("5"){
        print("contaim 5")
        let button6 = UIButton(frame: CGRect(x: 310, y: 0, width: 60, height: 20))

        button6.setTitleColor(UIColor.blackColor(), forState: .Normal)

        button6.setTitle("On Burger", forState: .Normal)
        button6.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
        button6.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
        myStackview.addSubview(button6)
    }
    if trim.contains("6"){
        print("contaim 6")
        let button7 = UIButton(frame: CGRect(x: 370, y: 0, width: 60, height: 20))

        button7.setTitleColor(UIColor.blackColor(), forState: .Normal)

        button7.setTitle("On Chips", forState: .Normal)
        button7.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
        button7.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
        myStackview.addSubview(button7)
    }

here my buttons are adding but at given position in  stackview. My requirement is that, for example if button1  condition is not satisfied then 2nd button should come at the place of first  like that??
the buttons should behave like radiobuttons

A: You can use this code:
var posX = 0
var posY = 0
if trim.contains("0"){
print("contaim 0")
let button1 = UIButton(frame: CGRect(x: posX, y: posY, width: 60, height: 20))
button1.setTitleColor(UIColor.blackColor(), forState: .Normal)
button1.setTitle("No", forState: .Normal)
button1.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
button1.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
myStackview.addSubview(button1)
posX = 60
}
if trim.contains("1") {
print("contaim 1")

let button2 = UIButton(frame: CGRect(x: posX, y: posY, width: 60, height: 20))
button2.setTitleColor(UIColor.blackColor(), forState: .Normal)
button2.setTitle("Less", forState: .Normal)
button2.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
button2.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
myStackview.addSubview(button2)
posX =  posX + 60
}
if trim.contains("2"){
print("contaim 2")

let button3 = UIButton(frame: CGRect(x: posX, y: posY, width: 60, height: 20))
button3.setTitleColor(UIColor.blackColor(), forState: .Normal)

button3.setTitle("Half", forState: .Normal)
button3.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
button3.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
myStackview.addSubview(button3)
posX =  posX + 60
}
if trim.contains("3"){
print("contaim 3")
let button4 = UIButton(frame: CGRect(x: posX, y: posY, width: 60, height: 20))

button4.setTitleColor(UIColor.blackColor(), forState: .Normal)

button4.setTitle("On", forState: .Normal)
button4.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
button4.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
myStackview.addSubview(button4)
posX =  posX + 60
}
if trim.contains("4"){
print("contaim 4")
let button5 = UIButton(frame: CGRect(x: posX, y: posY, width: 60, height: 20))

button5.setTitleColor(UIColor.blackColor(), forState: .Normal)

button5.setTitle("With", forState: .Normal)
button5.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
button5.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
myStackview.addSubview(button5)
posX =  posX + 60
}
if trim.contains("5"){
print("contaim 5")
let button6 = UIButton(frame: CGRect(x: posX, y: posY, width: 60, height: 20))

button6.setTitleColor(UIColor.blackColor(), forState: .Normal)

button6.setTitle("On Burger", forState: .Normal)
button6.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
button6.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
myStackview.addSubview(button6)
posX =  posX + 60
}
if trim.contains("6"){
print("contaim 6")
let button7 = UIButton(frame: CGRect(x: posX, y: posY, width: 60, height: 20))

button7.setTitleColor(UIColor.blackColor(), forState: .Normal)

button7.setTitle("On Chips", forState: .Normal)
button7.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
button7.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
myStackview.addSubview(button7)
}


text:
Q: Core Data Leaking Memory? I keep seeing what appears to be a memory leak - but I can't tell what to do. It looks like a memory leak in Core Data. I can see the LAST method I explicitly invoke in Objective-C, but I'm not creating any object there. I'm saving something and Core Data is leaking memory according to Leaks. Am I reading this incorrectly?

A: I've been informed:

There is a known memory leak in NSFetchedResultsController during the save.
  The fix will be available in 3.1.

Thanks.

A: I have a similar trace in Leaks and it looks to me like Core Data or NSFetchedResultsController is leaking memory. I've attached my own screenshot. My guess is that yes, Core Data is leaking memory.

See larger version


text:
Q: Defining multiple type instances I have to define let sideCalendar, which returns the following console log:

Interface I currently have:
interface ICalendar{
  month: moment.Moment;
  calendar?: {
    [key: number]: moment.Moment | null;
    'firstDay': moment.Moment;
    'lastDay': moment.Moment;
  };
}

How can I define multiple arrays like these? For now, only one instance is described:
    [key: number]: moment.Moment | null;

A: If you try what you're trying to do TypeScript will narrow the Record value type to what's common. For example:
type A = Record<number, string | number>;
type B = Record<number, boolean | string>;
type C = A & B;

const data: C = {
    42: 'foo'
};

The common type between A and B is string, so the value of the 42 property must also be a string.

A: Since the numbered keys will contain an array that has either moment.Moment or null in them, you will need to define it as [key: number]: Array<moment.Moment | null>:
interface ICalendar {
  month: moment.Moment;
  calendar?: {
    [key: number]: Array<moment.Moment | null>;
    'firstDay': moment.Moment;
    'lastDay': moment.Moment;
  };
}


text:
Q: CSS3 circle with clickable items jQuery(Radial Menu) Where can I find an example to create a circle like this with css3 and jQuery (for navigation)
There should be text (html) in the center
When you click (or hover) the next item, the center content should change, and also the background color

A: forked from codepen

/**
 * Circular menu v2
 */
* { margin: 0; padding: 0; }
html { font: 100%/1.3 Century Gothic, Verdana, sans-serif; }
body { overflow: hidden; min-width: 20em; }
.menuopt { display: none; }
.circle, .circle:before, .circle:after { border-radius: 50%; }
nav {
 margin: 5em auto;
 min-width: 16em; width: 72%; max-width: 40em;
}
nav ul {
 position: relative;
 padding: 50%;
 max-width: 0; max-height: 0;
 box-shadow: 0 0 .5em rgba(0,0,0,.5);
 list-style: none;
 background: white;
}
nav li {
 position: absolute;
 transition: 2s;
}
.slice {
 overflow: hidden;
 position: absolute;
 top: 0; left: 0;
 width: 50%; height: 50%;
 transform-origin: 100% 100%;
}
.unsel {
 top: 34%; left: 34%;
 width: 32%; height: 32%;
 box-shadow: 0 0 .75em;
 background: paleturquoise;
}
.coconut { transform: skewX(50deg); }
.vanilla { transform: rotate(40deg) skewX(50deg); }
.orange { transform: rotate(80deg) skewX(50deg); }
.almond { transform: rotate(120deg) skewX(50deg); }
.grape { transform: rotate(160deg) skewX(50deg); }
.blackberry { transform: rotate(-160deg) skewX(50deg); }
.cherry { transform: rotate(-120deg) skewX(50deg); }
.strawberry { transform: rotate(-80deg) skewX(50deg); }
.raspberry { transform: rotate(-40deg) skewX(50deg); }
.magnifiable { height: 100%; }
nav label { cursor: pointer; }
.slice label {
 display: block;
 width: 200%; height: 200%;
 transform: skew(-50deg) rotate(-70deg);
 box-shadow: 0 0 .1em black;
 opacity: .5;
 color: transparent;
 font-size: .8em;
 line-height: 1.9;
 text-align: center;
 text-decoration: none;
 transition: 1s;
}
.slice label:before {
 position: absolute;
 top: 10%; left: 10%;
 width: 80%; height: 80%;
 border-radius: 50%;
 box-shadow: 0 0 1em rgba(0,0,0,.5);
 background-position: 50% 0;
 background-repeat: no-repeat;
 background-size: 35% 35%;
 content: '';
}
.slice label:hover { opacity: 1; }
.dark label:hover { color: white; }
.light label:hover { color: black; }
.unsel label {
 display: block;
 height: 100%;
 background: radial-gradient(rgba(0,0,0,.5), transparent 50%);
}
.coconut label, .ococonut:checked ~ nav .unsel { background: #f4f5fa; }
.vanilla label, .ovanilla:checked ~ nav .unsel { background: #ffeb98; }
.orange label, .oorange:checked ~ nav .unsel { background: #ffb038; }
.almond label, .oalmond:checked ~ nav .unsel { background: #d3a573; }
.grape label, .ogrape:checked ~ nav .unsel { background: #d9e260; }
.blackberry label, .oblackberry:checked ~ nav .unsel { background: #833a68; }
.cherry label, .ocherry:checked ~ nav .unsel { background: #b1001d; }
.strawberry label, .ostrawberry:checked ~ nav .unsel { background: #ec0404; }
.raspberry label, .oraspberry:checked ~ nav .unsel { background: #ef6982; }
.coconut label:before { background-image: url(http://upload.wikimedia.org/wikipedia/commons/thumb/4/4a/Cocos_nucifera00.jpg/320px-Cocos_nucifera00.jpg); }
.vanilla label:before { background-image: url(http://www.learningherbs.com/image-files/vanilla-extract-7.jpg); }
.orange label:before { background-image: url(http://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/OrangeBloss_wb.jpg/250px-OrangeBloss_wb.jpg); }
.almond label:before { background-image: url(http://upload.wikimedia.org/wikipedia/commons/thumb/8/84/PikiWiki_Israel_7025_Amond_blossom.jpg/170px-PikiWiki_Israel_7025_Amond_blossom.jpg); }
.grape label:before { background-image: url(http://upload.wikimedia.org/wikipedia/commons/thumb/b/bb/Table_grapes_on_white.jpg/220px-Table_grapes_on_white.jpg); }
.blackberry label:before { background-image: url(http://upload.wikimedia.org/wikipedia/commons/thumb/7/78/Ripe%2C_ripening%2C_and_green_blackberries.jpg/220px-Ripe%2C_ripening%2C_and_green_blackberries.jpg); }
.cherry label:before { background-image: url(http://upload.wikimedia.org/wikipedia/commons/thumb/b/bb/Cherry_Stella444.jpg/220px-Cherry_Stella444.jpg); }
.strawberry label:before { background-image: url(http://upload.wikimedia.org/wikipedia/commons/thumb/2/29/PerfectStrawberry.jpg/220px-PerfectStrawberry.jpg); }
.raspberry label:before { background-image: url(http://upload.wikimedia.org/wikipedia/commons/thumb/6/69/Raspberries05.jpg/220px-Raspberries05.jpg); }
.slice label:hover:after { opacity: 0; }
.ococonut:checked ~ nav .coconut { transform: skewX(50deg) scale(1.05); }
.ovanilla:checked ~ nav .vanilla { transform: rotate(40deg) skewX(50deg) scale(1.05); }
.oorange:checked ~ nav .orange { transform: rotate(80deg) skewX(50deg) scale(1.05); }
.oalmond:checked ~ nav .almond { transform: rotate(120deg) skewX(50deg) scale(1.05); }
.ogrape:checked ~ nav .grape { transform: rotate(160deg) skewX(50deg) scale(1.05); }
.oblackberry:checked ~ nav .blackberry { transform: rotate(-160deg) skewX(50deg) scale(1.05); }
.ocherry:checked ~ nav .cherry { transform: rotate(-120deg) skewX(50deg) scale(1.05); }
.ostrawberry:checked ~ nav .strawberry { transform: rotate(-80deg) skewX(50deg) scale(1.05); }
.oraspberry:checked ~ nav .raspberry { transform: rotate(-40deg) skewX(50deg) scale(1.05); }
.ococonut:checked ~ nav .coconut label,
.ovanilla:checked ~ nav .vanilla label,
.oorange:checked ~ nav .orange label,
.oalmond:checked ~ nav .almond label,
.ogrape:checked ~ nav .grape label,
.oraspberry:checked ~ nav .raspberry label {
 box-shadow: 0 0 .45em rgba(0,0,0,.5);
 opacity: 1; color: black;
}
.oblackberry:checked ~ nav .blackberry label ,
.ocherry:checked ~ nav .cherry label,
.ostrawberry:checked ~ nav .strawberry label {
 box-shadow: 0 0 .45em rgba(0,0,0,.5);
 opacity: 1; color: white;
}
@media (min-width: 25em) { .slice label { font-size: 1em; line-height: 2.3; } }
@media (min-width: 35em) { .slice label { font-weight: 700; line-height: 2.7; } }

<input type='radio' name='opt' id='ococonut' class='menuopt ococonut'>
<input type='radio' name='opt' id='ovanilla' class='menuopt ovanilla'>
<input type='radio' name='opt' id='oorange' class='menuopt oorange'>
<input type='radio' name='opt' id='oalmond' class='menuopt oalmond'>
<input type='radio' name='opt' id='ogrape' class='menuopt ogrape'>
<input type='radio' name='opt' id='oblackberry' class='menuopt oblackberry'>
<input type='radio' name='opt' id='ocherry' class='menuopt ocherry'>
<input type='radio' name='opt' id='ostrawberry' class='menuopt ostrawberry'>
<input type='radio' name='opt' id='oraspberry' class='menuopt oraspberry'>
<input type='radio' name='opt' id='unsel' class='menuopt' checked>

    Coconut

    Vanilla

    Orange

    Almond

    Grape

    Blackberry

    Cherry

    Strawberry

    Raspberry

Or even this one

$(document).ready(function() {
  //Center the "info" bubble in the  "circle" div
  var divTop = ($("#divCircle").height() - $("#middleBubble").height()) / 2;
  var divLeft = ($("#divCircle").width() - $("#middleBubble").width()) / 2;
  $("#middleBubble").css("top", divTop + "px");
  $("#middleBubble").css("left", divLeft + "px");

  //Arrange the icons in a circle centered in the div
  numItems = $("#divCircle img").length; //How many items are in the circle?
  start = 0.0; //the angle to put the first image at. a number between 0 and 2pi
  step = (4 * Math.PI) / numItems; //calculate the amount of space to put between the items.

  //Now loop through the buttons and position them in a circle
  $("#divCircle img").each(function(index) {
    radius = ($("#divCircle").width() - $(this).width()) / 2.3; //The radius is the distance from the center of the div to the middle of an icon
    //the following lines are a standard formula for calculating points on a circle. x = cx + r * cos(a); y = cy + r * sin(a)
    //We have made adjustments because the center of the circle is not at (0,0), but rather the top/left coordinates for the center of the div
    //We also adjust for the fact that we need to know the coordinates for the top-left corner of the image, not for the center of the image.
    tmpTop = (($("#divCircle").height() / 2) + radius * Math.sin(start)) - ($(this).height() / 2);
    tmpLeft = (($("#divCircle").width() / 2) + radius * Math.cos(start)) - ($(this).width() / 2);
    start += step; //add the "step" number of radians to jump to the next icon

    //set the top/left settings for the image
    $(this).css("top", tmpTop);
    $(this).css("left", tmpLeft);
  });

});

$('.avatarList').click(function() {
  $(this).toggleClass('expand');
  $('#divCircle').toggleClass('expand');
});

$('#divCircle img').click(function() {
  var theSrc = $(this).attr('src');
  // alert(theSrc);
  $('.mainImg img').attr('src', theSrc);
});
html {
  background: #f2f6f8;
  /* Old browsers */
  background: -moz-linear-gradient(top, #f2f6f8 0%, #d8e1e7 50%, #b5c6d0 51%, #e0eff9 100%);
  /* FF3.6+ */
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f2f6f8), color-stop(50%, #d8e1e7), color-stop(51%, #b5c6d0), color-stop(100%, #e0eff9));
  /* Chrome,Safari4+ */
  background: -webkit-linear-gradient(top, #f2f6f8 0%, #d8e1e7 50%, #b5c6d0 51%, #e0eff9 100%);
  /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(top, #f2f6f8 0%, #d8e1e7 50%, #b5c6d0 51%, #e0eff9 100%);
  /* Opera 11.10+ */
  background: -ms-linear-gradient(top, #f2f6f8 0%, #d8e1e7 50%, #b5c6d0 51%, #e0eff9 100%);
  /* IE10+ */
  background: linear-gradient(to bottom, #f2f6f8 0%, #d8e1e7 50%, #b5c6d0 51%, #e0eff9 100%);
  /* W3C */
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#f2f6f8', endColorstr='#e0eff9', GradientType=0);
  /* IE6-9 */
}
.body {
  width: 200px;
  font-family: sans-serif;
  margin: 10% auto;
  text-align: center;
  height: 200px;
}
#divCircle {
  width: 195px;
  height: 195px;
  border-radius: 200px;
  position: relative;
  overflow: hidden;
  top: -10px;
  left: -10px;
  opacity: 0;
  margin: -60px;
  -webkit-transition: opacity 0s 0s;
}
#divCircle img {
  position: absolute;
  width: 50px;
  height: 50px;
  background: orange;
  border-radius: 60px;
  border: 2px #000 solid;
  -webkit-transition: all 0.4s;
}
#divCircle img:hover {
  border: 2px #333 solid;
  width: 55px;
  height: 55px;
}
#middleBubble {
  text-align: center;
  vertical-align: top;
  color: #252525;
  /*#6d6e71*/
  height: 60px;
  width: 60px;
  position: absolute;
  text-align: center;
}
#middleBubble img {
  top: 0px !important;
  left: 0px !important;
}
.mainImg {
  width: 60px;
  position: absolute;
  margin: -60px;
}
.mainImg img {
  width: 60px;
  border-width: 0px;
  border-style: solid;
  border-color: rgba(0, 0, 0, 0);
  border-radius: 600px;
  overflow: hidden;
  -webkit-transition: all 0.5s;
  margin: 60px 0 0 60px;
}
.avatarList {
  margin: 0px -60px;
  display: inline-block;
  /*  border:1px black solid; */
  width: 60px;
  height: 60px;
  background: orange;
  border-radius: 60px;
}
.avatarList.expand .mainImg img {
  border-color: rgba(0, 0, 0, 1);
  border-width: 60px;
  margin: 0;
}
#divCircle.expand {
  display: block;
  opacity: 1;
  -webkit-transition: opacity 0.5s 0.4s;
}

Click to pick avatar


text:
Q: Adding content to Facebook feed dialog from Facebook SDK for Android In my android app, I want users to "share" my app in their wall, so I want them to post a predefined content status on their wall.
How can I customize the wall status? (I want to add my app icon and some flare text).

A: Download the Facebook SDK and import it in your project. Then use the following code to Authorize:
    public void sendtoFacebook(){
        facebookClient = new Facebook("<Your_APP_ID");
        facebookClient.authorize(<Current_class>.this, new AuthorizeListener());
    }

Now you have to add the following methodes:
class AuthorizeListener implements DialogListener {
    public void onComplete(Bundle values) {
        Bundle parameters = new Bundle();
            parameters.putString("message", "<Message_you_want_to_send>");// the message to post to the wall
            facebookClient.dialog(<Current_class>.this, "stream.publish", parameters, this);// "stream.publish" is an API call
    }
    @Override
    public void onFacebookError(FacebookError e) {
    }
    @Override
    public void onError(DialogError e) {
    }
    @Override
    public void onCancel() {
    }
}

Your Application name and Icon will automatically be added :)

A: After learning the Facebook API, I came across this page
so now I know all the options for the bundle parameters.
Thanks everyone for your help!

A: You can also do that without the SDK, just via Share URL:
public void shareOnFacebook(View v) {

    Uri uri = Uri.parse("http://m.facebook.com/sharer.php?u=http://yourdomain/page.html&t=YourMessage");
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}

You just need to put a content page / html somewhere on your server, under the url your provided to the sharer.
If you want that a certain image appears in the shared message, put this in the meta tag of your html page on the server that you're sharing:
<link rel="image_src" type="image/jpeg" href="http://yourdomain.com/promo/image.png" />

See a sample of such promo page with linked image: http://www.modelme.co.uk/promo/amandaharrington

A: This is how I am making a bundle to set content via a facebook dialog using the Facebook SDK
Bundle parameters = new Bundle();
        parameters.putString("app_id", "xxxxxxx");
        parameters.putString("link", "https://play.google.com/store/apps/details?id=myappistasty");
        parameters.putString("name", "This is the name of the link set in app.");
        parameters.putString("caption", "This is Text that is specified in bt the aoo");
        parameters.putString("picture", "www.urltoimage.com);
facebook.dialog(MainActivity.this, "feed", parameters, new DialogListener() {
etc...

http://developers.facebook.com/docs/reference/dialogs/feed/
this is the link that explained all to me, although none of it is in java the table gives you a good idea.


text:
Q: Hazelcast partition counts and thread concurrency In the Master Hazelcast eBook under "17.4.1. Partition-aware Operations" it states:

To execute partition-aware operations, an array of operation threads is created.
A single operation thread executes operations for multiple partitions;
Each partition belongs to only 1 operation thread.

Suppose I have the default number of 271 partitions on a 17-node cluster each with 16 partition threads. Distributing the partitions across the cluster, this means all partitions will have one thread associated with it and each thread will only have 1 partition (seems the optimal case to me).
Ignoring backups and near-caches, when I create an IMap instance, does this mean I can only ever have 1 concurrent put/get operation executing on every map partition across the cluster? Going further, if I attach a MapStore, does this mean I can only ever have 271 concurrent operations running against my backend database, since there is no way of making async MapStores?
My reason for asking this is that I have a highly concurrent web-application, and I recently switched the datastore to run with Hazelcast IMap in front of it. The application accepts thousands of concurrent connection and almost every single request performs at least a get operation from the distributed map. I'm seeing a lot of these errors:
com.hazelcast.core.OperationTimeoutException: No response for 20000 ms. Aborting invocation! Invocation{serviceName='hz:impl:mapService', op=com.hazelcast.map.impl.operation.GetOperation{identityHash=1003806362, serviceName='hz:impl:mapService', partitionId=244, replicaIndex=0, callId=55212219, invocationTime=1462913274676 (Tue May 10 20:47:54 UTC 2016), waitTimeout=-1, callTimeout=10000, name=..., name=...}, partitionId=244, replicaIndex=0, tryCount=250, tryPauseMillis=500, invokeCount=1, callTimeout=10000, target=Address[10.0.2.221]:5701, backupsExpected=0, backupsCompleted=0, connection=Connection [/10.0.2.219:5701 -> /10.0.2.221:14565], endpoint=Address[10.0.2.221]:5701, alive=true, type=MEMBER} No response has been received!  backups-expected:0 backups-completed: 0
Could this simply be caused by the MapStore blocking the partition thread while it's trying to fetch from the database? I should also note that while it says No response for 20000 ms, 20s has not elapsed.
I'm running Hazelcast 3.6.2 on Java 8.

A:

gnoring backups and near-caches, when I create an IMap instance, does this mean I can only ever have 1 concurrent put/get operation executing on every map partition across the cluster?

Correct. So it could be that partition 25 of map a and map b, is busy processing an operation for map b and therefor an operation for map a needs to wait.

Going further, if I attach a MapStore, does this mean I can only ever have 271 concurrent operations running against my backend database, since there is no way of making async MapStores?

For a write through mapstore --> yes. But I'm not that familair with writebehind (async) mapstores threading model.

Could this simply be caused by the MapStore blocking the partition thread while it's trying to fetch from the database? I should also note that while it says No response for 20000 ms, 20s has not elapsed.

That could very well be the cause.


text:
Q: How to create a decorator class that does not take any argument and can be imported by another class for API authentication My user case is I want to create a decorator Util that I can consume throughout the application, I want it like a module and it should not take any arguments. There are many example of writing a function but very few for class.

A: '''
from flask import make_response, jsonify
import functools
class IsAdmin(object):
  def __init__(self, arg):
      self._arg = arg #--> self._args will hold the method
      functools.update_wrapper(self, arg)
  def __call__(self, *param_arg): #param_arg will hold the method params(2,2)
      (status,msg) = util.isOwner()
      if status == True and msg == 'is Owner':
        #If there are decorator arguments, __call__() is only called onceas part of the decoration process. You can only give it a single argument,which is the function objectIf there are no decorator arguments, the functionto be decorated is passed to the constructor.>
        # if len(param_arg) == 1:
        #     def wrapper(*main_args): #--> here we are passing the values that we pass to the function
        #         retval = param_arg[0](self, main_args[0], main_args[1])
        #         return retval ** self._arg[0]
        #     return wrapper
        # else:
        # expo = 2
        retval = self._arg(self, *param_arg)
        return retval
    else:
        return "you are not the admin"

'''


text:
Q: Check string in PHP I want to check some string before sending an email.
I have 3 fields: name +  email + text
I'm wondering if mysql_escape_string is good even  If I'll not insert the values into a sql table. So I used:
PHP code:

  $name = trim($name);
  $name = strip_tags($name);
   # etc

Question:
It's enough?
EDIT:
I want to remove HTML Tags (Expet
 &
 from the Text Field) + Trim the strings

A: Actually you can pass strip_tags what you want to allow
example:
<?php
$text = '
Test paragraph.

';
// Allow
 and

echo strip_tags($text, '

');
?>

A: If you want to remove all HTML Tags except
 &
:
$name = strip_tags(trim($name), '

');

Second argument to strip_tagsDocs is the allowed tags. But you can not specify which attributes to preserve or drop for the tags with that function.
I'm pretty sure how to do that has been already asked on this site, so you should take a search or look at this duplicate:

*

*PHP function to strip tags, except a list of whitelisted tags and attributes

A: You really want to read the documentation  of filter_var, filter_var_array, filter_input and filter_input_array. That's the modern way to go, with this you're able to compose complex filtering and sanatizing.

A: I didn't create this snippet, and I've misplaced the source, but this function seems to do a decent job of sanitizing for me and my low-traffic sites:
#   Sanitizer function - removes forbidden tags, including script tags
function strip_tags_attributes( $str,
    $allowedTags = array('','','
','
','','','','
','','
','
','
','
','
','
','','','','<q>','
','
','
','
','<samp>','','','','
','
','
','','','
',''),
    $disabledEvents = array('onclick','ondblclick','onkeydown','onkeypress','onkeyup','onload','onmousedown','onmousemove','onmouseout','onmouseover','onmouseup','onunload') )
{
    if( empty($disabledEvents) ) {
        return strip_tags($str, implode('', $allowedTags));
    }
    return preg_replace('/<(.*?)>/ies', "'<' . preg_replace(array('/javascript:[^\"\']*/i', '/(" . implode('|', $disabledEvents) . ")=[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", strip_tags($str, implode('', $allowedTags)));
}

HTH.


text:
Q: Log4jConfigurer in Spring 5 I had upgraded my project from Spring 4 to Spring 5 and I am resolving the deprecated/removed classes. As part of the effort I had noticed that log4jConfigurer is removed from Spring 5.
I have the following code:
<bean
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetClass" value="org.springframework.util.Log4jConfigurer"/>
    <property name="targetMethod" value="initLogging"/>
    <property name="arguments">
        <list>
            <value>file:///${logPropertyFile}</value>
        </list>
    </property>
</bean>

I am aware of the fact that many had posted a similar question but I don't see any explanation on how to do when I have custom path for the log4j2 configuration file.
I am aware of the fact that we can put it in web.xml file but I want to load a different log file configuration for the child project irrespective of the parent project log configuration. So, Spring context file is best place of it.
I would like to know how to resolve the Log4jConfigurer for custom log file in Spring-5.
Thanks in advance!

A: You could try using the log4j PropertyConfigurator instead?
<property name="targetClass" value="org.apache.log4j.PropertyConfigurator"/>
        <property name="targetMethod" value="configure"/>
        <property name="arguments">
            <list>
                <value>${logPropertyFile}</value>
            </list>
</property>

The configure(String) method is backed by a FileInputStream where typically the path is referenced without using a file: scheme ...