Q: How to get an array of files to upload I am running into a scenario that I cannot get more than one file to upload. If I add more than one file, only the last one will send through. I know this means I need to put the files into an array, but when I try I get an error from the fileUpload class.
IF I change the input html's name to `name="uploadedFile[]"' then I get the following error in my fileUpload class:

PHP Warning:  basename() expects parameter
1 to be string, array given in
/php/fileUpload.php on line 11
PHP Warning:  move_uploaded_file() expects parameter 1
to be string, array given in
/php/fileUpload.php on line 46

Then in my Communication class, you will see that if there is more than one file being uploaded, I send it as a zip, so I'm not sure if anything would need to be changed in there.
Does anyone see what I need to do to get the array to work?
HTML:
<input type="file" name="uploadedFile" class="inputfile" id="uploadedFileTest" data-multiple-caption="{count} files selected" multiple>

FileUpload class:
class fileUpload
{

    public function __construct()
    {}
    public function upload() {

        $target_dir = "uploads/";
        $target_file = $target_dir . basename($_FILES["uploadedFile"]["name"]);
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            return 0;
// if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $target_file)) {
                return basename($_FILES["uploadedFile"]["name"]);
            } else {
                return 0;
            }
        }
    }
}

Rest of the php file:
$files = null;
if (!empty($_FILES['uploadedFile']['name']) && $_FILES['uploadedFile']['error'] != 4) {
    $fu = new fileUpload();
    $filename = $fu->upload();
    $template = str_replace("{filename}", "A file was uploaded. You can download the file from: {$filename}", $template);
    clearstatcache();
}

Communication Class - what sends out the attachment(s):
if (!empty($file) && !$recipient && count($file['uploadedFile']['name']) > 1) {

                $f = new ZipArchive();
                $zip = $f->open('uploads/' . $file['uploadedFile']['name'][0] . ".zip", ZipArchive::CREATE | ZipArchive::OVERWRITE);
                if ($zip) {
                    for ($index = 0; $index < count($file['uploadedFile']['name']); $index++) {
//                        echo $file['uploadedFile']['name'][$index] . "\n";
                        $f->addFile($file['uploadedFile']['tmp_name'][$index], $file['uploadedFile']['name'][$index]);
                    }
                    $f->close();

                    $message["attachment[0]"] = curl_file_create("uploads/{$file['uploadedFile']['name'][0]}.zip",
                        pathinfo("uploads/{$file['uploadedFile']['name'][0]}.zip", PATHINFO_EXTENSION),
                        $file['uploadedFile']['name'][0] . ".zip");
                } else {
                    throw new Exception("Could not zip the files.");
                }
//                $message['html'] = str_replace("{filename}", "A file was uploaded. You can download the file from: {$file['uploadedFile']['name']}", $message['html']);

            } elseif (count($file['uploadedFile']['name']) == 1) {
                $message["attachment[0]"] = curl_file_create("uploads/{$file['uploadedFile']['name']}",
                    pathinfo("uploads/{$file['uploadedFile']['name']}", PATHINFO_EXTENSION),
                    $file['uploadedFile']['name']);

            }

A: Try inspecting the $_FILES array to see the structure of a single file upload and a mulit-file upload.
Here is a small function you can use to visually inspect an array:
function varDumpToString($var, $type=false){
    ob_start();
    var_export($var);
    $return = ob_get_clean();

    return ($type === 'web'
        ? str_replace("\n", '
', $return)
        : $return
    );
}

Usage:
echo varDumpToString($_FILES, 'web');

Alternatively:
error_log(varDumpToString($_FILES));


Q: Fish adb not found I installed fish shell on my macbook. when I try to run the command adb - get error fish: Unknown command 'adb', though adb is added to .bash_profile. How to fix it?
~/.bash_profile
export ADB=:/Users/mancj/Library/Android/sdk/platform-tools/
export PATH=$ADB:$PATH

EDIT:
I tried a cd in the adb folder and run the adb command , also get error fish: Unknown command 'adb'

A: fish doesn't care about bash's startup files, see https://fishshell.com/docs/current/tutorial.html#tut_startup
You need to change your PATH in ~/.config/fish/config.fish instead and restart the shell.

A: Within Android Studio's Terminal, run the following command:
set PATH ~/Library/Android/sdk/platform-tools $PATH
This means any executable within the given path (adb in our case) can be run by its name rather than path directory.
If you're not using FISH, you can achieve the same using this command:
export PATH="~/Library/Android/sdk/platform-tools":$PATH

A: Use
fish_add_path /Users/mancj/Library/Android/sdk/platform-tools/
or you can add the same to ~/.config/fish/config.fish
Might need to re start the shell

A: Further, it's unlikely that fish includes '.' (i.e. the CWD) in its path by default, so simply entering the directory containing the binary you want to run is not likely to work.  If that's strictly necessary, explicitly specify the path:
$ ./binary_to_run
In general, including '.' in the path is a security exploit waiting to happen.


Q: How to configure spark runner for apache beam pipeline for java I'm new to Apache Beam and Apace spark, i want to configure the beam pipeline for spark runner. what is mentioned in the documentation is not clear to me.

A: You can pass argument --runner SparkRunner to the pipeline launcher to use spark as the underlying runner. Also, Please share what language of Beam SDK you are using. Python and java have some what different ways to run on Spark via Beam.


Q: LLVM segmentation fault with opt command when i am trying to run the very simple (Hello world) pass given in llvm (my file is pass Hello.cpp) on a file XX.c
(X64 OS)
the opt command
opt -load ../../../Release+Asserts/lib/Hello.so -hello vv.bc > vv.txt

gives this error
0  libLLVM-3.2svn.so 0x00007f314b0f1e52
1  libLLVM-3.2svn.so 0x00007f314b0f22b3

2  libpthread.so.0   0x00007f314a0c7340

3  libstdc++.so.6    0x00007f31499645cb std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) + 11

4  libLLVM-3.2svn.so 0x00007f314aadef1d llvm::createPrintFunctionPass(std::string const&, llvm::raw_ostream*, bool) + 77

5  libLLVM-3.2svn.so 0x00007f314aad1585 llvm::PMTopLevelManager::schedulePass(llvm::Pass*) + 37

6  opt               0x0000000000413e4f main + 4767

7  libc.so.6         0x00007f31492eeec5 __libc_start_main + 245

8  opt               0x000000000040dfca
Stack dump:
0.  Program arguments: opt -load ../../../Release+Asserts/lib/Hello.so -hello vv.bc

Segmentation fault (core dumped)
any suggestion would be appreciable. I am new to both Linux and llvm

A: Something I found extremely useful is to use the verifier pass.
So first, make sure basic opt flow works as intended, and that the input file is legal:
opt -verify vv.bc -o out.bc

Then make sure your pass results in a legal module:
opt -load ../../../Release+Asserts/lib/Hello.so -hello -verify vv.bc -o out.bc

If that still won't help, I'd fire up the debugger.


Q: Is it possible to create fluent interface that can nest generic types many times in C# I'm trying to create a Fluent API that describes a nested structure and as a result I would like to use generics to type the resulting object. I would like to do something like:
var test = new Query<Entity>().Select(x => x.UniqueValue<string>())
                              .Select(x => x.UniqueValue<DateTime>())
                              .Select(x => x.UniqueValue<decimal>());

Where test would be of type:
Result<Entity, string, Result<Entity, DateTime, Result<Entity, decimal>>>

So far I have code like:
   class Program
{
    static void Main(string[] args)
    {
        // test : ResultWithResult<Entity,string, Result<Entity, DateTime, ChildLessResult<Entity, decimal>>>
        var test = new Query<Entity>().Select(x => x.UniqueValue<string>())
                                      .Select(x => x.UniqueValue<DateTime>())
                                      .Select(x => x.UniqueValue<decimal>());
    }
}

public class Entity
{
    public string Item1 { get; set; }
}

public class Aggregate<TEntity>
{
    public ChildLessResult<TEntity, TReturnValue> UniqueValue<TReturnValue>()
    {
        return new ChildLessResult<TEntity, TReturnValue>();
    }
}

public class Query<TEntity>
{
    public ChildLessResult<TEntity, TReturnValue> Select<TReturnValue>(Func<Aggregate<TEntity>, ChildLessResult<TEntity, TReturnValue>> predicate)
    {
        var aggregator = new Aggregate<TEntity>();
        return predicate(aggregator);
    }
}

public class ChildLessResult<TEntity, TReturnValue>
{
    public Result<TEntity, TReturnValue, TChild> Select<TChild>(Func<Aggregate<TEntity>, ChildLessResult<TEntity, TChild>> predicate)
    {
        return new Result<TEntity, TReturnValue, TChild>();
    }
}

public class Result<TEntity, TReturnValue, TChild>
{
    private ChildLessResult<TEntity, TChild> _child = new ChildLessResult<TEntity, TChild>();

    public ResultWithResult<TEntity, TReturnValue, Result<TEntity, TChild, ChildLessResult<TEntity, TNewChild>>> Select<TNewChild>(Func<Aggregate<TEntity>, ChildLessResult<TEntity, TNewChild>> predicate)
    {
        return new ResultWithResult<TEntity, TReturnValue,
            Result<TEntity, TChild, ChildLessResult<TEntity, TNewChild>>>();
    }
}

public class ResultWithResult<TEntity, TReturnValue, TChild>
{
}

As you can see this is pretty limited since it only allows you to go as deep as the structures you have defined and you would need a new structure for each level deeper. Is it possible to create types that would allow an unlimited number of levels (i.e. as many Selects as you would ever want without the same corresponding number of Types).

A: Yes, sort of.... it is possible to create some very long and deep nested types, more or less automatically. The trick is you need to use generic type inference, and since constructors don't do inference, you have to use a factory method. For example:
public class MyType<TData,TChild>
{
    public MyType(TData data, TChild child)
    {
    }
}

public class MyTypeFactory
{
   public static MyType<TData,TChild> Create<TData,TChild>(TData data, TChild child)
   {
      return new MyType<TData,TChild>(data, child);
   }

   public static MyType<TData,object> Create<TData>(TData data)
   {
      return new MyType<TData,object>(data, null);
   }
}

