text:
Q: Guidance Needed-Command line in terminal to install Gimp 2.10.6 from flatpakref Try as I might, I cannot come up with a terminal command that will install Gimp 2.10.6 from the flatpak package.
I have tried:
sudo apt-get install computer/home/paul/downloads/org.gimp.gimp.flatpackref

& I get the error message:
cannot find package 'home/paul/downloads/org.gimp.gimp.flatpakref

So I tried:
sudo apt-get install computer/home/paul/downloads/org.gimp.gimp.flatpackref  --directory

& I get:
confused with options presented with --directory

So I tried:
sudo apt-get install computer/home/paul/downloads/org.gimp.gimp.flatpackref
 --directory /home/paul/cache/org.gimp.gimp.flatpakref

I tried each command several times with different derivations and I got the error messages every time. Terminal either says I haven't specified the target, or if I do, it says
confused by options presented with --directory.

I need someone to give me a command line prompt that will install the Linux gimp 2.10.6 package @ home/paul/ applications or home/paul/cache.

A: You install the flatpak Gimp using flatpak itself, not Apt. As far as I can tell:

*

*Install flatpak:
sudo add-apt-repository ppa:alexlarsson/flatpak
sudo apt update
sudo apt install flatpak

*Add the flatpak repo (could already be set):
flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo

*Install Gimp:
flatpak install flathub org.gimp.GIMP

*Run Gimp:
flatpak run org.gimp.GIMP

(from the current Howtos, but installing flatpak Gimp on my 16.04 was a no-brainer)
You will also update Gimp the same way, possibly with just a:
flatpak update

A: Thank you very much Xenoid for your information.  I successfully executed several of the commands you gave me and was able to install flatpak.
Then I did another search and found this article on itsfoss which has a real gold mine of advice about how to load Gimp 2.10 into Ubuntu.  I used the following instructions, and terminal loaded Gimp right up!  :-)

Method 1: Installing GIMP 2.10 via Snap Packages
You can use Snap for installing GIMP 2.10. If you are using Ubuntu, you are good. For other Linux distributions, please make sure that you have Snap support enabled.
With Snap installed, all you have to do is to use the Snap command:
snap install gimp

That's it. GIMP 2.10.x will be installed.

This is what I did and it worked like a charm!  Problem fixed!


text:
Q: Me sale error cuando activo Mysql con Xampp Ayúdenme Por favor, quise activar MySQL con xampp y me sale error, ya lo desinstale y lo volví a instalar, pero me sigue apareciendo igual, Ayúdenme por favor, tengo que entregar un proyecto con phpMyAdmin y local host

TRANSCRIPCION DEL ERROR:
03:33:54 a. m.  [mysql]     Error: MySQL shutdown unexpectedly.
03:33:54 a. m.  [mysql]     This may be due to a blocked port, missing dependencies,
03:33:54 a. m.  [mysql]     improper privileges, a crash, or a shutdown by another method.
03:33:54 a. m.  [mysql]     Press the Logs button to view error logs and check
03:33:54 a. m.  [mysql]     the Windows Event Viewer for more clues
03:33:54 a. m.  [mysql]     If you need more help, copy and post this
03:33:54 a. m.  [mysql]     entire log window on the forums

A: abre una temrinal y coloca el comando netstat -ano | findstr :3306 para ver si no hay otros programas utilizando el puerto.
Te va a salir algo asi:
  TCP    0.0.0.0:3306           0.0.0.0:0              LISTENING       4568
  TCP    [::]:3306              [::]:0                 LISTENING       4568

para eliminar el proceso usa taskkill /F /PID 4568
con eso, intenta encenderlo de nuevo encenderlo.
También en configuración, puedes cambiar el puerto.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Plotting previous data in pine script for Tradingview How can I have the previous data shown on Tradingview?  I've tried using the historical reference operator but it only shows the chart for the current time frame.
In Thinkorswim x[20] would plot x from 20 bars ago.  If I run this script in Thinkorswim after the market closes, it shows the previous 20 bars on the chart for the following trading day.  So it would show the graph from 6:30AM PST to 6:50AM PST the following day if using 1 minute data.
But in Tradingview it only shows up to the end of the trading day.
Please help!
Thank you!


text:
Q: Transaction Log backup fails if no full backup exists ...at least I think so.
I recently revamped my backup routine on my development server. I created a maintenance plan for user databases that did some weekly cleanup tasks, daily full backups and transactionlog backups at key points throughout the day.
All has been working well until today, when a received an email notifying me that the lunchtime backup had failed. The log viewer didn't reveal much, other than that a certain number of DBs were backed up success fully, before ending the log entry with:
[snipped] Source: ...  The package execution fa...  The step failed.

Not exactly revealing
It occurred to me that the only change to previous attempts was that I'd created a new (small and unremarkable) database this morning.
I restarted the SQL Server Agent, and tried manually re-running the (transaction log backup) step but it failed again.
However, running the full backup step (thus creating the first full backup for my new DB) worked - furthermore, re-running the transaction log backup step again also worked.
It appears that the transaction log backup struggled because of the lack of a full backup or previous transaction log backup.
Is this the expected behaviour? On the one hand, at a primitive level this sort of makes sense, but really, I'd expect it to handle such a scenario more gracefully.
If so, is there a way to automatically handle this? It won't happen that often, but I can't be relied to remember to backup the DB when I create it, especially since it's only in the early stages of development.
If not, what is the likely cause of this behaviour? Can I avoid it?

A: Yes, this is expected behavior.  In order for the transaction logs to be useful, there needs to be a full backup to use as a starting point for rolling forward.
Don't worry about it too much.  If you create a new database, the first day you will get that error.  The log backups for the other DBs will succeed, as you saw, but that error will just make it LOOK like the step failed when in reality only the one DB failed.  Then, that night (or whenever), it will do the full backup.  After that, the trans log backups will be successful for the new DB.  Basically, you would have one day or errors when you create a new DB until the full backup job runs.

A: I put a flag on my list of DBS to back up that indicates that it has been backed up.  The backup script won't do Txn backups until it equals 1.  In my full backup script I set the flag to 1.  Presto, no more failures.


text:
Q: How to Use ajax& j Query in spring I am new to Spring with AJAX.
My requirement is to check whether email is registered or not, when user clicks on check availability. I am successfully making calls to the controller class but the response is displayed in the browser instead of in same jsp and not entering the success block. I am unable to find the problem.
Below is sample code:
@Controller
public class CheckAvailbiltyEmailController {

    @RequestMapping(value="/check",method = RequestMethod.GET)
    public ModelAndView viewAjaxEmail(Map model){

        return new ModelAndView("CheckEmailAvaliblity");
    }

    @RequestMapping(value="/check", method=RequestMethod.POST)
    public @ResponseBody String ajaxEmailCheck(@RequestParam("email") String email){

        System.out.println("Email is:"+email);
        return "Please carry on registration";

    }
}

My Ajax code:
   $.ajax({
        type:"POST",
        url:"/check"
      success:function(data){
            alert("Inside Success");
            $('#resp email').html(data);
        }
       error: function(e){

       }
    });

A: You need to specify the data you want to send to the server,
The controller will accept "email" as the RequestParam.
Do it like the following snippet :
$.ajax({
    type:"POST",
    url:"/check",
    data: {"email":"email@to.check.com"},
    success:function(responseData){
        alert("Inside Success");
        $('#resp email').html(responseData);
    },
   error: function(e){

   }
});


text:
Q: I'm getting this error while building flutter application A problem occurred configuring project ':image_cropper'. > I got this code from my company to build the v2 of the app.
But the codes are not working on my computer and giving me very ridiculous errors please help me.
Here is the pubspec.yaml file
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  hexcolor:
  fluttertoast:
  google_fonts:
  fl_chart:
  pinput:
  provider:
  table_calendar:
  intl:
  flutter_svg:
  multi_select_flutter:
  firebase_auth:
  firebase_core:
  firebase_database:
  firebase_storage:
  flutter_spinkit:
  image_cropper:
  uuid:
  flutter_image_compress:
  image_picker:
  share: ^2.0.4

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
      - assets/
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

And when I type flutter un in the terminal, I get this error in the debug console.

* Where:
Build file 'C:\Users\Kamal\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\firebase_auth-3.1.0\android\build.gradle' line: 24

* What went wrong:
A problem occurred evaluating root project 'firebase_auth'.
> Could not find the firebase_core FlutterFire plugin, have you added it as a dependency in your pubspec?

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 51s
2

Exception: The plugin firebase_auth could not be built due to the issue above.
Exited (sigterm)

If I'm not wrong, Maybe be it is due to the dependencies, how to solve this. I also tried downgrading the flutter version but it didn't worked for me.


text:
Q: MongoDB query of array of documents returning all elements I have a collection called 'cupcakes' that was loaded from a GeoJSON file using mongoimport. The GeoJSON can be found here, and is a known valid JSON file. This part seems to have gone to plan, and doing:
use cupcakes
db.cupcakes.find({ })

This pulls back all the features as expected. However, I am trying to do a query that will return only the features that have gluten free set to "no".
I have tried the instructions as per the documentation around querying arrays of documents.
 db.cupcakes.find({features: { $elemMatch: { "properties.gluten free":"no"}}}).pretty()

