text:
Q: Compare all elements of a std::vector with every other element in the same vector efficiently I'm new to C++.
I'm trying to find how to iterate through a vector to compare every element with every other element, where the comparison order is irrelevant where;

(a 'compared to' b) = (b 'compared to' a)

So checking one means you don't need to compare every value to EVERY other value, just the remaining ones.
I have something that's like this TOY algorithm;
#include <vector>

typedef std::vector<double> vector_t;

int countTheFoo(const vector_t &v)
{
  int fooFound {0};
  for (auto it1 = v.begin(); (it1 != v.end()); it1++)
  {
    for (auto it2 = it1.next(); (it2 != v.end()); it2++)
    {
      if testForFoo(*it1, *it2)
      {
        // Woot! Found some...
        fooFound++;
      }
    }
  }
  return fooFound;
}

vector_t foo { 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0 };

int numFoo {countTheFoo(foo)};

I'm actually comparing lines to find ones which intersect not simple doubles but the technique would be the same.
It's the;
for (auto it2 = it1.next(); (it2 != v.end()); it2++)

part that I think could be done more efficiently using lambdas.
This approach works, but;

*

*Is it the most efficient way of doing this sort of iteration?

*Can it be done as a lambda using std::for_all()?
Thank you.

A: No. You don't need to test (it1 != it2) because by the definition of your loop on it2, it2 will always be greater than it1. Efficiency will be increased if you delete that phrase from your code.
You probably could use std::for_all but it's not clear that that would increase the efficiency of the code.

A: Use a std::set, and a single loop to check if the value in the vector already exists in the set; and if not insert it.
This is really what std::set is for. It'll be hard to come up with a lookup implementation that will outperform std::set.


text:
Q: Two fields don't get saved after submitting form. Django I have two model fields (hobbies and languages) that don't get saved when the user submits the form. They are many to many fields connected to separate models. But I'm not sure how to have them save in the model.
This is the model:
# this is model for user
class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')

    hobbies = models.ManyToManyField(Hobby)
    languages = models.ManyToManyField(Language)

    profilepic = models.ImageField(upload_to='static/images/Profile Pictures', blank=True)
    city = models.ForeignKey(City)
    slug = models.SlugField(unique=True)

    average_rating = models.IntegerField(default=0)
    ratings_count = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        # Uncomment if you don't want the slug to change every time the name changes
        self.slug = slugify(self.user.username)
        super(UserProfile, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.user.username

This is the Hobby and Language models:
# this is the model for hobbies - one to many relationship with User
class Hobby(models.Model):
    hobby = models.CharField(max_length=128)

    def save(self, *args, **kwargs):
        # if self.id is None:
        # self.slug = slugify(self.name)
        self.slug = slugify(self.hobby)
        super(Hobby, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.hobby

# this is the model for languages - one to many relationship with User
class Language(models.Model):
    language = models.CharField(max_length=128)

    def save(self, *args, **kwargs):
        # if self.id is None:
        # self.slug = slugify(self.name)
        self.slug = slugify(self.language)
        super(Language, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.language

This is the view that saves the form data into the database:
def createprofile(request):

    registered = False
    if request.method == 'POST':
        user = User.objects.get(username = request.user.username)
        user_form = UserForm(data=request.POST, instance = user)

        profile_form = UserProfileForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user

            if 'profilepic' in request.FILES:
                profile.profilepic = request.FILES['profilepic']

            profile.save()

            registered = True

            if 'next' in request.GET:
                return redirect(request.GET['next'])

        else:
            print user_form.errors, profile_form.errors

    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    return render(request,
            'createprofile.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )

A: When using commit=False in your save method, Django provides a save_m2m method to create the relation.
https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#the-save-method
As stated by Django docs at the link above:

Another side effect of using commit=False is seen when your model has a many-to-many relation with another model. If your model has a many-to-many relation and you specify commit=False when you save a form, Django cannot immediately save the form data for the many-to-many relation. This is because it isn't possible to save many-to-many data for an instance until the instance exists in the database.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ruby on Rails - Method Name Identical to ActiveRecord Method In my Rails model I have a description method:
def description
  if self.channels.nil?
    return self.allowed_ip_addresses
  else
    return self.channels.to_s + ' channels - ' + self.allowed_ip_addresses
  end
end

I have quite a few models where I created a description method which returns some useful info based on the other properties of that model.
The problem I have just realised is that this model in particular has a description column in it's table so I was just wondering the best way to solve this, I've looked around but not found anything useful.
The first thing I thought of was to pass an argument when calling description, e.g.
def description(table_value = 0)
  if table_value
    return self.description
  end

  if self.channels.nil?
    return self.allowed_ip_addresses
  else
    return self.channels.to_s + ' channels - ' + self.allowed_ip_addresses
  end
end

but soon realised that this is pointless since it will just call the description method recursively and die (assuming a 1 is passed with the call to description).
I could also change the table column name but it's used elsewhere so I'm just trying to see if there is an alternative solution.

A: I would definitely rename your custom description method.

A: Ruby has the concept of "super" which lets you call methods in parent classes or modules. In Rails, Active Record lets you take advantage of this by overriding the "column method" and still get to the database value by calling super. It's not really clear from your question under what conditions you want to use the database value and when you want to use the custom logic. Here's some pseudo code to get you started though:
def description
  return super if Use Database Value?

  if self.channels.nil?
    return self.allowed_ip_addresses
  else
    return self.channels.to_s + ' channels - ' + self.allowed_ip_addresses
  end
end


text:
Q: Replace double quotes with single quotes at the extremes of string only I have a string
var myString = "[{"portal.home":"Home"},{"displaytag.tracking.id":"Item ID"}]";

I want the output as
myString  = '[{"portal.home":"Home"},{"displaytag.tracking.id":"Item ID"}]';

A: If you create a string with double quotes, you cannot have unescaped double quotes inside it.
You cannot write
var myString = "A "B" C";

That will be a syntax error. However,
var myString = "A \"B\" C";

is exactly the same thing as:
var myString = 'A "B" C';

The resulting value of myString will be exactly the same. It's not like the first example will contain any escape markers in the final string. The escapes are only there to assist the creation of the string, which will be exactly A "B" C, in both cases; often wrapped in double quotes when being logged, to denote that the type is a string.
So if you run console.log(myString); it will say "A "B" C", but the value of myString is simply A "B" C. This is simply a result of how the developer tools represent a string. There is nothing about the string itself that says that it was created with double quotes. The developer tools could equally well have just logged the value in a special color, but surrounding with double quotes happens to be the conventional way of denoting a string.

A: You could do it with .slice():
var newString =  "'" + myString.slice(1, -1) + "'";

Or with regex:
var newString = myString.replace(/^"|"$/g, "'");


text:
Q: Vlc video architecture I am studying the VLC source code in order to understand where exactly VLC writes the decoded frame to the screen. I'm basically interested in the qt ui version, and the windows and linux platforms.
I have come as far as tracing from avcodec_decode_video2 up until the point where it writes the frame to a queue using vout_PutPicture and picture_fifo_Push. On the other end, I see there is a Thread object that calls ThreadDisplayRenderPicture, which in turn calls vout_display_Display, which calls Display. I expected this last function to be the one where the bytes for the video frame actually get copied to the frame buffer, but all it does is set the size, and then release the picture.
Could someone explain to me, or point me to a resource that does, where exactly does VLC writes the picture_t structure that is sitting in the queue to the WId structure, effectively writing the frame to the screen? Any link to a more thorough explanation of VLC's video architecture would be great too!

A: I cannot directly answer your question, but provide you with a reference to a thorough explanation of VLC's architecture. (As stated in your last sentence)
Christophe Massiot from the University of Klagenfurt has written a paper on the VLC media player API Documentation. You can find it on google here and on google scholar here.
It includes the following illustration, which may lead you in the right direction.

I think the document could prove useful to your question. Take a look at Chapter 5 describing the video output layer


text:
Q: How to call a different part of a script with -x I am designing a script to install a lot of my common applications but I was wondering if there is a way to add a -t tag to go a different part of a script so -t called the tutorial and nothing just lists help  for it?

A: Yes, but you would have to do some command line parsing.
This is without using getopt:
case "$1" in
  -t) do_tutorial
      exit 0 ;;
  -i) do_install "$2"
      exit 0 ;;
  -h) do_usage
      exit 0 ;;
  *)  do_usage >&2
      exit 1 ;;
esac

This is just an example but it will take the first thing after the script name on the command line ($1, the flag) and depending on its value it will do different things.  Then you would have functions that implement the different behaviours that you need for supporting each flag on the command line, like e.g.
do_usage () {
  cat <<USAGE_END
Usage:  script [ -i "component" | -h | -t ]

Options:

  -i "component"    Install "component"
  -h                Show this help text
  -t                Show tutorial

USAGE_END
}

Look into getopt or Bash's getopts for how to do more complicated command line parsing.
One simple example of getopts usage: https://unix.stackexchange.com/a/292242/116858


text:
Q: Aws IAM group: Setup readonly access on log group on Terraform Does someone know how to setup read-only access to specific log groups?
resource "aws_iam_policy" "logs" {
  name        = "AWSLogs${title(var.product)}"
  description = "Logging policy for ${title(var.product)}"
  policy      = <<EOF
  {
        "Version": "2012-10-17",
        "Statement": [
              {
                "Effect": "Allow",
                "Action": [
                    "logs:Get*",
                    "logs:List*",
                    "logs:Filter*"
                ],
                "Resource": [
                    "arn:aws:logs:::log-group:${aws_cloudwatch_log_group.one.arn}:log-stream:*",
                    "arn:aws:logs:::log-group:${aws_cloudwatch_log_group.two.arn}:log-stream:*",
                    "arn:aws:logs:::log-group:${aws_cloudwatch_log_group.three.arn}:log-stream:*"
                ]
            },
            {
                "Effect": "Allow",
                "Action": [
                    "logs:DescribeLogGroups"
                ],
                "Resource": "*"
            }
        ]
   }
EOF
}

resource "aws_iam_group_policy_attachment" "logs" {
  group      = "${aws_iam_group.logs.name}"
  policy_arn = "${aws_iam_policy.logs.arn}"
}

resource "aws_iam_group" "logs" {
  name = "${title(var.product)}Logs"
}

I'm currently struggeling to setup to only have access on specified log groups, but I can only get access to them when I set my resource to "*". This is not possible when I setup this dedicated to predefined log groups. Does someone have a good practice or solution? When I try this solution above I only get

Not authorized to perform: logs:FilterLogEvents
  , when I try to access it via an user which is part of the IAM group "logs".

A: aws_cloudwatch_log_group.one.arn already is the full ARN of the one log group, i.e.,

arn:aws:logs:us-east-1:123456789012:log-group:one

