text:
Q: templated comparison function in c++ I have the following compare function that I pass to the std::sort algorithm to sort a vector of objects:
template <typename PointT>
bool myCompareLines (A<PointT>::model_struct model_a, A<PointT>::model_struct model_b) {
    return (/* some comparison code*/);
}

The compare function is declared outside the class and I am calling it like this:
template <typename PointT>
class B {
    [...]
    std::sort(lines.begin().lines.end(),::myCompareLines);
    [...]
}

When I compile I get the error: template declaration of 'bool myCompareLines'
Inside class A I declare class B as a friend class so that class B can
access the the private type model_struct.  What am I missing?

A: Though hideous, is this what you're looking for? Note: Compiles does not equate to good. Even if this works for you I would suggest an alternate way of declaring your hierarchy.
template<class PointT>
class A
{
public:
    A() {};

    struct model_stuct
    {
        // need something to use in comparison, so i just threw this in.
        int value;
    };
};

// comparitor
template<class PointT>
bool compareLines(
    const typename A<PointT>::model_stuct& left,
    const typename A<PointT>::model_stuct& right)
{
    return left.value < right.value;
}

template<class PointT>
class B
{
public:
    B() : lines() {};

    void sort()
    {
        std::sort(lines.begin(), lines.end(), compareLines<PointT>);
    }

    std::vector<typename A<PointT>::model_stuct> lines;
};

// main entrypoint
int main(int argc, char *argv[])
{
    // this does nothing, but demonstrate that it can compile and
    //  sort() doesn't puke.
    B<int> bInt;
    bInt.sort();
    return 0;
}

A: Shouldn't you just do:
template <typename PointT>
class B {
    [...]
    std::sort(lines.begin(), lines.end(), ::myCompareLines<PointT>);
    [...]
}

A: I was missing the typename keyword in my CompareLines signature.
This fixes it:
bool myCompareLines (typename A<PointT>::model_struct model_a, typename B<PointT>::model_struct model_b)

A: Compiler cannot deduce template param PointT from inner class A<PointT>::model_struct.
It cannot because many specialization of A<PointT> can have identical model_struct - like:
template <class PointT>
class A {
public:
  typedef int model_struct;
};

with this example:
   int a;
   bool res = compareLines(a,a);

Define model_struct as top level template.


text:
Q: Paired t-test for repeated measurements, but with 2 missing samples. I am doing a gene expression analysis on blood samples collected from the same 8 goats. My sampling points are before LPS-treatment (0h), and 1h, 2h, 5h and 24h after treatment. I want to compare the mean expression of each post-treatment to the before-treatment values. Due to problems in RNA-extraction, one sample is missing at 1h and one sample is missing at 2h. Is it possible to do a paired t-test with unequal sample size? E.g n=8 at 0h and n=7 at 1h/2h?
I'm using log2 transformed data for the statistical analysis. (We are have decided not to correct for multiple comparisons, but we use a fold-change limit instead)

A: You can not do a t-test for paired data with unequal sample-sizes but you can omit cases with missing data for the analysis of these times: Do a n=8 comparison for 5h an 24 h and an n=7 comparison for n=1h an n=2h.
Have you considered repeated-measurements-ANOVA instead of all those t-tests? With n so small and 4 different tests, alpha Inflation is an issue to be considered.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does my UIView got different position on different iPhones? Why does my UIView got different position on different iPhone screen sizes ? I guess it's because of autoresizingMask but how could I get a frame of a view after applying autoresizingMask, to create some universal logic? or whats the best practice to handle this ?
here is the code :
private func setup() {

        positionView = CircularProjectPositionControl(frame: self.bounds)
        positionView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        positionView.outerCircleWidth = outerCircleWidth

        assetsView = CircularProjectAssetsControl(frame: self.bounds)
        assetsView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        assetsView.backgroundColor = UIColor.clearColor()
        assetsView.imageWidth = outerCircleWidth

        let size = CGSize(width:40, height:40)
        let width = floor(CGRectGetMidX(self.bounds) - size.width/2.0)
        let height = floor(CGRectGetMidY(self.bounds) - size.width/2.0)
        collaboratorView = AvatarView(frame: CGRect(x: width, y: height, width: size.width, height: size.height))
        collaboratorView.autoresizingMask = [.FlexibleBottomMargin, .FlexibleLeftMargin, .FlexibleRightMargin]

        self.addSubview(assetsView)
        self.addSubview(positionView)
        self.addSubview(collaboratorView)
    }

iPhone 6s:

iPhone 5:

A: Try adding .CenterX & .CenterY contraints to center each of the subviews:
NSLayoutConstraint(item: view1, attribute: .CenterX, relatedBy: .Equal, toItem: view2, attribute: .CenterX, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: view1, attribute: .CenterY, relatedBy: .Equal, toItem: view2, attribute: .CenterY, multiplier: 1, constant: 0).active = true

A: Looks like you only set the relative position with the self.view. If you want three circles have some remain same relative position with each other, you should also set the constraint between them.


text:
Q: Adding a custom font to a paragraph in iTextSharp My goal is to add a custom font to a paragraph using iTextSharp however it does not seem to work, I have tried with both .ttf and .otf font types however neither worked.
My code:
var pgSize = new iTextSharp.text.Rectangle(378, 576);
Document document = new Document(pgSize);

BaseFont customfont = BaseFont.CreateFont("Azonix.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
iTextSharp.text.Font azonix = new iTextSharp.text.Font(customfont, 12);

PdfWriter.GetInstance(document, new FileStream("someFile.pdf", FileMode.Create));

document.Open();

Paragraph p = new Paragraph("example paragraph");
p.Alignment = Element.ALIGN_CENTER;
p.Font = azonix;

document.Add(p);
document.Close();

The output of the PDF file uses the default font instead of the azonix font.
The font is also inside of the same directory as the executable as shown in the picture:

Other information:

*

*Windows 10 Pro

*.NET Framework 4.7.2

*Windows Forms Application

A: You first add text to the paragraph and,  thereafter, set the font:
Paragraph p = new Paragraph("example paragraph");
...
p.Font = azonix;

To have the font applied to the text, though, set the font together with the text:
Paragraph p = new Paragraph("example paragraph", azonix);

or before it:
Paragraph p = new Paragraph();
...
p.Font = azonix;
p.Add("example paragraph");


text:
Q: Yau's conjecture on nodal sets for manifolds with boundary I've just read a review paper about Yau's conjecture on nodal sets of the eigenfunctions for the Laplace operator on manifolds.
Briefly, if $\phi_\lambda$, $\lambda$ are an eigenpair for the Laplace-Beltrami operator on a manifold $M$, i.e.
$$-\Delta\phi_\lambda = \lambda\phi,$$
then as $\lambda \to \infty$, there are constants $c$, $C$ such that
$$c\sqrt\lambda \le \text{area}(\{\phi_\lambda = 0\}) \le C\sqrt\lambda.$$
I've seen several results for manifolds without boundary of varying degrees of regularity. For example, Donnelly and Feffermann proved that Yau's conjecture is true for real analytic manifolds, but as I understand, the conjecture hasn't been proven yet for $C^\infty$ manifolds.
Are there extensions of the Yau conjecture to manifolds with boundary? Most of the work I've found (mainly other papers by Malinnikova and Logunov) considers only manifolds without boundary.

A: Yau's conjecture was proved for the real analytic manifolds by Donelly and Fefferman, first for manifolds without boundary, then for manifolds with boundary in the paper Nodal Sets of Eigenfunctions: Riemannian Manifolds With Boundary, Analysis, et Cetera (1990), 251--262. The main result there is stated below.

Theorem 1.2 On any real analytic Riemannian manifold  $M$ with boundary, the $n-1$ dimensional Hausdorff measure, $\mathcal{H}^{n-1}(N)$, of the nodal set $N$ of eigenfunction $f$, $\Delta f = -\lambda f$, (with Dirichlet or Neumann conditions on the boundary of $M$) satisfies $$c_1\sqrt{\lambda}\leq \mathcal{H}^{n-1}(N) \leq c_2 \sqrt{\lambda},$$
  for some positive constants $c_1$, $c_2$.

There are other papers that handle more general boundary conditions, many of which reference the above paper.


text:
Q: how to fetch data from mock Api in ionic 2 I have a mock API having thousand of records. I have implemented infinite scroll. I want fetch 20 records from API and display only 10 of that.
I'm new to ionic 2 please suggest some simple code.
I'm using services. The same example which is given in angular tutorials
https://angular.io/docs/ts/latest/tutorial/toh-pt6.html
following is the code
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {HeroService} from '../home/services/hero.service';
import {InMemoryDataService} from '../home/services/in-memory-data.service';
import {Hero} from '../home/services/hero'

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  heroes:Hero[];
  items=['Thor','Batman','Superman','Ironman','Spiderman']

  getHeroes()
  {
    this.heroservice.getHeroes().then(heroes=>this.heroes=heroes);
  }

i:number;
  constructor(public heroservice:HeroService) {

    for (let i = 0; i < 10; i++) {
      this.items.push( this.items[i] );

    }
    this.getHeroes();
  }

  doInfinite(infiniteScroll) {
    console.log('Begin async operation');

    setTimeout(() => {
      for (let i = 0; i < 100; i++) {
        this.items.push( this.heroes[i].name );
      }
     console.log('Async operation has ended');
      infiniteScroll.complete();
    }, 500);
  }

}

A: Refer to this blog post by Josh Morony


text:
Q: Why does PHP cURL POST request shows as GET? I'm Trying to send POST request to an api to create user using PHP cURL. Here is the code sample
<?php
$email="jas@example.com";
$name = "jas";
$data = array(
"user" => array("email"=>$email,"name"=>$name)
);
//encoding to json format
$jsondata= json_encode($data);