But as far as I can tell this appears to be returning all of the features as opposed to just those that are gluten free establishments.
Essentially I am wanting to pull back all the features where "properties.gluten free" of the features is set to "no" (or "yes" for that matter).
A sample output might be:
{
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": [
            -122.70069837570189,
            45.53570881624427
        ]
    },
    "properties": {
        "name": "Le Cookie Monkey",
        "address": "1902 NW 24th Avenue",
        "website": "http://www.lecookiemonkey.com/",
        "gluten free": "no",
        "open1": "Tuesday - Friday, 9am - 3pm",
        "open2": "Saturday, 9am - 2pm"
    }
},
{
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": [
            -122.6375323534012,
            45.5219957171348
        ]
    },
    "properties": {
        "name": "Crema Coffee + Bakery",
        "address": "2728 SE Ankeny Street",
        "website": "http://www.cremabakery.com/",
        "gluten free": "no",
        "open1": "Monday - Sunday, 7am - 6pm"
    }
},
{
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": [
            -122.60960519313811,
            45.472775425296014
        ]
    },
    "properties": {
        "name": "Mehri's Bakery & Deli",
        "address": "6923 SE 52nd Avenue",
        "website": "http://www.mehris.com/",
        "gluten free": "no",
        "open1": "Monday - Friday, 7am - 7pm",
        "open2": "Saturday, 8am - 5pm",
        "open3": "Sunday, 8am - 2pm"
    }
},

... and so on until all the features where "gluten free" : "no" are returned.
What am I missing here? Thanks in advance.

A: You forgot to add the positional $ operator in your projection which limits the contents of the features array from the query results to contain only the first element matching the query document as follows:
db.cupcakes.find(
    { "features.properties.gluten free": "no" },
    { "features.$": 1, "_id": 0 }
);

Sample Output:
/* 0 */
{
    "features" : [
        {
            "type" : "Feature",
            "geometry" : {
                "type" : "Point",
                "coordinates" : [
                    -122.653357386589,
                    45.51208367658516
                ]
            },
            "properties" : {
                "name" : "Hungry Heart Cupcakes",
                "address" : "1212 SE Hawthorne Boulevard",
                "website" : "http://www.hungryheartcupcakes.com",
                "gluten free" : "no",
                "open1" : "Monday - Sunday, 11am - 9pm"
            }
        }
    ]
}

To pull back all the features where gluten free is equal to no, the $redact pipeline operator in the aggregation framework should work for you in this case. This will recursively descend through the document structure and do some actions based on an evaluation of specified conditions at each level. The map() method will then produce the final array of objects as per expectation. The concept can be a bit tricky to grasp but the following example demonstrates this:
db.cupcakes.aggregate([
    {
        "$match": { "features.properties.gluten free" : "no" }
    },
    {
        "$redact": {
            "$cond": {
                "if": {
                    "$eq": [ "$gluten free", "yes" ]
                },
                "then": "$$PRUNE",
                "else": "$$DESCEND"
            }
        }
    }
]).map(function(doc){ return doc.features; });


text:
Q: Resharper: Set sort order for class/method modifiers 'static'/'sealed' vS 'public'/'internal'/'protected' When it comes to 'static' and 'sealed' I would like the default sort order for my classes (and methods) to be like this:
         sealed public class Foo {   static public void Bar() {}  }

The default settings of Resharper automatically reorder the above class definition to:
         public sealed class Foo {    public static void Bar() {} }

How can one change the default sort order for 'static'/'sealed' vS 'public'/'private' etc?

A: I somehow managed to miss the option:
Resharper -> Options -> Code Editing -> C# -> Code Style -> Modifiers -> Modifiers Order


text:
Q: Modify a value inside a rails mongoid query I am storing phone numbers in the database in the user model in various formats. All the followings are possible.
+306974135662, 306974135662, 30 6974135662

Then from the front-end, I am getting a specific format that has the plus sign and no spaces.
+306974135662

I want to write a mongoid query that matches all the above formats. Is that possible?
User.where(phone: params[phone])

should return all 3 users with phone numbers +306974135662, 306974135662, and 30 6974135662

A: Option 1: store phone numbers as they are entered, use regular expressions for matching.
Option 2: store phone numbers as they are entered in one field. In another field store canonicalized representations of the phone numbers (the second one in your example). Match against the canonicalized representation.
The second option costs additional disk space, memory and pre-processing but allows queries to be simpler and faster.


text:
Q: Terraform: prevent recreating rds cluster during each apply with ignore_changes I managed to prevent recreating rds cluster during each apply by setting ignore_changes = all, but it is only one parameter -- cluster_members -- that changes. Setting only this parameter to ignore_changes doesn't work -- cluster gets destroyed and created again. Could someone help me understand why it doesn't work please?
resource "aws_rds_cluster" "aurora_cluster" {

  cluster_identifier     = local.cluster_id
  final_snapshot_identifier       = try(data.aws_db_cluster_snapshot.start_from_snapshot[0].id, null)
  engine                 = "aurora-mysql"
  engine_version         = var.rds_engine_version
  engine_mode            = "provisioned"
  master_username        = var.rds_master_username
  master_password        = var.rds_master_password
  db_subnet_group_name   = aws_db_subnet_group.rds-subnet-group.name
  vpc_security_group_ids = concat([aws_security_group.rds_inbound.id], var.external_sgs)
  apply_immediately               = true
  skip_final_snapshot             = true
  deletion_protection             = var.deletion_protection
  backup_retention_period         = var.backup_retention_period
  enabled_cloudwatch_logs_exports = var.rds_cloudwatch_logs
  kms_key_id                      = data.aws_kms_alias.rds_kms_key.arn
  storage_encrypted        = true
  db_cluster_parameter_group_name = aws_rds_cluster_parameter_group.rds-cluster-params.name
  db_instance_parameter_group_name = aws_db_parameter_group.rds-instance-params.name
  tags = merge(
    local.common_tags,
    {
      Description = "RDS cluster ..."
    }
  )
  lifecycle {
    ignore_changes = [cluster_members]
  }
}

Terraform plan:
# aws_rds_cluster.aurora_cluster has changed
  ~ resource aws_rds_cluster aurora_cluster {
      ~ cluster_members                     = [
          + rds-1-1,
          + rds-1-2,
        ]
        id                                  = rds-1
        tags                                = {
            Description      = RDS cluster 1
            EnvName          = env
            EnvType          = dev
            ...
        }
        # (37 unchanged attributes hidden)
    }

Unless you have made equivalent changes to your configuration, or ignored the
relevant attributes using ignore_changes, the following plan may include
actions to undo or respond to these changes.


text:
Q: How do I return an exception? I wrote a function that needs to do 3 checks and if one of the tests fails it should return an exception of type of LookupError, but it doesn't work.
(*verify_checksum is another function)
def check_datagram(datagram, src_comp, dst_app):
    try:
        src_comp==datagram[0:16]
    except LookupError:
        return "Mismatch in src_comp"
    try:
        dst_app==datagram[40:48]
    except LookupError:
        return "Mismatch in dst_app"
    try:
        verify_checksum(datagram)
    except False:
        return "Wrong checksum"
    return True

For example:
Input:
check_datagram("1111000000001111000011111111000001010101101010101111111111111111000000001111111100000000","0000111100001111", "11110000")

Expected output:
"Mismatch in dst_app"

A: def check_datagram(datagram, src_comp, dst_app):
    if src_comp != datagram[0:16]:
        raise LookupError("Mismatch in src_comp")
    if dst_app != datagram[40:48]:
        raise LookupError("Mismatch in dst_app")
    if not verify_checksum(datagram):
        raise LookupError("Wrong checksum")
    return True # redundant?

A: With construction from NPE's answer you should use try..except there where you'll use declared check_datagram() function.
#python3
try:
    check_datagram(a,b,c)
except LookupError as e:
    print(str(e))

That allow you to get message from raised error.


text:
Q: How are dependency files in Makefile with include resolved I have a few questions about makefiles. I have defined my own version of a dependency file (.d) by creating it in code and called it say .dd (Looks just like a normal .c dependency file except that this is for some internal file format). Now this file I have included in the makefile with the include statement. (There are a whole bunch of these files so I've defined this as a rule which uses subst to replace the extension as required.)
Now suppose that file X depends on file Y i.e. X.dd contains a reference to file Y. Now from my understanding, whenever I run make and the program goes through the include and finds that Y has been updated, it somehow recompiles this so as to reflect the changes in X.
My question and problem is when this timestamp change in Y is noticed, does make restart itself so as to include the changes. How exactly are dependency files of this sort resolved. Also file X is not a typical .c or .cc file. So how would the file be treated when its dependency changes.
The problem I'm facing is that if file Y is changed/touched, file X does not recompile. Also if I touch file X, it recompiles just fine. Also as expected, if the makefile is touched, everything recompiles appopriately.
This bug has me scratching my head for a few days now so any help whatsoever would be appreciated.

A: Presuming that an X.boy is generated from an X.src (and Y.boy from Y.src) then to following works:
Makefile:
    all: X.boy Y.boy
# for the example I will generate .boy with cp
%.boy: %.src
    cp $< $@

include X.dd

X.dd:
    X.boy: Y.src
This then gives:
$make
cp X.src X.boy
cp Y.src Y.boy

$touch X.src
$make
cp X.src X.boy

$touch Y.src
$make
cp X.src X.boy
cp Y.src Y.boy

A:
My question and problem is when this timestamp change in Y is noticed,does make restart itself so as to include the changes.

GNU make reads the timestamps of files once, when it starts up. If you don't explicitly re-invoke it (e.g. by calling make or $MAKE from within the makefile), it won't re-check the timestamps after running commands.

So how would the file be treated when its dependency changes.

All files are treated identically; make just has a few built in rules for some types of files. Dependencies are handled the same way for all file types.
It sounds like your included .d file is creating a dependency on the source file(s), and not the target file. You can verify this by printing the rules make is using with make -p.
I'll use c files as an example, since you already know how their dependencies should work. Lets assume you have a file foo.c (source) which gets compiled to foo.o (target) and whos dependencies are specified in foo.d. For this example, lets say if bar.h or baz.h change, we want foo.o to be rebuilt.
foo.d should then contain something like:
foo.o : bar.h baz.h

And your makefile would read
%.o:%.c
       $(CC) -c $< -o $@

include foo.d

Your symptoms sound like you have instead got a foo.d containing:
foo.c: bar.h baz.h
    ^

Or something totally unrelated on the left hand side, such that make does not see a dependency on foo.o. If you run make -p and search for foo.o in the output, you will see what make thinks it depends on from your makefile contents.


text:
Q: Securing a Windows Server 2008 R2 Public Web Server I'm setting up a public web server: Windows Server 2008 R2, IIS7.5. Does anyone have a tutorial / walkthrough / tips on properly securing a public web server? I've seen a few tutorials but mostly focused on Windows Server 2003.
What I've done so far:

*

*Created a specific user account for the website / app pool,

*Renamed Admin account,

*Installed FTPS,

*Configured firewall to block any non-public service (web / https),

*Configured firewall to allow access to management interfaces only from specific IP addresses (rdp, IIS management, ftp)

Maybe a few other things but can't remember at the moment...
ICMP is allowed... Should I disable all except ping?
Port scan reveals only web and https ports.
Any other suggestions?
Thanks

A: As far as ICMP, I don't disable it.
Certain ICMP messages control TCP window scaling and path MTU discovery. Disabling ICMP can lead to connection problems.
refs:
http://www.znep.com/~marcs/mtu/ <- Path MTU issue
http://www.daemon.be/maarten/icmpfilter.html <- ICMP filtering policy

A: Looks good. Do you have anything in front of the web server?

A: Check this question (though much only applies to IIS6) and have a look at Server 2008 Security Compliance Manager to create and apply a local security policy.


text:
Q: How to pass store values to the middleware? Here is my middleware, that increments store value each sec by one:
const timer = ({ dispatch }: { dispatch: Dispatch }) => {
  setInterval(() => dispatch(increment()), 1000);

  return (next: Dispatch) => (action: AnyAction) => {
    next(action);
  };
};

I want to provide here additional functionality, that depends on the stored value.
How can I pass the stored values to the middleware for writing here several conditions?
export const store = configureStore({
  reducer: root,
  middleware: [timer],
});


text:
Q: Bidirectional link in Realm database I want to access the field in parent table from child table.
public class Product extends RealmObject {

    @SerializedName("location")
    private String locationInStore;

     @SerializedName("tags")
    private RealmList<Tag> productTags;
}

and
public class Tag extends RealmObject {

    @PrimaryKey
    private String name;
    }
}

