text:
Q: Read Write json file This method reads text from json file.I want to read only name,date,time from json file.How can I accomplish this.My json file contains various records each record consisting of name,lat,lon,image_name,date,time.I need to read name,date,time of one record and place it as radio button1 value then read second name,date,time of second record and place it in radio butto2 value.
I also need to delete specific name and update specific name.
Please help me and Thank You in advance.Have a great day ahead.
 String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
            File myDir = new File(root + "/GeoPark");//create folder in internal storage
            myDir.mkdirs();// make directory
            File file = new File(myDir, FILENAME);//making a new file in the folder

            if(file.exists())   // check if file exist
            {
                //Read text from file
                StringBuilder text = new StringBuilder();

                try {
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    String line;

                    while ((line = br.readLine()) != null) {
                        text.append(line);
                    }
                }
                catch (IOException e) {
                    //You'll need to add proper error handling here
                }
                //Set the text
                String x=text.toString();
                String z=x.replace("{","").replace("date:","").replace("time:","").replace("Record:","").replace("[","").replace("latitude:","").replace("longitude:","").replace("name:","").replace("address:","").replace("pin:","").replace("area:","").replace("image:","").replace("\"","").replace("]","").replace("}","");
                String[] y=z.split(",");

                rb1.setText(y[3].toString()+","+y[7].toString()+","+y[8].toString());

            }
            else
            {
                rb1.setText("Sorry file doesn't exist!!");
            }

This is my json file
{Record:["lat":"22.5835","lon":"88.456","name":"aa","add":"cc",date:30/04/2018,time:21:05:10]}
{Record:["lat":"22.583544","lon":"88.45642","name":"BB","add":"cc",date:30/04/2018,time:21:05:40]}

A: Consider using GSON.
Serialization is as simple as calling
String jsonStr = Gson().toJson(obj)

And for deserialization,
MyClass deserialized = Gson().fromJson(jsonStr, MyClass.class);

JSON on Android - serialization

A: First you should convert your string to json object then parse it as you want.
Assuming your json is
String data="{'foo':'bar','coolness':2.0, 'altitude':39000, 'pilot':{'firstName':'Buzz','lastName':'Aldrin'}, 'mission':'apollo 11'}";

then you can easily do
JSONObject json = (JSONObject) JSONSerializer.toJSON(data);
    double coolness = json.getDouble( "coolness" );
    int altitude = json.getInt( "altitude" );
    JSONObject pilot = json.getJSONObject("pilot");
    String firstName = pilot.getString("firstName");
    String lastName = pilot.getString("lastName");

    System.out.println( "Coolness: " + coolness );
    System.out.println( "Altitude: " + altitude );
    System.out.println( "Pilot: " + lastName );

Isn't it easy?

A: Here, try this
String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
            File myDir = new File(root + "/GeoPark");//create folder in internal storage
            myDir.mkdirs();// make directory
            File file = new File(myDir, FILENAME);//making a new file in the folder

            if(file.exists())   // check if file exist
            {
                //Read text from file
                StringBuilder text = new StringBuilder();

                try {
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    String line;

                    while ((line = br.readLine()) != null) {
                        text.append(line);
                    }
                }
                catch (IOException e) {
                    //You'll need to add proper error handling here
                }
                //Set the text

            JSONObject obj = new JSONObject(text.toString());
            JSONArray arr = obj.getJSONArray("Record");
            for (int i = 0; i < arr.length(); i++){
                 String name = arr.getJSONObject(i).getString("name");
                 String date = arr.getJSONObject(i).getString("date");
                 String time = arr.getJSONObject(i).getString("time");
              }
            }
            else
            {
                rb1.setText("Sorry file doesn't exist!!");
            }

you can also see -> http://theoryapp.com/parse-json-in-java/


text:
Q: In gradle, how can a test configuration declare a dependency upon another project's test configuration? In gradle 5.6.2, I have a project with sub-projects. The tests in the sub-projects share a lot of code, so I'd like sub-projects tests to depend upon parent projects tests. But references in tests do not resolve, even though references in the main projects do. The Gradle docs say to use a "map notation" dependency declaration, and this dependencies block does not generate errors:
dependencies {
    api project(":henchbot-api")
    testImplementation project(path: ':henchbot-api', configuration: 'testRuntime')
}

... but the tests won't compile. If I change testRunTime to testRuntimeClasspath then gradle fails to resolve that project dependency.

A: you will also need to declare the test artefact - see https://docs.gradle.org/current/userguide/multi_project_builds.html#sec:project_jar_dependencies
in the project henchbot-api
configurations {
    testLib
}

task testLibJar(type: Jar) {
    archiveBaseName = archivesBaseName + '-testLib'
    from sourceSets.test.output
}

artifacts {
    testLib testLibJar
}

in the other one - the dependency is
testImplementation project(path: ':henchbot-api', configuration: 'testLib')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessing multiple tables in SQLEXEC statement, SQL Pass Through I create a cursor called 'table1_data' from the statement:
lnResult1 = SQLEXEC(m.hConn, 'select * from table1 where status like ?m.seeStatus','table1_data')
Now I want to access this table in my next SQLEXEC statement:
lnResult2 = SQLEXEC(m.hConn, 'select * from table2 where table2.item_id = table1_data.item_id','table2_data')
however I get the error: The multi-part identifier table1_data.item_id could not be bound. Any help much appreciated!

A: You can join both tables, but instead of SELECT * you should always neme the columns that you only need.
that helps also in future.
lnResult1_2 = SQLEXEC(m.hConn, 'select table1.*,table2.* from table1, table2 where table2.item_id = table1_data.item_id AND  status like ?m.seeStatus')

I can't find any code related to joins, but
lnResult1_2 = SQLEXEC(m.hConn, 'select table1.*,table2.* from table1 JOIN table2 ON table2.item_id = table1_data.item_id WHERE  status like ?m.seeStatus')

should also work, but as i said i can't find any code that uses explicit join, so you can give it a try and give a short response

A: In first case table1_data is a local cursor and you cannot use it in second call which is made to server.
However since table1_data is also coming from server side you could instead do this:
*** Using text ... endtext just to make the SQL more readable

local lcSQL
text to m.lcSQL noshow
select * from table2
where exists (select * from table1
              where table2.item_id = table1_data.item_id and
                    table1.status like ?m.seeStatus);
endtext

lnResult1 = SQLEXEC(m.hConn, 'select * from table1 where status like ?m.seeStatus','table1_data')
lnResult2 = SQLEXEC(m.hConn, m.lcSQL,'table2_data')

EDIT: BTW you can return 2 results from a single SQLExec() call however  it is not worth it here in this case. Two separate queries as above is just fine (and remember you could make them updatable per table).


text:
Q: Can't uploading base 64 to imgur     up: function(req, res) {
    console.log(req.param('image'));
    imgurwrap.setClientID('myImgurClientID')
    imgurwrap.uploadImageBase64({
        image: req.param('image'),
        title: 'sfdsf',
        description: 'sfsdf'
    }, function(err, res) {
        console.log(res);
        console.log(err);
    });
},

This code returns me an url with an empty image like this: http://i.imgur.com/1cmilFL.png . However if I declare a variable and put my encoded base64 string in it, it works.
So I thought some data was appened in the request but a diff showed no difference. I've tried others npm imgur modules and it's always the same behavior so something must be wront on my side but I can't figure it out..


text:
Q: missing java source files after brew cask install adoptopenjdk11 having installed java via brew cask install adoptopenjdk11
using it in e.g. vscode works fine.
But I want to "go to definition" of jdk classes and investigate the source .java code of jdk classes.
Is there a way to "add" jdk sources which vscode "recognizes" with F-12 "Go to Definition" ?

A: reinstalling the jdk solved the problem


text: Q: How do you change the icon for a message box in tkinter? I was wondering how you could change the icon that appears next to the title of the MessageBox? I was wondering because I have seen other programs using it, but nobody will tell me how. Please help!


text:
Q: Matlab rat function in C language Do you know how to make a rational approximation of a decimal number in C (similar to rat Matlab function)?
Update
If we want a P/Q approximation of a double number number, a quick fix could be:
int factor=1000000;
P=floor(number*factor);
Q=factor;

The error is less than (number/factor), which is negligible.

A: Continued fractions can be used to calculate rational approximations to real numbers that are optimal in a sense. That way with the input 0.33333333  you have a chance of obtaining 1/3 rather than 3333/10000.

A: You can do the same as you have done in your update, but then check for the highest common factor between the top and bottom and simplify. For example, 0.5 would go to 500000/1000000 doing it your method. They share a common factor of 500000 so you can divide both top and bottom by that to get 1/2. Google has a lot of examples of hcf functions , such as this one (Edit: And this impressive list).


text:
Q: Discord.py - Add role to user import discord
from discord import Embed, Color

def ex(args, message, client, invoke):
    if (message.mentions.__len__() > 0):
        for member in message.mentions:
            server = message.server.name
            role = discord.utils.get(server.roles, name="MMDev")
            yield from client.add_roles(member, role)

This is my code. I have tried to add the mentioned user the role "MMDev".
This is the error:
Traceback (most recent call last):
  File "venv\lib\site-packages\discord\client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "main.py", line 91, in on_message
    yield from commands.get(invoke).ex(args, message, client, invoke)
  File "cmdmute.py", line 9, in ex
    role = discord.utils.get(server.roles, name="MMDev")
AttributeError: 'str' object has no attribute 'roles'

It´s Python 3.5

A: message.server.name is the name of the server, you instead want the Server object itself.
def ex(args, message, client, invoke):
    if (message.mentions.__len__() > 0):
        for member in message.mentions:
            role = discord.utils.get(message.server.roles, name="MMDev")
            if role:
                yield from client.add_roles(member, role)


text:
Q: keyWindow lost when call to start watching location in iOS APP When we call to sfmc_startWatchingLocation, if we have location permissions granted, with the conditions details below, after assign window key:
window.makeKeyAndVisible()

its provokes to lose the reference when we accessed to it from our app:
UIApplication.shared.keyWindow

this answers nil, and we can not reassign it.
If we don't call to sfmc_startWatchingLocation, this problem never happens.
NOTE:  If location permissions have not been granted, the problem never happens either.
Please help me to solve this problem. If any further clarifications are required on this question please post a comment.
This error is provoking crashes in my app, and bad comments in Store.
Thanks
ERROR CONDITIONS:
Devices: iPhone 12pro(iOS15.3), iPhoneXR, ... (newest devices)
iOS version: iOS 15.3.1 (we had not detected it before)
Lib version: 'MarketingCloudSDK' version '7.3.1', integrated via cocoapods
Xcode version: tested in 12.1, 13.2, 13.2.1


text:
Q: Javascript's Date.getTimezoneOffset returns 0 when running on remote server I'm in Philippines and running this line of code in localserver/localhost returns a timezone offset correctly.
console.log(new Date().getTimezoneOffset());
// output: -480

But when I run this code in remote server it outputs 0.
My localserver setup:
Mac os, node.js, and mongodb
Our remote sever setup:
ec2 instance in Amazon web services (AWS), running ubuntu os, node.js and mongodb.
Does anyone here know how to get the timezone offset when running from remote server?
Thank you.

A: You have to set the correct timezone on your server. On an Ubuntu server you can input the following command:
sudo dpkg-reconfigure tzdata

Choose the correct timezone for you and then you'll get the correct timezone when using: new Date().getTimezoneOffset()

In case you need to handle multiple timezones, I recommend using moment-timezone to do it easily.
const moment = require('moment');
const losAngeles = moment().tz('America/Los_Angeles');
console.log(losAngeles.format());

const manila = moment().tz('Asia/Manila');
console.log(manila.format());

A: Try to check your server timezone:
timedatectl