public static class Program
{
    static public void Main()
    {
        var grandchild  = MyTypeFactory.Create( 12 );
        var child       = MyTypeFactory.Create( 13D, grandchild );
        var parent      = MyTypeFactory.Create( 14M, child) ;
        var grandparent = MyTypeFactory.Create( 15F, parent );

        Console.WriteLine(  grandchild.GetType().FullName );
        Console.WriteLine(       child.GetType().FullName );
        Console.WriteLine(      parent.GetType().FullName );
        Console.WriteLine( grandparent.GetType().FullName );
    }
}

The output:

MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
MyType'2[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]
MyType'2[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]
MyType'2[[System.Single, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]

It's even type-safe, amazingly enough. If you add the necessary properties...
public class MyType<TData,TChild>
{
    protected readonly TChild _child;
    protected readonly TData _data;

    public MyType(TData data, TChild child)
    {
        _data = data;
        _child = child;
    }

    public TChild Child
    {
        get
        {
            return _child;
        }
    }

    public TData Data
    {
        get
        {
            return _data;
        }
    }
}

...this will work:
var grandchildValue = grandparent.Child.Child.Child.Data;
Console.WriteLine(grandchildValue); //12
Console.WriteLine(grandchildValue.GetType().Name); //int32

And of course you can use the builder pattern:
public static class ExtensionMethods
{
    static public MyType<TDataAdd,MyType<TDataIn,TResultIn>> AddColumn<TDataIn,TResultIn,TDataAdd>(this MyType<TDataIn,TResultIn> This, TDataAdd columnValue)
    {
        return MyTypeFactory.Create(columnValue, This);
    }
}

var grandparent = MyTypeFactory.Create( 12 )
    .AddColumn( 13D )
    .AddColumn( 14M )
    .AddColumn( 15F );

var grandchildValue = grandparent.Child.Child.Child.Data;
Console.WriteLine(grandchildValue);                       //12
Console.WriteLine(grandchildValue.GetType().FullName);    //System.Int32

See my code on DotNetFiddle
P.S. This is a great example of why we needed the var keyword! Otherwise you'd be typing forever.


Q: Can declaring POD types throw an exception? When I declare a condition_variable, it may throw std::system_error.
But how about when I declare a POD type (e.g. int, double or float)?
Like the code below:
int main()
{
    //do something
    int i;    //will here throw exception?
}

If declaring a POD type may throw exception, how do I guarantee
void test() noexcept
{
    //do something
    int i;
}

is noexcept?

A:
But how about declare a fundamental type (e.g., int, double or float)?

Declaring POD type objects won't cause an exception to be thrown.
Constructors of non-POD types can throw exceptions. Only the documents/source code of those types can help you figure out whether that will happen for a particular type.

A: It is the constructor of std::condition_variable that can throw an exception. Primitive types like int and double do not have any constructors. They simply have some stack space allocated for them and that's it, plus a value being written if you initialize the variable. The only way this could cause an exception is if you overflow the stack and the ensuing undefined behaviour happens to throw one.

A: POD types typically are initialized with initializer expressions instead of constructors. Like constructors, initializers can throw exceptions. But if you have neither a constructor nor an initializer, there's no code associated with the definition and therefore also no possibility for that code to throw.


Q: Circles partitioning the plane What is the equation for the  maximum number of regions into which N circles can partition a plane? Is there a name for this equation?
A single circle partitions the plane into two regions, inside and out.
First few outputs:

*

*1 circle  2 regions

*2 circles 4 regions

*3 circles 8 regions

*4 circles 14 regions

A: The equation is $C_{n} = n^2 - n + 2$.  See here: http://mathworld.wolfram.com/PlaneDivisionbyCircles.html.
I don't know a specific name for this, but I assume "Plane Division by Circles Equation" might work.
If you want me to prove why this equation is correct, let me know.


Q: Minkowski inequality for distances of random variables I do not understand why Minkowski's inequality guarantee the triangle inequality for the next metric in a random variable set, with second moment finite:
$d(X,Y)= \left \| X-Y \right \|_p$,
where:
$\left \| X \right \|_p = (E\left | X \right |^p)^\frac{1}{p}$
Minkowski's inequality is:
$\left \| X+Y \right \|_p$ $\leq$ $\left \| X \right \|_p$ + $\left \| Y \right \|_p$

A: $$d(X,Z)=||X-Z||_p=||(X-Y)+(Y-Z)||_p \leq ||X-Y||_p+||Y-Z||_p=d(X,Y)+d(Y,Z).$$
Thus, you get the triangle inequality: $d(X,Z)\leq d(X,Y)+d(Y,Z).$


Q: SQL query to replace multiple occurrences with the most frequent ones I have a products table, which has the product description in two languages, one in English and one in an alternate language.
Let's say:

Product_Desc
Product_Desc_Alt

A
A1

A
A2

A
A1

A
A3

B
B1

B
B2

B
B2

C
C1

If I do a GROUP BY statement, there are multiple alternate language occurrences for the same product. So, let's say:
SELECT Product_Desc, COUNT(DISTINCT Product_Desc_Alt) AS CNT
FROM products
GROUP BY Product_Desc
ORDER BY CNT DESC

Product_Desc
CNT

A
3

B
2

C
1

I would like to replace the Product_Desc_Alt occurrences with the most frequent ones,
so for example I would like the output to be:

Product_Desc
Product_Desc_Alt

A
A1

A
A1

A
A1

A
A1

B
B2

B
B2

B
B2

C
C1

Obviously, if a product has only one alter lang description, just keep that one.
There may be lots of ways to do that, but I can't think of one.
I am using Azure Databricks so this could also happen with PySpark, but I am interested in doing this the SQL way.
Thanks a lot!

A: Is this what you mean?
UPDATE products
SET Product_Desc_Alt = (
  SELECT TOP 1 Product_Desc_Alt
  FROM   products P2
  WHERE  P2.Product_Desc = products.Product_Desc
  GROUP BY Product_Desc_Alt
  ORDER BY COUNT(*) DESC
)


Q: How to get text wrapped with  I wanted to get the text inside break html but this it's not wrap with paragraph just a text inside break. Division is my only identifier for this which is "Msg". How can I get one of each element?

       HI!

         2017-11-30-15.28.09.133

         123

         abc

       Your number is 5.

Draft:
HtmlElement msg = (HtmlElement) page.getFirstByXPath("//div[@name='Msg']/text()");
System.err.println(msg.getTextContent());

A: Understood correctly you might want the code output as

Your number is 5.

  123

  123

  HI!2017-11-30-15.28.09.133

Maybe you might want to try with StringTokenizer (the codes below will hit java.util.NoSuchElementException as the nextToken() call is forced, but hopefully it will become a general idea)
import java.util.StringTokenizer;
..
String sampleStr= "Hello
 there
";
StringTokenizer token = new StringTokenizer(sampleStr);
System.out.println(token.nextToken());//You can use .trim()
System.out.println(token.nextToken());

Would this help?


Q: How to save media file in app specific folder using Media Store API - Scoped Storage Android I am trying to use scoped storage for Android 10 and above to save images taken from the camera in the app specific folder.
I know how to do it using File API but I am looking for to do it with Media store API.
Here is the issue, using the below code it saves images in Internal storage > Pictures, but doesn't save it in app specific folder. Hence if I uninstall the app, the images saved by the app still remains in the memory. I want them to get deleted automatically if user removes the app from his phone.
Let me know if I am doing it wrong or missing something.
    private void dispatchTakePictureIntent() throws IOException {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            if (!checkIfVersionCodeQAndAbove()) {
                try {
                    photoFile = createImageFile();
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    return;
                }
                // Continue only if the File was successfully created
                if (photoFile != null) {
                    Uri photoURI = FileProvider.getUriForFile(getActivity().getApplicationContext(), getActivity().getPackageName() + ".provider", createImageFile());
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                }
            }
            if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                startActivityForResult(takePictureIntent, TAKE_PICTURE);
            }
        }
    }

private void storeImageUsingMediaApi(Intent data) {
        if (getActivity()!=null) {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            String imageFileName = "JPEG_" + timeStamp + "_";

            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Images.Media.TITLE, imageFileName + ".jpg");
            contentValues.put(MediaStore.Images.Media.DESCRIPTION, "profile_image");
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES  + File.separator + "MyApp");

            ContentResolver resolver = getActivity().getContentResolver();

            OutputStream stream = null;
            Uri uri = null;
            try {
                Bundle extras = data.getExtras();
                Bitmap bitmap = null;
                if (extras != null) {
                    bitmap = (Bitmap) extras.get("data");
                }

                final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                uri = resolver.insert(contentUri, contentValues);

                if (uri == null) {
                    throw new IOException("Failed to create new MediaStore record.");
                }

                stream = resolver.openOutputStream(uri);

                if (stream == null) {
                    throw new IOException("Failed to get output stream.");
                }

                if (bitmap!=null && !bitmap.compress(Bitmap.CompressFormat.JPEG, 95, stream)) {
                    throw new IOException("Failed to save bitmap.");
                }

                stream.close();

                selctedImageUri = String.valueOf(uri);

                Glide.with(getActivity()).load(uri).into(imageProfile);

            } catch (IOException e) {
                if (uri != null) {
                    // Don't leave an orphan entry in the MediaStore
                    resolver.delete(uri, null, null);
                }
                e.printStackTrace();
            }
        }
    }

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        CgUtils.showLog(getTag(), "frag onActivityResult");

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == TAKE_PICTURE) {
                CgUtils.showLog(getTag(), "frag TAKE_PICTURE");

                if (checkIfVersionCodeQAndAbove()) {
                    storeImageUsingMediaApi(data);
                } else {
                    Uri imageUri = Uri.parse(selctedImageUri);
                    if (imageUri.getPath() != null) {
                        File file = new File(imageUri.getPath());
                        try {
                            InputStream ims = new FileInputStream(file);
                            imageProfile.setImageBitmap(BitmapFactory.decodeStream(ims));
                        } catch (FileNotFoundException e) {
                            CgUtils.showLog(TAG, "error " + e.toString());
                        }
                    }
                }
                if (!selctedImageUri.isEmpty()) {
                    if (null != loginResponse)
                        loginResponse.setImageUri(selctedImageUri);
                    new InsertLoginResponse(getActivity(), loginResponse, false).executeOnExecutor(CgUtils.getExecutorType());

                    sharedPreferencesEditor.putString(CgConstants.USER_PROF_PIC, selctedImageUri);
                    sharedPreferencesEditor.commit();
                }
            }
      }
}