$credentials = "username:pass";
$header[] = "Content-Type: application/json";
$header[] =  "Authorization: Basic " . base64_encode($credentials);
$connection = curl_init();
curl_setopt($connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($connection, CURLOPT_HTTPHEADER, $header);
curl_setopt($connection, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($connection, CURLOPT_HEADER, false);

//POSTS
curl_setopt($connection, CURLOPT_POST, 1);
curl_setopt($connection, CURLOPT_POSTFIELDS, $jsondata);

curl_setopt($connection, CURLOPT_VERBOSE, 1);

curl_setopt($connection, CURLOPT_URL, "http://domain.freshdesk.com/contacts.json");
$response = curl_exec($connection);
?>

It looks like it is not sending post actually even though i have set
curl_setopt($connection, CURLOPT_POST, 1);
curl_setopt($connection, CURLOPT_POSTFIELDS, $jsondata);

I see a GET request in firebug net tab.

Is it really a post request? Because the indented operation(create new user) are not happening instead it is listing all user as it is a GET Request.

A: That GET request is simply your request to PHP script which then executes POST request.
You can't see requests done with cURL in your developer console because they were sent from server, not client.

A: The error is in the logic of using firebug to debug this request.
You send a GET request to your server/page, create-user.php. In turn, this script/server sends a POST request to the API site. Your web client (browser), and therefore firebug, does not "know" this second part, which happens on your server.
To see the actual POST request, you should use different tools. For example, point the POST request to a machine of your own, then confirm in the server log that there was an inbound POST request.


text:
Q: How to find ArrayList containing Object I have a method from which i am returning object like
public static Object login(DataManager dataManager, String userName, String password)
    ArrayList<LoginCredentialsBean> loginCredentialsList = new ArrayList<LoginCredentialsBean>();
    String authenticated = "false";
    Connection connection = null;
    try {
        connection  = dataManager.getConnection();
    } catch (Exception e) {
         return ("Having problem in connectiong to databaste: " + e.getMessage());
    }
    if (connection != null) {
         try {
             ...
             try {
                 ResultSet rs = prepStatement.executeQuery();

                 try {
                     while (rs.next()) {
                         ...
                         loginCredentialsList.add(new LoginCredentialsBean(roleId, orgaCode, passwordExpiryDate, date, status, language));
                        authenticated = "true";
                     } //end of while()
                 } finally {
                     rs.close();
                 }
             } finally {
                 prepStatement.close();
             }
             if (authenticated.equals("true")) {
                updateUserLogByInserting(connection, userName);
             }

         } catch(SQLException e) {
             System.out.println("Could not login from dataabse:" + e.getMessage());
         } finally {
             dataManager.putConnection(connection);
         }
    }
    if (authenticated.equals("true")) {
        return loginCredentialsList;
    } else {
        return authenticated;
    }
} //end of login()

Now i am testing it like
public static void main(String... args) {

    MoneyTreeServices moneyTreeServices = new MoneyTreeServices();

    Object result = moneyTreeServices.login("Admin", "cbas1234");
    if (result instanceof ArrayList<?>) {

        System.out.println("ArrayList instance");
    }
    System.out.println(result);
}

It returns me result like
ArrayList instance
[pk.mazars.moneyTree.bean.LoginCredentialsBean@b7ec5d]

I want to ask i am using condition like ArrayList<?>. How can i check that ArrayList that contain LoginCredentialsBean object. Like when i use
if (result instanceof ArrayList<LoginCredentialsBean>) {

}

i get error that
Can not perform instanceof check against parameterized type ArrayList<LoginCredentialsBean>. Use the form ArrayList<?>

I want to check instanceof ArrayList and arraylist has LoginCredentialsBean ?
Thank you.

A: Parameterized type info is erased at compile time and instanceof is resolved at (fanfare) runtime - that is why you get that error.
What you could do is iterate over the elements in the List and instanceof them.
Cheers,

A: The short answer is that you can't.  Generics are implemented via type erasure - they're effectively a compile-time syntactic sugar to ensure you don't put an Integer into a List<String>.
The runtime objects themselves, however, are just the raw types.  An instance of ArrayList doesn't know that it's an ArrayList<String> (or rather, that it was assigned to a variable with that generic type).  So when you interrogate it with reflection, you cannot get any generic type info.
There are two broad types of solution I can think of.  One is to iterate over the list contents and check their dynamic type - if the first element is a LoginCredentialsBean, for example, then it's reasonable to assume that you have a List<LoginCredentialsBean>.  This won't work for empty lists though, which could be a problem, and can potentially give false positives (e.g. a List<Object> allParameters might happen to have a LoginCredentialsBean as its first element...)
The other is to explicitly pass metadata objects around - so in this case you'd return the Object from the login method, along with a token which describes what type of object it is.  This could be a simple enum constant; or going to the other extreme you could make the tokens generically typed, such that the compiler can check this against the type of what you're returning and ensure that the tokens are type-correct.
But in any case, instanceof is too little (information), too late.

Mind you, your login method looks... odd.  I don't think it should return an Object at all, as that's just lazy and completely subverting the static type system which would help you here.  Rather, I think it should just return a List<LoginCredentialsBean> containing the credentials that pertain to the given login.
You have three different paths where you return.  The first is if an exception is encountered when connecting to the database - in which case you should throw an exception!  Returning a string with the error details is very atypical and confusing - an exceptional condition should be handled as an Exception, that's what they're for.
The other two situations are ones where you're able to look up definitive results.  For the failed login case, I would just return an empty list (i.e. this username/password has no credentials whatsoever), while returning the populated list during a successful login.
If you strongly want to be able to distinguish between a login failure, and a successful login (with no credentials), then perhaps return a compound object instead, such as:
class LoginStatus {
    final boolean authenticated;
    final List<LoginCredentialsBean> credentials;
}

Either way, the caller knows exactly what they're getting back, and can call methods on it appropriately without having to call instanceof and typecast.

A: You have to check it twice.
if (result instanceof ArrayList<?>) {
 System.out.println("ArrayList instance");
 //cast
 ArrayList<LoginCredentialsBean> list = (ArrayList<LoginCredentialsBean>) result;

  ///..check if list contains LoginCredentialsBean
 for(int i=0; i<list.size(); i++){
  if(list.get(i) instanceof LoginCredentialsBean){
   System.out.println("LoginCredentialsBean instance");
  }
 }
}

A: There is no such thing like "ArrayList that contain LoginCredentialsBean"
ArrayList contains Objects, all the time.
you must iterate over the list and check each object:
for (Object o: result) {
     if (!(o instanceof LoginCredentialsBean)) {
           //Fail
     }
}

A: you can use the contains(Object o) to check whether the ArrayList contains your object. With the instanceof List to check whether the given object is a List. Because of type erasure at runtime the generic type of the List wont be available

A: If your login method returns an Object type there is no way to check this the way you try.
Type parameters exist only on compile-time due to type erasure. You need to check if retuned object is a List or Collection or just Iterable, then iterate throuh it and check every item, if it is a instance of LoginCredentialsBean.
However, your code is an example of bad design. A method that returns a String or a list is just wrong. To make it right:

*

*make it return List<LoginCredentialsBean>

*throw a checked exception if authentication fails

public static List<LoginCredentialsBean> login(DataManager dataManager, String userName, String password) throws AuthenticationException {...}
Note: Use boolean to keep logical data instead of "true" or "false" strings.


text:
Q: Why the Delayed Alert Display? Scenario:
I'm playing around with accessing & displaying remote images to learn Combine's assorted notification flags/protocols.

One Goal:
Accessing a bad URL should immediately display an Alert().

Reality:
Alert is displayed AFTER then second request and beyond.

Here's the main (calling) view:
import Combine
import SwiftUI

struct ContentView: View {
    @EnvironmentObject var settings: MySettings
    @State private var url: String = "https://garbage.com"  // ...purposely set to display alert.
    @State private var image: URLImage = URLImage()
    @State private var angelFish: Image = Image("QueenAngelfish")
    @State private var isPresented = false

    var body: some View {
        ZStack {
            Color.green
            NavigationView {
                VStack {
                    Button(action: {
                        self.url = "garbage.com"
                        self.isPresented = self.image.imageLoader.isPresented
                        self.image.imageLoader.load(url: URL(string: self.url)!)
                    }) {
                        Text("Get An Image")
                    }

                    angelFish
                        .resizable()
                        .frame(width: 300, height: 200, alignment: .center)
                        .padding()
                    image
                        .alert(isPresented: $isPresented, content: { () -> Alert in
                            Alert(title: Text(verbatim: "Unable to Acquire Image."))
                        })

                }.navigationBarTitle(Text(settings.name))
            }
        }
    }
}

Here's the access engine:
import Combine
import SwiftUI

enum ImageURLError: Error {
    case dataIsNotAnImage
}

struct URLImage: View {
    @EnvironmentObject var settings: MySettings
    @ObservedObject var imageLoader: ImageLoader
    var placeholder: Image

    init() {
        self.placeholder = Image(systemName: "photo")
        self.imageLoader = ImageLoader()
    }

    var body: some View {
        VStack {
            imageLoader.image == nil ?
                placeholder : Image(uiImage: imageLoader.image!)
            Button(action: {
                self.settings.name = "Happy Thanks Giving"
                self.settings.isPresented = true
            }, label: {
                Text("Touch Me")
            })
        }
    }
}

// =====================================================================================================

class ImageLoader: ObservableObject {
    let id: String = UUID().uuidString
    var didChange = PassthroughSubject<Void, Never>()

    @Published var isPresented = false

    @Published var image: UIImage? {
        didSet {
            DispatchQueue.main.async {
                self.didChange.send()
            }
        }
    }

    // ---------------------------------------------------------------------------

    func load(url: URL) {
        print("Hello Ric: ", #function)

        URLSession.shared.dataTask(with: url) { data, _, error in
            DispatchQueue.main.async {
                if error != nil {
                    self.isPresented = true
                    self.didChange.send()   // ...attempting to activate alert().
                    return
                }

                self.image = UIImage(data: data!)
            }

        }.resume()
    }
}

This code purposely creates an error due to a bad URL.
I tried to immediately notify the calling routine via passing the boolean 'isPresented' flag as an '@Published' variable

Expected Result:
Displayed Alert.

Actual Result:
Alert is displayed AFTER & beyond the initial attempt.

Question: How do I perform an INSTANT Alert display?

A: Ok, there were several issues here, mostly about ObservableObject usage and linking things together. Please find below modified module that works. (I substituted some absent entities with mine just to test).
import Combine
import SwiftUI

class ImageLoader: ObservableObject {
    let id: String = UUID().uuidString

    // !!! no need in didChange, @Published is already Publisher
    // see below .onReceive for usage example
    @Published var isPresented = false
    @Published var image: UIImage?

    func load(url: URL) {
        URLSession.shared.dataTask(with: url) { data, _, error in
            DispatchQueue.main.async {
                if error != nil {
                    self.isPresented = true
                    return
                }
                self.image = UIImage(data: data!)
            }
        }.resume()
    }
}

class MySettings: ObservableObject { // << reconstructed for testing
    @Published var name = "My Name"
    @Published var isPresented = false
}

enum ImageURLError: Error {
    case dataIsNotAnImage
}

struct URLImage: View {
    @EnvironmentObject var settings: MySettings
    @ObservedObject var imageLoader: ImageLoader
    var placeholder: Image

    init() {
        self.placeholder = Image(systemName: "photo")
        self.imageLoader = ImageLoader()
    }

    var body: some View {
        VStack {
            imageLoader.image == nil ?
                placeholder : Image(uiImage: imageLoader.image!)
            Button(action: {
                self.settings.name = "Happy Thanks Giving"
                self.settings.isPresented = true
            }, label: {
                Text("Touch Me")
            })
        }
        .onReceive(imageLoader.$isPresented) { self.settings.isPresented = $0 }
    }
}

struct ContentView: View {
    @EnvironmentObject var settings: MySettings
    @State private var url: String = "https://garbage.com"  // << this url is valid
    @State private var image: URLImage = URLImage()
    @State private var angelFish: Image = Image("QueenAngelfish")

    var body: some View {
        ZStack {
            Color.green
            NavigationView {
                VStack {
                    Button(action: {
                        self.url = "garbage.com" // << this url is not valid [to test alert]
                        self.image.imageLoader.load(url: URL(string: self.url)!)
                    }) {
                        Text("Get An Image")
                    }

                    angelFish
                        .resizable()
                        .frame(width: 300, height: 200, alignment: .center)
                        .padding()
                    image
                        .alert(isPresented: $settings.isPresented) {
                            Alert(title: Text(verbatim: "Unable to Acquire Image."))
                        }
                }.navigationBarTitle(Text(settings.name))
            }
        }
    }
}

struct TestDelayedAlert_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environmentObject(MySettings())
    }
}


