text:
Q: Codeigniter: Categories and Subcategroies I am trying to make a restaurant menu and I have to have Categories and Subcategories, so I created the following tables:
Table: Categories
       ID
       NAME

Table: Subcategories
       ID
       NAME
       PRICE
       DESCRIPTION
       CATEGORIES_ID

I am using Codeigniter and DataMapper PHP by wanwizard. So currently I have some version of 2 foreach loops but the problem is that when I add a new SUBCATEGORY and only the last one appear, so it is NOT listing all the subcategories of the category Any ideas where I am wrong ?
public function index()
{

$categories = new Category_model();
$subcategories = new Subcategory_model();
$categories->get();
$subcategories->get();

$recent_categories = array();
foreach ($categories as $category)
{
  foreach($subcategories as $subcategory)
  {
    if($subcategory->categories_id == $category->id)
    {
      $single_category = array
      (
        'category_name' => $category->name,
        'subcategory_name' => $subcategory->name,
        'subcategory_description' => $subcategory->description,
        'subcategory_price' => $subcategory->price,
      );
    }
  }
  array_push($recent_categories, $single_category);
}

$data = array
(
  'categories' => $recent_categories,
);

$this->parser->parse('templates/content_menu', $data);
}

THIS IS THE VIEW:
{categories}

{category_name}

        <a class="clb-photo" href="<?php echo site_url('design/images/photos/food.jpg'); ?>">
          {subcategory_name}

        {subcategory_price}

{subcategory_description}

  {/categories}

A: It's in your structure of the loops. You need to do the array_push INSIDE the foreach($subcategories as $subcategory) loop. Your single_category array is overwritten with each iteration of the loop, but it is never added to the recent_categories array until after is has been overwritten. Change your code to:
foreach ($categories as $category)
{
  foreach($subcategories as $subcategory)
  {
    if($subcategory->categories_id == $category->id)
    {
      $single_category = array
      (
        'category_name' => $category->name,
        'subcategory_name' => $subcategory->name,
        'subcategory_description' => $subcategory->description,
        'subcategory_price' => $subcategory->price,
      );
      array_push($recent_categories, $single_category); // ****** MOVED THIS LINE
    }
  }
}


text:
Q: How to pass the parameter to an api using http POST method I'm using HTTP POST method to post a parameter but it is showing a 404 error. The same API is working fine in command line
My code is :
var dataToPost = {url:'http://google.com'};

    $http.post("http://appfil.es" , dataToPost)

        .success(function(serverResponse, status, headers, config) {

        })
        .error(function(serverResponse, status, headers, config) {

        }
    );

The above code returns error with status 404.. but the below code works fine is console.
curl -X POST http://appfil.es --data "url=http://google.com"..

Please help me out to solve this problem.
Thanks

A: Your code is correct.
However, you can't make a post call across websites from a client's browser (XSS security)
Either ensure that http://appfil.es is the same url as the one of the web page containing your angular code or prefer using $http.jsonp.
More info on JSONP on Wikipedia.
You won't be able to shorten URLs from appfil.es as long as they don't send the following header from their API
Access-Control-Allow-Origin

Indeed, if you print the headers returned by appfil.es by adding option -v to your command, you only see:
< HTTP/1.1 201 Created
* Server nginx/1.4.4 is not blacklisted
< Server: nginx/1.4.4
< Date: Mon, 29 Dec 2014 10:52:21 GMT
< Content-Type: text/html;charset=utf-8
< Content-Length: 23
< Connection: keep-alive
< Location: http://appfil.es/YVcCEA

Thus, no Access-Control-Allow-Origin. You can call their API from your website, server-side, not client (browser) side.

A: Since you are using AngularJs, you can use this transformer to encode your data, which will centralize the encoding for all your requests:
(function () {
    'use strict';
    // Module name is handy for logging
    var id = 'app';
    // Create the module and define its dependencies.
    var app = angular.module('app', [
    ]);
    app.config(['$httpProvider', function ($httpProvider) {
        // Use x-www-form-urlencoded Content-Type
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
        // Override $http service's default transformRequest
        $httpProvider.defaults.transformRequest = [function (data) {
            /**
             * The workhorse; converts an object to x-www-form-urlencoded serialization.
             * @param {Object} obj
             * @return {String}
             */
            var param = function (obj) {
                var query = '';
                var name, value, fullSubName, subName, subValue, innerObj, i;
                for (name in obj) {
                    value = obj[name];
                    if (value instanceof Array) {
                        for (i = 0; i < value.length; ++i) {
                            subValue = value[i];
                            fullSubName = name + '[' + i + ']';
                            innerObj = {};
                            innerObj[fullSubName] = subValue;
                            query += param(innerObj) + '&';
                        }
                    }
                    else if (value instanceof Object) {
                        for (subName in value) {
                            subValue = value[subName];
                            fullSubName = name + '[' + subName + ']';
                            innerObj = {};
                            innerObj[fullSubName] = subValue;
                            query += param(innerObj) + '&';
                        }
                    }
                    else if (value !== undefined && value !== null) {
                        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
                    }
                }
                return query.length ? query.substr(0, query.length - 1) : query;
            };
            return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
        }];
    }]);

})();

A: Pass the cURL request thru PHP inside the JavaScript variable.
    var dataToPost = <?php
    $ch = curl_init("http://www.google.com");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result=curl_exec($ch);
    echo $result;
    curl_close($ch);
    ?>

Document.write(dataToPost); will give you the webpage of Google.com

redpajama_set_name: RedPajamaStackExchange


text:
Q: error while loading shared libraries: libQtSql.so.4: cannot open shared object file: No such file or directory A similar issue is found elsewhere but only with 32bit programs.
I have this problem when trying to run clementine - which is 64bit, i checked the binary i have - and ubuntu-one-control-panel-qt
I'm starting to feel like I've tried everything.  Is there a way to restore my qt installation to some kind of default state?
I think this might have happened after I uninstalled Rhythmbox with 'sudo apt-get remove rhythmbox'.  I've since reinstalled rhythmbox though, and thought any removed dependencies would be reinstalled with apt....
EDIT: this is my apt history log:
https://gist.github.com/2646562
Line 215 is when I first installed Clementine.  It was obviously working at this point.  Removing Rhythmbox at line 305 doesn't look like it did too much damage.  Yet that is the point when it stopped working, as most of the rest of the log is me trying to fix Clementine.
Just to repeat:  I don't think any Qt apps are working on my installation.  I'm about to research how to completely remove and reinstall Qt, see if that's a hopeful avenue.

A: I've got the same issue when installing Time Doctor (not from repos) on fresh install of Ubuntu 13.10 GNOME x64.
Your comments made me to investigate and do this:
sudo apt-get install libqt4-sql
sudo apt-get install libqt4-gui

After that the error did not occur.

A: The rhythmbox package is a dependency of the ubuntu-desktop package, which is used to ensure you have the basic desktop components.
If you forced the removal of Rhythmbox, it would have also forced the removal of ubuntu-desktop, which might have let some other critical desktop components be removed.  Reinstalling Rhythmbox wouldn't restore the other packages that needed to be removed to complete that first operation.
You might be able to fix things up by reinstalling ubuntu-desktop with the following command:
sudo apt-get install ubuntu-desktop

If that doesn't help, please provide a bit more information about what changes you made to your system between when things worked and when they stopped working.


text:
Q: MySQL Error: Authentication plugin 'caching_sha2_password' cannot be loaded I just installed MySQL Ver 14.14 Distrib 5.7.22 with Homebrew on my macOS v10.13.4.
I ran the command:
brew install mysql
After the installation completed, as directed by Homebrew, I ran the command:
mysql_secure_installation
and was returned the error: Error: Authentication plugin 'caching_sha2_password' cannot be loaded: dlopen(/usr/local/Cellar/mysql/5.7.22/lib/plugin/caching_sha2_password.so, 2): image not found
I tried a few things like changing default_authentication_plugin to mysql_native_password in the my.cnf file but it still throws the same error.
Next I tried running:
mysql_upgrade -u root
and I was thrown the same error again mysql_upgrade: Got error: 2059: Authentication plugin 'caching_sha2_password' cannot be loaded: dlopen(/usr/local/Cellar/mysql/5.7.22/lib/plugin/caching_sha2_password.so, 2): image not found while connecting to the MySQL server
Upgrade process encountered error and will not continue.
Any help is appreciated.

A: So, I found the running process of mysqld by sudo lsof -i tcp:3306 then I killed it using sudo kill -9 <PID>.
After this I tried $ mysql_secure_installation again but ran into a new error Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (61)
After trying a few fixes for getting mysql.sock to work, I started the MySQL server with
$ sudo mysql.server start
then went ahead with $ mysql_secure_installation to set password for the root user.
This worked for me finally.
Note: Homebrew asks you to first do mysql_secure_installation before starting the MySQL server for the first time but that just made me run into endless loop of errors.

A: I had the same error and solved this by stopping the MySQL server 8.0 from System Preferences -> MySQL settings. I have both the 5.7 and 8.0 installed at the same time.
Now when I type

mysql --version

I get

mysql  Ver 14.14 Distrib 5.7.22, for osx10.13 (x86_64)

And I can log in successfully.


text:
Q: Mini Magick, GraphicMagick and Carrierwave I am trying to get my uploader file to resize images as they are uploaded using the following code:
 version :thumb do
  process :resize_to_limit => [230, 230]
 end

I have installed Carrierwave to handle the upload along with GraphicMagick to process the images (installed correctly) and MiniMagick (installed successfully using gem install Mini_magick)
I keep receiving the following error though:
No such file or directory - identify -ping C:/Users/THOMAS~1/AppData/Local/Temp/mini_magick20120904-4644-1jvulye.jpg
Request

Parameters:

{"utf8"=>"✓",
"authenticity_token"=>"yzrsjbr91do/8kpk7R67A7MMNfHu+6+BRQlTlBfPssw=",
"profile"=>{"name"=>"test2",
"image"=>#<ActionDispatch::Http::UploadedFile:0x4946e68
@original_filename="centaur.JPG",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"profile[image]\";  filename=\"centaur.JPG\"\r\nContent-Type: image/jpeg\r\n",
@tempfile=#<File:C:/Users/THOMAS~1/AppData/Local/Temp/RackMultipart20120904-4644-4abl14>>}, "commit"=>"Submit"}

I managed to get this working on another windows 7 computer but for whatever reason I keep receiving this error.
If anyone could point me in the right direction to fix this it really would be much appreciated! :)

A: try require 'mini_gmagick' instead of require 'mini_magick', graphics magick has only one executable gm, and by default mini_magick uses image magick, which has multiple binaries and identify is one of them.


text:
Q: Linearly separating a Gaussian Filter and calculating with Numpy I have a 2d numpy array containing greyscale pixel values from 0 to 255. What I want to do is to create a gaussian filter from scratch. I have already written a function to generate a normalized gaussian kernel:
def gaussianKernel(size, sigma):
    kernel =  np.fromfunction(lambda x, y: (1/(2*math.pi*sigma**2)) * math.e ** ((-1*((x-(size-1)/2)**2+(y-(size-1)/2)**2))/(2*sigma**2)), (size, size))
    return kernel / np.sum(kernel)

which works fine:
>>> vision.gaussianKernel(5, 1.5)
array([[ 0.01441882,  0.02808402,  0.0350727 ,  0.02808402,  0.01441882],
       [ 0.02808402,  0.05470021,  0.06831229,  0.05470021,  0.02808402],
       [ 0.0350727 ,  0.06831229,  0.08531173,  0.06831229,  0.0350727 ],
       [ 0.02808402,  0.05470021,  0.06831229,  0.05470021,  0.02808402],
       [ 0.01441882,  0.02808402,  0.0350727 ,  0.02808402,  0.01441882]])

So then I created a basic convolution function to apply this kernel to each pixel and produces a gaussian blur:
def gaussianBlurOld(img, kSize, kSigma):
    kernel = gaussianKernel(kSize, kSigma)
    d = int((kSize-1)/2)
    gaussian = np.zeros((img.shape[0]-2*d, img.shape[1]-2*d))
    for y in range(d, img.shape[0]-d):
        for x in range(d, img.shape[1]-d):
            gaussian[y-d][x-d] = np.sum(np.multiply(img[y-d:y+d+1, x-d:x+d+1], kernel))
    return gaussian

Which works fine and blurs an image, however, as this code will be eventually running on a raspberry pi, I need it to be efficient and for it to be much faster. So thanks to this answer on a question I asked yesterday on how to speed up a Sobel edge detector, I tried to apply the same logic he gave to the gaussian filter. However, as the function will accept a variable size parameter for the kernel, it complicates things slightly from the set size of the Sobel kernel which is just 3x3.
If I understand the explanation correctly, I need to first separate the kernel into x and y components which can be done by just using the top row and left column of the original kernel (obviously they are the same, but I decided to just keep them separate as I have the 2d kernel already calculated). Below is the matrix separated:

From these row and column vectors, I need to go through each value and multiply that 'window' of the array by it element-wise. After each one, shifting the reduced size of the window along the array to the right. To show what I think I need to do clearer, these are the 3 different 'windows' I am talking about for a small image with a kernel size of 3x3:
          _______3_______
     _____|_2_______    |
_____|_1__|____|    |   |
|    |    |    |    |   |
|123,|213,|124,|114,|175|
|235,|161,|127,|215,|186|
|128,|215,|111,|141,|221|
|224,|171,|193,|127,|117|
|146,|245,|129,|213,|221|
|152,|131,|150,|112,|171|

So for each 'window', you multiply by the index of that window in the kernel and add that to the total.
Then, take that img which has had the x component of the gaussian kernel applied to it and do the same for the y component.
These are the steps I think I can do to calculate the gaussian blur much faster than using nested for-loops as above and here is the code that I wrote to try and do it:
def gaussianBlur(img, kSize, kSigma):
    kernel = gaussianKernel(kSize, kSigma)
    gausX = np.zeros((img.shape[0], img.shape[1] - kSize + 1))
    for i, v in enumerate(kernel[0]):
        gausX += v * img[:, i : img.shape[1] - kSize + i + 1]
    gausY = np.zeros((gausX.shape[0] - kSize + 1, gausX.shape[1]))
    for i, v in enumerate(kernel[:,0]):
        gausY += v * gausX[i : img.shape[0]  - kSize + i + 1]
    return gausY

My problem is that this function produces the right 'blurring effect', but the output values are all between 0 and 3 as floats for some reason. Luckily, for some other reason, matplotlib can still display the output fine so I can check that it has blurred the image correctly.
The question is just simply: why are the pixel values outputting between 0 and 3???
I have debugged for hours but cannot spot the reason. I am pretty sure that there is just a little scaling detail somewhere, but I just cant find it. Any help would be much appreciated!

A: For anyone interested, the problem was from the fact that The function gaussianKernel returned the 2d kernel normalised for use as a 2d kernel. This meant that when I split it up into its row and column components by taking the top row and left column, these components were not normalised.
To solve this, I just added a parameter to the gaussianKernel function to select 2 dimensions or 1 dimensions (both normalised correctly):
def gaussianKernel(size, sigma, twoDimensional=True):
    if twoDimensional:
        kernel = np.fromfunction(lambda x, y: (1/(2*math.pi*sigma**2)) * math.e ** ((-1*((x-(size-1)/2)**2+(y-(size-1)/2)**2))/(2*sigma**2)), (size, size))
    else:
        kernel = np.fromfunction(lambda x: math.e ** ((-1*(x-(size-1)/2)**2) / (2*sigma**2)), (size,))
    return kernel / np.sum(kernel)

So now I can get just the 1d kernel with gaussianKernel(size, sigma, False) , and have it be normalised correctly. This means I can finally get the right blurring effect without scaled pixel values.


text:
Q: Joomla 2.5 - Generate URL based on article id I am trying to generate an URL for an article basead on Article ID.
After runing this query
SELECT a.sectionid,
CASE WHEN CHAR_LENGTH( a.alias )
THEN CONCAT_WS( ":", a.id, a.alias )
ELSE a.id
END AS slug,
CASE WHEN CHAR_LENGTH( cc.alias )
THEN CONCAT_WS( ":", cc.id, cc.alias )
ELSE cc.id
END AS catslug
FROM #__content AS a
INNER JOIN #__categories AS cc ON cc.id = a.catid
WHERE a.id = $articleID

I store my result in $data and generate the link this way:
$link = JRoute::_(ContentHelperRoute::getArticleRoute($data[0]->slug, $data[0]->catslug, $data[0]->sectionid));

The problem is that the generated link its not correct when my article doesn't belong to any menu.
I noticed that when my article is not associated with any menu, the API gets the active menu id and add to the generated link, the parameter "&Itemid=MyActiveMenuId" (this happens in the route.php file). But since the article doesn't exist in the active menu, the generated link will not work.
I know that if the API just ignores the "item menu id" instead of getting the "active menu id" it will work, but I can do this without change the Joomla code? Also, I want that the "item menu id" continue to be considered for the cases where an article actually belongs to a menu, so the generated URL will be SEF.
There is any way to solve this? Or every article must belong to a menu item?
My Joomla version is 2.5.13

A: If you're trying to generate a URL based on the article ID ($articleID in your code), your query should look something like the following:
select id from #__menu where link='index.php?option=com_content&view=article&id=$articleID';

For this example we'll assume to you stored the result in $menuID, or that $hasMenuID===false.  You'll then determine your output URL like so:
if($hasMenuID===false) $outURL = "index.php?option=com_content&id=$articleID";
else $outURL = "index.php?option=com_content&itemid=$menuID";

If you want nice SEF-friendly URLs you can then apply JRoute.  Also, please don't forget to typecast your $articleID to an integer before your initial query.  SQL safety and all.

A: Every article need not be linked to menu to make it work.
You would want to run the url through JRoute to get the full url.
echo $id =JRequest::getVar('id');
$url = JRoute::_('index.php?option=com_content&view=article&id='.$id);

You can also redirect a url to another url with .htaccess
There are also other extensions out there, which can help you redirect to a url.
For the rest of the url you would need to know the component you are calling
(added as the option like above, Content manager is always com_content)
and the view (which for an article is article).
You can see the different views available for com_content by checking the file structure under /components/com_content/views/.
Besides Article, you should see articles, categories, and category as well as a few other.


text:
Q: Read a folder of parquet files from s3 location using pyspark to pyspark dataframe I want to read some parquet files present in a folder poc/folderName on s3 bucket myBucketName to a pyspark dataframe. I am using pyspark v2.4.3 for the same.
below is the code which i am using
    sc = SparkContext.getOrCreate()
    sc._jsc.hadoopConfiguration().set("fs.s3.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem")
    sc._jsc.hadoopConfiguration().set("fs.s3a.awsAccessKeyId", 'id')
    sc._jsc.hadoopConfiguration().set("fs.s3a.awsSecretAccessKey", 'sid')
    sqlContext = SQLContext(sc)
    parquetDF = sqlContext.read.parquet("s3a://myBucketName/poc/folderName")

I have downloaded the hadoop-aws package using command pyspark --packages org.apache.hadoop:hadoop-aws:3.3.0 but when i run above code i am receive below error.
An error occurred while calling o825.parquet.
: java.lang.RuntimeException: java.lang.ClassNotFoundException: Class org.apache.hadoop.fs.s3a.S3AFileSystem not found
    at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2195)
    at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2654)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2667)

What is the thing that I am doing wrong here?
I am running the python code using Anaconda and spyder on windows 10

A: The Maven coordinates for the open source Hadoop S3 driver need to be added as a package dependency:
spark-submit --packages org.apache.hadoop:hadoop-aws:2.7.0

Note the above package version is tied to the installed AWS SDK for Java version.
In the Spark application's code, something like the following may also be needed:
hadoop_conf = spark.sparkContext._jsc.hadoopConfiguration()
hadoop_conf.set("fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem")
hadoop_conf.set("fs.s3a.access.key", access_id)
hadoop_conf.set("fs.s3a.secret.key", access_key)