Q: Auto dial out issue in asterisk I am applying an auto dial in asterisk using .call file
My a.call
Channel: DAHDI/g0/09*********
MaxRetries: 1
RetryTime: 600
WaitTime: 30
Context: outgoing
Extension: 10
Priority: 1

My problem is that every time above number is called by same number means  even if i change the dialled number(receiver number above) the caller number is same.How can i set the caller number in an outgoing call?
Thanks in advance.

A: You can use
Channel: DAHDI/g0/09*********
MaxRetries: 1
RetryTime: 600
WaitTime: 30
Context: outgoing
Extension: 10
Priority: 1
Callerid: 12345

Note, dahdi g0 have be digital trunk and ALLOW change of callerid.

A: You just add the parameter on your .call file
Callerid: <your_callerid>


Q: Fetching cached image not working I was trying to load and cache images in my app for showing on UITableView.
The original concepts looks like:
if (image in cache){
    show cached image;
}else{
   if (image in file){
     show filed image;
   }else{
      load image from web asynchronously;
      if (finished){
         store in cache;
         store in file;
      }
   }
}

Here's the whole class I created to handle image storage:
ImageStore.h
@interface ImageStore : NSObject

@property (nonatomic, strong) NSCache *imageCache;

+ (ImageStore*)sharedImageStore;
//cache
- (void)writeImage: (UIImage*)image ToCacheForKey: (NSString*)imageURL;
- (UIImage*)readImageFromCacheForKey: (NSString*)imageURL;
- (BOOL)imageCachedForKey: (NSString*)imageURL;
//file
- (BOOL)writeImage: (UIImage*)image ToPlistFileForKey: (NSString*)imageURL;
- (UIImage*)readImageFromPlistFileForKey: (NSString*)imageURL;
- (BOOL)imageFiledInPlistForKey: (NSString*)imageURL;
@end

ImageStore.m
#import "ImageStore.h"

@implementation ImageStore
static ImageStore* sharedImageStore;
NSMutableDictionary* plistDictioary;

+(ImageStore*)sharedImageStore
{
    if (sharedImageStore == nil){
        sharedImageStore= [[self alloc] init];
    }
    return sharedImageStore;

}

+(id)alloc
{
    {
        NSAssert(sharedImageStore == nil, @"second singleton");
        sharedImageStore = [super alloc];

        return sharedImageStore;
    }

    return nil;
}

-(id)init
{
    self = [super init];
    if (self != nil)
    {
        _imageCache = [[NSCache alloc] init];
    }

    return self;
}

#pragma mark - Cache
- (void)writeImage:(UIImage *)image ToCacheForKey:(NSString *)imageURL{

    if(image != nil){
        [_imageCache setObject:image forKey:imageURL];
    }else{
        NSLog(@"NIL image:%@ ",imageURL);
    }
}

- (UIImage *)readImageFromCacheForKey:(NSString *)imageURL{

    return [_imageCache objectForKey:imageURL];
}

- (BOOL)imageCachedForKey:(NSString *)imageURL{

    if ([_imageCache objectForKey:imageURL] == nil)
    {
        return false;
    }

    return true;

}

#pragma mark - File
- (BOOL)writeImage:(UIImage*)image ToPlistFileForKey: (NSString*)imageURL{

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:image];
    if (plistDictioary == nil) {
        plistDictioary = [NSMutableDictionary new];
    }
    [plistDictioary setObject:data forKey:imageURL];

    BOOL didWriteSuccessfull = [plistDictioary writeToFile:[self getPlistFilePath] atomically:YES];
    return didWriteSuccessfull;

}

- (UIImage *)readImageFromPlistFileForKey:(NSString *)imageURL{

    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[self getPlistFilePath]];
    NSData * data = [dict objectForKey:imageURL];
    UIImage * image = [UIImage imageWithData:data];
    return image;

}

- (BOOL)imageFiledInPlistForKey:(NSString *)imageURL{

    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[self getPlistFilePath]];
    if ([dict objectForKey:imageURL] == nil) {

        return NO;
    }else{

        return YES;
    }

}

- (NSString*)getPlistFilePath{

    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];
    NSString * path = [documentsDirectory stringByAppendingPathComponent:@"Images.plist"];
    return path;
}
@end

Implementation in tableView:cellForRowAtIndex:
if ([[ImageStore sharedImageStore]imageCachedForKey:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]]) {
  //cache
  NSLog(@"cached");

  cell.image = [[ImageStore sharedImageStore] readImageFromCacheForKey:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]];

}else{

  NSLog(@"nothing cached");

  if ([[ImageStore sharedImageStore] imageFiledInPlistForKey:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]]) {
     //plist file

     cell.image = [[ImageStore sharedImageStore] readImageFromPlistFileForKey:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]];
  }else{
     //loading with UIImage category async method (see below)

     [UIImage loadFromURL:[NSURL URLWithString:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]] completionBlock:^(BOOL succeeded, UIImage *image) {

            if (succeeded){
                cell.image = image;
            }
        }];
    }
}

EDIT
Downloaded Images stored in the UIImage Category:
+ (void)loadFromURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               if ( !error )
                               {
                                   UIImage *image = [[UIImage alloc] initWithData:data];
                                   [[ImageStore sharedImageStore] writeImage:image ToCacheForKey:[url absoluteString]];//write to NSCache
                                   [[ImageStore sharedImageStore] writeImage:image ToPlistFileForKey:[url absoluteString]];//write to Plist
                                   completionBlock(YES,image);

                               } else{

                                   completionBlock(NO,nil);
                               }
                           }];

}

(Sorry for the long method naming.)
The console returns "nothing cached" for every onscreen cell, and sometimes the scrolling become stutter when checking cache and file.
I've been trying handy caching for a couple of days while there's already a bunch of useful image caching library. It'd be nice to know what am I doing wrong with this! Thanks for any advice.

A: The problem is in the writeImage:ToPlistFileForKey: method. You convert an image to a data as below:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:image];

But convert the data to image like this:
UIImage * image = [UIImage imageWithData:data];

This will always return a nil that because the format of the archived data is NSPropertyListBinaryFormat_v1_0 not PNG(or bitmap format).
Instead of using [NSKeyedArchiver archivedDataWithRootObject:image], you should use UIImagePNGRepresentation(image) as below:
- (BOOL)writeImage:(UIImage*)image ToPlistFileForKey: (NSString*)imageURL {
    archivedDataWithRootObject:image];
    NSData *data = UIImagePNGRepresentation(image);
    if (plistDictioary == nil) {
        plistDictioary = [NSMutableDictionary new];
    }
    [plistDictioary setObject:data forKey:imageURL];

    BOOL didWriteSuccessfull = [plistDictioary writeToFile:[self getPlistFilePath] atomically:YES];
    return didWriteSuccessfull;
}

The UIImagePNGRepresentation function which returns the data for the specified image in PNG format, then you get an image [UIImage imageWithData:data].
Hope this will help you.


Q: PHP stream_context_create with proxy I'm currently developing an web application which uses an XML Interface located on a different server, that I have to access via a proxy.
So I tried to set the proxy in a stream_context_create array, but it doesn't seem to work.
$set = array(
    'http' => array(
        'method' => 'GET',
        'header' => sprintf(
            'Proxy-Authorization: Basic %s',
            base64_encode(Constants::XML_AUTH)
        ),
        'protocol_version' => '1.1',
        'proxy' => '89.122.180.178:46565'
    )
);
$stream = stream_context_create($set);

I'm not quite sure what I'm doing wrong.
If I comment out the proxy key i get a 403 Forbidden Response as it should be.
If I comment in the proxy key I receive a 400 Bad Request Response.
I'm not quite sure what I'm doing wrong. Can you help me out? I never did a communication through a proxy before with PHP.

A: My guess is that the proxy declaration is missing the protocol. An URI has to be specified (according to the doc), that contains the protocol (scheme).
So this could work: 'proxy' => 'tcp://89.122.180.178:46565'. It might be necessary to remove 'protocol_version' since this may not be required for tcp.
Does that work for you? (or have you already solved it? ... ;-)


Q: Want to multiply, not repeat variable I want to input a command-line variable and then multiply it, but when I print the variable it repeats by the number I want to multiply it by.
eg:
#!/usr/bin/env python3
import sys
st_run_time_1 = sys.argv[1]*60

print ("Station 1 : %s" % st_run_time_1)

When I run the script I get the following:
    python3 test.py 2
Station 1 : 222222222222222222222222222222222222222222222222222222222222

A: sys.argv[x] is string. Multiplying string by number casue that string repeated.
>>> '2' * 5         # str * int
'22222'

>>> int('2') * 5    # int * int
10

To get multiplied number, first convert sys.argv[1] to numeric object using int or float, ....
import sys
st_run_time_1 = int(sys.argv[1]) * 60 # <---

print ("Station 1 : %s" % st_run_time_1)

A: You are multiplying a string with an integer, and that always means repetition. Python won't ever auto-coerce a string to an integer, and sys.argv is always a list of strings.
If you wanted integer arithmetic, convert the sys.argv[1] string to an integer first:
st_run_time_1 = int(sys.argv[1]) * 60


Q: NotificationHub Push Notification returns : The Token obtained from the Token Provider is wrong I have Wp8.1 Silverlight app that receives push notification (WNS) from  Mobileservice (the old azure service).
I therefore wanted to update to the new service because of the new features. I have now created/upgraded a new server to use App Service - Mobile App. And tested push notification with the sample app from azure (everything works).
Going back to my app WP8.1 -> Adding the new package Microsoft.Azure.Mobile.Client through NuGet (2.0.1), there is the issue that the Microsoft.WindowsAzure.Mobile.Ext does not contain the 'GetPush' extension. It seems like it is missing it? looking to the WP8 version, it only registers to MPNS, and I need WNS. So I do not know if any other assembly could be used.
Can I add another assembly reference?
Update
The following code lets me register the device on the server, and I can see the device register correctly. where the channelUri and the installationInformation are retrieved by the client and send to the server.
Installation ins = new Installation();
ins.Platform = NotificationPlatform.Wns;
ins.PushChannel = uTagAndChan.ChannelUri;
ins.Tags = uTagAndChan.Tags;
ins.InstallationId = uTagAndChan.installationInformation;
await hubClient.CreateOrUpdateInstallationAsync(ins);