text:
Q: create-react-app build deploy on LAMP/XAMPP/WAMP How to deploy the build on Apache WAMP/XAMPP server?
I have an app created with create-react-app and I have two pages on this application
When I execute yarn start or npm start it's working fine and all the pages are rendering properly on the URL navigation or button click
I executed the build command

npm run build

It's generating all the static and index.html files on build folder.
I moved this build folder content to www of wamp folder and execute on the url http://localhost its showing only the home page.  and the next page gives 404 not found error
But when I am executing the serve module of npm command it's working fine on http://localhost:5000

serve build

Please help me how to resolve this?
I have to deploy my application on wamp server all are static pages there is no rest api contents

A: By default, your react project is built to be deployed directly into your server 'www' (root) folder. Hence you may copy the contents of your project 'build' folder to the WAMP 'www' folder and then go to http://localhost/ in your browser. Your project will be displayed.
Alternatively, you may want to use a WAMP root subfolder, e.g. 'www/react/'.
In this case add to your package.json file a homepage key:
"homepage": "http://localhost/react/",

Then build your project again:
npm run build

Finally, copy the contents of your project 'build' folder to 'www/react/'. To display your project visit http://localhost/react/
You may get more information in
How to deploy a React App on Apache web server

A: Create a folder in htdocs (xampp) named react.
add "homepage": "./", (for relative path) or "homepage": "http://localhost/react/", (absolute path) in package.json file.
And on App.js file
<BrowserRouter basename='/react'>
  <Switch>
    <Route exact path="/">
      Hello
    </Route>
    <Route path="*" render={() => "404 Not found!"} />
  </Switch>
</BrowserRouter>

After configuring package.json and App.js run build command
npm run build

Then copy all files from build folder to react folder in htdocs.
And also create an .htaccess in react folder in htdocs.
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

If your sub folder name is different then replace /react with your folder name.
Example - rename /react from
"homepage": "http://localhost/react/"
<BrowserRouter basename='/react'>

to
"homepage": "http://localhost/your_folder_name/"
<BrowserRouter basename='/your_folder_name'>

A: You need to configure homepage for your build.

A: Set the basename attribute on the .
<Router basename={'/directory-name'}>
    <Route path='/' component={Home} />
</Router>

directory-name is the folder name under your xampp htdocs folder


text:
Q: When is $\dim(W_1 \cap W_2) = \dim(W_1)$ for subspaces of a finite dimensional vector space $V$? To clarify my question:
Let $W_1$ and $W_2$ be subspaces of a finite dimensional vector space $V$. What are the conditions that need to be satisfied in order to say that $\dim(W_1\cap W_2)=\dim(W_1)$?
I started by saying that if $W_1 \subseteq W_2$, then $W_1 \cap W_2=W_1$, in which case that $\dim(W_1 \cap W_2)$ must equal to $\dim(W_1)$. I also added the condition that the intersection of $W_1$ and $W_2$ can not be empty.
I'm having trouble trying to find out the conditions for other situations, like $W_1 \not\subset W_2$ and $W_2 \not\subset W_1$. I put down that if the basis of $W_1 \cap W_2$ has the order of $n$, then the basis of $W_1$ must have the same order. I'm not sure if I've done the right reasoning.
Any suggestion would help! Thanks a lot.


text:
Q: How do you get a git log output from a shelljs.exec command? I need to put a git log into a file.
The command line works fine
Git log command line result
But if I call this command with a grunt task using shelljs.exec, I dont get any output
Git log with grunt task using shelljs.exec
Here the grunt code :
/*global module:false,require,console*/
'use strict';

var shell = require('shelljs');

module.exports = function (grunt) {

    // Project configuration.
    grunt.initConfig({
        // Task configuration.
    });

    grunt.task.registerTask('git-log', 'git log output', function () {
        console.log('RESULT : ', shell.exec('git log HEAD...HEAD^ --oneline',{silent : true}).output);
    });

    // Default task.
    grunt.registerTask('default', ['git-log']);

};

I checked all the shelljs docs and tried different ways (including async) with no success...
Any idea ?
Thx

A: Try to use .stdout instead of .output.
In your code:
shell.exec(
  'git log HEAD...HEAD^ --oneline',
  {silent : true}
).output;

Change to:
shell.exec(
  'git log HEAD...HEAD^ --oneline',
  {silent : true}
).stdout;


text:
Q: Strange behavior when adding UIButton to UICollectionViewCell I'm trying to add aUIButton to aUICollectionViewCell. The main purpose of the button is to let users to select their favourites.
When they click on theUIButton, the UIButton will display a glowing star image, showing that the item has been picked as favourite.
Click on the UIButton again, and the button return to display the original image with an empty star, meaning deselection.
The way I realize this is as below:
1 - In the storyboard, put an UIButton into theUICollectionViewCell, ctrl-drag the button to the cell's .h file to setup an action called
-(IBAction)favoriteBtnClick:(id)sender;

2 - In the cell's .m file, edit the action as follows:
-(IBAction)favoriteBtnClick:(id)sender {
    if ([self.favoriteChecked isEqualToString:@"NO"]) {
        UIImage *image = [UIImage imageNamed:@"FavoriteSelected.PNG"];
        [sender setBackgroundImage:image forState:UIControlStateNormal];
        self.favoriteChecked = @"YES";
    } else if ([self.favoriteChecked isEqualToString:@"YES"]) {
        UIImage *image = [UIImage imageNamed:@"FavoriteBlank.PNG"];
        [sender setBackgroundImage:image forState:UIControlStateNormal];
    }
}

However, when I try to run the UICollectionView, when I clicked the button on one cell, "strange" behaviors occurred:
1 - Click on one cell to turn one button to favorite glowing star, buttons on some other cells below also turn selected, after your scroll down the list.
2 - The switching only functions for one cycle. After you finish the first round of select and deselect, there is no longer reactions upon further clicking.
Can anybody help me understand the reasons for this and probably give me some hints on how to solve it?
Thank you!
Regards,
Paul

A: Add this code in your button action
CGPoint ButtonPoint = [sender convertPoint:CGPointZero toView:self.collectionView];
    NSIndexPath *ButtonIndex = [self.collectionView indexPathForItemAtPoint:ButtonPoint];
buttonindexpath = ButtonIndex.row
[collectionView reloadData];

Now in your cellForItemAtIndexPath, check if indexPath.row == buttonindexpath, if yes give the code you gave in button action....
ie....
if (indexPath.row == buttonindexpath)
{
    if ([self.favoriteChecked isEqualToString:@"NO"])
    {
        UIImage *image = [UIImage imageNamed:@"FavoriteSelected.PNG"];
        [sender setBackgroundImage:image forState:UIControlStateNormal];
        self.favoriteChecked = @"YES";
    }
    else if ([self.favoriteChecked isEqualToString:@"YES"])
    {
        UIImage *image = [UIImage imageNamed:@"FavoriteBlank.PNG"];
        [sender setBackgroundImage:image forState:UIControlStateNormal];
    }

}
Hope this works fine

A: This is happening because of cell reuse. since self.favoriteChecked is a property inside the custom collection cell class, and its value is updated only inside that class causes this issue.
Solution to this problem is, if you are using custom object model to populate collection cells from viewcontroller, then on favourite button click update the favourite status on that custom object and in cellForItemAtIndexPath method check the value of favourite status and update the favoriteChecked status of custom collectionviewcell class.
If you are not using custom object, you need to keep a list of favourite items separately either indexpaths of favourite item or unique identifier of fav item. Then in cellForItemAtIndexPath method check the value of favourite status and update the favoriteChecked status of custom collectionviewcell class.

A: This is no no a strange behaviour. You have load the cells from the model data objects. You have to track & keep the state change of button clicked data in an array & then load the cell data values.
Here is a sample code : which aligns with solution to your problem.
NSMutableArray *favoriteStatusArray = [[NSMutableArray alloc]init];
// assume favoriteStatusArray is initialized with all BOOL as NO.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    SomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    cell.favoriteButton.tag = indexPath.row;
    [cell.favoriteButton addTarget:self action:@selector(peformFavoriteChange:) forControlEvents:UIControlEventTouchUpInside];

    if([[favoriteStatusArray objectAtIndex:indexPath.row] boolValue] == NO)
        UIImage *image = [UIImage imageNamed:@"FavoriteSelected.PNG"];
        [cell.favoriteButton setBackgroundImage:image forState:UIControlStateNormal];
    }else {
    UIImage *image = [UIImage imageNamed:@"FavoriteBlank.PNG"];
    [cell.favoriteButton setBackgroundImage:image forState:UIControlStateNormal];
   }
    return cell;
}

-(void)peformFavoriteChange:(UIButton *)sender
{
    BOOL oldValue = [[favoriteStatusArray objectAtIndex:sender.tag] boolValue];
    [favoriteStatusArray replaceObjectAtIndex:sender.tag withObject:[NSNumber numberWithBool:!oldValue]];

    [myCollectionView reloadData];
}

Hope you got the idea of doing this.


text:
Q: Java command line exit command? I'm making a server, and it is on a Text Based Raspberry Pi. basically, everything is running from the command line, so when the server runs, there is no graphics, and it prints everything out using System.out.println();. so my question is, instead of having a button that runs a shutdown() method, how can i make it so at any point in time, i am able to push, say, 'e', and the program will run the shutdown() method? i've done some searching, and am not sure quite how to phrase the question. i was thinking adding a keylistener, but im not sure if that can be added to nothing graphic? anyway, any help would be appreciated!!! thanks in advance

A: To register keyboard events you first need to have the focus on your program, and for that you need a gui. I suggest:
1.- Create a JLabel(and a scrollbar).

2.- Instead of using System.out.print("text");, use myJLabel.append("text" + "/n");.

3.- Add a keyboard listener. Register key events so that the x key closes your server, the s key stops it, ...

As you have described your app, you can't write input to the server, you can only read output from it. I recomend step 4.
4.-Add a JTextFiel to send input to the server.

5.-To make it user-friendly , you could use a JEditorPane instead of a JLabel, and add HTML to your output.

A: Alright, so based on the comments, (which i up voted btw), i made a thread that constantly used scanner to see if i typed "exit". Thanks for all the help!

A: If you don't want to have a visible gui, you could create an "always-focused invisible grafical interface" with the listener.


text:
Q: MySQL: merge different tables into one big table I have 12 tables with this 2 fields:

*

*code (varchar primary key) and text (varchar)

Each table has already 1055 entries (all tables have the same amount then)
I need to make a new table with the following fields:

*

*id (int pk), field-1, field-2, ... field-2
Each field-N will have the contents of the text field of one of the tables. I don't need the code field from those tables.
So, at the end, this new big table should have 1055 entries, with the id field going from 1 to 1055, and the rest of fields (field-1, field-2, etc) storing the values held in the text field of the 12 tables that I have now.
How can I accomplish this? I've been trying for a while but I can't find the right way to do this.
Any help would be much appreciated!