So refer only to that in the Resources list:
resource "aws_iam_policy" "logs" {
  name        = "AWSLogs${title(var.product)}"
  description = "Logging policy for ${title(var.product)}"
  policy      = <<EOF
  {
        "Version": "2012-10-17",
        "Statement": [
              {
                "Effect": "Allow",
                "Action": [
                    "logs:Get*",
                    "logs:List*",
                    "logs:Filter*"
                ],
                "Resource": [
                    "${aws_cloudwatch_log_group.one.arn}:log-stream:*",
                    "${aws_cloudwatch_log_group.two.arn}:log-stream:*",
                    "${aws_cloudwatch_log_group.three.arn}:log-stream:*"
                ]
            },
            {
                "Effect": "Allow",
                "Action": [
                    "logs:DescribeLogGroups"
                ],
                "Resource": "*"
            }
        ]
   }
EOF
}

A: I was able to kind of solve this by adding a Condition filtering by tags to the Statement and making sure that the log groups and streams are tagged correspondingly:
"Condition": {
   "StringEquals": {
     "aws:ResourceTag/sometagname": "sometagvalue"
   }
}


text:
Q: How to clone the random access stream? I want to clone the IRandomAccessStream. I tried the CloneStream() to clone the stream but it not supported. Is there any way to clone the random access stream.
Thanks,
Santhiya A

A: You can use the CopyTo method
https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.copyto?view=netframework-4.7.2

A: You can try converting it to a byte[]  and then clone the byte[] in to new IRandomAccessStream.
    public async Task<IRandomAccessStream> CloneIRandomeAccessStream(IRandomAccessStream randomAccessStream)
    {
        var reader = new DataReader(randomAccessStream.GetInputStreamAt(0));
        byte[] bytes = new byte[randomAccessStream.Size];
        await reader.LoadAsync((uint)randomAccessStream.Size);
        reader.ReadBytes(bytes);
        MemoryStream stream = new MemoryStream(bytes.ToArray());
        IRandomAccessStream ClonerandomAccessStream = stream.AsRandomAccessStream();
        return ClonerandomAccessStream;
    }


text:
Q: Runtime Error 429; Can't Create Object (Excel 2007) My application is as follows: I am using an Access 2007 Database for data storage and using Excel 2007 as the front end. I am using Microsoft.ACE.OLEDB.12.0 for ADODB Connection and have referenced the libraries (dlls) needed for this. My code below is in an Excel Module and works on 9 out of 12 machines. The other are getting the "Runtime Error 429" and are failing on line 25 of the code which attempts to create the ADODB Object. Can anyone help me with a troubleshooting plan to figure out what is wrong with these machines? I think it may be a registry issue, but wanted to see what you guys have to say. All machines have XP SP3 OS and Office 2007 Installed. Thank you for any help.
Cross-posted at http://www.mrexcel.com/forum/excel-questions/723189-runtime-error-429%3B-cant-create-object.html
Public Sub AccessData()
Dim UserID As String
Dim adoConn As ADODB.Connection
Dim adoRS As ADODB.Recordset
Dim sSQL, ConnSQL As String
Dim IDName As String
On Error GoTo err_handler
10:    UserID = Environ("USERNAME")
20:    pwd = Worksheets(2).Cells(8, 2).Value
25:    Set adoConn = CreateObject("ADODB.connection")
26:    Set adoRS = CreateObject("ADODB.Recordset")
30:    ConnSQL = Worksheets(2).Cells(10, 3).Value
35:    adoConn.ConnectionString = ConnSQL
40:    adoConn.Open
50:    adoRS.CursorType = adOpenDynamic
60:    adoRS.CursorLocation = adUseClient
70:    adoRS.ActiveConnection = adoConn
90:    sSQL = "SELECT fname, lname FROM Staff WHERE userid ='" & UserID & "'"
100:    adoRS.Source = sSQL
110:    adoRS.Open
120:    Worksheets(2).Cells(2, 2).CopyFromRecordset adoRS
130:    adoRS.Close
140:    adoConn.Close
150:    Set adoRS = Nothing
160    Set adoConn = Nothing
170:    Call GetPlans(UserID)
err_handler:
    MsgBox "The code failed at line " & Erl, vbCritical
End Sub


text:
Q: How to correctly install YouCompleteMe on mac? I have the following line in ~/.vimrc
Plugin 'valloric/youcompleteme'

Running PluginInstall successfully installed the plugin.
Then I ran python3 install.py --clang-completer under /Users/$UserName/.vim/bundle/youcompleteme.
Running vim gave me:

YouCompleteMe unavailable: requires Vim compiled with Python (3.5.1+) support.

The python3 version is 3.6.8.
vim --version shows that it has python3 support:
VIM - Vi IMproved 8.1 (2018 May 18, compiled Dec 13 2019 14:45:40)
Included patches: 1-503, 505-680, 682-1312
Compiled by root@apple.com
Normal version without GUI.  Features included (+) or not (-):
+acl               +extra_search      -mouse_netterm     -tag_old_static
-arabic            -farsi             +mouse_sgr         -tag_any_white
+autocmd           +file_in_path      -mouse_sysmouse    -tcl
+autochdir         +find_in_path      -mouse_urxvt       -termguicolors
-autoservername    +float             +mouse_xterm       +terminal
-balloon_eval      +folding           +multi_byte        +terminfo
-balloon_eval_term -footer            +multi_lang        +termresponse
-browse            +fork()            -mzscheme          +textobjects
+builtin_terms     -gettext           +netbeans_intg     +textprop
+byte_offset       -hangul_input      +num64             +timers
+channel           +iconv             +packages          +title
+cindent           +insert_expand     +path_extra        -toolbar
-clientserver      +job               -perl              +user_commands
-clipboard         +jumplist          +persistent_undo   -vartabs
+cmdline_compl     -keymap            +postscript        +vertsplit
+cmdline_hist      +lambda            +printer           +virtualedit
+cmdline_info      -langmap           -profile           +visual
+comments          +libcall           +python/dyn        +visualextra
-conceal           +linebreak         -python3           +viminfo
+cryptv            +lispindent        +quickfix          +vreplace
+cscope            +listcmds          +reltime           +wildignore
+cursorbind        +localmap          -rightleft         +wildmenu
+cursorshape       -lua               +ruby/dyn          +windows
+dialog_con        +menu              +scrollbind        +writebackup
+diff              +mksession         +signs             -X11
+digraphs          +modify_fname      +smartindent       -xfontset
-dnd               +mouse             +startuptime       -xim
-ebcdic            -mouseshape        +statusline        -xpm
-emacs_tags        -mouse_dec         -sun_workshop      -xsmp
+eval              -mouse_gpm         +syntax            -xterm_clipboard
+ex_extra          -mouse_jsbterm     +tag_binary        -xterm_save
   system vimrc file: "$VIM/vimrc"
     user vimrc file: "$HOME/.vimrc"
 2nd user vimrc file: "~/.vim/vimrc"
      user exrc file: "$HOME/.exrc"
       defaults file: "$VIMRUNTIME/defaults.vim"
  fall-back for $VIM: "/usr/share/vim"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H   -DMACOS_X_UNIX  -g -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
Linking: gcc   -L/usr/local/lib -o vim        -lm -lncurses  -liconv -framework Cocoa

A: I use YouCompleteMe for C and built vim 8.2 from source on my mac with OSX 10.15. If you want to use it for c-family languages it's pretty finicky. You might spend a lot of time reading posts like these, ones where someone was having a different issue 3 months ago and there's no answer.
To build vim with python3 support you can do one of two things,
git clone https://github.com/vim/vim.git
cd vim
git pull
cd src
make distclean
./configure --with-features=huge
make
sudo make install

This will give you more than just python3. There aren't any drawbacks to having the extra features as far as I know.
my vim is installed in $HOME, I think the install script symlinked the binary to /usr/local/bin/vim.
or you can use homebrew and macvim which is what I would recommend,
brew install macvim

sources:
https://www.vim.org/git.php
https://vim.fandom.com/wiki/Building_Vim

A: YouCompleteMe need that VIM, that VIM must support Python3.
(That means that you need to use Python3 to config installling VIM).
As your VIM 's "vim --version" shows, your installed VIM Do Not Support
Python3(Beacuse the symbol before python3 is that '-', that '-' minus
means Your installed VIM do not support python3).
Even your Mac defualt python3 is over 3.5.1,
your installed VIM support python@2(from "+python/dyn" sa your "vim --version" shows).
Please use Homebrew reinstall VIM with supporting python3,
DO NOT USE your Mac default installed VIM.
Could refer:
0.Installing Vim with Python3 support on MacOS.
1.Debian Manually install VIM which suppoet Python3.
2.How do I install vim on OSX with Python 3 support?


text:
Q: Open pull request on a single commit I have a branch with 3 or 4 commits pushed to it on GitHub.  I would like to open a pull request to our master branch involving only one of those commits.  However, the GitHub interface appears to require a new PR to include all those commits.
Is it possible to open a new pull request using a subset of my branch's commits?

A: It would be best to create a branch just to encompass that pull request. It sounds like one isolated feature or bug fix anyway. During the pull request, the maintainer of the repository might request changes. It is easier to incorporate those changes to the pull request if you limit your Git branch to only the changes necessary for the pull request.


text:
Q: kubectl tls secret automatisation I'm trying to use tls secret on gke ingress (gpc LB7) and I'm stuck. To be clear I can create the tls secret using the kubectl command:
kubectl create secret tls wildcard-cert --cert fullchain.pem --key private.pem

That works just fine, but for automatisation purpose, I would like to be able to deploy the secret from a yaml file using the same files, those are wildcard used in more than one place and stored in a secret engine.
I can't use secretgenerator as it doesn't seems to support tls and the secret type tls doesn't seems to be able to take files.
What I would like to be able to create:
---
apiVersion: v1
kind: Secret
metadata:
  name: wildcard-cert
type: kubernetes.io/tls
data:
  tls.crt: fullchain.pem
  tls.key: private.pem

A: You should be able to use secretGenerator as I don't think nginx cares if it's a TLS or Opaque secret.  A TLS secret is really just an Opaque secret with a known layout.
Rename your key/cert files:  fullchain.pem to tls.crt and private.pem to tls.key.
Using secretGenerator:
secretGenerator:
- name: wildcard-cert
  files:
  - tls.crt
  - tls.key

Which should generate a Secret like:
apiVersion: v1
kind: Secret
metadata:
  name: wildcard-cert
data:
  tls.crt: |
        MIIC2DCCAcCgAwIBAgIBATANBgkqh ...
  tls.key: |
        MIIEpgIBAAKCAQEA7yn3bRHQ5FHMQ ...

which should work with GKE Ingress.
EDIT:
Note that
kubectl create secret tls wildcard-cert --cert fullchain.pem --key private.pem
will actually create a secret that looks like:
apiVersion: v1
    kind: Secret
    metadata:
      name: wildcard-cert
    type: kubernetes.io/tls
    data:
      tls.crt: |
            MIIC2DCCAcCgAwIBAgIBATANBgkqh ...
      tls.key: |
            MIIEpgIBAAKCAQEA7yn3bRHQ5FHMQ ....

which should be equivalent to what secretGenerator generated for all practical purposes.