I guess it may be "Etc/UTC (UTC, +0000)". If so, that means your server is currently set to UTC. This isn't physical place where your server is located. We can set our computer to any timezone.
However, for the server, I recommend to keep the timezone as UTC. So we can do any calculations relating to date/time based on a standard unit. We should store the date time values in the database as UTC time.


text:
Q: Moving from shared cpanel hosting to non cpanel VPS - What should I know? I'm currently looking into migrating a few sites from my shared cpanel hosting to a VPS. Got to the point where I want to do more and have been learning about some system admin stuff through my placement/work.
Firstly, what are the essential things I should know? I understand how to set up an apache config, can probably work out how to set up email accounts and the like, however I'm sure there is much more that I haven't been shown, as I'm a programmer and not a sys admin.
I currently host a number of wordpress sites, a few static sites and a zen cart (shudders), and will be porting all of them including email accounts over to a new VPS.
If it helps, I'm currently with Hostgator shared hosting, and planning to move to Thrus VPS (Thrust VPS Site) on their basic VPS OpenVZ plan. They do have a cpanel option, however it's A LOT more expensive. Could I for example use cpanel to import everything, then turn it off and do everything terminal side? I know little about how cpanel actually does its job.
Further, their three *nix hosting packages are either OpenVZ, Xen PV or Xen HVM, and to be totally honest, even though I've researched into each of these, I'm not completely sure which one I would want and why, although I suspect OpenVZ.

A: It's impossible to predict everything you'll need to know of course, but here's a quick checklist, assuming you have not had much experience with modern linux distros.

*

*Choose what distro you want your server to run. Debian derivative, redhat derivative or something else?

*Get SSH figured out so you can get into your server.

*Get your distro's package management tools figured out so you can install stuff.

*Install the stuff you need through your package manager... for example apache, php, mysql.

*Configure the stuff you installed. Realize you need more modules for apache and php. Install them.

*Learn how to (re)start system services. Restart apache now that you added a bunch of apache and php modules you needed and reconfigured it.

*Learn how to set up virtual hosts (vhosts) on apache.

Amazon's AWS service is a good way to set up virtual machines quickly and test stuff out without too much trouble, and it scales into one of the nicest hosting solutions I've ever seen. You might consider it before looking at some of the other hosting options.
These guys are good too: http://www.gplhost.com/  ... particularly if you're looking for something less corporate or want to be sure real people are behind the service. It's a small outfit with only a handful of employees but they somehow manage to have offices worldwide and answer the phone at 3:00 AM when we call them with stupid questions.

A: cpainl creates a compressed archive for individual accounts.  To restore/import a domain/account to a non-cpanel system, decompress (uncompress?) the archive and take a look at the file structure therein:
total 96K
drwx------.  2 ilmostro    6 Aug 21 03:02 bandwidth
drwx------.  2 ilmostro    6 Aug 21 03:02 bandwidth_db
drwx------.  2 ilmostro    6 Aug 21 03:02 counters
drwx------.  2 ilmostro   19 Aug 21 03:02 cp
drwx------.  2 ilmostro    6 Aug 21 03:02 cron
drwx------.  2 ilmostro   26 Aug 21 03:02 dnszones
drwx------.  4 ilmostro   33 Aug 21 03:02 domainkeys
drwx--x--x. 19 ilmostro 4.0K Aug 21 03:02 homedir
drwx------.  2 ilmostro    6 Aug 21 03:02 httpfiles
drwx------.  2 ilmostro   24 Aug 21 03:02 ips
drwx------.  2 ilmostro    6 Aug 21 03:02 locale
drwx------.  2 ilmostro   99 Aug 21 03:02 logs
drwx------.  2 ilmostro   93 Aug 21 03:02 meta
drwx------.  2 ilmostro    6 Aug 21 03:02 mm
drwx------.  4 ilmostro   27 Aug 21 03:02 mma
drwx------.  2 ilmostro    6 Aug 21 03:02 mms
drwx------.  2 ilmostro 4.0K Aug 21 03:02 mysql
drwx------.  2 ilmostro   67 Aug 21 03:02 mysql-timestamps
drwx------.  2 ilmostro    6 Aug 21 03:02 psql
drwx------.  2 ilmostro   22 Aug 21 03:02 resellerconfig
drwx------.  2 ilmostro    6 Aug 21 03:02 resellerfeatures
drwx------.  2 ilmostro    6 Aug 21 03:02 resellerpackages
drwx------.  2 ilmostro    6 Aug 21 03:02 ssl
drwx------.  2 ilmostro 4.0K Aug 21 03:02 sslcerts
drwx------.  2 ilmostro 4.0K Aug 21 03:02 sslkeys
drwx------.  2 ilmostro    6 Aug 21 03:02 suspended
drwx------.  2 ilmostro    6 Aug 21 03:02 suspendinfo
drwxr-xr-x.  2 ilmostro    6 Aug 21 03:02 userconfig
drwx------.  2 ilmostro   96 Aug 21 03:02 userdata
drwx------.  2 ilmostro   47 Aug 21 03:02 va
drwx------.  2 ilmostro   47 Aug 21 03:02 vad
drwx------.  2 ilmostro   47 Aug 21 03:02 vf
-rw-------.  1 ilmostro    0 Aug 21 03:02 addons
-rw-------.  1 ilmostro  41K Aug 21 03:02 bandwidth_db.json
-rw-------.  1 ilmostro    0 Aug 21 03:02 digestshadow
-rw-r--r--.  1 ilmostro    0 Aug 21 03:02 has_sslstorage
-rw-------.  1 ilmostro   13 Aug 21 03:02 homedir_paths
-rw-------.  1 ilmostro 1.5K Aug 30 06:09 mysql.sql
-rw-------.  1 ilmostro    0 Aug 21 03:02 nobodyfiles
-rw-------.  1 ilmostro    0 Aug 21 03:02 pds
-rw-r-----.  1 ilmostro  350 Apr 20 03:28 proftpdpasswd
-rw-------.  1 ilmostro    1 Aug 21 03:02 quota
-rw-------.  1 ilmostro   18 Aug 21 03:02 sds
-rw-------.  1 ilmostro   48 Aug 21 03:02 sds2
-rw-------.  1 ilmostro  106 Aug 21 03:02 shadow
-rw-------.  1 ilmostro   31 Aug 21 03:02 shell
-rw-------.  1 ilmostro    0 Aug 21 03:02 ssldomain
-rw-r--r--.  1 ilmostro   39 Aug 21 03:02 version

For the most part, a lot of the directories and/or files can be ignored, unless you want to import everything; i.e. cron, mail, bandwidth usage, etc.
Arguably, the main items, in most scenarios, pertain to the database, dns, and apache.  Therefore, focus should be on the following files/folders:
drwx------.  2   26 Aug 21 03:02 dnszones
drwx------.  4   33 Aug 21 03:02 domainkeys
drwx--x--x. 19 4.0K Aug 21 03:02 homedir
drwx------.  2 4.0K Aug 21 03:02 mysql
drwx------.  2 4.0K Aug 21 03:02 sslcerts
drwx------.  2 4.0K Aug 21 03:02 sslkeys
drwx------.  2   96 Aug 21 03:02 userdata
-rw-------.  1 1.5K Aug 30 06:09 mysql.sql
-rw-------.  1   18 Aug 21 03:02 sds
-rw-------.  1   48 Aug 21 03:02 sds2

The userdata directory made it in there because it has some useful reference items for the configuration; similar reasons for the sds and sds2 files.

Make any necessary changes to the files, paying attention to the old IPs in particular!
Database
Then create the specific database.  Repeat for additional databases, depending on the domains, files, databases.  dbname.create file also creates the necessary users and give them the necessary privileges on the databases.
# mysql < mysql/yourdomain_database.create

Import the database like so:
# mysql yourdomain_database < mysql/yourdomain_database.sql

DNS
# cp -v dnszones/*.db /var/named/

Copying over the DNS zone files to your dns server, if applicable.  Make sure to adjust the necessary DNS server configuration to include the zone files; e.g./etc/named.conf.
apache
Then, focus on the remaining stuff related to apache, which will be located in homedir/public_html/ (though, it may be directly in /homedir/ in recent cpanel versions).  The following WordPress installation, with a folder to a subdomain, can be used as an example:
homedir/public_html/
├── cgi-bin
├── configurations.json
├── css
├── font-awesome
├── fonts
├── img
├── index.php
├── js
├── LICENSE
├── license.txt
├── subdomain.yourdomainname.com
├── readme.html
├── sitemap.xml
├── strac-yourdomainname.com-phpindex
├── test.php
├── wp-activate.php
├── wp-admin
├── wp-blog-header.php
├── wp-comments-post.php
├── wp-config.php
├── wp-content
├── wp-cron.php
├── wp-includes
├── wp-links-opml.php
├── wp-load.php
├── wp-login.php
├── wp-mail.php
├── wp-settings.php
├── wp-signup.php
├── wp-trackback.php
└── xmlrpc.php