A: I am not sure if I understand your question but I would simply write a loop that will insert each row of each table into a newly created table.
Something like this
CREATE TABLE newTable
(
code int NOT NULL AUTO_INCREMENT,
text varchar(255),
PRIMARY KEY (code)
)

// Do this for each table:
SELECT text FROM table1;

for(int i = 0; i < dataSet.size; i++)
{
  INSERT INTO newTable (text) VALUES (row(i).value)
}

A: So what I finally decided to do is to download all the information of those tables to excel, create a new excel with the structure and values that I needed, and upload this new excel as CSV. Now I have exactly what I wanted! Probably not the best method, but it didn't take so long and worked :)


text:
Q: how to setup nodejs code on server(cpanel) I have installed node js and npm on server successfully.
Node server is running properly on live with below message:-
Sever listening at port 3000.
My client js is as below:-
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>

    <script>
        var socket = io.connect( 'https://'+window.location.hostname+':3000' );
        socket.on( 'new_count_message', function( data ) {
            if(curkey == data.key)
            {
                $('#notif_audio')[0].play();
                $( "#action" ).html( data.new_count_message ).css('color', '#a94442');
            }
        });

Here I am adding my sever js code on asking:-
var socket  = require( 'socket.io' );
var express = require('express');
var app     = express();
var server  = require('https').createServer(app);
var io      = socket.listen( server );
var port    = process.env.PORT || 3000;

server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

io.on('connection', function (socket) {
  socket.on( 'new_count_message', function( data ) {
    io.sockets.emit( 'new_count_message', {
        new_count_message: data.new_count_message,
        key: data.key
    });
  });
});

Note:- This code is working fine on localhost.
But on live showing below error:-

err_ssl_version_or_cipher_mismatch

1) How to correct this?
2) How to use local script instead of cdn script?

A: You probably need to serve the folder statically. Assuming you're using express, you can use this after requiring express:
var app = express();
app.use(express.static('public'));


text:
Q: Stream MP3 through a php file with audiojs I have the following code to get the contents of MP3 file and set the headers as required(?):
$file = fopen("test.mp3","r");
$content = fread($file,filesize("test.mp3"));

header("Content-Type: audio/");
header("Content-Length: " .(string)(filesize("test.mp3")) );

fclose($file);

echo $content;

For playing the file I use audiojs (http://kolber.github.io/audiojs/).
My PHP file acts as the data source as a normal MP3 file would do.
audiojs is able to play this MP3 file, BUT
You can visually see the player buffering, but you cannot jump to an already buffered position in the MP3 file.
For real MP3 files this is possible.
Why not with PHP files which act as MP3 file?
Is PHP or audiojs the reason?
I also tried the following code:
// Try and open the remote stream
  if (!$file = fopen("test.mp3","r")) {
    // If opening failed, inform the client we have no content
    header('HTTP/1.1 500 Internal Server Error');
    exit('Unable to open remote stream');
  }

  $stream = stream_get_contents($file);

  // It's probably an idea to remove the execution time limit - on Windows hosts
  // this could result in the audio stream cutting off mid-flow
  set_time_limit(0);

  // Inform the client we will be sending it some MPEG audio
  header("Content-type: audio");
  header("Content-Length: ".(string)(filesize("test.mp3")) );
  header("Content-transfer-encoding: binary");

  // Send the data
  fpassthru($stream);

Both not working :(
Any chance? I really need this feature for permission topics.
Or are there any other alternatives except .htaccess?
captan2


text:
Q: Adding a primary key with an "insert into" statement I have the following query and need to add a Primary Key to the Column of Employeenumber:
SELECT [Exceptions].Employeenumber,[Exceptions].exceptiondate, [Exceptions].starttime, [exceptions].endtime, [Exceptions].code, datediff(minute, starttime, endtime)  as minutes INTO scratchpad3,
FROM Employees INNER JOIN Exceptions ON [Exceptions].EmployeeNumber = [Exceptions].Employeenumber
where [Exceptions].exceptiondate between '5/1/2011' and '5/8/2011'
GROUP BY [Exceptions].Employeenumber, [Exceptions].Exceptiondate, [Exceptions].starttime, [exceptions].endtime,
[Exceptions].code, [Exceptions].exceptiondate

but don't know the proper syntax when you're doing a "create" this way. What's the propery syntax to add a primary key this way?
Thank you.

A: You can't add a Primary Key to a SELECT statement. Primary Keys are identifying columns of tables. You'd need to ALTER TABLE and ADD PRIMARY KEY. The syntax is different, but it looks like you're using SQL Server. Statements can be found  Here.
If you're looking to just add a number for each record, try using ROW_NUMBER (might be different depending on the database you're using).
Hope that helps,
Jason


text:
Q: secure upload with uploadify and asp.net mvc 2 i have an asp.net mvc 2 application and i am using uploadify. I am uploading the files straight into a sql server db. What are the necessary checks i need to do and how? I would like to perform a anti virus scan? what are possible security loopholes here?

A: You could try feeding the uploaded stream into a XmlReader and parse through it. In the event of an exception chances are that there is something wrong with this XML file:
using (var reader = XmlReader.Create(uploadedFile.InputStream))
{
    try
    {
        while (reader.Read())
        { }
        // At this stage you may save the XML file into the database.
    }
    catch (Exception ex)
    {
        // probably not a valid XML file
    }
}

If the uploaded XML files need to obey a certain structure you could validate them against an XSD schema by specifying this to the XmlReader.


text:
Q: While loop without explicit increment / counter (basic) I am new to php and it's my first language. So my question seems to be very basic.
First the basic concept of a while loop seems pretty clear to me.
As long as i increment (i++) until the "crash condition" (i<10) becomes true.
But I realy wonder why the following code example without any explicit incrementation works.
$originals = "originale";
$thumbnails="thumbnails";
$directory = opendir($originale);
$images = array();
while(($file = readdir($directory)) !== false) {
    if(preg_match("/\.jp?g$/i", $file)){
        $images[] = $file;
    }
}
echo "<pre>";
var_dump($images);
echo "</pre>";
closedir($directory);

Obviously I missed something. It seems to be magic. I would expect an enless loop which returns the first file... ?
I hope that despite my English (sorry for that) the question becomes clear.
Many thanks in advance.

A: As you can see in the PHP documentation readdir does:

Returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.

So everytime you call readdir will return the next file from that directory.
For example if you have a direcotry with 2 files:

*

*one.txt

*two.txt
First time you call readdir will return one.txt. And this is different from false so will execute the code inside the while
Second time you call readdir will return two.txt and the same as above.
Thrid time you call readdir will return false because no more files are in that dirrecotry. and the condition from while will not be true anymore so will not enter while anymore.


text:
Q: Understanding the Grand Central Dispatch I saw a lot of topics about it and still unclear ..
1)
When I doing :
dispatch_async(dispatch_get_main_queue(), ^(void) {
    for(int i = 0; i < 10000000; i++)
    {
        NSLog(@" i = %i", i);
    }
});

The UI is froze, I can't click in any button. If I understand, it's because it's called on dispatch_get_main_queue, that's say the main thread ? So why talking about "background" if the UI is froze ?
2)
dispatch_async(dispatch_get_main_queue(), {
        self.tableData = results
        self.appsTableView!.reloadData()
        })
    })

The context : I get back some data (session.dataTaskWithURL ) from an api service and when I received all informations, I'm doing this dispatch.
But I didn't understood the explanations, I quote :

"Because this task happens in the background, we need to jump in to
  the foreground before we update the UI. So we need to use
  dispatch_async to move back in to the main thread, and reload the
  table view."

Hum ?? It is because the session url was in background and now it's necessary to come back to the main thread ? And what if we don't come back ?
3) I listened something like updating the UI from another thread is not safe. Why ?
4) A little HS, but will be nice : Now, I'm waiting that the request finish to receive all informations and display it to the UI. It can be 3 secondes for exemple. During this laps of tame, the UI is empty. It is possible to display informations in the UI little by little the data are received and not waiting that the request finish ?
Thanks a lot in advance, all !

A: 1) You're dispatching to the main thread so it is going to be a blocking operation.  Instead, you want to dispatch to a different thread.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {

    // this is on a background thread
    for (int i = 0; i < 10000000; i++) {

        NSLog(@"i = %i", i);

    }

    dispatch_async(dispatch_get_main_queue(), ^(void) {

        NSLog(@"Done - this is on the main thread.");

    });

});

2) The previous dispatch block that you were in was in the background, so now you dispatch to the main thread within that block to perform UI tasks (all UI tasks MUST be performed on the main thread).
3) From the documentation:

Note: For the most part, UIKit classes should be used only from an application's main thread. This is particularly true for classes derived from UIResponder or that involve manipulating your application's user interface in any way.

4) As some background tasks finish, you can call to the main thread to update UI for sure.  ex:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {

    for (int i = 0; i < 10000000; i++) {

        NSLog(@"i = %i", i);
        if (i % 1000000 == 0) {

            dispatch_async(dispatch_get_main_queue(), ^(void) {

                NSLog(@"Another million is done (this is on the main thread)");

            });

        }

    }

    dispatch_async(dispatch_get_main_queue(), ^(void) {

        NSLog(@"Done - this is on the main thread.");

    });

});


text:
Q: What Intent Action to use to share zip file I'm using FileProvider implementing the logic for sharing internal app zip files, i tested it and works fine with Intent.ACTION_SEND with OneDrive,Google Drive, Gmail, Outlook, Wifi direct and bluetooth.
I tried with viber also but this failed to attach zip file then i used a file browser and tried to share the same file with viber and it succeeded.
I think it's coming from Intent Action but wich one is suitable for sharing files with all possible apps ? And better yet how to display a "save in device" alike from ShareActionProvider ?


text:
Q: How to save bitmap locally? I'm trying to save my bitmap to local storage, but it doesn't work or I just can't find it.
                    try {
                        val fileOutputStream: FileOutputStream =
                            context!!.openFileOutput("BitMapFileSave", Context.MODE_PRIVATE)
                        viewBitMap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)
                        fileOutputStream.close()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }

Where is directory of my savings or how to directly save it somewhere in app like
app/res/drawable


text:
Q: Python http request from url, answer in xml format i am going to work with python http requests. I need to get a request lets say from httpbin.org/get, get its content, convert it into xml format and post it back let say to httpbin.org/post. I also need to handle 10-15 requests a minute. Do i need to use grequests(async) or requests library? Code i tried:
import grequests

urls = ['http://www.google.com/finance','http://finance.yahoo.com/','http://www.bloomberg.com/']
def def1(response,**kwargs):
print(response.url," is available...")
def def2(response,**kwargs):
print(response.url," content is: ",response.content)
def requestAsync(urls):
responses=[]
for u in urls:
    get=grequests.get(u,hooks={'response':def1})
    post=grequests.post("http://httpbin.org/post",hooks={'response':def2},data="some data")
    responses.append(get)
    responses.append(post)
return grequests.map(responses)
print(requestAsync(urls))