Now I have to search for the name in tag table and then I have to show the name that has matched the search and location of that tag.
  RealmResults<Tag> name = mRealm.where(Tag.class).contains("name", tag, Case.INSENSITIVE).findAll();

But this gives me only tag name, how can I access its location and other properties.
I also tried
 List<RealmResults<Product>> results = new ArrayList<>();

 results.add(mRealm.where(Product.class).contains("productTags.name", tag, Case.INSENSITIVE).findAll());

Above query returns me the product object but this product object contain the tag array not the one which has matched the search.
Thanks in advance

A: The main idea, why not the one of array has no matched the search, is a Case.INSENSITIVE search. Be carefull using this because of functionality have limitations:

Sorting and case insensitive string matches in queries are only supported for character sets in 'Latin Basic', 'Latin Supplement', 'Latin Extended A', 'Latin Extended B' (UTF-8 range 0-591). Moreover, sorting is done so capital and non-capital letters are sorted togther unlike what standard libraries do. That means that '- !"#0&()*,./:;?_+<=>123aAbBcCxXyYzZ is the actual sorting order in Realm. In addition, setting the case insensitive flag in queries when using equalTo(), notEqualTo(), contains(), endsWith(), beginsWith() or like() will only work on characters from the English locale.

Read more about these limitations here


text:
Q: C# Function with optional and params values I have this test code:
    void func1(string a, params string[] p)
    {
        func1(a, true, p);
    }

    void func1(string a, bool b, params string[] p)
    {
        //...
    }

    void func2(string a, bool b = true, params string[] p)
    {
        //...
    }

    void exec()
    {
        func1("a", "p1", "p2");
        func2("a", "p1", "p2");
    }

Is func1 and func2 equals?
There are no errors when I create the func2, but, when I try to use the func2 like in exec (using the optional value), the compiler show an error This function has some invalid arguments.
I think that func1 and func2 are equal for someone that will consume this function like an API.
What is wrong with this code?
Can I use this approach for functions that have optional and params values?

A: Normally optional parameters have to come at the end of a method declaration - a parameter array (such as p here) is the only exception to that. But when it comes to using the arguments, the compiler will assume that all positional arguments are in the same order as the method declaration... so you get into trouble if you want to use the optionality and the parameter array side. This should be okay:
func2("a", p: new[] { "p1", "p2" })

but personally I'd just steer clear of mixing parameter arrays and optional parameters. It's clearly confusing.
I believe the relevant section of the C# 5 specification is 7.5.1.1, which includes:

A positional argument of a function member with a parameter array invoked in its expanded form, where no fixed parameter occurs at the same position in the parameter list, corresponds to an element of the parameter array.

See also section 7.5.3.1. It's all pretty complicated...


text:
Q: Why is css text-align:center, not centering text? Underlining in the same format is working I wrote simple CSS to align text using the w3schools example with:
text-align:center

When I add an underline in the same format, the underline works.
Here's the snippet:

.CenterIt {
 text-align:center;
}
.UnderlineIt {
 text-decoration:underline;
}

Registration Form

Here's the w3schools page (the align text section):
https://www.w3schools.com/css/css_align.asp
In my full code I have the text I want to center inside another box. I've tried it both inside that box and outside any boxes. It doesn't center.

A: Try this. You need to wrap it with a container unit of

Registration Form

Following will work as well

Registration Form

A: It might work better if you run "display: flex;" on the container span and "justify-content: center;" on the child span. Flexbox is a little easier to use when placing items within a container.

A: Because your html, is in wrong format. You cant have a span child of a span.
try like this:

Registration Form

to have the span centered , without a parent div you would need to put the display, as block.
so you could have on your html and css like this:
span{display:block;}

 .CenterIt {
    text-align:center;
}
.UnderlineIt {
    text-decoration:underline;
}

html:
Registration Form

A:

.CenterIt {
 text-align:center;
  display:block;
}
.UnderlineIt {
 text-decoration:underline;
}

Registration Form

The display property of span by default is inline. i.e.,
display:inline;

Therefore,  will take only the width of its content. In contrast, block elements like
, by default, take the full line (and thereby the full width of the page) for its content.
To make the text-align work for , you need to change it into a block element.
Set
display: block;
for the span with .CenterIt class. This will make .CenterIt take the full line (and thereby the full width of the page), and then the text-align: center; will centralize the content.


text:
Q: Ansible: Output a variable in vars_prompt Is it possible to include the value of an existing variable in the message output by vars_prompt?
I am looking to do something like this:
- hosts: production
vars_prompt:
    confirm: "This playbook is configured to act on all $hosts hosts, please confirm"

...where the question printed by vars_prompt should be:
"This playbook is configured to act on all **production** hosts, please confirm"

A: This is not exactly answering the question, as what I tried to achieve apparently is not possible using the current stable version of Ansible, but I would like to describe a workaround that helped my solve my use case:
First of all, the reason I wanted to output the hosts from the playbook inside a vars_prompt message was to make sure that the playbook would never be run on hosts it was not intended for. The playbook sets up backup for a VM, and while its actions are idempotent, only some of my VMs require backups in the first place. So I wrote the playbook to automate installation of a backup client on a VM and to configure the new client on a central backup server.
What I did to make sure that I only ever run this playbook for the intended host was to make the hosts parameter in the playbook itself a variable, like this:
- hosts: '{{ host }}'

Now the playbook will fail immediately, if no host is specified on the command line. The way to specify such a variable on the command line is this:
ansible-playbook --extra-vars="host=HOSTNAME" playbook.yml

A: This is not possible, at least as recently as ansible version 1.4.4.  The vars_prompt displays literally exactly what is within the quotes, so any $, {{ }}, etc. is displayed exactly as entered.
It might be worth submitting a feature request for this by posting at https://github.com/ansible/ansible/issues


text:
Q: storing the accessor to innerHtml as a var I was trying to figure out a way to do the following
var foo = document.body.innerHtml;

then call foo = "testing"
and the body's html would read "testing"

but so far all that happens is innerHtml is returning the value of innerHtml ... which is expected
is there any way to store innerHtml and maybe do something like
var hold = "innerHtml"

document.body[hold] = "foo"  <--- this does not work by the way

A: You will have to use innerHTML (uppercase) instead of innerHtml to get the desired results.
These lines produce the same results:
document.body.innerHTML;
document.body["innerHTML"];
document["body"].innerHTML;
document["body"]["innerHTML"];


text:
Q: Should I use private variables in javascript? I just recently found out ( here) that there is a way to make variables in classes completely private in Javascript, meaning not accessible with the dot operator.
It works as such: JSFIDDLE
function PrivateRuns(startOff) {// make an object
    function getRuns() {// private function used to get private variables
        privateRuns -= 1; // accessable with "out" because in same scope
        privateRuns = Math.max( privateRuns, 0);
        return privateRuns + privateHits;
    }

    var privateRuns = startOff;
    var privateHits = 6;

    this.setRuns = function(val){ privateRuns = Math.max(val, 0); };
    this.getAction = function () {// this function is of scope "this"
        //out.privateHits = out.privateHits + 1;
        return ( "runs n hits:  "+ getRuns() +"   "  );
    };
}
var myRuns = new PrivateRuns(10);

myRuns.privateRuns = -10;// does not work
//myRuns.setRuns(-10);// DOES work
for( var i = 0; i < 10; i ++ ){
     $("HTML").append(  myRuns.getAction() +"<br>" );
}

Now I know that if used properly this has a lot of benefits, but is it really necessary? I have rarely ever seen this in tutorials, and I can't say I have personally looked for this in open-source projects.
Regarding this,

*

*Is it actually an error? (the site I read it mentioned it was a "hack")

This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.

*Is it a common practice, why or why not?

