text:
Q: R: Installing Quantstrat Error I'm trying to install quantstrat, however I always get following errors trying this:
> install.packages("quantstrat",repos="http://R-Forge.R-project.org")
Warning in install.packages :
  package 'quantstrat' is not available (for R version 3.0.1)
Installing package into 'C:/Users/mp/Documents/R/win-library/3.0'
(as 'lib' is unspecified)
trying URL 'http://R-Forge.R-project.org/bin/windows/contrib/3.0/quantstrat_0.7.8.zip'
Content type 'application/zip' length 1047389 bytes (1022 Kb)
opened URL
downloaded 1022 Kb

package 'quantstrat' successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\TEMP\Rtmp8uoKKX\downloaded_packages
> require(quantstrat)
Lade nötiges Paket: quantstrat
Lade nötiges Paket: foreach
Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) :
  es gibt kein Paket namens 'iterators'
Failed with error:  'Paket 'foreach' konnte nicht geladen werden'

Sorry the error messages are German. The first error is: "There is no packages called 'iterators'"
The second error is: "Package 'foreach' couldn't be loaded"

A: I ran into to the same problem
in order to get the install to run i had to install the quantmod package first because the rest of the packages require it pre-installed.
So first solve this dependency:
install.packages("quantmod")

then the rest of the packages
install.packages("FinancialInstrument", repos="http://R-Forge.R-project.org")
install.packages("blotter", repos="http://R-Forge.R-project.org")
install.packages("quantstrat", repos="http://R-Forge.R-project.org")

A: Try installing from source, CRAN is not up to date and the latest fixes are only available by installing from source. I have R-3.2.1 x64, installed fine form source.
Use the following in this order from your R console or RStudio:
install.packages("FinancialInstrument", repos="http://R-Forge.R-project.org")
install.packages("blotter", repos="http://R-Forge.R-project.org")
install.packages("quantstrat", repos="http://R-Forge.R-project.org")

Hope this helps.