A: grequests is definitely a better way of implementing the design, it will be harder to implement though.
What is the issue you are facing with the code ?


text:
Q: Why is StoreDevtoolsModule in my production bundle, and how to remove it from there? Using webpack-bundle-analyzer I detected the module StoreDevtoolsModule into my production bundle.
I though three shaking would removed it, but it does not...
Is there a way to build in production mode without it? (it is not used anyway in production):
(....)
//                \/ this one
import { StoreDevtoolsModule } from '@ngrx/store-devtools';

@NgModule({
    imports: [
        (....),
        !environment.production ? StoreDevtoolsModule.instrument() : [],
        (....),
    ],
})
export class AppModule {}

A: After discussing the problem with my peers, we figured that the reason for it to be in the bundle is that because environment.production is evaluated at runtime, tree shaking will not remove the module from the bundle. Event though it is not really used.
There is a way around it though.
first create 2 files:
one to host the import array for non-prod (default), with the following contents
src/hat-trick/store-dev-tools-import.ts
import { environment } from 'src/environments/environment';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';

export const storeDevToolsImport = [
    !environment.production ? StoreDevtoolsModule.instrument() : []
];

and the other to host the import array for prod builds, with the following contents
src/hat-trick/store-dev-tools-import.prod.ts :
export const storeDevToolsImport = [];

add a fileReplacements section to your angular.json file at the production build config:
"production": {
 (....)
    "fileReplacements": [
        (....)
        {
            "replace": "src/hat-trick/store-dev-tools-import.ts",
            "with": "src/hat-trick/store-dev-tools-import.prod.ts"
        },
    ]
}

and finally, use the new variable storeDevToolsImport in you module, instead of importing StoreDevtoolsModule directly:
@NgModule({
    imports: [
        (....),

        ...storeDevToolsImport,

        (....),
    ],
})
export class AppModule {}

And done! next time you build in prod mode, StoreDevtoolsModule will no longer be included (saving about 4kb)
NgRx docs have the same solution in a hidden spot as per comment on the question above

A: It can be as simple as adding the following line.
@NgModule({
  declarations: [AppComponent],
  imports: [
    [... other imports]
    !environment.production ? StoreDevtoolsModule.instrument({
          name: 'overview',
          maxAge: 25,
        }) : [], //
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}


text:
Q: XNA: Scrolling A Linearly Wrapped, Rotating Texture, Up, Down, Left, And Right: I'm working on a simple XNA based game for the PC where I have a game screen window size of 1024 X 768 and I want to scroll, in the direction in which I move my mouse, a linearly wrapped, rotating texture, which is 1280 X 1280 in size.
The origin of this texture has been set to it's center point(640, 640) and I then place this texture onscreen in the middle of my game window at (512, 384).
The code I have so far (pasted in it's entirety below) works perfectly until I introduce rotation to the mix.
public class Game1 : Microsoft.Xna.Framework.Game
{

    GraphicsDeviceManager graphics;

    SpriteBatch spriteBatch;

    int x;
    int y;

    float z = 250f;

    Texture2D Overlay;

    Texture2D RotatingBackground;

    Rectangle? sourceRectangle;

    Color color;

    float rotation;

    Vector2 ScreenCenter;

    Vector2 Origin;

    Vector2 scale;

    Vector2 Direction;

    SpriteEffects effects;

    float layerDepth;

    public Game1()
    {

        graphics = new GraphicsDeviceManager(this);

        Content.RootDirectory = "Content";

    }

    protected override void Initialize()
    {

        graphics.PreferredBackBufferWidth = 1024;

        graphics.PreferredBackBufferHeight = 768;

        graphics.ApplyChanges();

        Direction = Vector2.Zero;

        IsMouseVisible = true;

        ScreenCenter = new Vector2(graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight / 2);

        Mouse.SetPosition((int)graphics.PreferredBackBufferWidth / 2, (int)graphics.PreferredBackBufferHeight / 2);

        sourceRectangle = null;

        color = Color.White;

        rotation = 0.0f;

        scale = new Vector2(1.0f, 1.0f);

        effects = SpriteEffects.None;

        layerDepth = 1.0f;

        base.Initialize();

    }

    protected override void LoadContent()
    {

        spriteBatch = new SpriteBatch(GraphicsDevice);

        Overlay = Content.Load<Texture2D>("Overlay");

        RotatingBackground = Content.Load<Texture2D>("Background");

        Origin = new Vector2((int)RotatingBackground.Width / 2, (int)RotatingBackground.Height / 2);

    }

    protected override void UnloadContent()
    {

    }

    protected override void Update(GameTime gameTime)
    {

        float timePassed = (float)gameTime.ElapsedGameTime.TotalSeconds;

        MouseState ms = Mouse.GetState();

        Vector2 MousePosition = new Vector2(ms.X, ms.Y);

        Direction = ScreenCenter - MousePosition;

        if (Direction != Vector2.Zero)
        {

            Direction.Normalize();

        }

        x += (int)(Direction.X * z * timePassed);

        y += (int)(Direction.Y * z * timePassed);

        //No rotation = texture scrolls as intended, With rotation = texture no longer scrolls in the direction of the mouse. My update method needs to somehow compensate for this.
        //rotation += 0.01f;

        base.Update(gameTime);

    }

    protected override void Draw(GameTime gameTime)
    {

        spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null);

        spriteBatch.Draw(RotatingBackground, ScreenCenter, new Rectangle(x, y, RotatingBackground.Width, RotatingBackground.Height), color, rotation, Origin, scale, effects, layerDepth);

        spriteBatch.Draw(Overlay, Vector2.Zero, Color.White);

        spriteBatch.End();

        base.Draw(gameTime);

    }
}

For example if I were to rotate the texture to the right then moving the mouse straight up from the screen's center causes the texture to scroll diagonally upwards and to the right - this is not my intent - If I move my mouse in any direction I want my texture to scroll in that direction just the same as if I had never introduced rotation to the mix.
How do I go about altering my Update() method to achieve this?
Thanks for reading.....

A: From your question, I gather that you want the mouse to control the camera, and the rotation to affect only the texture.
For that, the change required affects the Draw method. When calling Spritebatch.Begin you should pass a transformation matrix as a parameter, using the x and y values. This allows you to rotate the texture in world coordinates, while moving the camera independent from the rotation.
Check this question - Spritebatch.Begin() Transform Matrix - to understand how the transform matrix works.

A: This seems to work. There might be a more elegant solution, but it was sure a neat problem to solve.
public class Game1 : Microsoft.Xna.Framework.Game
{

    GraphicsDeviceManager graphics;

    SpriteBatch spriteBatch;

    int x;
    int y;

    float z = 250f;

    Texture2D Overlay;

    Texture2D RotatingBackground;

    Rectangle? sourceRectangle;

    Color color;

    float rotation;

    Vector2 ScreenCenter;

    Vector2 Origin;

    Vector2 scale;

    Vector2 Direction;

    SpriteEffects effects;

    float layerDepth;

    public Game1()
    {

        graphics = new GraphicsDeviceManager(this);

        Content.RootDirectory = "Content";

    }

    protected override void Initialize()
    {

        graphics.PreferredBackBufferWidth = 1024;

        graphics.PreferredBackBufferHeight = 768;

        graphics.ApplyChanges();

        Direction = Vector2.Zero;

        IsMouseVisible = true;

        ScreenCenter = new Vector2(graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight / 2);

        Mouse.SetPosition((int)graphics.PreferredBackBufferWidth / 2, (int)graphics.PreferredBackBufferHeight / 2);

        sourceRectangle = null;

        color = Color.White;

        rotation = 0.0f;

        scale = new Vector2(1.0f, 1.0f);

        effects = SpriteEffects.None;

        layerDepth = 1.0f;

        base.Initialize();

    }

    protected override void LoadContent()
    {

        spriteBatch = new SpriteBatch(GraphicsDevice);

        Overlay = Content.Load<Texture2D>("Overlay");

        RotatingBackground = Content.Load<Texture2D>("Background");

        Origin = new Vector2((int)RotatingBackground.Width / 2, (int)RotatingBackground.Height / 2);

    }

    protected override void UnloadContent()
    {

    }

    protected override void Update(GameTime gameTime)
    {
        float timePassed = (float)gameTime.ElapsedGameTime.TotalSeconds;

        MouseState ms = Mouse.GetState();

        Vector2 MousePosition = new Vector2(ms.X, ms.Y);

        Direction = ScreenCenter - MousePosition;

        if (Direction != Vector2.Zero)
        {

            float angle = 0;
            angle = (float)Math.Atan2(Direction.Y, Direction.X) - rotation;
            Direction.X = (float)Math.Cos(angle);
            Direction.Y = (float)Math.Sin(angle);
            Direction.Normalize();
        }

        x += (int)(Direction.X * z * timePassed);
        y += (int)(Direction.Y * z * timePassed);

        //No rotation = texture scrolls as intended, With rotation = texture no longer scrolls in the direction of the mouse. My update method needs to somehow compensate for this.
        rotation += .01f ;
        if (rotation > MathHelper.Pi * 2)
        {
            rotation -= (MathHelper.Pi * 2);
        }
        base.Update(gameTime);

    }

    protected override void Draw(GameTime gameTime)
    {

        spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null);

        spriteBatch.Draw(RotatingBackground, ScreenCenter, new Rectangle(x, y, RotatingBackground.Width, RotatingBackground.Height), color, rotation, Origin, scale, effects, layerDepth);
        spriteBatch.Draw(Overlay, Vector2.Zero, Color.White);

        spriteBatch.End();

        base.Draw(gameTime);

    }
}


text:
Q: DEBUG DOS program to view memory I have just started studying X86 Assembly Language.
My doubt -
When I am using the DOS DEBUG program to look at memory location, I am getting slightly different values on examining the same memory location using two different segment:offset addresses. I.e.-
Aren't D 40[0]:17 and D 41[0]:7 supposed to give exactly same output? since both of them give same address on adding segment + offset = 400+17 = 410+7 = 417H
The results which I get - (notice they are slightly different)
-D 40:17
0040:0010                       00-00 00 1E 00 1E 00 0D 1C          .........
0040:0020  44 20 20 39 34 05 34 05-3A 27 39 0A 0D 1C 44 20   D  94.4.:'9...D
0040:0030  20 39 34 05 30 0B 3A 27-31 02 37 08 0D 1C 00 00    94.0.:'1.7.....
0040:0040  93 00 C3 00 00 00 00 00-00 03 50 00 00 10 00 00   ..........P.....
0040:0050  00 18 00 00 00 00 00 00-00 00 00 00 00 00 00 00   ................
0040:0060  0F 0C 00 D4 03 29 30 00-00 00 00 00 91 DA 10 00   .....)0.........
0040:0070  00 00 00 00 00 00 08 00-14 14 14 14 01 01 01 01   ................
0040:0080  1E 00 3E 00 18 10 00 60-F9 11 0B 00 50 01 00 00   ..>....`....P...
0040:0090  00 00 00 00 00 00 10                              .......
-D 41:7
0041:0000                       00-00 00 2C 00 2C 00 44 20          ...,.,.D
0041:0010  20 39 34 05 31 02 3A 27-37 08 0D 1C 0D 1C 44 20    94.1.:'7.....D
0041:0020  20 39 34 05 30 0B 3A 27-31 02 37 08 0D 1C 00 00    94.0.:'1.7.....
0041:0030  08 00 C3 00 00 00 00 00-00 03 50 00 00 10 00 00   ..........P.....
0041:0040  00 18 00 00 00 00 00 00-00 00 00 00 00 00 00 00   ................
0041:0050  0F 0C 00 D4 03 29 30 00-00 00 00 00 1C DB 10 00   .....)0.........
0041:0060  00 00 00 00 00 00 08 00-14 14 14 14 01 01 01 01   ................
0041:0070  1E 00 3E 00 18 10 00 60-F9 11 0B 00 50 01 00 00   ..>....`....P...
0041:0080  00 00 00 00 00 00 10                              .......