A: One reason you might want to use 'private' variables is if you are developing a library that is going to be used by other people. You can encapsulate all of your private variables, functions, etc and expose a public API into your library. This would allow your library to be included onto a page without having to worry about any of your variable names conflicting with other variables on the page. Take for example: jQuery. You can access all of the public API through the variable names jQuery or $. This means that only the variables jQuery and $ have been added to your page so you are free to use any other variable name you want without fear of conflicting with jQuery. The private variables allow you to implement things in your library however you want without fear of some piece of code on the page intentionally or accidentally altering the expected behavior.
It is not an error it is simply a side effect of the way variables are scoped in JavaScript
Check out the concept of immediately invoked function expressions as an example use case where private variables and functions can be useful (http://benalman.com/news/2010/11/immediately-invoked-function-expression/). There are many examples where private variables are used in JavaScript - as previously mentioned JavaScript library such as jQuery use them extensively.


text:
Q: Auto-Transformer: how to understand the following diagram? I have a question about the CW Auto-Transfomer that I will be using.
The wiring diagram is above. As you can see, the equitment takes 277/240/208/120V as input. But on its specification sheets, it never specify the output voltage. Can I assume that regardless of input level, the output voltage (which supplies to the cap and the lamp) will always be the same?

A: If you applied 277 volts to the top-tap of the primary or instead applied 120V to the bottom tap, the voltage seen at the secondary tap point should be the same. In fact the secondary wouldn't know whether it was supplied from any of the primary taps because they should all be designed to produce the same voltage at the secondary tap point.
If, on the other hand you decided to put 100 volts on the top-tap you couldn't expect the correct secondary voltage to be generated.

A: The core flux depends on and is proportional to the primary voltage per turn .The diagram shows the number of primary winding turns are higher for 277 input voltage than the number of turns for 100 input voltage . So it is designed to keep the voltage per turn at the input side constant.This will mean that the output voltage will be approximately constant ....................
The open circuit ans short circuit currents are different for different input voltages.That will decide the power output of the lamp ..............................The input ratings (120*4=480;208*2.3=478.4 ;240*2=480;277*1.75=484.75 ) shows the input VA is almost constant .So it is designed for a constant power output (400w) lamp.


text:
Q: SQL query to join multiple tables to meet all conditions or nothing in return I have this scenario and result set for my query. I need to filter the result set using certain condition.
Query I have:
SELECT
ord_no,parent_item,child_item,status

FROM **TABLE1** WHERE parent_item IN ('ITEM1') AND ord_no IN ('12345','34567','67854')

UNION ALL

SELECT
ord_no,parent_item,child_item,status

FROM **TABLE2** WHERE parent_item IN ('ITEM2') AND ord_no IN ('12345','34567','67854')

UNION ALL

SELECT
ord_no,parent_item,child_item,status

FROM **TABLE3** WHERE parent_item IN ('ITEM3') AND ord_no IN ('12345','34567','67854')

The query returns result like this and expected result that I am looking for is to return only that specific order_no where  ALL child_items are in COMPLETE status.
Query Result:
ord_no parent_item child_item status
12345   item1   childA  complete
12345   item1   childB  complete
12345   item2   childC  complete
12345   item2   childD  incomplete
12345   item3   childE  incomplete
12345   item3   childF  complete

34567   item1   childA  complete
34567   item1   childB  complete
34567   item2   childC  complete
34567   item2   childD  complete
34567   item3   childE  complete
34567   item3   childF  complete

67854   item1   childA  incomplete
67854   item1   childB  incomplete
67854   item2   childC  complete
67854   item2   childD  complete
67854   item3   childE  incomplete
67854   item3   childF  incomplete

Expected Result:
I am not able to figure out how do I implement this. Any help on this would be greatly appreciated.
ord_no parent_item child_item status

34567   item1   childA  complete
34567   item1   childB  complete
34567   item2   childC  complete
34567   item2   childD  complete
34567   item3   childE  complete
34567   item3   childF  complete

A: You can create a view from your existing query to avoid long expressions and use it for subqueries.
SELECT *
FROM MyView
WHERE ord_no NOT IN
  (SELECT ord_no
  FROM MyView
  WHERE status <> 'complete');


text:
Q: Why aren't final instance variables given default values? I was preparing for Java OCA certification where I came across a similar question like that of the following one:
public class TestClass {
    final int i;

    public static void main(String[] args) {
        TestClass t = new TestClass();
        System.out.println(t.i);
    }
}

As per Java, the instance and static variables are given default values. Surprisingly, this was error that was shown in my console:
error: variable i not initialized in the default constructor final int i;

Why wasn't i assigned a default value above?

A: Assigning default value to the final variable would defeat the entire purpose of making a variable final in the first place.
final would mean that you can't change the value once assigned.
If a default value is given to final variable then you would never be able to set the value of the variable to something else (even for the first time).

A: It's defined this way in the Java Language Specification:

Chapter 16. Definite Assignment
Each local variable (§14.4) and every blank final field (§4.12.4, §8.3.1.2) must have a definitely assigned value when any access of its value occurs.
[...]
For every access of a local variable or blank final field x, x must be definitely assigned before the access, or a compile-time error occurs.

Where the term "blank final field" refers to a final field with no value or initializer, and "definitely assigned" means that the field will be assigned to no matter what:

The idea behind definite assignment is that an assignment to the local variable or blank final field must occur on every possible execution path to the access. Similarly, the idea behind definite unassignment is that no other assignment to the blank final variable is permitted to occur on any possible execution path to an assignment.

Aside from throwing an error by specification, there's logical reasoning behind the decision. There's no point in having a default value for a blank final field. In your case, the blank final is an integer, and it would just be given 0 and you wouldn't be able to change it. What would the use of the variable be?
Also, if a final variable is not explicitly given a default value, why not initialize it in the first place? You can't reassign to it later since a default value would already be given, so why not initialize it now?

A: Error message is misleading since it can be initialized with default value:
class FinalTest{
    final int x = printXAndInitializeIt();

    private int printXAndInitializeIt(){
        System.out.println("x before initialization = "+x);
        return 1;
    }

    public static void main(String[] args) {
        FinalTest ft = new FinalTest();
        System.out.println("x after initialization = "+ft.x);
    }
}

Output:
x before initialization = 0
x after initialization = 1

But even if there is default value final variable expects explicit initialization, since in most cases lack of initialization is caused by mistake. This error could be changed to warning, but I am guessing that Java designers though that "better safe than sorry".

A:
Why didn't it assign a default value in the above case ? Can anyone
  explain!

if a default value were to be provided then you wouldn't be able to change the value of it. when the final keyword is used with variables it means once the variable is assigned, it cannot be re-assigned.
Wikipedia:

A final variable can only be initialized once, either via an
  initializer or an assignment statement. It does not need to be
  initialized at the point of declaration: this is called a "blank
  final" variable. A blank final instance variable of a class must be
  definitely assigned in every constructor of the class in which it is
  declared; similarly, a blank final static variable must be definitely
  assigned in a static initializer of the class in which it is declared;
  otherwise, a compile-time error occurs in both cases. (Note: If the
  variable is a reference, this means that the variable cannot be
  re-bound to reference another object. But the object that it
  references is still mutable, if it was originally mutable.)

further reading:
Definite Assignment

A: It's not that final fields aren't initialized to the default value — in fact they sort of are, though you'll only observe the fact if you're doing some silly stuff — but that you're required to explicitly initialize them exactly once (either as part of the declaration, or in an initializer block, or in every single constructor).
To understand the motivation for this, consider the following code:
public class Foo {
    private final int mValue;

    public Foo(final boolean shouldSet) {
        if (shouldSet) {
            mValue = 1;
        }
    }

    // ...
}

If the field weren't final, then the compiler would infer an implicit = 0 at the end of its declaration; but with a final field that's not always valid . . . and in the above example, the compiler can't even tell beforehand whether it will be valid or not. So the compiler sidesteps the issue by never inferring an implicit = 0, and requiring explicit initialization.


text:
Q: How to safely delete a thread pointer in a destructor? Say, I have a C++ class including a thread pointer as a member variable. The thread keeps running until the program exits. If I delete the pointer in the destructor, it seems that the thread has not yet finished at that moment? What is the best practice to manage this or any tricks?
Sample code:
class Car {
public:
    Car();
    ~Car();
private:
    boost::thread *m_runningThreadPtr;
};

Car::Car() {
    m_runningThreadPtr = new boost::thread();
}

Car::~Car() {
    delete m_runningThreadPtr;    // The thread should be still running now.
                                  // Problematic if it was deleted here?
}

A: By default the destructor will call terminate() to kill the thread if it's still running, whether this is safe or not depends on what the thread is doing at the time. You can call join() before deleting it if you want to wait for the thread to finish, and use some sort of synchronization system (even just a global flag) that tells the thread to quit.

A: It depends on what kind of behavior you're looking for.
If you want to delete the object, and have it stop its owned thread and then delete its thread object, then you should have a stop flag which your thread checks from time to time. In the destructor, you'd set the stop flag, and then call join() on your thread. Once it returns, you can safely delete the pointer.
If, on the other hand, you want to delete the object and have the thread go on its own until it finishes, then you need a more clever mechanism, like at the end of your thread function, posting to the main thread of your application a callback that calls join() on your thread and then deletes it. For that, of course, you'll need to have in your thread function a pointer to your thread object.
EDIT
In the case of boost::thread, it simply detaches in its destructor, so for the second option you can safely delete it when you're done.
It's important to note, however, that this won't work with std::thread's destructor, which will terminate your program in such a case. But then you can also manually call detach() and then delete. So you really have to look at the API you're using.

A: Don't delete it. Have the thread delete itself when done.

A: Your program is done when there's no more code to run. Are your threads still running code? Then why do you think your program is done?
So, it's reasonable to assume your threads are i fact done. That means you can call .join() on the thread, after which it is OK to call delete.


text:
Q: How can i draw a slanted rectangle in a frame (or picture)? I have a code that takes a video, split it into frames and then asks me how many rectangles would i like to draw on the frame (only the first frame, kin the code below).
I would like to be able to draw a slanted rectangles too. Is there any command that can help me?
 if k==1
    result=input('How many rectangles would you like to draw? ');
    pos=zeros(result,4);
    for i=1:result
      handle=imrect;
      pos(i,:)=handle.getPosition;
    end
end

A: In your code, imrect is responsible for drawing a rectangle.
You may use impoly to draw some polygons (here slanted rectangles).
The code
imshow('cameraman.tif')
h_poly = impoly;

will give

You can modify the shape by drag/dropping the selection's blue handles.
The positions of the blue handles can be known with
pos = getPosition(h_poly)


text:
Q: Need Help formulating an SQL Query I'm using MySql 5.5. Let's start by looking at a sample of my table:
pickupid    pickuplocation      Date1       Date2       Date3       Date4
1           Collingwood         1328079600  1330585200  1333260000  1335852000
2           Varsity             1328079600  1330585200  1333260000  1335852000
3           Canmore             1328079600  1330585200  1333260000  1335852000
4           Westbrook           1328079600  1330585200  1333260000  1335852000

I need  a query which will select only those dates which are in the future. If a date is in the past the query must skip over it. I have tried using Select with Have, Or, Where & AND. My queries fail because if one of the dates  happens to be in the past then the whole query comes back with zero results.  Yes, I know that if I orientated my table around the other way ie with locations in the columns and dates in the rows it could make it easier - I've tried that,  but I run into other problems as my HTML report has to accommodate over 50 locations,  but only 4 dates.
Many Many Thanks for All your Help !!

A: Since there's not a lot of detail about what you're trying to get, I'm just taking a guess, but, the below query will return all results where one of the dates is in the future, only the date columns with dates in the future will have data in them, the others will be set to NULL.
You can then exclude the null dates in your processing ...
Is this what you're going for?
SELECT
    pickupid,
    pickuplocation,
    IF(Date1 > NOW(),Date1,NULL) AS Date1,
    IF(Date2 > NOW(),Date2,NULL) AS Date2,
    IF(Date3 > NOW(),Date3,NULL) AS Date3,
    IF(Date4 > NOW(),Date4,NULL) AS Date4
FROM
    locations_table
WHERE
    Date1 > NOW()
    OR Date2 > NOW()
    OR Date3 > NOW()
    OR Date4 > NOW()


text:
Q: Multiple Inheritance in java Java is not allowing inheritance from multiple classes (still it allows inheritance from multiple interfaces.), I know it is very much inline with classic diamond problem. But my questions is why java is not allowing multiple inheritance like C++ when there is no ambiguity (and hence no chances of diamond problem) while inheriting from multiple base class ?

A: I have read that most programmers don't use multiple inheritance in a proper way. "Just go ahead and inherit from a class just to reuse code" is not the best practice in case of multiple inheritance.
Many programmers do not know when to use simple inheritance in most cases. Multiple inheritance must be used with caution and only if you know what you are doing if you want to have a good design.
I don't think that the lack of multiple inheritance in java (as in c++) will put restrictions in your code / application design / problem domain mapping into classes.

A: Simplicity. To quote Tom Sintes,

The Java design team strove to make Java:

*

*Simple, object oriented, and familiar

*Robust and secure

*Architecture neutral and portable

*High performance

*Interpreted, threaded, and dynamic

  The reasons for omitting multiple inheritance from the Java language
  mostly stem from the "simple, object oriented, and familiar" goal. As
  a simple language, Java's creators wanted a language that most
  developers could grasp without extensive training. To that end, they
  worked to make the language as similar to C++ as possible (familiar)
  without carrying over C++'s unnecessary complexity (simple).
In the designers' opinion, multiple inheritance causes more problems
  and confusion than it solves. So they cut multiple inheritance from
  the language (just as they cut operator overloading). The designers'
  extensive C++ experience taught them that multiple inheritance just
  wasn't worth the headache.

A: if java support multiple inheritance then it may effect other features of java
consider super() method which is used to call super class constructor.if program has multiple super class(because of multiple inheritance) then compiler will get confused about which super class constructor should be called and throw an error

A: It was a design decision of Java. You'll never get it, so don't worry too much about it. Although MI might help you make Mixins, that's the only good MI will ever do you.

A: Java designers decided that. Multiple inheritance can be simulated by the use of interfaces.

A: One simple answer is that all classes in Java derive from java.lang.Object IIRC. So, you would always have a diamond problem... :-D

A: It is true that Java did not use to support multiple inheritance of implementation (just of type i.e. interface). That was a design decision.
However, since Java 8, it supports multiple inheritance using default methods. See http://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html:

Multiple inheritance of implementation is the ability to inherit
  method definitions from multiple classes. Problems arise with this
  type of multiple inheritance, such as name conflicts and ambiguity.
  ... Default methods introduce one form of multiple inheritance of
  implementation.

A: The diamond problem arises when multiple parent classes define their own implementations of something and the child class of these two has to deal with the ambiguity of which implementation to use. So what if all classes in Java derive from Object, that's a single parent class. "Single parent, multiple derived classes" is not the same as "Multiple parents, single derived class"


text:
Q: Relate a new user to a role from their registration Laravel I have an app in laravel and I have 3 Admin, owner, user roles, I want that when a user registers he can choose between user and owner, for now I will use the registry of laravel / ui, I will leave them my relationships and my tables
Model Role
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function users(){

        return $this->belongsToMany('App\User');

    }
}

