text:
Q: Give a name to localhost with specifying a port I am using xammp on windows. I change my port number as 8090 but now I couldnt reach the localhost when I type example.com to the browser. What should I do to make any name to open my localhost even if the port is not 80. Or moreover I
127.0.0.1 example.com
Thank in advance,

A: You can't, you have to expressly state the changed port at the client end.
DNS is purely for IP resolution, it doesn't deal with port numbers at all, that's a client-side assumption that's built into your various client applications.
So for instance you'd use your browser to point to example.com:8090 - there's no other way for the client to know that you've changed the port.
By the way, please read our FAQ, this site's for professional sysadmins, be aware of our sister site superuser.com which is perhaps more appropriate for very basic general questions such as this.

A: You can't.
If you don't provide a port number in your web browser, it'll automatically use the well-known ports for HTTP (80/tcp) or HTTPS (443/tcp), depending on the URI you've entered.
If you don't use the well-known ports for your web server you'll have to enter them explicitly.

A: It is absolutely unclear what you are asking!
If you set your Apache to listen on 8090 then it listens on that port (and probably not on any other). So you have to put http://127.0.0.1:8090/ or http://localhost:8090 in your webbrowser.
When you now put a line as

127.0.0.1 localhost example.com

in your hosts file, then you can reach your site with http://example.com:8090/, too.
But you always have to specify the port. Otherwise it won't work!


text:
Q: Calculate new point offset based on angle of rotation? I am working on an application for the past few weeks which involves some trigonometry and am currently stuck.  As shown in the diagram below, I have a circular item (green circle at position #1) which I know the center point (let's call that X1,Y1).  The circle has another point (orange circle) that is off-centered a bit - midway between two other marks (blue circles).  These marks can move around.  The coordinates of the orange point are calculated (let's call it X2, Y2) and the angle of the blue line is calculated (call it Angle) in relation to the horizontal of the circle.

I can calculate the difference between the center of the circle and the point by:
deltaX = X2-X1
deltaY = Y2-Y1
I need to move and rotate the green circle (either CW or CCW - whichever is shorter) from it's start location (position 1) over to position 2.  This means the angle could be negative or positive.  The blue line must end up vertical and the orange dot at the center of position 2 (red square).  I know the coordinates for the center of position 2 (let's call this point X3,Y3). Position #1 and position #2 are exactly 90 degrees from each other.
I thought I could use some trig identity formulas that calculate the rotation of a point, as such:
offsetX = deltaX * cos(90-Angle) - deltaY * sin(90-Angle)
offsetY = deltaX * sin(90-Angle) + deltaY * cos(90-Angle)
I was hoping these offsets would be what I need to adjust the circle to it's new center when it moves/rotates over to position 2.
X3 = X3 + offsetX
Y3 = Y3 + offsetY
However, when I try use this math, it's not placing the orange mark of the circle in the center of the square.  Not sure if my equations and calculations are correct based on the angle of rotation (positive or negative, CW or CCW) or if I'm using the angle correctly (where I subtract the known angle from 90 degrees).  How do I correctly calculate the final point/position?  Any help and examples would be greatly appreciated!
Thank you very much for your time!

A: So you need to rotate your circle by 90 - Angle and then move orange point to (X3, Y3)?
First you need to find orange point coordinate after rotation:
newX = X2 * cos(90 - Angle) - Y2 * sin(90 - Angle);
newY = X2 * sin(90 - Angle) + Y2 * cos(90 - Angle);

newX and newY are orange point coordinates after rotation. To find move transformation simply substract:
moveX = X3 - newX;
moveY = Y3 - newY;

Now if you rotate circle by 90 - Angle and move it by (moveX, moveY) orange point will move to (X3, Y3). That is if you rotate circle around (0, 0) point. If you rotating around some (X, Y) point, you first need to substract X from X2, Y from Y2 and then add X to newX, Y to newY. That substraction 'moves' your rotation base point to (0, 0), so after rotation you need to move it back:
newX = (X2 - X) * cos(90 - Angle) - (Y2 - Y) * sin(90 - Angle) + X;
newY = (X2 - X) * sin(90 - Angle) + (Y2 - Y) * cos(90 - Angle) + Y;

A: Be aware that your code is using a counter clockwise rotation, (conventionally angles are measured counter clockwise) which may be why you're not getting the results you expect. if you want a clockwise rotation try:
offsetX = deltaX * cos(angle) + deltaY * sin(angle)
offsetY = -deltaX * sin(angle) + deltaY * cos(angle)

Ensure your angles are in radians not degrees.
Drawing some lines may help you debug things too.

redpajama_set_name: RedPajamaStackExchange


text:
Q: T4 Templates - SubSonic 3 - Running at Build Time How do you get the SubSonic 3 T4 templates to rerun prior to building in VS2008?
I don't have to continually "Run Custom Tool" on each one?

A: Dupe: How to get t4 files to build in visual studio?
Oleg is the T4 guru, so his answer is probably as good as you'll get.


text:
Q: An error happened during template parsing (template: "ServletContext resource [/WEB-INF/views/hello_world.html]") (Spring MVC + Thymleaf) Вот контроллер
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("/hello-world")
    public String sayHello(){
        return "hello-world";
    }
}

Вот класс конфигурации контекста
@Configuration
@ComponentScan("com.rusned.mvc")
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {
    private final ApplicationContext applicationContext;

    @Autowired
    public SpringConfig(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(applicationContext);
        templateResolver.setPrefix("/WEB-INF/views/");
        templateResolver.setSuffix(".jsp");
        //templateResolver.setTemplateMode("HTML5");
        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        registry.viewResolver(resolver);
    }

}

И html файл
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
Hello world
</body>
</html>

Плюс ко всему идея подсвечивает название html файла, т.е. просто не видит его

Я думаю это связано с проблемой.

A: Как заметил @Chubatiy вам надо разобраться с именем файла. Ошибка Thymeleaf для файла "hello_world.html", но не видит ваш файл потому что в конфигурации у вас суфикс ".jsp", а надо ".html" ...
templateResolver.setSuffix(".html");

TemplateMode почему-то закоментирован, это правильная конфигурация, оставьте её. И добавьте characterEncoding UTF8, потому что вы прописали это в вашем HTML.


text:
Q: Laravel 4: Separate superadmin auth I want to be able to have a separate login mechanism for admin users than our regular users. Authentication for general users is the default Laravel way. Using a users table and user model.
For our internal admin section (superadmin), I would prefer to use basic http authentication and not use the users table but no table at all or a new superadmins table containing only the users that can login to the superadmin.
What would be the best approach? Is there some way to hardcode a few superadmin login credentials or would a superadmins table be required? I was thinking of writing a custom auth driver but how would I load a custom auth config file only for the superadmin section? Preferably the custom auth driver would use a different cookie name as our superadmin users need to be able to login as users without constantly needing to re-login to the superadmin.

A:
Preferably the custom auth driver would use a different cookie name as our superadmin users need to be able to login as users without constantly needing to re-login to the superadmin.

This doesnt make sense. You cant be logged in as two different users at the same time, regardless how you set your cookies. You need some way to 'switch' between them.
Personally I think your making this too hard. Just have a column "superuser" in your users table. Then after you login the normal way - you can do something like
Filters.php
Route::filter('auth.superuser', function()
{
    if ( ! (Auth::user()->isSuperUser())) return Redirect::to('/');
});

Then in your routes file:
// Normal routes here
Route::get('/', ['uses' => 'FrontController@showHomePage']);

Route::group(['before' => 'auth.superuser'], function ()
{
     // Superuser routes here
}

Edit - if you want to allow them to 'switch' between SuperUser and another userAlso - then do something like this:
function login()
{
      // login code here
      if Auth::user()->isSuperUser()
      {
          $cookie = Cookie::forever('superuser', 'really_long_secret_token');
          // Return with redirect AND cookie
      }
}

Then in your dashboard, or whereever - you can do:
@if (Cookie::get('superuser') === 'really_long_secret_token')
        Show superuser switch option here
@endif

That will work regardless if they are currently logged in as a superuser or not - because the cookie on the computer gives them the ability to switch to superuser whenever


text:
Q: Expense account is coming blank in view accounting (Payment Invoice) in oracle apps Expense account is coming blank in view accounting (Payment Invoice) in oracle apps.
When I checked the view journal entry, I can see one error saying "Code combination is not valid".
I just need an information like from where I can get the expense account which is causing this issue.
I have below information with me:

*

*Payment Invoice

*Purchase Order number


text:
Q: Trim and return any type i've developed this basic method which i hoped would be able to trim and return any type:
public static object TrimValue<T>(T arg, int MaxLength)
{
    var val = arg.ToString();

    var trimVal = val.Substring(0, MaxLength);

    return Convert.ChangeType(trimVal, arg.GetType());
}

Use:
    double aDouble = 1000;

    double cDouble = TrimValue(aDouble, 2);

Unfortunately i get the error:

cannot implicitly convert type 'object' to 'double'

A cast would work but i might be trimming a Double, String or Int so that wont work. Does anyone have any idea how to trim a generic value?
Thanks

A: Your return type is not correct,instead of returning object change it to return the specific generic type passed by the caller using T:
public static T TrimValue<T>(T arg, int MaxLength)
{
    var val = arg.ToString();

    var trimVal = val.Substring(0, MaxLength);

    return (T)Convert.ChangeType(trimVal, arg.GetType());
}


text:
Q: Windows Server backup D: volume access denied error The problem:
When running a full server backup to NAS share, C: partition is backed up correctly, but at some point during backing up D: partition (around 300 GB out of 490 GB) if fails with access denied for volume D:
What I tried:
Took ownership of the volume, tried backing up only D: volume and still fails with same symptoms
Ran the backup with no one in the network except server and NAS, same problem occurs
Details:
Windows Server 2008 SP1
VSS is active and there is around 11 GB System Volume Information folder that i cannot take ownership of because it is a system folder
There are 5 folders in the drive, two folders on the volume are shared to domain users and the rest are shared to administrators group
I'm pretty sure that there is a permissions issue somewhere but my problem is that the failure doesn't leave any trace in the Event Log where to look for it or at least how to narrow it down.
Any help and ideas are greatly appreciated!

A: In order to reach the NAS you had to put a system account into Windows Backup. Is this a privileged account?Can it reach C:, D:, and the NAS?
You should try to back it up through command line, on a local (might be usb) drive, using the local system account.
Use the wbadmin command, use this link for the syntax. Prevent the -quiet parameter. Take a look at the output. If it still fails, I don't think it's a permission related issue, as Windows Backup ran through the local service should be able to access anything locally. You may probably have some kind of filesystem related issue.
You may try a full read scan of D: in order to confirm every sector of your D: drive is actually readable. If you'll get an error on such test, you'll not be able to backup such drive entirely. Try a per-folder backup then, until you fix the drive(s)/filesystem of D:.
Running wbadmin manually can help you troubleshoot the issue.
I won't put command syntax on the answer, as I encourage people to make their own research, and in this case wbadmin usage is widely documented in every language.


text:
Q: How to order a string column by a concrete order For example, I have the typical dataframe:
library(tidyverse)
my_data <- as_tibble(iris)
my_data

# A tibble: 150 × 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          <dbl>       <dbl>        <dbl>       <dbl> <fct>
 1          5.1         3.5          1.4         0.2 setosa
 2          4.9         3            1.4         0.2 setosa
 3          4.7         3.2          1.3         0.2 setosa
 4          4.6         3.1          1.5         0.2 setosa
 5          5           3.6          1.4         0.2 setosa
 6          5.4         3.9          1.7         0.4 setosa
 7          4.6         3.4          1.4         0.3 setosa
 8          5           3.4          1.5         0.2 setosa
 9          4.4         2.9          1.4         0.2 setosa
10          4.9         3.1          1.5         0.1 setosa
# … with 140 more rows

I just want to reorder the dataset by the column "Species" (which has 3 values: setosa, virginica and versicolor), specifying an exact order of rows. For  example: virginica, then setosa, then versicolor.

A: You can use arrange and match:
library(dplyr)

iris %>%
  arrange(match(Species, c("virginica", "setosa", "versicolor")))

#>     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
#> 1            6.3         3.3          6.0         2.5  virginica
#> 2            5.8         2.7          5.1         1.9  virginica
#> 3            7.1         3.0          5.9         2.1  virginica
#> 4            6.3         2.9          5.6         1.8  virginica
#> 5            6.5         3.0          5.8         2.2  virginica
#> 6            7.6         3.0          6.6         2.1  virginica
#> 7            4.9         2.5          4.5         1.7  virginica
#> 8            7.3         2.9          6.3         1.8  virginica
#> 9            6.7         2.5          5.8         1.8  virginica
#> 10           7.2         3.6          6.1         2.5  virginica
#> 11           6.5         3.2          5.1         2.0  virginica
#> 12           6.4         2.7          5.3         1.9  virginica
#> 13           6.8         3.0          5.5         2.1  virginica
#> 14           5.7         2.5          5.0         2.0  virginica
#> 15           5.8         2.8          5.1         2.4  virginica
#> 16           6.4         3.2          5.3         2.3  virginica
#> 17           6.5         3.0          5.5         1.8  virginica
#> 18           7.7         3.8          6.7         2.2  virginica
#> 19           7.7         2.6          6.9         2.3  virginica
#> 20           6.0         2.2          5.0         1.5  virginica
#> 21           6.9         3.2          5.7         2.3  virginica
#> 22           5.6         2.8          4.9         2.0  virginica
#> 23           7.7         2.8          6.7         2.0  virginica
#> 24           6.3         2.7          4.9         1.8  virginica
#> 25           6.7         3.3          5.7         2.1  virginica
#> 26           7.2         3.2          6.0         1.8  virginica
#> 27           6.2         2.8          4.8         1.8  virginica
#> 28           6.1         3.0          4.9         1.8  virginica
#> 29           6.4         2.8          5.6         2.1  virginica
#> 30           7.2         3.0          5.8         1.6  virginica
#> 31           7.4         2.8          6.1         1.9  virginica
#> 32           7.9         3.8          6.4         2.0  virginica
#> 33           6.4         2.8          5.6         2.2  virginica
#> 34           6.3         2.8          5.1         1.5  virginica
#> 35           6.1         2.6          5.6         1.4  virginica
#> 36           7.7         3.0          6.1         2.3  virginica
#> 37           6.3         3.4          5.6         2.4  virginica
#> 38           6.4         3.1          5.5         1.8  virginica
#> 39           6.0         3.0          4.8         1.8  virginica
#> 40           6.9         3.1          5.4         2.1  virginica
#> 41           6.7         3.1          5.6         2.4  virginica
#> 42           6.9         3.1          5.1         2.3  virginica
#> 43           5.8         2.7          5.1         1.9  virginica
#> 44           6.8         3.2          5.9         2.3  virginica
#> 45           6.7         3.3          5.7         2.5  virginica
#> 46           6.7         3.0          5.2         2.3  virginica
#> 47           6.3         2.5          5.0         1.9  virginica
#> 48           6.5         3.0          5.2         2.0  virginica
#> 49           6.2         3.4          5.4         2.3  virginica
#> 50           5.9         3.0          5.1         1.8  virginica
#> 51           5.1         3.5          1.4         0.2     setosa
#> 52           4.9         3.0          1.4         0.2     setosa
#> 53           4.7         3.2          1.3         0.2     setosa
#> 54           4.6         3.1          1.5         0.2     setosa
#> 55           5.0         3.6          1.4         0.2     setosa
#> 56           5.4         3.9          1.7         0.4     setosa
#> 57           4.6         3.4          1.4         0.3     setosa
#> 58           5.0         3.4          1.5         0.2     setosa
#> 59           4.4         2.9          1.4         0.2     setosa
#> 60           4.9         3.1          1.5         0.1     setosa
#> 61           5.4         3.7          1.5         0.2     setosa
#> 62           4.8         3.4          1.6         0.2     setosa
#> 63           4.8         3.0          1.4         0.1     setosa
#> 64           4.3         3.0          1.1         0.1     setosa
#> 65           5.8         4.0          1.2         0.2     setosa
#> 66           5.7         4.4          1.5         0.4     setosa
#> 67           5.4         3.9          1.3         0.4     setosa
#> 68           5.1         3.5          1.4         0.3     setosa
#> 69           5.7         3.8          1.7         0.3     setosa
#> 70           5.1         3.8          1.5         0.3     setosa
#> 71           5.4         3.4          1.7         0.2     setosa
#> 72           5.1         3.7          1.5         0.4     setosa
#> 73           4.6         3.6          1.0         0.2     setosa
#> 74           5.1         3.3          1.7         0.5     setosa
#> 75           4.8         3.4          1.9         0.2     setosa
#> 76           5.0         3.0          1.6         0.2     setosa
#> 77           5.0         3.4          1.6         0.4     setosa
#> 78           5.2         3.5          1.5         0.2     setosa
#> 79           5.2         3.4          1.4         0.2     setosa
#> 80           4.7         3.2          1.6         0.2     setosa
#> 81           4.8         3.1          1.6         0.2     setosa
#> 82           5.4         3.4          1.5         0.4     setosa
#> 83           5.2         4.1          1.5         0.1     setosa
#> 84           5.5         4.2          1.4         0.2     setosa
#> 85           4.9         3.1          1.5         0.2     setosa
#> 86           5.0         3.2          1.2         0.2     setosa
#> 87           5.5         3.5          1.3         0.2     setosa
#> 88           4.9         3.6          1.4         0.1     setosa
#> 89           4.4         3.0          1.3         0.2     setosa
#> 90           5.1         3.4          1.5         0.2     setosa
#> 91           5.0         3.5          1.3         0.3     setosa
#> 92           4.5         2.3          1.3         0.3     setosa
#> 93           4.4         3.2          1.3         0.2     setosa
#> 94           5.0         3.5          1.6         0.6     setosa
#> 95           5.1         3.8          1.9         0.4     setosa
#> 96           4.8         3.0          1.4         0.3     setosa
#> 97           5.1         3.8          1.6         0.2     setosa
#> 98           4.6         3.2          1.4         0.2     setosa
#> 99           5.3         3.7          1.5         0.2     setosa
#> 100          5.0         3.3          1.4         0.2     setosa
#> 101          7.0         3.2          4.7         1.4 versicolor
#> 102          6.4         3.2          4.5         1.5 versicolor
#> 103          6.9         3.1          4.9         1.5 versicolor
#> 104          5.5         2.3          4.0         1.3 versicolor
#> 105          6.5         2.8          4.6         1.5 versicolor
#> 106          5.7         2.8          4.5         1.3 versicolor
#> 107          6.3         3.3          4.7         1.6 versicolor
#> 108          4.9         2.4          3.3         1.0 versicolor
#> 109          6.6         2.9          4.6         1.3 versicolor
#> 110          5.2         2.7          3.9         1.4 versicolor
#> 111          5.0         2.0          3.5         1.0 versicolor
#> 112          5.9         3.0          4.2         1.5 versicolor
#> 113          6.0         2.2          4.0         1.0 versicolor
#> 114          6.1         2.9          4.7         1.4 versicolor
#> 115          5.6         2.9          3.6         1.3 versicolor
#> 116          6.7         3.1          4.4         1.4 versicolor
#> 117          5.6         3.0          4.5         1.5 versicolor
#> 118          5.8         2.7          4.1         1.0 versicolor
#> 119          6.2         2.2          4.5         1.5 versicolor
#> 120          5.6         2.5          3.9         1.1 versicolor
#> 121          5.9         3.2          4.8         1.8 versicolor
#> 122          6.1         2.8          4.0         1.3 versicolor
#> 123          6.3         2.5          4.9         1.5 versicolor
#> 124          6.1         2.8          4.7         1.2 versicolor
#> 125          6.4         2.9          4.3         1.3 versicolor
#> 126          6.6         3.0          4.4         1.4 versicolor
#> 127          6.8         2.8          4.8         1.4 versicolor
#> 128          6.7         3.0          5.0         1.7 versicolor
#> 129          6.0         2.9          4.5         1.5 versicolor
#> 130          5.7         2.6          3.5         1.0 versicolor
#> 131          5.5         2.4          3.8         1.1 versicolor
#> 132          5.5         2.4          3.7         1.0 versicolor
#> 133          5.8         2.7          3.9         1.2 versicolor
#> 134          6.0         2.7          5.1         1.6 versicolor
#> 135          5.4         3.0          4.5         1.5 versicolor
#> 136          6.0         3.4          4.5         1.6 versicolor
#> 137          6.7         3.1          4.7         1.5 versicolor
#> 138          6.3         2.3          4.4         1.3 versicolor
#> 139          5.6         3.0          4.1         1.3 versicolor
#> 140          5.5         2.5          4.0         1.3 versicolor
#> 141          5.5         2.6          4.4         1.2 versicolor
#> 142          6.1         3.0          4.6         1.4 versicolor
#> 143          5.8         2.6          4.0         1.2 versicolor
#> 144          5.0         2.3          3.3         1.0 versicolor
#> 145          5.6         2.7          4.2         1.3 versicolor
#> 146          5.7         3.0          4.2         1.2 versicolor
#> 147          5.7         2.9          4.2         1.3 versicolor
#> 148          6.2         2.9          4.3         1.3 versicolor
#> 149          5.1         2.5          3.0         1.1 versicolor
#> 150          5.7         2.8          4.1         1.3 versicolor


text:
Q: PHP Excel / Excel 2007 cannot open the file I've created a program to dynamically create a file. It works fine. When I add in code to prompt the user about where to save the file, it saves, but when I try to open the file I get the error 'Cannot open the file because the file format or file extention is not valid'. When I save it without prompt it opens fine.
The relevant parts of the code are:
if(isset($_POST['esd']))
{
$sqlcust = "SELECT * FROM compliance_customers WHERE Customer_ref = " . $_REQUEST['cust'];
$sqlcustresult = mysqli_query($conn, $sqlcust);
while($row_sqlcustresult = mysqli_fetch_array($sqlcustresult))
{
    $name = $row_sqlcustresult['Customer_name'];
}
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$name.'_'.$date.'.xlsx"');
}

#use php excel to create a spreadsheet of the customers current subscription
if( (isset($_REQUEST['esd'])) && (!isset($noEsd)) )
{
// Set properties for the excel file
$objPHPExcel = new PHPExcel();

$objPHPExcel->getProperties()->setCreator($_SESSION['username']);
$objPHPExcel->getProperties()->setLastModifiedBy($_SESSION['username']);
$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Customer export_" . $customername);
$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Customer export_" . $customername);
$objPHPExcel->getProperties()->setDescription($customername . "_" . $date);

$cnt_current_record = 2;

$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Content Name');
$objPHPExcel->getActiveSheet()->SetCellValue('B1', 'Content Type');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Content Description');

$sql_excelfile = "SELECT * FROM compliance_changes ORDER BY change_type";
$result_sql_excelfile = mysqli_query($conn, $sql_excelfile);
while($row_sql_excelfile = mysqli_fetch_array($result_sql_excelfile))
{
    if(in_array($row_sql_excelfile['change_name'], $excel_array))
    {
        #echo  "
" .$row_sql_excel['change_name']."	"   .$row_sql_excel['change_type']."	". $row_sql_excel['change_description']."
";
        #$objPHPExcel->setActiveSheetIndex($cnt_current_record);
        $objPHPExcel->getActiveSheet()->SetCellValue('A' . $cnt_current_record, $row_sql_excelfile['change_name']);
        $objPHPExcel->getActiveSheet()->SetCellValue('B' . $cnt_current_record, $row_sql_excelfile['change_type']);
        $objPHPExcel->getActiveSheet()->SetCellValue('C' . $cnt_current_record, $row_sql_excelfile['change_description']);
        $cnt_current_record++;
    }
}
#rename sheet
$sheet_title = $customername;
$objPHPExcel->getActiveSheet()->setTitle($sheet_title);

#write the xls file
#$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$filename = $customername . "_" . $date . ".xlsx";
#$objWriter->save(str_replace('customerdetail2.php', $filename, __FILE__));

$objWriter->save('php://output');

#echo the file has been written
echo $filename . " has been created";

I'm not overly familiar with PHPexcel, not sure why if I just save it, the files open fine, but when I use
         $objWriter->save('php://output');
to output the code, it fails. Can anyone help?

A: Thanks to @markbaker for the solution.
I had PHP code echoing code on the same page as php://output. This causes the stream to be overwritten with the HTML/PHP from the page which I hadn't been aware of. A good way to spot this if you encounter the same issue, is open the file with a text editor, if your stream contains html instead of your output information, this could be your issue too.
I changed this so the form when clicked posted to another page, containing only the code for the stream I wanted to output, and this worked perfectly fine.
I hope this is helpful,
Stephen.


text:
Q: Submitting a Django Form in a Bootstrap Modal I am new to Django and I am trying to figure out how to submit a form inside of a modal. I have two Django apps in question, frontend and login. The frontend app delivers the page, and the login is supposed to process the form. I am using crispy forms to render the forms but cannot get the forms to submit. Been struggling with this for a few days. Read through many posts on this and still can't figure it out. Any help will greatly be appreciated. Thank you so much. I'm using Django version 1.6
frontend app's urls.py:
from django.conf.urls import patterns, url
from django.contrib import admin
from frontend import views
from login.views import registration

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^about/$', views.about, name='about'),
    url(r'^contact/$', views.contact, name='contact'),
    url(r'^$', 'index', name='index'),
    url(r'^$',views.registration, name='register'),
)

frontend app's views.py:
from django.template import RequestContext
from django.shortcuts import render_to_response
from login.forms import RegistrationForm
from login.forms import LoginForm
from login.views import registration

def index(request):
    return render_to_response('index.html', {'regform':RegistrationForm(),'loginform': LoginForm()} )

def about(request):
    return render_to_response('about.html')

def contact(request):
    return render_to_response('contact.html')

login apps's urls.py:
from django.conf.urls import patterns, url
from login import views

urlpatterns = patterns('',
   url(r'^register/$', views.registration, name='index.html')

)

login app's views.py:
from django.template import RequestContext
from django.shortcuts import render_to_response
from login.forms import RegistrationForm

def registration(request):

    context = RequestContext(request)

    registered = False

if request.method == 'POST':

    user_form = RegistrationForm(request.POST)

    user = user_form.save()

    user.set_password(user.password)
    user.save()

    registered = True

else:
    user_form = RegistrationForm()

return render_to_response('index.html', {'regform': user_form}, context)

def login(request):
   context = RequestContext(request)
   login_form = LoginForm()
   return render_to_response('index.html', {loginform: login_form}, context)

login app's forms.py:
from django.contrib.auth.models import User
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Field
from crispy_forms.bootstrap import (PrependedText, PrependedAppendedText, FormActions)
from login.models import User

class RegistrationForm(forms.ModelForm):
     password = forms.CharField(widget=forms.PasswordInput())

     class Meta:
           model = User
           fields = ('username', 'email', 'first_name','last_name','password')
           helper = FormHelper()
           helper.form_method = 'POST'
           helper.add_input(Submit('save', 'save', css_class='btn-primary'))

     class LoginForm(forms.ModelForm):
           password = forms.CharField(widget=forms.PasswordInput())

 class Meta:
    model = User
    fields = ('username', 'password')
@property
def helper(self):
    helper = FormHelper()
        helper.form_method = 'POST'
        helper.add_input(Submit('save', 'save', css_class='btn-primary'))
    return helper

Index.html modal:

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Register

Login

Register

        <form action="" method=post">

    {% crispy loginform %}

    {% crispy regform %}

         </form>

        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary">Submit</button>

Modal with Ajax attempt(snip):

        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button id="register" type="button" class="btn btn-primary">Submit</button>

Login view for Ajax request:
def addUser(request):
if request.is_ajax() and request.POST:
    data = {request.POST.get('item')}
    return HttpResponse(json.dumps(data), content_type='application/json')
else:
raise Http404

As Requested Rendered HTML For Modal:

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Register

Login

Register

        <form id="login" action="/frontend/register/" method="POST">

                Username* Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters
                Password*

                 Username*            Required. 30 characters or fewer. Letters, numbers and @/./+/-/_  characters
                Email address

                First name

                Last name

                Password*

         </form>

        <button type="button" class="btn btn-default"   data-dismiss="modal">Cancel</button>
        <button id="register" type="button" class="btn btn-primary">Submit</button>

Update Ajax:

Update:
The form is now being submitted to the database. However form Validation is not functioning. The if/else control seems to always validate false. If I remove form.submit(). It functions and shows form errors, but the page refreshes.
updated views.py:
def addUser(request):

form = RegistrationForm(data=request.POST or None)
if form.is_valid():
    # You could actually save through AJAX and return a success code here
    form.save()
    return {'success': True}

form_html = render_crispy_form(form)
return {'success': False, 'form_html': form_html}

updated Forms.py:
class RegistrationForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())
    class Meta:
         model = User
         fields = ('username', 'email', 'first_name','last_name','password')
    def __init__(self, *args, **kwargs):
             super(RegistrationForm, self).__init__(*args, **kwargs)
             self.helper = FormHelper()
             self.helper.form_id = 'id-registration'
             self.helper.form_class = 'blueForms'
             self.helper.form_method = 'post'
             self.helper.form_action = '/register/'
             self.helper.add_input(Submit('submit', 'Submit'))

The Problem has been resolved:

A: In a first instance I would fire up your Browser Developer Tools (e.g. Firebug in Firefox). In the Network tab monitor closely if your POST request is sent or not.
Once the request is sent, you can inspect the content and answer of your request. This helps to identify if your form catches all the data from the inputs, or if you might have trouble with your urls.py.
In case the form is submitted correctly (Status 200), you can start debugging your Django App.

A: You have two possibilities:

*

*Via a HTML post request

Put <button> into <form>. Change the type of the submit button to type="submit" and fix the form attributes by adding an action and fixing the typo in the method.

*

*Via an AJAX request.

Add an id to the submit button and attach a click-event to the button where you do the AJAX request.

For further information read http://getbootstrap.com/javascript/#modals-examples

A: I had a similar problem and getting rid of data-dismiss="modal" fixed it for me.
It doesn't answer your question so much, but people with the same issue end up on this page, and perhaps this will help them.


text:
Q: Django: Method Not Allowed (POST): I am trying to create an event in FullCalendar by passing a timestamp into the url of a Django CreateView. However, after pressing submit on my form I keep getting a blank page and the error:
Method Not Allowed (POST): /fullcalendar/ambroses-calendar/

html:
dayClick: function(date, jsEvent, view) {
    if($('#calendar').fullCalendar('getView').type != 'month') {
        $("#occDiv").load("{% url 'edit_occurrence_short' 1234567898765 %}".replace(1234567898765, (new Date(date)).getTime())).dialog({
        autoOpen: false,
        modal: true,
        bgiframe: true,
        width: 800
    });
    $("#occDiv").dialog('open');
}

urls.py
   url(r'^occurrence/add/(?P<date>\d+)/$',
        ShortCreateOccurrenceView.as_view(),
        name='edit_occurrence_short')

Views.py:
class ShortOccurrenceMixin(CalendarViewPermissionMixin, TemplateResponseMixin):
    model = Occurrence
    pk_url_kwarg = 'occurrence_id'
    form_class = ShortOccurrenceForm

class ShortCreateOccurrenceView(ShortOccurrenceMixin, CreateView):
    template_name = 'schedule/edit_occurrence_short.html'

    def form_valid(self, form):
        occurrence = form.save(commit=False)
        start = datetime.datetime.fromtimestamp(self.kwargs.get('date', None)/1000.0)
        end = start + datetime.timedelta(hours=1)
        occurrence.start = start
        occurrence.end = end
        occurrence.save()
        return HttpResponseRedirect('home')

Models.py:
class Occurrence(models.Model):
    event = models.ForeignKey(Event, on_delete=models.CASCADE, verbose_name=_("event"))
    title = models.CharField(_("title"), max_length=255, blank=True)
    description = models.TextField(_("description"), blank=True)
    start = models.DateTimeField(_("start"), db_index=True)
    end = models.DateTimeField(_("end"), db_index=True)
    cancelled = models.BooleanField(_("cancelled"), default=False)
    original_start = models.DateTimeField(_("original start"), auto_now=True)
    original_end = models.DateTimeField(_("original end"), auto_now=True)
    created_on = models.DateTimeField(_("created on"),   auto_now_add=True)
    updated_on = models.DateTimeField(_("updated on"), auto_now=True)

Forms.py:
class ShortOccurrenceForm(forms.ModelForm):
    class Meta(object):
        model = Occurrence
        fields = ('title', 'event')

A: The comments under the question led me to the right answer. Thank you very much @Willhen Van Onsem and @dirkgroten!
I was able to change the origin of the form POST by setting the action on the form in the html
...
<form action="{% url 'edit_occurrence_short' date %}" method="post" >
...


text:
Q: Throwing argument exceptions in method overloads I just recently started looking into exceptions and best practices for their use and I wonder what is the correct way of doing this:
Suppose there is a method with multiple arguments. And there are multiple overloads for this method with less parameters, which call the main implementation by providing default values.
Do I validate all arguments in every overload?
public string Translate(string text)
{
    if (String.IsNullOrEmpty(text))
        throw new ArgumentNullException();

    return Translate(text, "english");
}

public string Translate(string text, string language)
{
    if (String.IsNullOrEmpty(text))
        throw new ArgumentNullException();

    // Do the rest of the work
    // ...
}

Do I rethrow the exceptions?
public string Translate(string text)
{
    try
    {
        return Translate(text, "english");
    }
    catch
    {
        throw;
    }
}

public string Translate(string text, string language)
{
    if (String.IsNullOrEmpty(text))
        throw new ArgumentNullException();

    // Do the rest of the work
    // ...
}

Or do I completely drop exceptions and try/catch blocks in the overload?
public string Translate(string text)
{
    return Translate(text, "english");
}

public string Translate(string text, string language)
{
    if (String.IsNullOrEmpty(text))
        throw new ArgumentNullException();

    // Do the rest of the work
    // ...
}

Also, how would the documentation of the two methods look like?
(Using C# XML comments. Especially where I put the <exception> elements.)

I do realize that this is a minor topic, still, I keep wondering everytime I encounter this kind of situation (which is actually quite often).

A: Optional arguments solves this in a way, then you have only one method:
public string Translate(string text, string language="english")

There are some quirks with optional arguments that are good to know about.

the default values are "baked into" the calling code. [...]
  The issue this can cause is the same for exposing public consts – if
  you change the default values in a library, but don't recompile the
  calling code, then the calling code will still call your method(s)
  with the old default values. This is definitely something you need to
  consider when designing APIs using optional parameters.

A: Lets make a pros and cons list of the three options you have got and decide :
1. Do I validate all arguments in every overload?
Pros : You get to know whether the string is empty and then throw the exception. Classic and good.
Cons : You are calling the second function after the exception is thrown, knowing that exception occured due to string empty or null.
So I would drop this idea.
2. Do I rethrow the exceptions?
Pros : 1) This is my personal favorite as if you go line by line this is what happens. The second function is called and there the exception is thrown and caught in the calling function's catch and some other jobs are done.
       2) using throw keyword instead of throw ex make sure that your stack trace is intact.
       3) Handling an exception at the calling part is the best practice.
Cons : Please help me with the cons. I dont find any.
3. Or do I completely drop exceptions and try/catch blocks in the overload?
Pros : Try catch is not used in the calling function. Not exactly a pros, but ehh, it reduces some code.
Cons : Proper handling is not there and the best practice says we should handle the exception at the calling function.
I think the second option is the best option.
Also there is a link I would like to share which is really helpful
Best Practice : Code Project Link
Please let me know.

A: Actually this a traditional issue in what has been recognized in crypto as best done with what is called static factory methods - usually named getInstance() - in which you refactor a lot of the question into one place.
It gets rather nasty trying to wade through all the responses you get but never throw away exceptions by doing nothing at all, just simplify greatly for end-use-case and either keep something in a log and fail-fast or make sure you are in a student setting.

A: I'm late to answering here, but I wanted to point out that if you're doing overloads properly, this really shouldn't be an issue. The correct way to overload to is to put all the functional code in a method that accepts all possible params:
public string Foo(string param1, string param2, string param3)
{
    // do work here, including throwing argument exceptions
}

Then, your overloads should fill missing params with default values:
public string Foo(string param1)
{
    return Foo(param1, null, null);
}

public string Foo(string param1, string param2)
{
    return Foo(param1, param2, null);
}

Based on that, then, you need only handle your exceptions in your primary overload (the one that actually does stuff). Just bear in mind that your overloads should not themselves cause an exception to be raised. For example, if param3 was enforced to be not null via throwing ArgumentNullException, then you shouldn't pass null for that param, but rather some actual string that can serve as a default.
No matter which overload ends up being called, the primary overload (with the throws) is called, and any exceptions it throws will bubble up to the originating code. In other words, you don't need to do something like:
public string Foo(string param1)
{
    if (param1 == null)
    {
        throw new ArgumentNullException(nameof(param1));
    }

    return Foo(param1, "param2 default", "param3 default");
}

Because the primary overload already has that check and will throw if param1 is null.


text:
Q: Make a Label Copyable I'm developing a WebApp for iOS which has a Label that will show a result for the user that should be copied for further use, but how I can make the Label content copyable?

A: u could add a copy button near the label, when the user tapps it, the value of the label is stored in a var and could be inserted at another point of the application...
or, if u want the labeltext in the clipboard, u could use this:
http://mobileorchard.com/new-in-iphone-30-tutorial-series-part-3-copy-paste-with-uipasteboard/
u can get the text from the label via mylabeloutlet.text and store it in the pastboard, so the user can insert it into another textfield/inputfield


text:
Q: Referential integrity with One to One using hibernate I'm having two tables -
Foo { foo_id, name }
Foo_properties { fp_id, foo_id, phoneNumber}

Now I want to map this in my object model using hibernate..
I need a foo_id in Foo_properties  because i want to maintain referential integrity and want to add ON DELETE CASCADE constraint.
so I mapped the relation in the following way -
@Entity
public class Foo{
    @Id
    private long foo_id;

    private String name;

    @OneToOne(mappedBy = "foo")
    private FooProperties fooProperties;
}

@Entity
public class FooProperties{

    @Id
    private long fp_id;

    private String phoneNumber;

    @OneToOne
    @JoinColumn(name = "foo_id",  nullable = false)
    private Foo foo;
}

Now since the owning side is FooProperties class, I'm facing following issues -
If I set the new instance of FooProperties to Foo the existing FooProperties still remains in DB and hibernate doesn't delete that instance, e.g.
Foo foo = entityManager.find(Foo.class, fooId);
foo.setFooProperties(new FooProperties("xxx-xxx-xxx"));
entityManager.merge(foo);

This results into the new row in FooProperties table along with the existing one. Now I don't understand how I can change my mapping to so I can have above code (or variant of it) working for all scenarios, that means I need Foo as a owning side and foo_id in FooProperties. Is there any way to define the mapping like this?
NOTE: I already asked question based on this but I think I wasn't clear in previous question so asked this another one.

A: You were already told to use orphanRemoval = true or CascadeType.DELETE_ORPHAN. However, due to casuistics in interpretation of JPA Specification it wouldn't work as expected for one-to-one relationships (HHH-5559).
You can achieve a proper behaviour of orphanRemoval with the following trick:
@Entity
public class Foo{
    @OneToMany(mappedBy = "foo", orphanRemoval = true)
    private List<FooProperties> fooProperties;

    public FooProperties getFooProperties() {
        if (fooProperties == null || fooProperties.isEmpty()) return null;
        else return fooProperties.get(0);
    }

    public void setFooProperties(FooProperties newFooProperties) {
        if (fooProperties == null) fooProperties = new ArrayList<FooProperties>();
        else fooProperties.clear();
        if (newFooProperties != null)
            fooProperties.add(newFooProperties);
    }
    ...
}

@Entity
public class FooProperties{
    @ManyToOne
    @JoinColumn(name = "foo_id",  nullable = false)
    private Foo foo;
    ...
}

Or even this, if you don't need FooPropeties.foo:
@Entity
public class Foo{
    @OneToMany(orphanRemoval = true)
    @JoinColumn(name = "foo_id",  nullable = false)
    private List<FooProperties> fooProperties;

    // getter/setter as above
    ...
}

A: Bar is the owner of the association (as indicated by the mappedBy on the inverse side) and thus the cascade has to be set there.
Edit:
To invert that, this might help.

A: There are 2 options for you to choose from, since you don't want to change your mapping :

*

*Do it via your service layer logic. I think you have a similar question already.

*Use the Hibernate annotation @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN) on the Foo side of the relationship. However this is explicitly Hibenate and JPA 2 doesn't include support for the same.

A: I think instead of calling merge on the entity, if you directly call update on session object then hibernate will first delete the existing row and then it will add the new one. I implemented the same, but, in my case I used xml for mapping the entity. I hope this will help you.


text:
Q: find source of input value modification on page ready in javascript I'm trying to find the cause of an unwanted value modification so I can remove the bug. When I turn off javascript for my page it includes this element after loading:
<input type="hidden" value="5123" name="report[sub_district_id]" id="report_sub_district_id">

but when I have javascript on, the same element looks like this after page load:
<input type="hidden" value="" name="report[sub_district_id]" id="report_sub_district_id">

I can't work out what code is unsetting the value property.
I've got one method that I know of that modifies the value. I've tried putting an alert in that method, but it's not triggered. I've also tried commenting out that method, but still the change happens. Perhaps some of my other JS accidentally hooks onto this element, but it seems unlikely. Perhaps the change is caused by some code in my framework (Rails with Materialize).
I've also tried adding DOM breakpoints "attribute modified" and "subtree modified" on this element, and "subtree modified" on the parent element, but none of these breakpoints are triggered.
The "attribute modified" breakpoint does trigger when my code modifies the value of the input at some point after the page is loaded, but I'm trying to find what is happening when "page:change" event is triggered, and this breakpoint is not triggering - perhaps because the DOM is not loaded yet.
I've tried the answers to this question but they don't help because they don't show how to make a breakpoint on an element change event that triggers before the DOM is loaded.
I'm using Chromium browser 48.0.2564.116 on Ubuntu 15.10 (64-bit)
How can I find what the cause of this bug is?

A: Debug after insert this code on top line of your page.
setInterval(function() {
  var value = $("#report_sub_district_id").val();
  if(value !== 5123) debugger;
},10);

and,
Maybe any Chrome extension program might cause the problem.
You should disable your all Chrome extensions.

A: TL;DR is there's no easy way.
So working backwards from the code that was actually changing, I don't think there is a way with browser's debugging tools to put a breakpoint here.  However with an educated guess about the dom node's property that was getting changed, you could (assuming you run soon enough in the page) set a breakpoint that would help you out.
You found that the code in question was $('#parent-div-id input').val('').
Now .val() in jQuery just finds the actual node element and sets node.value = "blah";  The important distinction here is that it was changing a "property" on the node, and not an "attribute".  You'll notice that all the DOMAttribute etc breakpoints talk about node attributes.  If you take a node and edit the html's attribute, by say doing $('#parent-div-id input').attr('value', 'blah'), the breakpoint would get hit.  The list of properties on a node is much larger than the list of HTML attributes, and the debugging tools only put breakpoints on HTML attribute modifications.
However in this case, you know the element in question (the input element), and the property that was getting messed with (the value property), so you could have done what was suggested in this answer, and redefined the property.
Example code here:
var node = $('#parent-div-id input')[0];
Object.defineProperty(node, 'value', {
    get: function () {
        return node._value;
    },

    set: function (value) {
        debugger; // sets breakpoint
        node._value = value;
    }
});

All you'd need to do is get that code to run early enough in the page.  To do that I'd probably set a breakpoint on the first line of the first javascript file loaded in the network tab.


text:
Q: PostgreSQL trigger prevents another one to work Suppose we have:
create table T
(
    id bigserial primary key
  , a  int
  , b  int
  , c  int
);

I want c to be always equals to a+b and I want to prevent manual changes of c. So I create two triggers:
-- Prevents manual changes of c:

create or replace function no_changes() returns trigger as $$
begin
    if old.c is distinct from new.c then
        raise exception 'Can''t change c manually.';
    end if;
    return new;
end;
$$ language plpgsql;

create trigger no_changes
before update of c  -- 'before' so prevents changes in 'c'
on T
for each row
execute procedure no_changes();

-- Do c = a + b:

create or replace function change() returns trigger as $$
begin
    update T
    set c = a + b
    where id = new.id;
    return new;
end;
$$ language plpgsql;

create trigger change
after insert or update of a, b  -- 'after' so I'm sure the row is inserted/updated
on T
for each row
execute procedure change();

If I do:
update T set c = 247;

I see the error message "Can't change c manually" and the column doesn't changes. Great.
However, If I do:
insert into T (a, b) values (4, 3);

Or:
update T set a = 3 where id = 2 -- suppose id = 2 exists

Then I get the same error message as before. Obviously, The update command from change trigger fires no_changes trigger preventing the update in the c column.
Any ideas? Thanks!

A: The whole logic could be placed in single function:
create or replace function change() returns trigger as $$
begin
    if old.c is distinct from new.c then
        raise exception 'Can''t change c manually.';
    end if;
    new.c := new.a + new.b;
    return new;
end;
$$ language plpgsql;

create trigger change
before insert or update on T
for each row
execute procedure change();

But if you prefer to split the logic, then
1) Create both triggers on before event
2) "If multiple triggers of the same kind are defined for the same event, they will be fired in alphabetical order by name." So name triggers to get the desired order, for example trg1_check to prevent changes of c and trg2_change to calculate c value.


text:
Q: IBM ODM if condition in for loop I want to iterate over a list of objects in my rule and check some conditions on each object using if statement in the loop, is it possible?
Have tried the for loop, but it is not allowing to have if statement within it.

A: Not only is it possible, it is very common.
Just use a DEFINITIONS clause to bind a variable to each element in the list.
The iteration is implied.
definitions
set <variable> to <definition> in <list> ;
Using a second SET statement and another list yields a nested loop.
You can check conditions on the object either in an IF statement or by adding a WHERE clause to the SET statement.
Here is a link to one of the Knowledge Center pages: https://www.ibm.com/support/knowledgecenter/en/SSQP76_8.9.2/com.ibm.odm.itoa.ref/topics/ref_bal_set_var_to_def.html
By contrast, the FOR EACH loop is used in the action of the rule -- after all the conditions have been satisfied. There is nothing wrong with using it when appropriate, but its use is not that common.

A: define:
make 'varialbe' be any in collection ;

if
"condition"

then
something

else:
other

Sorry for the syntacs. I'm not using the english version of ODM, but i think you got the idea. It works both in tables and rules.


text:
Q: Transform dom elements to match an image regardless of its deformations I want to have an image on page with DIVs sitting at the same place relative to the image even when the image gets stretched. Basically, I know the position the stars should take in the original picture, however I dont know how to move them such that they stand in the right place.
Here I explain with a picture :

Here is my HTML markup. The .slide-point elements are the red stars:

let points = document.querySelectorAll(".slide-point");

points.forEach(point => {
  const x = point.dataset.x;
  const y = point.dataset.y;
  const h = point.dataset.h;
  const w = point.dataset.w;

  let image = point.closest(".slide").querySelector("img");
  let natH = image.naturalHeight;
  let natW = image.naturalWidth;

  let clientH = image.clientHeight;
  let clientW = image.clientWidth;

  point.style.left = x * clientW / natW + "px";
  point.style.top = y * clientH / natH + "px";
  point.style.width = w;
  point.style.height = h;
});
.slide-point {
  position: absolute;
  background: red;
}

.slide>img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: top left;
}

★

★

Obviously, as soon as I resize the page, the stars don't align with the image anymore.

Thank you in advance !


text:
Q: HTML view page save as PDF using roatativa I have following image for the Create_Brochure ActionResult in Brochure Contrller Class

Here the whole URL of that Action
http://localhost:49669/Brochure/Create_Brochure?%5B0%5D.Property_ID=1&%5B0%5D.IsChecked=true&%5B0%5D.IsChecked=false&%5B1%5D.Property_ID=2&%5B1%5D.IsChecked=true&%5B1%5D.IsChecked=false&%5B2%5D.Property_ID=3&%5B2%5D.IsChecked=true&%5B2%5D.IsChecked=false&%5B3%5D.Property_ID=4&%5B3%5D.IsChecked=false&%5B4%5D.Property_ID=5&%5B4%5D.IsChecked=false&%5B5%5D.Property_ID=6&%5B5%5D.IsChecked=false&%5B6%5D.Property_ID=7&%5B6%5D.IsChecked=false&%5B7%5D.Property_ID=8&%5B7%5D.IsChecked=false&%5B8%5D.Property_ID=9&%5B8%5D.IsChecked=false&%5B9%5D.Property_ID=10&%5B9%5D.IsChecked=false
Once I click I want to save this view page as PDF , to do that I followed this tutorial
So this is the cshtml view page , so it doesn't have a model class
@model IEnumerable<int>

@{
    ViewBag.Title = "Create Template";
}
<!DOCTYPE html>

    <title>Create a Template</title>

                                    Bank Brochure

                       @if (Model.Contains(1))
                        {

Product Name

                        }

                        @if (Model.Contains(2))
                        {

Product Description

London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.Standing on the River Thames London has been a major settlement for two millennia, its history going back to its founding by the Romans, who named it Londinium.

                        }

                        @if (Model.Contains(3))
                        {

"Unique Selling Propositions It enables ASP.NET Web developers to replace any textbox with an intuitive Word-like WYSIWYG html editor.
"

                        }

                        @if()....

                                    Copyright © 2015 Zoo Group , Solution by kelum.

    <button id="btn_sumbit" type="button" class="btn btn-danger submit">Save as PDF</button>

@section Scripts {

    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/jqueryui")

}

this is controller class method to save to PDF
    [HttpPost]
    public ActionResult DownloadActionAsPDF()
    {
        string path = Request.Url.ToString();
        //Request.Url.ToString() using to get current page URL
        return new Rotativa.UrlAsPdf(path) { FileName = "UrlTest.pdf" };
    }

but once I click this button it doesn't save to PDF file,

A: As i already commented that your code is calling the same Method again and again..
You can do the same thing by using ActionAsPdf and point it to the Create_Brochure Action method of yours
Ex:-
    public ActionResult DownloadActionAsPDF()
            {
              return new Rotativa.ActionAsPdf("Create_Brochure") { FileName = "TestPdf.pdf"};
            }

    public ActionResult Create_Brochure()
            {
               //Your logic....
               return View()
            }

and in your view page no need of a button or a Ajax call can be done by a anchor tag
View:-
 SaveAsPdf


text:
Q: When parsing datetime into month day with English culture, it is still parsed in Turkish language Here is the code. I still get incorrect results
string srRegisterDate = "25.07.2009 00:00:00"
CultureInfo culture = new CultureInfo("en-US");
srRegisterDate = String.Format("{0:dddd, MMMM d, yyyy}", Convert.ToDateTime(srRegisterDate), culture);

The result is Cumartesi, Temmuz 25, 2009
Instead it should be Saturday, July 25, 2009
How can i fix this error?
C#.net v4.5.2

A: Convert.ToDateTime(srRegisterDate) still uses your CurrentCulture which looks like tr-TR based on day and month names. Cumartesi - Temmuz
In String.Format, your culture will be ignored since you used it as a third parameter as an argument but you never use it.
Your code called Format(string format, object arg0, object arg1) overload. But you never use the arg1. This overload doesn't think this is a culture. It thinks it is another argument that you want to format.
This String.Format has an overloads that takes IFormatProvider as a first argument.

*

*Format(IFormatProvider, String, Object)

*Format(IFormatProvider, String, Object[])

*Format(IFormatProvider, String, Object, Object)

*Format(IFormatProvider, String, Object, Object, Object)
For example;
srRegisterDate = String.Format(culture, "{0:dddd, MMMM d, yyyy}", Convert.ToDateTime(srRegisterDate));

But most comman way (and I always prefer) to get the result that you want is using .ToString() method like;
srRegisterDate = Convert.ToDateTime(srRegisterDate).ToString("dddd, MMMM d, yyyy", culture);

A: The issue is because of ignored culture value in String.Format and not with converting string to DateTime.
You need:
srRegisterDate = String.Format(culture, "{0:dddd, MMMM d, yyyy}", Convert.ToDateTime(srRegisterDate));

Your current call to String.Format utalizes the overload String.Format Method (String, Object[]) and the culture passed in parameter is treated as a simple object parameter passed for place holder. Since there is no place holder, you don't even see it getting ignored.
If you want to have culture utilized in String.Format then you have to use the overload : Format(IFormatProvider, String, Object) or String.Format Method (IFormatProvider, String, Object[])

A: This works
DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;
DateTimeFormatInfo trDtfi = new CultureInfo("tr-TR", false).DateTimeFormat;
string result = String.Format("{0:dddd, MMMM d, yyyy}", Convert.ToDateTime(srRegisterDate, trDtfi).ToString(usDtfi));

original
25.07.2009 00:00:00
transformed
7/25/2009 12:00:00 AM
EDIT
Was one to short of required
string test = String.Format("{0:dddd, MMMM d, yyyy}", Convert.ToDateTime(Convert.ToDateTime(srRegisterDate, trDtfi).ToString(usDtfi)));

Saturday, July 25, 2009


text:
Q: C++11 Get non-default constructed object as output parameter I have a custom method that pops an object from a queue of value objects as out parameter and returns an error code:
class Element
{
public:
    Element() = delete;

    Element(int32_t a, const std::string &s)
    {
        a_ = a;
        s_ = s;
    }

private:
    int32_t a_;
    std::string s_;
}

enum class ErrorCode : uint32_t
{
    OK = 0,
    QueueEmpty,
    QueueFull
}

class QueueWrapper
{
public:
    ErrorCode push(const Element &e)
    {
        // Implementation
    }

    ErrorCode pop(Element &outE)
    {
        // Simple example

        if(queue_.empty())
        {
            return ErrorCode::QueueEmpty;
        }

        outE = queue_.front();
        queue_.pop();

        return ErrorCode::OK;
    }

private
    std::queue<Element> queue_;
}

void function()
{
    QueueWrapper queueWrapper;

    Element e1(1, "1");
    ErrorCode errorCode = queueWrapper.push(e1);

    // What should I do here?
    // Element e2;
    // errorCode = queueWrapper.pop(e2);
}

Can I get a non-default constructed object as output parameter using move semantics or other mechanisms?

A: Change the signature of pop() to return an Element and not an ErrorCode, then:
Element e( queueWrapper.pop() );

If you absolutely have to have the ErrorCode, pass it into pop() by reference. BUT error codes really aren't modern C++. Errors should mostly be handled with exceptions, leading to something more like this:
try {
    ...
    Element e( queueWrapper.pop() );
    ...
}
catch ( QueueWrapper::Exception & e )
{
    // exception handling/reporting
}

Error codes should really only be used for crossing module boundaries.

A: No. If you can form a reference to an Element, that means it has already be constructed (or it would be a segment of memory gibberish, not an Element).
If the behaviour you want is for the function to somehow get a designated space to construct the object into, let (N)RVO do the job.


text:
Q: more efficient way of remove a few characters from the end of a string I would like to remove last n characters from a string. I know there is a method called pop_back() which can remove the last character. I can use it in a loop like the following, but it doesn't feel efficient.
string st("hello world");
for (i=0; i<n; i++) {
    st.pop_back();
}

Wonder if there is more efficient alternative. Thanks.

A: string::substr would be a better way to do this. You could do it like this:
st = st.substr(0, st.length()-n);

A: std::string::erase is what you are looking for.
If you wanted to erase the last n characters, you would do something like:
st.erase(st.length()-n);

But make sure you do proper bounds checking.


text:
Q: Play Framework Production Logging issue My current Loggers shows as below.
    10:31:11.015 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:11.901 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:12.115 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:13.001 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:13.215 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:14.101 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:14.315 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:15.201 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:15.415 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:15.702 [HikariPool-1 housekeeper] DEBUG com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Pool stats (total=10, active=0, idle=10, waiting=0)
10:31:16.301 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:16.515 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:17.401 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:17.614 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:18.501 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:18.715 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:19.600 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:19.815 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:20.701 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:20.915 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:21.801 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:22.015 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:22.901 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:23.115 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:24.001 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:24.215 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:25.101 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
10:31:25.315 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms

It works perfectly during development and would like only to show info set up on Logger.info,
I'm using Play Framework Version 2.5.10
How do i solve this.
Logback XML is a below

<conversionRule conversionWord="coloredLevel" converterClass="play.api.libs.logback.ColoredLevel" />

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%coloredLevel %logger{15} - %message%n%xException{10}</pattern>
    </encoder>
</appender>

<appender name="ASYNCSTDOUT" class="ch.qos.logback.classic.AsyncAppender">
    <appender-ref ref="STDOUT" />
</appender>

<logger name="play" level="INFO" />
<logger name="application" level="INFO" />

<logger name="com.gargoylesoftware.htmlunit.javascript" level="OFF" />

<root level="WARN">
    <appender-ref ref="ASYNCSTDOUT" />
</root>

A: Removed Logback.xml from conf.


text:
Q: Question on number of solutions of $\sin (e^{x}) = e^{\sin x}$ Let $S_n$ be the number of solutions of
$\sin (e^{x}) = e^{\sin x}$ in the interval $[0,2n\pi]$
Then find the value of
$\lim_{n \to \infty} \frac{ S_n}{e^{2n\pi}}$

A: HINT
We can show that
$$S_{n+1}-S_n\sim\frac{e^{2\pi n}(e^{2\pi}-1)}{\pi}$$
then note that by Stolz-Cesaro
$$\lim_{n \to \infty} \frac{ S_n}{e^{2n\pi}}=\lim_{n \to \infty} \frac{ S_{n+1}-S_n}{e^{2\pi(n+1)}-e^{2\pi n}}$$


text:
Q: convert csv data to DataTable in VB.net I am trying to import a large array of integers stored as a csv file into a VB.Net DataTable called BeamMap. The .csv file consists only of integers, with a delimiter of ,, no quotes around the data (ie., 1,3,-2,44,1), and an end of line character of line feed and carriage return. All I want to do is get each integer into a DataTable cell with the appropriate rows and columns (there are the same number of columns for each row) and be able to reference it later on in my code. I really don't want anything more than absolutely necessary in the code (no titles, captions, headings, etc.), and I need it to be fairly efficient (the csv array is approx. ~1000 x ~1000).
Thanks!

A: Here's a simple approach which requires a strict format (as you've mentioned):
Dim lines = IO.File.ReadAllLines(path)
Dim tbl = New DataTable
Dim colCount = lines.First.Split(","c).Length
For i As Int32 = 1 To colCount
    tbl.Columns.Add(New DataColumn("Column_" & i, GetType(Int32)))
Next
For Each line In lines
    Dim objFields = From field In line.Split(","c)
                 Select CType(Int32.Parse(field), Object)
    Dim newRow = tbl.Rows.Add()
    newRow.ItemArray = objFields.ToArray()
Next

A: Use OleDb provider to read CSV and pouplate the DataTable.
 Dim folder = "c:\location\of\csv\files\"
 Dim CnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & folder & ";Extended Properties=""text;HDR=No;FMT=Delimited"";"
 Dim dt As New DataTable
 Using Adp As New OleDbDataAdapter("select * from [nos.csv]", CnStr)
       Adp.Fill(dt)
 End Using

A: Getting the file from a mapped drive and putting the retrieved data in a dataset:
Dim folder = "Z:\"
Dim CnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & folder & ";Extended Properties=""text;HDR=No;FMT=Delimited"";"

Dim dssample As New DataSet
Using Adp As New OleDbDataAdapter("select * from [samplecsv.csv]", CnStr)
    Adp.Fill(dssample)
End Using

If dssample.Tables.Count > 0 Then
    'some code here
End If

A: Also, don't forget to include the
Imports System.Data.OleDb

And if you wish to link to a DataGridView (after read):
Dim bs As New BindingSource
bs.DataSource = dt
DataGridView1.DataSource = bs


text:
Q: Counting row per column when upload excel with codeigniter I want to upload the data excel, but before it uploads the data I want to make sure these data first. example: there is one blank column if it can not be uploaded. The simple question, how do I count the number of rows of each column that has been uploaded earlier?
so later the output will be like this:
Column 1: 50 lines
Column 2: 49 lines. for example (assuming empty 1 data)
Column 3: 47 lines. for example (assuming empty 3 data)
Here is my controller
for ($i = 1; $i <= $data['numRows']; $i++) {
    if($data['cells'][$i][1] == '') break;
    $kode=str_replace($simbol, '', $data['cells'][$i][1]);
    $dataexcel[$i-1]['kode_matkul'] = $kode;
    $dataexcel[$i-1]['nama_matkul'] = $data['cells'][$i][2];
    $dataexcel[$i-1]['sks_a'] = $data['cells'][$i][3];
    $dataexcel[$i-1]['sks_b'] = $data['cells'][$i][3];
    $dataexcel[$i-1]['semester_matkul'] = $data['cells']$i][4];
}

I try use echo count($data['cells'][$i][1])
but it doesn't work

A: You'll need to create an array to hold the count of the empty cells. This can be done using a simple single array.
$emptyValues = array_fill(1,$data['num_rows'],0) ; //create array of predefined length and set all valuese to 0.

for ($i = 1; $i <= $data['numRows']; $i++) {
if($data['cells'][$i][1] == '') {
     $emptyValues[$i]++ ;
     break;
}
$kode=str_replace($simbol, '', $data['cells'][$i][1]);
$dataexcel[$i-1]['kode_matkul'] = $kode;
$dataexcel[$i-1]['nama_matkul'] = $data['cells'][$i][2];
$dataexcel[$i-1]['sks_a'] = $data['cells'][$i][3];
$dataexcel[$i-1]['sks_b'] = $data['cells'][$i][3];
$dataexcel[$i-1]['semester_matkul'] = $data['cells']$i][4];

}
The $emptyValues would be something like
[
    1 => 0,
    2 => 1, //2nd column, 1 empty cell
    3 => 3
];

The above is untested btw


text:
Q: Why is probability so unintuitive to us? There are so many famous paradoxes which are examples of how humans are unable to intuitively understand probability -- there's a discrepancy between their supposed actual experience and the mathematical evidence. There's things like the birthday problem where what we would expect the probability to be is much less than the actual, but also the monty hall problem where the confusion comes in why the answer is what it is.
My question is, what is the cause of this? Why are we biased into thinking things are more or less likely than they really are? Why do we find it so difficult to accept and understand the correct probability in the case of the monty hall problem, burnt pancake problem, etc.?

A: As another probabilistic problem consider: What is the probability that all of our intuitions are close to the probability for every mathematical problem?
In this case the answer my intuition tells me is it isn't 100% and I'm pretty sure in this case it is true.

A: Most of your questions can be answered by two simpler subquestions:

*

*Why does finite combinatorics seems to be so difficult?

*Why does our intuition is no big help with respect to probabilities?

Even so finite combinatorics indeed contains very "complex" problems, none of the examples you gave involved such "complex" problems. (Not sure in which sense the burnt pancake problem should be related to probability.) Missing experience in judging whether a discrete combinatorics problems allows a simple exact solution, or would better be solved by an approximative method, often leaves us with no solution at all, neither exact nor approximative. For example, is ${15 \choose 5}/{16 \choose 6}$ easy to evaluate exactly? Or should you rather use Stirling's approximation?
If we use our intuition about probabilities instead of addressing the underlying finite combinatorial problem, we often end-up with wrong results. One reason might be that probabilities are combined more multiplicative than additively. And it's also possible that probabilities are really inherently more difficult than finite combinatorics, but we can't believe that. I guess the problem with wrong results arises just from the context in school where we first encounter probability theory. Among all the nice and easily solvable linear problems, we learn this powerful linearization technique, without having much experience with the inherent challenges of the non-linear problems to which it can be applied.
.  .3. Why is true randomness so hard to capture, and why can probabilities be hard to get right.
In a certain sense, randomness contains an infinite amount of information, without actually containing any really useful information at all. This is the part of probability that runs directly counter our intuition.


text:
Q: Livewire global store works with file and cache - but not with Session Im making a deeply nested and reactive form renderer with Livewire. To do that I reached for a global store pattern, so any component in the hierarchy can refer to methods getStore() and setStore($store).
It seem to work, I could implement the store getter/setter methods with the data residing either in a json file or by using the Cache facade. However, my first choice would be to use the session, something like:
public function getStore()

{
    return Session::get($this->store_id);
}

public function setStore($store)
{
    Session::put($this->store_id, $store);
}

But, I can't get this to work specifically with Session. Have a hard time debugging why that is. It seems sometimes a session key is not set when it should, even though logging indicating it was set without any errors. I also tried explicitly persisting it with Session::save(); in case it does not reach the Terminable Middleware where it is normally persisted. No effect.
Any ideas why my store setup works with file_get_contents/Cache but not with Session?

A: Same happened to me. After refreshing the page, session would appear with old data. I even tried using setter with Session::forget() function, but it didn't work.
private function set($cart)
    {
        Session::forget('cart');
        Session::put('cart', $cart);
        Session::save();
    }

There was no error and logging data with Log::debug('after-set' . request()->session()->get('cart')['products']) and Log::debug('after-page-refresh' . request()->session()->get('cart')['products']) displayed 2 different arrays. Only thing that I found consistent is that after page refresh – only last Session::put() request was not saved – all other changes before it took effect.
I'll probably have to use Cache like you did, because such inconsistency is to risky for production.


text:
Q: How to installGestures on Reality Composer is there a way to add installGestures in reality composer?
i am able to do it in code, but i don`t want to mix too much code and ui parts. so i am searching how i can do the drag and drop part in reality composer.
here is the code snipit to do it in code and what i did so far.
arView.installGestures([.translation], for: modelEntity)

does anyone know how to enable this in reality composer?
thanks

A: I solved it with your hin now like this:
let startScene = try! RCProjectFile.loadStartScene()
if let cube = startScene.cube {
    if let cube = cube as? Entity & HasCollision {
        cube.generateCollisionShapes(recursive: true)
        arView.installGestures(for: cube)
    }
}

A: Reality Composer 1.5 allows you implicitly implement gestures only for animated behaviors. At the moment there's no explicit way to turn on Translation, Rotation or Pinch gestures in Reality Composer. Only via RealityKit, as you indicated.
arView.installGestures([.all], for: entity)

P. S.
Also, this post will show you how raycasting works in conjunction with RealityKit gestures.


text:
Q: Pytorch object detection model optimization I want to reduce the object detection model size. For the same, I tried optimising Faster R-CNN model for object detection using pytorch-mobile optimiser, but the .pt zip file generated is of the same size as that of the original model size.
I used the code mention below
import torch
import torchvision
from torch.utils.mobile_optimizer import optimize_for_mobile

model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)

model.eval()
script_model = torch.jit.script(model)
from torch.utils.mobile_optimizer import optimize_for_mobile
script_model_vulkan = optimize_for_mobile(script_model, backend='Vulkan')
torch.jit.save(script_model_vulkan, "frcnn.pth")

A: You have to quantize your model first
follow these steps here
& then use these methods
from torch.utils.mobile_optimizer import optimize_for_mobile
script_model_vulkan = optimize_for_mobile(script_model, backend='Vulkan')
torch.jit.save(script_model_vulkan, "frcnn.pth")

EDIT:
Quantization process for resnet50 model
import torchvision
model = torchvision.models.resnet50(pretrained=True)
import os
import torch

def print_model_size(mdl):
    torch.save(mdl.state_dict(), "tmp.pt")
    print("%.2f MB" %(os.path.getsize("tmp.pt")/1e6))
    os.remove('tmp.pt')
print_model_size(model) # will print original model size
backend = "qnnpack"
model.qconfig = torch.quantization.get_default_qconfig(backend)
torch.backends.quantized.engine = backend
model_static_quantized = torch.quantization.prepare(model, inplace=False)
model_static_quantized = torch.quantization.convert(model_static_quantized, inplace=False)

print_model_size(model_static_quantized) ## will print quantized model size


text:
Q: Template Specialization not working Consider the following code:
template<typename T, size_t... i>
class Bar{};

template<typename T1, typename T2>
class Foo{};

template<typename T1, size_t... i1>
template<typename T2, size_t... i2>
struct Foo<Bar<T1,i1...>,Bar<T2,i2...>>
{
    struct Eq {};
};

As you see, there is a variadic type Bar<T,size_t...> and a type Foo<T1,T2>. Foo has a specialization in case that two Bars are used as its template parameters. This specialization has an inner type Eq.
However, the following does not work:
typename Foo<Bar<int,2>,Bar<int,3>>::Eq b;

It tells that there is no type Eq in Foo<Bar<int,2>,Bar<int,3>>, i.e., the compiler does not pick the template specialization but the base definition of Foo<T1,T2> which indeed has no inner Eq type.
What am I doing wrong here? Why does the compiler not pick the specialization?

A: Just get rid of double template argument list:
template<typename T1, size_t... i1>
template<typename T2, size_t... i2>

Change to:
template<typename T1, size_t... i1, typename T2, size_t... i2>


text:
Q: OpenCart Change Pagination Links to SEO links I am trying to replace my Pagination within OpenCart.
From this:
$pagination->url = $this->url->link('product/search', $url . '&page={page}');
// Spits out
www.site.com/index.php?route=product/search&filter_name=QUERY&page=2

to this:
$pagination->url = $this->url->link('product/search', $url . '&page={page}');
// Spits out
www.site.com/search?q=QUERY&page=2

The file is in /catalog/controller/product/search.php (OC 1.5 near line 438-444). The full block of code:
$pagination = new Pagination();
$pagination->total = $product_total;
$pagination->page = $page;
$pagination->limit = $limit;
$pagination->text = $this->language->get('text_pagination');

$pagination->url = $this->url->link('product/search', $url . '&page={page}');
$this->data['pagination'] = $pagination->render();

A: I am assuming you have a .htaccess file setup and you are already using the SEO built into OpenCart 1.5.  If not, here are some pretty good instructions: Adding SEO Friendly URL'S to OpenCart by Kevin Dees
This is a partial hack, but if all you want to fix is the pagination, it should work.
First you need to add 3 lines to the .htaccess file I referenced earlier.  After this line:
RewriteRule sitemap.xml /index.php?route=feed/google_sitemap

Add:
RewriteCond %{QUERY_STRING} q=([^&]*) [OR]
RewriteCond %{SCRIPT_FILENAME} .*search$
RewriteRule search$ /index.php?route=product/search&filter_name=%1 [L,QSA]

So in all that section of the .htaccess file should look like:
RewriteBase /
RewriteRule sitemap.xml /index.php?route=feed/google_sitemap
RewriteCond %{QUERY_STRING} q=([^&]*) [OR]
RewriteCond %{SCRIPT_FILENAME} .*search$
RewriteRule search$ /index.php?route=product/search&filter_name=%1 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

Next you need to modify the /catalog/controller/product/search.php to generate the correct url.  I commented out the line that generates the link and added my own 2 lines above it(you'll need replace http://www.example.com with your own info):
$pagination = new Pagination();
$pagination->total = $product_total;
$pagination->page = $page;
$pagination->limit = $limit;
$pagination->text = $this->language->get('text_pagination');

$url = preg_replace("/filter_name/","q",$url);
$pagination->url = "http://www.example.com/search?".$url."&page={page}";
//$pagination->url = $this->url->link('product/search', $url . '&page={page}');

$this->data['pagination'] = $pagination->render();

Resources:

*

*I found some of the basics of RewriteRules from: RoScripts.com Pretty URLs - a guide to URL rewriting.

*Here's an example of how to pull from the query string from a blog comment by Nidaan here.

*And finally for everything else regarding Apache's mod_rewrite visit: Apache Module mod_rewrite


text:
Q: Return value from helper function not being waited for I am fairly new to NodeJS and Socket.io. I have my main file as index.js which calls a helper function verifyToken, but it does not wait for the return value from the helper function and continues forward.
I have added console.log to track execution flow as below:

File: index.js

socket.on('authenticate', function(data, ack) {
    var employeeID = data.employeeID;
    var token = data.Token;
    var tokenHelper = require("@helpers/tokenHelper"); //@helpers is an alias by using the module-alias package for helpers folder

    //Connect with helper to verify token
    var isValid = tokenHelper.verifyToken(employeeID, token);
    if(isValid) {
        socket.auth = true;
        ack("Authenticated");
        console.log("Authenticated");
    }
    else {
        ack("Unauthorised");
        console.log("Unauthorised");
    }
});

File: tokenHelper.js

var mysqlDatabase = require("@config/mysql");

module.exports = {
    verifyToken: function(employeeID, token, response) {
        var publicKey = fs.readFileSync(path.resolve("SOME_PATH"), "utf8");
        var isValid = false;

        //Verify options
        var verifyOptions = {
            issuer:  issuer,
            subject:  subject,
            audience:  audience,
            expiresIn:  expiresIn,
            algorithm:  ["RS256"]
        };

        //Extract data from received payload
        var receivedPayload = jwt.verify(token, publicKey, verifyOptions);
        var receivedEmailAddress = receivedPayload.sub;
        var receivedEmployeeID = receivedPayload.EmployeeID;
        console.log("Received email: " + receivedEmailAddress);
        console.log("Received id: " + receivedEmployeeID);
        console.log("Employee id: " + employeeID);

        //SQL Query to check EmployeeID in the database, verification of token is successful if entry is found in the database
        if(results !== null) {
            isValid = true;
            console.log("Verification successful");
        }

        return isValid;
    }
};

Current console log:
Received email: user@test.com
Received id: 1
Employee id: 1
Unauthorised
Verification successful
Expected console log:
Received email: user@test.com
Received id: 1
Employee id: 1
Verification successful
Unauthorised

A: File: tokenHelper.js
module.exports = {
    verifyToken: async (employeeID, token, response) => {
        try {
            const publicKey = fs.readFileSync(path.resolve('SOME_PATH'), 'utf8');
            let isValid = false;

            const verifyOptions = {
                issuer: issuer,
                subject: subject,
                audience: audience,
                expiresIn: expiresIn,
                algorithm: ['RS256'],
            };

            const receivedPayload = await jwt.verify(token, publicKey, verifyOptions);
            const receivedEmailAddress = receivedPayload.sub;
            const receivedEmployeeID = receivedPayload.EmployeeID;

            console.log(
                `Received email: ${receivedEmailAddress}, Received id: ${receivedEmployeeID} and Employee id: ${employeeID}`
            );

            if (results !== null) {
                isValid = true;
                console.log('Verification successful');
            }

            return isValid;
        } catch (error) {
            console.error(error);
        }
    },
};

File: index.js
const tokenHelper = require('@helpers/tokenHelper');
socket.on('authenticate', async (data, ack) => {
    try {
        const employeeID = data.employeeID;
    const token = data.Token;

    var isValid = await tokenHelper.verifyToken(employeeID, token);
    if (isValid) {
        socket.auth = true;
        ack('Authenticated');
        console.log('Authenticated');
    } else {
        ack('Unauthorised');
        console.log('Unauthorised');
    }
    } catch (error) {
        console.error(error);
    }
});

A: You missed the callback in the code. Please replace your code with the following and let me know if something went wrong.
Token Helper:
module.exports = {
  async verifyToken = (employeeID, token, response) => {
    const publicKey = fs.readFileSync(path.resolve("SOME_PATH"), "utf8");
    let isValid = false;

    const verifyOptions = {
      issuer: issuer,
      subject: subject,
      audience: audience,
      expiresIn: expiresIn,
      algorithm: ['RS256']
    };

    const receivedPayload = await jwt.verify(token, publicKey, verifyOptions);
    const receivedEmailAddress = receivedPayload.sub;
    const receivedEmployeeID = receivedPayload.EmployeeID;

    console.log(`Received email: ${receivedEmailAddress}, Received id: ${receivedEmployeeID} and Employee id: ${employeeID}`);

    if (results !== null) {
      isValid = true;
      console.log('Verification successful');
    }

    return isValid;
  }
};

File: index.js
const tokenHelper = require("@helpers/tokenHelper");
socket.on('authenticate', async (data, ack) => {
  const employeeID = data.employeeID;
  const token = data.Token;

  var isValid = await tokenHelper.verifyToken(employeeID, token);
  if (isValid) {
    socket.auth = true;
    ack('Authenticated');
    console.log('Authenticated');
  } else {
    ack('Unauthorised');
    console.log('Unauthorised');
  }
});


text:
Q: When selecting a cell in GridView/ListView, it selects another cell too I have a GridView where each cell contains an ImageView and TextView. When a user clicks on a cell, it changes the background color of that cell to Gray. However, when I scroll down, another cell is also selected (i.e. the background color is gray).
My guess is that this is because the cell reuses the same view as the cell that was just hidden when scrolling down.
This also happens when I change the orientation. If I select cell 1, when I change the orientation, another cell is now selected and cell 1 is not.
Thanks in advance.
public class LazyFeaturedTopicItemAdapter extends BaseAdapter {

private Activity activity;
private ArrayList<Topic> topics;
private static LayoutInflater inflater=null;
public PostItemImageLoader imageLoader;

public LazyFeaturedTopicItemAdapter(Activity a, ArrayList<Topic> d) {
    activity = a;
    topics=d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader=new PostItemImageLoader(activity.getApplicationContext());
}

public int getCount() {
    return topics.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public static class ViewHolder{
    public ImageView imgThumbnail;
    public TextView txtName;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    ViewHolder holder;

    final Topic topicItem = topics.get(position);

    if(convertView==null){
        vi = inflater.inflate(R.layout.featured_topic_item, null);
        holder=new ViewHolder();
        holder.txtName = (TextView) vi.findViewById(R.id.featured_topic_item_name);
        holder.imgThumbnail = (ImageView)vi.findViewById(R.id.featured_topic_item_thumbnail);

        vi.setTag(holder);
    }
    else
        holder=(ViewHolder)vi.getTag();
        holder.txtName.setText(topicItem.getName());

    holder.imgThumbnail.setTag(topicItem.getPictureLink());
    imageLoader.DisplayImage(topicItem.getPictureLink(), activity, holder.imgThumbnail);

    vi.setOnClickListener(
            new View.OnClickListener() {

                @Override
                public void onClick(final View v) {

                    if (topicItem.isSelected) {
                        v.setBackgroundColor(Color.WHITE);
                        topicItem.isSelected = false;
                    }
                    else {
                        v.setBackgroundColor(Color.GRAY);
                        topicItem.isSelected = true;
                    }
                }

            }
    );
    return vi;
}
}

Here is the solution in case anybody is interested. I added the following code before the listener.
    if (topicItem.isSelected) {
        vi.setBackgroundColor(Color.GRAY);
    }
    else {
        vi.setBackgroundColor(Color.WHITE);
    }

A: You are right in your guess, the view is being reused
In order to solve the problem, you could add
vi.setBackgroundColor(Color.WHITE);
topicItem.isSelected = false;

just before setting the listener, see it as the 'default' behavior
I hope that helps


text:
Q: How to add Drawer for SliverAppBar This is my code, copied from here:
SliverAppBar(
  expandedHeight: 150.0,
  flexibleSpace: const FlexibleSpaceBar(
      title: Text('Available seats'),
    ),
    actions: < Widget > [
      IconButton(
        icon: const Icon(Icons.add_circle),
          tooltip: 'Add new entry',
          onPressed: () { /* ... */ },
      ),
    ]
)

But I need to add a Drawer. How can I do that?
I am trying to rebuild my app in Flutter.
Converting java android  app to flutter
I replaced the icon but how can I create a Drawer?
leading: IconButton(icon: Icon( Icons.menu ),onPressed: ()=>{},)

My full code
@override
  Widget build(BuildContext context) {

  return NestedScrollView(
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return <Widget>[
          SliverAppBar(
            leading: IconButton(
              icon: Icon(Icons.menu),
              onPressed: () => {},
            ),
            actions: <Widget>[
              IconButton(
                onPressed: () => {},
                icon: Icon(Icons.shopping_cart),
              )
            ],
            expandedHeight: 200.0,
            floating: false,
            pinned: true,
            flexibleSpace: FlexibleSpaceBar(
                centerTitle: true,
                title: Text("My Pet Shop",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.0,
                    )),
                background: Image.network(
                  "https://firebasestorage.googleapis.com/v0/b/my-pet-world.appspot.com/o/images%2Fbannerads%2FxTmAblJI7fMF1l0nUa1gM32Kh9z1%2F734rm6w7bxznp%2FPETWORLD-HOME-SLIDER-KITTENS.webp?alt=media&token=cf7f48bb-6621-47b3-b3f8-d8b36fa89715",
                  fit: BoxFit.cover,
                )),
          ),
        ];
      },
      body: Container(
        margin: EdgeInsets.only(top: 0),
        child: Column(
          children: <Widget>[
            Expanded(
              //getHomePageWidget()
              child: ListView(
                padding: EdgeInsets.all(0.0),
                children: <Widget>[getHomePageWidget()],
              ),
            )
          ],
        ),
      ));
 }

A: Drawer is a property for Scaffold. Once you set a drawer property, the menu icon will automatically appear in the SliverAppBar.
Return this inside your build method, and you will get what you are looking for.
  return Scaffold(
    body: CustomScrollView(
      slivers: <Widget>[
        SliverAppBar(
          expandedHeight: 200.0,
          flexibleSpace: const FlexibleSpaceBar(
            title: Text('Available seats'),
          ),
          actions: <Widget>[
            IconButton(
              icon: const Icon(Icons.add_circle),
              tooltip: 'Add new entry',
              onPressed: () {},
            ),
          ],
        ),
        SliverList(
          delegate: SliverChildListDelegate([
            getHomePageWidget(),
          ]),
        ),
      ],
    ),
    drawer: Drawer(),
  );

NOTE: if you have multiple Scaffold in the tree above the CustomScrollView than the Drawer should be in the most bottom Scaffold


text:
Q: Using the Weak-Law of large numbers Consider two sequence $X_n,Y_n$ of random variable with Bernoulli distribution ($p=0.5$).
Let $Z_n\:=\:max\left(X_n,Y_n\right)$.
How to calculate $$\lim _{n\to \infty }\left(\frac{Z_1+Z_2+..+Z_n}{n}\right)=?$$
So far what i did is like this:
I calculated the expectation of $\frac{Z_1+Z_2+..+Z_n}{n}$ and i got this: $$E\left[\frac{Z_1+Z_2+..+Z_n}{n}\right]\:=\:\frac{1}{n}E\left[Z_1+Z_2+..+Z_n\right]\:=\:\frac{1}{n}\left(E\left[Z_1\right]+E\left[Z_2\right]+\:...\:+E\left[Z_n\right]\right)\:=\:\frac{1}{n}\left(E\left[\:max\left(X_1,Y_1\right)\right]+E\left[\:max\left(X_2,Y_2\right)\right]+\:...\:+E\left[\:max\left(X_n,Y_n\right)\right]\:\right)$$
and because $X_n,Y_n$ are both Bernoulli with $p=0.5$ it doesn't matter which one of them is the maximum, so i continued and i got:
$$=\:\frac{1}{n}\left(0.5+0.5+...\:+0.5\right)\:=\:\frac{1}{n}0.5\cdot n\:=\:0.5$$
And by using the Weak law of large numbers i conclude that $$\lim _{n\to \infty }\left(\frac{Z_1+Z_2+..+Z_n}{n}\right)=0.5$$
But i think i'm missing something important in the calculations here..it's even true what i did? can someone give any feedbacks? tnx a lot in advance!

A: Presumably your $X_n$'s and $Y_n$'s are all supposed to be independent.  Assumptions such as this are important, and should be stated.
Note that $\max(X_n, Y_n) = 1$ unless both $X_n$ and $Y_n$ are $0$, in which case it is $0$.  So
$E[\max(X_n, Y_n)] = 3/4$, not $1/2$.