A: You are looking at the BIOS data area, whose contents changes over time since it contains things like the state of shift/control/alt keys, the read/write positions of the keyboard buffer and the timer.


text:
Q: Struct declaration in Swift Package results in compilation error when used I have this compilation error on the line declaring ingredient in RecipesVC.swift when I declare the IngredientStruct as part of a swift package.  However, I do not see this when I declare the same struct in the project.  Here is the code snippet:
RecipeStruct.swift   // this is in the swift package Recipes
import Foundation
public struct IngredientStruct: Encodable, Decodable, Identifiable {
    public var id :                          String
    public var recipeID :                    String
    public var ingredientName :              String
    public var ingredientReplacement :       String
    public var measurementType :             String
    public var measurementQuantity :         Int
    public var storage :                     String
}

RecipesVC.swift
import SwiftUI
import Recipes  // from Recipes swift package
struct RecipesVC: View {
    var ingredient: IngredientStruct = IngredientStruct(id: "", recipeID: "", ingredientName: "", ingredientReplacement: "", measurementType: "", measurementQuantity: 0, storage: "")  // "Extra arguments at positions #1, #2, #3, #4, #5, #6, #7 in call\n  Missing argument for parameter 'from' in call \n Missing argument for parameter 'from' in call \n Insert 'from: <#Decoder#>, '"

    var body: View {
    …
    }
}

Now, if I declare the same IngredientStruct in a local project file, it compiles fine. I am not sure as to what I need to do in Swift package to make this compile. Any pointers?
@workingdog - my bad.. error in cut&paste in a hurry - lost 2 lines in the struct as well as the second error for the same line.  I updated the names to lowercase as well. However, I still see the same errors.
Here is the Package.swift file:
import PackageDescription
let package = Package(
    name: "Recipes",
    platforms: [.iOS(.v15), .macOS(.v12)],
    products: [
        .library(
            name: "Recipes",
            targets: ["Recipes"]),
    ],
    dependencies: [ ],
    targets: [
        .target(
            name: "Recipes",
            dependencies: []),
        .testTarget(
            name: "RecipesTests",
            dependencies: ["Recipes"]),
    ]
)

A: If a struct is being made public, it must be initialized appropriately. In the example above, the init() looks like this:
public struct IngredientStruct: Encodable, Decodable, Identifiable {
    public var id :                          String
    public var recipeID :                    String
    public var ingredientName :              String
    public var ingredientReplacement :       String
    public var measurementType :             String
    public var measurementQuantity :         Int
    public var storage :                     String

    public init(id: String, recipeID: String, ingredientName: String, ingredientReplacement: String, measurementType: String, measurementQuantity: Int, storage: String) {
        self.id = id
        self.recipeID = recipeID
        self.ingredientName = ingredientName
        self.ingredientReplacement = ingredientReplacement
        self.measurementType = measurementType
        self.measurementQuantity = measurementQuantity
        self.storage = storage
    }
}


text:
Q: Trouble passing data from a .yml file to a method in ruby I am having trouble passing data from a .yml file to a method to update tables in the db.
My file.yml looks like:
[
  { :emp_id: "123"},
  { "emp_acct": [{ :col_id: "22222", :age: "23"}]}
]

My file.rb looks like:
load_yaml()
update(@database, $x, $y, $z)

def load_yaml
 YAML.load_file("file.yml")
end

def YAML.load( io)
  yp = parser.load( io )
  $y = yp[0]  #I get:  {:emp_id=>"123"}
  $x = yp[1].keys   #I get:   :emp_acct
  $z = yp[1].values   #I get:  {:col=>"22222", :age=>"23"}
end

def modify(db, table, filter, opt)
  db[table].where(filter).update(opt)
end

I get this error:
"Failure/Error: modify(db, table, filter, opt)
  TypeError:
   can't convert Array into String"
Any idea what is going wrong here?

A: I think you want to parse this as JSON, because your file does not look like YAML. First you should fix the file, since a valid JSON will look like this:
[
  { "emp_id": "123"},
  { "emp_acct": [{ "col_id": "22222", "age": "23"}]}
]

In YAML the file should look like this:
---
  -
    emp_id: "123"
  -
    emp_acct:
      -
        col_id: "22222"
        age: "23"


text:
Q: Category page next page wordpress doesnt work Hi im having problems with my post category list next page, when i clicknext it goes to a sample page.
my personalize permalink is: /%category%/%post_id%/%postname%/
my site: http://hgps.org.do/prevencion_salud/
while( have_posts() ): the_post();
    ?>
    <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
        <?php echo avada_render_rich_snippets_for_pages(); ?>
        <?php if( ! post_password_required($post->ID) ): // 1 ?>
        <?php global $smof_data; if(!$smof_data['featured_images_pages'] ): // 2 ?>
        <?php
        if( avada_number_of_featured_images() > 0 || get_post_meta( $post->ID, 'pyre_video', true ) ): // 3
        ?>

                <?php if(get_post_meta($post->ID, 'pyre_video', true)): ?>

                        <?php echo get_post_meta($post->ID, 'pyre_video', true); ?>

                <?php endif; ?>
                <?php if( has_post_thumbnail() && get_post_meta( $post->ID, 'pyre_show_first_featured_image', true ) != 'yes' ): ?>
                <?php $attachment_image = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full'); ?>
                <?php $full_image = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full'); ?>
                <?php $attachment_data = wp_get_attachment_metadata(get_post_thumbnail_id()); ?>

                    <a href="<?php echo $full_image[0]; ?>" rel="prettyPhoto[gallery<?php the_ID(); ?>]" title="<?php echo get_post_field('post_excerpt', get_post_thumbnail_id()); ?>" data-title="<?php echo get_post_field('post_title', get_post_thumbnail_id()); ?>" data-caption="<?php echo get_post_field('post_excerpt', get_post_thumbnail_id()); ?>"><img src="<?php echo $attachment_image[0]; ?>" alt="<?php echo get_post_meta(get_post_thumbnail_id(), '_wp_attachment_image_alt', true); ?>" />

                <?php endif; ?>
                <?php
                $i = 2;
                while($i <= $smof_data['posts_slideshow_number']):
                $attachment_new_id = kd_mfi_get_featured_image_id('featured-image-'.$i, 'page');
                if($attachment_new_id):
                ?>
                <?php $attachment_image = wp_get_attachment_image_src($attachment_new_id, 'full'); ?>
                <?php $full_image = wp_get_attachment_image_src($attachment_new_id, 'full'); ?>
                <?php $attachment_data = wp_get_attachment_metadata($attachment_new_id); ?>

                    <a href="<?php echo $full_image[0]; ?>" rel="prettyPhoto[gallery<?php the_ID(); ?>]" title="<?php echo get_post_field('post_excerpt', $attachment_new_id); ?>" data-title="<?php echo get_post_field( 'post_title', $attachment_new_id ); ?>" data-caption="<?php echo get_post_field('post_excerpt', $attachment_new_id ); ?>"><img src="<?php echo $attachment_image[0]; ?>" alt="<?php echo get_post_meta($attachment_new_id, '_wp_attachment_image_alt', true); ?>" />

                <?php endif; $i++; endwhile; ?>


text:
Q: Read .dat file in binary mode in PowerShell to avoid conversion of special characters into garbage character I want to read a .dat file as binary stream in powershell. As I am new to Powershell, not able to figure out how it can be done.
After file being read as a binary stream and would like to replace the binary CRLF characters with LF..

A: You can use .Net $bytes = [System.IO.File]::ReadAllBytes("<YOUR FILE>") or Powershell $bytes = Get-Content -Path "<YOUR FILE>" -Encoding Byte -Raw to read the binary data as byte array (System.Byte[]).
If you convert that to ASCII string with $text = [System.Text.Encoding]::ASCII.GetString($bytes) you should be able to replace the CRLF to LF.
Something like this:
# read the binary data as byte array
$bytes = [System.IO.File]::ReadAllBytes("<YOUR FILE>")
# convert to ASCII string
$text = [System.Text.Encoding]::ASCII.GetString($bytes)

# replace the CRLF to LF
$text = $text -replace "`r`n", "`n"

# convert back to byte array
$bytes = [System.Text.Encoding]::ASCII.GetBytes($text)


text:
Q: Parse string using regex I need to come up with a regular expression to parse my input string. My input string is of the format:
[alphanumeric].[alpha][numeric].[alpha][alpha][alpha].[julian date: yyyyddd]

eg:
    A.A2.ABC.2014071
    3.M1.MMB.2014071

I need to substring it from the 3rd position and was wondering what would be the easiest way to do it.
Desired result:
A2.ABC.2014071
M1.MMB.2014071

A: Use this regex:
\w.[A-Z]\d.[A-Z]{3}.\d{7}

Use the above regex like this:
    String[] in = {
    "A.A2.ABC.2014071", "3.M1.MMB.2014071"
};

Pattern p = Pattern.compile("\\w.[A-Z]\\d.[A-Z]{3}.\\d{7}");
for (String s: in ) {
    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.println("Result: " + m.group().substring(2));
    }
}

Live demo: http://ideone.com/tns9iY

A: (?i) will be considered as case insensitive.
(?i)^[a-z\d]\.[a-z]\d\.[a-z]{3}\.\d{7}$

Here a-z means any alphabet from a to z, and \d means any digit from 0 to 9.
Now, if you want to remove the first section before dot, then use this regex and replace it with $1 (or may be \1)
(?i)^[a-z\d]\.([a-z]\d\.[a-z]{3}\.\d{7})$

Another option is replace below with empty:
(?i)^[a-z\d]\.

A: If the input string is just the long form, then you want everything except the first two characters.  You could arrange to substitute them with nothing:
s/^..//

Or you could arrange to capture everything except the first two characters:
/^..(.*)/

If the expression is part of a larger string, then the breakdown of the alphanumeric components becomes more important.
The details vary depending on the language that is hosting the regex.  The notations written above could be Perl or PCRE (Perl Compatible Regular Expressions).  Many other languages would accept these regexes too, but other languages would require tweaks.


text:
Q: Why this div is overlaping the one before? I dont really know how to ask it, dont know what error is this. Im very nob.
Im trying to order this divs, but the detalle_info is overlaping the one before (notice there white words).
Why is this happening? Thanks in advance.
http://tinyurl.com/cb8m37u