A: Very late here, but perhaps relevant to note that "quantstrat" is not on CRAN, and several years ago moved to GitHub. The README on the repo (https://github.com/braverock/quantstrat) has more information for installing quantstrat.
install.packages("devtools") # if not installed
install.packages("FinancialInstrument") #if not installed
install.packages("PerformanceAnalytics") #if not installed

# next install blotter from GitHub
devtools::install_github("braverock/blotter")
# next install quantstrat from GitHub
devtools::install_github("braverock/quantstrat")


text:
Q: Where does import code belong in Rails? In my Rails app, I have to import large XML files, that will effect 10 or more models at once.
Now I'm not sure, where the code for this import belongs to. Should I include it in one single model, split it over all the models effected, use modules, or even concerns?
Does anyone have experience with that and can give me some advise?

A: If the import happens all at once, from one XML file, then just write an import script and put it in /lib/imports then call it from a rake task or something. Unless you need to factor it down into class methods I don't see the point, personally.
We import about 600MB of XML every day via several different import scripts and they're all in /lib/imports and called from rake tasks which in turn are scheduled and run using cron.

A: I would go with app/models/tasks/somename_importer.rb and encapsulate all your importer stuff there. You might also create a model for the actual data object you are importing.
class ImportedObject
  attr_accessor :have, :some, :accessor, :to, :hold, :data
  def initialize(data, *opts)
    # move data to instance variables
  end

  def to_object
    Object.new(some: mapping)
  end
end

class Tasks::SomeNameImporter
  def initialize
    # maybe setup some logging and stuff
  end

  def perform
    # fetch data from some source via http or file or ftp and iterate over appropriate items
    data.each do |item|
      imported = ObjectToImport.new(item)

      # you can do whatever you want with your imported data
      object   = imported.to_object
      if object.valid?
        object.save
      else
        # do some logging
      end
    end
  end
end

A: Assuming you could probably need some methods to interact with xml as well, I would go something like this
class XmlBase < ActiveRecord::Base
  #import xml files

  def method_to_parse_xml
      #code
  end
end

in your models (which requires xml files)
class User < XmlBase

end

class Project < XmlBase

end

#normal models
class Company < ActiveRecord::Base

end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Confused - How to get the geocode for an address (Google Maps) I create a small web app, the user add his address and I want to show the map for his address.
Is there a way to get the latitude and longitude for an address? with Google Maps.

A: Or you could use the geocoding service from google maps: http://code.google.com/apis/maps/documentation/javascript/services.html#Geocoding
Here's a simple example for it: http://code.google.com/apis/maps/documentation/javascript/examples/geocoding-simple.html

A: Yes there is. It is called geocoding. Here is Google's API: http://code.google.com/apis/maps/documentation/geocoding/


text:
Q: TF400917: The current configuration is not valid for this feature I added a new state to Task work item and then changed the state in process configuration. Imported task wit through power tools and then imported process template again.
However I am getting an error "Details about the validation error appear below:
The following element contains an error: TaskBacklog/States. TF400587: This element defines the states for work items that appear on your backlog. Each state must exist in at least one of the work item types belong to category defined in: 'TaskBacklog/States'. The following state does not exist in any of the work item types: Need tech design." Am I missing something ?

A: You would get this error if you only added the state "Need tech design" under section "TaskBacklog" in configuration file, but didn't add this state in the "Task" work item's workflow.
To fix this issue, modify the "Need tech design" to workflow states for the work items under Task category and import the configuration file.


text:
Q: LayoutInflater fails to inflate layout with reference to class I try to inflate Layout which contain class.
I create inflater instance with:
 LayoutInflater inflate =(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRelLayout = (RelativeLayout) inflate.inflate(
                    R.layout.app_layout, null);

My app_layout.xml layout is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:panel="http://schemas.android.com/apk/res/com.alpha"
            android:id="@+id/layoutMain"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:gravity="top|right">

        .
        .
        .

Inflation fails with exception: java.lang.RuntimeException: Your Panel must have a child View whose id attribute is 'R.id.panelHandle'
Thanks for help

A: I have tried following code, It's working perfect, Please provide full source code so I can identify the error.
Test.java
 LayoutInflater inflate =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
     RelativeLayout mRelLayout = (RelativeLayout) inflate.inflate(
                         R.layout.app_layout, null);

app_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:panel="http://schemas.android.com/apk/res/com.alpha"
            android:id="@+id/layoutMain"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:gravity="top|right" />

A: Have you tryed to remove xmlns:panel="http://schemas.android.com/apk/res/com.alpha"?
Can you post the entire layout?


text:
Q: Fullscreen flutter_vlc_player I was trying to implement full screen with the flutter_vlc_player but wasn't able because it is always returning "already initialized" so how can I get the same instance of that VLC Player to show in full screen?

A: The main trick is to wrap the VLCPlayer inside an AspectRatio and optionally inside a Transform if you would like to sale the video.
As the flutter_vlc_player plugin behaves unintuitive in some ways, I have prepared a sample project on Github to demonstrate the setup.
Assuming your app is displayed in landscape mode and the video is in 16 / 9 format:
final screenSize = MediaQuery.of(context).size;

final vlcPlayer = VlcPlayer(
    controller: vlcController,
    aspectRatio: screenSize.width / screenSize.height,
    placeholder: const Center(child: CircularProgressIndicator()));

Scaffold(
  body: Stack(
     children: [
        Container(
          // Background behind the video
          color: Colors.black,
        ),
        Center(
            child: AspectRatio(aspectRatio: 16 / 9, child: vlcPlayer)),
     ],
  ),
)

A: Just comment the line "throw Exception('Already Initialized');"
In initialize method of vlc_player_controller.dart
Future<void> initialize() async {
    if (value.isInitialized) {
      // throw Exception('Already Initialized');
    }....
}


text:
Q: How to fix ASUS Zenbook UX305FA stuck in bios I'm running Windows 8.1 on an m2 SSD. All of sudden it went to BIOS and is now stuck. I've tried BIOS defaults (no SSD shown as boot option), disabling fast boot and launching CSM, disabling secure boot, etc. I even tried reinstalled Windows, but cannot create a new partition and won't install on the one unallocated partition.
There's no recovery partition. I guess its been deleted.  Windows repair goes nowhere; I tried all options. I cannot refresh, reset or restore. The SSD shows up in the Windows installation, but not as a boot option in BIOS. I downloaded a memtest86+ ISO, but it wouldn't boot from it. I am presently using the Media Creation Tool to try to install Windows 10.
Does anyone have any ideas how to fix this issue?


text:
Q: Passing List object and int to web api I have a web api core project that if I send just the list parameter than the API receives the values, however if I send both parameters that the controller is looking for then both parameters are seen as null
My contoller:
[HttpPost]
[Route("/jobApi/RunBD")]
public int RunBDReport([FromBody]int month, [FromBody] IEnumerable<ClientModel> clients)
{
    billingDetailCycle objBillDetail = new billingDetailCycle();
    if (ModelState.IsValid)
    {
       return objBillDetail.Run(clients.ToList(), month);
    }
    else
    {
        return 500;
    }
}

ClientModel:
public class ClientModel
{
    public string BlockOfBus { get; set; }
    public string ClientId { get; set; }
    public string Location { get; set; }
    public string SuppressSsn { get; set; }
}

The request I am sending:
{"month":7,
"ClientModel":[{"blockOfBus":"XXX",
"clientId":"123456",
"location":"",
"suppressSsn":"N"}]}

This causes both parameters to be seen as null by the controller, however if I send my request like this:
[{"blockOfBus":"XXX",
"clientId":"123456",
"location":"",
"suppressSsn":"N"}]

Then the controller is able to see the list object I am sending (however it obviously returns 500 as the model is not valid)

A: [FromBody] can only be used once since the request body can only be read once.

Don't apply [FromBody] to more than one parameter per action method. Once the request stream is read by an input formatter, it's no longer available to be read again for binding other [FromBody] parameters.

Reference Model Binding in ASP.NET Core
Create a single model that matches the expected data.
public class DbReport {
    public int month { get; set; }
    public ClientModel[] ClientModel { get; set; }
}

And update the action accordingly
[HttpPost]
[Route("/jobApi/RunBD")]
public int RunBDReport([FromBody]DbReport report) {
    billingDetailCycle objBillDetail = new billingDetailCycle();
    if (ModelState.IsValid) {
       return objBillDetail.Run(report.ClientModel.ToList(), report.month);
    } else {
        return 500;
    }
}

A: There can be only one parameter modified with [FromBody]  attribute. So you need to either modify your method like this :
[Route("/jobApi/RunBD/{month}")]
public int RunBDReport(int month, [FromBody] IEnumerable<ClientModel> clients)

Then make the request like this :
url :/jobApi/RunBD/7
body :
[{"blockOfBus":"XXX",
"clientId":"123456",
"location":"",
"suppressSsn":"N"}]

Or modify both your method and model like this :
public class BdPayload{
public int Month {get; set;}
public IEnumerable<ClientModel> ClientModel {get;set;}
}

[Route("/jobApi/RunBD")]
public int RunBDReport( [FromBody] BdPayload model)

and then you can use the second request's body.

A: Try:
{"month":7,
"clients":[{"blockOfBus":"XXX",
"clientId":"123456",
"location":"",
"suppressSsn":"N"}]}

It looks like your ClientModel enumerable is mistitled in the payload

A: Try changing the route to:
[Route("/jobApi/RunBD/{month}")]
public int RunBDReport([FromUri]int month, [FromBody] IEnumerable<ClientModel> clients)

The payload needs to be passed as an array, like in Jonathan's answer.

A: There are few simple rules that help you get through these kind of issues when trying to pass data to your Web API endpoint. These are the default rules based on which the parameter binding happens. Based on these rules, you need to be applying the attributes like [FromBody] and [FromUri]

*

*GET method call takes both primitive and complex types as a part of the query string

*POST method call takes a primitive type parameter by default in the query string and the complex type needs to be passed as a part of the request body.

*PUT and PATCH follow similar default rules as that of POST.

*DELETE method's default rules are inline with the GET method.

Here by primitive types, I mean types like int and complex types are the classes that we create.
You can tackle the problem that you're dealing with by applying any of the solutions that others have already mentioned -- like moving your complex type into your request body and passing the primitive type through the query string OR wrapping both the primitive and complex types into a single model and deserialize the request body to the model type (which is done as a part of the parameter binding inherently).


text:
Q: Why can't I run a Java program from another Java program? I am running the following code. I ask the user to enter a Java program. The user's program will compile correctly, and if there is any error it will be pointed out. But when I try to run the program it won't run at all. Instead I get this message:

Program finished with exit code 0.

How do I solve this problem?
import java.io.*;
import java.util.*;

public class myprog1 {

public static void main(String [] args) throws IOException, InterruptedException {
    System.out.println("enter the candidate name");
    Scanner scan = new Scanner(System.in);
    String cname = scan.next();
    String cfilename = "candidate.java";
    String file1 = "/home/prakasha/IdeaProjects/" + cname;
    String file2 = "/home/prakasha/IdeaProjects/";
    File file = new File("/home/prakasha/IdeaProjects/" + cname);
    file.mkdir();
    if (!file.exists()) {
        System.out.println("filenotfound");
    } else {
        System.out.println("the code is stored in his dir :" + cname);
        File fobj = new File(file, "/" + cfilename);
        FileWriter fw = new FileWriter(fobj);
        System.out.println("enter the code");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String code = br.readLine();
        fw.append(code);
        System.out.println(fobj);
        fw.close();

        ProcessBuilder pb = new ProcessBuilder
                ("javac", file1 + "/" + cfilename);
        pb.inheritIO();

        Process process = pb.start();
        process.waitFor();

        BufferedReader is =
                new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
            // reading the output
        while ((line = is.readLine()) != null)
            System.out.println(line);

        ProcessBuilder pb1 = new ProcessBuilder
                ("java", file1 + "/" + "candidate");
        System.out.println(file1 + "/" + "candidate");
        pb.inheritIO();
        Process process1 = pb1.start();
        BufferedReader reading =
                new BufferedReader(new InputStreamReader(process1.getInputStream()));
        String line1;
        while ((line1 = reading.readLine()) != null)
                System.out.println(line1);
        }
}
}

A: The argument to the java command is a class name.
/home/prakasha/IdeaProjects/XXX/candidate is not a class name, since / is not a valid character in a class name.
Two ways to fix the problem:

*

*Specify location using -cp argument.

*Change the working directory to the folder where the files are.
Also, since you use inheritIO(), there is no output to copy, so getInputStream() is a null input stream.
I'd suggest using the second fix:
new ProcessBuilder("javac", "candidate.java")
        .directory(file)
        .inheritIO()
        .start()
        .waitFor();

new ProcessBuilder("java", "candidate")
        .directory(file)
        .inheritIO()
        .start()
        .waitFor();


text:
Q: Java 8 doesn't provide the same solution to allow multiple inheritance which they gave to solve interface default methods Problem:
We know that Java doesn't allow to extend multiple classes because it would result in the Diamond Problem where the compiler could't decide which superclass method to use. With interface default methods the Diamond Problem were introduction in Java 8. That is, because if a class implements two interfaces, each defining the same default method, and the implementing class doesn't override the common default method, the compiler couldn't decide which implementation to chose.
Solution:
Java 8 requires to provide an implementation for default methods implemented by more than one interface. So if a class would implement both interfaces mentioned above, it would have to provide an implementation for the common default method. Otherwise the compiler would throw a compile time error.
Question:
Why is this solution not applicable for multiple class inheritance, by overriding common methods introduced by child class?

A: You didn't understand the Diamond Problem correctly (and granted, the current state of the Wikipedia article doesn't explain it sufficiently). As shown in this graphic,

the diamond problem occurs, when the same class is inherited multiple times through different inheritance paths. This isn't a problem for interfaces (and never was), as they only define a contract and specifying the same contract multiple times makes no difference.
The main problem is not associated with the methods but the data of that super type. Should the instance state of A exist once or twice in that case? If once, C and B can have different, conflicting constraints on A's instance state. Both classes might also assume to have full control over A's state, i.e. not consider that other class having the same access level. If having two different A states, a widening conversion of a D reference to an A reference becomes ambiguous, as either A could be meant.
Interfaces don't have these problems, as they do not carry instance data at all. They also have (almost) no accessibility issues as their methods are always public. Allowing default methods, doesn't change this, as default methods still don't access instance variables but operate with the interface methods only.
Of course, there is the possibility that B and C declared default methods with identical signature, causing an ambiguity that has to be resolved in D. But this is even the case, when there is no A, i.e. no "diamond" at all. So this scenario is not a correct example of the "Diamond Problem".

A: Methods introduced by interfaces may always be overriden, while methods introduced by classes could be final. This is one reason why you potentially couldn't apply the same strategy for classes as you could for interfaces.

A: The conflict described as "diamond problem" can best be illustrated using a polymorphic call to method A.m() where the runtime type of the receiver has type D: Imagine D inherits two different methods both claiming to play the role of A.m() (one of them could be the original method A.m(), at least one of them is an override). Now, dynamic dispatch cannot decide which of the conflicting methods to invoke.
Aside: the distinction betwee the "diamond problem" and regular name clashes is particularly relevant in languages like Eiffel, where the conflict could be locally resolved for the perspective of type D, e.g., by renaming one method. This would avoid the name clash for invocations with static type D, but not for invocations with static type A.
Now, with default methods in Java 8, JLS was amended with rules that detect any such conflicts, requiring D to resolve the conflict (many different cases exist, depending on whether or not some of the types involved are classes). I.e., the diamond problem is not "solved" in Java 8, it is just avoided by rejecting any programs that would produce it.
In theory, similar rules could have been defined in Java 1 to admit multiple inheritance for classes. It's just a decision that was made early on, that the designers of Java did not want  to support multiple inheritance.
The choice to admit multiple (implementation) inheritance for default methods but not for class methods is a purely pragmatic choice, not necessitated by any theory.


text:
Q: Passing a function down as props I'm having a problem with a "Nothing was returned from render" issue when trying to put {} around my functions that are passed down as props. I think perhaps I am putting them in the wrong places.
Where should I be putting the {} on this code?
const WhiteAdvantageTags = props => {
  props.whiteAdvantageTags.map(function (name1, index1) {
    return (
      <Typography
        style={{
          lineHeight: '2',
          marginLeft: '0px',
          padding: '0',
        }}
      >
        <Link
          href="#"
          onClick={event => {
            props.popupInstruction(name1, 'White');
          }}
          onMouseOver={event => {
            props.highlightSquares(name1, 'White');
          }}
          onMouseLeave={event =>
            props.board.current.removeMarkers(undefined, undefined)
          }
          variant="body2"
        >
          - {name1}
        </Link>
      </Typography>
    );
  });
};

A: in order to use {} braces to wrap your function, you need to make sure to return something from that function explicitly. In this example, the proper way to implement it with braces would be:
const WhiteAdvantageTags = props => {
  return props.whiteAdvantageTags.map(function (name1, index1) { // added return statement
    return (
      <Typography
        style={{
          lineHeight: '2',
          marginLeft: '0px',
          padding: '0',
        }}
      >
        <Link
          href="#"
          onClick={event => {
            props.popupInstruction(name1, 'White');
          }}
          onMouseOver={event => {
            props.highlightSquares(name1, 'White');
          }}
          onMouseLeave={event =>
            props.board.current.removeMarkers(undefined, undefined)
          }
          variant="body2"
        >
          - {name1}
        </Link>
      </Typography>
    );
  });
};

However, since the function simply returns this value, you could instead simply return it directly:
const WhiteAdvantageTags = props => props.whiteAdvantageTags.map(function (name1, index1) {
    return (
      <Typography
        style={{
          lineHeight: '2',
          marginLeft: '0px',
          padding: '0',
        }}
      >
        <Link
          href="#"
          onClick={event => {
            props.popupInstruction(name1, 'White');
          }}
          onMouseOver={event => {
            props.highlightSquares(name1, 'White');
          }}
          onMouseLeave={event =>
            props.board.current.removeMarkers(undefined, undefined)
          }
          variant="body2"
        >
          - {name1}
        </Link>
      </Typography>
    );
  });

A: You have two options.
First option.
const WhiteAdvantageTags = props => {
return (
<>
{
  props.whiteAdvantageTags.map(function (name1, index1) {
  ...
  }
}
</>
)
}

Second option: I did not try this one recently. You can check if it works.
const WhiteAdvantageTags = props => (
<>
{
... // put the orgin content here
}
</>
)

A: Explanation
Imagine you have welcome text passed through props
Your style will look like this
const WhiteAdvantageTags = props =>
{props.welcome}

If you want to use {}. You will put is inside function brackets.
const WhiteAdvantageTags = ({welcome}) =>
{welcome}

Complete solution to you problem
const WhiteAdvantageTags = ({whiteAdvantageTags, popupInstruction, highlightSquares, board}) => {
   whiteAdvantageTags.map(function (name1, index1) {
    return (
      <Typography
        style={{
          lineHeight: '2',
          marginLeft: '0px',
          padding: '0',
        }}
      >
        <Link
          href="#"
          onClick={event => {
            popupInstruction(name1, 'White');
          }}
          onMouseOver={event => {
            highlightSquares(name1, 'White');
          }}
          onMouseLeave={event =>
            board.current.removeMarkers(undefined, undefined)
          }
          variant="body2"
        >
          - {name1}
        </Link>
      </Typography>
    );
  });
};

A: const WhiteAdvantageTags = props => (
    <>
        { ...map function...}
    </>
)


text:
Q: Convert an HTML table to pdf, arabic not supported,also only few columns are shown I am trying to convert an HTML table with dynamic data which might also include Arabic into a PDF.
I am using JSPDF. However only the first few columns are shown in the PDF.
I have also tried to use CSV but couldn't find a way to get it into a tabular form.
My questions:

*

*How do I get to show all my HTML table columns in the PDF using JSPDF, and provide support for Arabic?

*Is there a way to email this file as an attachment to known user?


text:
Q: How to get product variation in cart? I have some meal packages to sell. For example.
Chicken meal has variations: 10 pack, 14 pack, 18 pack.
I want to disable flat_rate:3 when people order 10 pack. But I don't know how to get the variation.
My code is below:
function hide_one_delivery( $rates, $item_id ) {
    global $woocommerce, $product;
    $10_pack = 0;
    foreach ( $woocommerce->cart->cart_contents as $product ) {
        $variation_data = $product->get_variation_attributes();
        $variation_detail = woocommerce_get_formatted_variation( $variation_data, true );
        if( $variation_detail == "10 pack" ){
            $10_pack += 1;
        }
    }
    if ($10_pack > 0){
        unset( $rates['flat_rate:3'] );
    }
    return $rates;
}
add_filter( 'woocommerce_package_rates', 'hide_one_delivery', 100 );

It's not working. Can anyopne please help?

A: Just look into the product array, and you can get the variation data from the product array.
function hide_one_delivery( $rates, $item_id ) {
    global $woocommerce;

    foreach ( $woocommerce->cart->cart_contents as $product ) {
        //$product is a array, and 10-pack is the slug of the attribute name
        if ( $product['variation_id'] && in_array('10-pack', $product['variation']) ) {

            unset( $rates['flat_rate:3'] );
            break;

        }

    }

    return $rates;
}
add_filter( 'woocommerce_package_rates', 'hide_one_delivery', 100, 2 );

A: This code will allow you to add the variation to your cart.php page. My example has a name because I name my Variation "PkgDesc" when I added it to the Cart Session. This is code that you need to add to the Cart.php page.
Add the line of code after the foreach() line (around line 48):
$pkgDesc= apply_filters( 'woocommerce_cart_item_product_id', $cart_item['variation'], $cart_item, $cart_item_key );

Now add the code below after your product title (// Meta data) (around line 85)
echo ": ";

echo $pkgDesc['PkgDesc'];

Your Cart line item will now look like this:
Chicken meal: 10 pack


text:
Q: IntelliJ live template, annotated expression In Intellij live templates, there is a function 'annotated("annotation qname")' (https://www.jetbrains.com/idea/help/live-template-variables.html). How is the function used? What is the function for?

A: This macro returns all methods/fields/classes annotated with a specified qualified name. It can be useful when creating live templates for a particular framework, where in some place you only expect names of members that are annotated in a special way.
Some predefined live templates in RESTFul Web Services and Web Services groups are using this macro.


text:
Q: How do I programmatically "restart" an Android app? Firstly, I know that one should not really kill/restart an application on Android. In my use case, I want to factory-reset my application in a specific case where a server sends a piece of specific information to the client.
The user can only be logged in on the server with ONE instance of the application (i.e. multiple devices are not allowed). If another instance gets that "logged-in"-lock then all other instances of that user have to delete their data (factory-reset), to maintain consistency.
It is possible to forcibly get the lock because the user might delete the app and reinstall it which would result in a different instance-id and the user would not be able to free the lock anymore. Therefore it is possible to forcibly get the lock.
Because of that force-possibility, we need to always check in a concrete instance that it has the lock. That is done on (almost) each request to the server. The server might send a "wrong-lock-id". If that is detected, the client application must delete everything.

That was the use-case.
I have an Activity A that starts the Login Activity L or the app's main Activity B depending on a sharedPrefs value. After starting L or B it closes itself so that only L or B is running. So in the case that the user is logged in already B is running now.
B starts C. C calls startService for the IntentService D. That results in this stack:
(A) > B > C > D
From the onHandleIntent method of D, an event is sent to a ResultReceiver R.
R now handles that event by providing the user a dialog where he can choose to factory-reset the application (delete the database, sharedPrefs, etc.)
After the factory-reset I want to restart the application (to close all activities) and only start A again which then launches the login Activity L and finishes itself:
(A) > L
The Dialog's onClick-method looks like this:
@Override
public void onClick(DialogInterface dialog, int which) {

    // Will call onCancelListener
    MyApplication.factoryReset(); // (Deletes the database, clears sharedPrefs, etc.)
    Intent i = new Intent(MyApp.getContext(), A.class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    MyApp.getContext().startActivity(i);
}

And that's the MyApp class:
public class MyApp extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getContext() {
        return context;
    }

    public static void factoryReset() {
        // ...
    }
}

The problem is if I use the FLAG_ACTIVITY_NEW_TASK the Activities B and C are still running. If I hit the back button on the login Activity I see C, but I want to go back to the home screen.
If I do not set the FLAG_ACTIVITY_NEW_TASK I get the error:
07-07 12:27:12.272: ERROR/AndroidRuntime(9512): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

I cannot use the Activities' Context, because the ServiceIntent D might also be called from a background task which is started by the AlarmManager.
So how could I solve this to the activity stack becoming (A) > L?

A: The best way to fully restart an app is to relaunch it, not just to jump to an activity with FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_NEW_TASK. So my solution is to do it from your app or even from another app, the only condition is to know the app package name (example: 'com.example.myProject')
 public static void forceRunApp(Context context, String packageApp){
    Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageApp);
    launchIntent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(launchIntent);
}

Example of usage restart or launch appA from appB:
forceRunApp(mContext, "com.example.myProject.appA");

You can check if the app is running:
 public static boolean isAppRunning(Context context, String packageApp){
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
    for (int i = 0; i < procInfos.size(); i++) {
        if (procInfos.get(i).processName.equals(packageApp)) {
           return true;
        }
    }
    return false;
}

Note: I know this answer is a bit out of topic, but it can be really helpful for somebody.

A: Jake Wharton recently published his ProcessPhoenix library, which does this in a reliable way. You basically only have to call:
ProcessPhoenix.triggerRebirth(context);

The library will automatically finish the calling activity, kill the application process and restart the default application activity afterwards.

A: My best way to restart application is to use finishAffinity();
Since, finishAffinity(); can be used on JELLY BEAN versions only, so we can use ActivityCompat.finishAffinity(YourCurrentActivity.this); for lower versions.
Then use Intent to launch first activity, so the code will look like this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    finishAffinity();
    Intent intent = new Intent(getApplicationContext(), YourFirstActivity.class);
    startActivity(intent);
} else {
    ActivityCompat.finishAffinity(YourCurrentActivity.this);
    Intent intent = new Intent(getApplicationContext(), YourFirstActivity.class);
    startActivity(intent);
}

Hope it helps.

A: Still Working Now
 public void resetApplication() {
    Intent resetApplicationIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
    if (resetApplicationIntent != null) {
        resetApplicationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    }
    context.startActivity(resetApplicationIntent);
    ((Activity) context).overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}

A: IntentCompat.makeMainSelectorActivity - Last tested on 11/2020
The app will be restored with the launcher activity and the old process will be killed.
Works from Api 15.
public static void restart(Context context){
    Intent mainIntent = IntentCompat.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_LAUNCHER);
    mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.getApplicationContext().startActivity(mainIntent);
    System.exit(0);
}

A: My solution doesn't restart the process/application. It only lets the app "restart" the home activity (and dismiss all other activities). It looks like a restart to users, but the process is the same. I think in some cases people want to achieve this effect, so I just leave it here FYI.
public void restart(){
    Intent intent = new Intent(this, YourHomeActivity.class);
    this.startActivity(intent);
    this.finishAffinity();
}

A: You can use PendingIntent to setup launching your start activity in the future and then close your application
Intent mStartActivity = new Intent(context, StartActivity.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

A: The only code that did not trigger "Your app has closed unexpectedly" is as follows. It's also non-deprecated code that doesn't require an external library. It also doesn't require a timer.
public static void triggerRebirth(Context context, Class myClass) {
    Intent intent = new Intent(context, myClass);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);
    Runtime.getRuntime().exit(0);
}

A: There is a really nice trick. My problem was that some really old C++ jni library leaked resources. At some point, it stopped functioning. The user tried to exit the app and launch it again -- with no result, because finishing an activity is not the same as finishing (or killing) the process. (By the way, the user could go to the list of the running applications and stop it from there -- this would work, but the users just do not know how to terminate applications.)
If you want to observe the effect of this feature, add a static variable to your activity and increment it each, say, button press. If you exit the application activity and then invoke the application again, this static variable will keep its value. (If the application really was exited, the variable would be assigned the initial value.)
(And I have to comment on why I did not want to fix the bug instead. The library was written decades ago and leaked resources ever since. The management believes it always worked. The cost of providing a fix instead of a workaround... I think, you get the idea.)
Now, how could I reset a jni shared (a.k.a. dynamic, .so) library to the initial state?
I chose to restart application as a new process.
The trick is that System.exit() closes the current activity and Android recreates the application with one activity less.
So the code is:
/** This activity shows nothing; instead, it restarts the android process */
public class MagicAppRestart extends Activity {
    // Do not forget to add it to AndroidManifest.xml
    // <activity android:name="your.package.name.MagicAppRestart"/>
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.exit(0);
    }
    public static void doRestart(Activity anyActivity) {
        anyActivity.startActivity(new Intent(anyActivity.getApplicationContext(), MagicAppRestart.class));
    }
}

The calling activity just executes the code MagicAppRestart.doRestart(this);, the calling activity's onPause() is executed, and then the process is re-created. And do not forget to mention this activity in AndroidManifest.xml
The advantage of this method is that there is no delays.
UPD: it worked in Android 2.x, but in Android 4 something has changed.

A: I've found that this works on API 29 and later - for the purpose of killing and restarting the app as if the user had launched it when it wasn't running.
public void restartApplication(final @NonNull Activity activity) {
   // Systems at 29/Q and later don't allow relaunch, but System.exit(0) on
   // all supported systems will relaunch ... but by killing the process, then
   // restarting the process with the back stack intact. We must make sure that
   // the launch activity is the only thing in the back stack before exiting.
   final PackageManager pm = activity.getPackageManager();
   final Intent intent = pm.getLaunchIntentForPackage(activity.getPackageName());
   activity.finishAffinity(); // Finishes all activities.
   activity.startActivity(intent);    // Start the launch activity
   System.exit(0);    // System finishes and automatically relaunches us.
}

That was done when the launcher activity in the app has this:
<intent-filter>
    <action android:name="android.intent.action.VIEW"/>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

I've seen comments claiming that a category of DEFAULT is needed, but I haven't found that to be the case. I have confirmed that the Application object in my app is re-created, so I believe that the process really has been killed and restarted.
The only purpose for which I use this is to restart the app after the user has enabled or disabled crash reporting for Firebase Crashlytics. According to their docs, the app has to be restarted (process killed and re-created) for that change to take effect.

A: Try using FLAG_ACTIVITY_CLEAR_TASK

A: Kotlin version of this answer:
val intent = Intent(this, YourActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
Runtime.getRuntime().exit(0)

A: Ok, I refactored my app and I will not finish A automatically. I let this run always and finish it through the onActivityResult event.
In this way I can use the FLAG_ACTIVITY_CLEAR_TOP + FLAG_ACTIVITY_NEW_TASK flags to get what I want:
public class A extends Activity {

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        finish();
    }

    protected void onResume() {
        super.onResume();
        // ...
        if (loggedIn) {
            startActivityForResult(new Intent(this, MainActivity.class), 0);
        } else {
            startActivityForResult(new Intent(this, LoginActivity.class), 0);
        }
    }
}

and in the ResultReceiver
@Override
public void onClick(DialogInterface dialog, int which) {
    MyApp.factoryReset();
    Intent i = new Intent(MyApp.getContext(), A.class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    MyApp.getContext().startActivity(i);
}

Thanks anyway!

A: Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);

A: You can simply call:
public static void triggerRebirth(Context context, Intent nextIntent) {
    Intent intent = new Intent(context, YourClass.class);
    intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(KEY_RESTART_INTENT, nextIntent);
    context.startActivity(intent);
    if (context instanceof Activity) {
      ((Activity) context).finish();
    }

    Runtime.getRuntime().exit(0);
}

Which is used in the ProcessPhoenix library

As an alternative:
Here's a bit improved version of @Oleg Koshkin answer.
If you really want to restart your activity including a kill of the current process, try following code. Place it in a HelperClass or where you need it.
public static void doRestart(Context c) {
        try {
            //check if the context is given
            if (c != null) {
                //fetch the packagemanager so we can get the default launch activity
                // (you can replace this intent with any other activity if you want
                PackageManager pm = c.getPackageManager();
                //check if we got the PackageManager
                if (pm != null) {
                    //create the intent with the default start activity for your application
                    Intent mStartActivity = pm.getLaunchIntentForPackage(
                            c.getPackageName()
                    );
                    if (mStartActivity != null) {
                        mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        //create a pending intent so the application is restarted after System.exit(0) was called.
                        // We use an AlarmManager to call this intent in 100ms
                        int mPendingIntentId = 223344;
                        PendingIntent mPendingIntent = PendingIntent
                                .getActivity(c, mPendingIntentId, mStartActivity,
                                        PendingIntent.FLAG_CANCEL_CURRENT);
                        AlarmManager mgr = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
                        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
                        //kill the application
                        System.exit(0);
                    } else {
                        Log.e(TAG, "Was not able to restart application, mStartActivity null");
                    }
                } else {
                    Log.e(TAG, "Was not able to restart application, PM null");
                }
            } else {
                Log.e(TAG, "Was not able to restart application, Context null");
            }
        } catch (Exception ex) {
            Log.e(TAG, "Was not able to restart application");
        }
    }

This will also reinitialize jni classes and all static instances.

A: I have slightly modified Ilya_Gazman answer to use new APIs (IntentCompat is deprecated starting API 26). Runtime.getRuntime().exit(0) seems to be better than System.exit(0).
 public static void triggerRebirth(Context context) {
    PackageManager packageManager = context.getPackageManager();
    Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
    ComponentName componentName = intent.getComponent();
    Intent mainIntent = Intent.makeRestartActivityTask(componentName);
    context.startActivity(mainIntent);
    Runtime.getRuntime().exit(0);
}

A: Use:
navigateUpTo(new Intent(this, MainActivity.class));

It works starting from API level 16 (4.1), I believe.

A: You can use startInstrumentation method of Activity. You need implement empty Instrumentation and pointed in manifest. After that you can call this method for restart your app. Like this:
try {
    InstrumentationInfo info = getPackageManager().queryInstrumentation(getPackageName(), 0).get(0);
    ComponentName component = new ComponentName(this, Class.forName(info.name));
    startInstrumentation(component, null, null);
} catch (Throwable e) {
    new RuntimeException("Failed restart with Instrumentation", e);
}

I get Instrumentation class name dynamically but you can hardcode it. Some like this:
try {
    startInstrumentation(new ComponentName(this, RebootInstrumentation.class), null, null);
} catch (Throwable e) {
    new RuntimeException("Failed restart with Instrumentation", e);
}

Call startInstrumentation make reload of your app. Read description of this method. But it can be not safe if acting like kill app.

A: Directly start the initial screen with FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK.

A: The application I'm working on has to give the user the possibility to choose which fragments to display (fragments are dynamically changed at run-time). The best solution for me was to restart completely the application.
So I tried plenty of solutions and none of them has worked for me, but this:
final Intent mStartActivity = new Intent(SettingsActivity.this, Splash.class);
final int mPendingIntentId = 123456;
final PendingIntent mPendingIntent = PendingIntent.getActivity(SettingsActivity.this, mPendingIntentId, mStartActivity,
                    PendingIntent.FLAG_CANCEL_CURRENT);
final AlarmManager mgr = (AlarmManager) SettingsActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
this.finishAffinity(); //notice here
Runtime.getRuntime().exit(0); //notice here

Hoping that is going to help someone else!

A: fun triggerRestart(context: Activity) {
    val intent = Intent(context, MainActivity::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    context.startActivity(intent)
    if (context is Activity) {
        (context as Activity).finish()
    }
    Runtime.getRuntime().exit(0)
}

A: I got this way.
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(
 getBaseContext().getPackageName() );
 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 startActivity(i);
 finish();

A: I had to add a Handler to delay the exit:
 mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 200, mPendingIntent);
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Runtime.getRuntime().exit(0);
            }
        }, 100);

A: try this:
Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

A: With the Process Phoenix library. The Activity you want to relaunch is named "A".
Java flavor
// Java
public void restart(){
    ProcessPhoenix.triggerRebirth(context);
}

Kotlin flavor
// kotlin
fun restart() {
    ProcessPhoenix.triggerRebirth(context)
}

A: Apply delay restart
startDelay Startup delay (in milliseconds)
 public static void reStartApp(Context context, long startDelay) {
    //Obtain the startup Intent of the application with the package name of the application
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
    PendingIntent restartIntent = PendingIntent.getActivity(context.getApplicationContext(), -1, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (mgr != null) {
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + startDelay, restartIntent);
    }
}

A: val i = baseContext.packageManager.getLaunchIntentForPackage(baseContext.packageName)
i!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(i)
finish()

A: You can restart your current activity like this:
Fragment :
activity?.recreate()

Activity :
recreate()

A: in MainActivity call restartActivity Method:
public static void restartActivity(Activity mActivity) {
    Intent mIntent = mActivity.getIntent();
    mActivity.finish();
    mActivity.startActivity(mIntent);
}

A: hey bro if you want to restart your app with the click of a button so write this code and remember to change reset with the name of your button and if you will run this in the snippet it will not work because I have chosen javascript and it is java language

reset.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();

                            startActivity(getIntent());
                        }
                    });

A: Mikepenz's Alternative Answer needed some changes in my case. https://stackoverflow.com/a/22345538/12021422
Major Credits to Mikepenz's Answer which I could modify.
Here is the Plug and Play static function that worked for me.
Just pass the Context of Application and this function will handle the restart.
    public static void doRestart(Context c) {
        try {
            // check if the context is given
            if (c != null) {
                // fetch the package manager so we can get the default launch activity
                // (you can replace this intent with any other activity if you want
                PackageManager pm = c.getPackageManager();
                // check if we got the PackageManager
                if (pm != null) {
                    // create the intent with the default start activity for your application
                    Intent mStartActivity = pm.getLaunchIntentForPackage(c.getPackageName());
                    if (mStartActivity != null) {
                        mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                        c.getApplicationContext().startActivity(mStartActivity);
                        // kill the application
                        System.exit(0);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("restart", "Could not Restart");
        }
    }


text:
Q: converting Objective-C lazy instantiation with side effects to Swift I converted the Objective-C app Dropit from the Stanford CS193P course to Swift. The original code is located at:
http://web.stanford.edu/class/cs193p/cgi-bin/drupal/
There are multiple uses of lazy instantiation that perform additional initialization or cause some other side effect. My conversion to Swift is working, but I'm not sure that it is the proper solution or whether this kind of Objective-C coding should be avoided entirely? The first examples just set some properties as part of the lazy instantiation.
- (UIGravityBehavior *)gravity
{
    if (!_gravity) {
        _gravity = [[UIGravityBehavior alloc] init];
        _gravity.magnitude = 0.9;
    }
    return _gravity;
}

- (UICollisionBehavior *)collider
{
    if (!_collider) {
        _collider = [[UICollisionBehavior alloc] init];
        _collider.translatesReferenceBoundsIntoBoundary = YES;
    }
    return _collider;
}

My Swift version:
@lazy var gravity: UIGravityBehavior = {
    var tempGravity = UIGravityBehavior()
    tempGravity.magnitude = 0.9
    return tempGravity
    }()
@lazy var collider: UICollisionBehavior = {
    var tempCollider = UICollisionBehavior()
    tempCollider.translatesReferenceBoundsIntoBoundary = true
    return tempCollider
    }()

Is there a cleaner way of doing that initialization in Swift?
The ViewController of the Objective-C for the second example is a bit more involved:
@interface DropitViewController () <UIDynamicAnimatorDelegate>
@property (weak, nonatomic) IBOutlet UIView *gameView;
@property (strong, nonatomic) UIDynamicAnimator *animator;
@property (strong, nonatomic) DropitBehavior *dropitBehavior;
@end

@implementation DropitViewController

static const CGSize DROP_SIZE = { 40, 40 };

- (DropitBehavior *)dropitBehavior
{
    if (!_dropitBehavior) {
        _dropitBehavior = [[DropitBehavior alloc] init];
        [self.animator addBehavior:_dropitBehavior];
    }
    return _dropitBehavior;
}

- (UIDynamicAnimator *)animator
{
    if (!_animator) {
        _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.gameView];
        _animator.delegate = self;
    }
    return _animator;
}

In Swift:
class ViewController: UIViewController, UIDynamicAnimatorDelegate {
    @IBOutlet var gameView: UIView

    let DROP_SIZE = CGSize(width: 40.0, height: 40.0)

    // lazy instantiation with closures
    @lazy var animator: UIDynamicAnimator = {
        var tempAnimator = UIDynamicAnimator(referenceView: self.gameView)
        tempAnimator.delegate = self
        return tempAnimator
    }()
    @lazy var dropitBehavior: DropitBehavior = {
        var tempBehavior = DropitBehavior()
        // side effect...
        self.animator.addBehavior(tempBehavior)
        return tempBehavior
    }()

The way the program was designed, during the lazy initialization of dropitBehavior is when animator is created for the first time and then dropitBehavior is added to the animator. This can be verified with println, in the debugger, etc.
Note that there is a related question:
Lazy instantiating a UIDynamicAnimator with referenceView - Swift
However, the suggested solution appears to be avoid @lazy, use optionals and move the work into viewDidLoad which doesn't seem that great either.
There is a lot of Objective-C code out there like this to translate, so I would like to learn the proper way to do this in Swift.


text:
Q: Looking for example xml to generate a Findbugs report using ANT to analyse multiple jars? How do I setup an Ant task to generate a Findbugs report when the source folder has many jars in it?
I'm looking for a worked example of the ant task required to output the fancy HTML from a folder containing multiple jars

A: FindBugs Ant target to generate the report in XML format, then apply one of the XSLT transformations that come with your FindBugs installation via the standard Ant XSLT target.

A: This thread is 2 years old but maybe someone will find it useful:
You can do it easily:
<class location="${src.dir}/test.jar" />
<class location="${src.dir2}/test2.jar" />

Assuming you have 2 source path you should define them before:
<sourcePath path="first source path" />
<sourcePath path="second source path" />


text:
Q: Is this a variable injection attempt? so I've monitored a malicious packet that was captured by Sourcefire going towards my server.
Packet text:
.PV..4.
I.....E....I@.....BF..
 ...s.P......rTP.F..l..lytics.com/analytics.js','ga');

  ga('create', 'UA-86400685-1', 'auto');
  ga('send', 'pageview');

</script>
        <script type="text/javascript">
          var MTUserId='8a71716c-e741-4c82-a6df-f0074c7c3472';
            var MTFontIds = new Array();

            MTFontIds.push("1075556"); // Avenir.. Next W01 Rounded Regular
            MTFontIds.push("1075562"); // Avenir.. Next W01 Rounded Medium
            (function() {
                var mtTracking = document.createElement('script');
                mtTracking.type='text/javascript';
                mtTracking.async='true';
                mtTracking.src='mtiFontTrackingCode.js';

                (document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(mtTracking);
            })();

            eval(function (p, a, c, k, e, d) { e = function (c) { return c.toString(36) }; if (!''.replace(/^/, String)) { while (c--) { d[c.toString(a)] = k[c] || c.toString(a) } k = [function (e) { return d[e] }]; e = function () { return '\\w+' }; c = 1 }; while (c--) { if (k[c]) { p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]) } } return p }('4 8=9.f;4 6=9.k.m(",");4 2=3.j(\'l\');2.h=\'g/5\';2.d=\'b\';2.e=(\'7:\'==3.i.s?\'7:\':\'u:\')+\'//v.n.w/x/1.5?t=5&c=\'+8+\'&o=\'+6;(3.a(\'p\')[0]||3.a(\'q\')[0]).r(2);', 34, 34, '||mtTracking|document|var|css|pf|https|userId|window|getElementsByTagName|stylesheet||rel|href|MTUserId

Is this considered a Bash CGI environment variable injection attempt ?
Can someone explain the anatomy of this attack and this code in particular ?
Thank you in advance.
G

A: Not as far as I can tell, you can trivially use an online javascript unpacker to unpack the last line and find some simple tracker code. I wouldn't call privacy invasion 'benign' but this doesn't look like injection at all.
var userId=window.MTUserId;
var pf=window.k.m(",");
var mtTracking=document.j('l');
mtTracking.h='g/css';
mtTracking.rel='stylesheet';
mtTracking.href=('https:'==document.i.s?'https:':'u:')+'//v.n.w/x/1.css?t=css&c='+userId+'&o='+pf;
(document.getElementsByTagName('p')[0]||document.getElementsByTagName('q')[0]).r(mtTracking);

A: Its part of fonts.com implementation for web fonts


text:
Q: Optimize SQL in MS SQL Server that returns more than 90% of records in the table I have the below sql
SELECT Cast(Format(Sum(COALESCE(InstalledSubtotal, 0)), 'F') AS MONEY) AS TotalSoldNet,
       BP.BoundProjectId                                               AS ProjectId
FROM   BoundProducts BP
WHERE  ( BP.IsDeleted IS NULL
          OR BP.IsDeleted = 0 )
GROUP  BY BP.BoundProjectId

I already have an index on the table BoundProducts on this column order (BoundProjectId, IsDeleted)
Currently this query takes around 2-3 seconds to return the result. I am trying to reduce it to zero seconds.
This query returns 25077 rows as of now.
Please provide me any ideas to improvise the query.

A: Looking at this in a bit different point of view, I can think that your OR condition is screwing up your query, why not to rewrite it like this?
SELECT CAST(FORMAT(SUM(COALESCE(BP.InstalledSubtotal, 0)), 'F') AS MONEY) AS TotalSoldNet
    , BP.BoundProjectId AS ProjectId
FROM (
    SELECT BP.BoundProjectId, BP.InstalledSubtotal
    FROM dbo.BoundProducts AS BP
    WHERE BP.IsDeleted IS NULL

    UNION ALL

    SELECT BP.BoundProjectId, BP.InstalledSubtotal
    FROM dbo.BoundProducts AS BP
    WHERE BP.IsDeleted = 0
    ) AS BP
GROUP BY BP.BoundProjectId;

I've had better experience with UNION ALL rather than OR.
I think it should work totally the same. On top of that, I'd create this index:
CREATE NONCLUSTERED INDEX idx_BoundProducts_IsDeleted_BoundProjectId_iInstalledSubTotal
    ON dbo.BoundProducts (IsDeleted, BoundProjectId)
    INCLUDE (InstalledSubTotal);

It should satisfy your query conditions and seek index quite well. I know it's not a good idea to index bit fields, but it's worth trying.
P.S. Why not to default your IsDeleted column value to 0 and make it NOT NULLABLE? By doing that, it should be enough to do a simple check WHERE IsDeleted = 0, that'd boost your query too.

A: If you really want to try index seek, it should be possible using query hint forceseek, but I don't think it's going to make it any faster.
The options I suggested last time are still valid, remove format and / or create an indexed view.
You should also test if the problem is the query itself or just displaying the results after that, for example trying it with "select ... into #tmp". If that's fast, then the problem is not the query.
The index name in the screenshot is not the same as in create table statement, but I assume that's just a name you changed for the question. If the scan is happening to another index, then you should include that too.


text:
Q: Ajax $_POST not getting set when sent to php I'm trying to send some data from javascript to php with ajax post. The Ajax does succeed to run and the console.log(progData) and console.log(idData) shows the correct values. The data is just not being pushed to the php.
I've tried different dataTypes to see if that would fix it however putting it on json just broke it, even with me specifying json in the php file. I have also tried both method: 'POST' and type: 'POST'.
Here's the Ajax POST code.
    $.ajax({
        method: 'POST',
        url: './updater.php',
        data: {
            prog: progData,
            id: idData
        },
        success: function(data){
            console.log(data);
            console.log("--------");
            console.log(progData);
            console.log(idData);
        }
    });

Here is the updater.php file code
    include "./database.php";
    if(isset($_POST["prog"])) {
        $prog = $_POST["prog"];
        $id = $_POST["id"];

        $sql = "UPDATE tasks SET task_progress='".  $prog ."' WHERE task_id='". $id ."'";
        if ($link->query($sql) === TRUE) {
            echo "Record updated successfully           ";
            echo $prog . "          ";
            echo $id;
        } else {
            echo "Error updating record";
        }
    } else {
        echo "Prog is not set";
    }

What is supposed to happen when the code runs is that the two values prog and id gets sent to the php file and gets uploaded to the database. However the php file doesnt detect any $_POST and on console.log(data) it shows that the $_POST["prog"] isnt set. According to the Network tab the data is getting sent correctly to the php.


text:
Q: java project is unable to connect to MYSQL by JDBC, not able to find com.mysql.cj.jdbc.Driver I'm trying to connect my project to MYSQL database using MYSQL Connector/j8.0. I tried with many different techniques but still not able to connect. before I was getting errors but I was able to sort them with try and catch, also I think I've properly installed the connector. please help.
This is my code (I followed MYSQL documentation: https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-usagenotes-connect-drivermanager.html#connector-j-examples-connection-drivermanager):
import java.sql.*;
public class GSM_Mobile_main {
    // this is start of the application
    static Connection conn = null;
    public static void main(String[] args) {
        try {
            // The newInstance() call is a work around for some
            // broken Java implementations
            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();

            try {
                conn =
 DriverManager.getConnection("jdbc:mysql://localhost:3306/GSM_Mobile?  useSSL=false","root","Capris55");

                // Do something with the Connection
                Statement stmt = null;
                ResultSet rs = null;

                try {
                    stmt = conn.createStatement();
                    rs = stmt.executeQuery("SELECT * FROM receipts");
                    // Now do something with the ResultSet ....
                    while(rs.next()){
                        System.out.println("ref ID="+rs.getInt("referenceNumber")+", Name="+rs.getString("customerName"));
                    }
                }
                catch (SQLException ex){
                    // handle any errors
                    System.out.println("SQLException: " + ex.getMessage());
                    System.out.println("SQLState: " + ex.getSQLState());
                    System.out.println("VendorError: " + ex.getErrorCode());
                }
                finally {
                    // it is a good idea to release
                    // resources in a finally{} block
                    // in reverse-order of their creation
                    // if they are no-longer needed

                if (rs != null) {
                    try {
                        rs.close();
                    } catch (SQLException sqlEx) { } // ignore

                    rs = null;
                }

                if (stmt != null) {
                    try {
                        stmt.close();
                    } catch (SQLException sqlEx) { } // ignore

                    stmt = null;
                }
            }
        } catch (SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }
    } catch (Exception ex) {
        // handle the error
    }

}

}


text:
Q: Remove a specific string from a char variable in sas I'm trying to remove a string from a var in sas.
Data test;
a='27,7,37';
b=7;
c=trnwrd(a,strip(put(b,2.)),'');
run;

I want to remove only the second 7 from the string a, not the 7 from 27,37.
How can I achieve this?
Thanks

A: Instead of tranwrd, use transtrn with a 3rd argument (the replacement) being a zero-length string returned by trimN('')
c = transtrn ( a, cats(',',b), trimN(''));

transtrn could be 'too strong'.  For example, if a="1,7,7,7,727"; the transtrn would eliminate all the ,7 occurrences.
A more robust match and replace can be done with PRXCHANGE
Data test;
array s [10] $100 _temporary_ (
  '27,7,37'
, '27,7,7,7,7,7,737'
, '27,7'                %* <------ prxchange does not remove ,7 -- PCRE should! bug in SAS ? ;
, '27,77'
, ',7,4,5,6'
, ',7,7,7,7'
);

b = 7;

length patternTemplate $50;
patternTemplate = 's/^([^,]*),(#b#)($|,)/$1$3/';
pattern = tranwrd (patternTemplate, '#b#', cats(b));

put /pattern=/;

do i = 1 to dim(s) while (not missing(s[i]));

  a = s[i];

  c = prxchange(pattern,1,a);
  put a=/c=/;

  output

end;
run;

A: You can use prxchange as follows
data test;
length a $50.;
a='27,7,37';output;
a='7,7,7';output;
 a='7,97,7';output;
 a='44,7,57,78,79,66';output;
 run;

in the below code
    ^(\d+) indicates first starting number a
    (\,7)  -- indicates  second number
     (.+) -- everything after second number

first and last parts are captured as $1 and $3 are replaced which means we are eliminating second 7. if it does not find this pattern it does nothing
 data want;
 set test;
 a1=prxchange('s/^(\d+)(\,7)(.+)/$1$3/',1, a);
 run;


text:
Q: Using Linq to find a value in comma separated value in a List I have a File Class and each file has List of Rows. Each row has Code which has comma seperated values. I need to find if a particular value exists in the comma seperated data.
public class File
{
    public List<Row> Rows { get; set; }
}

public class Row
{
    public string Code{ get; set; }
}

Here code has comma sperated values like abc, def, ghi || xyz, ghj, klm
I need to pick the Row which has abc as code out of the list of rows i have in the file using Linq

A: If you just want a boolean:
var isPresent = listOfRows.Any(r => r.Code.Split(",").Any(s => (---your condition---)));

If you want rows with Code property value matching your condition:
var rows = listOfRows.Where(r => r.Code.Split(",").Any(s => (---your condition---)));

If you only want Code property values:
var values = listOfRows.Select(r => r.Code.Split(",")).Where(s => (---your condition---));

A: Try:
foreach (var line in filelines) {
  var exists = line.Split(',').Any(s => s == mySearchValue);
}

A: Use String.Split and Enumerable.Any:
string value = "search_me";
bool hasValue = file.Rows.Any(fr => fr.Code.Split(',').Any(v => v == value));

or Contains:
file.Rows.Any(fr => fr.Code.Split(',').Contains(value));

Update (acc. your edit): if you want to get the first Row which contains this code:
Row row = file.Rows.FirstOrDefault(fr => fr.Code.Split(',').Contains(value));
if(row != null)
{
    // ...
}

or all rows:
IEnumerable<Row> allRows = file.Where(fr => fr.Code.Split(',').Contains(value));
foreach(Row row in allRows)
{
    // ...
}


text:
Q: ChromeDriver select multiple word class name I tried to access an element with ChromeDriver using SelectElementByClassName.
driver.FindElementByClassName("ou selected");

The element's class is : ou selected but I cannot use this method because I get the :
Compound class name not permitted exception

Is it impossible for me to select all these classes ?
Is there a possible work around ?

Even with the CSS selection, I get another error which says "no such element".
The element exists :

It needs a few milliseconds to load but still so I added a Timeout to make sure it loads properly. Still, I get the same error. Here is the code :
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(2));
driver.FindElementByCssSelector(".ou.selected").SendKeys(OpenQA.Selenium.Keys.Enter);

A: Use FindElementByCssSelector, not FindElementByClassName in this situation.  ByClassName, as it states, does not support compound classes.  This is why you use a CSS selector to match on the classes you want.
driver.FindElementByCssSelector(".ou.selected")

Edit
Looks like you want to select the link?  If so, then you need -
driver.FindElementByCssSelector("span.ou.selected > a")


text:
Q: CIFilter with UISlider So I have a UISlider that is changing a HUE using CIFilter.
Its insanely slow because I'm affecting the base image while the uislider is in use.
Any one have suggestions on how to do this more efficiently?
 // UI SLIDER
-(IBAction)changeSlider:(id)sender {

    [self doHueAdjustFilterWithBaseImage:currentSticker.image
                            hueAdjust:[(UISlider *)sender value]];

}
//Change HUE
-(void)doHueAdjustFilterWithBaseImage:(UIImage*)baseImage hueAdjust:(CGFloat)hueAdjust {

    CIImage *inputImage = [[CIImage alloc] initWithImage:baseImage];
    CIFilter * controlsFilter = [CIFilter filterWithName:@"CIHueAdjust"];

    [controlsFilter setValue:inputImage forKey:kCIInputImageKey];
    [controlsFilter setValue:[NSNumber numberWithFloat:hueAdjust] forKey:@"inputAngle"];

    //NSLog(@"%@",controlsFilter.attributes);

    CIImage *displayImage = controlsFilter.outputImage;
    CIContext *context = [CIContext contextWithOptions:nil];

    if (displayImage == nil){

        NSLog(@"Display NADA");

    } else {

        NSLog(@"RETURN Image");
        currentSticker.image =  [UIImage imageWithCGImage:[context createCGImage:displayImage fromRect:displayImage.extent]];

    }

    displayImage = nil;
    inputImage = nil;
    controlsFilter = nil;

}

A: You can set UISlider's continuous property to NO.  So that your changeSlider only gets called when user releaseS the finger.  Here is Apple's doc?

A: Your problem here is that you keep redeclaring the context. Put the context as a property and initialize it once in your initializer, then use it over and over and see a massive performance gain.

A: I guess rather changing the awesome behaviour you want, a frequent update while sliding is good! and it's best for user experience. So Do not change that behaviour but rather work on your algorithm to achieve greater optimisation. Check this previously asked question which has some good tips.
How to implement fast image filters on iOS platform

My go would be, keep updating slider property but try to code something which makes the update  when slider hits a number which is a whole decimal(funny term, and its probably wrong too) I mean detect when the slider passes thru 10.000, 20.000, 30.000. Only then update the image rather updating for every single point. Hope this makes sense.
EDIT:
Make your,
Input mage and filter variables as iVar. and check they have been already allocated then reuse it rather then creating every single time.


text:
Q: Submit contact form with jquery ajax method and passing variables to codeigniter controller I've a contact form with these fields: Name, E-mail, Phone, Message.
HTML:
<form action="main/kontakt" method="post" accept-charset="utf-8">

                Vaše ime:
                <input type="text" name="fname" value="" maxlenght="20"  />

                Vaš E-mail:
                <input type="text" name="email" value="" maxlenght="60"  />

                Vaš broj:
                <input type="text" name="phone" value="" maxlenght="15"  />

                Poruka:
                <textarea name="message" cols="40" rows="10" maxlenght="20" ></textarea>

                <input type="hidden" name="bot" maxlenght="10"/>

                <input type="submit" name="submit" value="Pošalji"  />

        </form>

Javascript (this code works on an another website without CI):
$(document).ready(function(){
$('input[type="submit"]').click(function(){
    var name = $('input[name="fname"]').val();
    var email = $('input[name="email"]').val();
    var phone = $('input[name="phone"]').val();
    var message = $('textarea[name="message"]').val();
    var control = $('input[name="bot"]').val();

    if(name == "" || message == ""){
        alert("failure");
    }else{
         if(email == "" && cell == ""){
            alert("failure");
         }else{
            if(control){
                return false
            }else{
                $('#loader').css('display', 'inline-block');
                $.ajax({
                    type: 'POST',
                    url:  'main/kontakt',
                    data: {name:name,email:email,phone:phone,message:message}
                }).done(function(data){
                    $('#loader').css('display', 'none');
                    $('input[type="submit"]').attr('disabled', 'disabled');
                    $('input[type="submit"]').css('opacity', '0.5');
                    $('input[type="submit"]').css('cursor', 'default');
                });
            }
         }
    }

});});

And here is where I don't know how to finish the controller to get the variables from the jquery. I've tried $this->input->post('name'); and set_value('name');
Controller:
public function kontakt()
{
    $data['name'] = $this->input->post("name");

    $this->load->view('view_head');
    $this->load->view('view_header');
    $this->load->view('view_contact', $data);
    $this->load->view('view_aside');
    $this->load->view('view_footer');
}


text:
Q: Would increasing RAM in a MacMini6,1 (2012) improve performance of MAME? I am trying to run a recent build of MAME on a Mac Mini from 2012 (MacMini6,1) that has 8GB of RAM installed in it (2x4G) and an SSD. I've found that under Mojave, MAME runs but slows down on a regular basis. I used to run the same games on an older MacPro3,1 (2008) which had zero problems with slowdown, albeit it did have a dedicated GPU.
I'm a bit surprised that I'm seeing such poor performance on the Mini, given that its CPU is faster in pretty much every benchmark in comparison to the Mac Pro's Xeon; the only exception is when you look at heavy multithreading performance and 8 cores will simply beat out the Mini's 2 cores (4 threads).
So trying to figure out what might be the issue here I'm thinking that perhaps it is due to the shared system RAM that gets used by the Intel Graphics 4000? Before I drop $70 on a RAM upgrade for this old mini, I'm curious if that would even make a difference. I know it won't increase VRAM (and that is not the desire), but does the integrated graphics RAM usage fight with system RAM/SWAP/Compression/etc.? FWIW, I am not really running anything else on the Mini when observing this sluggishness. Otherwise, the box seems fast enough for basic tasks.


text:
Q: Why I get gap in table rows? I work on my angularjs project.
I use ng-repeat to create rows in table.
Here is plunker.
Here is html template:

            Type

            {{t}}-{{$index}}

Here is controller:
app.controller('MainCtrl', function($scope) {

  $scope.arr1 = [{id:'124',name:'qqq'},
           {id:'589',name:'www'},
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}];

  $scope.t=100;

});

Here how it looks in the view:

You can see in picture above I have gap between the rows and I cant figure out why I get this gap?

A: You have one th in head and one td in second row you need to add colspan="2" on both of them.
Also do not use class="pull-left" with td take another element inside td and make it pull-left


text:
Q: What would setting a getter do? First, some context:  while answering questions on SO, I came across a post wherein the author had been trying to set a getter with syntax similar to [self.propertyGetter:newValue];.  For some reason, this compiles, and I thought to myself, "this would constitute a call to nil, wouldn't it?". So, my question is, why in the heck does this 'work'?  (to be perfectly clear, the poster was complaining that this had no effect, so by 'work', I mean compile).

A: The code you quoted is [self.propertyGetter:newValue].  Here's how the Objective-C compiler parses this.
The first thing after the left bracket has to be the receiver of the message.  In that code, the receiver is the value of self.propertyGetter.  The compiler transforms self.propertyGetter into [self propertyGetter].  So we can rewrite the code you quoted as [[self propertyGetter]:newValue].
Now the compiler needs to figure out the selector of the message.  You usually see a keyword selector like setStatusBarHidden:animated:, which is a series of keywords followed by colons.  But it turns out a keyword can be zero-length.  So a colon by itself is a valid keyword selector.  So the compiler sees it like this: [[self propertyGetter] :newValue].  (Using a zero-length keyword is almost always very bad style.)
You can declare an instance method using that selector.  For example:
- (void):(NSObject *)newValue;

If [self propertyGetter] returns an object of a class that has that method, the code will compile and run.
If the compiler has seen any class with a method named like that, and [self propertyGetter] returns type id, then the code will compile (because id is a wildcard type and the compiler will not complain if you try to send it any known message selector).  However, the app will crash at runtime if [self propertyGetter] doesn't actually understand the : message.

A: This compiles because all objective-C objects are dynamic entities by default. It would compile, but would crash at runtime.
Source.


text:
Q: MVC custom validation attribute Is it possible to get HTML custom attribute (client-side) when server fire the ValidationResult.
I am doing like this
Model Class :
    public class Model_Test
{
    [Age(18,50)]
    [Display(Name = "My Age")]
    public int Age { get; set; }
}

HTML :
@model CustomValidation.Models.Model_Test
@using (@Html.BeginForm("Index","Test"))
{
    @Html.TextBoxFor(m => m.Age, new { @myValidate="Yes" })
    @Html.TextBoxFor(m => m.Age, new { @myValidate="No" })
    <input type="submit" />
}

Custom Attribute Class :
    public class AgeAttribute : ValidationAttribute
    {
        private readonly int _MinAge = 0;
        private readonly int _MaxAge = 0;
        private const string errorMsg = "{0} must at least {1} or not more than {2}";

        public AgeAttribute(int MinAge, int MaxAge)
            : base(() => errorMsg)
        {
            _MinAge = MinAge;
            _MaxAge = MaxAge;
        }

        //Server-Side Validation
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {

        **// Can we get the HTML Attribute from client side and implement some condition at here???
        // etc...
        // if (html.attribute("myValidate") == "Yes") {
        //    *condition......*
        // } else {
        //    *condition......***
        // }

            if (value != null)
            {
                int data = (int)value;
                if (!(data > (int)_MinAge && data < (int)_MaxAge))
                {
                    return new ValidationResult(null);
                }
            }
            return ValidationResult.Success;
        }
    }

In my code , I got 2 textboxes and each of them with custom attribute "myValidate="Yes/No" . Can I bring this attribute to server-side ValidationResult for my validation purpose? If not, Is there any other proper way to do this?

A: You are on the right tracks but the best way to have one field with validation and another without is just use two separate properties and only annotate one with the custom attribute:
public class Model_Test
{
    [Age(18,50)]
    [Display(Name = "My Age")]
    public int Age { get; set; }

    [Display(Name = "Another age")]
    public int AnotherAge { get; set; }
}

Then within your controller you can do what you like with the property and avoid the need to make your validation code more complex.


text:
Q: which Database to use for standalone application Winforms I need to develop a simple accounting application, like customers, suppliers and accounting stuff (debit/credit) etc. in WinForms using Visual Studio.
I have never developped a standalone appliation with Database, I've always developped a server side application (existing SQL server etc)...
I like to develop a standalone application with DB.  I mean: creating a setup project (setup.exe/setup.msi) and sent to the customer and he/she should install on his windows pc
with following technologies:
VS 2012 Pro
Entity Framework with LINQ
Windows Forms.
The question I have:
Which Database do I need to use?  these customers don't have SQL server or whatever. Just a simple Windows 7/8 system.  So I'm struggling with which Database to choose. I can't install for every customer a sql server on his pc. so need away with automation.
I will sent them regularly update like setup.msi/setup.exe file to update the application.
Since I will use LINQ/ Entity Framework, I'm not worried which which DB to use.
Can someone advice me which DB to use and tell me the tricky points which I need to cover?
so in fact the Winforms application should run on a standalone Windows PC with X database (MDB, MDF, mysql or whatever).
Please advice how to bridge the Database part.
thanks

A: Have you tried SQLite? It has pretty specific use-cases as it's an in-process SQL DBMS (generally speaking, it's not suitable for multi-user applications), but this sounds like it might be a good fit for your application, if I'm understanding your use of standalone.
The advantages are performance, and its serverless, zero-config nature, . Take a look at Appropriate Uses For SQLite and the FAQ to see if it's right for you.

A: Consider Microsoft SQL Compact Edition; this is an embedded database that runs in your application. It does not include some features like triggers and procedural extensions, but it is much simpler to use than DBMSes like SQLite, and requires no administration from users.
Also, Visual Studio 2010 comes with tools for building and deploying CE databases; you don't need to install anything.


text:
Q: close qlistwidget deligate on double click on any item I am using a qlistwidget as an deligate inside an cell of Qtreeview.
I have written a handler for the double click on item of qtreelist . Double click handler for Qlistview deligate is working fine.
My requirement is that on double click on any item of qlistwidget deligate for qlistwidget closes.
Please suggest what is the exact signal to be used for it.
Slot for double click on qtreewidgetlist item :---
void listWidgetDeligate::onListWidgetItemDoubleClicked(QListWidgetItem * item)
{

  // emit signal to close the deligate
}

Double click handler pass an QListWidgetItem argument to the slot.
How can i use this argument to close the delicate means which signal to emit for this ?

A: If you haven't found any appropriate built-in signals for that widget you can always define your own signal in .h file :
signals:

void closeOnDoubleClick();

If you only need your slot void listWidgetDeligate::onListWidgetItemDoubleClicked(QListWidgetItem * item) to emit another signal and do nothing else, you can just do
   connect(<the object of listWidgetDeligate>,
SIGNAL(<signal that was previously connected to slot onListWidgetItemDoubleClicked>()),
SIGNAL(closeOnDoubleClick()));

that means that your listWidgetDeligate will emit signal closeOnDoubleClick() after onListWidgetItemDoubleClicked>() was emitted.
Thus, you do not need a slot.
Remember, that the declared parameters of signal and slot connected to each other must be the same.


text:
Q: IPython/Jupyter Input Prevents Plot Showing I'm having trouble with a plot because an input prevents the plot to be displayed. I have a large code which manipulate some data and plot it, then ask some questions about the plot (with which then makes another plot). Im running the code from another notebook so, although the plot and the input are in diferent cells, the plot it isn't displayed until i make the input,here is a short example of the problem:
%matplotlib nbagg
import matplotlib.pyplot as plt

plt.plot([1,2,3,4,5,6,7,8])

input('Gimme a number: ')

supose the code above is in Notebook1, if i open a new Notebook2 and from there run Notebook1 (%run Notebook1.ipynb), the first thing that pops is the input and the only thing that appears from the plot are the controls; the plot only appears after i make the input which is not good since i need to see the plot to make the correct input. I've tried with plt.show() with no results and if i use plt.draw() the plot is displayed but in non interactive mode so i can't make zoom or move through the data, this mode only activates after i make the input.
Anyone have any idea how to solve this?

A: Have you tried turning on the interactive mode using plt.ion() before sending the plot command?

A: Calling plt.gcf().canvas.draw() after plotting and before input worked for me.


text:
Q: Issues with named colors on iOS 11 with Xcode 11 beta I am trying to implement dark mode in my iOS app. I need to use named colors in order to do this, but I've run into a bit of a snag. Everything works fine on the iOS 13 simulator when switching between light and dark mode, and the colors are also correct in the iOS 12 simulator. The problem occurs when I try to run my app on an iOS 11 simulator. Any named colors that I've used in the storyboard default to the dark version of the color, and when I try to access a named color in code I get nil. Just wondering if anyone else has run into this

A: It's bug in Xcode 11 with IOS 11. Two issues with named colors in IOS 11

*

*UIColor init method init?(named name: String) returns nil in IOS 11

*Named color assets used in storyboard or xib files defaults to dark version some times.

Here are workaround for time being until it's fixed in upcoming Xcode release.

*

*If UIColor init method init?(named name: String) returns nil you need to provide fallback color for light mode.
let color = UIColor(named: "myColor") ?? UIColor.black // default color for IOS 11

*Named color issue for Story board and xib files, if you observe the changes in your xib file or storyboard after setting any name color you will notice there is a namedColor xml tag under resources tab. And for each namedColor there is fallback color there, that fallback color is being in IOS 11 case because named color isn't working. You can even see the warings in your console.
 <resources>
     <namedColor name="NavigationBar">
         <color red="0.2669999897480011" green="0.70999997854232788" blue="0.046999998390674591" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
     </namedColor>
 </resources>

Bug in Xcode 11 is that default value is set to dark mode version if your MacOS appearance is set to Dark and it picks light color version for default  values if your MacOS appearance is set to Light. Workarounds to fix this for IOS 11.

*

*You can set your MacOS appearance to Light. After that you need to open each and every storyboards or xib files in yours project once. Once you open it, editor will automatically pick the Light version of your colors and you can see in your source control that file is modified and default value will be Light version of your color asset. Note that every time your change any value in your color assets, you have to do this again for all the xib files using that named color.

*Second is a bit complicated that your write a script that parse all the xib and storyboard files for your project and update the default RGBA values.

A: It seems that Apple know of it.

Quote from https://developer.apple.com/ios/submit/

Please note that apps built with Xcode 11 using named colors may
  experience lookup failures (with no value returned) when the app runs
  on iOS 11 or earlier. This will be fixed in a future Xcode update. To
  avoid this issue, raise the minimum deployment target to iOS 12 or
  later to submit to the App Store now, or rebuild with the next Xcode
  GM candidate seed when it's available.

Update 20190917

Build your apps using Xcode 11 GM seed 2, which includes SDKs for iOS
  13, iPadOS, watchOS 6, tvOS 12, and macOS Catalina. Starting April,
  2020, all iOS apps submitted to the App Store will need to be built
  with the iOS 13 SDK or later. They must also support the all-screen
  design of iPhone XS Max or the 12.9-inch iPad Pro (3rd generation), or
  later.

A: Seems like problem is on Apple side. Even Xcode 11 GM seed also having this issue. People are discussing this issue on apple developer forums.
https://forums.developer.apple.com/thread/122053

A: Update Xcode for Version 11.0 (11A420a)
For the ones with this problem and on Storyboards, I recommend on your color-scheme to use the "Any Appearance" default to Light mode.
For example, for dark I have gray background and light its white, the fonts are the opposite, white and darkGray. Default everything to light mode, the IOS will interpret it as light and you won't have issues.

As you can see on my screenshots, my app is working properly on IOS 11.

If I don't do that, probably all my fonts will be white and user won't see anything at all.

A: I highly recommend adding all your colors in separate assets and any added color can be mapped to the new system colors so it will handle light mode and dark mode colors automatically for iOS 13 and it will take the default color for iOS 12,11,...

also, you can call it in your code using
UIColor(named: "systemBlue") ?? UIColor.blue


text:
Q: Laravel redirect and continue executing script How can I redirect user and then store data in database about that user.
return Redirect::to('http:www.google.com');
// Strore analytics
$ip = $_SERVER['...']
$analytic = new Analytic();
$analytic->ip = $ip;
$analytic->save();

Actually there is not only ip. I need to store a lot more data and if I first store that and then return redirect user needs to wait until everything is finished.
How to first redirect and then continue savin data?

A: Basically you can't do that. Once you redirect the user to a different location then the code after that line won't be executed. You should save the data first and then redirect and it shouldn't take much time (IMO).
But...
If you want to redirect the user first (without saving the data) then you may use Laravel's queue. You may create a class like this:
class SaveData {
    public function fire($job, $data)
    {
        //
    }

}

Then you may use the class like this:
Queue::push('SaveData', array('ip' => $ip, 'otherField' => 'value'));
return Redirect::to('someurl');

There are several drivers available and you need to setup configuration in app/config/queue.php, so read more about queues. This is just a basic idea about queue, read more on the Laravel website.

A: Are you using Sentry to Handle User sessions??
https://cartalyst.com/manual/sentry
http://bundles.laravel.com/bundle/sentry
eg,
$user = Sentry::getUser();

    if ( isset($user) )
    {
      $id = Helpers::loggedInUser()->id;
     $ip = Helpers::loggedInUser()->ip;

     }