User Model
<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    public function roles(){

        return $this->belongsToMany('App\Role');
    }

    /* Validations */

    // The roles are received in the authorizeRoles variable, and they are validated if my role is valid or not, when accessing a page, the helpers abort generates an http exception and the user receives an error

    public function authorizeroles($roles){

        if($this->hasAnyRole($roles)){

            return true;

        }

        abort(401,'This action is unauthorized');
    }

    // Function, where we iterate (HasAnyRole) Enter the roles to check if you have any role

    public function hasAnyRole($roles){

        if(is_array($roles)){

            foreach($roles as $role){

              if($this->hasRole($role)){
                return true;
                }

            }

        }else{
            if($this->hasRole($roles)){
                return true;
            }
        }

        return false;

    }

     // HasRole function - We validate if our user contains the role for which it is asked -->

    public function hasRole($role){

        if($this->roles()->where('name',$role)->first()){
            return true;
        }

        return false;
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
         'name', 'email', 'password', 'provider', 'provider_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Register Controller
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }
}

I would like to know how to filter between only two roles in my controller and paint them in my view in a select, I would appreciate your support

A: In Controller
$roles = Role::whereIn('name', ['owner', 'user'])->get();

//And pass this roles in your view for example:

return view('user.create', compact('roles');

In view, in form:
<select name='role_id'>
  @foreach($roles as $role)
    <option value="{{$role->id}}">{{$role->name}}</option>
  @endforeach
</select>


text:
Q: Permission denied в Laravel Laravel проект создал. Запустил командой
php -S 127.0.0.1:8000-t public
Так как слишком долго загружался с
php artisan serve
Failed to open stream: Permission denied in Unknown on line 0
Fatal error. Unknown: Failed opening required 'public' ('include_path='C:\xampp\php\PEAR') in Unknown on line 0
Прочитал что надо добавить файл server.php но с ним у меня все в порядке
Ещё нашёл что надо написать
php artisan cache:clear
composer dump-autoload
Ничего не помогает
Уже три дня как не могу создать проект
Пожалуйста отзовитесь


text:
Q: how to make html content in browser center? I'm new to html/css, I have tried many times on a simple html/css file, but still not working. I want to make the content in center of the browser.
two source code are under same directory, here's the source code:
index.html:
<!DOCTYPE HTML>

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />

    <link rel="alternate stylesheet" type="text/css" href="style.css" />

Head Title2

write something in the center

Content

Introduction

Chapter

Chapter-1

Section-1

Section-2

Section-3

Section-4

Chapter-2

Section-1

Section-2

Section-3

Section-4

Chapter-3

Section-1

1

2

3

4

5

Section-2

1

2

3

4

5

Section-3

1

2

3

4

5

Reference

book1

book2

book3

style.css:
h1 {
    text-align: center;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 48px;
}

h2 {
    text-align: center;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 44px;
}

h3 {
    text-align: left;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 42px;
}

h4 {
    text-align: left;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 40px;
}

p {
    text-indent: 25px;
}

body {
    margin: 0;
    padding: 0;
    text-align: center; /* !!! */
}

.centered {
    margin: 0 auto;
    width: 800px;
}

but all the content are in left part. it shows like this:

I want the content in center part, and still the same format. what should I do ?
besides, I found my h1-h4 css not working, when I modify the font-size, index.html didn't change at all. why is it ?

thank for your help, after reading @J.Sahbu's code, I update my source code like this:
index.html:
<!DOCTYPE HTML>

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />

    <link rel="stylesheet" type="text/css" href="style.css" />

Head Title2

write something in the center

Content

Introduction

Chapter

Chapter-1

Section-1

Section-2

Section-3

Section-4

Chapter-2

Section-1

Section-2

Section-3

Section-4

Chapter-3

Section-1

1

2

3

4

5

Section-2

1

2

3

4

5

Section-3

1

2

3

4

5

Reference

book1

book2

book3

style.css:
h1 {
    text-align: center;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 34px;
}

h2 {
    text-align: center;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 30px;
}

h3 {
    text-align: left;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 26px;
}

h4 {
    text-align: left;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 24px;
}

p {
    text-indent: 25px;
}

body {
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 20px;
    margin-left: 20%;
    margin-right: 20%;
    min-width: 600px;
    max-width: 1024px;
}

This style is actually what I want.

A: The simplest and most natural way to center content horizontal is to use display: inline-block; on the element and text-align: center on its parent.
Its advantage over margin: 0 auto on a block element, it doesn't need a width, it simply adjust based on its content width
So change your centered rule to this, and it will center properly
.centered {
    display: inline-block;
}

As the text-align: center on the parent makes text inside the centered element also align centered, like with the

Introduction  Chapter

you simply add text-align: left to the centered rule
.centered {
    display: inline-block;
    text-align: left;
}

Stack snippet

h1 {
    text-align: center;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 48px;
}

h2 {
    text-align: center;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 44px;
}

h3 {
    text-align: left;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 42px;
}

h4 {
    text-align: left;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 40px;
}

/*  removed this as it cause the text to not center correct
p {
    text-indent: 25px;
}
*/

body {
    margin: 0;
    padding: 0;
    text-align: center; /* !!! */
}

.centered {
    display: inline-block;
    text-align: left;
}

Head Title2

write something in the center

Content

Introduction

Chapter

Chapter-1

Section-1

Section-2

Section-3

Section-4

Chapter-2

Section-1

Section-2

Section-3

Section-4

Chapter-3

Section-1

1

2

3

4

5

Section-2

1

2

3

4

5

Section-3

1

2

3

4

5

Reference

book1

book2

book3

A: Here is your fixed code. Just copy and paste below HTML And CSS as it is.
<!DOCTYPE HTML>

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />

    <link rel="stylesheet" type="text/css" href="style.css" />

Head Title2

write something in the center

Content

Introduction

Chapter

Chapter-1

Section-1

Section-2

Section-3

Section-4

Chapter-2

Section-1

Section-2

Section-3

Section-4

Chapter-3

Section-1

1

2

3

4

5

Section-2

1

2

3

4

5

Section-3

1

2

3

4

5

Reference

book1

book2

book3

css
body
{
 font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 18px;
      text-align: center;
    margin: 0 auto;
}

h1 {
    text-align: center;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 28px;
}

h2 {
    text-align: center;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 24px;
}

h3 {
    text-align: left;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 22px;
}

h4 {
    text-align: center;
    font-family: Cambria,Calibri,"Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size: 20px;
}

p {
    text-indent: 25px;
}

.centered {
    margin: 0 auto;
    text-align: center;
    width: 15%;
}

Cheers !


text:
Q: Cordova app suddenly not working correctly anymore since a few days ago i believe (mid march '15), my previously built apps with phonegap and/or cordova don't work properly anymore and this without updating anything. The Webview app seems to be the culprit since I load .html files as views. Webview is version 40 (1808730). Android 5.0.2 and 5.1.
Anyone with the same issue? Is there a fix somewhere?
Edit: it seems that Android >= 5.0.2 breaks my app. I could check on 5.0.1 and they still work ok. Any idea what changed? The apps are compiled with Cordova 4.3.0

A: I am also seeing changes. After Android Web View was updated to v.40 on 3/30/2015, my Cordova (v.4.3.0) app that displays Google Maps started missing tiles when I pan the map. Missing tiles appear as black squares and sometimes they reappear after a couple of seconds sometimes they don't.
To make sure I am not imagining this, I uninstalled the WebView update - the problem disappeared. I reinstalled the update - the problem appeared again.
I was not able to find the cure so far.

A: I could fix it but I did a bunch of things to finally get it to work again and honestly not sure which step actually fixed it.. Here's what I did. I uninstalled all of my plugins then forced the android platform update
cordova platform update android@3.7.1

then re added the plugins then compiled. Then uninstalled and reinstalled my plugins then recompiled. That fixed the display issues (Also I did uninstall and reinstall my android SDK's ...).


text:
Q: How do I add bookmarks to a watermarked secured PDF eBook? I have purchased a few PDF eBooks (RPG rulebooks) and they come with a set of bookmarks, but with such "technical" books, I would really like to be able to add new bookmarks for easy reference. (Normal PDF bookmarks would be best, because I'd like to use them on my tablet as well.)
However, these PDF files are secured ("watermarked" it said) and I cannot edit anything about them. The PDF security info that Adobe reader gives looks like this:
Security: Password Security
All contents of the document are encrypted ...
Document Restrictions Summary:
  Printing: Allowed
  ...
  Content Copying: Allowed
  ...
  Commenting: Not allowed
  ...

Anything I can do?
Note that while it says "Password Security" I myself don't have any password for this file, I just open it with a PDF reader and can then read it just fine.
Note: Personally, I don't care whether the document is still secured afterwards or whether doing anything is "legal" in anyone's opinion or some random jurisdiction. I payed good money for that document, I don't plan on sharing it, I just want some post-it notes in my tablet ready rulebooks ;-) .

A: Not sure if a password remover can help.
http://securityxploded.com/instant-pdf-password-remover.php
OR, metadata remover may help with many things:
http://www.becyhome.de/download_eng.htm
For BeCy (MetaEdit and PDFAsm), you need additional other programs so please read full info before trying to use it for the first time.

A: The challenge with the secure files is just that, they are secure.
I didn't have time today to test this, so I am not sure if this will work on secure PDFs, but JPdfBookmarks is freeware which helps you add bookmarks to existing PDF files.
Also, here is an article explaining how to do it - How to add bookmarks to a PDF document (using free software)


text:
Q: Console App Host ASPX Page? In Framework 4.0 I have a little console app. I have a self-contained .aspx page (no codebehind) and would like to run the console app just to host this page. I searched around for tricks with System.ServiceModel.Web or System.Web.Services trying to find a way to do this.
Can anyone help me get clue?
Thanks.

A: Have you seen this article? It's not written for asp.net 4.0, it's written for asp.net 2.0, but I don't think there's much difference.

A: The easiest way to host ASP.NET on a simple web server is to use the Cassini web server, which you can download from MS, including source code. The following two links help:

*

*http://en.wikipedia.org/wiki/Cassini_Web_Server

*http://www.asp.net/downloads/archived-v11/cassini
After downloading, the only things you need to do are:

*

*Comment out lines 92 through 96 of request.cs such that Cassini does not discard
requests coming from hosts other than localhost.

*Run build, which builds and installs the Cassini library into the GAC.

*Run the server.

Note: Cassini is a Console app, which just happens to show a form. If you're interested in it working purely as a Console app, refactor and remove the form. It should not be hard.


text:
Q: Highcharts rendering high amount of data points showing message "A webpage is slowing down your browser. What would you like to do?" in Firefox I'm using Highcharts in React and am having performance issues in Firefox 60.0.
It initially renders an empty chart fine, but whenever I try to update it with data, it gives me the message "A web page is slowing down your browser. What would you like to do?"
The web app will always be displaying anywhere from 20k points to 100k points, sometimes millions depending on the filters the user selects.
I have tried most optimizations Highcharts recommended. This is my code to initialize the chart:
componentDidMount() {
  let myChart = Highcharts.chart('my-plot', {
    chart: {
      zoomType: 'xy',
      marginTop: 40
    },
    boost: {
      useGPUTranslations: true,
      usePreAllocated: true
    },
    title: {
      text: null
    },
    xAxis: {
      events: {
        afterSetExtremes: function(event) {
          this.onZoom(event);
        }.bind(this)
      }
    }
    yAxis: {
      type: 'datetime',
      reversed: true,
      events: {
        afterSetExtremes: function(event) {
          this.onZoom(event);
        }.bind(this)
      }
    }
    plotOptions: {
      series: {
        turboThreshold: 0,
        events: {
          legendItemClick: function(event) {
            this.onLegendClick(event);
          }.bind(this);
        },
        stickyTracking: false
      },
      tooltip: {
        snap: 0
      }
    },
    series: [[]]
  });

  this.setState({myPlot: myChart});
}

And I am updating the data using:
componentDidUpdate(prevProps, prevState) {
  if(prevProps.plotData !== this.props.plotData) {
    let chart = this.state.myPlot;

    while(chart.series.length) {
      chart.series[0].remove(false);
    }

    chart.redraw();
    this.props.plotData.forEach((series) => {
      chart.addSeries(series, false);
    }
    chart.redraw();
  }
}

Here is the gist of what I am trying in a codesandbox.
I tried setting the redraw boolean to false when adding the series in hopes that it will not freeze up so often, and did a chart.redraw() after the forEach so it will redraw altogether at the very end. That was in another SO or blog post to help reduce lag, which did help in shortening the amount of times that "this web page is slowing down the browser" message appeared. But I'd like that message to go away completely.
This doesn't happen when I used other charting libraries like Plotly. But I like highcharts and the flexibility it offers, so I would like to continue using it.

A: The boost module has to be initialized properly:
// import Boost module
import Boost from "highcharts/modules/boost";

// initialize it
Boost(Highcharts);

Demo:

*

*https://codesandbox.io/s/o5z98km486


text:
Q: Importing split csv file in R I have a csv file that looks like:
Point            Site Energy Savings (%/yr) Annualized Energy Related Costs ($/yr)
Optimal Point 0        0                        1822.880005
Optimal Point 1        14.39999962              1608.069946
Optimal Point 2        20.65999985              1596.76001
Optimal Point 3        26.05999947              1639.98999
Optimal Point 4        34.54999924              1786.359985

Point            Site Energy Savings (%/yr) Annualized Energy Related Costs ($/yr)
Reference              0                        1822.880005
Iter 1, Pt 1           6.929999828              1818.089966
Iter 1, Pt 2           8.170000076              1863.180054
Iter 1, Pt 3           4.159999847              1845.390015

And I am trying to read it into R to plot the 2nd and 3rd column in a scatterplot, however read.csv is getting confused because of the double header. Any idea how to read it into R skipping the second header?
I would like the following to show in R:
Point                Site Energy Savings (%/yr) Annualized Energy Related Costs ($/yr)
Optimal Point 0      0                           1822.880005
Optimal Point 1      14.39999962                 1608.069946
Optimal Point 2      20.65999985                 1596.76001
Optimal Point 3      26.05999947                 1639.98999
Reference            0                           1822.880005
Iter 1, Pt 1         6.929999828                 1818.089966
Iter 1, Pt 2         8.170000076                 1863.180054
Iter 1, Pt 3         4.159999847                 1845.390015

A: I would do something like:
# read in first 5 rows only
a <- read.csv(file, nrows=5, header=TRUE)

# read in the last rows skipping the first 5 row data set
b <- read.csv(file, skip=6, header=TRUE)

rbind(a,b) # put them back together


text:
Q: Working with object consider the variable ob4 as shown in figure
now : how can i reach ob4[0]->[0,2]
var o=ob4[0];
double[,] p=(double[,]) o[0,0];

the line (double[,] p=(double[,]) o[0,0];) gives the following error :
Cannot apply indexing with [] to an expression of type 'object'

A: You need to cast o[0, 0] to object[,] first:
var o = (object[,]) ob4[0];
double[,] p = (double[,]) o[0, 0];

It would be better if you could avoid having all these nested multi-dimensional arrays with so little type information at compile-time though - you haven't given us much context, but if you could change your object model, it would help a lot.

A: Well, from the error message it is obvious that the runtime thinks o is object, not object[,]. So you might want to change your code to:
double[,] = (double[,])((object[,])o)[0,0];

Now the runtime knows that o should be treated as object[,].


text:
Q: primefaces dialog onchange to load datatable i am developing an application using jsf, primefaces and jpa. I'm facing one issue is that i'm using radio buttons and datatable in a dialog window. My condition is on selection radio button it invokes a method from the action and retrieves a list of data but i need to load the values in the datatable. But it is not loading the values in datatable
here is my xhtml code
<p:dialog header="RxnNo" widgetVar="dlg3" height="500" width="800">
     <p:selectOneRadio id="series" value="#{curation.series}">
          <f:selectItem itemLabel="SGML" itemValue="1" />
          <f:selectItem itemLabel="9000" itemValue="2" />
          <f:selectItem itemLabel="8500" itemValue="3" />
          <p:ajax listener="#{curation.getSeries9000}" update="seriesDataTable" />
      </p:selectOneRadio>
      <p:dataTable id="seriesDataTable" var="series" value="#{homePage.reactionsList}" widgetVar="seriesTable" scrollRows="20" scrollable="true" rowIndexVar="rowIndex">
             <p:column headerText="Id" filterBy="#{rowIndex+1}">
                    <h:outputText value="#{rowIndex+1}" />
          </p:column>
       </p:dataTable>
  </p:dialog>

here is my java code
public void getSeries9000() throws Exception {
        try {
            if (series.equals("2")) {
                series9000List = cationController.getAllSeries9000();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

can anyone help me to solve this problem.

A: try this :
<p:dialog header="RxnNo" widgetVar="dlg3" height="500" width="800">
<h:panelGroup id="global">
     <p:selectOneRadio id="series" value="#{curation.series}">
          <f:selectItem itemLabel="SGML" itemValue="1" />
          <f:selectItem itemLabel="9000" itemValue="2" />
          <f:selectItem itemLabel="8500" itemValue="3" />
          <p:ajax listener="#{curation.getSeries9000}" update="global" />
      </p:selectOneRadio>
      <p:dataTable id="seriesDataTable" var="series" value="#{homePage.reactionsList}" widgetVar="seriesTable" scrollRows="20" scrollable="true" rowIndexVar="rowIndex">
             <p:column headerText="Id" filterBy="#{rowIndex+1}">
                    <h:outputText value="#{rowIndex+1}" />
          </p:column>
       </p:dataTable>
</h:panelGroup>
  </p:dialog>


text:
Q: Image file not going to server using retrofit 2 post method Hi friends please help me out here i am new for the retrofit i am trying use the post method in the retrofit to send the image file by converting it into base64 format but it is not uploading please friends help me out this is my code
Retrofit code
    Retrofit registerretrofit = new Retrofit.Builder().baseUrl(Constant.url).client(Constant.okClient()).addConverterFactory(GsonConverterFactory.create()).build();
            Api registerapi = registerretrofit.create(Api.class);
            String urlbitmap=Constant.getStringImage(profilebitmap);
            Call<LoginResponse> registerresponse = registerapi.getregisterdetails(namestring, emailstring, passwordstring, phonestring, citystring, landnumstring, housenumstring, adrsstring1, adrssrtring2,urlbitmap, "Android", "DeviceToken", lat, lngitude);
            registerresponse.enqueue(new Callback<LoginResponse>() {
                @Override
                public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
//                    Constant.l(Constant.getStringImage(profilebitmap));
                    try {
                        Constant.l(String.valueOf(response));
                    } catch (Exception e) {
                        Constant.l(e.toString());
                    }
                    /*Constant.l(String.valueOf(response));
                    if (response.body().getStatus().equals("success")) {
                        Session.createlogin(getApplicationContext(), response.body().getUserid(), response.body().getName(), response.body().getEmail());
                        Intent loginintent = new Intent(getApplicationContext(), Login.class);
                        loginintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(loginintent);
                    } else if (response.body().getStatus().equals("failure")) {
                        Constant.s(username, "Email Already Exists");
                    }*/

                }

                @Override
                public void onFailure(Call<LoginResponse> call, Throwable t) {
                    Constant.l(t.toString());
                }
            });
        }

Interface.java
@FormUrlEncoded
    @POST("keemajson.php?action=register")
    Call<LoginResponse> getregisterdetails(@Query("uname") String uname, @Query("email") String email, @Query("password") String password, @Query("phone") String phone, @Query("city") String city, @Query("landline") String landline, @Query("building_num") String building_num, @Query("address1") String address1, @Query("address2") String address2, @Field("image") String image, @Query("device_name") String device_name, @Query("device_token") String device_token, @Query("lat") String lat, @Query("lng") String lng);

Base64 Method
ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] imagebytes = baos.toByteArray();
        String uploadencodedImage = Base64.encodeToString(imagebytes, Base64.DEFAULT);

The Reponse i am getting is
Response{protocol=http/1.0, code=500, message=Internal Server Error, url=http://54.202.3.127/keema/keemajson.php?action=register&uname=test2&email=tester2@gmail.com&password=123456&phone=1234567890&city=KKD&landline=0884237688&building_num=12-2-18&address1=Address1&address2=Address2&device_name=Android&device_token=DeviceToken&lat=16.9952685&lng=82.2450855}

This multipart code i had used
Retrofit registerretrofit = new Retrofit.Builder().baseUrl("http://54.202.3.127/keema/").client(Constant.okClient()).addConverterFactory(GsonConverterFactory.create()).build();
            Api registerapi = registerretrofit.create(Api.class);
            File profilefile = new File("/storage/emulated/0/Pictures/Screenshots/Screenshot_2017-02-22-14-10-53.png");
            RequestBody reqfile = RequestBody.create(MediaType.parse("image/*"), profilefile);
            RequestBody actionrb = RequestBody.create(MediaType.parse("text/plain"), "register");
            MultipartBody.Part body = MultipartBody.Part.createFormData("image", profilefile.getName(), reqfile);
            RequestBody namerb = RequestBody.create(MediaType.parse("text/plain"), namestring);
            RequestBody emailrb = RequestBody.create(MediaType.parse("text/plain"), emailstring);
            RequestBody passwordrb = RequestBody.create(MediaType.parse("text/plain"), passwordstring);
            RequestBody phonerb = RequestBody.create(MediaType.parse("text/plain"), phonestring);
            RequestBody cityrb = RequestBody.create(MediaType.parse("text/plain"), citystring);
            RequestBody adrssrb = RequestBody.create(MediaType.parse("text/plain"), adrsstring1);
            RequestBody adrssrrb = RequestBody.create(MediaType.parse("text/plain"), adrssrtring2);
            RequestBody landnumrb = RequestBody.create(MediaType.parse("text/plain"), landnumstring);
            RequestBody housenumrb = RequestBody.create(MediaType.parse("text/plain"), housenumstring);
            RequestBody devicenamerb = RequestBody.create(MediaType.parse("text/plain"), "Android");
            RequestBody devicetokenrb = RequestBody.create(MediaType.parse("text/plain"), "Devicetoken");
            RequestBody latrb = RequestBody.create(MediaType.parse("text/plain"), lat);
            RequestBody lngrb = RequestBody.create(MediaType.parse("text/plain"), lngitude);
            Call<ResponseBody> respbody = registerapi.getregisterdetails(actionrb,body, namerb, emailrb, passwordrb, phonerb, cityrb, adrssrb, adrssrrb, landnumrb, housenumrb, devicenamerb, devicetokenrb, latrb, lngrb);
            respbody.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    Constant.l(String.valueOf(response));
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Constant.l(t.toString());
                }
            });
        }

Interface of Multipart
@Multipart
      @POST("keemajson.php")
        Call<ResponseBody> getregisterdetails(@Part("action") RequestBody action,@Part MultipartBody.Part image,@Part("uname") RequestBody uname, @Part("email") RequestBody email, @Part("password") RequestBody password, @Part("phone") RequestBody phone, @Part("city") RequestBody city, @Part("landline") RequestBody landline, @Part("building_num") RequestBody building_num, @Part("address1") RequestBody address1, @Part("address2") RequestBody address2, @Part("device_name") RequestBody device_name, @Part("device_token") RequestBody device_token, @Part("lat") RequestBody lat, @Part("lng") RequestBody lng);

A: In order to POST a file, we need to enable Multipart.Part define a part inside the Multipart. MultipartBody.Part is the type that we want to use for a file / image. Non-file Part should use RequestBody type with expected fieldname
Service / Endpoint interface
interface Service {
    @Multipart
    @POST("/")
    Call<ResponseBody> postImage(@Part MultipartBody.Part image, @Part("name") RequestBody name);
}

Retrofit call, postImage parameter
File file = new File(filePath);

RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "upload_test");

retrofit2.Call<okhttp3.ResponseBody> req = service.postImage(body, name);
req.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        // Do Something
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        t.printStackTrace();
    }
});