A: In #tabscontent your tabs2 and tabs3 DIVs are within the tabs1 DIV. Move them out of there and hopefully it should be fixed.

A: I see that the <div> with id namecost has a fixed height 30px, just remove it. Removing that height will make the div resizable depending on its content.

A: You are setting a height of 30px but the content doesn't fit in that height.

A: Make your blocks float, nothing more complicated.
Use float:left on your div.
By the way, you don't need a div per sentence.
(don't forget to put a clear:both at the end)


text:
Q: Nginx 404 pages request method is always GET When I post to a 404 page, nginx is stripping the post data and changing the request method to "GET". How do I prevent this? I have nginx configured to serve a php file as the error 404 page that is in the root of the domain directory. I would like to keep a log of whatever is posted to it.
nginx.conf
server {
        listen 80;
        error_page 404 = /404.php;
        set $oldhost $host;
        root /var/www/www/$oldhost;
        location ~* \.(?:ico|css|js|gif|jpg|png|html|htm)$ {
            expires 3d;
            add_header Pragma public;
            add_header Cache-Control "public";
        }
        location = /favicon.ico {
            log_not_found off;
            access_log off;
        }
        location = /robots.txt {
            allow all;
            log_not_found off;
            access_log off;
        }
        location / {
            index index.php index.htm index.html;
            try_files $uri $uri/ /index.php?$args;
        }
        location ~ .php$ {
            location ~ \..*/.*\.php$ {return 404;}
            expires 1d;
            add_header Pragma public;
            client_max_body_size 80m;
            add_header Cache-Control "public";
            fastcgi_pass   unix:/var/run/php5-fpm.sock;
            fastcgi_buffers 16 16k;
            fastcgi_buffer_size 32k;
            fastcgi_intercept_errors on;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
    }

A: This happens because when nginx cannot find a page, it will redirect (GET) the user to that 404.php page you defined.
What you need to do is to add it to the try_files directive, so nginx will try to post to it when it cannot find the others, or make it that you can handle 404 error directly on your index.php (like wordpress does).
EDIT:
 location / {
            index index.php index.htm index.html;
            try_files $uri $uri/ /index.php?$args 404.php 404.php?$args;
        }


text:
Q: Rank of a set, could you give me an example? I don't understand the definition of rank of a set.
The definition I have is:
For any set $V_{\infty}$, the rank of $x$, written $\rho(x)$, is the least ordinal $\alpha$ for which $x \in V_{\alpha^+}$
$V_{\infty}$ is the class of all sets which are in at least one of the $V_{\alpha}$s. I've found here https://ncatlab.org/nlab/show/cumulative+hierarchy a few examples, and in particular that the rank of $\{1\}$ is $2$, but how? $\rho(\{1\})$=$\rho(\{\{\emptyset\}\})$, and its not true that $2=\{\emptyset,\{\emptyset\}\}$ is the least ordinal for which $\{\{\emptyset\}\} \in V_{2^+}=V_3=\{\emptyset,\{\emptyset\},\{\emptyset,\{\emptyset\}\}\}$ what am i missing?

A: $\{\{∅\}\}∉V_0=∅$
$\{\{∅\}\}∉V_1=\{∅\}$
$\{\{∅\}\}∉V_2=\{∅,\{∅\}\}$
$\{\{∅\}\}∈V_3=\{∅,\{∅\},\{\{∅\}\},\{∅,\{∅\}\}\}$
So, the first stage where $\{1\}$ appear is $3=2+1$, so the rank of $\{1\}$ is $2$


text:
Q: Mysterious newline appears in Common Lisp format directive I'm running into an odd issue with Common Lisp's format directive that only shows itself in GNU CLISP, which leads me to wonder if it's a bug in the implementation.
Consider the following code
(defun f (s args)
  (format nil "~A~{~A~%~}" s args))

The function f produces a string consisting of the s argument, followed by each argument, where each argument (but not the header) is followed by a newline. So, for instance, I would expect
(format t "~A" (f "foo" '("arg1" "arg2")))

to produce
fooarg1
arg2

which it does, correctly. Now, consider the following calls
(format t "~A" (f "a" ()))
(format t "~A" (f "b" ()))
(format t "~A" (f "c" '("d")))

Given that the only newlines I ever print out are following elements from the second argument of f, and the first two calls pass an empty list for the second f argument, I expect to see no newlines until the very end, i.e. I expect this to print
abcd

It does exactly this in SBCL. However, in GNU CLISP, I get
ab
cd

Note the newline between b and c.
Changing the code to
(format t "~S" (f "a" ()))
(format t "~S" (f "b" ()))
(format t "~S" (f "c" '("d")))

shows the following, even less illuminating, results
"a""b"
"cd
"

So the newline between b and c is not part of either of the strings. Why is CLISP deciding to print a newline in between these format statements? And how can I prevent it from doing so?

A: This is a feature of GNU CLISP. See the documentation of *pprint-first-newline*.
If you want a different output than that, bind either *print-pretty* or *pprint-first-newline* to nil during your format invocation.


text:
Q: What kind of waste is a battery? Is there an efficient way of recycling or reusing waste batteries and where am I supposed to throw it (Biodegradable, Non-Biodegradable, and Recyclables) ?

A: Battery disposal 101
Waste batteries have different disposal requirements depending on the size and chemistry -- disposing of them with common waste is generally a mistake, but this mistake is more tolerable for some chemistries than others.  For bare coin/cylindrical cells or PP3 (9V) batteries of all chemistries though, a piece of electrical tape should be placed over the + electrode, or both electrodes for that matter, before disposing of the battery -- this prevents shorts in waste battery containers, which can lead to fires.  Short-circuit prevention is also important for lead-acid starting and marine deep-cycle batteries -- most small sealed-lead batteries and manufactured packs have connector/contact designs resistant to accidental shorts, though.
TL;DR:
Safe to dispose of in non-biodegradable household waste (but can be recycled with other batteries):

*

*Alkaline

*Carbon Zinc

*Lithium primary "AA" and "AAA" (LiFeS2)

*Lithium coin "CR" (LiMnO2)

*Zinc-Air

Should be recycled in a battery recycling stream (i.e. they won't do anything nasty to the landfill but would be silly to throw away or pose environmental hazards in large quantities):

*

*NiMH

*Silver Oxide (AgO)

Must be recycled in a dedicated battery recycling stream!:

*

*Lead-Acid (flooded and sealed/AGM)

*Nickel Cadmium (NiCd)

*Mercury primary

*Exotic lithium primary (LiCF, LiSOCl2)

*Lithium Ion/Polymer

Common (cylindrical/prismatic) primary chemistries (CZn, Alkaline, LiFeS2)
This covers AA, AAA, AAAA, C, D, and PP3 (9V) cells/batteries used in general applications.  A few rarer types such as N and A23 also fall here, as well as some photo batteries and coin cells that use alkaline chemistries.
These can be disposed of with other batteries in a battery recycling stream, or as general household waste (i.e. non-compostable/non-biodegradable) in most areas -- reputable primary cells of these types no longer contain mercury or other things that make them hazardous to dispose of.
Coin cell/watch battery primary chemistries (ZnAir, AgO, LiMnO2)
These chemistries are primarily found for coin cells and "watch" or "hearing aid" batteries.  Note that older or more oddball coin-type cells may contain more exotic chemistries such as Hg or LiCFx that must be disposed of in a dedicated battery recycling stream.
Silver oxide batteries should be disposed of in a battery recycling stream (as they contain valuable silver that can be recovered -- old ones had mercury in them, but the mercury containing types are no longer made by reputable manufacturers).  Common consumer lithium coin cells of the "CR" chemistry type (LiMnO2) and zinc-air cells can be disposed of either in a battery recycling stream or as general waste (again, non-biodegradable) in most areas.
Nickel based secondary chemistries (NiCd, NiMH)
Nickel based secondary chemistries include the obsolete NiCd (Nickel Cadmium) cells and more modern NiMH (Nickel Metal Hydride) cells.  The former are most commonly seen in old rechargeable battery packs used for power tools, portable equipment, and other miscellaneous applications, while the latter are both seen in smaller pack applications and as bare cells.  There are also flooded and recombinant NiCds used in some large format applications -- these are long-lived and not seen in the consumer world, so won't be discussed further here.
In the case of NiCd cells and packs, they must be recycled in a battery recycling stream due to the toxic cadmium in them.  NiMH batteries don't contain particularly toxic materials, but should be recycled as well to recover the nickel content, and can be problematic when disposed of in quantity.
Lead Acid secondary (sealed and flooded)
Lead Acid batteries must be recycled, for obvious reasons -- besides, they are simple and highly economic to recycle.  Automotive battery recycling has been the primary driver of battery recycling for over a century now, and you can even get a small return payment for turning in dead starting (car, motorcycle, boat, or small-aircraft) or deep-cycle lead-acid batteries in some locales.  Small-form sealed-lead cells don't have quite this many incentives, but should definitely be recycled as well!
Lithium Ion Secondary (LiIon/LiPo)
Lithium-ion secondary cells must be recycled, especially in larger form factors and quantities.  This is partly for environmental reasons and partly because household waste processing can mechanically damage (crush) cells, which has the potential to lead to a smoking trash truck or trash compactor/chute fire.  They also should not be mixed with lead-acid recycling streams -- most locations that accept nickel-based chemistries can deal with lithium-ion as well, though.
Exotics and miscellaneous chemistries
If you run into exotic or obsolete chemistries/configurations (flooded nickel cadmium or nickel iron, mercury primary, lithium metal secondary, lithium metal primary other than CR/LiMnO2 or FR/LiFeS2), send them to a dedicated battery recycler who deals with commercial/industrial batteries and be certain to include as much information about the chemistry as possible.  Also make sure to insulate the terminals!
Nickel zinc secondary and nickel oxyhydroxide primary cells can be recycled in a nickel battery stream, but do not pose undue disposal hazards in small quantities when disposed of in household non-biodegradable waste.  Water-activated batteries such as those found in radiosondes are intended to be disposed of as non-biodegradable household waste.


text:
Q: Android: how to deny access to the components of my application from other applications? Iwant to know how to deny access to the components of my application from other applications

A: By default android os don't allow other app to access your component. So you don't need to worry about it. You have to change permission in case you want to allow other app to access your component.


text:
Q: HTML - table how to use it to make a page I am trying to make something like this picture

Using Table and as little as possible of css can someone help me reach this result.
My current code is this

<!DOCTYPE html>

        <title>Mailing</title>
        <meta name="author" content="Ronald Dewindt">

Geachte klant,

Voor uw e-mail is een reset link aangevraagd voor het wijzigen van het e-mailadres bij Green-parking. Gebruik onderstaande link om het e-mailadres te bevestigen. U moet daarna met uw gewijzigde e-mailadres inloggen.

Klik hier om uw wachtwoord opnieuw in te stellen of kopieer en plak deze URL in de webbrowser: {$CallbackUrl}

Hartelijk dank dat u Greenparking gebruikt.

Met vriendelijke groet,

Het team van Greenparking

                ">

support@greenparking.nl

A: Used to this css

table{border-collapse: collapse;
    border-spacing: 0;
    border: 0;
    outline: 0;}
td {
    border: 0;
}

table > tbody > tr:first-child td {
    background: gray;
    line-height: 53px;
    text-align: center;
    vertical-align: top;
}
<!DOCTYPE html>

        <title>Mailing</title>
        <meta name="author" content="Ronald Dewindt">

Geachte klant,

Voor uw e-mail is een reset link aangevraagd voor het wijzigen van het e-mailadres bij Green-parking. Gebruik onderstaande link om het e-mailadres te bevestigen. U moet daarna met uw gewijzigde e-mailadres inloggen.

Klik hier om uw wachtwoord opnieuw in te stellen of kopieer en plak deze URL in de webbrowser: {$CallbackUrl}

Hartelijk dank dat u Greenparking gebruikt.

Met vriendelijke groet,

Het team van Greenparking

                ">

support@greenparking.nl


text:
Q: Determinate a continuous function given a few coordinates. Given a few Cartesian coordinate points $(x,y)$, for example: $(0, 1), (2, 3), (1, 4), (-1, -2),$ etc., is it possible determinate a function $y=f(x)$ that passes exactly for that points?

A: Given any set of points, we can have an infinite amount of functions which pass through them. We can do this 'naively' simply defining a function which has those values at those points then whatever values we want elsewhere. If you wanted a 'nice' function which goes through those points, the following polynomial will do:
$$
1 + (1 + (-2 - 2/3 (-1 + x)) (-2 + x)) x=\frac{-2}{3} x^3 \frac{11}{3} x+1
$$

A: You can do Lagrange interpolation to find the lowest degree polynomial that passes through the points.  If you have $n$ points, it will usually be of degree $n-1$.  The basic idea is to find a set of polynomials.  Each one is $1$ at one of your data points and $0$ at all the rest.  Then using the linearity of polynomials you construct the one that goes through your points.
For some purposes, a piecewise linear function between the points works well and requires less computation.  There are many other choices:  some people like cubic splines to avoid the corners.  Any numerical analysis book will have a discussion.


text:
Q: How to keep mail messages on servers for Apple mail? My "late 2013" Mac Pro has a small internal SSD. Since Yahoo Mail and Google Mail have large storage on their servers, I don't see reasons for me to store mail messages on my local SSD. Can Apple Mail client be configured in a way that it only stores, say, 1 month of mail messages locally? Then it can fetch older mail messages on demand. Can I configure Apple Mail to do that?

A: You can begin with Setting the Download Attachments to None in you Mac Mail.
That is the biggest part of mails anyway, the rest is just text.
If you are up to the task you can then export all attachments out of your Local storage.
They are located in ~/Library/Containers/com.apple.mail/Data/Library/Mail Downloads/
You can also Export all of the mail box, to for example iCloud.
It just makes a copy of it, so you can now delete mails on your Mac, and get them again later.
To do so right click on the mailbox and use Export.
Did you know that for $1/Month you can upgrade your iCloud to 50GB.

Now if you want to automate that, like keep emails for a month then Export, you will need a Automator process for that.


text:
Q: Create ..... When Overflow Occurs in Div I am using asp.net. i am trying to Insert data into the list view.My code smaple is like this:

                <asp:ListView ID="LatestRatingBusinessListView" runat="server">
                    <GroupTemplate>

                    </GroupTemplate>
                    <LayoutTemplate>

                    </LayoutTemplate>
                    <ItemTemplate>

                                    <a id="LatestRatingBusiness" href='<%#ResolveClientUrl("~/YellowPages/BusinessInstancePage.aspx?Menu=menu_cat_3594&bid=")+ Eval("BusinessID") %>'
                                        title="<%#Eval("BusinessName") %>" class="CategoryAndSubCategory">
                                        <%#Eval("BusinessName")%>

                    </ItemTemplate>
                </asp:ListView>

i have code behind like this:
  DataTable dt =  objYPReviewRatingDataAccess.GetLatestRatingOrderByOperationDate();
            LatestRatingBusinessListView.DataSource = dt;
            LatestRatingBusinessListView.DataBind();

in dt I have the Data like this
 BusinessID                  BusinessName
  000000001                  GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG
  000000002                  abcd
  000000003                  HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH

and i am trying to display the BusinessName like This
  GGGGGGGGGGGGGGGGGG...
  abcd
  HHHHHHHHHHHHHHHHHH...

I have no Idea of doing so I don't Want to Reject any of the character rather i just want to Show the Content with dot at the last when there is overflow.
How can i do this. Your Help means a lot to me.
Thank You
With Regard.

A: If I understand what you're asking, you can add the CSS property text-overflow: ellipsis to the objects you're talking about, which will add "..." to an overflowing text line before it's cut off.
Say you have a span:
Here's some text. Once the line becomes long enough, it will be cut off.

With this CSS:
.testspan {
     text-decoration: none;
    text-overflow: ellipsis;
    display: block;
    overflow: hidden;
    white-space: nowrap;
    width: 100px;
    height: 20px;
}

You get this:
Here's some t...

See the jsfiddle here: http://jsfiddle.net/8a9gB/


text:
Q: Understanding; for i in range, x,y = [int(i) in i.... Python3 I am stuck trying to understand the mechanics behind this combined input(), loop & list-comprehension; from Codegaming's "MarsRover" puzzle. The sequence creates a 2D line, representing a cut-out of the topology in an area 6999 units wide (x-axis).
Understandably, my original question was put on hold, being to broad. I am trying to shorten and to narrow the question: I understand list comprehension basically, and I'm ok experienced with for-loops.
Like list comp:
 land_y = [int(j) for j in range(k)]
    if k = 5;    land_y = [0, 1, 2, 3, 4]

For-loops:
for i in the range(4)
    a = 2*i       = 6
    ab.append(a)  = 0,2,4,6

But here, it just doesn't add up (in my head):
6999 points are created along the x-axis, from 6 points(x,y).
  surface_n = int(input())
  for i in range(surface_n):

      land_x, land_y = [int(j) for j in input().split()]

I do not understand where "i" makes a difference.
I do not understand how the data "packaged" inside the input. I have split strings of integers on another task in almost exactly the same code, and I could easily create new lists and work with them - as I understood the structure I was unpacking (pretty simple being one datatype with one purpose).
The fact that this line follows within the "game"-while-loop confuses me more, as it updates dynamically as the state of the game changes.
   x, y, h_speed, v_speed, fuel, rotate, power = [int(i) for i in input().split()]

Maybe someone could give an example of how this could be written in javascript, haskell or c#? No need to be syntax-correct, I'm just struggling with the concept here.

A: input() takes a line from the standard input. So it's essentially reading some value into your program.
The way that code works, it makes very hard assumptions on the format of the input strings. To the point that it gets confusing (and difficult to verify).
Let's take a look at this line first:
land_x, land_y = [int(j) for j in input().split()]

You said you already understand list comprehension, so this is essentially equal to this:
inputs = input().split()
result = []
for j in inputs:
    results.append(int(j))
land_x, land_y = results

This is a combination of multiple things that happen here. input() reads a line of text into the program, split() separates that string into multiple parts, splitting it whenever a white space character appears. So a string 'foo bar' is split into ['foo', 'bar'].
Then, the list comprehension happens, which essentially just iterates over every item in that splitted input string and converts each item into an integer using int(j). So an input of '2 3' is first converted into ['2', '3'] (list of strings), and then converted into [2, 3] (list of ints).
Finally, the line land_x, land_y = results is evaluated. This is called iterable unpacking and essentially assumes that the iterable on the right has exactly as many items as there are variables on the left. If that's the case then it's just a nice way to write the following:
land_x = results[0]
land_y = results[1]

So basically, the whole list comprehension assumes that there is an input of two numbers separated by whitespace, it then splits those into separate strings, converts those into numbers and then assigns each number to a separate variable land_x and land_y.
Exactly the same thing happens again later with the following line:
x, y, h_speed, v_speed, fuel, rotate, power = [int(i) for i in input().split()]

It's just that this time, it expects the input to have seven numbers instead of just two. But then it's exactly the same.


text:
Q: Esta operacion con if me da un fallo Por que ponga lo que ponga en el prompt el resultado es que mi instrumento es de viento? no encuentro el error.

let musica = prompt("Que instrumento tocas?");

if (musica === "saxofón" || "flauta" || "clarinete" || "trompeta" || "oboe") {
  console.log(`${musica} es un instrumento de viento`);
} else if (musica === "guitarra" || "arpa" || "violín" || "piano") {
  console.log(`${musica} es un instrumento de cuerda`);
} else if (musica === "timbal" || "tambor" || "platillos" || "bombo") {
  console.log(`${musica} es un instrumento de percusion`);
} else if (musica === "bajo electrico" || "guitarra eléctrica" || "theremín" ||
  "sintetizado") {
  console.log(`${musica} es un instrumento electrico`);
} else {
  console.log(`${musica} tiene un error vuelvelo a completar`)
}

A: Entre cada '||' debes poner otra vez el comparador

musica = prompt("Que instrumento tocas?");

if (musica == "saxofón" || musica == "flauta" || musica == "clarinete" || musica == "trompeta" || musica == "oboe") {
  console.log(`${musica} es un instrumento de viento`);
} else if (musica == "guitarra" || musica == "arpa" || musica == "violín" || musica == "piano") {
  console.log(`${musica} es un instrumento de cuerda`);
} else if (musica == "timbal" || musica == "tambor" || musica == "platillos" || musica == "bombo") {
  console.log(`${musica} es un instrumento de percusion`);
} else if (musica == "bajo electrico") {
  console.log(`${musica} es un instrumento electrico`);
} else {
  console.log(`${musica} tiene un error vuelvelo a completar`)
}

A: Podrías crear arrays independientes por cada tipo de instrumento y comporbar si el valor introducido esta en alguna de ellas.

let instrumento = prompt("Que instrumento tocas?");

let instrumentosViento = ["saxofón", "flauta", "clarinete", "trompeta", "oboe"];
if (instrumentosViento.includes(instrumento)) {
  console.log(`${instrumento} es un instrumento de viento`);
}


text:
Q: Ignore quote in SQL query in VB.NET I have a method within a class that writes all of the rows and columns from a table in my database. However, when I try to fetch data from myTable in my DB with readAllFromTable("myTable", myDataGridView) it fails because the selected table is wrapped around quotes, so the query looks like this:

SELECT * FROM "mytable"

...When it I need it to look like this:

SELECT * FROM mytable

Source code:
 Public Sub readAllFromTable(table As String, datagrid As DataGridView)
    Dim sda As New MySqlDataAdapter
    Dim dbDataSet As New DataTable
    Dim bSource As New BindingSource
    Dim sql As String = "SELECT * FROM @table"

    sqlQuery = New MySqlCommand(sql, login.connection)
    sqlQuery.Parameters.AddWithValue("@table", table)

    sda.SelectCommand = sqlQuery
    sda.Fill(dbDataSet)
    bSource.DataSource = dbDataSet
    datagrid.DataSource = bSource
    sda.Update(dbDataSet)
End Sub