Note that when using the open source Hadoop driver, the S3 URI scheme is s3a and not s3 (as it is when using Spark on EMR and Amazon's proprietary EMRFS). e.g. s3a://bucket-name/
Credits to danielchalef


text:
Q: How to instal LAMP for Ubuntu 12.04 LTS?
Possible Duplicate:
What's the easiest way to set up a LAMP stack?

I'm studying SQL database right now and I need a mySQL server. I was guided to use a LAMP server on Linux .. but I don't know how to install it on my Ubuntu 12.04 LTS ?!!
I looked for previous situations like me and I found that I should install some software called tasksel .. but when I did .. something went wrong and it failed to install the LAMP server.
So, please I need your help in this problem


text:
Q: Function Error Object Required 800a01a8 I'm relatively new to functions and classes so not too sure if this is a beginners mistake. I'm getting:
Microsoft VBScript runtime error '800a01a8'

Object required: 'EngineerNote(...)'

/backup-check/backup_frontendlist_import_NEW.asp, line 76

Line 76 is:
Set NoteArray=EngineerNote(company, servername, backupsolution)

The three variables I'm passing are all strings. All the function and class is set in:
Class EngineerNoteClass
public note
public notesubmitdate
End Class

Function EngineerNote(Company, ServerName, Solution)
Set RecordSet = Server.CreateObject("ADODB.Recordset")
RecordSetSQLString = "SELECT note, submitdate FROM tbl_BackupChecks_AuditInformation WHERE Company='" & company & "' AND ServerName='" & servername & "' AND Solution='" & solution & "' ORDER BY submitdate desc;"
RecordSet.Open RecordSetSQLString, DatabaseConnection
If Recordset.EOF Then
'Do Nothing
Else
Dim NoteResults
Set NoteResults = new EngineerNoteClass
noteresults.note = RecordSet("note")
noteresults.notesubmitdate = RecordSet("submitdate")
Set Engineernote = NoteResults
End If
Recordset.Close
End Function

A: Most likely your database query didn't return any results. You only set the return value of your function when the recordset isn't at EOF:
If Recordset.EOF Then
  'Do Nothing
Else
  ...
  Set Engineernote = NoteResults
End If

Setting the return value to Nothing (or to an empty EngineerNoteClass object) in the Then branch should make the error go away:
If Recordset.EOF Then
  Set EngineerNote = Nothing
Else
  ...
  Set Engineernote = NoteResults
End If

Make sure you handle the returned value/object appropriately in the rest of your script.


text:
Q: Finding F ' (y) This question looks deceivingly simple to me so I was wondering if someone out there could enlighten me whether it really is what I think it is or if I have completely missed the point.
Let $$F(y) = \int^1_0 f(x,y) dx$$
$$
f(x,y)=
\left\{
\begin{array}{c}
\sin{xy},\,\, x\ne 0 \\
y,\,\, x=0 \\
\end{array}
\right.
$$
Find $F ' (y).$
The way I see it is that by the fundamental theory of calculus $F'(y)=f(x,y)$.
However since the interval $ [0,1]$ needs to be considered, I think, I don't know what to do.
Anybody able to help me out here? It's such an annoyingly simple-looking question it's bugging me

A: Using Leibnitz integral rule
$$F'(y) = \int_0^1 \frac{\partial}{\partial y} f(x,y) \,dx $$

A: The point of this problem is to mess with your mind a bit. Think about it: For each fixed $y,$ you have an integrand equal to $\sin(xy), x\in (0,1],$ and something else when $x=0.$ It doesn't matter what you defined it to be at $x=0.$ You could define $f(0,y)$ to be an arbitrary function of $y$ and you'd get the same answer coming out of the integral.
So just do the integral $\int_0^1 \sin (xy)\,dx.$ You'll get a function of $y$ from that. Then differentiate that.
PS: No, the FTC does not give what you wrote.


text:
Q: Accessing shared folders from Ubuntu (guest OS) in VMware Workstation ACE Edition I have enabled the "Shared Folders" feature on the VM that runs Ubuntu 9.04. How do I access this from the Ubuntu guest OS?
My host OS is Windows Vista Home Premium with SP2.
Note: I have enabled "Shared Folders" for Windows 7 RC (guest OS) by mapping the //.host/shared folder.

A: You need to install the VMware Tools. Once you have done that and the hgfs kernel module has loaded you should be able to access the shared folders at /mnt/hgfs/

A: You need vmware-tools installed, which has been problematic in 9.04.
Check out: http://communities.vmware.com/thread/208507

A: This should help :

*

*Create the sharefolder on your windows

*Create an account for your linux on windows

*Add your windows ip on you linux hosts file

*then log as root  with su -

*And finally mount the share folder :
mount -t smbfs -o username=<Windows system user account>,password=<password> //YourComputer/YourShareFolder /mnt/YourShareFolder
There is also another method (maybe easier)

*

*First backup you smb conf file :
cp /etc/smb.conf /etc/smb.conf.backup

*Then edit the smd conf by adding this to the end:

[SHARE_NAME]
path = /home/user/shared
public = no
writable = yes
printable = no (since you want to share files, not a printer)

*

*Then restart your smb service :
/etc/init.d/smb restart
These 2 ways work fine for me.
Hope this will help you.


text:
Q: how to record normal/PSTN calls using asterisk i want to recording incoming calls and outgoing calls using asterisk. when i make a call from my mobile phone with a custom dialer. my calls will not be a voice calls i.e. Voice over ip , that will be the normal trunk calls.
so does anyone has idea how can i recording incoming and outgoing calls at asterisk level and from where should is tart it ?

A: You can use MixMonitor command in dialplan
Or you can use Freepbx/Elastix/Trixbox and enable recordings in web.
Asterisk will record only calls sent via pbx.


text:
Q: Счетчик скачивания файлов на Java (jQuery) Здравствуйте, такая проблема: есть сайт на бесплатном хостинге Ucoz, они не дают работать с php, а мне нужен счетчик скачивания файлов (подойдет даже счетчик просто кликов по ссылке для скачивания). Можно ставить только скрипты Java (jQuery у них уже подключена). Можно ли как-то решить этот вопрос при помоши Java? Заранее благодарен!
A: Сдаётся мне, что автор имел ввиду другое... :-)
Если нужно считать общее количество переходов по ссылке всех пользователей и чтобы оно не сбрасывалось при каждом обновлении страницы, а где-то запоминалось - то тут одним только JavaScript не обойтись. Нужен серверный скрипт, который будет запоминать и сохранять. Например, написанный на PHP или Perl или ASP... Ну или каком-либо другом языке серверного программирования.
A: Без серверной части при решении проблемы не обойтись никак.
Нашел сайт zahodi-ka.ru
Работу сервиса не проверял, но из его описания следует, что Вы получите счетчик загрузок, при этом серверный скрипт будет располагаться у них.
Если на указанном сайте неправда написана, то попробуйте посмотреть еще здесь


text:
Q: showing that if a function is a bijection, then there exists a an identity function Let f:x-y be a bijection, show that foi =iof =f where i is identity function.
I know that a bijection is one which is bith noe to one and onto. The problems is that the question is so trivial that I find it difficult to prove.

A: HINT: Recall that $(g\circ f)(x)=g(f(x))$, and that $i(x)=x$.


text:
Q: How to Update model and database with code first approach in Asp.net MVC I'm new to mvc. I've creted an MVC app, in which i have used code first approach. Right now i have two tables Deal and Comment. Now i want to add a new table Category in the database and new column categoryId in Deal table.
How i can update database and model?
I'm using Sql Server 2008 R2 for Database.
I've following structure of class:
      namespace FBWebApp.Models
    {
        public class Deal
      {
        public int ID { get; set; }                 // ID
        public string Title { get; set; }           // Titolo del deal
        public string Description { get; set; }     // Descrizione dell'annuncio
        public string FacebookUID { get; set; }     // UID facebook dell'utente
        public string Visibility { get; set; }      // Visibility
        public string Category { get; set; }
        public int Option1 { get; set; }
        public int Option2 { get; set; }
        public int Option3 { get; set; }
        public int Option4 { get; set; }
        public string PhotoURL { get; set; }    // URL of the facebook photo profile
        public string Name { get; set; }        // Name of the user
        public string ProfileUrl { get; set; }  // URL of the facebook profile
        public string Photo1 { get; set; }  // URL of the Photo1 (local )
        public string Photo2 { get; set; }
        public string Photo3 { get; set; }
        public string Photo4 { get; set; }
        public string Photo5 { get; set; }
    }
    public class Comment
    {
        [Key]
        public int CommentId { get; set; }
        public string CommentText { get; set; }
        public int ID { get; set; }
        [ForeignKey("ID")]
        public Deal DelNav { get; set; }
    }

    public class DealDBContext : DbContext
    {

        public DealDBContext() : base("DealDBContext") { }
        public DbSet<Deal> Deals { get; set; }
        public DbSet<Comment> Comments { get; set; }

    }
}

A: Try using 'update-database -force -verbose' in the Package Manager Console.
If it doesn't work, modify the migration but typing 'add-migration somename' and it will apear in the Migrations folder.
If you are new to MVC and EF, definitely check out this tutorial. It explains all about that and everything else you need to know:
http://pluralsight.com/training/Player?author=scott-allen&name=mvc4-building-m1-intro&mode=live&clip=0&course=mvc4-building

A: first add your model :
public class Category
{
  public int ID { get; set; }
  public int cateName { get; set; }
}

in Deal class :
public class Deal
    {
        //..
         [ForeignKey("CatId")]
         public virtual Category Category { get; set; }
    }

after Enable Migration you should use this command in console manager to update your database :
update-database


text:
Q: get_the_post_thumbnail wordpress 3.5 For some reason the following isn't loaded anymore in wordpress 3.5. Does anyone know how to fix the get_the_post_thumbnail() ?
I'm using the follow code:
echo "
";
echo "";
echo "
".get_the_post_thumbnail($post->post_id, 'thumbnail', $attr)."
";
echo "
".$post->post_title."
";
echo "";
echo "
";

A: I could be mistaken, but I don't think $post->post_id works to retrieve the post's ID. I believe you want $post->ID. So that was probably your issue to begin with, though without seeing your $attr array, it's hard to say. Here's a reference for $post's properties. In this case, get_the_post_thumbnail is the more appropriate function.
In your answer you posted for yourself, you're using the_post_thumbnail incorrectly. First off, you don't need to echo it; the_post_thumbnail will output the thumbnail. Side note: Any function in WordPress that starts with the_ is almost always going to output something automatically. Second, You don't need to pass it $post->ID (again, using the wrong property). Third, the first property of the_post_thumbnail is the size, e.g. "thumbnail".

A: Problem solved,
                echo the_post_thumbnail($post->post_id, array('class' => 'meta_icon')); echo "
";

Don't use 'get_the_thumbnail' but simply use the_post_thumbnail.


text:
Q: C++ Boost ASIO simple periodic timer? I want a very simple periodic timer to call my code every 50ms. I could make a thread that sleeps for 50ms all the time (but that's a pain)... I could start looking into Linux API's for making timers (but it's not portable)...
I'd like to use boost.. I'm just not sure it's possible. Does boost provide this functionality?

A: A very simple, but fully functional example:
#include <iostream>
#include <boost/asio.hpp>

boost::asio::io_service io_service;
boost::posix_time::seconds interval(1);  // 1 second
boost::asio::deadline_timer timer(io_service, interval);

void tick(const boost::system::error_code& /*e*/) {

    std::cout << "tick" << std::endl;

    // Reschedule the timer for 1 second in the future:
    timer.expires_at(timer.expires_at() + interval);
    // Posts the timer event
    timer.async_wait(tick);
}

int main(void) {

    // Schedule the timer for the first time:
    timer.async_wait(tick);
    // Enter IO loop. The timer will fire for the first time 1 second from now:
    io_service.run();
    return 0;
}

Notice that it is very important to call expires_at() to set a new expiration time, otherwise the timer will fire immediately because it's current due time already expired.

A: The second example on Boosts Asio tutorials explains it.
You can find it here.
After that, check the 3rd example to see how you can call it again with a periodic time intervall

A: To further expand on this simple example. It will block the execution as was said in the comments, so if you want more io_services running, you should run them in a thread like so...
boost::asio::io_service io_service;
boost::asio::io_service service2;
timer.async_wait(tick);
boost::thread_group threads;
threads.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
service2.run();
threads.join_all();

A: As I had some issues with prior answers, here is my example:
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>

void print(const boost::system::error_code&, boost::asio::deadline_timer* t,int* count)
{
    if (*count < 5)
    {
        std::cout << *count << std::endl;
        ++(*count);
        t->expires_from_now(boost::posix_time::seconds(1));
        t->async_wait(boost::bind(print, boost::asio::placeholders::error, t, count));
    }
}

int main()
{
    boost::asio::io_service io;
    int count = 0;
    boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));

    t.async_wait(boost::bind(print, boost::asio::placeholders::error, &t, &count));

    io.run();
    std::cout << "Final count is " << count << std::endl;

    return 0;

}

it did what it supposed to do: counting to five. May it help someone.

A: A Boost Asio add-on class that encapsulates this functionality (call a specfied function every N milliseconds): https://github.com/mikehaben69/boost/tree/main/asio
The repo includes a demo source file and makefile.


text:
Q: How to Call Function From Separate WordPress Install on Same Server? Is there a way to call functions from a default location for multiple installed sites on the same server?
For example:
\public_html\functions\global_functions.php has the shared functions for all sites.
\public_html\site1\wp-content\themes\theme1_child\functions.php
require_once( dirname(__FILE__) . '../../../../global_functions.php');

\public_html\site2\wp-content\themes\theme1_child\functions.php
require_once( dirname(__FILE__) . '../../../../global_functions.php');

I know this is not correct but I am not sure if it is even possible to do something like this. Since it is on the same server, I didn't know if there was a way to see other directories above the current install point.

After continuing to play with this, I ended up doing it this way:
define ( 'global_functions_dir', dirname(__FILE__) . '../../../../../_functions' );

require_once( global_functions_dir . '/global-functions.php');

which can be added on each site to include the necessary functions.  If anyone knows if there are any security risks doing it this way, please let me know.  Since this is a server-side call, I would think this is fine??
I have started reading through the multi-site configuration and this could be a great way to accomplish this.  I will look at moving in this direction after I have a better understanding of the issues that might arise by doing so.  Thank you for your help.

A: Your include path is incorrect.
You have:
require_once( dirname(__FILE__) . '../../../../global_functions.php');
When it should be:
require_once( dirname(__FILE__) . '../../../../functions/global_functions.php');

The other alternative would be to change your setup from individual standalone installations of WordPress to WordPress Multi-site.
You would then have a couple of options:

*

*Option #1 being a Must-Use Plugin.

*Option #2 being a standard Plugin (Activated network-wide).

*Option #3 being a standard Plugin (Activated on a per-site basis).

Personally, I would recommend option #1 (Must-Use plugin). This will activate the plugin across every site in your network and it can't be deactivated or removed via user interface. This guarantees the code will be available for all sites in your network at all times.
Option #2 is nice, because it does exactly the same as option #1, except if you want to troubleshoot what might be causing a problem, you can very easily activate or deactivate the functionality with a simple click through the administrative user interface.
Option #3 is a bit more versatile. You can activate the plugin on a per-site basis. Maybe you have three sites to manage, but only two of them need the functionality. Then you can activate it on just those two sites and not the third one.
Either way, which ever option you choose (related to WordPress multi-site), you only have to manage the functionality in one place, while multiple sites can share and use that functionality.


text:
Q: Error delivering iOS App update. "This bundle is invalid. Apple is not currently accepting applications built with this version of the SDK." I reticently delivered an app to the iOS App store on 1/24/2014. It's an iO7/iPhone only app and everything was delivered correctly. As of yesterday my app was approved and it is currently visible in the App Store.
I put together a small update and am currently working on getting it delivered using Application Loader.
However, now when I upload my production IPA it gets rejected due to what seems like a sdk error.
Messages:
    Apple's web service operation was not successful
    Unable to authenticate the package: 806906410.itmsp
    ERROR ITMS-9000: "This bundle is invalid. Apple is not currently accepting applications built with this version of the SDK." at SoftwareAssets/SoftwareAsset (MZItmspSoftwareAssetPackage)

I'm struggling to figure out what has changed since I am building with the same SDK as I did last weekend.

A: From the February 1st you can use only XCode 5.X and iOS7 SDK to create apps for the AppStore. Double check that you compiled your app with the correct XCode/SDK.
Information about this: https://developer.apple.com/news/?id=12172013a

A: I was hoping your suggestion works but I got the error despite using Air 4.0 SDK. I didn't get this error when I uploaded it to the App Store a few days ago (I was already using Air 4.0 then). Does it really mean that Apple has limited development to using Xcode?
EDIT:
Updating to Air 4.0 SDK does work! But make sure what you have is Air 4.0 SDK for Flex Developers

A: For Flex users with the same error message: you have to download the AIR 4.0 SDK beta from Adobe Lab:
http://labs.adobe.com/downloads/air.html
(for me, it was SDK for Flex, Mac)
Then extract it (sudo tar jxvf air4-0_sdk_sa_mac.tbz2) and overlay it with the Flex SDK as explain in:
http://www.247sw.ca/installing-flash-builder-4-7-and-air-3-5-for-windows-and-mac
Publishing to the AppStore is OK after that.

A: I was facing the same issue, i updated the Air 4.0 SDK, and it works fine! Make sure to update Air 4.0 SDK for Flex Developers. Please set xmlns="http://ns.adobe.com/air/application/14.0" inside --app.xml configuration file.
You can download the latest sdk from http://labs.adobe.com/downloads/air.html.

A: I ran into the same issue, however in my case, the reason was because I had the latest Xcode beta for iOS 8 on my computer. Event I built from Xcode 5.1.1 GUI, the beta compiler was picked. Had to move beta to trash first to make a build for the store.


text:
Q: Load jQuery in PHP page - no head tags This is probably super simple answer, but I just can't figure this out.
Basically, I've got a php page only starting with opening <?php tag.
I've got a jquery script that I need to call on this page.
<script type="text/javascript">
     $('input[name="_manage_item"]').click(function() {
     $('input[name="_item"]')[this.checked ? "show" : "hide"]();
     });
</script>

From what I researched, I need to load the script by placing
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

into the <head> tags of the page.
But my page doesn't have the html <head> or <body> tags. Where do I call the script then ?
I tried to place it in front of the opening <?php tag, but that broke the page.
What is the correct way of doing this ?

A: You can place your javascript outside the php tags at the bottom of you page. But when you use the php in a web page, you should add the html and head and body tags. A simple php page could look like this:
<html>
<head>
  <!-- stylesheets and javascript -->
</head>
<body>
  <?php
    //You php-code
  ?>
  <!-- scripts at the end of the page to let the side load faster -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script type="text/javascript">
   $('input[name="_manage_item"]').click(function() {
     $('input[name="_item"]')[this.checked ? "show" : "hide"]();
   });
</script>
</body>
</html>

A: Relying on your wordpress tag, I suggest you to read this article. There are described all details concerning javascript usage within wordpress. Probably the most common way is to use wp_register_script() function.

The safe and recommended method of adding JavaScript to a WordPress generated page, and WordPress Theme or Plugin, is by using wp_enqueue_script().

I would  also advise you to merge your code to a distinct file, and load it straight after jquery library. It is a good practice, because in such a way browser can cache your script and would not download it on every page request. You should also wrap it into a $( document ).ready() function, to be sure that it will be executed only only when document is in ready state.


text:
Q: Open Windows Phone App In Emulator via Command Line? Is there a way to load a Windows Phone Application into the Windows Phone emulator via the command line? I would like to be able to run Jeff Wilcox's test runner during an automated build. Something along the lines of
"C:\Program Files (x86)\Microsoft XDE\1.0\XDE.exe" "C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.0\Emulation\Images\WM70C1.bin" /project:"path/to/project.xap"

would be the best scenario (the /project parameter doesn't actually exist to my knowledge). The primary issue is not deploying the XAP to the emulator (that's possible via XapDeploy.exe), but rather opening it through the command line.

A: Justin Angel had a post about directly automating, I believe this is all quite unsupported but might be useful: http://justinangel.net/#BlogPost=WindowsPhone7EmulatorAutomation

A: Justin changed the link structure of his page.
New link (if you are too lazy to use the search):
http://justinangel.net/WindowsPhone7EmulatorAutomation

A: It looks like there is now a developer tool installed automatically called XapDeploy, I'm curious if it supports any command-line options.


text:
Q: Why has replacing ng-select with a custom directive caused $http requests not to be sent every other time edit I've now fixed the bug by using ng-click in the directive's template, but I'm still interested to know what ng-click does that's different to element.bind and why it's important
I did have a ng-select box to update my model

<select
  ng-model="tune.dummyStandard"
  ng-options="opt.value as opt.label for opt in dropdowns.playback"
  ng-change="update()" >
  <option value="">-- rate performance --</option>
</select>

At the end of a long validation process, it created a new $http request (via $resource.$update) and saved the record.
I've now changed to use a custom directive

which attaches the following listener (the actual listener is a little more complicated but I've checked quite rigorously that it always fires tune.resource.$update as expected)
element.bind('click', function (ev) {

   // code for validation and setting of model props

   tune.resource.$update();

});

Now odd-numbered clicks create the $http object but don't send, and the even-numbered clicks send the previously created $http object and create and successfully send a new one. This happens consistently even when the clicks are on different instances of the directive. I've tried playing around with $digest and $apply on the scope but they don't have any impact (and I'm not sure if they should as $http seems to me like it should behave independently of the digest cycle).
Can anyone think what the problem might be?
Full directive code
directives.directive('jPerformanceRater', function () {
    return {
    // transclude: true,
        scope: true,
        templateUrl: '/views/directives/performance-rater.html',
        compile: function(element, attrs) {
            return function (scope, element, attrs) {
                var tune = scope[attrs.tune || 'tune'];

                scope.tune = tune.tune;
                element.bind('click', function (ev) {
                    ev.cancelBubble = true;
                    var btn = ev.target.className.indexOf('icon') > -1 ? ev.target.parentNode : ev.target;

                    if (btn.className.indexOf('btn')  === -1) {
                        return;
                    }
                    tune.dummyStandard = +btn.textContent;
                    tune.update(); // most of the validation happens in here and then it calls resource.$update()

                });
                element.addClass('performance-rater');
            };
        }
    };
});

And the template
{{rating.value}}

A: Changing :
element.bind('click', function (ev) {
  tune.resource.$update();
});

to:
element.bind('click', function (ev) {
  scope.$apply(function(){
     tune.resource.$update();
  });
});

should do the trick.
Diference between bind('click') and ng-click is that ng-click triggers angular $digest cycle whereas bind('click') does not.
Any $http or $resource requests trigger request to server only when invoked within angular $digest cycle (internal angular event loop cycle). So in your case you invoked resource.update but outside angular $digest cycle, so request to server wasn't made but only 'scheduled' until next time angular event loop was triggered (for example when ng-change was executed) and request to server was initiated.


text:
Q: Python Fit ellipse to an image I have a webcam feed using OpenCV, and I am trying to fit an ellipse in real time.
The code I am using at the moment works, but it fails to fit an ellipse to the image a lot of the time. What other methods of ellipse fitting to an image can I pursue?
Current code:
def find_ellipses(img): #img is grayscale image of what I want to fit
        ret,thresh = cv2.threshold(img,127,255,0)
        _,contours,hierarchy = cv2.findContours(thresh, 1, 2)

        if len(contours) != 0:
            for cont in contours:
                if len(cont) < 5:
                    break
                elps = cv2.fitEllipse(cont)
                return elps  #only returns one ellipse for now
        return None

Where elps is of the form (x_centre,y_centre),(minor_axis,major_axis),angle
Here is an example of what I want to successfully fit an ellipse to. My current code fails with this image when I don't want it to.

A: Turns out I was wrong is just getting the first ellipse from the function. While I thought the first calculated ellipse was the most correct one, what I actually had to do was go through all the ellipses - and choose the most suitable one that bounded the object in the image.

A: I would define my contours outside of the function, as you don't need to keep re-defining them in this image.
def create_ellipse(thresh,cnt):
    ellipse = cv2.fitEllipse(cnt)
    thresh = cv2.ellipse(thresh,ellipse,(0,255,0),2)
    return thresh

What this code is doing is im taking my thresh image stream and adding an ellipse on top of it. Later on in my code when I want to call it I use the line
thresh = create_ellipse(thresh,cnt)


text:
Q: How can AC source with different voltage provide same power? As some of us maybe aware, USA mains connection is 110 V while those in Asian countries are 220 V. How is it still possible for the Adapter to provide the necessary power to the device, say a laptop, despite having a lower voltage of 110 V at some places.
I understand that the Adapter is built to handle different input AC voltage, but is a 110 V source sufficient to provide the necessary power which a 220 V can.
Perhaps, it doesn't matter for light power consumers such as laptop, but won't High Power demanding home appliances such as Iron, may lack necessary input voltage to operate at maximum level.

A: I think that most people in the world knows that usa has app. 110 V while most(not just asia) of the rest of the world has app. 220 V. see map here http://users.telenet.be/worldstandards/electricity.htm
I believe that your question is asked with a limited back ground knowledge in electricity - and I will try to answer. Please correct me if you really want a technical explanation of how an adapter works.
It takes two things to deliver power to an apparatus - voltage and current. If you think of electricity like a flow of electrons, a river if you will. The voltage will tell you how much pressure there is on the electricity. -and the current tells you how much it is flowing. An adaptor that is build for more than one voltage will automatically adjust the current to deliver the same power. - If the pressure(voltage) drops, the flow(current) will increase.

A: In U.S.A., we have two different voltages available in any residence.  Residential power is 240V from a center-tapped transformer, giving two 120V "legs".  Most of the convenience outlets in a residence will be 120V with a maximum capacity of either 15A or 20A, and you won't find small appliances that pull any more than 1500W (12.5A).
You can find a few window air conditioners that require a 120V/20A outlet, but the majority of smaller ones plug into a 120V/15A outlet and most of the rest plug into a 240V outlet.
Our electric cookers typically plug in to a 240V/50A outlet, and our electric clothes dryers plug in to 240V/30A.  Other stationary equipment (e.g., whole-house HVAC systems, and electric water heaters) typically forego the plug, and are hard-wired to 240V.

Commercial power is a whole other story.  Office buildings and light industrial buildings that are supplied with three-phase power typically will use 277V, single-phase for the overhead lighting, and 480V, three-phase for HVAC, for elevators, and for other stationary machinery.
Heavy industrial buildings may be supplied with other, higher voltages.

won't High Power demanding home appliances such as Iron, may lack necessary input voltage to operate at maximum level?

A clothes iron set to scorch-all-fabrics-quicker-than-you-can-blink uses about a thousand watts.  Our small appliance outlets can handle that.
The performance of portable heaters and electric kettles sold in the U.S.A. however may not be quite up to your expectations if you're from anywhere else.

A: For the most simple electrical devices such as an incandescent lightbulb or a water kettle, which are little more and a resistance, they will draw a quarter as much power if the voltage is halved, since $V^2/R$.
This will probably mean that their operation is unsatisfactory: much dimmer or much slower to heat up.  Things are slightly more complicated for an iron which is typically regulated using a thermostat.
This is why suppliers rate their appliances. The reverse of doubling the voltage can be dangerous as the power may be four times than the equipment is designed to take.
You should either use equipment designed and labelled for the local voltage or use a transformer.

A: It depends greatly on what you are using. A 15 Amp circuit in Asia, running at a full 15 Amps through some appliance is using 3300 watts, while in the US is using half of that. So, high-power appliances (toasters, microwaves) can't simply be plugged in to the wrong voltage.
That said, most small appliances do not draw the entire 15 amps that a circuit can handle. A DC power adapter, in particular (like for a laptop or cellphone) is converting higher voltage (and current) AC to low voltage and low current DC. For example, my cellphone charger outputs 5V at 0.7A which corresponds to 3.5 watts, well under the the maximum power a circuit can provide. So, even the 1650W available in 110V-land is more than enough to power the adapter.


text:
Q: $_FILES array empty when uploading PNG from form
I am having some trouble with an image upload on my website. I have an upload page that lets people upload entries into a handbook. But when I upload an image, the $_FILES array is empty. I have:

*

*Checked that upload is on

*Adjusted maximum size allowed to 20M

*Added enctype="multipart/form-data"

*Checked the size of the image (it is 38KB)

*Made sure I used the name attribute

*Changed permissions of temp folder to 777

*Made sure I used POST

*Checked that I have enough space available (20GB is available)

*Other things that can be seen in the code

*I adjusted the code, and submitting without an image fills $_FILES with empty values as expected.

I have uploaded the output of phpinfo() on my server here.
Nothing has helped, wherever I looked.  Note that I am running this on my local machine, a Mac (10.11.4) with Apache 2.4.18 and PHP 5.5.31.
I used the answer to Why would $_FILES be empty when uploading files to PHP? to check these things.
Here is the code:
Upload page (upload.php):
<?php include "sql.inc"; ?>

        <title>The Emerson Nature Center Official Handbook | Upload</title>
        <link rel="stylesheet" href="page.css" type="text/css">

Upload an entry to the Handbook!

            <form action="upload_page.php" method="POST" enctype="multipart/form-data">

Title: <input type="text" name="title" placeholder="Title" style="font-size: 18pt;" required>

                <input type="hidden" name="author" value="<?php if ($canadd) echo $db->querySingle("SELECT name FROM passwords WHERE id=".$_COOKIE['userid']); ?>">

Author: <?php if ($canadd) echo $db->querySingle("SELECT name FROM passwords WHERE id=".$_COOKIE['userid']); ?>
                <textarea id="styled" width="300" height="300" placeholder="text" name="entry" required></textarea>

Insert images here:

                Image 1 (required): <input type="file" name="image1" accept=".png, image/png" required>

                Image 2 (optional): <input type="file" name="image2" accept=".png, image/png">

                <input type="submit" value="submit">
            </form>

Upload handler (upload_page.php):
<?php
include "sql.inc";
$target_dir = "images/";
$images = scandir($target_dir);
$last_id = ltrim(end($images), "id-");
$last_id = rtrim($last_id, ".png");
$firstid = intval($last_id) + 1;
$target_file = $target_dir . "id-" . $firstid . ".png";
$uploadOk = 1;
$typeAllowed = array("image/png");
echo 'Array:
';
var_dump($_FILES);
//$check = getimagesize($_FILES["image1"]["tmp_name"]);
//if ($check !== false) {
//  $uploadOk = 1;
//} else {
//  echo "The first file you uploaded is not a valid PNG image.";
//  $uploadOk = 0;
//}
if ($_FILES["image1"]["size"] > 500000) {
  echo "Sorry, your first file is too large. Your size was " .     $_FILES["image1"]["size"] . " bytes.";
  $uploadOk = 0;
}
if (exif_imagetype($_FILES['image1']['tmp_name']) != IMAGETYPE_PNG){
  echo 'You can only upload PNG images. (first file) Your type was "' . $_FILES['image1']['type'] . '".';
  $uploadOk = 0;
}
if ($uploadOk == 0) {
  echo "Sorry, your first file was not uploaded.";
// if everything is ok, try to upload file
} else {
  if (move_uploaded_file($_FILES["image1"]["tmp_name"], $target_file)) {
    $uploadOk = 1;
  } else {
     echo "Sorry, there was an error uploading your first file.";
  }
}
if (isset($_FILES['image2'])) {
  $target_dir = "images/";
$secondid = $firstid + 1;
$target_file = $target_dir . "id-" . $secondid . ".png";
$uploadOk = 1;
//$check = getimagesize($_FILES["image2"]["tmp_name"]);
//if ($check !== false) {
//} else {
//  echo "The second file you uploaded is not a valid PNG image.";
//  $uploadOk = 0;
//}
if ($_FILES["image2"]["size"] > 500000) {
  echo "Sorry, your second file is too large. Your size was " .     $_FILES["image2"]["size"] . " bytes.";
  $uploadOk = 0;
}
if (exif_imagetype($_FILED['image2']['tmp_name']) != IMAGETYPE_PNG){
  echo 'You can only upload PNG images. (second file) Your type was ' . $_FILES['image2']['type'];
  $uploadOk = 0;
}
if ($uploadOk == 0) {
  echo "Sorry, your second file was not uploaded.";
// if everything is ok, try to upload file
} else {
  if (move_uploaded_file($_FILES["image2"]["tmp_name"], $target_file)) {
    $uploadOk = 1;
  } else {
     echo "Sorry, there was an error uploading your second file.";
  }
}
}
if (isset($secondid)) $secondid = ",".$secondid;
else $secondid = "";
if ($uploadOk == 1) $db->exec('INSERT INTO handbook (id,title,author,entry,imageids) VALUES (NULL,"'.$_POST["title"].'","'.$_POST["author"].'","'.$_POST["entry"].'","'.$first    id.','.$secondid.'")');
else echo "Your entry was not added.";
header(""); //to send headers to stop redirect
flush(); // ---^
if (!headers_sent()) header("Location: view.php?id=".$db->querySingle("SELECT id FROM handbook WHERE title='".$_POST['title']."'"));
else echo 'Please press the back button on your browser.';
?>

    <title>Uploading...</title>

If you need extra code, logs, or php.ini entries, please tell me, and I will get the code necessary.


text:
Q: What is the benefit of adding YearWeek when year and week exist as separate columns? I'm looking at data model and there is column for date, year, week, yearweek.
Yearweek is concatenation of year and week.
What is the benefit of having the YearWeek column when year and week are available?

A: It can be used for various things. I have one in my table for sorting purposes. e.g. if you wanted to display "Week 3, 2023" in a table or chart as a label, you'd use your column as a sort by column.
It called about be used to simplify weekly time intelligence e.g. create a filter this many weeks in the past which easily crosses year boundaries etc

A: I think it's related to performance as well. If you are adding the column in the database, you are losing performance while creating a table and gaining performance on the report population as the week-year is ready. No need to apply any concatenation on the reporting side. And this is true for the opposite way.
Now it's our decision, where we need better performance.


text:
Q: python- Firestore get() performence issue ├───Users
│   ├───full_name
│   ├───...
│   ├───connected_groups[]

├───Groups
│   ├───name
│   ├───...
│   ├───connected_users[]

Users and Groups are my collections. Users have connected_groups array which holds group reference documents. I need to get details like name, member count etc. of connected groups.
When i use <DocumentReference>.get().to_dict() it takes approximately 500ms for each document reference in connected_groups array. So it takes large amount of time to get all of details :(
Then I duplicated data. But groups have number_of_posts value. When someone posted a new post, I have to update all users connected_groups array in that group. So It will take approximately 25sec to do if there are 50 members in a group.
Are there any way to achieve this?
Update:
screenshot1
screenshot2
nodes=groups in here


text:
Q: Is there a way to pass a php variable to another page using a button (html/php)? For example, say you have a loop that produces a button every time it loops. So if the loop ran five times, there would be 5 buttons. Now say i have a variable like $num which will change each time the loop loops. Is there a way so that each button will pass its individual $num when the button is clicked?
$num = 0;
while(...){
    //want this to send $num via POST or GET to xyz.php
    echo '<button type="submit" value="3" name="editId">Remove</button>';
    $num++;//$num changes every instance of the loop
}

A: The easiest way is to create a <form> surrounding each of the <button> tags:
$num = 0;
while(...){
    //want this to send $num via POST or GET to xyz.php
    echo '<form method="post" action="xyz.php">';
    // Pass $num into the form value
    echo '<button type="submit" value="' . $num. '" name="editId">Remove</button>';
    echo '</form>'
    $num++;
}

Whichever is clicked will be passed to xyz.php as $_POST['editId'].
While this method creates a different form for each button, there are other ways to do it using JavaScript which would use a single form and assign the value to a hidden input based on the button clicked.  If it's only the one input value being sent, the multiple <form>s option is probably easiest to code.

A: The button's name & value should be submitted with the form.
For example:
<?php print_r($_POST); ?>

<form action="" method="post">
    <button type="submit" name="button" value="value">Button</button>
</form>

When the button "Button" is clicked, the form will be submitted and
Array ( [button] => value )

Will be output above the form.
Applying this to your situation, one could use something like:
$num = 0;
while(...){
    // Set $num as the value of each button
    echo "<button type='submit' value='{$num}' name='editId'>Remove</button>";
    $num++;//$num changes every instance of the loop
}

A: You're almost there:
$num = 0; while(...){     //want this to send $num via POST or GET to xyz.php
echo '<button type="submit" value="'.$num.'" name="editId">Remove</button>';
$num++;//$num changes every instance of the loop
}

A: You're very close. Just insert $num into the value attribute of your button.
$num = 0;
while(...){
    //want this to send $num via POST or GET to xyz.php
    echo '<button type="submit" value="'.$num.'" name="editId">Remove</button>';
    $num++;//$num changes every instance of the loop
}

When you surround this code block in <form> tags, clicking the [ Remove ] button would send the value of $num to: $_POST['editId'].


text:
Q: leveldb - numeric indexing and paging I understand that with leveldb you can do ranged queries by key(start, end) but I am wondering if there are any clever ways that one can do a numerically ranged query as you can do with an sql query such using offset and limit?

A: You need to use your key comparator instead of the default in leveldb.  The you can construct a start key by given numeric offset.


text:
Q: Rails 3.1 ssl is used even if I disabled ssl? I have added force_ssl in my ApplicationController, and deleted later, but now, every request is still prompted to https. I have tried to add config.force_ssl = false to all the configuration files in application.rb and environments/development.rb, etc., but it doesn't work. When I reboot the server, the requests are still converted to https. Any clue?
Updates:
This happens only when I request the root of the application, e.g. http://localhost:3000/, however in my config/routes.rb file I have specified the url for the root clearly: root :to => 'home#index'

A: In addition to rebooting your app, you also have to clear the browser cache.

A: You're seeing the effects of HTTP Strict Transport Security's max-age, which is set by Rack::SSL (which config.force_ssl = true sets up) to something high.

A: For those who it's still unclear, here is what I did to do the trick.
In application_controller.rb :
before_filter :expire_hsts

[...]
private
  def expire_hsts
    response.headers["Strict-Transport-Security"] = 'max-age=0'
  end

In production.rb
config.force_ssl = false

Clear the cache of your web browser and that's it !

A: yfeldblum is absolutely correct. Disabling it and making chrome forget the header can be a pain.
Here's what I ended up putting in my config/application.rb
config.middleware.insert_before(Rack::Lock, Rack::SSL, hsts: false, exclude: proc { |env|
  !env['PATH_INFO'].start_with?('/manage')
})

** note A: hsts: false is the critical bit
** note B: I'm using 1.9, so my hash syntax might be different than yours.
Beyond that, I had to open this url in Chrome chrome://net-internals/#hsts and remove the domains that had this header set.
Thankfully this didn't make it to production, because Rack::SSL sets a very long expires on this header.

A: if are you using nginx see option:
proxy_set_header X-Forwarded-Proto https;

and disable it!


text:
Q: AWS RDS connection count I am using AWS RDS with MySQL for a project and have a "large" instance. The documentation is clear on what this means as far as compute resources and RAM goes, but I can't find anything that documents how many open database connections that I can have. The app that I am using is PHP and it utilizes PDO with persistent connections. This means that the number of open connections could reach the maximum number of PHP child processes running at any given point. How do I ensure that my RDS instance has a max connections setting high enough to be comfortable with this?

A: You can always check actual value in AWS console. Open RDS -> DB Parameter Groups, probably you have only one parameter group there, e.g. default.mysql5.5. Then, check max-connections parameter. In my case it is {DBInstanceClassMemory/12582880}, ie ~50 connections for micro instance, ~150 for small etc.

A: From RDS Console > Parameter Groups > Edit Parameters,
You can change the value of the max_connections parameter to a custom value.

A: According to this 2011 blog post, the max connections on RDS instances come out this way:
t1.micro: 34 connections ($0.035)
m1.small: 150 connections ($0.115)
m1.large: 640 connections ($0.455)
m1.xlarge: 1263 connections ($0.920)
m2.xlarge: 1441 connections ($0.655)
m2.2xlarge: 2900 connections ($1.315)
m2.4xlarge: 5816 connections ($2.630)

No AWS docs I can find demonstrate this information is current, but other sources suggest if it isn't, it's very close. You can find your instances max connections with:
show variables like '%conn%';

from the mysql terminal, or via an SDK.

A: We can change the limit but the connection is not extending for RDS instance type t3.medium. Max 100 connections are there. After that web server goes down. Can anyone suggest to increase the connection limition?


text:
Q: Limiting Hive 1.2.1. (HDInsight 3.6) to running only SELECT queries I have the following version stack that I am using to run Hive:-

*

*HDInsight 3.6

*Hadoop 2.7

*Hive 1.2.1

Is there any way I can create an HDInsight cluster against the same Hive Metastore but it will only allow SELECT queries and nothing else (no insert/overwrite/drop , no alter table commands etc). All the other clusters using that shared metastore should continue to have regular access.

A: There is no such specific utility/interface to achieve that. If I understand your concern correctly, your Metastore is shared between clusters and you want to have only select query access for a specific cluster. If your tables are not scattered or it's inside a specific database then this should work smoothly. Did you check on the access part providing only view access to all the users which will prohibit them to alter or run DML statements? Have a look at this link-https://docs.cloudera.com/HDPDocuments/HDP2/HDP-2.6.5/bk_security/content/user_access_hive_db_tables_cmd_line.html  You can also make use of Apache Ranger if yours is an ESP cluster-
https://learn.microsoft.com/en-us/azure/hdinsight/domain-joined/apache-domain-joined-run-hive#create-ranger-policies

Note: I didn't focus on the specific versions, you can test it out
Hope this helps


text:
Q: Can I create a configuration file for a shell script? Is it possible to create a .sh shell or .command file with a configuration file?
I need to backup websites via Terminal and be able to put some data to configuration files,
and have the shell execute it.
For example, the username, password, ssh id, et cetera.
#!/bin/bash
ssh admin@host.com "tar cjvf webfilesbackup-date-`date +%Y%m%d`.tar.bz2 public_html/"
ssh admin@host.com "mysqldump -u user_admin -ppass database_1 > databasebackup-`date +%Y%m%d`-db.sql"
scp admin@host.com:webfilesbackup-date-`date +%Y%m%d`.tar.bz2 ~/backup/
scp admin@host.com:databasebackup-`date +%Y%m%d`-db.sql ~/backup/
ssh admin@host.com "rm -f webfilesbackup-date-`date +%Y%m%d`.tar.bz2"
ssh admin@host.com "rm -f databasebackup-`date +%Y%m%d`-db.sql"

A: Create a file (e.g. settings)  with your settings as variables:
username='foo'
pass='bar'
website='baz'
database='yak'

Then source the file from your script and you will be able to access the variables:
. settings
echo $username     # <- this will print "foo"

Concerning your second "question", if you have multiple hosts you can just have multiple config files and source the one passed as an argument to your script. For example, create a config file called site1.
Call your script with ./backup.sh site1
. $1               # <- this will load the file "site1"
echo $username     # <- this will print "foo"

With your backup script, this would mean:
#!/bin/bash
. $1
ssh admin@host.com "tar cjvf webfilesbackup-date-`date +%Y%m%d`.tar.bz2 public_html/"
ssh admin@host.com "mysqldump -u $user -p$pass $database > databasebackup-`date +%Y%m%d`-db.sql"
# ... and so on

A: The other option is just to create a text file and use a while loop to access that file line by line.

A: mkdir -p Example.app/Contents/MacOS`
cp script.sh Example.app/Contents/MacOS/Example

...and that will work.  This article has more detailed instructions, including how to get custom icons.
You might also look to Automator or AppleScript Studio as ways to build applications that can run sanely, without having to do it by hand.

A:      # parse the ini like $0.hostname.conf and set the variables
     # place a $0.`hostname -s`.conf file in the same dir as your script
     # set here any VarName=VarValue
     # use ; for comments - you will get host independant conf file
     # for your bash scripts - [examle usage :][1]
     doParseIniFile(){
        eval `sed -e 's/[[:space:]]*\=[[:space:]]*/=/g' \
            -e 's/;.*$//' \
            -e 's/[[:space:]]*$//' \
            -e 's/^[[:space:]]*//' \
            -e "s/^\(.*\)=\([^\"']*\)$/\1=\"\2\"/" \
           < $IniFile \
            | sed -n -e "/^\[$IniSection\]/,/^\s*\[/{/^[^;].*\=.*/p;}"`
     }
     #eof function doParseIniFile


text:
Q: A confusion in an ARM assembly instruction My question about a simple instruction code of an ARM micro-controller.
LDR R2, [R1]
In the above instruction I interpret it as: R1 a RAM memory register and R2 is a processor register. What I understand from this was R1 represents the memory content in RAM and R2 is a processor register. So it says: Go to the address of R1 in RAM memory and load its contents to the processor's R2 register. Is that right? R1 is in RAM but R2 is in processor?

A: Your wording is weird, so I can't decide whether you have the correct interpretation or a wrong one.
Physically, all ARM registers are in the CPU. They hold (32 bit) values. In the instruction you ask about the value in R1 is used as a memory address. The value at that address in memory (and the next 3 addresses, because the memory is byte-addressed and the LDR loads 32 bits) is loaded into register R2.
This is the sheet from my ARM assembler course that illustrates this instruction. It is partly in Dutch, and covers the more general case where an offset is applied to the R1 value.
The green block at the left is the CPU with its registers, the enclosing yellowish block is the microcontroller, which contains both the CPU and the (RAM) memory.


text:
Q: Undo drawing in Paint Application I am making a paint application using OpenGl framework and I'm stuck at UNDO/REDO option..
The code I implemented is like this:
  -(void)undo_called
{

artbrushAppDelegate *app=(artbrushAppDelegate *)[[UIApplication sharedApplication]delegate];
mbrushscale=app.brushscale;
brushimage=app.brush_image;
Erase=YES;
[self playRayundo];
 }

-(void)playRayundo
{
artbrushAppDelegate *app=(artbrushAppDelegate *)[[UIApplication sharedApplication]delegate];
glColor4f(app.r1g,
          app.b1g,
          app.g1g,
          0);
NSLog(@"%f",app.r1g);

if(undo != NULL)
{
    for(int l = 0; l < [undo count]; l++)
    {
        //replays my writRay -1 because of location point
        for(int p = 0; p < [[undo objectAtIndex:l]count]-1; p ++)
        {
            [self drawErase:[[[undo objectAtIndex:l]objectAtIndex:p]CGPointValue] toPoint:[[[undo objectAtIndex:l]objectAtIndex:p + 1]CGPointValue]];
        }
    }
}

Erase=NO;
glColor4f(app.rg,
          app.bg,
          app.gg,
          kBrushOpacity);

  }

 -(void) drawErase:(CGPoint)start toPoint:(CGPoint)end

 {
    static GLfloat*     eraseBuffer = NULL;
    static NSUInteger   eraseMax = 64;

NSUInteger          vertexCount = 0,
count,
i;

[EAGLContext setCurrentContext:context];
glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);

// Convert locations from Points to Pixels
CGFloat scale = 1.0;//self.contentScaleFactor;
start.x *= scale;
start.y *= scale;
end.x *= scale;
end.y *= scale;

// Allocate vertex array buffer
if(eraseBuffer == NULL)
    eraseBuffer = malloc(eraseMax * 2 * sizeof(GLfloat));

// Add points to the buffer so there are drawing points every X pixels
count = MAX(ceilf(sqrtf((end.x - start.x) * (end.x - start.x) + (end.y - start.y) * (end.y - start.y)) / kBrushPixelStep), 1);

for(i = 0; i < count; ++i)
{
    if(vertexCount == eraseMax)
    {
        eraseMax = 2 * eraseMax;
        eraseBuffer = realloc(eraseBuffer, eraseMax * 2 * sizeof(GLfloat));
    }

    eraseBuffer[2 * vertexCount + 0] = start.x + (end.x - start.x) * ((GLfloat)i / (GLfloat)count);
    eraseBuffer[2 * vertexCount + 1] = start.y + (end.y - start.y) * ((GLfloat)i / (GLfloat)count);
    vertexCount += 1;
  }

  [self ChangebrushPic:brushimage];

 //the erase brush color  is transparent.

glEnable(GL_POINT_SPRITE_OES);
glTexEnvf(GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, GL_TRUE);
glPointSize(64/mbrushscale);

// Render the vertex array

glVertexPointer(2, GL_FLOAT, 0, eraseBuffer);
glDrawArrays(GL_POINTS, 0, vertexCount);

// Display the buffer
glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
[context presentRenderbuffer:GL_RENDERBUFFER_OES];

// at last restore the  mixed-mode
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

 }

This code is not efficient and it has so many faults..Have a look at images before and After Undo.
Before: http://imageshack.us/photo/my-images/577/screenshot20110714at121.png/
After: http://imageshack.us/photo/my-images/200/screenshot20110714at121.png/
So i want to Save image in buffer every time user's Touch ends and call previous image on UNDO..Can anyone help me how to Store image in buffer and retrieve back on UNDO?? I tried to find its sample code but could not find..
Thanks..

A: Ok. I am posting answer to my own Question as so many people seem to refer this question.
There is an application named TouchPainter and its source code is available. It contains drawing, color blending, Undo/Redo (Amazing..!!), Save/Open drawings..
Note : It may require very deep level knowledge of Objective C and design pattern (I still do not know what design pattern is. But I found it so I am sharing..). The whole application's source code is explained in this book "Apress.Pro Objective-C Design Patterns for iOS".
I hope it will be helpful to you.. :) Good luck..

A: use the nsundomanager, that is the best way to undo

A:         Hope this may be help u..

This code for UIBezierPath Drawing.

    -(void)undoButtonClicked
        {
            if([pathArray count]>0){
                UIBezierPath *_path = [pathArray lastObject];
                [bufferArray addObject:_path];
                [bufferColorArray addObject:[PathColorArray lastObject]];
                [pathArray removeLastObject];
                [PathColorArray removeLastObject];
                [bufferDrawType addObject:[pathDrawType lastObject]];
                [pathDrawType removeLastObject];
                [bufferDrawOpacity addObject:[pathDrawOpacity lastObject]];
                [pathDrawOpacity removeLastObject];
                [bufferDrawLineWidth addObject:[pathDrawLineWidth lastObject]];
                [pathDrawLineWidth removeLastObject];

                [self setNeedsDisplay];
            }
        }

        -(void)redoButtonClicked
        {
            if([bufferArray count]>0){
                UIBezierPath *_path = [bufferArray lastObject];
                [pathArray addObject:_path];
                [bufferArray removeLastObject];
                [PathColorArray addObject:[bufferColorArray lastObject]];
                [bufferColorArray removeLastObject];
                [pathDrawType addObject:[bufferDrawType lastObject]];
                [bufferDrawType removeLastObject];

                [pathDrawOpacity addObject:[bufferDrawOpacity lastObject]];
                [bufferDrawOpacity removeLastObject];
                [pathDrawLineWidth addObject:[bufferDrawLineWidth lastObject]];
                [bufferDrawLineWidth removeLastObject];

                [self setNeedsDisplay];
            }
        }


text:
Q: is it possible to create google calendar event in other users instead of adding attendees I am using PHP to create a google calendar event and add attendees, but I want to create, update, delete events in the user's calendar directly.
below is my PHP code which is working fine to insert add event in my gmail clanedar but I am not able to add an event to other users calendars.
 <?php
require  'google/vendor/autoload.php';

function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
    $accessToken = json_decode(file_get_contents($tokenPath), true);
    $client->setAccessToken($accessToken);
}

// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
    // Refresh the token if possible, else fetch a new one.
    if ($client->getRefreshToken()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));

        // Exchange authorization code for an access token.
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
        $client->setAccessToken($accessToken);

        // Check to see if there was an error.
        if (array_key_exists('error', $accessToken)) {
            throw new Exception(join(', ', $accessToken));
        }
    }
    // Save the token to a file.
    if (!file_exists(dirname($tokenPath))) {
        mkdir(dirname($tokenPath), 0700, true);
    }
    file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);

// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
$events = $results->getItems();

$event = new Google_Service_Calendar_Event(array(
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google\'s developer products.',
'start' => array(
'dateTime' => '2021-05-29T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => '2021-05-29T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'recurrence' => array(
'RRULE:FREQ=DAILY;COUNT=1'
),
'attendees' => array(
array('email' => 'example1@gmail.com'),
array('email' => 'example2@gmail.com'),
),
'reminders' => array(
'useDefault' => FALSE,
'overrides' => array(
  array('method' => 'email', 'minutes' => 24 * 60),
  array('method' => 'popup', 'minutes' => 10),
),
),
));

 $calendarId = 'primary';
 $event = $service->events->insert($calendarId, $event);
 printf('Event created: %s\n', $event->htmlLink);

I want to add event direct to example1 and example2 google calendar. it is possible ?.
Thanks in advance

A: I have a feeling you may have just copied this code from somewhere and dont completely understand what it is doing.
Who, what, Where?
When your code is run the very first time.  The user will be presented with a web page asking them to consent to your application accessing their data.
Once the user has consented your event will be inserted into the Primary calendar of that user.
$calendarId = 'primary';

All users have one calendar that is set to primary, besides that they can create different calendars but you have chosen to insert it into their primary calendar.
So the event will be inserted into the primary calendar of the user who authncates.
Who is the user.
Your code is requesting something called offline access.
$client->setAccessType('offline');

This means that you are asking the user to let you access their calendar when they are not present.  Or offline.  This would work for example if you want to automatically add events to users calendars for say meetings or something.
What it actually does is return to you a refreshToken, refresh tokens are an Oauth2 thing which will give you the ability to request a new access token when ever you need to access the users data, this being their calendar.  With a refresh token you can do the following which will cause the client to load itself a new access token.
$client->fetchAccessTokenWithRefreshToken([refreshtoken]);

Which you do apear to be doing to some extent.
The thing is that you will need to have each user whos calendar you wish to access to authorize your application at least once and save the refreshtoken in the database or in a file of some kind in order to keep track of which refresh token belongs to which user.
Currently your code is only storing one user
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
    $accessToken = json_decode(file_get_contents($tokenPath), true);
    $client->setAccessToken($accessToken);
}

.....

 // Save the token to a file.
    if (!file_exists(dirname($tokenPath))) {
        mkdir(dirname($tokenPath), 0700, true);
    }

The first time your code runs its going to request access then its going to save the token file without defining which user it is and then it will just load that file from now on.  Your current code is single user.  This is what you will need to change if you want other users to run your application so that you can store their refresh tokens and write to their calendars as well.

A: If you want to create, update or delete events on other user's calendars.
You'll need to ask the owner to turn on the Make changes and manage sharing permission on their calendar.

*

*On your computer, open Google Calendar. You can't share calendars from the Google Calendar app.

*On the left, find the "My calendars" section. You might need to click it to expand it.

*Hover over the calendar you want to share, click More More and then Settings and sharing.
To broadly share it:
Under "Access permissions," check the boxes of the ways you want to share and choose your options in the drop-down menu.
To share with individuals: Under "Share with specific people," click Add people.

*Add the person or Google group email address. Use the drop-down menu to adjust their permission settings.

*Click Send.

*The recipient will need to click the emailed link to add the calendar to their list.
References:
https://support.google.com/calendar/answer/37082?hl=en
https://support.google.com/a/users/answer/37082#permissions

In your case, they need to share their calendar using "Share with specific people".
Here are the permission settings available:
Make changes & manage sharing

*

*Change sharing settings

*Add and edit events

*Find details for all events, including private ones

*Find the time zone setting for the calendar

*Permanently delete the calendar

*Restore or permanently delete events from the calendar's Trash

*Subscribe to email alerts when events are created, changed, cancelled, RSVPed to, or coming up

Make changes to events

*

*Add and edit events

*Find details for all events, including private ones

*Find the time zone setting for the calendar

*Restore or permanently delete events from the calendar's Trash

*Subscribe to email alerts when events are created, changed, cancelled, RSVPed to, or coming up

Find all event details

*

*Find details for all events except those marked as private

*Find the time zone setting for the calendar

*Subscribe to email alerts when events are created, changed, cancelled, RSVPed to, or coming up

Find only free/busy (hide details)

*

*Check when your calendar is booked and when it has free time, but not the names or other details of your events.

Once you were able to gain the required calendar permission, you can now create, update and delete events using the Google Calendar API.
For more details regarding the Calendar Events Methods please refer here:
https://developers.google.com/calendar/v3/reference#Events
Example:
I shared a calendar to User1 Test with the following configuration:

Then I created an event using the Calendar API using User1 Test account, using Events:insert method based on the calendar's id that was shared.

*

*Notice that in the event that was created, it indicates that the event was created by User1 Test.

In your code, you are creating events on your currently logged in user with the use of 'primary' keyword.
If you want to create events on other user's calendars, you need to replace the calendar id based on the calendar that you want to modify.
You can view the calendar id in the calendar's settings and sharing.
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';


text:
Q: In Entity Framework is it more efficient / preferred to create projections rather than selecting full entities? I am working on an application, trying to improve performance. Obviously I will be doing my own profiling and testing, but I would like to know if there is a "consensus" or known best practice.
In the old SQL days, one of the main things to do to improve efficiency was to not select data you aren't going to consume. I'm trying to go down that route with EF6.
In this particular case, I have a master-detail-detail relationship where I need to render some data about the parent, child, and grandchild on the screen.
My application is n-tier with an MVC front end, and a web-api REST backend. These entities are ultimately going to be serialized as JSON, sent over the rest connection back to the MVC controller, where they will be rendered to the screen. In this case I will not be updating the entities from this flow, so I don't need to worry about merging partial entities back into the repository (in those cases, I would probably send over the full entity for ease of maintenance)
So, the original straightforward EF code I wrote looks like this
Repository.GetAll()
          .AsNoTracking()
          .Include("Children")
          .Include("Children.GrandChildren")
          .ToList();

However, I am only actually consuming a subset of the  properties of these entities, and some of the unused properties can be rather large (big chunks of XML, etc)
Here is a first pass at trying to project out only the fields I need (for the example here, I have cut out and renamed most of the fields I would actually select to improve readability, but in general I'm using lets say 5-20% of the full entities)
var projection = Repository.GetAll()
            .AsNoTracking()
            .Select(r => new
            {
                r.Id,
                r.RandomId,
                r.State,
                r.RequestType,
                r.CreatedDate,
                r.CreatedBy,
                Children = r.Children.Select(r2 => new
                {
                    r2.Id,
                    r2.Status,
                    GrandChildren = r2.GrandChildren.Select(r3 => new
                    {
                        r3.Id,
                        r3.Status,
                        r3.GrandChildType
                    })
                }),
            }
            ).ToList();

This is obviously using anonymous types (I believe this is required in EF there is not a way to project into a named type?) (edit : apparently you can project into a non-mapped named type, but in this case, the return type of the query is a mapped type. So I could create a DTO, but that's even more code to maintain)
so then I have to get back into my concrete types. I could certainly generate DTOs that only had the properties needed, but I don't think that changes the fundamental logic used, nor probably the performance characteristics.
I tried my standbys of Automapper and ValueInjecter, but neither one seemed to fit the bill perfectly here (deep clone of heterogeneous types with matching names) so I went dirty
var json = projection.Select(JsonConvert.SerializeObject).ToList();

var mapped = json.Select(JsonConvert.DeserializeObject<Parent>).ToList();

This is somewhat lame since its just going to be serialized again as part of the rest call. There is probably a way I can override the webAPI calls to say I am returning the already serialized data, which would let me skip the rehydration into the entity type (as all of the property names match, the rest client should be able to rehydrate the anonymous type as if it were the real type, the same way the snippet above does)
BUT all this seems like a lot of work, less maintainable code, more possible places to have bugs, etc for a use case that entity framework really does not seem to want to support. But my old school instincts can't let go of the idea that I'm selecting, serializing, and transferring a whole lot of data that ultimately I'm not going to consume.
Does this produce sane SQL under the covers? Is that worth the double serialization? (assuming I don't figure out how to override webapi to let me hand it the data)
I suppose my other choice would be to refactor all the entities so that the unused properties are in different sub entities that I can just not include, but that would be a lot of rework throughout the system (versus being able to surgically improve performance at critical points) and it also seems like a poor choice to design entities around the ORM I happen to be using vs standard normalization rules etc.

A: you can project into named types.
var projection = Repository.GetAll()
        .AsNoTracking()
        .Select(r => new ParentModel()
        {
            Id = r.Id,
            RandomId = r.RandomId,
            State = r.State,
            RequestType = r.RequestType,
            CreatedDate = r.CreatedDate,
            CreatedBy = r.CreatedBy,
            Children = r.Children.Select(r2 => new ChildModel()
            {
                Id = r2.Id,
                Status = r2.Status,
                GrandChildren = r2.GrandChildren.Select(r3 => new GrandChildModel
                {
                    Id = r3.Id,
                    Status = r3.Status,
                    GrandChildType = r3.GrandChildType
                })
            }),
        }
        ).ToList();

but yes it does make sense to not include fields you're not going to need.
lately when using the DTO approach or Models.. i'll add a static Func to my model and use that in my context projections.. In your case it would look something like
public class ParentModel
{
    public int Id { get; set; }
    public int RandomId { get; set; }
    public string State { get; set; }
    public List<ChildModel> Children { get; set; }
    public static Func<Parent, ParentModel> Project = item => new ParentModel
    {
        Id = item.Id,
        RandomId = item.RandomId,
        State = item.State,
        Children = item.Children.Select(ChildModel.Project)
    };
}
public class ChildModel
{
    public int Id { get; set; }
    public int Status { get; set; }
    public string State { get; set; }
    public List<GrandChildModel> GrandChildren { get; set; }

    public static Func<Child, ChildModel> Project = item => new ChildModel
    {
        Id = item.Id,
        Status = item.Status
        GrandChildren = item.GrandChildren.Select(GrandChildModel.Project)
    };
}
public class GrandChildModel
{
    public int Id { get; set; }
    public int Status { get; set; }
    public int GrandChildType { get; set; }
    public static Func<GrandChild, GrandChildModel> Project = item => new GrandChildModel
    {
        Id = item.Id,
        Status = item.Status,
        GrandChildType = item.GrandChildType
    };
}

then your projection code would just look like
var projection = Repository.GetAll()
      .AsNoTracking()
      .Include("Children")
      .Include("Children.GrandChildren")
      .Select(ParentModel.Project)
      .ToList();

A: Use table splitting which allows you to split a table into more than one entity without modifying the underlying table. The "less accessed" properties can be lazy loaded on demand or loaded eagerly, behaving as any other navigation property. Note the key here is that the additional entities use their pk as the fk to the primary entity

A: Of course, projects are better. There are two approaches,
Use DTO or Split Tables
Problem is, too much to code and too much to manage, however this is better approach as you can visualize all entities and refactor them easily when needed.
Or use a separate DbContext with limited model just as Readonly context.
Dynamic DTO Proxy
Instead, in ASP.NET MVC, I created a REST proxy layer, which allows me to dynamically query without creating too many DTOs (Data Transfer Objects). In my approach, I had created a query like,
/app/entity/message/query
    ?query={UserID:2}
    &orderBy=DateReceived+DESC
    &fields={MessageID:'',Subject:''}
    &start=10
    &size=10

query expects anonymous object as filter, here are more examples

Here, I am passing required fields in query string, in this design, my API layer creates a projection by using Reflection and Expression API. This is kind of complex. But this allows me to not create many permutations and combinations.
Source code is here, https://github.com/neurospeech/atoms-mvc.net
However, this code was used to create Entity Framework like context in JavaScript, which would then load related navigation properties asynchronously as a separate query but once again with limited fields.
There is a class LinqRuntimeTypeBuilder.cs which contains source code to build type dynamically that can be used in query. https://github.com/neurospeech/atoms-mvc.net/blob/master/src/Mvc/LinqRuntimeTypeBuilder.cs
This approach is little longer, as it requires setting up "Firewall" against entities to control access.

A: You might be interested in the Command-Query Responsibility Segregation (CQRS) approach, where you have one model for the write side and multiple separate query models tailored for your reads. The write model will typically reflect a single entire EF entity, while the read models are any projections and aggregations of data from as many entities as you want.
Yes that means there will be multiple read model DTO's with just the properties you need in them, but it's much better in terms of consistency and expressiveness than sending client code a big bag of data and letting it cherrypick what it wants IMO.