Go through this githib example  for more details
EDIT
Parameters along with Image would be as follows
@Multipart
@POST("users/{id}/user_photos")
Call<models.UploadResponse> postImage(@Path("id") int userId, @PartMap Map<String, RequestBody> params);

Request parameters
//All the String parameters
Map<String, RequestBody> map = new HashMap<>();
map.put("methodName", toRequestBody(methodName));
map.put("userid", toRequestBody(userId));
map.put("name", toRequestBody(name));

//To put your image file as well
File file = new File("file_name");
RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), file);
map.put("relative_image\"; filename=\"some_file_name.png\"", fileBody);

// This method  converts String to RequestBody
public static RequestBody toRequestBody (String value) {
    RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
    return body ;
}

//To send your request
call = service.postImage(body, params);


text:
Q: awesome-ts-loader doesn't correctly process files when loaded through karma-webpack I have an Angular 2 application that is bundled with Webpack, and tested with Jasmine through Karma with karma-webpack. When developing, the code is bundled and served correctly. When testing, awesome-ts-loader throws a "Module parse failed" error on my .spec.ts file.
Module parse failed: /Users/kyleburke/angular2-app/app/main/app.component.spec.ts Unexpected token (10:8)
You may need an appropriate loader to handle this file type.
| ////////  SPECS  /////////////
| describe('AppComponent', function () {
|   let de: DebugElement;
|   let comp: AppComponent;
|   let fixture: ComponentFixture<AppComponent>;
@ ./app \.spec\.ts
@ ./karma-shim.js

I'm using the karma-webpack "alternative method" described on their Github Readme to load all of my .spec files (in karma-shim.js):
var appContext = require.context('./app', true, /\.spec\.ts/);
appContext.keys().forEach(function(path) {
  try {
    appContext(path);
  }
  catch(err) {
    console.error('problem with'+ path);
    console.error(err);
  }
});

The relevant section of my karma.conf.js is configured correctly, according to several sample repos:
files: [
  { pattern: './karma-shim.js', watched: false }
],
preprocessors: {
  './karma-shim.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,

And everything in my Webpack config lines up (partial sample):
module.exports = () => {
  const TARGET = process.env.npm_lifecycle_event;

  const isTest = TARGET === 'test';

  let config = {};

  config.entry = isTest ? {} : './app/main.ts';

  config.output = isTest ? {} : {
    path: './dist',
    filename: 'bundle.js'
  };

  config.resolve = {
    extensions: ['.ts', '.js', '.json', '.html']
  };

  config.module = {
    rules: [
      {
        test: /\.ts$/,
        loaders: ['awesome-typescript-loader', 'angular2-template-loader' ],
        exclude: [isTest ? /\.(e2e)\.ts$/ : /\.(spec|e2e)\.ts$/, /node_modules\/(?!(ng2-.+))/]
      },
      {test: /\.json$/, loader: 'json-loader'},
      {test: /\.html$/, loader: 'raw-loader'}
    ]
  };

  ...
}

The error from tslint makes me think that Webpack is correctly finding the spec file, but it maybe isn't being handed off to awesome-ts-loader, or it isn't loading the tsconfig.json. (again, everything loads fine when developing).


text: Q: Move SearchView Icon to the right side in ConstraintLayout I have a SearchView in ConstraintLayout. I set width to match_constraints, but how to move the icon to the right side? It seems that gravity_end doesn't work for icon.


text:
Q: Deploy AddIn-part(s) only to sp online I want to deploy one or more addin-parts (not just addins). Provider hosted.
I have no problems deploying a provider hosted addin, and no problem adding a addin-part to the existing addin. In VS I create an SP Addin-project and right-click on the SP-project and then Add new "client web part". But when I deploy SP asks me if I trust  (which is ok). I can see the default MS addin which I never use. It also creates an QuickLaunch-entry to this useless default addin
BUT:
I just want to deploy the addin-part(s) without any addin... hope this is somewhat clear :D

A: From where I understand, you have a provider hosted add-in and you want to deploy only the Add-in without the web? If yes, then please follow the below steps

*

*In the solution on the web project, right click and select unload project

*Go to the App Manifest file of the Add-in, inside the tag App Principal, where it says RemotePrincipal, change the tag to


text:
Q: how to set up basic AsyncCommand with Task in xamarin form Tools: I am using Xamarin.form MVVM.
Question: How do I set up basic AsyncCommand command with Task?
Debug: I am not getting any error, when I click on button, Displaybox alert doesnt show up. I check and addcommand method is not getting runned on tap.
Bind: I also have bind View with ViewModel
 BindingContext = new ProductViewModel();

I watched a tutorial by microsoft and there seem to be working just fine. Did I missed something?
View Page
<Button Text="Add" Command="{Binding AddCommand}" />

ViewModel Page
public class ProductViewModel : INotifyPropertyChanged
    {
       ...
      public AsyncCommand AddComamnd { get; }

      public ProductViewModel()
      {
        ...
        AddComamnd = new AsyncCommand(OnAddComamnd);
       }

  public async Task OnAddComamnd()
    {
        await App.Current.MainPage.DisplayAlert("Alert", "You have been alerted", "OK");
      // I have also tried both (App and Application) neither works
    }
}

A: ok, first of all there's a lot of typo, you put AddCommand here:
<Button Text="Add" Command="{Binding AddCommand}" />

So you need same command name:
public Command AddCommand { get; }

Then:
public ProductViewModel()
{
    ...
    AddCommand = new Command(async () => await OnAddComamnd()); //OnAddCommamnd is your async task
}

you can watch about command in here: Episode 5: MVVM & Data Binding with Xamarin.Forms start at minute 22


text:
Q: Gson to json coverting getting issue with class {"f":"RECEIVED","g":"Siva Sankar","n":"342","o":"PREPAID"}
I am getting keys as f,g,n instead of my key set
My code is:GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
            Gson gson = gsonBuilder.create();
            String gsonStr = gson.toJson(saveOrderDetails(),OrderDetails.class);

A: After making a lot of work on it.If found the issue in android that in build.gradle file in build release for debug we enabled it as minifyEnabled true. Make sure to change to minifyEnabled to false. Because of minifyEnabled true keys are converting into original keys to some random keys.


text:
Q: Dynamic selection of database, table and SQL query in SSIS I am new to SSIS project. I try to transfer data to a server which database, table names and SQL query changes according to the year of date.

*

*Source database: A17

*source table: A_PRICE_17

*source query:
 SELECT CODE, PRICE
 FROM A_PRICE_17
 JOIN someothertables

(so whole table selection is not possible)
Destination:

*

*Destination database: B17

*Destination table:  B_PRICE_17
17 comes from year 2017 and next year all database and tables names will be like A18,B18 etc.
I need help on configuring the source & destination, choosing the database, table and query which change related to the years.
I appreciate any help. Thank you

A: Make a meta table which holds Year,SourceName,DestinationName and TableName
Year | YearAlias | SourceName | DestinationName | TableName
2017 | 17        | A          | B               | Sales
2017 | 17        | A          | B               | Budget
2018 | 18        | A          | B               | Sales
.... | ....      | ..         | ..              | ....

Then in SSIS you can loop over each table and make your SQL Selects in a variable with values from SourceName when you use select and values from DestinationName when you want to choose your destination. Then your able to make it dynamic.


text:
Q: jquery to apply a css class to an image based on its width I have a div that is 770px wide. Due to surrounding elements I need to have the image within the div float left. I need to center the images that are less then 770px wide. Some image's are only 300px wide so stretching and cropping them are out of the question.
Is it possible to apply a class to all slider images that relates back to a jquery script that says if original image width is less then 770px then apply this css class to it. Then that class would center them image.
This seems like an easy fix but I cant wrap my head completely around it.
Here is a jsfiddle where im working.
would the toggle class work here? Just not sure how.
$(element).toggleClass("A B");

Any help or direction would be greatly appreciated.

A: Your fiddle is kind of a mess, so many scripts in different places. So I can't see exactly where your code for the Flexslider is, but the good news is that we should be able to figure this out without that :)
Flexslider has some pretty great built in functionality, including callbacks. Basically, you'll want to add something like this to the flexslider call:
$('#property-detail-flexslider').flexslider({
 after: function(){
  var current_img = $('.flex-active-slide img');
  if ( current_img.width() < 770 ) {
   current_img.addClass('center-img');
  }
 }
});

A: Temporarily free img tag from size limits, check its offsetWidth and then make decision about class. offsetWidth contain actual tag(block) width in pixels.

A: If the containing container is 770, and you want anything 770+ to fill the container, then put a max width on the image, and center the image within. I don't see why you need to float left if you want it to be either centered or full


text:
Q: Save file on server in wordpress using php i'm trying to save a file on server on a live domain  in wordpress using php , but when ever i try to give path it gives error and page goes blank
Here is my code.
<?php
$address=content_url()."/pdf_files/".$current_user->display_name."".$attempttotal.".pdf";
$pdf->Output($address,'F');
?>

This code work fine in localhost but i give path manually instead of using content_url function.
Warning: file_put_contents(http://domainname.com/wp-content/pdf_files/sen.pdf): failed to open stream: HTTP wrapper does not support writeable connections in /home/ameliadeol2015/public_html/wp-content/plugins/lifterlms/templates/quiz/fpdf/fpdf.php on line 1021
this is the error message

A: This error is solved by giving the server address instead of url address using this /home/content/site/folders/filename.php).


text:
Q: Jenkins makes github status stuck when PR I am using Jenkins to build. When I start a PR to a protected branch by an administrator, it always gives github two pending status of context "continuous-integration/jenkins/branch" and "continuous-integration/jenkins/pr-head" and have no detail link to them. It never happens when I make a PR from non-administrator. I don't know what is the reason of it.

And a github status of context "continuous-integration/jenkins/pr-merge" always work and is related to the running status of my Jenkinsfile. No matter who performs the PR.