Sending a test toast-notification to the registered tags, results in the following error :

The Token obtained from the Token Provider is wrong

Searching on this issue I found Windows Store App Push Notifications via Azure Service Bus. Which the proposed solution says to register to the notification hub directly from the app, I would rather not have the app to have directly access to the hub. But is this the only way? (mind you the answer was not accepted, but I will try it all though it is not a desired solution)
Update
Registering  for notifications via client (WP8.1 Silverligt), makes a registration to MPNS, which I do not want.
The snippet on the server registers a WNS, the two registrations can be seen here:

The URI retrieval is done using
var channel = await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();

which in the description states it returns a WNS. This seems to infer that the registration I am doing on the server (code snippet in the top) is correct and the registration on the client is faulty.
But the registration on the image seems wrong. Shouldn't the PNS Identifier be different for the two registrations? also expiration date seems wrong ?
How to mend this since the GetPush() (which was available in the sample registered the client correctly for notifications) does not exist in the NuGet package?
Update
I read one place that deleting and recreating the NotificationHub could help. I will try this today. Even IF it works, it would be more desirable to have the solution, and to know if the registrations are done correctly?
Temporary solution:
Deltede, recreated, inserted Package SID and Secret. And it works again (strange)!
Still interested in the underlying issue!

A: Deleted and recreated the service, setting all the same settings made it work again.

A: I had same issue with my UWP. But in my case I had issue with self signed certificate.
When I set the AppxPackageSigningEnabled property to True (in .csproj) then notifications stopped working and I got "The token obtained from the Token Provider is wrong" (Test send from Azure Portal).
The certificate must have same issuer as Publisher in Identity element in .appxmanifest file.


Q: Is it appropriate to return derived/aggregated representations of resources, via content negotiation, in a REST API? I refer to this fantastic answer to an earlier question I had.
My question is, say you have an endpoint GET /tasks and that endpoint accepts query params to get certain groupings of data like:

*

*GET /tasks?createdDate=01-01-2022&completedDate=30-01-2022

*GET /tasks?isOpen=true&priority=high
etc.
As a consumer of this API I can use these query params to then derive statistics like:

*

*How many high priority tasks are currently open?

*For the month of January, what was the mean time to complete a task?

etc.
Now the problem is, if I want derive statistics like 'mean time to complete a task, across all time' I'm going to need to pull in every single item just to make that calculation.
I figure that instead the backend could be calculating and storing these statistics on a separate table, and it can update that table as resources change, or cache queries as they occur.
The question is - is it appropriate to use the same endpoint and the Accept header to request these statistical representations?
eg:
GET /tasks?createdDate=01-01-2022&completedDate=30-01-2022
Accept: application/vnd.metric+meanTimeToCompleteTask+json