Copy the content to the DocumentRoot and update your apache config files with any VirtualHost options:
cp -r homedir/public_html/* /var/www/html/

vim /etc/httpd/httpd.conf

You might have to make the necessary changes to the PHP, apache, and/or mysql versions and configuration as well.  Try to ensure the versions and options are as close to that of the cpainl server as possible.


text:
Q: Would it matter where in the DOM tree that I insert the external JavaScript resource? I am reading the official Facebook JS SDK script:
<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId      : 'your-app-id',
      xfbml      : true,
      version    : 'v2.8'
    });
    FB.AppEvents.logPageView();
  };

  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));
</script>

It inserts the created <script> tag to the fjs.parentNode. Is that by design?
If I write replace:
fjs.parentNode.insertBefore(js, fjs);

with:
document.head.appendChild(js);

Would it still work?

A: Yes both will work but
fjs.parentNode.insertBefore(js, fjs);

This will insert JS before all JS file and other-side
document.head.appendChild(js);

This will insert after all JS in Head.


text:
Q: how to add cc in email while sending email from iphone app I am sending email from iphone app it is working fine i want to add cc also in email any idea how to do this .i am using following code can you please help how to add CC in this.
thanks.
initializing controller for sending email
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;

    NSString*giveFileName=@"CPAC_Contract_Equine";
NSString *fileName;
//fileName = [[NSString alloc]initWithFormat:@"%@.pdf",giveFileName];
fileName = [[NSString alloc]initWithFormat:@"%@",giveFileName];

NSString*myFileName=@"W9.pdf";

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];

NSMutableData *myPdfData = [NSMutableData dataWithContentsOfFile:pdfFileName];

NSString *pathJam = [[NSBundle mainBundle] pathForResource:@"W9" ofType:@"pdf"];
NSData *myDataJam = [NSData dataWithContentsOfFile: pathJam];

NSArray * toRecipients = [NSArray arrayWithObject:@""];

[picker setToRecipients:toRecipients];

[picker setSubject:@"CPAC Contract for Equine-Sam Veterinarian"];

[picker addAttachmentData:myPdfData mimeType:@"application/pdf" fileName:giveFileName];

NSString * emailBody =@"Thank you for your participation in Consulting
Practitioner and Client Program.

Attached is the copy of your signed contract for your records
Please email or fax your completed W-9 form to
our PEI Support Team
Email:PEISupportServices@zoetis.com
Fax:800-741-1310";

[picker setMessageBody:emailBody isHTML:YES];

[self.navigationController presentViewController:picker animated:YES completion:nil];

A: The MFMailComposeViewController has a setCcRecipients: method. You would use it like this:
[picker setCcRecipients:[NSArray arrayWithObject:@"someone@example.com"]];

A:     NSString *subject = @"";
    NSString *body = @"";
    NSString *address = @"to@gmail.com";
    NSString *cc = @"cc@gmail.com";
    NSString *path = [NSString stringWithFormat:@"mailto:%@?cc=%@&subject=%@&body=%@", address, cc, subject, body];
    NSURL *url = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    [[UIApplication sharedApplication] openURL:url];

A: [mailComposeViewController setToRecipients:@[@"ibanking@com"]];

[mailComposeViewController setCcRecipients:@[@"ccs.cmc@com"]];


text:
Q: How to read a file from the Documents directory asynchronously in ios I want to read a local file stored in the Documents directory asynchronously. My code is given below:
-(NSString *)getLogFilePath
{
    NSString *logFileNameString = logFile;
    return  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:logFileNameString];
}

 -(NSString *)readStringFromFile
  {
  NSString *fileAtPath =  [self getLogFilePath];
  return [[NSString alloc] initWithData:[NSDataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
  }

Someone please help me in this regard.
Thanks in advance.

A: Use Grand Central Dispatch and Block syntax to do this,
+(void) readStringFromFileWithCompletion:(void (^)(BOOL success,NSString *output))completionBlock{

dispatch_queue_t myQueue = dispatch_queue_create("FileReadingQueue",NULL);
dispatch_async(myQueue, ^{
    // Perform long running process
    NSString *fileAtPath =  [self getLogFilePath];
    NSString *output = [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];

    completionBlock(true,output);

});

}
Use your method,
[self readStringFromFileWithCompletion:^(BOOL success, NSString *output) {
    // use 'output' here, to get the string read from file
}];


text:
Q: Keep Group on One Page using Reporting Services I created a report as part of a C# application using Reporting Services and I cant find some functionality I am used to seeing in other environments.  I believe both MS Access and Crystal reports have an option called "Keep Together" so that you can keep a specific grouping of data on one page instead of the information being split over two pages.
How do I do that using 2005 Reporting Services when my report is rendered locally in a C# app and viewed using the .net report viewer.  Essentially, I want to keep all records for a certain year on one page.  I am using Visual Studio 2008.
The year is one of the columns and the number of rows for one year is always smaller than a page.  My report uses just one table and has an innermost grouping by year and then another outer grouping by client name.
Currently I can fit two years of data on the report, however, if the data starts half way through the first year, then I get the following:
Example:
Page one:
1/2 of 2004 because the data started half way through 04
All of 2005
First half of 2006
Page2:
Second Half of 2006
What I would rather do is push all of 2006 to page two.
I am currently using a table for all of the data in the report.  There is a keep together option at the Table level, but I need one at the Group level.  In this case the Grouping by year.
Any help that can be provided will be much appreciated.

A: Please click on a group which you want to keep together in same page under Row Group section. After clicking on the desired group make "Keep Together option as True" in properties section. That's it. It worked for me.

A: Just to add a bit to John's answer. For SSRS 2005 the List and Table objects do have a KeepTogether property, which means they will try to keep everything on one page. I think the best approach is to follow John's advice first though.

A: Ok, what you need to do is to first define the reports page size to be large enough to encompass your entire data region.
See:
http://msdn.microsoft.com/en-us/library/bb677374.aspx
You then need to add Page Break Points to the Group in your Matrix. See below:
http://msdn.microsoft.com/en-us/library/ms156434.aspx

A: *

*Insert a "List" into the report.

*Under its "Tablix Properties" set the "Dataset Name" property to your dataset name.

*From the design view right-click on the list and then select "Row Group > Group Properties".

*On the "Group Properties" window, click "Add" button under "Group Expressions" then choose the field that you want to group within a page.

*After that you can insert a "Table" for your detail data inside the row group.

*Once you render the report the report will keep data inside the group together between page breaks.

A: Use the Rectangle element and copy and paste all the controls into it. On tke rectangle properties check the box for keeping contents together. Don't include a border if you don't want extra lines.
I had a number of items outside of the matrix element that I need for a footer. I only wanted them
on the last page, so I couldn't use the standard footer section. By putting them in rectangle I avoid page breaks in the middle of the group.

A: The problem was that I needed two years on a page and never 1/2 year even if the specific set of records started half way through the year.  It turns out that even though there is a "Keep Together" option at the table level, there is not one at the group level.  I needed this option at a group level.  Instead of using a format solution I altered the underlying SQL for the report.  In cases where there was only 1/2 year of data I created records for the other part of the year with correct dates, but zeros for all other values.  This means that if the page is formatted properly to hold two years then it will always show two complete years and one year will never be broken over two pages.  I also thought the answers provided by Mozy and John Sansom were good and I voted them both up.
Thanks for the help!


text:
Q: A doubt in a theorem about group extensions I am reading this chapter.
Part 1 in theorem 1.2 tells us that
Let $E : 1 \to A \xrightarrow{i} X \xrightarrow{f}  G \to 1$ be an extension of $A$ by $G$ let $t : G \to X$ be a section of $f$ i.e. $t(1) = 1$ and $f \circ t = 1_G$.
The formula ${^x a} = t(x)at(x)^{-1}$ determines an action of $G$ on $A$, which depends only on the equivalence class of $E$.
I am able to prove that the given formula gives an action. Now I want to prove that it only depends on the equivalence class of $E$.
If $E' : 1 \to A \xrightarrow{i} Y \xrightarrow{g}  G \to 1$ is another extension that is equivalent to $E$, then without loss of generality, we may take $X=Y$ and $f=g$.
Suppose $s$ is another section of $f$, and $ x * a $ denotes the corresponding action. I defined $\phi : A \to A$ given by $a \mapsto t(x) s(x)^{-1} a s(x) t(x)^{-1}$. It is easy to see that $\phi(x*a) = {^xa}$. Also, I verified that $\phi$ is injective and surjective as follows:
$$\phi(a) = \phi(b) \implies t(x) s(x)^{-1} a s(x) t(x)^{-1}=t(x) s(x)^{-1} b s(x) t(x)^{-1} \implies a = b.$$
Given $b \in A$ we see that $\phi(t^{-1}(x) s(x) b s^{-1}(x) t(x)) = b$.
So $\phi$ is bijective and preserves group actions.
My doubt is that I have not used the fact that $s$ and $t$ are sections. Where I am missing?
Note : The same question is asked here.


text:
Q: Excel SUMPRODUCT with table I am trying to perform a sumproduct with table references and when im trying to add a extra condition it will no longer work. Below are the two examples there must be something simple I am missing the @Type field is just matching text, if anyone could please guide me with the correct syntax to use, when I recreated without the table references in a new workbook it worked fine.
Formula that works
Excel Formula:
=SUMPRODUCT(--([@Key]=RecFY!AK:AK),--([@[Appointment_Date]]=RecFY!Y:Y),RecFY!AD:AD)

Formula that errors as #N/A have checked there should be a result
Excel Formula:
=SUMPRODUCT(--([@Key]=RecFY!AK:AK),--([@[Appointment_Date]]=RecFY!Y:Y),--([@Type]=RecFY!V:V),RecFY!AD:AD)


text:
Q: How to find the sum of the given series: $\sum_{k=0}^{\min(n ,m)} \binom{n}{k} \binom{m}{k}$?  I wonder whether it is possible to calculate the following sum that involves the Binomial coefficients
$\sum_{k=0}^{\min(n ,m)} \binom{n}{k} \binom{m}{k}$ .

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\sum_{k=0}^{\min\braces{n,m}}{n \choose k}{m \choose k} & =
\sum_{k=0}^{\infty}{n \choose k}{m \choose m - k} \\[5mm] & =
\sum_{k=0}^{\infty}{n \choose k}
\bracks{z^{m - k}}\pars{1 + z}^{m}
\\[5mm] & =
\bracks{z^{m}}\pars{1 + z}^{m}
\sum_{k=0}^{\infty}{n \choose k}z^{k}
\\[5mm] & =
\bracks{z^{m}}\pars{1 + z}^{m + n} =
\bbx{m + n \choose m}
\end{align}

A: Yes, it is in fact possible to sum this. The answer is
$$\sum_{k=0}^n\binom{n}{k}\binom{m}{k}=\binom{m+n}{n}$$
assuming that $n\leq m$. This comes from the fact that
$$\sum_{k=0}^n\binom{n}{k}\binom{m}{k}=\frac{m+n}{n}\sum_{k=0}^{n-1}\binom{n-1}{k}\binom{m}{k}$$
The way that I solved this problem was using WZ theory to find a recursion for the sums, which is quite algebraically intensive, and I don't know if there is a better way of showing this recursion.


text:
Q: How to find the limit of the following series based on a new operation? Lets define an operation as $$a*b=a+b+ab$$  Now I need to find the following limit $$\lim_{n\to\infty}\frac{1}{1}*\frac{1}{4}*\frac{1}{9}*\frac{1}{16}\cdots*\frac{1}{n^2}$$
Now I observed the series and found that it is nothing but the sum of the magnitude of  coefficients of the equation except for the first term $$\prod_{i=1}^{n}(x-\frac{1}{i^2})$$ Now to get the sum of coefficients I substituted the value of $x$ as $-1$ thus the answer will be  $$\prod_{i=1}^{n}(-1-\frac{1}{i^2})-1$$ After this I could not proceed. My first doubt was that for $n$ odd value will be negative , and secondly I am not able to evaluate this limit.$$\prod_{i=1}^{\infty}(1+\frac{1}{i^2})$$

A: If
$$x_n = \frac{1}{1} * \frac{1}{4} * \frac{1}{9} * \cdots * \frac{1}{n^2}$$
then
$$x_n = x_{n-1} * \frac{1}{n^2} = (1 + x_{n-1})\left(1 + \frac{1}{n^2}\right) - 1,$$
so
\begin{align}1 + x_n &= (1 + x_{n-1})\left(1 + \frac{1}{n^2}\right)\\
& = (1 + x_{n-2})\left(1 + \frac{1}{(n-1)^2}\right)\left(1 + \frac{1}{n^2}\right)\\
&\quad\vdots\\
& = \prod_{j = 1}^n \left(1 + \frac{1}{j^2}\right).\\
\end{align}
Now
$$\prod_{j = 1}^n \left(1 + \frac{1}{j^2}\right) \to \frac{\sinh \pi}{\pi}\quad \text{as}\quad n\to \infty$$
using the product formula

$$\sin \pi z = \pi z \prod_{j = 1}^\infty \left(1 - \frac{z^2}{j^2}\right)$$

and substituting $z = i$.
It follows that
$$\lim_{n\to \infty} x_n = \frac{\sinh \pi}{\pi} - 1.$$

A: About the product, note that holds $$\sinh\left(x\right)=x\prod_{k\geq1}\left(1+\frac{x^{2}}{k^{2}\pi^{2}}\right)$$
 so$$\prod_{k\geq1}\left(1+\frac{1}{k^{2}}\right)=\frac{\sinh\left(\pi\right)}{\pi}.$$


text:
Q: Yarn Workspaces And Webpack Hot Module Reloading React App I am using Yarn Workspaces to manage a mono repo. I am using webpack 4 for hot module reloading. In my mono repo I have an app, a UI component library, and another component library for authorizing users (auth package). I am using the component library in both the app and the auth package. Everything local to the app hot reloads fine, but the UI component library will not hot reload - it requires a full refresh.
I've tried accepting the UI component library using module.hot.accept(...), but doesn't seem to pick it up.
Guessing this question is a stretch, but any ideas?

A: Add --hot in your package.json dev build script.
It works for webpack 4.


text:
Q: Index based dot product with numpy I am trying to optimize a transformation problem and let numpy do as much heavy-lifting as possible.
In my case I have a range of coordinate sets that each have to be dotted with corresponding indexed roll/pitch/yaw values.
Programatically it looks like this:
In [1]: import numpy as np
   ...: from ds.tools.math import rotation_array
   ...: from math import pi
   ...:
   ...: rpy1 = rotation_array(pi, 0.001232, 1.234243)
   ...: rpy2 = rotation_array(pi/1, 1.325, 0.5674543)
In [2]: rpy1
Out[2]:
array([[ 3.30235500e-01,  9.43897768e-01, -1.23199969e-03],
       [ 9.43898485e-01, -3.30235750e-01,  1.22464587e-16],
       [-4.06850342e-04, -1.16288264e-03, -9.99999241e-01]])

In [3]: rpy2
Out[3]:
array([[ 2.05192356e-01,  1.30786082e-01, -9.69943863e-01],
       [ 5.37487075e-01, -8.43271987e-01,  2.97991829e-17],
       [-8.17926489e-01, -5.21332290e-01, -2.43328794e-01]])
   ...:
   ...: a1 = np.array([[-9.64996132, -5.42488639, -3.08443],
   ...:                [-8.08814188, -4.56431952, -3.01381]])
   ...:
   ...: a2 = np.array([[-6.91346292, -3.91137259, -2.82621],
   ...:                [-4.34534536, -2.34535546, -4.87692]])

Then I dot the coordinates in a1 with rpy1 and a2 with rpy2
In [4]: a1.dot(rpy1)
Out[4]:
array([[-8.30604694, -7.31349869,  3.09631641],
       [-6.97801968, -6.12357288,  3.0237723 ]])

In [5]: a2.dot(rpy2)
Out[5]:
array([[-1.20926993,  3.86756074,  7.3933692 ],
       [ 1.83673215,  3.95195774,  5.40143613]])

Instead of iterating over lists of a's and rpy's I want to do the whole thing in one operation. So I was hoping for that effect with the following code, so that each set of coordinates in a12 would be dotted with the corresponding indexed array from rpy_a.
But as it is clear, from the output I an getting more than I was hoping for:
In [6]: rpy_a = np.array([rpy1, rpy2])
   ...:
   ...: a12 = np.array([a1, a2])

In [7]: a12.dot(rpy_a)
Out[7]:
array([[[[-8.30604694, -7.31349869,  3.09631641],
         [-2.37306761,  4.92058705, 10.1104514 ]],

        [[-6.97801968, -6.12357288,  3.0237723 ],
         [-1.6478126 ,  4.36234287,  8.57839034]]],

       [[[-5.9738597 , -5.23064061,  2.83472524],
         [-1.20926993,  3.86756074,  7.3933692 ]],

        [[-3.64678058, -3.32137028,  4.88226976],
         [ 1.83673215,  3.95195774,  5.40143613]]]])

What I need is:
array([[[-8.30604694, -7.31349869,  3.09631641],
        [-6.97801968, -6.12357288,  3.0237723 ]],

       [[-1.20926993,  3.86756074,  7.3933692 ],
        [ 1.83673215,  3.95195774,  5.40143613]]])

Can anyone tell me how to achieve this?
EDIT:
Runnable example:
import numpy as np

rpy1 = np.array([[ 3.30235500e-01,  9.43897768e-01, -1.23199969e-03],
                 [ 9.43898485e-01, -3.30235750e-01,  1.22464587e-16],
                 [-4.06850342e-04, -1.16288264e-03, -9.99999241e-01]])

rpy2 = np.array([[ 2.05192356e-01,  1.30786082e-01, -9.69943863e-01],
                 [ 5.37487075e-01, -8.43271987e-01,  2.97991829e-17],
                 [-8.17926489e-01, -5.21332290e-01, -2.43328794e-01]])

a1 = np.array([[-9.64996132, -5.42488639, -3.08443],
               [-8.08814188, -4.56431952, -3.01381]])

a2 = np.array([[-6.91346292, -3.91137259, -2.82621],
               [-4.34534536, -2.34535546, -4.87692]])

print(a1.dot(rpy1))
# array([[-8.30604694, -7.31349869,  3.09631641],
#        [-6.97801968, -6.12357288,  3.0237723 ]])
print(a2.dot(rpy2))
# array([[-1.20926993,  3.86756074,  7.3933692 ],
#        [ 1.83673215,  3.95195774,  5.40143613]])

rpy_a = np.array([rpy1, rpy2])
a12 = np.array([a1, a2])

print(a12.dot(rpy_a))
# Result:
# array([[[[-8.30604694, -7.31349869,  3.09631641],
#          [-2.37306761,  4.92058705, 10.1104514 ]],
#         [[-6.97801968, -6.12357288,  3.0237723 ],
#          [-1.6478126 ,  4.36234287,  8.57839034]]],
#        [[[-5.9738597 , -5.23064061,  2.83472524],
#          [-1.20926993,  3.86756074,  7.3933692 ]],
#         [[-3.64678058, -3.32137028,  4.88226976],
#          [ 1.83673215,  3.95195774,  5.40143613]]]])

# Need:
# array([[[-8.30604694, -7.31349869,  3.09631641],
#         [-6.97801968, -6.12357288,  3.0237723 ]],
#        [[-1.20926993,  3.86756074,  7.3933692 ],
#         [ 1.83673215,  3.95195774,  5.40143613]]])

A: Assuming you want to treat an arbitrary number of arrays rpy1, rpy2, ..., rpyn and  a1, a2, ..., an, I suggest explicit first axis concatenation with explicit broadcasting, simply for the cause of "explicit is better than implicit":
a12 = np.concatenate([_a[None, ...] for _a in (a1, a2)], axis=0)
rpy_a = np.concatenate([_a[None, ...] for _a in (rpy1, rpy2)], axis=0)

This is equal to:
a12 = np.array([a1, a2])
rpy_a = np.array([rpy1, rpy2])

np.array requires less code and is also faster than my explicit approach, but I just like defining the axis explicitly so that everyone reading the code can guess the resulting shape without executing it.
Whatever path you choose, the important part is the following:
np.einsum('jnk,jkm->jnm', a12, rpy_a)
# Out:
array([[[-8.30604694, -7.3134987 ,  3.09631641],
        [-6.97801969, -6.12357288,  3.0237723 ]],

       [[-1.20926993,  3.86756074,  7.3933692 ],
        [ 1.83673215,  3.95195774,  5.40143613]]])

Using the Einstein summation convention, you can define your np.matmul (equal to np.dot for 2D-arrays) to be executed along a specific axis.
In this case, we define the concatenation axis j (or first dim. or axis 0) to be the shared axis, along which the operation 'nk,km->nm' (equal to np.matmul, see the signature description in the out parameter) is performed.
It is also possible to simply use np.matmul (or the python operator @) for the same results:
np.matmul(a12, rpy_a)
a12 @ rpy_a

But again: For the general case, where the concatenation axis or shapes may change, the more explicit np.einsum is preferable. If you know that no changes will be made to shapes etc., np.matmul should be preferred (less code and faster).


text:
Q: How to loop through matrix and count zero-term values? sample collection =
[['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'],
['apple', 1, 1, 1, 1],
['banana', 1, 1, 0, 0],
['lemon', 1, 0, 2, 1]]

In preperation of an tf-idf calculation, I would like to collect every row's amount of 'hits' aka, the amount of times there is not a zero.
I have tried the following but I am stuck:
def n_calc(frequency_matrix):
    non_zero_term_frequencies = []
    for list_ in sample_collection:
        for value in list_:
            if value != 0.0:
                non_zero_term_frequencies += 1
            else:
                pass

idf_calc(sample_collection)

desired output:
non_zero_term_frequencies: [4, 2, 3]

A: Use list comprehension, this should work:
counts = [
    sum(1 if value else 0 for value in line[1:]) for line in collection[1:]
]

print(counts)
>>> [4, 2, 3]

A: This can be achieved like this:
non_zero_term_frequencies = []
for list_ in frequency_matrix[1:]:
    non_zero = len(list_[1:]) \
               - len([x for x in list_ if x == 0])
    non_zero_term_frequencies.append(non_zero)


text: Q: success rate/probability distribution and uncertainty Apologies if this is a question, which is too basic. Despite many google searches, I could not find an answer. Let us say I have a biased coin and success is defined as head. Is there a way to determine the standard error/confidence interval (e.g. +/- 1.96 * se/standard deviation?) around the observed success rate, depending on the number of observations? So if the coin was tossed only 3 times, the confidence interval would be larger than if I tossed it 100 times. I would think this is somewhat related to the binomial distribution but I am interested in the success rate rather than number of successes. I am familiar with bootstrapping, so resampling from the observations may also be an option? Thanks.


text:
Q: Multiple match between boundaries I am trying to do a multiple match within a string but I just need to find the matches between some boundaries.
EX: Let's say I have the following string and flags inside the string. I just need to find the '123.12' that are between the HELLO and BYE flags.
Lorem Ipsum is *123.12* dummy text of the printing and *123.12* industry. *123.12* Ipsum has been the industry's *123.12* dummy text ever *123.12* the 1500s, when an unknown *123.12* took a galley of *123.12* and scrambled it to *123.12* a type specimen *123.12*. HELLO *123.12* has survived not only *123.12* centuries, *123.12* also the leap into *123.12* typesetting, remaining *123.12* unchanged. BYE It was *123.12* in *123.12* 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software *123.12* Aldus PageMaker *123.12* versions of *123.12* Ipsum.

Right now I'm doing a match with all the substrings that have the characteristics I need but it is matching outside the range I need.
PS: The engine is python and no libraries can be added.

A: string = """Lorem Ipsum is *123.12* dummy text of the printing and *123.12* industry. *123.12* Ipsum has been the industry's *123.12* dummy text ever *123.12* the 1500s, when an unknown *123.12* took a galley of *123.12* and scrambled it to *123.12* a type specimen *123.12*. HELLO *123.12* has survived not only *123.12* centuries, *123.12* also the leap into *123.12* typesetting, remaining *123.12* unchanged. BYE It was *123.12* in *123.12* 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software *123.12* Aldus PageMaker *123.12* versions of *123.12* Ipsum."""

startFlag = 'HELLO'
endFlag = 'BYE'

lookingFor = '*123.12*'

EndOfStartFlagIndex = string.index(startFlag) + len(startFlag)

betweenFlags = string.split(startFlag)[1].split(endFlag)[0]

lookingForInices = [i+EndOfStartFlagIndex for i in range(0,len(betweenFlags)) if betweenFlags[i:i+len(lookingFor)] == lookingFor]

print(lookingForInices)


text:
Q: Let $G$ be a group of order 35. Show that $G \cong Z_{35}$ Let $G$ be a group of order 35. Show that $G \cong Z_{35}$
Now, I am going to assume that this is a LaGrange based question. Also, I know that in order to be isomorphic, it must be one to one and onto.

A: $\#G = 5.7$ Let ${S}_{5}$ denote the Sylow 5-subgroup and ${S}_{7}$ the Sylow 7-subgroup.
Now $${S}_{5} \cap {S}_{7}$$ is a subgroup and the number of elements in it divides 5 and 7 (Lagrange). So $$ \#{S}_{5} \cap {S}_{7} = 1$$
Then $$ \#{S}_{5}{S}_{7} = \frac{\#{S}_{5}.\#{S}_{7}}{ \#{S}_{5} \cap {S}_{7}}=5.7=35$$
Because ${S}_{5}{S}_{7} \subset G$ and $\#{S}_{5}{S}_{7} = \#G$ it follows that: $$G = {S}_{5}{S}_{7}$$ By Sylow's second theorem (because 5 and 7 are primes):  ${S}_{5}$ is the only Sylow 5-subgroup of $G$. The same for ${S}_{7}$. So $${S}_{5},{S}_{7} \triangleleft G$$
This are all the requirements that needed to be true for a group to be isomorphic with the direct product: ${S}_{5} \times {S}_{7}$. Since ${S}_{5}$ and ${S}_{5}$ are cyclic (number of elements is prime) it follows that ${S}_{5} \cong \mathbb{Z}_{5}$. Same for ${S}_{7}$. So ${S}_{7} \cong \mathbb{Z}_{7}$. Because 5 and 7 have no common divisors other than 1 it follows: $$\mathbb{Z}_{5} \times \mathbb{Z}_{7} \cong \mathbb{Z}_{35}$$ And so $$G \cong {S}_{5} \times {S}_{7} \cong \mathbb{Z}_{35}$$


text:
Q: Texto como formato archivo buen día.
Estoy trabajando en un chat interno en un sistema. Y le meti un input donde se pudiera agregar archivos para enviar. pero cuando selecciono el archivo y envió el mensaje con el archivo, me lo muestra como texto y no como archivo.
Y quiero poder que cuando se abra el chat, se pongan el archivo para descargarlo o verlo.
así me lo muestra:

Y para mostrar los mensajes uso una funcion con ajax y jquery, donde le paso el id, del chat que quiero.
function Seguimientos(id) {

    document.getElementById("mensajes").innerHTML = "";

    const format1 = "DD/MM/YYYY hh:mm:ss a"

    console.log('seguimientos');
    showSpinner();

    var URL = '/SolicitudSeguimientos/SeguimientosPorSolicitudId' + '/' + id;
    console.log('url ' + URL);
    var card = "";
    $.getJSON({
        url: URL,
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            //var d = (JSON.parse(data));
            console.log(data);

            $.each(data.seguimientos, function (i, o) {
                //@*if (o.Correo == '@(User.Identity.Name.Substring(User.Identity.Name.IndexOf("#") + 1))') {*@

                    card += "
";
                    card += "
";
                    card += ""

                    if (o.AgenteId != 0) {
                        card += o.Agente.Nombre;
                    }
                    else {
                        card += o.Contacto.Nombre;
                        //console.log('ContactoId: ' + o.ContactoId);
                        //console.log('Contacto: ' + o.Contacto.Nombre);
                    }
                    card += "";
                    card += "" + moment(o.Fecha).format(format1) + "";
                    card += "
";
                    if (o.Mensaje == null) {
                        card += "

";
                    }
                    else {
                        card += "
" + o.Mensaje.replaceAll("\n", "
") +
                        "
";
                    }

                    if (o.Mensaje != null || o.Archivos != undefined) {
                        card += "
" + o.Archivos + "
";
                    }
                    card += "
";

                });
                var parser = new DOMParser;
                var dom = parser.parseFromString(card, 'text/html');

                if (card.length > 0) {
                    document.getElementById("mensajes").innerHTML = card;
                }
                else{
                    document.getElementById("mensajes").innerHTML = "
No hay seguimientos
";
                }

            },

                error: function (data) {
                    console.log('error');
                    hideSpinner();
                }
        })
}


text:
Q: How do I calculate the distribution of number of events in the busiest period? I've got an estimate of the number of site visitors I'll see in a 1 hour period clicking email links in a large email campaign.  I need to make sure I've got the required server capacity.  That means I need to estimate the peaks in usage on a smaller time scale.

*

*How do I calculate the expected distribution for the number of visitors I should expect in any given smaller time period?  eg for a given 1 minute period.

*How do I calculate the expected distribution for number of visitors in the busiest time period of a given length?
I figure it's good enough for estimation purposes to assume that each visitor arrives at a random time that's evenly distributed within the one hour period.
--
EDIT: (in response to rocinante) OK, so lets consider the problem redefined in terms of the assumptions of the poisson distribution.  There's some minor differences, but they don't matter to me.  Also, lets not worry about possible notions like sliding windows of time for the period in 2.  So long as the period in 2. is short, that doesn't matter either.
Supposing I expect visitors to arrive at a rate of 10K visitors per hour over a one hour period.  If I divide that hour up into 720 adjacent 5 second intervals, I expect the number of visitors in each of those 5 second periods to follow a poisson distribution.
Part 2 of my question can then be restated: I can take 720 samples from a poisson distribution, and find the largest value of those 720 sample values.  If I repeatedly took sets of samples like that, calculating the maximum value in each set, what would the distribution of those maximums be like?
Having graphed some poisson distributions, I'm comfortable that I know enough about what to expect for planning purposes, but I'd still like to how to do part 2 of my problem as posed.
Also, for large lambda, I presume some other calculation of the distribution should be used?  Calculating factorials becomes impractical at some point.

A: You can't calculate the expected distribution. You can calculate the expected number of visitors from a distribution.
The distributions typically used for this type of problem is usually Poisson or Geometric. To obtain the parameter you're looking for, you need to look at past data from previous campaigns. If you don't have any because it's the first time you're doing this, then check the traffic for comparable campaigns. Google Trends provides charts on how quickly hot trends pick up and die down.


text:
Q: How to recalculate all-pairs shorthest paths on-line if nodes are getting removed? Latest news about underground bombing made me curious about the following problem.  Assume we have a weighted undirected graph, nodes of which are sometimes removed.  The problem is to re-calculate shortest paths between all pairs of nodes fast after such removals.
With a simple modification of Floyd-Warshall algorithm we can calculate shortest paths between all pairs.  These paths may be stored in a table, where shortest[i][j] contains the index of the next node on the shortest path between i and j (or NULL value if there's no path).  The algorithm requires O(n³) time to build the table, and eacho query shortest(i,j) takes O(1).  Unfortunately, we should re-run this algorithm after each removal.
The other alternative is to run graph search on each query.  This way each removal takes zero time to update an auxiliary structure (because there's none), but each query takes O(E) time.
What algorithm can be used to "balance" the query and update time for all-pairs shortest-paths problem when nodes of the graph are being removed?

A: As mentioned by goran, you only have to recalculate those shortest paths which contained a node that was removed in the meanwhile. So, I'd do the following:

*

*Calculate all the shortest paths using the Floyd-Warshall algorithm. This is O(n3).

*Create an index which assigns vertex indices to the list of shortest paths that vertex participates in. (In other words, for every vertex i, it gives you a list of (j, k) pairs s.t. i is present in the shortest path between vertex j and k). This is O(n2d) (where d is the graph diameter) since you have to loop over each vertex in each of the shortest path determined in the previous step, and there are n2 such shortest paths.

*After a vertex removal, look up the list of the affected shortest paths from the index created in step 2 and recalculate them. Since you don't need all the shortest paths here and I assume that only a few nodes are affected, you are probably better off with multiple breadth first searches, which is O(m + n) where m is the number of edges.

A: I'll answer the implied non-generic variant of the problem, where the graph is a road network. This seems to me one of the cases where theoretical bounds on arbitrary graphs are less interesting.
Some of the best approaches for shortest path finding are highway-node routing and transit-node routing. (described in a dissertation by Dominik Schultes). The acceleration structure  can be built reasonably fast (~15 min. for the HNR of the whole Europe) and it supports incremental updates. What's interesting is that query times for random queries is around 1ms, and all-pairs distance tables can be calculated for as low as 0.2us per entry. What's even more interesting is the query performance scaling, data suggests that the scaling is sub-logarithmic/near-constant in graph size. Transit node routing is even faster at 4.3us random queries. Alas I don't have any information on the updatability of the datastructure. Intuitively it shouldn't be too hard to incrementally update.
The same or similar approaches could be used on other graphs that are similar to road networks (sparse, planar, hierarchical).

A: Well I don't think that you need to rerun the whole build if a node is removed. Only for those paths which had a node in them.
Trivial solution to your problem would be to add information about redundant paths, for example you could have a second shortest path for each of the nodes on the shortest path.
This does not reduce the computation time, but caches it (it also increase storage requirements by a factor of n, where n is average number of nodes, for a single node removal, by factor of n*(n-1) for 2 node redundancy... and by factor of n! for complete redundancy and also increases initial build time by the same factor and also increases the time needed to add nodes)
If there is a way to improve this and reduce the rebuild time then you need to find a structure that would allow a quick computation of the shortest distance but that should be immutable (or cheap to recalculate) when nodes are removed or added to a graph.

A: Quick concept of Floyd-Warshall Algorithm!
The first loop in the algorithm is a new node which is introduced in addition to the existing nodes. We will run the algorithm to relax all the existing node distances with the new introduced node.
In this problem we will reverse the order of removal of the nodes and hence the removed nodes will act as an adding node.
-- given the deleted array del[n];
-- we will traverse from the end of deleted array.

*

*for(int k=n; k>=1; k--)

*for(int i=1; i<=n; i++)

*for(int j=1; j<=n; j++)

*graph[i][j] = min(graph[i][j],graph[i][del[k]] + graph[del[k]][j]);

-- Now traverse through the all k to n nodes and find the required all pair distances in each iteration and store it in a vector.
-- finally, reverse the vector to get the required all pair distances.
So running time of the algorithm is as the same as Floyd Warshall algorithm, i.e. O(n3).


text:
Q: what else is in $\prod_{j=1}^n(1+q^j)$? From time to time, I run into the finite product $\prod_{j=1}^n(1+q^j)$. And, the more it happens, the more fascinated I've become. So, herein, I wish to get help in collecting such results. To give some perspective into what I look for, check out the below examples. First, some nomenclature: $(q)_k=(1-q)(1-q^2)\cdots(1-q^k)$ and $\binom{n}k_q=\frac{(q)_n}{(q)_k(q)_{n-k}}$.
(0) It's almost silly, but the sum of elementary functions of the specialization $\pmb{q}=(q,q^2,\dots,q^n)$:
$$e_0(\pmb{q})+e_1(\pmb{q})+\cdots+e_n(\pmb{q})=\prod_{j=1}^n(1+q^j).$$
(1) The classical $q$-binomial theorem, which results from counting restricted distinct partitions or number of weighted tilings:
$$\sum_{k=0}^nq^{\binom{k+1}2}\binom{n}k_q=\prod_{j=1}^n(1+q^j).$$
(2) I can't remember where I saw this (do you?) but
$$\sum_{k=0}^nq^k\binom{n}k_{q^2}=\prod_{j=1}^n(1+q^j).$$
(3) The $H$-polynomial of a symplectic monoid $MSp_n$ (see this paper, page 13):
$$\sum_{k=0}^n(-1)^kq^{k^2}\binom{n}k_{q^2}^2\prod_{i=1}^k(1-q^{2i})\prod_{j=1}^{n-k}(1+q^j)^2=\prod_{j=1}^{2n}(1+q^j),$$
although the authors did not seem to be aware of the RHS.

QUESTION. Can you provide such formulas (in any field) with the same RHS (always a finite product) as in above, together with resources or references?

Thank you.

A: In a $2n$ dimensional vector space equipped with a symplectic form, you can look at all the Lagrangian subspaces, and this forms a subvariety of the Grassmannian $G(n,2n)$ called the Lagrangian Grassmannian, $\Lambda(n)$. It is a smooth projective variety which inherits a schubert cell decomposition from the Grassmannian, and lots of other Schubert calculus goodness. It's cells are indexed by strict partitions with largest part at most $n$. The number of points of $\Lambda(n)$ over finite fields is given by $\prod_{i=1}^n(1+q^i)$, so unimodality of the coefficients can be obtained from the Hard Lefschetz theorem. (Not like this is a simpler way of looking at it, but perhaps a geometric point of view can be useful for certain applications, for example the classical q-binomial theorem follows from a certain stratification of $\Lambda(n)$.)
A reference for an explicit presentation of the cohomology ring using Schur Q-polynomials can be found in "Algebro—Geometric applications of Schur S- and Q-polynomials" by Piotr Pragacz, Topics in Invariant Theory ,M. P. Malliavin Ed., Springer Lecture Notes in Math., 1478, 1991.

A: Up to scaling, $\prod_{j=1}^n(1+q^j)$ is the character of the principal specialization of
the spinor representation of $\mathfrak{so}(2n+1)$. This was first
explicitly stated by J. W. B. Hughes, Lie algebraic proofs of some theorems on partitions, in Number Theory and
Algebra, Academic Press, 1977, pp. 135--155.

A: Let $exp(z,q)=\sum_{k=0}^{\infty}z^k/[k]_q!$ be the usual  $q-$analogue of the exponential function $e^x.$
The identity
$\sum_{k=0}^n{q^k}{\binom{n}{k}_{q^2}}=\prod_{j=1}^n(1+q^j)$
can be obtained by comparing coefficients in
$$exp(\frac{z}{1+q},q^2)exp(\frac{qz}{1+q},q^2)=exp(z,q),$$
which is a natural $q-$analogue of $e^\frac{x}{2} e^\frac{x}{2}=e^x.$
This identity occurs in Séminaire Lotharingien de Combinatoire, B05a (1981), but is perhaps older.


text:
Q: How to update existing array in JavaScript? I have function update tag, user can remove or add new tag.

this is the output of the temp
tag_temp = [{
    db_id: 5,
    id: 1,
    name: 'Add Product'
  },
  {
    db_id: 6,
    id: 2,
    name: 'New'
  }, {
    db_id: 7,
    id: 3,
    name: 'Test'
  }
];

this is how I do it to achieve the above output.
  if(e.tag.length > 0){
     e.tag.map((e) => {
       tag_temp.push({
         "db_id" : e.db_id,
          'id'   : e.tag_id ,
          'name' : e.tag_name,
      });
   });
  console.log(tag_temp);
}

And now I want to perform update function, I have to compare the existing tag and push it into the finalized temp to fulfill my API Request.
I have this in my Postman API Request
"assign_tag":[
    {
        "db_id": 1,
        "tag_id": 3,
        "status": false
    },
    {
        "db_id": null,
        "tag_id": 3,
        "status": true
    }],

this is what I have tried on the update button
But I got error with

Uncaught ReferenceError: e is not defined at the line === e.db_id)[0].db_id;

finalized_temp = [];
        tag_temp = tag_temp.filter(function (el){
            if (el != null){

                let db_id = tag_temp.filter((el) => el.id  === e.db_id)[0].db_id;
                let tag_id = tag_temp.filter((el) => el.id === e.tag_id)[0].tag_id;
                let status = true;

                finalized_temp.push({
                    "db_id" : db_id,
                    "tag_id" : tag_id,
                    "status" : status

                })
            }

        });

I have to send data like this if I want to perform the update function how do I fix this problem ?
Example on how the concept is.

//tag_temp is current fetching of select option before updating into the new final_temp.
let tag_temp = [{
    db_id: 5,
    id: 1,
    name: 'Add Product'
  },
  {
    db_id: 6,
    id: 2,
    name: 'New'
  }, {
    db_id: 7,
    id: 3,
    name: 'Test'
  }
];

$(document).ready(function() {
  updateTag();
});

const updateTag = () => {
let finalized_temp =[]
  let status = false;

  //if db_id is null meaning status is set to true.

  finalized_temp = [{
      db_id: 5,
      tag_id: 1,
      status: 'false',
    },
    {
      db_id: null,
      tag_id: 4,
      status: 'true',
    }
  ];

  console.log(finalized_temp);

}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />

Previous selected Tag :
<select class="selectpicker" multiple data-live-search="true" id="mytitle">
  <option value="1" selected>Add Product</option>
  <option value="2" selected>New</option>
  <option value="3" selected>Test </option>
  <option value="4">Others</option>
</select>

New Selected Tag :
<select class="selectpicker" multiple data-live-search="true" id="mytitle">
  <option value="1" selected>Add Product</option>
  <option value="2">New</option>
  <option value="3">Test</option>
  <option value="4" selected>Others</option>
</select>

the logic for this is
// db_id null is because new data is inserted to the array so the status need to be changed into 'true' otherwise it will be set to 'false'
if(db_id == '' || db_id == null)
 status = true

my expected output data will be like this
finalized_temp = [{
          db_id: 5,
          tag_id: 1,
          status: 'false',
        },
        {
          db_id: null,
          tag_id: 3,
          status: 'true',
        }
      ];


text:
Q: SQL Server - Grouping Combination of possibilities by fixed value
I have to create cheapest basket which inculde fixed items.
For example for a basket which have (5) items
1 and 4 = (1 * 50) + (1 * 100) = 150
2 and 3 = (1 * 60) + (1 * 80)  = 140 -- this is my guy
2 and 2 and 1 = (1 * 60) + (1 * 60) + (1 * 50) = 170
3 and 3 = (1 * 80) + (1 * 80)  = 160  **** this 6 items but total item can exceed min items. The important thing is total cost...
....
Also this is valid for any number of items a basket may have. Also there are lots of stores and each stores have different package may include several items.
How can handle this issue with SQL?
UPDATE
Here is example data generation code. Recursive CTE solutions are more expensive. I should finish the job under 500-600ms over 600-700 stores each time. this is a package search engine. Manual scenario creation by using ´#temp´ tables or ´UNUION´ is 15-20 times cheaper then Recursive CTE.
Also concatenating Item or PackageId is very expensive. I can found required package id or item after selecting cheapest package with join to source table.
I am expecting a megical solution which can be ultra fast and get the correct option.
Only cheapest basket required for each store. Manual scenario creation is very fast but sometimes fail for correct cheapest basket.
                CREATE TABLE #storePackages(
                StoreId int not null,
                PackageId int not null,
                ItemType int not null, -- there are tree item type 0 is normal item, 1 is item has discount 2 is free item
                ItemCount int not null,
                ItemPrice decimal(18,8) not null,
                MaxItemQouta int not null, -- in generaly a package can have between 1 and 6 qouata but in rare can up to 20-25
                MaxFullQouta int not null -- sometimes a package can have additional free or discount item qouta. MaxFullQouta will always greater then MaxItemQouta
            )

            declare @totalStores int
            set @totalStores = (SELECT TOP 1 n = number FROM master..[spt_values] WHERE number BETWEEN 200 AND 400 ORDER BY NEWID())

            declare @storeId int;
            declare @packageId  int;
            declare @maxPackageForStore int;
            declare @itemMinPrice decimal(18,8);
            set @storeId = 1;
            set @packageId = 1

            while(@storeId <= @totalStores)
                BEGIN
                    set @maxPackageForStore = (SELECT TOP 1 n = number FROM master..[spt_values] WHERE number BETWEEN 2 AND 6 ORDER BY NEWID())
                    set @itemMinPrice = (SELECT TOP 1 n = number FROM master..[spt_values] WHERE number BETWEEN 40 AND 100 ORDER BY NEWID())
                        BEGIN
                            INSERT INTO #storePackages
                            SELECT DISTINCT
                             StoreId = @storeId
                            ,PackageId = CAST(@packageId + number AS int)
                            ,ItemType = 0
                            ,ItemCount = number
                            ,ItemPrice = @itemMinPrice + (10 * (SELECT TOP 1 n = number FROM master..[spt_values] WHERE number BETWEEN pkgNo.number AND pkgNo.number + 2  ORDER BY NEWID()))
                            ,MaxItemQouta = @maxPackageForStore
                            ,MaxFullQouta =  @maxPackageForStore + (CASE WHEN number > 1 AND number < 4 THEN 1 ELSE 0 END)
                            FROM master..[spt_values] pkgNo
                            WHERE number BETWEEN 1 AND @maxPackageForStore
                            UNION ALL
                            SELECT DISTINCT
                             StoreId = @storeId
                            ,PackageId = CAST(@packageId + number AS int)
                            ,ItemType = 1
                            ,ItemCount = 1
                            ,ItemPrice = (@itemMinPrice / 2) + (10 * (SELECT TOP 1 n = number FROM master..[spt_values] WHERE number BETWEEN pkgNo.number AND pkgNo.number + 2  ORDER BY NEWID()))
                            ,MaxItemQouta = @maxPackageForStore
                            ,MaxFullQouta =  @maxPackageForStore  + (SELECT TOP 1 n = number FROM master..[spt_values] WHERE number BETWEEN 0 AND 2 ORDER BY NEWID())
                            FROM master..[spt_values] pkgNo
                            WHERE number BETWEEN 2 AND (CASE WHEN @maxPackageForStore > 4 THEN 4 ELSE @maxPackageForStore END)

                        set @packageId = @packageId + @maxPackageForStore;
                        END
                set @storeId =@storeId + 1;
                END

            SELECT * FROM #storePackages
            drop table #storePackages

MY SOLUTION
First of all I am thankful for everyone who try to help me. However all suggested solutions are based on CTE. As I said before recursive CTEs cause performace problems when hunderds of stores are considered. Also multiple packages are requested for one time. This means, I request can include mutiple baskets. One is 5 items other is 3 items and another one is 7 items...
Last Solution
First of all I generates all possible scenarios in a table by item size... By this way, I have option eleminate unwanted scenarios.
CREATE TABLE ItemScenarios(
   Item int,
   ScenarioId int,
   CalculatedItem int  --this will be joined with Store Item
)

Then I generated all possible scenario from 2 item to 25 item and insert to the ItemScenarios table. Scenarios can be genereated one time by using WHILE or recursive CTE. The advantage of this way, scenarios generated only for one time.
Resuls are like below.
Item          |   ScenarioId       |     CalculatedItem
--------------------------------------------------------
2                   1                     2
2                   2                     3
2                   3                     1
2                   3                     1
3                   4                     5
3                   5                     4
3                   6                     3
3                   7                     2
3                   7                     2
3                   8                     2
3                   8                     1
3                   9                     1
3                   9                     1
3                   9                     1
....
.....
......
25                  993                   10

By this way, I can restrict scenario sizes, Max different store, max different package etc.
Also I can eleminate some scenarios which matematically impossible cheapest then other. For example for 4 items request, some scenario
Scenario 1 : 2+2
Scenario 2: 2+1+1
Scenario 3: 1+1+1+1
Among these scenarios; It is impossible Scenario 2 would be cheapest basket. Because,
If Scenario 2 < Scenario 3 --> Scenario 1 would be lower then Scenario 2. Because the thing decreasing cost is 2 item price and **Scenario 1* have double 2 items
Also If Scenario 2 < Scenario 1 --> Scenario 3 would be lower then Scenario 2
Now, If I delete scenarios like Scenario 2 I would gain some performance advantages.
Now I can chose chepest item prices among stores
DECLARE @requestedItems int;
SET @requestedItems = 5;

CREATE TABLE #JoinedPackageItemWithScenarios(
   StoreId int not null,
   PackageId int not null,
   ItemCount int not null,
   ItemPrice decimal(18,8)
   ScenarioId int not null,
)
INSERT INTO #JoinedPackageItemWithScenarios
 SELECT
    SPM.StoreId
   ,SPM.PackageId
   ,SPM.ItemCount
   ,SPM.ItemPrice
   ,SPM.ScenarioId
   FROM (
      SELECT
            SP.StoreId
           ,SP.PackageId
           ,SP.ItemCount
           ,SP.ItemPrice
           ,SC.ScenarioId
           ,RowNumber = ROW_NUMBER() OVER (PARTITION BY SP.StoreId,SC.ScenarioId,SP.ItemCount ORDER BY SP.ItemPrice)
      FROM ItemScenarios SC
      LEFT JOIN StorePackages AS SP ON SP.ItemCount = SC.CalculatedItem
      WHERE SC.Item = @requestedItems
 ) SPM
 WHERE SPM.RowNumber = 1

-- NOW I HAVE CHEAPEST PRICE FOR EACH ITEM, I CAN CREATE BASKET

 CREATE TABLE #selectedScenarios(
   StoreId int not null,
   ScenarioId int not null,
   TotalItem int not null,
   TotalCost decimal(18,8)
)
 INSERT INTO #selectedScenarios
 SELECT
      StoreId
     ,ScenarioId
     ,TotalItem
     ,TotalCost
  FROM (
     SELECT
           StoreId
          ,ScenarioId
          --,PackageIds = dbo.GROUP_CONCAT(CAST(PackageId AS nvarchar(20))) -- CONCATENING PackageId decreasing performance here. We can joing seleceted scenarios with #JoinedPackageItemWithScenarios after selection complated.
          ,TotalItem = SUM(ItemCount)
          ,TotalCost = SUM(ItemPrice)
          ,RowNumber = ROW_NUMBER() OVER (PARTITION BY StoreId ORDER BY SUM(ItemPrice))
        FROM #JoinedPackageItemWithScenarios JPS
        GROUP BY StoreId,ScenarioId
        HAVING(SUM(ItemCount) >= @requestedItems)
     ) SLECTED
     WHERE RowNumber = 1

  -- NOW WE CAN POPULATE PackageIds if needed

  SELECT
      SS.StoreId
     ,SS.ScenarioId
     ,TotalItem = MAX(SS.TotalItem)
     ,TotalCost = MAX(SS.TotalCost)
     ,PackageIds = dbo.GROUP_CONCAT(CAST(JPS.PackageId AS nvarchar(20)))
    FROM #selectedScenarios SS
    JOIN #JoinedPackageItemWithScenarios AS JPS ON JPS.StoreId = SS.StoreId AND JPS.ScenarioId = SS.ScenarioId
    GROUP BY SS.StoreId,SS.ScenarioId

SUM
In my test, this way is mimimum 10 times faster then recursive CTE, especially when number of stores and requested items increased. Also It gets 100% correct results. Because recursive CTE tried milions of unrequired JOINs when number of stores and requested items increased.

A: If you want combinations, you'll need a recursive CTE.  Preventing infinite recursion is a challenge.  Here is one method:
with cte as (
      select cast(packageid as nvarchar(4000)) as packs, item, cost
      from t
      union all
      select concat(cte.packs, ',', t.packageid), cte.item + t.item, cte.cost + t.cost
      from cte join
           t
           on cte.item + t.item < 10  -- some "reasonable" stop condition
     )
select top 1 cte.*
from cte
where cte.item >= 5
order by cost desc;

I'm not 100% sure that SQL Server will accept the join condition, but this should work.

A: Assuming you want to compare all possible permutations of items until the total items in the basket exceeds your total basket number, something like the following would do what you want.
DECLARE @N INT = 1;

DECLARE @myTable TABLE (storeID INT DEFAULT(1), packageID INT IDENTITY(1, 1), item INT, cost INT);
INSERT @myTable (item, cost) VALUES (1, 50), (2, 60), (3, 80), (4, 100), (5, 169), (5, 165), (4, 101), (2, 61);

WITH CTE1 AS (
    SELECT item, cost
    FROM (
        SELECT item, cost, ROW_NUMBER() OVER (PARTITION BY item ORDER BY cost) RN
        FROM @myTable) T
    WHERE RN = 1)
, CTE2 AS (
    SELECT CAST('items'+CAST(C1.item AS VARCHAR(10)) AS VARCHAR(4000)) items, C1.cost totalCost, C1.item totalItems
    FROM CTE1 C1
    UNION ALL
    SELECT CAST(C2.items + ' + items' + CAST(C1.item AS VARCHAR(10)) AS VARCHAR(4000)), C1.cost + C2.totalCost, C1.item + C2.totalItems
    FROM CTE2 C2
    CROSS JOIN CTE1 C1
    WHERE C2.totalItems < @N)
SELECT TOP 1 *
FROM CTE2
WHERE totalItems >= @N
ORDER BY totalCost, totalItems DESC;

Edited to deal with the issue @Matt mentioned.

A: IF OBJECT_ID('tempdb..#TestResults') IS NOT NULL
    BEGIN
        DROP TABLE #TestResults
    END

DECLARE @MinItemCount INT = 5

;WITH cteMaxCostToConsider AS (
    SELECT
       StoreId
       ,CASE
          WHEN (SUM(ItemCount) >= @MinItemCount) AND
          SUM(ItemPrice) < MIN(((@MinItemCount / ItemCount) + IIF((@MinItemCount % ItemCount) > 0, 1,0)) * ItemPrice) THEN SUM(ItemPrice)
          ELSE MIN(((@MinItemCount / ItemCount) + IIF((@MinItemCount % ItemCount) > 0, 1,0)) * ItemPrice)
       END AS MaxCostToConsider
    FROM
       storePackages
    GROUP BY
       StoreId
)

, cteRecursive AS (
    SELECT
      StoreId
      ,'<PackageId>' + CAST(PackageId AS VARCHAR(MAX)) + '</PackageId>' AS PackageIds
      ,ItemCount AS CombinedItemCount
      ,CAST(ItemPrice AS decimal(18,8)) AS CombinedCost
    FROM
       storePackages

    UNION ALL

    SELECT
      r.StoreId
      ,r.PackageIds + '<PackageId>' + CAST(t.PackageId AS VARCHAR(MAX)) + '</PackageId>'
      ,r.CombinedItemCount + t.ItemCount
      ,CAST(r.CombinedCost + t.ItemPrice AS decimal(18,8))
    FROM
       cteRecursive r
       INNER JOIN storePackages t
       ON r.StoreId = t.StoreId
       INNER JOIN cteMaxCostToConsider m
       ON r.StoreId = m.StoreId
      AND r.CombinedCost + t.ItemPrice <= m.MaxCostToConsider
)

, cteCombinedCostRowNum AS (
    SELECT
       StoreId
       ,CAST(PackageIds AS XML) AS PackageIds
       ,CombinedCost
       ,CombinedItemCount
       ,DENSE_RANK() OVER (PARTITION BY StoreId ORDER BY CombinedCost) AS CombinedCostRowNum
       ,ROW_NUMBER() OVER (PARTITION BY StoreId ORDER BY CombinedCost) AS PseudoCartId
    FROM
       cteRecursive
    WHERE
       CombinedItemCount >= @MinItemCount
)

SELECT DISTINCT
    c.StoreId
    ,x.PackageIds
    ,c.CombinedItemCount
    ,c.CombinedCost
INTO #TestResults
FROM
    cteCombinedCostRowNum  c
    CROSS APPLY (
       SELECT( STUFF ( (
          SELECT ',' + PackageId
          FROM
             (SELECT T.N.value('.','VARCHAR(100)') as PackageId FROM c.PackageIds.nodes('PackageId') as T(N)) p
          ORDER BY
             PackageId
          FOR XML PATH(''), TYPE ).value('.','NVARCHAR(MAX)'), 1, 1, '')
    ) as PackageIds
    ) x
WHERE
    CombinedCostRowNum = 1

SELECT *
FROM
    #TestResults

Takes about 1000-2000 MS varies widely depending on combinations that have to be considered within test data (e.g. some times more or less data is generate by your script).
this answer no doubt looks a bit more complicated than Gordon's or ZLKs but it handles Ties, repeated values, 1 package meeting the criteria and a few other things.  The main difference however is really in the last query where I take the XML that was build during the recursive query split it and then re-combined in order so that you can use DISTINCT and get a unique pairing e.g. package 2 + package 3 = 140 & package 3 + package 2 = 140 would be the first 2 results in all of the queries so using the XML to split then recombine allows that to be a single row.  But lets say you also had another row such as (1,5,2,60) that had 2 items and a cost of 60 this query will return that combination too.
You can cherry pick between the answers and use their method to get to the combinations and my methods to get to the final results etc.... But to explain the process of my query.
cteMaxCostToConsider - this is just a way of getting a cost to contain the recursive query to so that less records have to be considered. what it does is determines the cost of all of the packages together or the cost if you bought all of the same package to satisfy the minimum count.
cteRecursive - this is similar to ZLKs answer and a litte like Gordon's but what it does is goes out and continues to add items & item combinations until it reaches MaxCostToConsider.  If I limit to look at item count it could miss a situation where 7 items would be cheaper than 5 so by constraining to the determined Combined Cost it limits the recursion and performs better.
cteCombinedCostRowNum - This simply finds the lowest Combined Cost and at least the minimum item count.
The final query is a bit trickier but the cross apply splits the XML string build in the recursive cte to different rows re-orders those rows and then concatenates them again so that the reverse combination e.g. Package 2 & Package 3 reverse Package 3 & Package 2 becomes the same record and then calls distinct.
This is a bit more flexible than SELECT top N.  To see the difference add the following test cases to your test data 1 at a time:
(StoreId, PackageId, Item, Cost)

*

*(1,5,2,60)

*(1,6,1,1),(1,7,1,1)

*(1,8,50,1)

Edited.  The above will give you every combination of a store that will have the lowest combined cost.  The bug that you noted was due to cteMaxCostToConsider.  I was using SUM(ItemPrice) but sometimes SUM(ItemCount) related to it didn't have enough items in it to allow it to be considered for the MaxCostToConsider. I modified the case statement to correct that issue.
I have also modified to work with your data example your provided.  NOTE you should change your PackageId in that to an IDENTITY column though because I was getting the duplicate PackageIds within a store with the method you used.
Here is a modified version of your script to see what I am talking about:
IF OBJECT_ID('storePackages') IS NOT NULL
    BEGIN
        DROP TABLE storePackages
    END

CREATE TABLE storePackages(
    StoreId int not null,
    PackageId int not null IDENTITY(1,1),
    ItemType int not null, -- there are tree item type 0 is normal item, 1 is item has discount 2 is free item
    ItemCount int not null,
    ItemPrice decimal(18,8) not null,
    MaxItemQouta int not null, -- in generaly a package can have between 1 and 6 qouata but in rare can up to 20-25
    MaxFullQouta int not null -- sometimes a package can have additional free or discount item qouta. MaxFullQouta will always greater then MaxItemQouta
)

declare @totalStores int
set @totalStores = (SELECT TOP 1 n = number FROM master..[spt_values] WHERE number BETWEEN 200 AND 400 ORDER BY NEWID())

declare @storeId int;
declare @packageId  int;
declare @maxPackageForStore int;
declare @itemMinPrice decimal(18,8);
set @storeId = 1;
set @packageId = 1

while(@storeId <= @totalStores)
    BEGIN
        set @maxPackageForStore = (SELECT TOP 1 n = number FROM master..[spt_values] WHERE number BETWEEN 2 AND 6 ORDER BY NEWID())
        set @itemMinPrice = (SELECT TOP 1 n = number FROM master..[spt_values] WHERE number BETWEEN 40 AND 100 ORDER BY NEWID())
            BEGIN
                INSERT INTO storePackages (StoreId, ItemType, ItemCount, ItemPrice, MaxFullQouta, MaxItemQouta)
                SELECT DISTINCT
                    StoreId = @storeId
                --,PackageId = CAST(@packageId + number AS int)
                ,ItemType = 0
                ,ItemCount = number
                ,ItemPrice = @itemMinPrice + (10 * (SELECT TOP 1 n = number FROM master..[spt_values] WHERE number BETWEEN pkgNo.number AND pkgNo.number + 2  ORDER BY NEWID()))
                ,MaxItemQouta = @maxPackageForStore
                ,MaxFullQouta =  @maxPackageForStore + (CASE WHEN number > 1 AND number < 4 THEN 1 ELSE 0 END)
                FROM master..[spt_values] pkgNo
                WHERE number BETWEEN 1 AND @maxPackageForStore
                UNION ALL
                SELECT DISTINCT
                    StoreId = @storeId
                --,PackageId = CAST(@packageId + number AS int)
                ,ItemType = 1
                ,ItemCount = 1
                ,ItemPrice = (@itemMinPrice / 2) + (10 * (SELECT TOP 1 n = number FROM master..[spt_values] WHERE number BETWEEN pkgNo.number AND pkgNo.number + 2  ORDER BY NEWID()))
                ,MaxItemQouta = @maxPackageForStore
                ,MaxFullQouta =  @maxPackageForStore  + (SELECT TOP 1 n = number FROM master..[spt_values] WHERE number BETWEEN 0 AND 2 ORDER BY NEWID())
                FROM master..[spt_values] pkgNo
                WHERE number BETWEEN 2 AND (CASE WHEN @maxPackageForStore > 4 THEN 4 ELSE @maxPackageForStore END)

            --set @packageId = @packageId + @maxPackageForStore;
            END
    set @storeId =@storeId + 1;
    END

SELECT * FROM storePackages
--drop table #storePackages

No PackageIds Simply StoreId and Lowest CombinedCost - ~200-300MS depending on data
Next if you don't care what Packages are in there and you only want 1 row per store you can do the following:
IF OBJECT_ID('tempdb..#TestResults') IS NOT NULL
    BEGIN
        DROP TABLE #TestResults
    END

DECLARE @MinItemCount INT = 5

;WITH cteMaxCostToConsider AS (
    SELECT
       StoreId
       ,CASE
          WHEN (SUM(ItemCount) >= @MinItemCount) AND
          SUM(ItemPrice) < MIN(((@MinItemCount / ItemCount) + IIF((@MinItemCount % ItemCount) > 0, 1,0)) * ItemPrice) THEN SUM(ItemPrice)
          ELSE MIN(((@MinItemCount / ItemCount) + IIF((@MinItemCount % ItemCount) > 0, 1,0)) * ItemPrice)
       END AS MaxCostToConsider
    FROM
       storePackages
    GROUP BY
       StoreId
)

, cteRecursive AS (
    SELECT
      StoreId
      ,ItemCount AS CombinedItemCount
      ,CAST(ItemPrice AS decimal(18,8)) AS CombinedCost
    FROM
       storePackages

    UNION ALL

    SELECT
      r.StoreId
      ,r.CombinedItemCount + t.ItemCount
      ,CAST(r.CombinedCost + t.ItemPrice AS decimal(18,8))
    FROM
       cteRecursive r
       INNER JOIN storePackages t
       ON r.StoreId = t.StoreId
       INNER JOIN cteMaxCostToConsider m
       ON r.StoreId = m.StoreId
      AND r.CombinedCost + t.ItemPrice <= m.MaxCostToConsider
)

SELECT
    StoreId
    ,MIN(CombinedCost) as CombinedCost
    INTO #TestResults
FROM
    cteRecursive
WHERE
    CombinedItemCount >= @MinItemCount
GROUP BY
    StoreId

SELECT *
FROM
    #TestResults

WITH PackageIds Only 1 Record Per StoreId - Varries widely depending on test data/combinations to consider ~600-1300MS
Or if you still want package ids but you don't care which combination you choose and you only want 1 record then you can do:
IF OBJECT_ID('tempdb..#TestResults') IS NOT NULL
    BEGIN
        DROP TABLE #TestResults
    END

DECLARE @MinItemCount INT = 5

;WITH cteMaxCostToConsider AS (
    SELECT
       StoreId
       ,CASE
          WHEN (SUM(ItemCount) >= @MinItemCount) AND
          SUM(ItemPrice) < MIN(((@MinItemCount / ItemCount) + IIF((@MinItemCount % ItemCount) > 0, 1,0)) * ItemPrice) THEN SUM(ItemPrice)
          ELSE MIN(((@MinItemCount / ItemCount) + IIF((@MinItemCount % ItemCount) > 0, 1,0)) * ItemPrice)
       END AS MaxCostToConsider
    FROM
       storePackages
    GROUP BY
       StoreId
)

, cteRecursive AS (
    SELECT
      StoreId
      ,CAST(PackageId AS VARCHAR(MAX)) AS PackageIds
      ,ItemCount AS CombinedItemCount
      ,CAST(ItemPrice AS decimal(18,8)) AS CombinedCost
    FROM
       storePackages

    UNION ALL

    SELECT
      r.StoreId
      ,r.PackageIds + ',' + CAST(t.PackageId AS VARCHAR(MAX))
      ,r.CombinedItemCount + t.ItemCount
      ,CAST(r.CombinedCost + t.ItemPrice AS decimal(18,8))
    FROM
       cteRecursive r
       INNER JOIN storePackages t
       ON r.StoreId = t.StoreId
       INNER JOIN cteMaxCostToConsider m
       ON r.StoreId = m.StoreId
      AND r.CombinedCost + t.ItemPrice <= m.MaxCostToConsider
)

, cteCombinedCostRowNum AS (
    SELECT
       StoreId
       ,PackageIds
       ,CombinedCost
       ,CombinedItemCount
       ,ROW_NUMBER() OVER (PARTITION BY StoreId ORDER BY CombinedCost) AS RowNumber
    FROM
       cteRecursive
    WHERE
       CombinedItemCount >= @MinItemCount
)

SELECT DISTINCT
    c.StoreId
    ,c.PackageIds
    ,c.CombinedItemCount
    ,c.CombinedCost
INTO #TestResults
FROM
    cteCombinedCostRowNum  c
WHERE
    RowNumber = 1

SELECT *
FROM
    #TestResults

Note all bench marking is done on a 4 year old laptop Intel i7-3520M CPU 2.9 GHz with 8 GB of RAM and SAMSUNG 500 GB EVO SSD.  So if you run this on an appropriately resourced server I would expect exponentially faster.  There is also no doubt that adding indexes on storePackages would expedite the answer as well.

A: Firstly we'll should to find all combinations, and next select one with minimal price for seeking value
DECLARE @Table as TABLE (StoreId INT, PackageId INT, Item INT, Cost INT)
INSERT INTO @Table VALUES (1,1,1,50),(1,2,2,60),(1,3,3,80),(1,4,4,100)

DECLARE @MinItemCount INT = 5;

WITH cteCombinationTable AS (
    SELECT  cast(PackageId as NVARCHAR(4000)) as Package, Item, Cost
    FROM @Table
    UNION ALL
    SELECT CONCAT(o.Package,',',c.PackageId), c.Item + o.Item, c.Cost + o.Cost FROM @Table as c join cteCombinationTable as o on CONCAT(o.Package,',',c.PackageId) <> Package
    where o.Item < @MinItemCount
)

select top 1 *
from cteCombinationTable
where item >= @MinItemCount
order by cast(cost as decimal)/@MinItemCount

A: MY SOLUTION
First of all I am thankful for everyone who try to help me. However all suggested solutions are based on CTE. As I said before recursive CTEs cause performace problems when hunderds of stores are considered. Also multiple packages are requested for one time. This means, A request can include mutiple baskets. One is 5 items other is 3 items and another one is 7 items...
Last Solution
First of all I generates all possible scenarios in a table by item size... By this way, I have option eleminate unwanted scenarios.
CREATE TABLE ItemScenarios(
   Item int,
   ScenarioId int,
   CalculatedItem int  --this will be joined with Store Item
)

Then I generated all possible scenario from 2 item to 25 item and insert to the ItemScenarios table. Scenarios can be genereated one time by using WHILE or recursive CTE. The advantage of this way, scenarios generated only for one time.
Resuls are like below.
Item          |   ScenarioId       |     CalculatedItem
--------------------------------------------------------
2                   1                     2
2                   2                     3
2                   3                     1
2                   3                     1
3                   4                     5
3                   5                     4
3                   6                     3
3                   7                     2
3                   7                     2
3                   8                     2
3                   8                     1
3                   9                     1
3                   9                     1
3                   9                     1
....
.....
......
25                  993                   10

By this way, I can restrict scenario sizes, Max different store, max different package etc.
Also I can eleminate some scenarios which matematically impossible cheapest then other. For example for 4 items request, some scenario
Scenario 1 : 2+2
Scenario 2: 2+1+1
Scenario 3: 1+1+1+1
Among these scenarios; It is impossible Scenario 2 would be cheapest basket. Because,
If Scenario 2 < Scenario 3 --> Scenario 1 would be lower then Scenario 2. Because the thing decreasing cost is 2 item price and **Scenario 1* have double 2 items
Also If Scenario 2 < Scenario 1 --> Scenario 3 would be lower then Scenario 2
Now, If I delete scenarios like Scenario 2 I would gain some performance advantages.
Now I can chose chepest item prices among stores
DECLARE @requestedItems int;
SET @requestedItems = 5;

CREATE TABLE #JoinedPackageItemWithScenarios(
   StoreId int not null,
   PackageId int not null,
   ItemCount int not null,
   ItemPrice decimal(18,8)
   ScenarioId int not null,
)
INSERT INTO #JoinedPackageItemWithScenarios
 SELECT
    SPM.StoreId
   ,SPM.PackageId
   ,SPM.ItemCount
   ,SPM.ItemPrice
   ,SPM.ScenarioId
   FROM (
      SELECT
            SP.StoreId
           ,SP.PackageId
           ,SP.ItemCount
           ,SP.ItemPrice
           ,SC.ScenarioId
           ,RowNumber = ROW_NUMBER() OVER (PARTITION BY SP.StoreId,SC.ScenarioId,SP.ItemCount ORDER BY SP.ItemPrice)
      FROM ItemScenarios SC
      LEFT JOIN StorePackages AS SP ON SP.ItemCount = SC.CalculatedItem
      WHERE SC.Item = @requestedItems
 ) SPM
 WHERE SPM.RowNumber = 1

-- NOW I HAVE CHEAPEST PRICE FOR EACH ITEM, I CAN CREATE BASKET

 CREATE TABLE #selectedScenarios(
   StoreId int not null,
   ScenarioId int not null,
   TotalItem int not null,
   TotalCost decimal(18,8)
)
 INSERT INTO #selectedScenarios
 SELECT
      StoreId
     ,ScenarioId
     ,TotalItem
     ,TotalCost
  FROM (
     SELECT
           StoreId
          ,ScenarioId
          --,PackageIds = dbo.GROUP_CONCAT(CAST(PackageId AS nvarchar(20))) -- CONCATENING PackageId decreasing performance here. We can joing seleceted scenarios with #JoinedPackageItemWithScenarios after selection complated.
          ,TotalItem = SUM(ItemCount)
          ,TotalCost = SUM(ItemPrice)
          ,RowNumber = ROW_NUMBER() OVER (PARTITION BY StoreId ORDER BY SUM(ItemPrice))
        FROM #JoinedPackageItemWithScenarios JPS
        GROUP BY StoreId,ScenarioId
        HAVING(SUM(ItemCount) >= @requestedItems)
     ) SLECTED
     WHERE RowNumber = 1

  -- NOW WE CAN POPULATE PackageIds if needed

  SELECT
      SS.StoreId
     ,SS.ScenarioId
     ,TotalItem = MAX(SS.TotalItem)
     ,TotalCost = MAX(SS.TotalCost)
     ,PackageIds = dbo.GROUP_CONCAT(CAST(JPS.PackageId AS nvarchar(20)))
    FROM #selectedScenarios SS
    JOIN #JoinedPackageItemWithScenarios AS JPS ON JPS.StoreId = SS.StoreId AND JPS.ScenarioId = SS.ScenarioId
    GROUP BY SS.StoreId,SS.ScenarioId

SUM
In my test, this way is mimimum 10 times faster then recursive CTE, especially when number of stores and requested items increased. Also It gets 100% correct results. Because recursive CTE tried milions of unrequired JOINs when number of stores and requested items increased.