text:
Q: What are the security risks of hardcoding username password in an angular 10 component? I have a web app, frontend framework for which is Angular v 10. Dist folder generated by angular build is deployed in S3(public bucket used as a static website endpoint) behind Cloudfront and backend is handled serverless API Gateway > Lambda with Go. For the API Gateway endpoint calls from Angular I have AWS Amplify integrated and API Gateway authentication is through Cognito User Pools.
Everything works great but while setting up I realized that in my angular component I have hardcoded the username and password in the angular component like below for initial Amplify Auth calls to get the token to make backeend API calls. Is there a better and secure way to do this? If I code it this way as I found in most examples what are the security risks?
//starting Angular component code snippets
@Component({
  selector: 'app-abcd',
  templateUrl: './abcd.component.html',
  styleUrls: ['./abcd.component.scss']
})
export class AbcdComponent implements OnInit {

  constructor(private apiService: ApiService, private changeDetectorRef: ChangeDetectorRef, private sanitizer:DomSanitizer) { }

  idToken:string ='';
  error: any;

**//Any security risks here? What is the best practice to securely do this in Angular?
      userdata = {username : "uname", password : "passcode"};**

  ngOnInit(): void {
    this.changeDetectorRef.detectChanges();

    Auth.signIn(this.userdata).then(user => {
      if (user.challengeName === 'NEW_PASSWORD_REQUIRED'){
        Auth.completeNewPassword(user, "hello");
      }
      this.idToken=user.signInUserSession.idToken.jwtToken;
      this.apiService.doTheThing(this.idToken).subscribe(res => {
        if (res!=null){
          console.log(res.response);
      }, error => this.error = error);
    }).catch(err => {
      console.log(err);
    });
  }
}

Is this any better if I store the hardcoded username and password in src/environments/environment and import it in the component and use it like this below.
src/environments/environment
export const environment = {
  production: true,
  username: 'hellouser',
  password: 'hellopasscodee',
};

In angular component
import { environment } from 'src/environments/environment';

userdata = {username : environment.username, password : environment.password};

This works as well but I am thinking how are hardcoded strings any safer in environment.ts than any other angular-related component ts files?


text:
Q: Compiling legacy components in Next.js (Can't resolve 'react/jsx-dev-runtime', Global CSS cannot be imported) I've just spun up a new Next.js project (React v 17.0.1). I am attempting to compile and import components from a legacy project. Seeing a few errors getting things to work:

*

*Module not found: Can't resolve 'react/jsx-dev-runtime'. I have a hunch this may have something to do with the new JSX compiler in React 17.

*

*This can be resolved by adding /** @jsxRuntime classic */ to the top of the file, but i'd prefer to just turn on the classic compiler. Is this possible?

*Global CSS cannot be imported from files other than your Custom <App>

*

*This can be resolved by using modules, or importing in pages/_app. However, i'd like to turn this safety feature off, leaving the legacy components as is.

Questions:

*

*How can I force Next.js to use the classic JSX compiler instead of the new automatic one

*How do I turn off the safety "feature" forcing CSS to only be imported to _app?

A: This was solved by downgrading the React dependency to 16 in package.json


text:
Q: Adding data to database using modal form in bootstrap I've been really struggling with this today. Can't seem to get it to work, all it does is navigates to 'add-entry.php?go' in the navbar, but goes grey then reloads the index.php with modal still intact with my entries in it.
Here's my html, including the form and javascript filter input.
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>ProSys Component Lookup</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="favicon.ico">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <link rel="stylesheet" href="css/main.css">

ProSys Component Lookup

      <button type="button" class="btn btn-primary btn-block" data-toggle="modal" data-target="#myModal">Add New Item</button>

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

Add New Item

              <form method="post" action="add-entry.php?go" role="form">

                  Location:
                  <input type="text" class="form-control" name="location">

                  Category:
                  <select class="form-control" name="category">
                    <option>Processor</option>
                    <option>Diode</option>
                    <option>Fuse</option>
                    <option>Regulator</option>
                    <option>Capacitor</option>
                    <option>Inductor</option>
                    <option>LED</option>
                    <option>Gate</option>
                    <option>Modem</option>
                    <option>Transceiver</option>
                    <option>Thermistor</option>
                    <option>Load Switch</option>
                    <option>Op Amp</option>
                    <option>Optocoupler</option>
                    <option>Line Driver</option>
                    <option>ESD Protection</option>
                    <option>ADC</option>
                    <option>RTC</option>
                  </select>

                  Manufacturer:
                  <input type="text" class="form-control" name="manufacturer">

                  Description:
                  <textarea type="text" class="form-control" name="description" rows="5"></textarea>

                  PackageSize:
                  <input type="text" class="form-control" name="packagesize">

                  Supplier:
                  <select class="form-control" name="supplier">
                    <option>Farnell</option>
                    <option>RS</option>
                    <option>Rapid</option>
                  </select>

                  Supplier Number:
                  <input type="text" class="form-control" name="suppliernumber">

                  Stock:
                  <input type="text" class="form-control" name="stock">

                <button type="submit" class="btn btn-default">Add</button>

              </form>

        <form class="styled">
            <input type="text" class="form-control" onkeyup="myFunctionOne()" id="myInput" placeholder="Search..">
        </form>

                  Location
                  Manufacturer
                  Description
                  PackageSize
                  Supplier
                  SupplierNumber
                  Stock

                  <?php
                  include("dbconnect.php");

                  $result = mysql_query("SELECT DrawLocation, Manufacturer, Description, PackageSize, Supplier, SupplierNumber, Stock FROM complibrary");

                  while($complibrary = mysql_fetch_array($result))
                  {
                    echo"".$complibrary['DrawLocation']."	";
                    echo"".$complibrary['Manufacturer']."	";
                    echo"".$complibrary['Description']."	";
                    echo"".$complibrary['PackageSize']."	";
                    echo"".$complibrary['Supplier']."	";
                    //IF statement adds in links for web search via SupplierNumber
                    if ($complibrary['Supplier'] == 'Farnell') {
                      echo"".$complibrary['SupplierNumber']."	";
                    } elseif ($complibrary['Supplier'] == 'RS') {
                      echo"".$complibrary['SupplierNumber']."	";
                    } elseif ($complibrary['Supplier'] == 'Rapid') {
                      echo"".$complibrary['SupplierNumber']."	";
                    } else {
                      echo"".$complibrary['SupplierNumber']."	";
                    }
                    //IF statement end
                    echo"".$complibrary['Stock']."	";
                    echo "
";
                  }
                  mysql_close($conn);
                  ?>

And here's my add-entry.php
<!DOCTYPE html>

    <meta charset="utf-8">

    <?php
      if (isset($_POST['location'])){
        $hostname = "localhost";
        $username = "root";
        $password = "";
        $dbname = "componentlookup";

        $conn = mysql_connect($hostname, $username, $password);

        if (!$conn) {
          die('Could not connect: ' . mysql_error());
        }

        mysql_select_db($dbname, $conn);

        $location = $_POST['location'];
        $category = $_POST['category'];
        $manufacturer = $_POST['manufacturer'];
        $description = $_POST['description'];
        $packagesize = $_POST['packagesize'];
        $supplier = $_POST['supplier'];
        $suppliernumber = $_POST['suppliernumber'];
        $stock = $_POST['stock'];

        $query = mysql_query("INSERT INTO 'complibrary' (ID, DrawLocation, Category, Manufacturer, Description, PackageSize, Supplier, SupplierNumber, Stock) VALUES ('NULL', '$location', '$category', '$manufacturer', '$description', '$packagesize', '$supplier', '$suppliernumber', '$stock')");

        echo "Item added sucessfully. Click HERE to go back.";
        mysql_close($conn);
      }
    ?>

Any ideas?

A: I think you should put data-dismiss="modal" on the add button to close the window.
Also, I think you should not use mysql connection. Better, use mysqli or PDO.


text:
Q: Using R and paws: How to set credentials using profile in config file? I use SSO and a profile as defined in ~/.aws/config (MacOS) to access AWS services, for instance:
aws s3 ls --profile myprofilename
I would like to access AWS services from within R, using the paws() package. In order to do this, I need to set my credentials in the R code. I want to do this through accessing the profile in the ~/.aws/config file (as opposed to listing access keys in the code), but I haven't been able to figure out how to do this.
I looked at the extensive documentation here, but it doesn't seem to cover my use case.
The best I've been able to come up with is:
x = s3(config = list(credentials = list(profile = "myprofilename")))
x$list_objects()

... which throws an error: "Error in f(): No credentials provided", suggesting that the first line of code above does not connect to my profile as stored in ~/.aws/config.

A: An alternative is to generate a user/key with programmatic access to your S3 data. Then, assuming that ~/.aws/env contains the values of the generated key:
AWS_ACCESS_KEY_ID=abc
AWS_SECRET_ACCESS_KEY=123
AWS_REGION=us-east-1

insert the following line at the beginning of your file:
readRenviron("~/.aws/env")

A: This AWS blog provides details about how to get the temporary credentials for programatic access. If you can get the credentials and set the appropriate environment variables, then the code should work fine without the profile name.
Or You can also try the following if you can get temporary credentials using aws cli

*

*Check if you can generate temporary credentials
aws sts assume-role --role-arn <value> --role-session-name <some-meaningful-session-name> --profile myprofilename

*If you can execute the above successfully, then you can use this method to automate the process of generating credentials before your code runs.

*Put the above command in a bash script get-temp-credentials.sh and generate a JSON containing the temporary credentials as per the documentation.

*Add a new profile programmatic-access in the ~/.aws/config

[profile programmatic-access]
credential_process = "/path/to/get-temp-credentials.sh"

*

*Finally update the code to use the profile name as programmatic-access

A: If you have AWS cli credentials set up as a bash profile eg. ~/.aws/config:
[profile myprof]
region=eu-west-2
output=json

.. and credentials eg. ~/.aws/credentials:
[myprof]
aws_access_key_id = XXX
aws_secret_access_key = xxx

.. paws will use these if you add a line to ~/.Renviron:
AWS_PROFILE=myprof


text:
Q: Prove that there are at least 50% of numbers $b$ which satisfy ${b_0}^{n-1} \not \equiv {1} \mod{n}$ if one such $b_0$ exists .
Possible Duplicate:
Accuracy of Fermat's Little Theorem?

$n$ is odd and composite number,and there exists $b_0$ , $0<b_0<n$ such that $gcd(n,b_0)=1$ and ${b_0}^{n-1} \not \equiv {1} \mod{n}$
prove that there are at least 50% of numbers $b$ such that $0<b<n$ and $gcd(b,n)=1$ which satisfy ${b_0}^{n-1} \not \equiv {1} \mod{n}$


text:
Q: Error compiling gradle project with dependency on version 0.3.150227 google-cloud-dataflow-java-sdk-all I'm working on a Java app that is using Google Cloud Data flow and I'm getting errors when trying to compile using gradle.
Dependencies section in build.gradle is:
dependencies {
compile 'commons-codec:commons-codec:1.9'
compile 'com.google.cloud.dataflow:google-cloud-dataflow-java-sdk-all:0.3.150227'
compile 'com.google.inject.extensions:guice-multibindings:3.0'
compile 'com.google.inject:guice:3.0'

}
The error I'm getting is:

Could not resolve
  com.google.cloud.dataflow:google-cloud-dataflow-java-proto-library-all:0.3.150206.
  Required by:
        :telstra-targetingserver-cdf-cptmappings:0.0.1 > com.google.cloud.dataflow:google-cloud-dataflow-java-sdk-all:0.3.150227

Could not parse POM https://repo1.maven.org/maven2/com/google/cloud/dataflow/google-cloud-dataflow-java-proto-library-all/0.3.150206/google-cloud-dataflow-java-proto-library-all-0.3.150206.pom
    Could not find com.google.cloud.dataflow:google-cloud-dataflow-java-sdk-parent:LATEST.
            Searched in the following locations:
                file:/Users/pablocaif/.m2/repository/com/google/cloud/dataflow/google-cloud-dataflow-java-sdk-parent/LATEST/google-cloud-dataflow-java-sdk-parent-LATEST.pom
                file:/Users/pablocaif/.m2/repository/com/google/cloud/dataflow/google-cloud-dataflow-java-sdk-parent/LATEST/google-cloud-dataflow-java-sdk-parent-LATEST.jar
                https://repo1.maven.org/maven2/com/google/cloud/dataflow/google-cloud-dataflow-java-sdk-parent/LATEST/google-cloud-dataflow-java-sdk-parent-LATEST.pom
https://repo1.maven.org/maven2/com/google/cloud/dataflow/google-cloud-dataflow-java-sdk-parent/LATEST/google-cloud-dataflow-java-sdk-parent-LATEST.jar

LATEST appears to be missing in https://repo1.maven.org/maven2/com/google/cloud/dataflow/google-cloud-dataflow-java-sdk-parent/
The content at this time is:

A: This is a known issue which will be resolved with the next Maven push of Cloud Dataflow which is planned for next Monday (3/23).


text:
Q: Vmware workstation takes too much time to shut down Each time I shuting down my virtual machine - it takes like 30 minutes for VM Ware to complete the process. The shut down is done, but it shows a black screen and doesn't respond to any command. I can't do a Power > Power OFF or Power > Suspend. When I click it - nothing changes.
When trying to close - it says "still busy".
This happens only when using a Virtual Machine stored on an external hard drive. When Virtual Machine files are stored on a local drive - everything is OK.
Hard drive is working good.
Any suggestions how can I investigate the issue?

A: Maybe this might work for you, for me it worked.

VM Takes Long Time to Shutdown Fix

*

*Shut down the VM before you do anything; if something like a Production server, you should either backup the entire directory that holds the VM files or take a snapshot (depends on your product).

*In the VM's folder, locate the .VMX file

*Make a copy (backup) of the file (this is important!)

*Edit the file using notepad (don't use anything like Word) - locate the following entries in file - if you DO NOT find them, add them to the bottom of the file:
prefvmx.minVmMemPct = "100"
mainMem.useNamedFile = "FALSE"
mainMem.partialLazySave = "FALSE"
mainMem.partialLazyRestore = "FALSE"

*Save the file and exit notepad

*Start the VM - let it completely start, log in, then choose normal shutdown - should now shutdown in a matter of seconds.

  I've had no adverse effects with these settings but use at your own risk.

Source: http://davidmsterling.blogspot.com.br/2012/08/vmware-virtual-machine-takes-long-time.html

A: In case you use external hard drive try disabling write caching on the device
It helped me.

A: After I installed the vmware tools in the VM, the problem went away!

A: https://social.technet.microsoft.com/Forums/windows/en-US/099565e7-fd3f-41da-9595-5f17637298ea/pagefile-clearpagefileatshutdown?forum=w7itprogeneral
Modify this setting within the registry to speed up the process. Please first read the article(s) on topic from Microsoft.
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management]
"ClearPageFileAtShutdown"=dword:00000000

A: For me, uninstall and re-install VMware-Tools helped to power off in less than 1 min. Before, it took from like 20 minutes to never...

A: Periodically I have the same problem. This may be a coincidence but takes 2 seconds and worth trying. In the bottom right of the window there is an icon that looks like a yellow page with the right bottom corner curled. The icon is used for displaying vmware messages. I clicked it and it displayed a message totally unrelated to the problem. Yet soon as I closed the message the virtual machine immediately finished suspending.


text:
Q: Creating a Pandas dataframe column which is conditional on a function Say I have some dataframe like below and I create a new column (track_len) which gives the length of the column track_no.
import pandas as pd
df = pd.DataFrame({'item_id': [1,2,3], 'track_no': ['qwerty23', 'poiu2', 'poiuyt5']})

df['track_len'] = df['track_no'].str.len()
df.head()

My Question is:
How do I now create a new column (new_col) which selects a specific subset of the track_no string and outputs that depending on the length of the track number (track_len).
I have tried creating a function which outputs the specific string slice of the  track_no given the various track_len conditions and then use an apply method to create the column and it doesnt work. The code is below:
Tried:

def f(row):
    if row['track_len'] == 8:
        val = row['track_no'].str[0:3]
    elif row['track_len'] == 5:
        val = row['track_no'].str[0:1]
    elif row['track_len'] =7:
        val = row['track_no'].str[0:2]
    return val

df['new_col'] = df.apply(f, axis=1)
df.head()

Thus the desired output should be (based on string slicing output of f):
Output
{new_col: ['qwe', 'p', 'po']}

If there are alternative better solutions to this problem those would also be appreciated.

A: Your function works well you need to remove .str part in your if blocks. Values are already strings:
def f(row):
    if row['track_len'] == 8:
        val = row['track_no'][:3]
    elif row['track_len'] == 5:
        val = row['track_no'][:1]
    elif row['track_len'] ==7:
        val = row['track_no'][:2]
    return val

df['new_col'] = df.apply(f, axis=1)
df.head()

#Output:

    item_id track_no    track_len   new_col
0   1       qwerty23    8           qwe
1   2       poiu2       5           p
2   3       poiuyt5     7           po


text:
Q: How to retrieve the Video thumbnail in android I want to retrieve the video thumbnail from the SDCARD and show in GridView for both Android OS version 1.5  and 2.0. By using MediaStore class I can retrieve the thumbnail in only 2.0 and above but I want one common code to retrieve the Video thumbnail for 1.5 and 2.0 also.  Is this possible?

A: I don't think this is possible. The simplest API exists beginning in android-8, and is explained in this answer.


text:
Q: PHPUnit "Unknown option "--configuration" Process finished with exit code 1" in PhpStorm I am able to execute unit tests in the CLI using the following command:
/usr/local/Cellar/php@7.4/7.4.27/bin/php /Users/USERNAME/PhpstormProjects/PROJECT_FOLDER/vendor/phpunit/phpunit/phpunit /Users/USERNAME/PhpstormProjects/PROJECT_FOLDER/tests

However, i want to fire the tests from inside PhpStorm, but the IDE is automatically adding parameters to the executing command which causes an instant execute fail:
/usr/local/Cellar/php@7.4/7.4.27/bin/php /Users/USERNAME/PhpstormProjects/PROJECT_FOLDER/vendor/phpunit/phpunit/phpunit --configuration /Users/USERNAME/PhpstormProjects/PROJECT_FOLDER/phpunit.xml /Users/USERNAME/PhpstormProjects/PROJECT_FOLDER/tests --teamcity
Testing started at 11:51 ...
PHPUnit 9.5.10 by Sebastian Bergmann and contributors.

Unknown option "--configuration"

Process finished with exit code 1

When i disable the "Default configuration file" checkbox in Preferences > PHP > Test Frameworks > {current project config} - it says:
Unknown option "--no-configuration"

Process finished with exit code 1

Is there a way to disable the configuration parameter at all? I'm pretty new to unit tests and i don't even know which purpose this configuration file would even has...
I hope someone can help me - thanks in advance !!


text:
Q: two store function in one pig script I have a pig script to load , process and store the data.
If there are two store functions in the same single pig script, how it works?
a = load 'somefile' using PigStorage(',');
b ...
c ...
d ...
e = store d into 'output1';
f = store c into 'output2';

Does this run two times for each store. That is for store 'e' it process from 'a' to 'e' and for store 'f' it directly store 'c' since it is already processed or it will again start from 'a' ?

A: Generally speaking the underlying map/reduce framework has a multiple-output format so Pig can use that and run a two store script in a single job e.g. by having separate reduces and each would write to another file
However the actual map/reduce plan depends on what you do to get to c and d - sometimes that processing would require more than a single job - to understand how your script behave you can use Pig's explain command. If you want a graphical visualization you can use Netflix's lipstick


text:
Q: how to close a console application from inside loop with 2 switches i'm creating a simple calculator and i've been trying to use switches to allow the user to select whether they want to add, subtract, multiply or divide their inputted values.
They can also type quit to exit the console. but after case quit: when i add a method of closing the console such as Environment.Exit(-1);
It throws up an error and using break; just brings me into my next switch (both of which are in the same while loop as the second one restarts the console).
Any ideas on what i can do?
            {
                case "add":
                    answer = (num1 + num2);
                    Console.WriteLine("your answer is {0:0.00}", answer);
                    break;
                case "subtract":
                    answer = (num1 - num2);
                    Console.WriteLine("your answer is {0:0.00}", answer);
                    break;
                case "multiply":
                    answer = (num1 * num2);
                    Console.WriteLine("your answer is {0:0.00}", answer);
                    break;
                case "divide":
                    answer = (num1 / num2);
                    Console.WriteLine("your answer is {0:0.00}", answer);
                    break;
                case "quit":

            }

A: i just needed to place a break statement after environment.exit(-1) instead of beforehand
case "quit":
    Environment.Exit(-1);
    break;


text:
Q: Flux Integral in spherical coordinates I need to know if my solution and answer to this problem is correct.
The problem is to calculate the flux through the unit sphere centered in origin from the vector field $\vec{A}$
The vector field: $\vec{A}=\frac{1}{r^2}\hat{e}_{r}$
The surface: $S = Unit \space sphere \space centered \space at \space origin$
The flux through the surface $S$ is given by: $\int_{S}\vec{A}\space\cdot\space d\vec{S}$
$$d\vec{S}=r^2\sin\theta \,d\theta d\phi\hat{e}_{r}$$
$$\int_{S}\vec{A}\space\cdot\space d\vec{S}=\int_{s}(\frac{1}{r^2}\hat{e}_{r})\cdot(r^2\sin\theta \,d\theta d\phi\hat{e}_{r})=\int_{S}\sin\theta \space d\theta d\phi=\int_{0}^{2\pi}\int_{0}^{\pi}\sin\theta \ d\theta d\phi=4\pi$$

A: We know from gauss' law that $$\int E.ds = \frac {Q_{in}}{\epsilon_0}  $$
Lets apply this, for a point charge at origin where $$E=\frac {Q_{in}}{4\pi \epsilon_0 r^2} e_r$$
So in your problem you are essentially doing the same thing where $$\frac {Q_{in}}{4\pi \epsilon_0}$$ is taken to the other side of the Gauss's equation
So your answer is correct
I am not so good at working with latex for vectors so take vectors for the symbols where necessary.


text:
Q: cached variables using lock and volatile Does a lock force variables to be written directly to memory instead of beëing cached like volatile does? in this question Orion Edwards states that using locks is better than using volatile, but if a public variable is accessed from within a lock, and always from that lock, does this mean that it is never cached outside of this lock statement?
private readonly object locker = new object();
private bool? _Var = null;

public bool? Var
{
    get
    {
        lock (locker)
        {
            //possibly get the variable _Var in cache memory somewhere
            return this._Var;
            //force _Var back to memory
        }
    }
    set
    {
        lock (locker)
        {
            //possibly get the variable _Var in cache memory somewhere
            this._Var = value;
            //force _Var back to memory
        }
    }
}

A: A lock introduces an acquire-fence before its first instruction, and a release-fence after its last instruction.
The acquire-fence prevents instructions within the lock from being moved backwards in time and above the lock (i.e., "cached"). (Also, notice how it doesn't prevent instructions above the lock to be moved inside the lock).
This is what the specification guarantees. The mechanism used to achieve this (e.g., preventing the processor from using a register and writing/reading directly to/from memory, cache-invalidation, etc) isn't relevant.


text:
Q: Wanted to make textarea with text editor set to required but won't work I created a simple page with textarea with condition that it should be required when the textarea is empty.

      <textarea class="cleditor" id="textarea2" rows="3" name="isi_visimisi" required><?php echo $data['isi_visimisi'] ?></textarea>

When I press submit button with condition that the textarea is empty, it doesn't show any alert that the textarea need to be filled

A: If it has any content, including whitespace, it will pass the check.  Is $data['isi_visimisi'] a string with any length at all?
Also, you must have a submit button for this to work.  If you're submitting the form via JavaScript or some other means, the HTML5 required keyword won't work.

A: It seems you are using CLEditor.  The editor set the initial textarea as hidden and provides its own html to build the text editor. When you submit your form, the alert is attached to your hidden textarea, so you can't see it.

A: This might get you started:

$('textarea').blur(function(){
  if (this.value.length) $(this).removeAttr('required');
  else $(this).attr('required', 'required');
});

$('button').click(function(){
  var attr = $('textarea').attr('required');
  if (typeof attr == 'undefined' && attr !== false) alert('No required attribute');
  else alert('Textarea has required attribute');
});

      <textarea class="cleditor" id="textarea2" rows="3" name="isi_visimisi" >Default text in field</textarea>

<button>TEST: Does textarea have required attribute?</button>


text:
Q: Vagrant SSH private key won't authorize I'm new to vagrant so maybe I'm missing something silly. I'm using puphpet to make a vagrant file and a config.yaml. I can vagrant up the first time no problem, and ssh in with no problem. The problem comes if I destroy the machine and then vagrant up again, vagrant just spins its wheels on the private ssh key. What am I doing wrong? Shouldn't I be able to destroy and rebuild the machine as much as I like?
cmd line output:
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:10201
default: SSH username: vagrant
default: SSH auth method: private key
default: Warning: Connection timeout. Retrying...
default: Warning: Authentication failure. Retrying...

vagrantfile:
# -*- mode: ruby -*-

dir = File.dirname(File.expand_path(__FILE__))

require 'yaml'
require "#{dir}/puphpet/ruby/deep_merge.rb"

configValues = YAML.load_file("#{dir}/puphpet/config.yaml")

if File.file?("#{dir}/puphpet/config-custom.yaml")
  custom = YAML.load_file("#{dir}/puphpet/config-custom.yaml")
  configValues.deep_merge!(custom)
end

data = configValues['vagrantfile']

Vagrant.require_version '>= 1.6.0'

eval File.read("#{dir}/puphpet/vagrant/Vagrantfile-#{data['target']}")

config.yaml:
vagrantfile:
    target: local
    vm:
        box: puphpet/ubuntu1404-x64
        box_url: puphpet/ubuntu1404-x64
        hostname: local.puphpet
        memory: '512'
        cpus: '1'
        chosen_provider: virtualbox
        network:
            private_network: 192.168.56.101
            forwarded_port:
                vflnp_v26uh67hl21f:
                    host: '8088'
                    guest: '22'
        post_up_message: ''
        provider:
            virtualbox:
                modifyvm:
                    natdnshostresolver1: 'on'
                showgui: '0'
            vmware:
                numvcpus: 1
            parallels:
                cpus: 1
        provision:
            puppet:
                manifests_path: puphpet/puppet
                manifest_file: site.pp
                module_path: puphpet/puppet/modules
                options:
                    - '--verbose'
                    - '--hiera_config /vagrant/puphpet/puppet/hiera.yaml'
                    - '--parser future'
        synced_folder:
            vflsf_q0vy639gq7tk:
                source: ./
                target: /var/www
                sync_type: nfs
                smb:
                    smb_host: ''
                    smb_username: ''
                    smb_password: ''
                rsync:
                    args:
                        - '--verbose'
                        - '--archive'
                        - '-z'
                    exclude:
                        - .vagrant/
                        - .git/
                    auto: 'true'
                owner: www-data
                group: www-data
        usable_port_range:
            start: 10200
            stop: 10500
    ssh:
        host: null
        port: null
        private_key_path: null
        username: vagrant
        guest_port: null
        keep_alive: true
        forward_agent: false
        forward_x11: false
        shell: 'bash -l'
    vagrant:
        host: detect
server:
    install: '1'
    packages: {  }
users_groups:
    install: '1'
    groups: {  }
    users: {  }
locale:
    install: '1'
    settings:
        default_locale: ''
        locales:
            - 'en_GB.UTF-8 UTF-8'
            - 'en_US.UTF-8 UTF-8'
firewall:
    install: '1'
    rules: {  }
cron:
    install: '1'
    jobs: {  }
nginx:
    install: '1'
    settings:
        default_vhost: 1
        proxy_buffer_size: 128k
        proxy_buffers: '4 256k'
    upstreams: {  }
    vhosts:
        nxv_ze7hudgh6tql:
            server_name: awesome.dev
            server_aliases:
                - www.awesome.dev
            www_root: /var/www/web
            listen_port: '80'
            index_files:
                - index.html
                - index.htm
                - index.php
            client_max_body_size: 1m
            ssl: '0'
            ssl_cert: ''
            ssl_key: ''
            ssl_port: '443'
            ssl_protocols: ''
            ssl_ciphers: ''
            rewrite_to_https: '1'
            spdy: '1'
            locations:
                nxvl_ssmmsc54r3v5:
                    location: /
                    autoindex: 'off'
                    try_files:
                        - $uri
                        - $uri/
                        - /index.php$is_args$args
                    fastcgi: ''
                    fastcgi_index: ''
                    fastcgi_split_path: ''
                nxvl_tkpkpi9c1sqc:
                    location: '~ \.php$'
                    autoindex: 'off'
                    try_files:
                        - $uri
                        - $uri/
                        - /index.php$is_args$args
                    fastcgi: '127.0.0.1:9000'
                    fastcgi_index: index.php
                    fastcgi_split_path: '^(.+\.php)(/.*)$'
                    fast_cgi_params_extra:
                        - 'SCRIPT_FILENAME $request_filename'
                        - 'APP_ENV dev'
    proxies: {  }
apache:
    install: '0'
    settings:
        user: www-data
        group: www-data
        default_vhost: true
        manage_user: false
        manage_group: false
        sendfile: 0
    modules:
        - proxy_fcgi
        - rewrite
    vhosts:
        av_h9yoti1r7seb:
            servername: awesome.dev
            serveraliases:
                - www.awesome.dev
            docroot: /var/www/awesome
            port: '80'
            setenv:
                - 'APP_ENV dev'
            custom_fragment: ''
            ssl: '0'
            ssl_cert: ''
            ssl_key: ''
            ssl_chain: ''
            ssl_certs_dir: ''
            ssl_protocol: ''
            ssl_cipher: ''
            directories:
                avd_jsxwt0q30rtn:
                    path: /var/www/awesome
                    options:
                        - Indexes
                        - FollowSymlinks
                        - MultiViews
                    allow_override:
                        - All
                    require:
                        - 'all granted'
                    custom_fragment: ''
                    files_match:
                        avdfm_w0oo82cm90x8:
                            path: \.php$
                            sethandler: 'proxy:fcgi://127.0.0.1:9000'
                            custom_fragment: ''
                            provider: filesmatch
                    provider: directory
php:
    install: '1'
    settings:
        version: '56'
    modules:
        php:
            - cli
            - intl
            - mcrypt
        pear: {  }
        pecl:
            - pecl_http
    ini:
        display_errors: 'On'
        error_reporting: '-1'
        session.save_path: /var/lib/php/session
        date.timezone: UTC
    fpm_ini:
        error_log: /var/log/php-fpm.log
    fpm_pools:
        phpfp_0pg56tk6btpm:
            ini:
                prefix: www
                listen: '127.0.0.1:9000'
                security.limit_extensions: .php
                user: www-user
                group: www-data
    composer: '1'
    composer_home: ''
xdebug:
    install: '1'
    settings:
        xdebug.default_enable: '1'
        xdebug.remote_autostart: '0'
        xdebug.remote_connect_back: '1'
        xdebug.remote_enable: '1'
        xdebug.remote_handler: dbgp
        xdebug.remote_port: '9000'
blackfire:
    install: '0'
    settings:
        server_id: ''
        server_token: ''
        agent:
            http_proxy: ''
            https_proxy: ''
            log_file: stderr
            log_level: '1'
        php:
            agent_timeout: '0.25'
            log_file: ''
            log_level: '1'
xhprof:
    install: '0'
wpcli:
    install: '0'
    version: v0.19.0
drush:
    install: '0'
    version: 6.3.0
ruby:
    install: '1'
    versions: {  }
python:
    install: '1'
    packages: {  }
    versions: {  }
nodejs:
    install: '0'
    npm_packages: {  }
hhvm:
    install: '0'
    nightly: 0
    composer: '1'
    composer_home: ''
    settings: {  }
    server_ini:
        hhvm.server.host: 127.0.0.1
        hhvm.server.port: '9000'
        hhvm.log.use_log_file: '1'
        hhvm.log.file: /var/log/hhvm/error.log
    php_ini:
        display_errors: 'On'
        error_reporting: '-1'
        date.timezone: UTC
mysql:
    install: '1'
    settings:
        version: '5.6'
        root_password: '123'
        override_options: {  }
    adminer: 0
    users:
        mysqlnu_9xckuvecv80g:
            name: dbuser
            password: '123'
    databases:
        mysqlnd_lvcvilhwb6v8:
            name: dbname
            sql: ''
    grants:
        mysqlng_e261aymkw2h4:
            user: dbuser
            table: '*.*'
            privileges:
                - ALL
mariadb:
    install: '0'
    settings:
        version: '10.0'
        root_password: '123'
        override_options: {  }
    adminer: 0
    users:
        mariadbnu_ag039xcfxeqe:
            name: dbuser
            password: '123'
    databases:
        mariadbnd_bf3fnggev6gq:
            name: dbname
            sql: ''
    grants:
        mariadbng_vp7qn0nrzpym:
            user: dbuser
            table: '*.*'
            privileges:
                - ALL
postgresql:
    install: '0'
    settings:
        global:
            encoding: UTF8
            version: '9.3'
        server:
            postgres_password: '123'
    databases: {  }
    users: {  }
    grants: {  }
    adminer: 0
mongodb:
    install: '0'
    settings:
        auth: 1
        bind_ip: 127.0.0.1
        port: '27017'
    databases: {  }
redis:
    install: '0'
    settings:
        conf_port: '6379'
sqlite:
    install: '0'
    adminer: 0
    databases: {  }
mailcatcher:
    install: '0'
    settings:
        smtp_ip: 0.0.0.0
        smtp_port: 1025
        http_ip: 0.0.0.0
        http_port: '1080'
        mailcatcher_path: /usr/local/rvm/wrappers/default
        from_email_method: inline
beanstalkd:
    install: '0'
    settings:
        listenaddress: 0.0.0.0
        listenport: '13000'
        maxjobsize: '65535'
        maxconnections: '1024'
        binlogdir: /var/lib/beanstalkd/binlog
        binlogfsync: null
        binlogsize: '10485760'
    beanstalk_console: 0
rabbitmq:
    install: '0'
    settings:
        port: '5672'
    users: {  }
    vhosts: {  }
    plugins: {  }
elastic_search:
    install: '0'
    settings:
        version: 1.4.1
        java_install: true
solr:
    install: '0'
    settings:
        version: 4.10.2
        port: '8984'


text:
Q: php mail() throws "550 Maximum line length exceeded" error on mail server I am trying to send my users a mail using php but keep getting the following error on my mail server.

550 Maximum line length exceeded

I figure the problem is that the body is all 1 line so I tried adding both a php line break "/n" as carriage return and line feed "%0D%0A" to each line, but I keep getting the same error.
Here is the relevant code:
$mailtemplate = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">';
$mailtemplate .= '';
$mailtemplate .= '';
$mailtemplate .= '<meta http-equiv="content-type" content="text/html;charset=utf-8">';
$mailtemplate .= '<title>Mail</title>';
$mailtemplate .= '';
$mailtemplate .= '';
$mailtemplate .= '
';
$mailtemplate .= '
';
$mailtemplate .= '
';
$mailtemplate .= 'header';
$mailtemplate .= '
';
$mailtemplate .= '
';
$mailtemplate .= '
';
$mailtemplate .= '
';
$mailtemplate .= 'content';
$mailtemplate .= '
';
$mailtemplate .= '
';
$mailtemplate .= '
';
$mailtemplate .= '
';
$mailtemplate .= '
';
$mailtemplate .= 'footer';
$mailtemplate .= '
';
$mailtemplate .= '
';
$mailtemplate .= '
';
$mailtemplate .= '
';
$mailtemplate .= '';
$mailtemplate .= '';
//echo $body;
$result = mail('recipient@email.com', 'Hello', $mailtemplate , "From: info@email.com");


text:
Q: Can I get direction using GPS? I am in need to get the direction of a person using IPhone GPS. Direction means where the person is heading. If he is heading towards North then it should say North or otherwise South, West, East any one out of these four.
Is there a way to get this value?
Added September 02, 2010

I just got that Magnetometer can help what I am looking of. But it raise another question to me. Lets assume you are on a street which goes just straight (either North or South). Dividing that street in two places as the right most (west) and the left most (east). Is there a way to get which part the person is located?

A: From http://developer.apple.com/iphone/library/documentation/CoreLocation/Reference/CLLocationManager_Class/CLLocationManager/CLLocationManager.html

Configuring Heading-Related Services
In iOS, a device with the appropriate
  hardware may also report heading
  information. When the value in the
  headingAvailable property is YES, you
  can use a location manager object to
  retrieve heading information. To begin
  the delivery of heading-related
  events, assign a delegate to the
  location manager object and call the
  location manager's
  startUpdatingHeading method. If
  location updates are also enabled, the
  location manager returns both the true
  heading and magnetic heading values.
  If location updates are not enabled,
  the location manager returns only the
  magnetic heading value. These features
  are not available in Mac OS X.

More details at the link above.

A: The iPhone 3GS brings a magnetometer:
How to build a compass with the iPhone?


text:
Q: Imshow from opencv is not working anymore I wrote some simple programs using imshow function. It worked fine few times. I've tried to view two pictures, before and after processing. For the first time it worked fine, but the second time it crashed my application.
Now imshow crash application every time.
How to fix that?
#include <iostream>
#include <iostream>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;

int main()
{
    Mat image, gray_image;
    string file_path;

    cout << "Input file path: ";
    cin >> file_path;

    image = imread(file_path, CV_LOAD_IMAGE_UNCHANGED);
    if (image.data==NULL)
        {
            cout << "No image found!";
            return 1;
        }

    cvtColor(image, gray_image, CV_BGR2GRAY);

    namedWindow("Orig", CV_WINDOW_AUTOSIZE);
    namedWindow("Gray", CV_WINDOW_AUTOSIZE);

    imshow("Orig", image);
    imshow("Gray", gray_image);

    cout << "Output file path: ";
    cin >> file_path;

    imwrite(file_path, gray_image);

    return 0;
}

A: You need waitKey
See what does waitKey (30) mean in OpenCV?


text:
Q: TortoiseSVN dropping fully qualified domain name I'm working with a client's TortoiseSVN repository and they have multiple domains in place due to mergers with other organizations. In order to access their repository from the domain I am on, I have to fully qualify the name of their repository server.
However, halfway during the checkout I started to receive errors for subdirectories saying
Unable to connect to a repository at URL
'http://servername/svn/dev/etc'
No such host is known.

What I notice immediately is that the name provided is not fully qualified, which I believe is causing the error. However, I'm not sure how to fix that as I wonder if it's some kind of internal repository reference to subfolders?

A: Most likely there is an external repository defined in one of the subdirectories, using a hardcoded non-relative address.
This can be changed for future changesets, but will pose a problem for older changesets, if you need to check out an older version where the incorrect externals definition is still in place.
One way, if it's only the host name/address that is wrong, would be to temporarily add an entry to your hosts file with the incorrect name but correct IP address. I believe this should be enough.


text:
Q: Calling entire feature file(or only when steps) into another feature file I have been trying to call one base feature file which has steps which are repetitive across most of my other scenarios in suite.
Since base/common feature file has around 50 odd steps(based on manual TC) and I had to verify every page/element hence it's becoming very long feature file.
To avoid confusion I had divided entire base file into small sections by giving the scenario steps after every 4-5 steps to avoid the chain and added "#" as a prefix since I wanted whole file to execute as a single scenario. Is this right methodology or if somebody has better solution please share,
feature file 1
Scenario: Successful addition of an entry in list
Given User is on the login screen of app
When User enters valid Username and password
And user clicks on Log In
Then My Recent Submissions screen is displayed
And Add new submission form button should be displayed

#Scenario: Viewing Material information
When User clicks on Add new submission form (+) button
And a valid Material is searched using <visit> or <mrn>
And user clicks on Search
Then Search Result screen is displayed

#Scenario: Confirming the Material information and taking a photo
When User clicks Take Photo button
And user clicks on Use Photo
Then Image details screen is displayed

#Scenario: Selecting the facility name to reach New submission screen
When user clicks on Warehouse
And user clicks on Xyz Warehouse
Then New Submission screen is displayed

#Scenario: Confirm the Selected Facility to reach My Recent Submission Screen
When user clicks on Submit
Then Alert window pops up
When user selects Yes button on pop up screen
Then My Recent Submissions screen is displayed
And New Entry is added in list
 Examples:
| Username | password   | visit  | mrn    | Search | SearchByScanning |
| user1    | password_1 | 330045 |        | Yes    | No               |
| user1    | password_1 |        | 330045 | Yes    | No               |
| user1    | password_1 |        |        |        |Yes               |
| user1    | password_1 |        |        |        |Yes               |

All the above steps with user click on XXXXXX
and YYYYYY  screen is displayed
XXXXXX and YYYYYY are the inline parameters which are used in step definition file inside methods to verify the pages with actual output and click on XXXXXX links/buttons
All the steps of feature file 1 are present across different/same step definition file in the format stated below,
[Then(@"(.*) screen is displayed")]
public void ThenApplicationShouldDisplayScreen(string expectedResult)
{
    actualResult = SearchResult.GetTitle ();
    Assert.AreEqual(expectedResult, actualResult);
}

feature file 2

Scenario: User verifies some other functionality
Given some other given statements
When user  does some otherxyz operations
Then user gets some anotherabc output

Scenario:
Given User has created submission successfully #This line would call some of the steps from feature file 1
Given some other given statements
When user  does some othermno operations
Then user gets some anotherpqr output

In another step definition file for (feature fle 2)
[Binding]
public class webConfigUpdation  : Warehouse.MM.Test.MyRecentSubmissionsSteps #This would inherit all the steps present in this file as stated in link given below
{
    [Given("User has created submission sucessfully")]
    public void createSubmissionSuccessfully()
    {
         //All the other statements as per requirement that I can add over here using from feature file 1 which will in turn call step definitions mapped to each one of them
        Then(@"My Recent Submissions screen is displayed");
    }
 }

I was trying the solution given by @samholder in another post with link
but was unable to implement it correctly. Am I making some silly mistake??
If anybody could share the solution would come very handy to me..

A: if you want to call your other steps you just need to call the steps. I'm not sure why this wouldn't work:
[Binding]
public class webConfigUpdation  : Steps
{
    [Given("User has created submission sucessfully")]
    public void createSubmissionSuccessfully()
    {
         //just call all the steps you need here:
         When("user clicks on Warehouse");
         When("user clicks on Xyz Warehouse");
         Then("New Submission screen is displayed");
         When("user clicks on Submit");
         Then("Alert window pops up");
         When("user selects Yes button on pop up screen");
         Then("My Recent Submissions screen is displayed");
    }
 }

Specflow will still use the regex to match the the steps.
Is there some specific problem with this that doesn't work?


text:
Q: Making accelerometer respond to double impacts (tapping it twice in the table) I'm creating a simple application which does certain things depending on the accelerometer. At the moment it initiates the things if i move it in -z-direction fast enough. My goal is though to make it so that if i tap the phone in the table twice it will perform the tasks.
The phone is going to be orientated face up and therefor the back of the phone will "hit" the table twice. The settings I would want for it is so that if the "strong" enough taps in the table happen within one second it will perform the tasks. So the setting of one tap is not an issue but it is, for me, to make it only respond to it if it happens twice within the given timelimit.
Huge thanks before hand!

A: Depending on the accelerometer you have you either have to sense two peaks within a reasonable, and separated by, the latency time interval, or you can get the hardware to detect a double pulse in the axis you wish. I'm looking at the spec of the MMA7455L, which can do double pulse. If you hardware doesn't do it, you can just sample the acceleration in measurement mode, or even easier set the device to level mode and wait for the interrupts on the threshold you specify.


text:
Q: Magento2 : Order Items Email Template Adjustment I need to add align="right" in th(i.e Subtotal, Shipping & Handling, Grand Total) to align right on tfoot. I have found that its rendering from the below code under Magento_Sales/templates/email/items.phtml file.

        <?= $block->getChildHtml('order_totals') ?>

Can anyone let me know how to edit & modify and add align="right" in that?

I tried the below solution but the design is breaking. Here is my updated code :
<?php $_order = $block->getOrder() ?>
<?php if ($_order): ?>
    <?php $_items = $_order->getAllItems(); ?>

                    <?= /* @escapeNotVerified */  __('Items') ?>

                    <?= /* @escapeNotVerified */  __('Qty') ?>

                    <?= /* @escapeNotVerified */  __('Price') ?>

        <?php foreach ($_items as $_item): ?>
            <?php if (!$_item->getParentItem()) : ?>

                    <?= $block->getItemHtml($_item) ?>

            <?php endif; ?>
        <?php endforeach; ?>

        <?= /* @escapeNotVerified */  __('Subtotal') ?>
          <?= /* @escapeNotVerified */  $_order->getSubtotal() ?>

        <?= /* @escapeNotVerified */  __('Shipping & Handling') ?>
        <?= /* @escapeNotVerified */  $_order->getShippingAmount() ?>

        <?= /* @escapeNotVerified */  __('Grant total') ?>
        <?= /* @escapeNotVerified */  $_order->getGrandTotal() ?>

    <?php if ($this->helper('Magento\GiftMessage\Helper\Message')->isMessagesAllowed('order', $_order, $_order->getStore()) && $_order->getGiftMessageId()): ?>
        <?php $_giftMessage = $this->helper('Magento\GiftMessage\Helper\Message')->getGiftMessage($_order->getGiftMessageId()); ?>
        <?php if ($_giftMessage): ?>

<?= /* @escapeNotVerified */  __('Gift Message for this Order') ?>

                        <?= /* @escapeNotVerified */  __('From:') ?> <?= $block->escapeHtml($_giftMessage->getSender()) ?>

<?= /* @escapeNotVerified */  __('To:') ?> <?= $block->escapeHtml($_giftMessage->getRecipient()) ?>

<?= /* @escapeNotVerified */  __('Message:') ?>

<?= $block->escapeHtml($_giftMessage->getMessage()) ?>

        <?php endif; ?>
    <?php endif; ?>
<?php endif; ?>

A: Following steps will be useful
step 1:
      override the items.phtml code
Path:app/design/frontend/Theme/Magento_Sales/templates/email/items.phtml
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php $_order = $block->getOrder() ?>
<?php if ($_order): ?>
    <?php $_items = $_order->getAllItems();
     ?>

                    <?= /* @escapeNotVerified */  __('Items') ?>

                    <?= /* @escapeNotVerified */  __('Sku') ?>

                    <?= /* @escapeNotVerified */  __('Qty') ?>

                    <?= /* @escapeNotVerified */  __('Subtotal') ?>

        <?php foreach ($_items as $_item): ?>
            <?php if (!$_item->getParentItem()) : ?>

                    <?= /* @escapeNotVerified */  $_item->getName()?>

            <?php
            $options = $_item->getProductOptions();
            $s="";
            $d="";
    if (isset($options['options']) ) {
        foreach ($options['options'] as $option) {
            $s= $option['label'];
            $d= $option['value'];
        }
    }
            ?>

                           <?= /* @escapeNotVerified */ $s?>

                           <?= /* @escapeNotVerified */ $d?>

                    <?= /* @escapeNotVerified */  $_item->getSku() ?>

                    <?= /* @escapeNotVerified */  $_item->getQtyOrdered() ?>

                    <?= /* @escapeNotVerified */  $_item->getPrice() ?>

            <?php endif; ?>
        <?php endforeach; ?>

    <?= /* @escapeNotVerified */  __('Subtotal') ?>
      <?= /* @escapeNotVerified */  $_order->getSubtotal() ?>

    <?= /* @escapeNotVerified */  __('Shipping & Handling') ?>
    <?= /* @escapeNotVerified */  $_order->getShippingAmount() ?>

    <?= /* @escapeNotVerified */  __('Tax') ?>
    <?= /* @escapeNotVerified */  $_order->getTaxAmount() ?>

    <?= /* @escapeNotVerified */  __('Grant total') ?>
    <?= /* @escapeNotVerified */  $_order->getGrandTotal() ?>

    <?php if ($this->helper('Magento\GiftMessage\Helper\Message')->isMessagesAllowed('order', $_order, $_order->getStore()) && $_order->getGiftMessageId()): ?>
        <?php $_giftMessage = $this->helper('Magento\GiftMessage\Helper\Message')->getGiftMessage($_order->getGiftMessageId()); ?>
        <?php if ($_giftMessage): ?>

<?= /* @escapeNotVerified */  __('Gift Message for this Order') ?>

                        <?= /* @escapeNotVerified */  __('From:') ?> <?= $block->escapeHtml($_giftMessage->getSender()) ?>

<?= /* @escapeNotVerified */  __('To:') ?> <?= $block->escapeHtml($_giftMessage->getRecipient()) ?>

<?= /* @escapeNotVerified */  __('Message:') ?>

<?= $block->escapeHtml($_giftMessage->getMessage()) ?>

        <?php endif; ?>
    <?php endif; ?>
<?php endif; ?>

It will works like a charm.

A: I have got this work, I have changed few things & now tis worked for me. Thanks @arun.
<?php $_order = $block->getOrder() ?>
<?php if ($_order): ?>
    <?php $_items = $_order->getAllItems(); ?>

                    <?= /* @escapeNotVerified */  __('Items') ?>

                    <?= /* @escapeNotVerified */  __('Qty') ?>

                    <?= /* @escapeNotVerified */  __('Price') ?>

        <?php foreach ($_items as $_item): ?>
            <?php if (!$_item->getParentItem()) : ?>

                    <?= $block->getItemHtml($_item) ?>

            <?php endif; ?>
        <?php endforeach; ?>

            <?= /* @escapeNotVerified */  __('Subtotal') ?>

           Rs: <?= /* @escapeNotVerified */  $_order->getSubtotal() ?>

           <?= /* @escapeNotVerified */  __('Shipping & Handling') ?>

           Rs: <?= /* @escapeNotVerified */  $_order->getShippingAmount() ?>

            <?= /* @escapeNotVerified */  __('Grant total') ?>

            Rs: <?= /* @escapeNotVerified */  $_order->getGrandTotal() ?>

    <?php if ($this->helper('Magento\GiftMessage\Helper\Message')->isMessagesAllowed('order', $_order, $_order->getStore()) && $_order->getGiftMessageId()): ?>
        <?php $_giftMessage = $this->helper('Magento\GiftMessage\Helper\Message')->getGiftMessage($_order->getGiftMessageId()); ?>
        <?php if ($_giftMessage): ?>

<?= /* @escapeNotVerified */  __('Gift Message for this Order') ?>

                        <?= /* @escapeNotVerified */  __('From:') ?> <?= $block->escapeHtml($_giftMessage->getSender()) ?>

<?= /* @escapeNotVerified */  __('To:') ?> <?= $block->escapeHtml($_giftMessage->getRecipient()) ?>

<?= /* @escapeNotVerified */  __('Message:') ?>

<?= $block->escapeHtml($_giftMessage->getMessage()) ?>

        <?php endif; ?>
    <?php endif; ?>
<?php endif; ?>

A: its work fine for me....
I modified the code to obtain 2 decimals for the price...
number_format($_order->getSubtotal(), '2', '.', ',')


text:
Q: Objective- C - Looping through all properties in a class? Is there a way to loop through all properties in an object and get their "name" and "value".
I am trying to write a category to serialize objects to a string, based on their property name and values. I'm trying to prevent writing encoding methods for each class, and instead write a generic one.
Is this possible?

A: I use the following Category on NSObject to say, for example, NSLog(@"%@", [someObject propertiesPlease]);, resulting in a log entry like…
someObject: {
    color = "NSCalibratedRGBColorSpace 0 0 1 1";
    crayon = Blueberry;
}

NSObject+Additions.h
@interface NSObject (Additions)
- (NSDictionary *)propertiesPlease;
@end

NSObject+Additions.m
@implementation NSObject (Additions)
- (NSDictionary *)propertiesPlease {
NSMutableDictionary *props = [NSMutableDictionary dictionary];
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList([self class], &outCount);
for (i = 0; i < outCount; i++) {
   objc_property_t property = properties[i];
   NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property)];
   id propertyValue = [self valueForKey:(NSString *)propertyName];
   if (propertyValue) [props setObject:propertyValue forKey:propertyName];
}
   free(properties);
   return props;
}
@end

A: You can use this code to enumerate all properties declared in a class, and all attributes of the properties. I guess you're more interested in parsing the type attribute. They are detailed here.
unsigned int numOfProperties;
objc_property_t *properties = class_copyPropertyList([self class], &numOfProperties);
for ( unsigned int pi = 0; pi < numOfProperties; pi++ ) {
    // Examine the property attributes
    unsigned int numOfAttributes;
    objc_property_attribute_t *propertyAttributes = property_copyAttributeList(properties[pi], &numOfAttributes);
    for ( unsigned int ai = 0; ai < numOfAttributes; ai++ ) {
        switch (propertyAttributes[ai].name[0]) {
            case 'T': // type
                break;
            case 'R': // readonly
                break;
            case 'C': // copy
                break;
            case '&': // retain
                break;
            case 'N': // nonatomic
                break;
            case 'G': // custom getter
                break;
            case 'S': // custom setter
                break;
            case 'D': // dynamic
                break;
            default:
                break;
        }
    }
    free(propertyAttributes);
}
free(properties);

A: Maybe class_copyPropertyList() will do what you are after - but notice that it only returns declared properties.
Not all properties are declared - NSDictionary and NSMutableDictionary are examples of classes where you can set properties that are not declared in the class.
More in the docs.

A: I don't have comment privileges yet, but to add to @Costique's answer, there is an additional attribute Type value "V" which is the name of the IVar to which a property may be bound (via synthesize).  This can be readily discovered with this
@interface Redacted : NSObject
@property (atomic, readonly) int foo;
@end

@implementation Redacted
@synthesize foo = fooBar;
@end
// for all properties
unsigned propertyCount = 0;
objc_property_t *properties = class_copyPropertyList([object class], &propertyCount);
for (int prop = 0; prop < propertyCount; prop++)
{
    // for all property attributes
    unsigned int attributeCount = 0;
    objc_property_attribute_t* attributes = property_copyAttributeList(property, &attributeCount);
    for (unsigned int  attr = 0; attr < attributeCount; attr++)
    {
        NSLog(@"Attribute %d: name: %s, value: %s", attr, attributes[attr].name, attributes[attr].value);
    }
}

2013-07-08 13:47:16.600 Redacted5162:303] Attribute 0: name: T, value: i
2013-07-08 13:47:16.601 Redacted[5162:303] Attribute 1: name: R, value:
2013-07-08 13:47:16.602 Redacted[5162:303] Attribute 2: name: V, value: fooBar


text:
Q: Can't execute servlet from JSP but can access from direct URL (mvc mysql tomcat) I'm working on a simple login app using mvc (JSP pages + servlets, running on Apache Tomcat server in Eclipse + Mysql database).
When I access my servlet from the direct URL:
http://localhost:8181/stage/LoginControlerdo

The servlet's instructions get executed, but do not when the servlet is invoked from the JSP form, it shows a blank page instead.
(Servlet's instructions are just simple messages that show up when the servlet is accessed directly of after actualising the page but not when called from the JSP form).
As you can see I'm using port 8181; I don't think the problem has anything to do with the web.xml config since the server starts correctly but here is a copy
Web.xml :
<servlet>
  <servlet-name>LoginContro</servlet-name>
  <servlet-class>attakmili.com.LoginControler</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>LoginContro</servlet-name>
  <url-pattern>/LoginControlerdo</url-pattern>
</servlet-mapping>

If anyone has an idea about what's going on I would be grateful.
The JSP code:
<form action="LoginControlerdo"  method="post">

Pseudo
<input type="text"  name="pseudo" />

Mot De Passe
<input type="text"  name="password" />

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

</form>

A: You are using POST method to submit your form, but when you access the servlet from browser directly GET method will be used.
You have to use the HttpServlet.doPost(HttpServletRequest, HttpServletResponse) to implement you logic.

A: This should work , (Add a slash before LoginControlerdo)
<form action="/LoginControlerdo"  method="post">

Pseudo
<input type="text"  name="pseudo" />

Mot De Passe
<input type="text"  name="password" />

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

</form>


text:
Q: input field for browsing folder input field with type file used for browsing file .How to make it for browsing folder.

A: You can't. The input type=file control is limited to picking one file at a time.
If you want to pick multiple files, there are various ways, Flash based uploaders, Java and ActiveX based components. The Flash based uploaders are the best bet, and there are Open Source ones around. Check out SWFUploader.

A: You would have to use server side or some ActiveX to do this as javascript does not support this


text:
Q: Drawing Images twitching in processing In this sketch it draws a list of objects horizontally. Each object's x position is dependent on the object to its left. Also when the object is not on the screen it will not draw. However when i move, the objects twitch. I don't really know why, it could be that processing's load image takes a bit of time so there is a slight delay? I tested this with just drawing rectangles (rect()) and the problem doesn't happen.

The following is a code that draws images loaded from the internet with the same algorithm: (it might take a while for the sketch to load because it is retrieving the images from different websites) After running the sketch, use the left and right arrow keys to move left and right. Use the up and down arrows to change the movement speed.
PImage backgroundImage;
PFont font;
int x = 0;
int xoffset = 0;
int deltax = 5;
float scale = 512/30;
float deltascale = 0.02;
ArrayList<Object> ObjectList;

class Object {
  String name;
  float diameter;
  String unit;
  String sprite;
  PImage img;
  int wid;
  int hei;
  int xpos;

  Object(String Oname, float Odiameter, String Ounit, String Oimg) {
    name = Oname;
    diameter = Odiameter;
    unit = Ounit;
    img = loadImage(Oimg);
    sprite = Oimg;
    //img = loadImage(Oimg);
    wid = img.width;
    hei = img.height;
  }
}

void setup() {
  size(1500, 800);
  frameRate(200);
  fill(255,255,255);
  textSize(32);
  textAlign(CENTER, CENTER);
  text("Images are loading (this may take a while)",700,400);
  ObjectList = new ArrayList();
  readObjects();
}

void addObject(String Aname, float Adiameter, String Aunit, String Aimg) {
  ObjectList.add(new Object(Aname, Adiameter, Aunit, Aimg));
}

void readObjects() {
  addObject("RED", 30, "m", "https://s-media-cache-ak0.pinimg.com/736x/8f/1b/cc/8f1bcc72c81d1e9370597f7239ee476a.jpg");
  //addObject("ORANGE", 60, "m", "http://6iee.com/data/uploads/36/489075.jpg");
  addObject("YELLOW", 70, "m", "https://i.stack.imgur.com/aez1V.jpg");
  addObject("GREEN", 100, "m", "http://space-facts.com/wp-content/uploads/mars.jpg");
  addObject("PURPLE", 105, "m", "http://space-facts.com/wp-content/uploads/jupiter.png");
  addObject("PINK", 110, "m", "https://vignette1.wikia.nocookie.net/starwars/images/4/4a/Alderaan.jpg");
  addObject("BROWN", 150, "m", "https://cdn.pixabay.com/photo/2013/07/12/16/33/venus-151142_960_720.png");
  addObject("GRAY", 180, "m", "http://www.lpi.usra.edu/lpi_40th/images/1989/neptune.jpg");
  //addObject("WHITE", 200, "m", "http://www.clipartkid.com/images/19/log-in-sign-up-upload-clipart-Dpr48a-clipart.png");
  addObject("INDIGO", 300, "m", "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Sun_in_February.jpg/155px-Sun_in_February.jpg");
  addObject("SKYBLUE", 301, "m", "https://upload.wikimedia.org/wikipedia/commons/e/ea/Uranus_(Edited).jpg");
  addObject("BLUE", 1000, "m", "https://vignette2.wikia.nocookie.net/heman/images/3/36/Earth.jpg");
}

void draw() {

  fill(0,0,0);
  rect(0, 0, 1500, 800);

  int x = 0 + xoffset;
  for ( Object drawObject : ObjectList ) {
    float dia = drawObject.diameter;

    if (x+drawObject.img.width >= 0 && x <= 1500) {

      //checks if image is too small to be drawn
      int drawWidth = int(scale * dia);
      int drawHeight = int(drawWidth * drawObject.hei / drawObject.wid);
      if (drawWidth > 0 && drawHeight > 0) {
        drawObject.img.resize(drawWidth, drawHeight);
        image(drawObject.img, x, 400-(drawObject.img.height/2));
        //calculates font size relative to object's current size
        int textSize;
        //checks if the name or diameter is longer, then uses the longer one for calculation
        fill(255,255,255);
        if (drawObject.name.length() < str(drawObject.diameter).length()) {
          textSize = int(drawObject.img.width/str(drawObject.diameter).length());
        } else {
          textSize = int(drawObject.img.width/drawObject.name.length());
        }
        if (textSize > 0) {
          textSize(textSize);
          float texty = 418+(drawObject.img.height/2);
          if (texty < (418+(drawObject.img.height/2))) {
            texty = 418;
          }
          text(drawObject.name, x+(drawObject.img.width/2), texty);
          text(drawObject.diameter+drawObject.unit, x+(drawObject.img.width/2), texty+textSize);
        }
      }
      drawObject.xpos = x;
      x += (drawObject.img.width*0.08 + drawObject.img.width);
    }
    //display deltax
    textSize(32);
    text(str(deltax), 1450, 10);
    text(str(deltascale), 1450, 50);

    println(str(scale));
  }
}

void mouseWheel(MouseEvent event) {
  float e = event.getCount();
  if (e < 0) {
    scale *= (1 + deltascale);
  } else if (e > 0) {
    scale *= (1 - deltascale) ;
  }
}

void keyPressed() {
  if (key == CODED) {
    if (keyCode == LEFT) {
      xoffset += deltax;
    } else if (keyCode == RIGHT) {
      xoffset -= deltax;
    } else if (keyCode == UP) {
      deltax += 5;
    } else if (keyCode == DOWN) {
      deltax -= 5;
    }
  }
  if (key == 'r') {
    //reloadObjects();
  } else if (key == 'q') {
    deltascale += 0.02;
  } else if (key == 'a') {
    deltascale -= 0.02;
  }
  if (deltax < 0) {
    deltax = 0;
  } else if (deltascale < 0) {
    deltascale = 0;
  }
}

the following original code will NOT work because it uses images that only I have.
The original code
I hope someone can help me with this bug, or help me improve my algorithm.
EDIT: Code is now verifiable and presents the problems I'm having

A: Well, I noticed that the image jumps whenever one of your images is about to go off the left edge of the screen.  It looks like you may be calculating the x position differently as each of your images goes offscreen.  Try getting rid of your if (x+drawObject.img.width >= 0 && x <= 1500) test (comment it out temporarily), but keep the code inside the if.
Few points:

*

*definitely don't create your own Object class (as Kevin Workman said)

*when you call img.resize() you are resampling the image data, which will lead to poor quality over time.  It would be better to just use the width, height parameters to the image() function (or use the scale() transformation function - but that may be more confusing).  Then use drawWidth/Height instead of img.width/height in the rest of your draw code.

*if you want to center an image, just use imageMode(CENTER) instead of doing the math yourself - especially since it looks like you're using a 'magic number' 400

*try not to use raw numbers for your screen size - instead use the width & height globals -it'll make your life easier when you change the screen size.


text:
Q: Huge Css file with huge numbers of unsed rules
Possible Duplicate:
Tool for checking unused CSS selectors?

I am working on a big project that was work on many people before me and now the CSS file is very big more than 4000 line there is many unused css rules i was trying firebug plugin CSS usage but i have to check page by page and compare what use here and not used there while its only one big CSS file is there any web site that can help me find unused CSS rules much better

A: *

*In the chrome console you have the "Audits" tab. There you click in "Run" and shows you a result with unused rules.

*http://code.google.com/intl/es/speed/page-speed/download.html this is a plugin for firefox and chrome

EDIT:
Here you have two tools to minimize css

*

*http://tools.w3clubs.com/cssmin/

*http://www.cleancss.com/


text:
Q: Testing EJB 3.0 components I've got a couple of questions concerning the integrated testing EJB 3.0 components using JUnit.
In your JUnit tests you can inject to session beans resource-local entity managers and therefore "simulate" ejb-container. But what if...

*

*What if you need to test if transaction attributes on your ejb methods are handled properly? Can this be done outside the container? If not, what is the simplest way to test  it inside the container?

*What if you need to assure there are some test records in db before each test? How would you assure that after test execution (even if it fail) db is cleaned of test data?

A: You can also use embeddable JBoss to unit test EJBs, as discussed in #553031
Its not a pretty solution, but it works.

A: If you happen to be using Maven or even if you're not, this might be helpful.  The typical way to test transactional semantics is with an in-memory database like H2 or HSQLDB (Hypersonic).  So in effect, you're testing inside a very lightweight container.  Hibernate can be configured as your JPA implementation.  It will persist the data to a fully-functional relational database running entirely in RAM.
As for fixtures, there are quite a few options, one of the more popular being DbUnit, but in my experience, they're more complicated than they're worth.  I prefer to create my own "builder" classes that set up my tests with the necessary model objects.  I like for the configuration "setters" to return an instance of the builder so that I can chain calls together like so:
  this.emf = Persistence.createEntityManagerFactory ("hibernate-hsqldb");
  Widget widget = new WidgetBuilder(this.emf).setAnOption(4).setAnother("test").build();

Typically, the emf will be created in the setUp method and closed in the tearDown.  This completely initializes the database in between test runs.