GET /tasks?isOpen=true&priority=high`
Accept: application/vnd.metric+count+json

Or should a separate endpoint be used?
eg:
GET /metrics?resourceType=task&metricRequired=count&isOpen=true&priority=high

Note: for these metric representations PUT/POST/PATCH/DELETE would not be allowed, they're a GET only operation.
What I like about the the content negotiation approach is that as a consumer of the API, you don't need to familiarise yourself with another API endpoint - your queries are going to match the query you would make if were calculating the values yourself.
Bounty Edit: I want to make it clear why I think using an Accept header against the same endpoint would be a good idea:

*

*Necessarily, the same set of query parameters can be used to define the list of data that determines the metric, as is used to fetch said of data itself.

*If you were to use two separate endpoints, they might well happen to have the same set of query parameters, but that is not a necessary
coincidence. It's conceivable that they would fall out of sync.

A: Groundwork first: REST doesn't have "endpoints" (see Fielding, 2018), it has resources.  The current HTTP standard offers this definition:

The target of an HTTP request is called a resource.  HTTP does not
limit the nature of a resource; it merely defines an interface that
might be used to interact with resources.

The resource targeted by the request is that resource identified by the entire target URI -- general purpose components do not distinguish between path segments and the query part.
/foo?a
/foo?b

These are two different resource identifiers, and therefore general purpose clients must assume they are two different resources.  (The fact that your server happens to route both of those target URI to the same request handler(s) is an implementation detail).
Therefore, when you talk about:
GET /tasks?createdDate=01-01-2022&completedDate=30-01-2022
GET /tasks?isOpen=true&priority=high

These are already two different resources (as far as the outside world can tell), so you don't need content negotiation to support the different representations, any more than you need to negotiate content when you are talking about /home.html and /home.jpeg

GET /tasks?isOpen=true&priority=high
GET /metrics?resourceType=task&metricRequired=count&isOpen=true&priority=high

Both of these spellings are fine; you could choose either, both, or something else entirely.  The machines don't care, so you can follow local spelling conventions, your own tastes, or choose spellings that best support the needs of the human beings you care about.  It's all good.

Now, there are cases where it makes sense for a single resource (our generalized abstraction for named information) might have multiple current representations.  We might want /test/123 to have a text/plain representation available for clients that won't understand the primary text/html representation.  Or perhaps /patch/123 has both application/json-patch+json and application/merge-patch+json.
Note the distinction: we're not using the Accept header to identify the resource we want (that's done by the target URI).  Instead, we're trying to identify the representation of that resource which best matches the client's capabilities.
Even when that makes sense, we might still prefer designs where those distinct representations are also available via more specific identifiers (think /home, /home.html, and /home.txt), and requests to the negotiated resource either redirect to the specialized resources or directly embed their representations.
Lots of possible trade offs.
It may be interesting to review Fielding 2006, a discussion of the concerns of language negotiation on the web, and the resource designs in place at his companies.

A: A list of tasks and a metric calculated over that list are two different resources and that is a very strong indication that they should be served from different URIs/paths.
I would even go a step further and argue that "number of tasks matching criterion" and "mean time to complete" are different resources and should have different URIs/paths.
That would lead to requests like
GET /metrics/tasks/counte?isOpen=true&priority=high
or
GET /metrics/tasks/mttr?createdDate=01-01-2022&completedDate=30-01-2022
(mttr = mean time to resolve)
This allows the backend to have different strategies for calculating and/or caching the various metrics and doesn't constrain you to put all metrics in the same reply format.
The fact that everything under /metrics is a read-only resource is not an issue at all. It is even easier to understand than that for /tasks some media formats are read/write and some are read-only.

A: TL/DR - Probably not. Recommend the following (or something like it) as a starting point:
GET /task-metrics

In my experience great APIs do two things:

*

*Follow expected conventions for efficient learning, reasoning, and use

*Offer a conceptual/logical model that makes sense to consumers
If task metrics is "a thing" for consumers then it makes sense to represent them as first class citizens in your API. Often, different audiences see things differently. For task metrics it may be that "doers" view these as purely derived/secondary whereas "managers" view these as first class elements.
If your API is to serve both audiences then it should make sense to both. It's usually better to increase the number of first class objects in your API than to require one or more audiences to adjust their world view. This allows people to pay attention to the parts they care about and (more likely) be able to ignore the parts they don't.
One might argue this is an API-centric application of the Single Responsibility Principle (SRP).
Regardless of what you decide, good luck!


Q: How to turn users input into a list in Python? Here is my code so far.
def pfunc():
    portList = []
    user_choice_port = userPort.get()
    portList.append(user_choice_port)

the userPort is basically a text variable for what the user will enter into an entry box (which will be ports). The user will enter the port numbers like this:
23, 80, 44, etc.

How do I take those numbers and put them into a list. Cause whenever I do it puts them in as a string that looks like this:
['23, 80, 44']

When I want it to look like this:
[23,80,44]

I cannot figure this out so any help would be appreciated

A: This should help.
user_choice_port = "23, 80, 44"
print map(int, user_choice_port.split(","))
print [int(n) for n in user_choice_port.split(",")]


Q: Leads to implement cart in shopping cart using Spring
I have implemented shopping cart up to product. But have no idea on how to implement separate cart for each user.
Please share your ideas

A: Please share your effort / code along with your question always.
According to me this can go with many scenarios
One of the scenarios would be like,
User have One Cart, Cart will have many products and many Products belongs to many carts
Code goes as below, You can go ahead and add required parameters to the entity.
User Entity
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "USERS")
public class User {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "USER_NAME")
    private String userName;

    @OneToOne(mappedBy = "user", fetch = FetchType.LAZY)
    private Cart cart;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Cart getCart() {
        return cart;
    }

    public void setCart(Cart cart) {
        this.cart = cart;
    }

}

Cart Entity
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "CART")
public class Cart {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "USER_ID")
    private User user;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinTable(name = "CART_PRODUCT", joinColumns = @JoinColumn(name = "CART_ID") , inverseJoinColumns = @JoinColumn(name = "PRODUCT_ID") )
    private Set<Product> products;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Set<Product> getProducts() {
        return products;
    }

    public void setProducts(Set<Product> products) {
        this.products = products;
    }

}

Product Entity
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name = "PRODUCT")
public class Product {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "name")
    private String productName;

    @ManyToMany(cascade = CascadeType.ALL, mappedBy = "products")
    private Set<Cart> carts;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public Set<Cart> getCarts() {
        return carts;
    }

    public void setCarts(Set<Cart> carts) {
        this.carts = carts;
    }

}


Q: Point wise convergence of $\sigma_n(f)$ Let $f$ be in $L^1[-\pi,\pi]$. Does $F_n*f$ converge  to $f$ almost every where?
Note.  $F_n$ is the Fejer kernel i.e, $F_n(t)=\sum_{-n}^n(1-\frac{|k|}{n+1})e^{ikt}$.

A: Yes, if $f\in L^1$ then $F_N*f\to  f$ almost everywhere.
Katznelson refers to Zygmund for most of this. Sketch/outline:
In addition to being what K calls a summability kernel, $F_N$ is  even when regarded as a function on $(-\pi,\pi)$, and $F_N\ge0$ is decreasing on $(0,\pi)$. Hence

Suppose $f\in L^1(\Bbb T)$. Then $F_n*f(t)\to f(t)$ for every $t$ such  that $f(t)=\lim_{h\to0}\frac1{2h}\int_{-h}^h f(t+s)\,ds$ (and hence almost everywhere, by the Lebesgue differentiation theorem).

Explanation: The conditions  on  $F_N$ mentioned above show that $F_N:(-\pi,\pi)\to(0,\infty)$ is a weighted average of the functions $\frac1h\chi_{(-h,h)}$.
Or, for an actual proof: We need only show that $\int fF_N\to f(0)$ if $\frac1{2h}\int_{-h}^hf\to f(0)$. Wlog $f$ is even. So $\frac1h\int_0^hf\to f(0)$. Define $$g(h)=\int_0^h f,$$so $g$ is absolutely continuous with $g'=f$ almost everywhere. Integration by parts shows that$$\int_0^\pi F_Nf=F_N(\pi)g(\pi)-\int_0^\pi g(t)F_N'(t)\,dt=o(1)-\int_0^\pi\frac 1tg(t)tF_n'(t)\,dt.$$The hypothesis implies that $\lim_{t\to0}\frac1tg(t)=f(0)$, so  $\frac1tg(t)$ is (or rather can be defined  at the origin so as to be) continuous on $[0,\pi)$. And you can verify that $-tF_N'(t)$ (for $t\in(-\pi,\pi)$) is a summability kernel in Katznelson's sense, so the integral above tends to $f(0)$.
(Yes, it's a summability kernel. It's clear that $-tF_n'(t)\ge0$ on $(-\pi. pi)$, and $$-\int_{-\pi}^\pi tF_N'(t)=-2\pi F_N(\pi)+\int_{-\pi}^\pi F_N=o(1)+2\pi.)$$

A: https://en.m.wikipedia.org/wiki/Carleson%27s_theorem
It is true in $L^p $ for $p>1$ but not in $L^1$.
EDIT: This is about Dirichlet kernel, not Féjer. Sorry about that mistake, I read too fast the author's question.

A: The Fejer Kernels form an approximation to the identity:
\begin{align}
\int_0^1 F_N(x)dx = 1~~ \forall N \\
\sup_N \int_0^1 |F_N(x)| dx < \infty \\
\text{for all}~ $\delta>0$ ~ \int_{|x|>\delta} |F_N(x)|dx \rightarrow 0~\text{as}~
N\rightarrow 0 \\ \end{align}
Additionally, in Muscalu/Schlag's Classical and Multilinear analysis I, it is a result (proposition 1.5) that $|| F_N * f -f ||_p \rightarrow 0$ for $1 \leq p <\infty$ if $f\in L^p(\mathbb{T})$, so it appears that we have convergence in $L^1$ norm on $L^1$ for periodic functions, and if you do some more work then you can show that $F_N *f \rightarrow f$ pointwise a.e. (i.e., show that $F_N$ is radially bounded or similar).


Q: Format to Currency using DisplayFor Html Helper I have page that will show some currency data.
I want to format the data with currency format but only using Display Template.
I have the following code:
 @foreach (var item in Model.Data)
{

    @Html.DisplayFor(modelItem => item.Name)
    @Html.DisplayFor(modelItem => item.Amount1)
    @Html.DisplayFor(modelItem => item.LName)
    @Html.DisplayFor(modelItem => item.Amount2)
    @Html.DisplayFor(modelItem => item.Amount3)

}

I have created a DisplayTemplate String.cshtml, since my datatype is string:
@model string

@{
    IFormatProvider formatProvider = new System.Globalization.CultureInfo("en-US");
    @Model.ToString("C",formatProvider)
}

But when I run it, I'm getting the error:

No overload for method 'ToString' takes 2 arguments

How can I display positive amount as $1000.00 and negative amount as ($1000.00) either using DisplayTemplate or string.Format("{0:C}")

A: The problem you're having is because you're trying to convert a string to a currency.  From MSDN:

The Currency ("C") Format Specifier
The "C" (or currency) format specifier converts a number to a string that represents a currency amount.

The .ToString(string format, IFormatProvider formatProvider) overload you're trying to use only exists for numeric types, which is why it's not compiling.
As an example to demonstrate this:
public class TestModel
{
    public decimal Amount { get; set; }
    public string StringAmount { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var model = new TestModel
        {
            Amount = 1.99M,
            StringAmount = "1.99"
        };

        IFormatProvider formatProvider = new CultureInfo("en-US");

        // Prints $1.99
        Console.WriteLine(model.Amount.ToString("C", formatProvider));

        // Prints 1.99
        Console.WriteLine(string.Format(formatProvider, "{0:C}", model.StringAmount));
    }
}

So you have a couple of choices:

*

*Convert your data to a numeric type in the template, and then format it.

*Store your data as a numeric type to begin with.

I believe 2 is the better option, because you're wanting to work with numeric data, so storing it as a string only adds complexity when it comes to calculating and formatting (as you can see here), as you're always going to have to perform conversions first.


Q: What are %O and %S in platex -synctex=1 -halt-on-error -file-line-error %O %S I installed LaTeX with brew:
# macOS MacTex Install
$ brew cask install mactex-no-gui

# Updating the packages
$ sudo tlmgr update --self && sudo tlmgr update --all

$ latex --version
pdfTeX 3.14159265-2.6-1.40.21 (TeX Live 2020)
kpathsea version 6.3.2
...
$ latexmk --version
Latexmk, John Collins, 29 September 2020. Version 4.70b
$ platex --version
e-pTeX 3.14159265-p3.8.3-191112-2.6 (utf8.euc) (TeX Live 2020)
kpathsea version 6.3.2
...

I also had to add PATH to .zshrc.
export PATH="/Library/TeX/texbin/:$PATH"

I have the following in .latexmkrc file for LaTeX. I have no experience with Perl.
...
$latex = 'platex -synctex=1 -halt-on-error -file-line-error %O %S';
$max_repeat = 5;
...

Q1. What is %O %S?
Q2. I change the platex to latex and pdflatex, but both give errors.
platex is for Japanese language.
How can I change platex using latex or pdflatex?
# not working
$pdflatex = 'pdflatex -synctex=1 -halt-on-error -file-line-error %O %S';

And log output:

LaTeX2e <2020-10-01> L3 programming layer <2020-10-05> xparse
<2020-03-03>
(/usr/local/texlive/2020/texmf-dist/tex/platex/jsclasses/jsarticle.cls
/usr/local/texlive/2020/texmf-dist/tex/platex/jsclasses/jsarticle.cls:14:
LaTeX Error: This file needs format pLaTeX2e' but this is LaTeX2e'. ...

Why is it using platex? I never set it up using platex.
Q3. How to change the preferences in mactex no gui?


Q: Spring's CachingConnectionFactory. Why do we need to close sessions although they are to be cached? I am trying to get my head around the Spring CachingConnectionFactory.
ActiveMQ documentation recommends when using JmsTemplate that a Spring CachingConnectionFactory or an ActiveMQ PooledConnectionFactory is used as the connection factory implementation.
I understand this because using the normal ConnectionFactory a connection is created, a session started, and both are closed for EVERY call of the jmsTemplate.send() which is very wasteful.
So I am trying to implement a custom JmsTemplate bean with a CachingConnectionFactory for use where I may have many requests that are A) Persisted to DB B) Enqueued JMS.
@Configuration
public class JMSConfig {

    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;

    @Bean
    @Qualifier("jmsTemplateCached")
    public JmsTemplate jmsTemplateCachingConnectionFactory() {
        cachingConnectionFactory.setSessionCacheSize(10);

        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setDeliveryMode(DeliveryMode.PERSISTENT);
        jmsTemplate.setSessionAcknowledgeMode(JmsProperties.AcknowledgeMode.CLIENT.getMode());
        jmsTemplate.setSessionTransacted(true);
        jmsTemplate.setDeliveryPersistent(true);
        jmsTemplate.setConnectionFactory(cachingConnectionFactory);
        return jmsTemplate;
    }
}

My first question regards the Spring Docs For CachngConnecionFactory which say:

SingleConnectionFactory subclass that adds Session caching as well MessageProducer caching. This ConnectionFactory also switches the "reconnectOnException" property to "true" by default, allowing for automatic recovery of the underlying Connection.
By default, only one single Session will be cached, with further requested Sessions being created and disposed on demand. Consider raising the "sessionCacheSize" value in case of a high-concurrency environment.

But then in bold:

NOTE: This ConnectionFactory requires explicit closing of all Sessions obtained from its shared Connection. This is the usual recommendation for native JMS access code anyway. However, with this ConnectionFactory, its use is mandatory in order to actually allow for Session reuse.

Does this mean I only need to close sessions if I create a connection "manually" via the template or my CachingConnectionFactory bean? In other words like:
    Connection connection = jmsTemplateCached.getConnectionFactory().createConnection();

    Session sess = connection.createSession(true, JmsProperties.AcknowledgeMode.CLIENT.getMode());

    MessageProducer producer = sess.createProducer(activeMQQueue);

    try {
        producer.send(activeMQQueue, new ActiveMQTextMessage());
        sess.commit();
    } catch (JMSException e) {
        sess.rollback();
    } finally {
        sess.close();
    }

If I use the template like below, should I close or not close the session?
    @Autowired
    public JmsTemplate jmsTemplateCached;

    @Transactional
    public InboundResponse peristAndEnqueueForProcessing(InboundForm  inboundForm) throws IrresolvableException, JsonProcessingException, JMSException {

    //Removed for clarity, an entity has been persisted and is then to be enqueued via JMS.

        log.debug("Queue For Processing : {}", persistedRequest);

        String serialisedMessage = objectMapper.writeValueAsString(persistedRequest);
        ActiveMQTextMessage activeMQTextMessage = new ActiveMQTextMessage();
        activeMQTextMessage.setText(serialisedMessage);

        //Will throw JMS Exception on failure
        Session sessionUsed = jmsTemplateCached.execute((session, messageProducer) -> {
            messageProducer.send(activeMQQueue, activeMQTextMessage);
            session.commit();
            return session;
        });

        return response;
    }

Secondly, if the above jmsTemplate.execute() throws an exception, what happens to the session? Will it rollback after x time?

A: The JmsTemplate reliably closes its resources after each operation (returning the session to the cache), including execute().
That comment is related to user code using sessions directly; the close operation is intercepted and used to return the session to the cache, instead of actually closing it. You MUST call close, otherwise the session will be orphaned.
Yes, the transaction will roll back (immediately) if its sessionTransacted is true.
You should NOT call commit - the template will do that when execute exits normally (if it is sessionTransacted).


Q: ASP.NET MVC With MEF integration I am following the same approach used in this link in my ASP.NET MVC 2 project and it is working fine.
All my pages are partial views (ascx). So I have created a class library in my solution as a plugin the same way done in the link sample and put a new partial view and a controller that is called from the host application using MEF the same way also and it worked fine.
The difference in my plugin project is that I created a new folder to put my models in.
This code below represent the partial view showing as a plugin view in my host application through MEF successfully
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

Hello I am a Plugin Partial View

But since I have added a model in my application models folder, I need to bind it to the partial view the same way done in my host ASP.NET MVC 2 host project.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Plugin.Models.ViewModel>" %>

Hello I am a Plugin Partial View

Once adding the ViewModel to the partial view an error shows in firebug and my view is not loading anymore. The error in http response showing in firebug looks as follows:
<!DOCTYPE html>

<title>Parser Error</title>
<meta name="viewport" content="width=device-width" />

Server Error in '/' Application.

 Parser Error

         Description: An error occurred during the parsing of a resource required to service this request.   Please review the following specific parse error details and modify your source file appropriately.

         Parser Error Message: Could not load type 'System.Web.Mvc.ViewUserControl<Plugin.Models.ViewModel>'.

        Source Error:

Line 11: --%>
Line 12:
Line 13: <%@ Control Language="C#"     Inherits="System.Web.Mvc.ViewUserControl<Plugin.Models.ViewModel>" %>
Line 14:
Line 15:

         Source File:  /Modules/Message/Views/Message/PartialView.ascx    Line:  13

        Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18010

I have also copied the web.config file and added the model namespace as following:
<system.web>
  <pages>
    <namespaces>
      <add namespace='Plugin.Models.ViewModel' />
    </namespaces>
  </pages>
</system.web>

But this is not working either.

A: See Tom Clarkson answer on
Views in separate assemblies in ASP.NET MVC


Q: datetime field won't update in MySQL Database Hi I am having an issue with updating a users last login time in my database, if I set it to update a different column it works perfectly, but it just does not work when i try to update the specific column "lastlogin".
My code:
    @mysql_query("UPDATE my_users SET lastlogin=NOW() WHERE id=".$_SESSION["id"]);

My DB column:

column name: lastlogin

type: datetime

Null: No

Default: 0000-00-00 00:00:00

Anything wrong with the way the column is setup in the DB? Like I mentioned above if I was to tell it to put NOW() in another column it works fine.

A: Solved. There was another similar statement further down which was over riding this one! How stupid of me but easy to miss!

A: use mysql_error to try and find what is wrong, then post that into here so we can help if you need it. (Would comment but to low rep)

A: From my experience in the past, mysql_query() doesn't necessarily substitute variables before executing sql. Try writing in this format. Also use mysql_error to check if there are any issues with your code execution:
$sql = "UPDATE my_users SET lastlogin=NOW() WHERE id=".$_SESSION["id"];
mysql_query($sql) or die(mysql_error());

If there is no error, then there are few possibilities as to why the laslogin entry is not happening:

*

*$_SESSION["id"] does not hold any value and no value is being passed to mysql.

*There is no id matching with $_SESSION["id"].

To debug:

*

*Also try updating some other columns.

*You might also want to check if you are using correct extensions like PDO..

Also found that, earlier version of mysql doesn't support updating datetime column with now(). In that case try resetting column type to TIMESTAMP. Refer this for details: https://bugs.mysql.com/bug.php?id=27645


Q: How can I model association between two polymorphic classes without using an enumeration I am using an enum to label two different classes of products - a SensorDevice and a [data]CaptureDevice.
They are intended to be used physically plugged to one another, but not every sensor model can be used by each receiver model, so I created an Enum for the different platforms, so the GUI would only display the compatible accessories for a given device:
enum Platform {
    Standard,
    Deluxe,
    Jumbo
}

abstract class CaptureDevice
{
    public Platform platform;

    public bool IsCompatibleWith(SensorDevice sd)
    {
        return sd.Platforms.Contains(this.Platform); // <- this is type-checking!
    }
}

abstract class SensorDevice
{
    public IEnumerable<Platform> Platforms;

    public bool IsCompatibleWith(CaptureDevice cd)
    {
        return this.Platforms.Contains(cd.Platform); // <- this is type-checking!
    }
}

I started to find this quite smelly, since the enum is hard-coded. I am considering to use "Replace Type Code by Polymorphism" refactor, but I am not quite sure how to do it for this situation. Any suggestion?

A: You could do the following to get rid of enum.
Replace enum with a class.
public abstract class Platform {}

Add Device class which answers if it's compatible with a Platform.
public abstract class Device
{
    public abstract bool IsCompatibleWith(Platform platform);
}

Make CaptureDevice a subclass of Device.
public abstract class CaptureDevice : Device
{
    public Platform Platform;

    public override bool IsCompatibleWith(Platform platform)
    {
        // I'm using type comparison for the sake of simplicity,
        // but you can implement different business rules in here.

        return this.Platform.GetType() == platform.GetType();
    }

    public bool IsCompatibleWith(SensorDevice sd)
    {
       // We are compatible if sensor is compatible with my platform.

        return sd.IsCompatibleWith(this.Platform);
    }
}

Make SensorDevice a subclass of Device.
public abstract class SensorDevice : Device
{
    public IEnumerable<Platform> Platforms;

    public override bool IsCompatibleWith(Platform platform)
    {
        // I'm using type comparison again.

        return this.Platforms.Any(p => p.GetType() == platform.GetType());
    }

    public bool IsCompatibleWith(CaptureDevice cd)
    {
        // We are compatible if capture is compatible with one of my platforms.

        return this.Platforms.Any(p => cd.IsCompatibleWith(p));
    }
}

Basically, that's all you need to do. To illustrate how it works, I've added the code below.
// Platforms
public class StandardPlatform : Platform { }
public class DeluxPlatform : Platform { }
public class JumboPlatform : Platform { }

// Capture device(s)
public class CD1 : CaptureDevice
{
    public CD1()
    {
        Platform = new StandardPlatform();
    }
}

// Sensor device(s)
public class SD1 : SensorDevice
{
    public SD1()
    {
        Platforms = new List<Platform>
        {
            new StandardPlatform(),
            new DeluxPlatform()
        };
    }
}

public class SD2 : SensorDevice
{
    public SD2()
    {
        Platforms = new List<Platform> {new JumboPlatform()};
    }
}

// Somewhere in the code...
var cd1 = new CD1();
var sd1 = new SD1();

Console.WriteLine(cd1.IsCompatibleWith(sd1)); // True
Console.WriteLine(sd1.IsCompatibleWith(cd1)); // True

var sd2 = new SD2();
Console.WriteLine(sd2.IsCompatibleWith(cd1)); // False
Console.WriteLine(cd1.IsCompatibleWith(sd2)); // False

A: EDIT: If you want to get rid off the enum, why shouldn't use a config file ?
You configure your platforms like this:
<Platforms>
    <Platform name="Standard">
        <Device>Namespace.of.your.Device.CaptureDevice</Device>
        <Device>Namespace.of.another.Device.AnotherDevice</Device>
    </Platform>
    <Platform name="Deluxe">
        <Device>Namespace.of.your.Device.CaptureDevice</Device>
    </Platform>
</Platforms>

Other syntax:
<Platforms>
    <Platform>
        <Name>Standard</Name>
        <Devices>
            <Device>Namespace.of.your.Device.CaptureDevice</Device>
            <Device>Namespace.of.another.Device.AnotherDevice</Device>
        <Devices>
    </Platform>
</Platforms>

Then, you have the same base structure, you could do something like this:
abstract class ADevice<T> where T : ADevice<T>
{
    public ADevice<T>(T device , string filename)
    {
        // Parsing of the file
        // Plus, setting the Platforms Property
    }

    // Or (but you should keep the first constructor to see the filename dependency)
    public ADevice<T>(T device)
    {
        // Parsing of the file
    }

    public IEnumerable<Platform> Platforms { get; private set; }

    public bool IsCompatibleWith(T device)
    {
        return this.Platforms.Contains(device.Platform); // <- this is type-checking!
    }
}

Then:
abstract class CaptureDevice : ADevice<CaptureDevice>
{
    public CaptureDevice(CaptureDevice device, string filename)
        : base(device, filename)
    {
    }

    // Or (But still same comment)
    public CaptureDevice(CaptureDevice device)
        : base(device, defaultFilename)
    {
    }
}

Same for SensorDevice
And instead of the Enum, you can create a simple class for the moment as:
public class Platform
{
    public Platform(string name)
    {
        Name = name;
    }

    public string Name { get; }
}


Q: List.Remove(T item) removing item from original List I have the following code
foreach (var d in dots)
{
    var _tempPointList = new List<Point>();
    _tempPointList = _pointList;

    foreach (var point in _tempPointList)
    {
        if (d >= point.X && d <= point.Y)
        {
            _tempPointList.Remove(point);
        }
    }
}

so when the integer d is between X and Y of the point type, it will be removed from the temporary list because the next d doesn't have to check the same _tempPointList element. But when the code reaches _tempPointList.Remove(point); the point element is getting removed from the _tempPointList and _pointList which I felt strange. Why is it removing from the main list as well?

A: Because you are working on the same list. You are assigning effectively the same instance to _tempPointList in this line (and removing the reference to your original _tempPointList which you created in the line above.):
_tempPointList = _pointList;

I'd suggest you instantiate your copy list by directly copying the list with this call:
var _tempPointList = new List<Point>(_pointList); //creates a shallow copy

I see yet another problem: you are removing elements from a list while you are iterating over it. Don't you get an System.InvalidOperationException when continuing to iterate?
I'd solve this by iterating over the original list and remove from the copy list like this:
foreach (var d in dots)
{
    var _tempPointList = new List<Point>(_pointList);

    foreach (var point in _pointList)
    {
        if (d >= point.X && d <= point.Y)
        {
            _tempPointList.Remove(point);
        }
    }

    _pointList = _tempPointList;

}

As mentionend in the comments of your question, you could just use a predicate on List.RemoveAll() which deletes an item if the predicate returns true. I didn't test the performance, but feel free to compare.
foreach (var d in dots)
{
    _pointList.RemoveAll(point => d >= point.X && d <= point.Y);
}

A: You will need to make a copy of the list for your logic to work.
// instead of this
var _tempPointList = new List<Point>();

// make a copy like this
var _tempPointList = new List<Point>(_pointList);

Otherwise, you have just copied a reference to the list and both _tempPointList and _pointList point to same memory

A: You're having this problem because both _tempPointList and _pointList have the same reference so when you modify one list the other is modified automatically. another problem you're having is with Foreach you can't moidify a list when iterating over it using Foreach


Q: C0209: Formatting a regular string which could be a f-string (consider-using-f-string) For the below line, I am getting pylint issue: " C0209: Formatting a regular string which could be a f-string (consider-using-f-string)"
auth = str(base64.b64encode(bytes("%s:%s" % (self.user, self.password), "utf-8")), "ascii").strip()

I tried resolving it, but I am not sure if it is the right way to fix it. Can someone please advise?
auth = str(base64.b64encode(bytes(f'{self.user, self.password}', "utf-8")), "ascii").strip()

A: auth = str(base64.b64encode(bytes(f'{self.user}:{self.password}', "utf-8")), "ascii").strip()

You may not be using the f-string correctly, change f'{self.user, self.password}' to f'{self.user}:{self.password}'
More info


Q: Encoding Issue with PHP and MySQL In MySQL with phpmyadmin my text looks like:
& eacute; <-- no space, added to see.
When I read it into PHP and print it to the error_log it looks like:
\xe9
When I try to look at it in a web browser it looks like:
�
It should look like this in the web browser:
é
Does anyone know what is wrong?
my html page has the tags
<meta charset='UTF-8'>
and
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

A: Is your database set to use uft8_unicode_ci charset?

A: Solved:
I had to change the my.cnf file my MySQL
[client]
default-character-set=utf8

[mysql]
default-character-set=utf8

[mysqld]
collation-server = utf8_unicode_ci
init-connect='SET NAMES utf8'
character-set-server = utf8


Q: How to move a WordPress website to my computer for development? I was just hired to work in web design with WordPress and I'm struggling because I'm not experienced with the platform. My job is, basically, take the design made in Adobe Illustrator and build the layout in HTML and CSS.
Today I was assigned a site that's already online and had to build the new layout. My instructions were to activate the new template in the WordPress wp-admin, to create the new files (index.php, header.php, footer.php and style.css) in the FTP server and build from there.
Everything OK with that except that when I'm working on the site (maybe 3 or 4 hours), the site is kinda down because I'm uploading the new (incomplete) layout, am I explaining correctly?. E.g., if the web address is theclientsite.com I go to theclientsite.com/wp-admin/themes, define and activate new theme, write the code and test it directly in the browser going to theclientsite.com.
The question is: is there a way to work locally with the WordPress installation? I mean a way to test the site in something like localhost/theclientsite in the browser. My intuition says that the answer is YES, because we're talking about php code. But, as I said, I'm not experienced in the WordPress platform. I don't know if I need to be connected to a WordPress's server or something like that, or if I need to install something in my machine.
Any help, guide or tutorial is welcomed and will be appreciated. Thanks in advance for your answers.

A: Yes, it is possible to work offline by installing locally:

*

*Apache / Nginx

*PHP

*MySQL

That can be done...:

*

*with WampServer (Windows)

*with XAMPP (ALL)

*with MAMP (OSX)

*manually by installing all apps.

You will have to edit your host file to map the domain.com to your localhost (127.0.0.1).  The reason is that, by default, WordPress is not domain agnostic, which means absolute links (including the domain) are stored in the database. Otherwise, you will need to edit the data to map it to localhost.
As you are new with WordPress, I will remind you to backup the website BEFORE doing any change.  A free tool like BackWPup can do the job to backup all files and the database.
The changes you made on the website were made directly in production (meaning on the live site).  That is a really bad practice, as you probably know why now, because your visitors see and incomplete and buggy website.
That is why you need a dev environment where you can build and test everything.  If you did not do any backup and feel screwed, you can install a maintenance plugin like Ultimate Coming Soon Page and configure it to tell your visitors that the site is having a make over and come back later.
As for tutorials, I would start with How to install WordPress with WampServer.  First, you will understand how to install WordPress... in general.  Once you understand this part, you are ready to export an existing website and import it locally.  I would suggest to read more about How move a WordPress website locally.
This is a start! Use Google as you go... it will help a lot! :-)

A: You can install XAMPP packages that ships with Apache, Mysql (MariaDB actually) and PHP environments. All already configured so you can just Next > Next > Install.
https://www.apachefriends.org/pt_br/index.html

A: I've always preferred working directly on the remote server using Aptana with built-in FTP client. I've known others that prefer working locally using WAMP.
https://sourceforge.net/projects/wampserver/


Q: accessors in class extending JPanel I'm writing a clone of Risk in Java, and am having some trouble with my code. When I create a new game, I create a JPanel with a JTextField (for the player name) and a JComboBox(for the player color), one panel for each player the user wants to create. Instances of this panel are created dynamically based on a second JComboBox which lets the user select a number of players from three to eight.
My problem is that when I want to create the player objects from the data entered into the player creation panel, each player object retrieves the data from the most-recently-created player creation panel. I have a functional solution, but I can't seem to figure out why what seems to be the 'proper' solution () won't work.
This is the code that I have working right now:
Creation panel class:
package risk;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class PlayerCreatePanel extends JPanel{

public static ImageIcon[] playerColors = {Resources.red,Resources.green,Resources.blue,Resources.cyan,Resources.magenta,Resources.yellow,Resources.orange,Resources.gray};

public JComboBox playerColor;

public JTextField playerName;

public PlayerCreatePanel(int index){

    this.setPreferredSize(new Dimension(360, 30));

    JLabel numberLabel = new JLabel ("Player " + index + ":  ");
    JLabel nameLabel = new JLabel("Name: ");
    JLabel colorLabel = new JLabel("  Color: ");

    playerName = new JTextField("");
    playerName.setColumns(13);

    playerColor = new JComboBox(playerColors);

    this.add(numberLabel);
    this.add(nameLabel);
    this.add(playerName);
    this.add(colorLabel);
    this.add(playerColor);
}
}

And for the new game class, the part that creates players:
package risk;

import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;

public class NewGame {

private static PlayerCreatePanel [] panels = {  new PlayerCreatePanel(1), new PlayerCreatePanel(2),
                                                new PlayerCreatePanel(3), null, null, null, null, null};

private static int playerCount = 3;

public static void createPlayers(){
    Resources.players = new Player[playerCount];
    switch(playerCount){
    case 8: Resources.players[7] = new Player (panels[7].playerName.getText(), Resources.colors[panels[7].playerColor.getSelectedIndex()], 8);
    case 7: Resources.players[6] = new Player (panels[6].playerName.getText(), Resources.colors[panels[6].playerColor.getSelectedIndex()], 7);
    case 6: Resources.players[5] = new Player (panels[5].playerName.getText(), Resources.colors[panels[5].playerColor.getSelectedIndex()], 6);
    case 5: Resources.players[4] = new Player (panels[4].playerName.getText(), Resources.colors[panels[4].playerColor.getSelectedIndex()], 5);
    case 4: Resources.players[3] = new Player (panels[3].playerName.getText(), Resources.colors[panels[3].playerColor.getSelectedIndex()], 4);
    case 3: Resources.players[2] = new Player (panels[2].playerName.getText(), Resources.colors[panels[2].playerColor.getSelectedIndex()], 3);
            Resources.players[1] = new Player (panels[1].playerName.getText(), Resources.colors[panels[1].playerColor.getSelectedIndex()], 2);
            Resources.players[0] = new Player (panels[0].playerName.getText(), Resources.colors[panels[0].playerColor.getSelectedIndex()], 1); break;
    default: break;
    }
}
}

Now, what I've learned is the proper way to do this is to make my JTextField and JComboBox private, and write accessors, like so:
private JComboBox playerColor;
private JTextField playerName;

//...same method as above

public static String getName(){
    return playerName.getText();
}

public static int getColorIndex(){
    return playerColor.getSelectedIndex();
}

and change the creation lines in the new game method to read something like this:
Resources.players [0] = new Player (panels[0].getName(), panels[0].getColorIndex(), 1);


Q: Is it true that $a^k\equiv a^\ell \mod n$? Let $a, b\in\mathbb{Z}$, $n\in\mathbb{N}$, and $k, \ell\in \mathbb{N}$, such that $k\equiv \ell \mod{n}$ and $a\equiv b\mod n$.
Is it true that $a^k\equiv a^\ell \mod n$? If so, prove it. If not, find a counterexample.
I suppose it's true, but I'm not sure how to prove it.

A: Hint: What if $n=3$, $k=1$, $\ell=4$ and $a=2$?

A: No. At least not generally. See: $$y\equiv b\bmod m\implies y=mx+b$$  This means only if y and m share a factor (or x but we generally ignore it) will b share a factor. So if y is a power based on a value that doesn't share a factor, all it's remainders b wont share a factor with the modulus m. Only when the number of of values less than m, that don't share a factor with m, ends up being a divisor of m, will your statement be true. This restricts it pretty much to powers of 2. A few  more edge cases exist like 6, but that's basically it. if they share a factor it will  change for example every value with a factor (2) in common with 8 will hit 0 mod 8 and stay there for any higher powers.It will only hit remainders that have that gcd in common.


Q: Two RigidBodies - How Do I Make One Immobile? In a 2D shooter, I have one RigidBody that is a rotating wall.  My player (ship) is another RigidBody.  Both have gravity of 0 and are non-kinematic.  I want the ship to not be able to move the wall, but to halt up against it.  Currently, the ship hits it and both are affected by the collision and start floating around.
Is the proper way to accomplish this to set the constrain Y and Z on the rotating wall so that it can't be moved by a collision with the ship?  When I do this, the rotating wall's rotation stops working so before I go further down that path I wanted to see if this is the canonical approach to making something with a rigidbody immobile (constraining X and Y).

A: Make the one you don't want to move kinematic

A: I've been through this, I had a wall and a character with RigidBody.
I didn't want the wall to move in a collision with the character, to solve that, I just made the wall a LOOOTT heavier than the character, just make the "MASS" of the wall very high! The character will not be able to move it!  /o/
Hope that helps!


Q: How do restructure the trip data to prepare a link data using spread and gather functions in R? I have a trip data set as follows:
df <- data.frame(user =c("P001", "P001", "P002"), tripID = c("tid1", "tid2", "tid3"), mode =c("bus", "train", "taxi"), Origin = c("Westmead", "Redfan", "Westmead"), Destination = c("Redfan", "Darlington", "Strathfield"), depart_dt = c("8:00", "8:30", "8:45") )

I need to restructure the above data using probably spread() and gather() functions from tidyr to prepare a link trip data as follows:
df_new <- data.frame(user=c("P001", "P002"), tripID = c("newtid1", "newtid2"), mode = c("bus + train", "taxi"), Origin = c("Westmead", "Westmead" ), Destination = c("Darlington", "Strathfield"), depart_dt = c("8:00", "8:45"))

I am a new bee in R. Can anyone help me here?
Many thanks in advance.

A: Using dplyr:
library(dplyr)

df <- data.frame(user =c("P001", "P001", "P002"), tripID = c("tid1", "tid2", "tid3"), mode =c("bus", "train", "taxi"), Origin = c("Westmead", "Redfan", "Westmead"), Destination = c("Redfan", "Darlington", "Strathfield"), depart_dt = c("8:00", "8:30", "8:45") )

df %>%
  group_by(user) %>%
  arrange(depart_dt, .by_group = TRUE) %>%
  summarize(Origin = Origin[1], mode = paste(mode, collapse = " + "),
            Destination = Destination[length(Destination)],
            depart_dt = depart_dt[1]) %>%
  mutate(tripID = paste0("newtid", row_number()))
#> # A tibble: 2 x 6
#>   user  Origin   mode        Destination depart_dt tripID
#>   <fct> <fct>    <chr>       <fct>       <fct>     <chr>
#> 1 P001  Westmead bus + train Darlington  8:00      newtid1
#> 2 P002  Westmead taxi        Strathfield 8:45      newtid2

Created on 2020-05-06 by the reprex package (v0.3.0)

A: You don't need to use spread() or gather() (or their successors pivot_longer. and pivot_wider().
The below should give you what you want.
library(tidyverse)

df %>%
  group_by(user) %>%
  arrange(tripID, .by_group = TRUE) %>%
  summarise(mode = str_c(mode, collapse = " + "),
            Origin = first(Origin),
            Destination = last(Destination),
            depart_dt = first(depart_dt)) %>%
  mutate(tripID = str_c("newtrid", row_number()))

#   user  mode        Origin   Destination depart_dt tripID
#   <fct> <chr>       <fct>    <fct>       <fct>     <chr>
# 1 P001  bus + train Westmead Darlington  8:00      newtrid1
# 2 P002  taxi        Westmead Strathfield 8:45      newtrid2


Q: Workflow Foundation Threading and WCF OperationContext I am using the WorkFlowServiceHost(in .net 3.5) to host a State Machine Workflow.  I use the WCF receive activities to handle calls into the workflow.  I am using a WCF authorization policy to attach claims to the incoming requests based on info in the message headers. So, further down the chain I can use the ServiceSecurityContext or just the Thread.CurrentPrincipal to get authorization info about the request(roles, user, etc).
I know this will not work for us because the workflow is dispatching different threads to handle the events that the runtime engine raises when there is work to do(ie. the receiveactivity).  The contextual info about the request(OperationContext) is no longer available within the workflow(except randomly when the work is executed on the runtime thread).
What I would like to do is get the info about the request(OperationContext) before the worker thread is created, get the worker thread and attach the contextual info to it so it is available within the workflow instance.
I am thinking there must be some event on the runtime I can handle to do this but I am not coming up with anything.  And I really don't want to use the manual workflow scheduler.  Any help is appreciated.
Thanks!

A: I'm pretty late with this, but I was googling "silverlight operationcontext" and found your SO question as well as the blog post that I am linking (one right after the other in the Google results).  I don't know if it will help or not (he says, almost two years later).
I haven't worked much with WCF and not at all with WFF, so I don't really have much to add aside from this link.


Q: App delegate methods aren't being called in iOS 13 I am using Xcode 11 and building an app for iOS 13. In a new project I created in Xcode some of the UIApplicationDelegate methods were missing so I added them back into the app delegate file. The new template for a "Single View App" project was missing the methods. The problem is that none of the delegate methods are getting called except -application:didFinishLaunchingWithOptions:. Here is my app delegate:
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSLog(@"application:didFinishLaunchingWithOptions:");
    return YES;
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSLog(@"applicationDidEnterBackground:");
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    NSLog(@"applicationWillEnterForeground:");
}
#pragma mark - UISceneSession lifecycle

- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
}

- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
}

@end

A: This thread helped me:
View controller responds to app delegate notifications in iOS 12 but not in iOS 13
Objective C:
if (@available(iOS 13.0, *)) {
    [[NSNotificationCenter defaultCenter] addObserver:self
          selector:@selector(appWillResignActive:)
          name:UISceneWillDeactivateNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
          selector:@selector(appDidBecomeActive:)
          name:UISceneDidActivateNotification object:nil];

}
else {
    [[NSNotificationCenter defaultCenter] addObserver:self
          selector:@selector(appWillResignActive:)
          name:UIApplicationWillResignActiveNotification object:nil];

    [[NSNotificationCenter defaultCenter]addObserver:self
          selector:@selector(appDidBecomeActive:)
          name:UIApplicationDidBecomeActiveNotification
                                              object:nil];
}

A: Application and scene lifecycle is not the same thing!

In my opinion, disabling calls of application state change methods (as well as sending application state change notifications on change the state of each scene) is a mistake, even though there was an understandable intention to force programmers to adapt to the new scenes lifecycle.
Here is a scene delegate template restoring the expected calls of application state change methods of the application delegate:
@available(iOS 13.0, *)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    func sceneWillResignActive(_ scene: UIScene) {

        if !UIApplication.shared.connectedScenes.contains(where: { $0.activationState == .foregroundActive && $0 != scene }) {
            UIApplication.shared.delegate?.applicationWillResignActive?(.shared)
        }
    }

    func sceneDidEnterBackground(_ scene: UIScene) {

        if !UIApplication.shared.connectedScenes.contains(where: { $0.activationState == .foregroundActive || $0.activationState == .foregroundInactive }) {
            UIApplication.shared.delegate?.applicationDidEnterBackground?(.shared)
        }
    }

    func sceneWillEnterForeground(_ scene: UIScene) {

        if !UIApplication.shared.connectedScenes.contains(where: { $0.activationState == .foregroundActive || $0.activationState == .foregroundInactive }) {
            UIApplication.shared.delegate?.applicationWillEnterForeground?(.shared)
        }
    }

    func sceneDidBecomeActive(_ scene: UIScene) {

        if !UIApplication.shared.connectedScenes.contains(where: { $0.activationState == .foregroundActive && $0 != scene }) {
            UIApplication.shared.delegate?.applicationDidBecomeActive?(.shared)
        }
    }
}

SceneDelegate.swift

A: iOS 13 has a new way of sending app lifecycle events. Instead of coming through the UIApplicationDelegate they come through the UIWindowSceneDelegate which is a UISceneDelegate sub-protocol. UISceneDelegate has the important delegate methods.
This change is to support multiple windows in iOS 13. There's more information in WWDC 2019 session 212 "Introducing Multiple Windows on iPad". The technical information starts at around 14:30 and is presented by a man with very sparkly high-tops. The shorter session 258 Architecting Your App for Multiple Windows also has a great introduction to what's changed.
Here's how it works: If you have an "Application Scene Manifest" in your Info.plist and your app delegate has a configurationForConnectingSceneSession method, the UIApplication won't send background and foreground lifecycle messages to your app delegate. That means the code in these methods won't run:

*

*applicationDidBecomeActive

*applicationWillResignActive

*applicationDidEnterBackground

*applicationWillEnterForeground
The app delegate will still receive the willFinishLaunchingWithOptions: and didFinishLaunchingWithOptions: method calls so any code in those methods will work as before.
If you want the old behaviour back you need to

*

*Delete the "Application Scene Manifest" entry from the app's Info.plist

*Comment or delete the application:configurationForConnectingSceneSession:options: method (or the Swift application(_:configurationForConnecting:options:)function)

*Add the window property back to your app delegate (@property (strong, nonatomic) UIWindow *window;)

Alternatively, open the SceneDelegate file that Xcode made and use the new lifecycle methods in there:
- (void)sceneDidBecomeActive:(UIScene *)scene {
}
- (void)sceneWillResignActive:(UIScene *)scene {
}
... etc

It's possible to use the new UIScene lifecycle stuff without adopting multiple window support by setting "Enable Multiple Windows" ("UIApplicationSupportsMultipleScenes") to "NO" in the Info.plist (this is the default for new projects). This way you can start adopting the new API in smaller steps.
You can see that the scene delegate method names are a close match for the app delegate ones. One confusing thing is that the app delegate methods aren't deprecated so you won't get a warning if you have both app delegate and scene delegate methods in place but only one will be called.
Other things that UISceneDelegate takes over are user activities (continueUserActivity: etc), state restoration (stateRestorationActivityForScene: etc), status bar questions and opening URLs. (I'm not sure if these replace the app delegate methods). It also has analogous notifications for the lifecycle events (like UISceneWillDeactivateNotification).
From the WWDC Session, some images for you:
The function equivalents for Swift:

The class responsibilities: