text:
Q: Passing order-dependent array into ActiveRecord's find() method Simple statement of the problem:
The ActiveRecord documentation shows that you can pass several values into the object find() method, as follows:
Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
My issue is that the objects returned are insensitive to the order of the values you pass in.
For instance, Person.find(1, 2, 6) returns exactly the same thing as Person.find(6, 1, 2).
Is there any way to make this kind of search order sensitive?
It feels like there should be a way to pass in an array of id and get an array of Person objects back in the same order...
Broader context, for those interested in reading on:
Really what I'm looking to do more generally, is find the "most viewed" Person objects for a given time period.
Here's what I've got:
@most_viewed = View.where('created_at < ?', Time.now - 1.week).group(:person_id).order('count_person_id desc').count('person_id').keys

This returns an (ordered!) array of id values for Person objects, in descending order of number of Views each Person has received in the last week.
My thinking was, if I could pass this array of ids into the Person.find method, then I'm home free! But maybe there's another way entirely to do it more easily. I'm open to all thoughts.
Thanks!

A: Instead of returning ids from your query you can return the views itself.
@most_viewed = View.where('created_at < ?', Time.now - 1.week)
  .group(:person_id).order('count_person_id desc').includes(:person)

Now you have the persons ordered, but you just have to access them through @most_viewed variable.
@most_viewed.each do |view|
  # do something with view.person
end

Edit:
If the solution above is not working for you, you can order the persons in this way
Person.find([6, 1, 2]).index_by(&:id).slice(*[6, 1, 2]).values

But the order is happening in ruby, not in the query.


text:
Q: A nice example of a functor naturally ismorphic to Stone-functor. I want to explain the natural transformation with an example involving the Stone functor, but, I can't think of any non-trivial one. Does any one have one?

A: (For those who, like me, did not know what the Stone functor was, this is the contravariant functor from topological spaces to Boolean algebras that assigns, to each topological space, the Boolean algebra of its clopen sets with union and intersection operations.)
There is a contravariant functor from topological spaces to commutative unital rings given by $X \mapsto C(X)$ that sends a topological space to its ring of continuous real-valued (or complex-valued, if you prefer) functions.
There is a covariant functor from commutative unital rings to Boolean algebras, which sends a ring $R$ to the set of its idempotents, using the following operations on two idempotents $e, f \in R$:

*

*$e \vee f = e + f - ef$

*$e \wedge f = ef$

*The "bottom" and "top" elements are $0$ and $1$, respectively.

Now an exercise for you: prove that the Stone functor is naturally isomorphic to the composite $\mathbf{Top}^{op} \to \mathbf{cRing} \to \mathbf{Boolean}$ of the two functors defined above.  A healthy hint for you: the isomorphism between these two Boolean algebras should send a clopen subset $K \subseteq X$ with the characteristic function $\chi_K$ (whose value is $1$ on $K$ and $0$ on $X \setminus K$).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Postgres: Is it possible to show only one entry when duplicate occurs? I have a postgres database with duplicated entries. I would like to show the created_by columns and the
id | name    | created_on
1  | 'Hello' | 3/29
2  | 'Hey'   | 4/3
3  | 'Hello' | 3/31
4  | 'Hey'   | 4/1

As 'Hello' and 'Hey' is duplicated, I would like to form a single query to list the following:
id | name    | created_on
2  | 'Hey'   | 4/3
3  | 'Hello' | 3/31

How could I form that SQL query?
Actually I tried putting 'DISTINCT ON' and 'ORDER BY' in a single query (with JOIN) it gives me the following error:
SELECT DISTINCT ON expressions must match initial ORDER BY expressions

Thanks in advance

A: Try this:
SELECT t1.*
FROM tablename AS t1
INNER JOIN
(
  SELECT name, MAX(created_on) AS MaxDate
  FROM tablename
  GROUP BY name
) AS t2  ON t1.name       = t2.name
        AND t1.created_on = t2.maxdate;

SQL Fidle Demo

A: Try this query
select
  a.*
from
  table1 a
inner join
  (select
     name,
     max(created_on) as date
  from
     table1
  group by
     name)b
on
  a.name = b.name AND
  a.created_on = b.date

FIDDLE

A: SQL Fiddle
select distinct on (name)
    id, name, created_on
from tablename
order by name, created_on desc

If you need it ordered by id:
select *
from (
    select distinct on (name)
        id, name, created_on
    from tablename
    order by name, created_on desc
) s
order by id


text: Q: How attach a native thread to a running CLRhost? With JNI code I can attach a native thread to the JVM and execute whatever I want. How do I do the same on the .NET CLR? I can't find any such function here: http://msdn.microsoft.com/en-us/library/ms404385.aspx


text:
Q: Select text between 2 complete span tags using regex Take the following:
1. Lorem Ipsum *

I am trying to create a regex expression that will select:
1.

AND
*

Regex expressions like ^(<span(.*)<\/span>)$ select all of the text.
What expression will select the two complete tags and ignore the loose text between them? (Lorem Ipsum)

A: Regex is not good way to find HTML tags. But this should work for you-
<\s*span[^>]*>(.*?)<\s*\/\s*span>

DEMO: https://regex101.com/r/vbLN9L/6


text:
Q: jfree chart custom label i would like to personilize my label of data in my Pie Chart, beacause in my legend i see data=value, in label i see data=value.
how i do to see  only name data in legend and value in label?
my code for paint a chart is this:
    public JfreeChart(String applicationTitle, String chartTitle)throws SQLException {
    super(applicationTitle);
    JFreeChart barChart = null;
    dataset=createDataset(conn,barChart);

    barChart = ChartFactory.createPieChart(chartTitle,dataset, true, true, false);
    ChartPanel chartPanel = new ChartPanel(barChart);
    PiePlot plot = new PiePlot(dataset);
    plot.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    plot.setNoDataMessage("No data available");
    plot.setCircular(true);
    plot.setLabelGap(0.02);

    chartPanel.setPreferredSize(new java.awt.Dimension(560, 367));
    setContentPane(chartPanel);
    try {
        ChartUtilities.saveChartAsPNG(new File("directory"), barChart, 600,450);
        writeChartToPDF(barChart, 600, 450,"C:\\Users\\axs0552\\Desktop\\grafico.pdf");
    } catch (IOException ex) {
        System.out.println(ex.getLocalizedMessage());
    }
}

public static void writeChartToPDF(JFreeChart chart, int width, int height,
        String fileName) {
    PdfWriter writer = null;

    Document document = new Document();

    try {
        writer = PdfWriter.getInstance(document, new FileOutputStream(
                fileName));
        document.open();
        PdfContentByte contentByte = writer.getDirectContent();
        PdfTemplate template = contentByte.createTemplate(width, height);
        Graphics2D graphics2d = template.createGraphics(width, height,new DefaultFontMapper());
        Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width,height);

        chart.draw(graphics2d, rectangle2d);

        graphics2d.dispose();
        contentByte.addTemplate(template, 0, 0);

    } catch (Exception e) {
        e.printStackTrace();
    }
    document.close();
}

and my pie chart is this:

A: Absent your implementation  of createDataset(), I'm guessing that the problem comes from the key passed to the setValue() method of your DefaultPieDataset. Instead, use the MessageFormat symbol {1} to construct a custom StandardPieSectionLabelGenerator, as shown here.
PiePlot plot = (PiePlot) chart.getPlot();
PieSectionLabelGenerator gen = new StandardPieSectionLabelGenerator("{0} = {1}");
plot.setLabelGenerator(gen);

Then you can elide the unwanted characters from your implementation  of createDataset() to keep them out of the legend requested in your invocation of ChartFactory.createPieChart().


text:
Q: Using Windsor 3.0+ xml configuration, how can I register multiple types for a service? I know I can register a single type for a component like so:
<component
    id="myservice"
    service="MyServices.IService"
    type="MyServices.Impl.Service1" />

Imagine a scenario where I have a class that takes an array of IService like so:
public class MyClass
{
    public MyClass(IService[] services) { ... }
}

How do I register, for example, Service1, Service2 and Service3 for the IService component using XML configuration?

A: <component
    id="myservice1"
    service="MyServices.IService"
    type="MyServices.Impl.Service1" />
<component
    id="myservice2"
    service="MyServices.IService"
    type="MyServices.Impl.Service2" />
<component
    id="myservice3"
    service="MyServices.IService"
    type="MyServices.Impl.Service3" />

Or if you want to be more compact:
<component service="IService" type="Service1" />
<component service="IService" type="Service2" />
<component service="IService" type="Service3" />


text:
Q: why string nam is not inside in this dyn_sprintf command? I was going through a pre written program where I find sprintf command.
if(IFROOT){
str1="bicoted; diameter(d):;
str2=dyn_sprint(", distance=" GFORM, diskratio);
}

here, str1 and str2 are initialized as strings,
GFORM is defined as "%.10g" and diskratio is a variable.
IFROOT is a flag
please help me to understand how str2=dyn_sprint(", distance=" GFORM, diskratio) is working


text:
Q: Regex for standard guitar lyric/chord bracketing I am trying to add square brackets around chords in standard text documents formatted for guitar/lyrics to make them more compatible with the OnSong app.  I have the rules but don't understand how to match for all the possible combinations.  The rules are:

*

*Chords will begin with a single capital A-G

*if the capital A-G is followed by a space, line break, #, b, m, sus, aug, dim, maj, min, or / I'd like to read until the next whitespace or line break (because of standard guitar formatting, a chord like F#min/E is possible, and rather than bother splitting it all out, I just want to keep reading until space)

*The regex should NOT match if the capital A-G is followed by another letter not in the list above (for example the name "Ed" should not match)

*bonus points if you can figure out how to make "A small world" NOT match due to the word FOLLOWING the "A" not being a valid chord.

*super bonus points if the replacement can remove a space before (when not starting a line) and after the new brackets (to keep alignment in place) - it was pointed out to me that this will fail on close chords... this is completely acceptable.

A couple notes:  This is for a helper script... perfection is not needed.  I do this by hand right now, so the occasional miss is okay.  I'm not trying to parse out the details of the chords, just to wrap them in [].  While the standard layout is 1 row of chords, 1 row of lyrics, this can't be counted on, so I'm aware some scenarios will fail occasionally.
Test source (chords are random for testing purposes, in case any musicians were going to chime in on the terrible music):
Db    Dsus4/F#           A            Cbmin/C
A man can't be asked for that much to do
D/F#        G         A           D#/E
And I can't sweep you off of your feet

Should turn into:
[Db]  [Dsus4/F#]         [A]          [Cbmin/C]
A man can't be asked for that much to do
[D/F#]      [G]       [A]         [D#/E]
And I can't sweep you off of your feet

My first attempt got me close with:
([A-G]((?!\s).)*)

but that picked up words that began with those letters as well.  I have gone around in circles now and only gotten as far as:
\b([CDEFGAB](#|##|b|bb|sus|maj|min|aug)?\b)

When I've tried to use [^\s+] I get mixed results that pick up more of what I want but also ditch things I need.  I think I'm just over my head.  Any help would be GREATLY appreciated and any explanation of how it works would be even better.  While I'd like a solution, I'd also really love to explain why it works...

A: This passes using your sample input and achieves all your "super bonus points" requirements:
String output = input.replaceAll("(?m)(^| )([A-G](##?|bb?)?((sus|maj|min|aug|dim)\\d?)?(/[A-G](##?|bb?)?)?)( (?!\\w)|$)", "[$2]");

This code turns this (as a single String with embedded line fees):
Db    Dsus4/F#           A            Cbmin/C
A man can't be asked for that much to do
D/F#        G         A           D#/E
And I can't sweep you off of your feet

Into this:
[Db]  [Dsus4/F#]         [A]          [Cbmin/C]
A man can't be asked for that much to do
[D/F#]      [G]       [A]         [D#/E]
And I can't sweep you off of your feet

A: I have some working regex for the case you provided, but not sure how it will work for others. The problem is that a line can start with A, or it can be in the song line. I tried to work around it using the negative lookahead checking if the chord is followed by a space and an alphanumeric. If there is a space and an alphanumeric, we do not match this chord. Since the chords can repeat after /, I am doubling the pattern.
\b([CDEFGAB](?:b|bb)*(?:#|##|sus|maj|min|aug)*[\d\/]*(?:[CDEFGAB](?:b|bb)*(?:#|##|sus|maj|min|aug)*[\d\/]*)*)(?=\s|$)(?! \w)
Have a look at the demo.

A: Check this out:
/([A-G](#|b)?)(\(?(M|maj|major|m|min|minor|dim|sus|dom|aug)?(\+|-|add)?\d*\)?)(\/([A-G](#|b)?))?/g

I've took it from chord-transposer:
var XRegExp = require("xregexp");

// Chromatic scale starting from C using flats only.
var FLAT_SCALE = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "Cb"];

// Chromatic scale starting from C using sharps only.
var SHARP_SCALE = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];

// Regex for recognizing chords
var ROOT_PATTERN = '(?<root>[A-G](#|b)?)';

var SUFFIX_PATTERN = '(?<suffix>\\(?(M|maj|major|m|min|minor|dim|sus|dom|aug)?(\\+|-|add)?\\d*\\)?)';

var BASS_PATTERN = '(\\/(?<bass>[A-G](#|b)?))?';

var MINOR_PATTERN = '(m|min|minor)+';

var CHORD_REGEX = XRegExp("^" + ROOT_PATTERN + SUFFIX_PATTERN + BASS_PATTERN + "$");

and then
console.log(CHORD_REGEX); // will output regexp mentioned at the beginning of the answer

It works great for me.

A: I have improved a little bit the answer from previous answer to help in my case. Now It was ignoring some "chords likely" when it is in the beginning of the verse (like A, E).
This what I came out:
(\(*[CDEFGAB](?:b|bb)*(?:#|##|sus|maj|min|aug|m|M|°|[0-9])*[\(]?[\d\/]*[\)]?(?:[CDEFGAB](?:b|bb)*(?:#|##|sus|maj|min|aug|m|M|°|[0-9])*[\d\/]*)*\)*)(?=[\s|$])(?! [a-z])

A: the code executes the agreement well in the sample I checked and Agreements simplesles 7th agreements with sharp or flat like C # 7
string strRegex = @"^[A-G]([5679bm#]([57])?|1[13]|6\/9|7[-#+b][59]|7?sus[24]|add[249]|aug|dim7?|m\/maj7|m1[13]|m[679]|m7?b5|maj1[13]|maj[79])?([\/][A-G]([5679bm#])?([57])?)?";

Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = @"A";
string strReplace = @"[$0]";

return myRegex.Replace(strTargetString, strReplace);


text:
Q: ng-cli/rxjs: multiple Observable modules? I am trying to use a observable for the first time.  i'm using angular-cli to build/serve my project: when I serve my app I get the following error.  Any idea what this means? Why would there be two observable modules?  i'm using this to handle a rest response from a local server but it seems like I might be getting back the wrong observable as i'm getting a NET_ERR as response...
my error:

lang.js:124Angular 2 is running in the development mode. Call
  enableProdMode() to enable the production mode.
      client:38[WDS] Warnings while compiling.
      client:73./~/rxjs/Observable.js
      There are multiple modules with names that only differ in casing.
      This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
      Use equal casing. Compare these module identifiers:
      * C:\Users\Deon\Documents\trade-link\barcode-checker\node_modules\rxjs\Observable.js
          Used by 6 module(s), i. e.
          C:\Users\Deon\Documents\trade-link\barcode-checker\node_modules\@angular\core\src\facade\async.js
      * C:\Users\Deon\Documents\trade-link\barcode-checker\node_modules\rxjs\observable.js
          Used by 1 module(s), i. e.
          C:\Users\Deon\Documents\trade-link\barcode-checker\node_modules\awesome-typescript-loader\dist\entry.js?{"useForkChecker":true,"tsconfig":"C:\Users\Deon\Documents\trade-link\barcode-checker\src\tsconfig.json","externals":["C:/Users/Deon/Documents/trade-link/barcode-checker/src/app/app.component.spec.ts","C:/Users/Deon/Documents/trade-link/barcode-checker/src/app/app.component.ts","C:/Users/Deon/Documents/trade-link/barcode-checker/src/app/app.module.ts","C:/Users/Deon/Documents/trade-link/barcode-checker/src/app/Components/product/product.component.spec.ts","C:/Users/Deon/Documents/trade-link/barcode-checker/src/app/Components/product/product.component.ts","C:/Users/Deon/Documents/trade-link/barcode-checker/src/app/index.ts","C:/Users/Deon/Documents/trade-link/barcode-checker/src/app/models/product.model.ts","C:/Users/Deon/Documents/trade-link/barcode-checker/src/app/services/rest.service.spec.ts","C:/Users/Deon/Documents/trade-link/barcode-checker/src/app/services/rest.service.ts","C:/Users/Deon/Documents/trade-link/barcode-checker/src/environments/environment.prod.ts","C:/Users/Deon/Documents/trade-link/barcode-checker/src/environments/environment.ts","C:/Users/Deon/Documents/trade-link/barcode-checker/src/main.ts","C:/Users/Deon/Documents/trade-link/barcode-checker/src/polyfills.ts","C:/Users/Deon/Documents/trade-link/barcode-checker/src/test.ts","C:/Users/Deon/Documents/trade-link/barcode-checker/src/typings.d.ts"],"doTypeCheck":true,"sourceMap":true,"verbose":false}!C:\Users\Deon\Documents\trade-link\barcode-checker\node_modules\angular2-template-loader\index.js!C:\Users\Deon\Documents\trade-link\barcode-checker\src\app\services\rest.service.tswarnings
  @ client:73
      error_handler.js:48EXCEPTION: Error in ./AppComponent class AppComponent - inline template:5:42 caused by: this.http.get(...).map
  is not a functionErrorHandler.handleError @ error_handler.js:48
      error_handler.js:50ORIGINAL EXCEPTION: this.http.get(...).map is not a functionErrorHandler.handleError @ error_handler.js:50
      error_handler.js:53ORIGINAL STACKTRACE:ErrorHandler.handleError @ error_handler.js:53
      error_handler.js:54TypeError: this.http.get(...).map is not a function
          at RestService.getProduct (rest.service.ts:13)
          at AppComponent.submitBarcode (app.component.ts:25)
          at _View_AppComponent0._handle_click_9_0 (component.ngfactory.js:111)
          at view.js:365
          at dom_renderer.js:262
          at dom_events.js:30
          at ZoneDelegate.invoke (zone.js:232)
          at Object.onInvoke (ng_zone.js:238)
          at ZoneDelegate.invoke (zone.js:231)
          at Zone.runGuarded (zone.js:128)ErrorHandler.handleError @ error_handler.js:54
      error_handler.js:57ERROR CONTEXT:ErrorHandler.handleError @ error_handler.js:57
      error_handler.js:58DebugContextErrorHandler.handleError @ error_handler.js:58
      zone.js:158Uncaught ViewWrappedError

RestService: (Which uses the observable)
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions  } from "@angular/http";
import { Observable } from  "rxjs/observable";
import { ProductModel } from "../models/product.model";

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw'

@Injectable()
export class RestService {
public API_URL: string = "http://10.60.160.34/BRMServices/WebEnquiry/";
private headers: Headers;
private options: RequestOptions;

  constructor(private http: Http){
      this.init();
  }

  init() {
      this.headers = new Headers({ 'Content-Type': 'application/json' });
      this.options = new RequestOptions({ headers: this.headers });
  }

  getProduct(barcode: string): Observable<ProductModel> {

      return this.http.get(this.API_URL + "/POSEnquiry/" + barcode, this.options)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
}

app.component.ts:
import { Component } from '@angular/core';

import { RestService } from "./services/rest.service";
import { ProductModel } from "./models/product.model";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

    product: ProductModel;

    constructor(private restService: RestService){

    }

submitBarcode(barcode: HTMLInputElement){

    this.restService.getProduct(barcode.value)
    .subscribe(
    (res) => {
        //product = res;
        console.log(res);
    },
    (res) => {
        console.log("failure" + res);
    }
    );
    //console.log("product: " + product);
}

}

A: The error occures because it cannot find map in the references.

TypeError: this.http.get(...).map is not a function at
  RestService.getProduct (rest.service.ts:13)

In this case I would suggest to use import { Observable } from 'rxjs/Rx' instead of import { Observable } from  "rxjs/observable"; and all import 'rxjs/add/...'. this will remove the warning of two observable modules with different casing.
Could you also use RequestOptionsArgs instead of RequestOptions. I think this will resolve the error. (When I compare my code with yours these are the only difference)


text:
Q: How to build an editable text document with its base content dynamically generated? I have a relational database (PostgreSQL 8.4) of around 3000 products proposed by a company. The database is used to display the products in the company's website (running on a python 2.6 application).
My final goal is to build a PDF file in order to print a paper version of the products catalog and I would like to know what technology to use for that purpose.
The operation will have to be repeated once a year for every new catalog so I would like to automate the catalog generation but still give some flexibility because I won't stay in the company forever and there is no technical person that will replace me after (small company, small budget).
Ideally, I would like to generate dynamically the structured content of the 3000 products in a text editor (like OpenOffice for example) for the following reasons:

*

*content is generated dynamically so no need to retype everything

*only the content structure is generated dynamically and not the styling so a non-technical user is able to customize styles.

*the document being editable, it is easy for a non-technical user to add pages in the catalog like a welcome page, a note page, the terms and conditions.
In other words, text editors are great, I don't want to reinvent the wheel but I don't want a person to retype all data for the 3000 products.

Soutions first looked:

*

*I had a look at LaTeX but it seem that the data and the styling are mixed together in opposition to HTML and CSS which clearly separate content and styling which I find much more easy to use.

*I thought about using directly HTML and CSS but it might too technical.

*I also looked at a library allowing to generate PDF directly from python like ReportLab (http://www.reportlab.com/software/documentation/tutorial/product-catalogue/). This, however, does not allow to modify anything once the PDF is build and a little modification might required a technical person.

So if you have an idea for this kind of job then I would be very happy to get some tips about the right technologies. Thank you very much.

A: Approach in LaTeX
General
LaTeX does allow to separate content from styling, as it is a markup language (and feels pretty like HTML and CSS if you are coming from it).
http://en.wikipedia.org/wiki/Markup_language#TeX
http://en.wikibooks.org/wiki/LaTeX/Modular_Documents#Getting_LaTeX_to_process_multiple_files

This way you can put all the formatting options in your base file and then input or include the files which contain the actual content of your work. This means that the important part of your working process, i.e. writing, is kept largely separate from formatting choices (which is one of the main reasons why LaTeX is so good for serious writing!) You will thus be dealing solely with text and very basic commands such as \section, \emph etc. Your document will be uncluttered and much easier to work with..

The commands \input{filename} and \include{filename} insert text files (with or without LaTex commands).
For more customization you would need own macro(s) to read the content files and style them accordingly.
Some resources on defining macros (I can´t provide the linked hyperlinks because of my reputation right now):
en.wikibooks.org/wiki/LaTeX/Macros
en.wikibooks.org/wiki/LaTeX/Creating_Packages
One specific example
I´ve written a software documentation, the actual source code was stored in separate files. The lstinputlisting package reads the source code and outputs it in a "styled way".
\lstinputlisting[caption=My caption]{sourcefile.lang}

A: OpenDocument Format (ODF) approach
Why:

*

*It is an open format, which is guarantee for long term solution, and it comes with no cost (small company, small budget).

*It separates content and style.

*There are mature free and open source software compatible with it: OpenOffice.org, LibreOffice. And these are easy to use for non-programmer users.

How:
The ODF format is quite complex but some libraries already exist to help generating files, and there are some available in Python: odfpy, lpod,JODreports, Apache odf toolkit, ...
And they seem to do the job!
Simliar question but for Java

A: What you are looking for is called database publishing. This can be done with a batch formatter (e.g. TeX or XSL-FO) or -- if you need don't want 100% automation -- with addons for DTP programs like InDesign and Quark.

A: Database publishing
Yes, as Martin Schroeder points out this is about database publishing. A recent similar specific question is about using the pod tool to generate LibreOffice ODT files.
The pod approach uses Python. Python statements are in the ODF template file. You might use the approach with any scripting language.
LibreOffice Writer has as well a 'flat XML' file format. A database publishing batch process needs to replace certain place holders with XML code generated from the database.
This might be done by an interpreter which goes through your 'flat XML' file and looks for certain keywords or commands and then executes them.
Advantage
The advantage of this approach is that a general user can alter the report just by using LibreOffice. Insertion commands which are interpreted by your batch program may be easily placed at the right place. These command may have the form of a DSL.


text: Q: Gradient norm in a neural network is bounded? Consider a fully connected neural network with single hidden layer $f(x,w) = w^T_2 \sigma(w^T_1 x) $ where $w = [ w_2, w_1 ]$ are networks' parameters and $\sigma$ is an activation function (e.g tanh, sigmoid, relu).  Let $l(f(x,w), y)$ be the binary cross entropy loss. Is that true that for a particular data point $x$, the gradient norm of the loss function $\| \nabla_w l(f(x,w),y)\|_2 \leq C$  is always bounded over all choices of model parameters $w$.


text:
Q: can't able to delete selected item in a listView via context menu? I'm trying to delete the selected item in listview through Context menu.
here is my code.
public class MainActivity extends AppCompatActivity
{
EditText editText;
Button add;
ListView listView;
final DBFunctions db=new DBFunctions(MainActivity.this);
ArrayAdapter<String> adapter;
String[] values;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editText= (EditText) findViewById(R.id.editText);
    add= (Button) findViewById(R.id.button);
    listView= (ListView) findViewById(R.id.listView);
    values=db.getAlldata();
    adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,values);
    listView.setAdapter(adapter);
    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String name = editText.getText().toString();
            if (!name.equals("")) {
                editText.setText("");
                long check = db.insertData(name);
                if (check < 0) {
                    Toast.makeText(MainActivity.this, "Error in insert query", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, name + " inserted", Toast.LENGTH_SHORT).show();
                }
                adapter.notifyDataSetChanged();
            } else {
                editText.setError("this field is empty");
            }
        }
    });

    registerForContextMenu(listView);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
    getMenuInflater().inflate(R.menu.menu_main, menu);
    super.onCreateContextMenu(menu, v, menuInfo);
}

@Override
public boolean onContextItemSelected(MenuItem item)
{
    int position=listView.getSelectedItemPosition();
    String data=values[position];                    //error line
    Log.e("Value  ", data );
    Log.e("Position ", position+"" );
    switch (item.getItemId())
    {
        case R.id.delete_name:
            long check=db.deleteData(data);
            if(check<0)
            {
                Toast.makeText(MainActivity.this,"Error in query",Toast.LENGTH_SHORT).show();
            }
            else
            {
                adapter.notifyDataSetChanged();
                Toast.makeText(MainActivity.this,data+" deleted",Toast.LENGTH_SHORT).show();
            }
            return true;
        default :
            return super.onContextItemSelected(item);
    }
}
}

when i run above code i get following error:
 java.lang.ArrayIndexOutOfBoundsException: length=3; index=-1
        at pack.madhan.listviewdemo.MainActivity.onContextItemSelected(MainActivity.java:72)
        at android.app.Activity.onMenuItemSelected(Activity.java:2628)
        at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:353)
        at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:144)
        at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:99)
        at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:3864)
        at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:741)

is it possible to delete selected item in listview via context menu ?
please help me on this.

A: Based on the logstack, your function listView.getSelectedItemPosition() returns -1.
int position=listView.getSelectedItemPosition();

java.lang.ArrayIndexOutOfBoundsException: length=3; index=-1

-1 is not a correct index, and is the cause of this OutOfBoundsException.
I've never tried to keep track of the latest element selected in a list, but you could do as follow :
Add a variable at the begining of your MainActivity to keep track of the selectedItem;
// First item of the list is selected by defaul to avoid out of bound
int selectedItem = 0;

And update this variable with the onItemClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
      selectedItem = id;
   }
});

A: finally i found an answer
Error Code:
int position=listView.getSelectedItemPosition();
String data=values[position];

Updated Code:
AdapterView.AdapterContextMenuInfo info= (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

String data=values[info.position];

where info.position gives the position of item in listView.
To refer click here


text:
Q: Can SG teams travel to different galaxies without extra power or an 8th chevron? In the tie-in of SG-1 and Atlantis, they had to use a ZPM to power the gate, and use an eighth chevron to travel to the Pegasus Galaxy. It was (so I thought) common knowledge that they could only travel to gates within our own galaxy unless they had met those requirements.
Now, I recently rewatched the movie, in which the probe traveled to the Kaliam Galaxy, or as Catherine put it, "the other side of the known universe." So, why the limitation on the TV show? And why were they able to travel back to that planet in the first episodes?

A: This seems to be an example of retcon. Whilst in the film the planet Abydos was in the Kaliam Galaxy, in the TV series this was changed, and Abydos was said to be the closest planet to Earth (with a stargate), and therefore in the Milky Way.
I imagine that the reason they changed it for the TV series was so that they could have storylines with the Asgard, the Ori and Atlantis, without the teams being able to travel back and forth at will. This is only speculation though so I'll look into it further.
See Differences from the series.

A: The answer is quite simple: The energy rate required to go to another galaxy is too high to be achieved with anything less than ZPM levels of power. Now, as it has been pointed out, there was a very large retcon of Abydos's location for the show.
However, this is not the only way to travel between galaxies: There is the McKay/Carter Intergalactic Gate Bridge.
This was designed to facilitate travel from Pegasus to the Milky Way by making sure that each gate is only dialing a local gate, and thus being able to transport from one galaxy to another without the outrageous intergalactic fees high energy rate.

A: The simple answer was that the probe that calculated the distance (obviously via star constellations) was very confused. It had only traveled a few relative light years (Abydos is quite close!) but misinterpreted the sky as being in another galaxy. LOL, oops!
Think about it! It was the first time non-Sol constellations had ever been triangulated by their civilization. Mistakes happen ;-)


text:
Q: How to check if a user-specified name refers to a directory or not? I am trying to write a simple program that checks if a given filename refers to a directory. But I keep getting an error saying that "bad interpreter: no such file or directory" when I run ./isdir.sh (This is the name of the script).
here is my code:
#!bin/sh

if [[ $# -ne 1 ]];then
    echo "Usage: $0 dir"
    exit 1
fi

dir="$1"
dirname = "$1"

if [[ ! -d "$dir" ]]; then
    echo "Error: directory $dir not found."
    exit 2
fi

if [[ -d "$dirname" ]]; then
    echo "$dirname is a directory."
    exit 3

ALSO, IMPORTANT QUESTION:
How do I handle input values that contain spaces in them?

A: You could do this:
#!/bin/bash

if [[ $# -ne 1 ]]; then
  echo "Usage: $0 dir"
  exit 2
fi

dir="$1"
rc=1
if [[ -d "$dir" ]]; then
  # it is a directory
  rc=0
elif [[ -e "$dir" ]]; then
  echo "Error: '$dir' is not a directory"
else
  echo "Error: directory '$dir' does not exist"
fi

exit "$rc"

*

*Don't need the dirname variable.

*The script is safe for directories that have white spaces or wild cards in their name as we have enclosed the variable in double quotes.

*Exit code of 2 is a Unix standard for invalid argument error; exit 1 is all other errors.  However, you can change the exit codes as per your need.

See this related post for more perspectives around this problem: Check if a directory exists in a shell script


text:
Q: USACO - Dynamic Programming - Maximum Decreasing Subsequence I've confused with the code that is written in the TEXT Dynamic Programming section of USACO Training about a classical problem (Finding Maximum Decreasing Subsequence). This is Article Link. Please help me to get it!
Here's the code:
 1  #include <stdio.h>
 2  #define MAXN 200000
 3  main () {
 4      FILE *in, *out;
 5      long num[MAXN], bestrun[MAXN];
 6      long n, i, j, highestrun = 0;
 7      in = fopen ("input.txt", "r");
 8      out = fopen ("output.txt", "w");
 9      fscanf(in, "%ld", &n);
10      for (i = 0; i < n; i++) fscanf(in, "%ld", &num[i]);
11      bestrun[0] = num[n-1];
12      highestrun = 1;
13      for (i = n-1-1; i >= 0; i--) {
14          if (num[i] < bestrun[0]) {
15            bestrun[0] = num[i];
16            continue;
17        }
18        for (j = highestrun - 1; j >= 0; j--) {
19            if (num[i] > bestrun[j]) {
20                if (j == highestrun - 1 || num[i] < bestrun[j+1]){
21                    bestrun[++j] = num[i];
22                    if (j == highestrun) highestrun++;
23                    break;
24                }
25            }
26        }
27      }
28      printf("best is %d\n", highestrun);
29      exit(0);
30  }

I have 3 problems with it:
1) What exactly lines 14-17 do?
For example for the sequence 10, 2, 8, 9, 4, 6, 3 , the result of the that code is 4 but it's subsequence is 10, 8, 4, 2 that it's wrong, because the element 2 in original sequence is before 8 and 4 but in the resulting subsequence is after 8 and 4!
2) Consider the sequence 5, 10, 8, 9, 4, 6, 3. According to above code, the length of the maximum decreasing subsequence is 4 and this subsequence is 10, 5, 4, 3. But in this subsequence opposite of the original sequence 5 is after 10.
3) Is it necessary to check num[i] < bestrun[j+1] condition in inner loop? I think it's satisfied before by num[i] > bestrun[j] condition.
I'm waiting for you helpful answers.
Thanks for your help!

A: 1) bestrun[i] keeps track of the smallest integer that is the start of a longest decreasing subsequence of length i + 1. Therefore, if you encounter a value that is smaller than your current bestrun[0], you want to change bestrun[0] to that value, as that would be the the smallest decreasing subsequence of length 1.
2) I'm not particularly sure what you're asking. If you're wondering about what happens when you flip the sequence around, then you could run the longest increasing subsequence algorithm instead to get the same result.
3) Yes, that seems to be redundant, as bestrun should be nonincreasing. In fact, some implementations of longest increasing/decreasing subsequence exploit this fact to improve runtime to O(n log n) by doing a binary search to find the highest j such that num[i] is bigger than bestrun[j].


text:
Q: Grails json cells with enum In my code I have a domain object with an Enum type in it.  That enum type saves and retrieves fine from the database.  I am converting a list of domain objects into json cells.  All fields except the enum are either a string or a long.  When the json gets picked up 'on the other side' it displays [Object object] for the column, instead of the enum name or enum value.  Is there something on either the domain or json side that would help with this?  Code/example below
Domain Class
class MyDomain {
long id
long otherValue
MyEnum enu  //Nullable per constraints
//Mapping and constraints are not special.
}

Enum
enum MyEnum {
ENUM1("Value1"),ENUM2("Value2")
//constructor ommitted
String myValue
String toString() { myValue }

Json cell creation
def jsonCells = domainList.collect
    {
        [cell: [
                it.id,
                it.otherValue,
                it.enu?.value
            ],
            id: it.id]
    }

it.enu?.value works.  However, is there somehow a better way to do this where I don't have to call the value every time and can rely on the object?  I would have assumed that overriding the toString method would have taken care of it, but apparently I was wrong.  I know it seems like a minor issue, but its easier to forget ".value", especially as the same enum will be used in many domain objects.  Ideas?

A: Since you're simply putting it in a List when building the object, it will treat it as an Object unless you specifically do something else with it (like you're doing currently).
One alternative would be to use it.enu as String or something similar, but that still probably doesn't achieve what you're trying to achieve.
Another (maybe overengineered?) way would be to create a method on the domain itself that returns the value, and then use that method when building JSON:
class MyDomain {
    MyEnum enu

    def enuVal() {
        enu?.value
    }
}

with
def jsonCells = domainList.collect {
    [cell: [
        it.enuVal()
    ],
    ...]

As for me, I guess I'd just prefer to use it.enu?.val in the JSON. Write a test for your JSON-rendering methods and make sure the value is what you expect it to be, so that you don't forget.


text:
Q: What is the difference between android:gravity and android:layout_gravity I'm working on a simple android application , and i need to align some of views in a specific location but without using padding or constants integer values for sizes , I wanna do that using gravity attribute , Can any one tell me what is the gravity attribute and what is the difference between android:gravity and android:layout_gravity attribute .
and thanks in advance .

A: android:gravity sets the gravity of the content of the View its used on.
android:layout_gravity sets the gravity of the View or Layout in its parent.
check https://stackoverflow.com/a/6819801/1434631

A: android:gravity sets the gravity of the content of the View its used on.
android:layout_gravity sets the gravity of the View or Layout in its parent.

A: Gravity: will specify to where the content of the view will be alighted, meaning If you have a TextView and it's parameters are not wrap_content for both dimensions then Gravity will determine which boarder this text will touch.
Layout_Gravitiy: this will specify the location of the View inside it's parent layout, meaning that if you Layout is bigger the the View inside this will determine which boarder of this layout this View will touch.


text: Q: Splinter, JS - uncaught at Ya at Ya -> Error occured while calling Localization service I'm using Splinter and Python to do some simple scraping from a particular website. Only a few pages once a week. When I enter an address to see pricing options for this company, the promise appears to be uncaught, and the page just hangs up indefinitely. When I do this same action in same browser (Chrome) but in a different window, it goes through fine and the iframe/data is returned and I can see the page. I'm attaching screenshots of the console for both browser actions doing the same thing. Can someone please point me to what changes I need to make to Chromedriver in order to get the page to answer just like the browser not running Splinter. 1st pic is the console log running Splinter. The 2nd pic is the browser not running Splinter. Thanks in advance for any help


text:
Q: Adding Date and Time values in R I have the following kind of data in my datafile
DriveNo     Date and Time
12         2017-01-31 23:00:00     //Start time of a trip for Driver12
134        2017-01-31 23:00:01
12         2017-01-31 23:10:00     //End time ( 10 min trip)
345        (some date/time)
12         2017-01-31 23:20:00     //Start Time
12         2017-01-31 23:35:00     //End Time (15 min trip)
 .
 .
 .

millions of similar data follow
The total number of data is around 3 million. Now, I need to get the time driven my each of the drivers(there are around 500 drivers).My ideal output would be like
DriveNo    TotalTimeDriven
12          35mins
134         ........(in days/hours/mins)
.
.

(for all other Drivers as well)
Above, DriveNo 12 has four entries, suggesting start and end of two rides.Is there an efficient R way to do this?

A: Data table solution:-
# Sample data
df <- data.table(DriveNo = c(12, 134, 12, 134), Time = c("2017-01-31 23:00:00", "2017-01-31 23:00:01", "2017-01-31 23:10:00", "2017-01-31 23:20:01"))

df[, duration := max(as.POSIXct(Time)) - min(as.POSIXct(Time)), by = DriveNo]

df
DriveNo                Time duration
1:      12 2017-01-31 23:00:00  10 mins
2:     134 2017-01-31 23:00:01  20 mins
3:      12 2017-01-31 23:10:00  10 mins
4:     134 2017-01-31 23:20:01  20 mins

A: range returns the maximum and minimum, and diff subtracts sequential numbers in a vector, so you could just do
aggregate(DateTime ~ DriveNo, df, function(x){diff(range(x))})
##   DriveNo DateTime
## 1      12      10
## 2     134       0

or in dplyr,
library(dplyr)

df %>% group_by(DriveNo) %>% summarise(TimeDriven = diff(range(DateTime)))
## # A tibble: 2 × 2
##   DriveNo TimeDriven
##     <int>     <time>
## 1      12    10 mins
## 2     134     0 mins

or in data.table,
library(data.table)

setDT(df)[, .(TimeDriven = diff(range(DateTime))), by = DriveNo]
##    DriveNo TimeDriven
## 1:      12    10 mins
## 2:     134     0 mins

To change the units, it may be simpler to call difftime directly.

Data
df <- structure(list(DriveNo = c(12L, 134L, 12L), DateTime = structure(c(1485921600,
    1485921601, 1485922200), class = c("POSIXct", "POSIXt"), tzone = "")), class = "data.frame", row.names = c(NA,
    -3L), .Names = c("DriveNo", "DateTime"))

For the edit, you can make a variable identifying starts and stops, reshape, and summarise with difftime and sum.
library(tidyverse)
set.seed(47)

drives <- data_frame(DriveNo = sample(rep(1:5, 4)),
                     DateTime = seq(as.POSIXct("2017-04-13 12:00:00"),
                                    by = '10 min', length.out = 20))

drives %>% str()
#> Classes 'tbl_df', 'tbl' and 'data.frame':    20 obs. of  2 variables:
#>  $ DriveNo : int  5 3 4 3 5 1 1 2 3 5 ...
#>  $ DateTime: POSIXct, format: "2017-04-13 12:00:00" "2017-04-13 12:10:00" ...

elapsed <- drives %>%
    group_by(DriveNo) %>%
    mutate(event = rep(c('start', 'stop'), n() / 2),
           i = cumsum(event == 'start')) %>%
    spread(event, DateTime) %>%
    summarise(TimeDriven = sum(difftime(stop, start, units = 'mins')))

elapsed
#> # A tibble: 5 × 2
#>   DriveNo TimeDriven
#>     <int>     <time>
#> 1       1    60 mins
#> 2       2   110 mins
#> 3       3   120 mins
#> 4       4   130 mins
#> 5       5    80 mins

It would be faster to index by recycled Boolean vectors, but in dplyr they get unclassed at some point. In data.table,
library(data.table)
set.seed(47)

drives <- data.table(DriveNo = sample(rep(1:5, 4)),
                     DateTime = seq(as.POSIXct("2017-04-13 12:00:00"),
                                    by = '10 min', length.out = 20))

elapsed <- drives[, .(TimeDriven = sum(difftime(DateTime[c(FALSE, TRUE)],
                                                DateTime[c(TRUE, FALSE)],
                                                units = 'mins'))),
                  keyby = DriveNo]

elapsed
#>    DriveNo TimeDriven
#> 1:       1    60 mins
#> 2:       2   110 mins
#> 3:       3   120 mins
#> 4:       4   130 mins
#> 5:       5    80 mins

or in base,
set.seed(47)

drives <- data.frame(DriveNo = sample(rep(1:5, 4)),
                     DateTime = seq(as.POSIXct("2017-04-13 12:00:00"),
                                    by = '10 min', length.out = 20))

elapsed <- aggregate(DateTime ~ DriveNo, drives,
                     function(x){sum(difftime(x[c(FALSE, TRUE)], x[c(TRUE, FALSE)], units = 'mins'))})

elapsed
#>   DriveNo DateTime
#> 1       1      60
#> 2       2     110
#> 3       3     120
#> 4       4     130
#> 5       5      80

All forms will likely have issues if there are an odd number of times for a driver, which is not possible under the assumptions given. If it is, more cleaning is necessary.


text:
Q: Applying a cutoff value to a Tensor I want to apply a threshold to 1 column in a 2D tensor. Any value below the cutoff would be listed as null or zero. I have tried to avoid looping through the tensor and I want the input & output tensor to have the same shape.
Here is the code:
NFValue = tf.Variable(1.,dtype=tf.float64,constraint=lambda t: tf.clip_by_value(t, 10, 20))

col1 = tf.gather(x, [0], axis=0)
col2 = tf.gather(x, [1], axis=0)

y = tf.fill(tf.shape(col2), NFValue)   # creates a tensor of the same size as X, with Cutoff
y = tf.cast(y, np.float32)             # converts that tensor into the correct type for comparision.

NewCol2 = tf.boolean_mask(col2, tf.math.greater(col2, y))

return tf.concat([col1[0,:], NewCol2], axis=0)

The problem is that tf.boolean_mask() returns a tensor with just the values which were greater than NFValue. So the shape has changed.  tf.Greater will return a boolean vector of the correct shape, but I would need to loop through the tensor.
I have tried several different options around this. I have looked at slice, tf.Scan and a couple different functions. I am expecting there to be a canned solution here.

A: Use tf.where
import tensorflow as tf

x = tf.reshape(tf.range(9), (3, 3))

<tf.Tensor: shape=(3, 3), dtype=int32, numpy=
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])>

tf.where(x > 5, x, 0)

<tf.Tensor: shape=(3, 3), dtype=int32, numpy=
array([[0, 0, 0],
       [0, 0, 0],
       [6, 7, 8]])>


text:
Q: shard cluster doesn't seem to be dividing data based on keys on mongoDB prototype Background Information
I have the following shard cluster defined:
mongos> sh.status()
--- Sharding Status ---
  sharding version: {
    "_id" : 1,
    "version" : 4,
    "minCompatibleVersion" : 4,
    "currentVersion" : 5,
    "clusterId" : ObjectId("547496dd009cc54d845c2ff1")
}
  shards:
    {  "_id" : "jjrs0",  "host" : "jjrs0/mongohost1:27017" }
    {  "_id" : "jjrs1",  "host" : "jjrs1/mongohost2:27017" }
    {  "_id" : "jjrs2",  "host" : "jjrs2/mongohost3:27017" }
  databases:
    {  "_id" : "admin",  "partitioned" : false,  "primary" : "config" }
    {  "_id" : "rtables",  "partitioned" : true,  "primary" : "jjrs1" }
        rtables.widgets
            shard key: { "location" : 1, "name" : 1 }
            chunks:
                jjrs1   1
            { "location" : { "$minKey" : 1 }, "name" : { "$minKey" : 1 } } -->> { "location" : { "$maxKey" : 1 }, "name" : { "$maxKey" : 1 } } on : jjrs1 Timestamp(1, 0)
    {  "_id" : "test",  "partitioned" : false,  "primary" : "jjrs0" }

mongos>

I have 3 replicasets (each with just a primary for testing purposes).
I've defined "location" as being my shard key, where location will contain values like "CAN" for "Canada" and "USA" for "United States".
I am hoping to have a different location on different shards.
Shard Key
I've made what I *think it a compound key.  The location, and the name fields make up the key.  A widget's name will always be unique.
What the Data / CSV Files Look Like
The Canada CSV files look like this:
location,name,rt_id,type
canada,can-widget111,123,the best widget
canada,can-widget222,1,the next best widget

The USA CSV looks like:
location,name,rt_id,type
usa,usa-widget1,24,test widget
usa,usa-widget2,25,widget widget

Problem
Either I'm misunderstanding how the shard keys work, or I've set something up incorrectly... or maybe I'm not validating my data properly.  In any case, here's whats happening:

*

*I've imported all canada records into the primary shard for the "rtables" database "jjrs1".  This is the command I ran:

 mongoimport -h mongohost2 --port 27017 -d rtables -c widgets --type csv /tmp/canada_rtables.csv --headerline

*I started mongo on this host.. and then check the number of records in the rtables.widgets collection, and it matches the number of records imported.  Let's say 50.

*Then i imported all records for United States by running a similar command, like so:

mongoimport -h mongohost2 --port 27017 -d rtables -c widgets --type
  csv /tmp/usa_rtables.csv --headerline

*I checked the records in the "primary" replicaset jjsr1 and it had the new records in the collection.

*The other two databases on the other replicasets (jjrs0 and jjrs2) and empty. Infact the rtables databases on both servers are empty, as you can see below:

jjrs2:PRIMARY> use rtables
      switched to db rtables
      jlrs2:PRIMARY> show databases
      admin       (empty)
      local       1.078GB
      rtables  (empty)
      jjrs2:PRIMARY>

and
jjrs0:PRIMARY> show databases
admin       (empty)
local       1.078GB
rtables  (empty)
test        0.078GB
jjrs0:PRIMARY>

Questions

*

*Am I correct in assuming that the data will be divided in such a way where all the Canadian content will be in one replicaset and the USA data in another?

*If so, am I testing properly?

*If my assumption is incorrect, can you please explain how the division of data is supposed to occur based on the shard key I've defined?

I've found the following post that might be related... but I haven't been able to apply the answer to my own questions..:
Mongo sharding fails to split large collection between shards
I'm still mulling it over.
Thanks
EDIT 1
I'm thinking that maybe I should use a tag as a shard key?
Maybe something like this:
mongos> sh.addShardTag("jjrs1", "CAN")
mongos> sh.addShardTag("jjrs1", "USA")
mongos> sh.addShardTag("jjrs0", "JPN")
mongos> sh.addShardTag("jjrs2", "IND")
mongos> sh.addShardTag("jjrs2", "TAI")
mongos> sh.addShardTag("jjrs1", "VET")
mongos> sh.status()

The next question would be how to then associate every record that has "can" in the location field with jjrs1...

A: First of all:
mongoimport -h mongohost2 ...
Here is your first mistake. You are importing directly into a "regular" mongod host. You should have used mongos for imports, which holds routing logic (which chunks reside on which shard).
Also, take a look at the following:
chunks:
    jjrs1   1
{"location" : {"$minKey" : 1}, "name" : {"$minKey" : 1} } -->>
{"location" : {"$maxKey" : 1}, "name" : {"$maxKey" : 1} } on : jjrs1 Timestamp(1, 0)

This can be read as "for every location and name values, the document should be routed to jjrs1.
This is no wonder. A chunk is a sequence of documents with a shard key within a certain range. Also, each chunk's default size is 64MB. If a document's size average is 64KB for example, you will have to insert more than 1000 documents (let's say 500+ for US and 500+ for CANADA) before the chunk will split into 2.
Then, sh.status() may resemble something like:
 chunks:
    jjrs0   0
{"location" : {"$minKey" : 1}, "name" : {"$minKey" : 1} } -->>
{"location" : "canada", "name" : {"$maxKey" : 1} } on : jjrs0 Timestamp(1, 0)
    jjrs1   1
{"location" : {"usa" : 1}, "name" : {"$minKey" : 1} } -->>
{"location" : {"$maxKey" : 1}, "name" : {"$maxKey" : 1} } on : jjrs1 Timestamp(1, 0)

I'm thinking that maybe I should use a tag as a shard key? Maybe something like this:

Well this is not a shard key, but a mechanism to associate tags with shards. This is a step in the right direction, but not enough.
For example, using the (imaginary) sh.status() above, once the chunk had split into two, the "canadian" chunk had been migrated to jjrs0. This may not be the desired behavior, assuming you want to rout the "american" documents to jjrs0.
Why does it happen? Because you've missed declaring tag ranges. Without these the shard tags are just static cluster metadata.
You will also have to configure tag ranges as follows:
sh.addTagRange( "rtables.widgets",
   { country: "usa", name: MinKey }, { country: "usa", name: MaxKey }, "USA")
sh.addTagRange( "rtables.widgets",
   { country: "canada", name: MinKey }, { country: "canada", name: MaxKey }, "CAN")

To wrap it up, in order for the american documents to be on jjrs0 shard, and Canadian to be on jjrs1, do the following:

*

*Optionally delete all widget documents from jjrs1.

*Declare the shard tags as in the edit section of your post (for sake of testing, CAN and USA are enough).

*Declare the tag ranges as above.

*Use a mongos for import.

Comment: for the rest of the countries - where tags had not been declared -an attempt will be made to balance the cluster, meaning chunks will be routed / migrated randomly in order to balance the number of chunks among shards.


text:
Q: virtual hosts with subdomains not working I have these two virtual hosts for my development server. I need to send any request to dev. or *.dev. to one application, which will handle dealing with the subdomains. Right now, only the second one works, with any request sent to *.dev. being passed to the application. But if I just go to the dev. subdomain, i get an error in my browser saying the page couldn't be found. What is going on?
<VirtualHost *>
    ServerName dev.redemptionconnect.com
    ServerAlias dev.redemptionconnect.com
    DocumentRoot "C:/xampp/htdocs/dev.redemptionconnect.com/"
</VirtualHost>

<VirtualHost *>
    ServerName sub.dev.redemptionconnect.com
    ServerAlias *.dev.redemptionconnect.com
    DocumentRoot "C:/xampp/htdocs/dev.redemptionconnect.com/"
</VirtualHost>

A: Edit: I assume you have defined the subdomain dev.redemptionconnect.com in DNS? I don't turn up an address for it.
# tournaments.dev. works....
PING tournaments.dev.redemptionconnect.com (107.21.224.129) 56(84) bytes of data.

# but bare dev. does not...
ping: unknown host dev.redemptionconnect.com

You'll need DNS records for the first subdomain and each of its sub-subdomains.  Defining the sub-subdomains does not implicitly define their parent subdomain as well.
This may be because you are using dev.redemptionconnect.com in both the ServerName andServerAliasdirectives for the firstVirtualHost`, however I wouldn't expect that to cause an issue.
However, since you're pointing them both to the same application directory do you really need to VirtualHosts at all? You can just specify multiple ServerAlias:
<VirtualHost *>
    ServerName sub.dev.redemptionconnect.com
    # Multiple domains in ServerAlias
    ServerAlias dev.redemptionconnect.com *.dev.redemptionconnect.com
    DocumentRoot "C:/xampp/htdocs/dev.redemptionconnect.com/"
</VirtualHost>


text:
Q: How can I apply multiple conditions in Pandas, with Python? How can I apply multiple conditions in pandas?
For example I have this dataframe
Country   VAT
RO       RO1449488
RO       RO1449489
RO       RO1449486
MD       2980409450027

For example I want for the Countries with RO, to delete the "RO" from VAT and remain just number.
Or for example if the Country is not RO and let(VAT) is 13, to add "03" in front of VAT
Output to be like
Country   VAT
RO       1449488
RO       1449489
RO       1449486
MD       032980409450027

I know how to do this with openpyxl, but pandas is new for me and I find pandas syntax to be harder to understand.

A: If you want to have something else than @mozway one-liner, you can use apply() to make any modification over your DataFrame. Defining your code in a function :
def myFunc(x):
    if x['VAT'].startswith("RO"):
        result = x['VAT'][2:]
    elif x['Country'] != 'RO' and len(x['VAT']) == 13:
        result = "03" + x['VAT']
    # add other conditions here

    return result

Then you can apply it to your DataFrame row by row with axis=1
df['VAT'] = df.apply(myFunc, axis=1)

# Output
  Country              VAT
0      RO          1449488
1      RO          1449489
2      RO          1449486
3      MD  032980409450027

A: You can use boolean selection with numpy.select:
import numpy as np
                       # condition1            condition2
df['VAT'] = np.select([df['Country'].eq('RO'), df['VAT'].str.len().eq(13)],
                       # replacement1
                      [df['VAT'].str.replace('^RO', '', regex=True),
                      '03'+df['VAT']], # replacement2
                       df['VAT']       # default
                     )

output:
  Country              VAT
0      RO          1449488
1      RO          1449489
2      RO          1449486
3      MD  032980409450027


text:
Q: When is $L^{2}(X,\mathscr{B},m)$ spearable If $X$ is a metric space, $m$ is a Borel probability space on $(X,\mathscr{B})$ where $\mathscr{B}$ is the $\sigma$-algebra generated by open sets on $X$, can we prove that the space $L^{2}(X,\mathscr{B},m)$ is spearable?

A: This post answers your question precisely: https://mathoverflow.net/a/42383.
I am not able to post this answer as a comment as I do not have 50 reputation yet.


text:
Q: How to generate a random variable using values of another random variable as its parameter I have a code that generates 5 random variables from a specified distribution(e.g. uniform)
and placed it in the first column of a 5x2 matrix
my.data <- data.frame(matrix(nrow = 5, ncol = 2))
colnames(my.data) <- c("unif", "norm")
set.seed(1)
my.data[, 1] <- runif(5)

which looks something like this
       unif norm
1 0.2655087   NA
2 0.3721239   NA
3 0.5728534   NA
4 0.9082078   NA
5 0.2016819   NA

I want to use the generated random variables as the parameter of another distribution(e.g. normal),
that is, I want to sample from a normal distribution with mean equal to the value of the uniformly distributed random variables and standard deviation equal to the the value of random variable*0.1.
my.data[, 2] <- rnorm(1, mean = my.data$unif, sd = my.data$unif*0.1)
my.data[, 2] <- rnorm(1, mean = my.data[,1], sd = my.data[,1]*0.1)

I've written the code in two ways but obtained the same results.
       unif      norm
1 0.2655087 0.2992928
2 0.3721239 0.2992928
3 0.5728534 0.2992928
4 0.9082078 0.2992928
5 0.2016819 0.2992928

Where all the values in column two are identical.
How can I change the code so I can generate a random variable in the second column using values from the first column as its parameters?

A: You are generating only 1 number in rnorm which is being recycled for all the values. Generate numbers as much as the number of rows in your data.
my.data[, 2] <- rnorm(nrow(my.data),  mean = my.data$unif, sd = my.data$unif*0.1)


text:
Q: Google Apps Script: API authentication to Luno API Total noob programmer here (originally an old-school mechanical engineer).
After going through some of Javascript lessons online, I thought I could try buidling a simple script on Google Sheet.
My project plan was to have a script to automatically track all of my transactions on Luno.com (cryptoexchange) through their API.
Their API documentation is here.
I was attempting to use List Transactions to populate all historical transactions on my spreadsheet, but I got stuck at the authenticate UrlFetchApp.fetch(url) endpoint access request

Edit: You should reconsider sharing your authentication information publicly.  I removed it.

Below is my Code.gs script:
function importStatementLuno() {
  var ss = SpreadsheetApp.getActiveSpreadsheet(); //get active spreadsheet (bound to this script)
  var url = 'https://api.luno.com/api/1/accounts/xxx/transactions'; //api endpoint as a string

  var response = UrlFetchApp.fetch(url,{'muteHttpExceptions': false}); // get api endpoint
  var json = response.getContentText(); // get the response content as text
  var lunodata = JSON.parse(json); //parse text into json

Logger.log(lunodata);

My fetch response gave me this Error:

Exception: Request failed for https://api.luno.com returned code 401. Truncated server response: Unauthorized
(use muteHttpExceptions option to examine full response)

I can't for my life understand their documentation! I'm not sure if there's actually different expressions used to provide authentication keys to their server (they explicitly mentioned they support Go better in their Get Started documentation)
I hope someone here could help me point out where I went wrong.

A: Based on the Luno-Go documentation, it uses SetBasicAuth and according to Go documentation, SetBasicAuth is just HTTP Basic Authentication. Can you try the code below if it fixes your issue?
Code:
var apiKeyID = 'apiKeyID';
var apiKeySecret = 'apiKeySecret';

var headers = {
  "Authorization": "Basic " + Utilities.base64Encode(apiKeyID + ":" + apiKeySecret)
};

var options = {
  "headers" : headers
};

var response = UrlFetchApp.fetch(url, options); // get api endpoint

New Error:

*

*Error is now different since I used an invalid credential. Try inputting yours here.


text:
Q: What IP address for an iPhone app using TfL data? To get a data feed from Transport for London (TfL) the registration form has a mandatory field that wants the IP address of the server requesting the data. But for an iPhone app that uses NSURLConnection, it is the phone that does the downloading so there is no server involved.
I emailed TfL but have had no reply. Local IP addresses are rejected:

(127.0.0.1, 192.168., 10. or in the range 172.16.* - 172.31.*)
  cannot be accepted

Has anyone got round this and how?

A: Your app is not supposed to connect directly to the server, instead you should use your own server which acts as a proxy to TfL's server.
From TfL's Developer Guidelines:

You should take our data and proxy it, you shouldn't allow all your
  clients to hit our service driectly. This is intended to reduce TfL's
  cost liability for hosting and content delivery.

A: Looking at the TfL application form you have to specify a range of ip addresses you'll be making calls to the TfL api from.


text:
Q: How to read a CSV file and then save it as JSON in Spark Scala? I am trying to read a CSV file that has around 7 million rows, and 22 columns.
How to save it as a JSON file after reading the CSV in a Spark Dataframe?

A: Read a CSV file as a dataframe
val spark = SparkSession.builder().master("local[2]").appname("test").getOrCreate
val df = spark.read.csv("path to csv")

Now you can perform some operation to df and save as JSON
df.write.json("output path")

Hope this helps!


text:
Q: Magento 2 custom module override knockout template How can we override a knockout template in a custom module?
I know how we can do this in our own theme but I need this in a module.
For example I like to override this file:
vendor/magento/module-checkout/view/frontend/web/template/shipping-address/form.html
Is this possible?

A: Yes you can override a knockout template in a custom module, just did it, in your module create a requirejs-config.js file and place it in your module:
app/code/Namespace/Module/view/frontend/requirejs-config.js

In the file add the configuration to specify the override:
var config = {
    map: {
        '*': {
            'Magento_Checkout/template/billing-address':
                'Namespace_Module/template/billing-address'
        }
    }
};


text:
Q: How to use AppDomainInitializer in Powershell I am trying to create an AppDomain in a Powershell script. I implemented the exact same in C# and it seems to be working fine. However, the Powershell version always fails with an exception. The script code is:
function Execute($arguments)
{
    Write-Host "Arguments: " $arguments[0] $arguments[1] $arguments[2]
}

function Main
{
    $appDomain = $null
    Try
    {
        $appDomainSetup = New-Object -TypeName System.AppDomainSetup
        $appDomainSetup.AppDomainInitializer = ${function:Execute}
        $appDomainSetup.AppDomainInitializerArguments = @("Test1", "Test2", "Test3")

        $appDomain = [AppDomain]::CreateDomain("TestDomain", $null, $appDomainSetup)
    }
    Finally
    {
        If ($appDomain -ne $null)
        {
            [AppDomain]::Unload($appDomain)
        }
    }
}

Main

And the exception is:
Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at System.AppDomain.nCreateDomain(String friendlyName, AppDomainSetup setup, Evidence providedSecurityInfo, Evidence creatorsSecurityInfo, IntPtr parentSecur
ityDescriptor) ...
What am I missing here?
Edit 1:
The issue seems to be with the delegate in AppDomainSetup, Powershell creates a dynamic method from it. Is there any way to change this behavior?


text:
Q: In ZFC given any set $X$ if $x\in X$ then is $\emptyset=x\cap X$? Given any set $X$ and any element $x\in X$ then is $\emptyset=x\cap X$?
Feels like it should be, I mean most of the time I don't even think of elements of sets as sets unless I'm deliberate doing so. Though I know if like I'm working in ZFC or something, then like pretty much everything I write is a set I think. Anyway an answer to the first question would be helpful.
Also if yes, what axiom(s) would it follow from? All of them? Only a couple?
Lastly if in modern axiomatic set theory essentially everything is a set wouldn't things like this:
https://en.wikipedia.org/wiki/Set_function
Be redundant?

A: For any non-empty set $X$, some element of $X$ is disjoint from it; this is the axiom of regularity. But not all $x \in X$ are required to have this property. Consider for instance $X=\{ \emptyset,\{ \emptyset \} \}$: $\{ \emptyset \}$ is an element of $X$ which is not disjoint from $X$.
The fact that not all $x$ in $X$ are required to have this property is actually important in how we might use ZF to do other math. For instance, $\{ \emptyset,\{ \emptyset \} \}$ is the "bare metal" representation of the ordinal number "2", and in general the ordinal number $n+1$ is given by $n \cup \{ n \}$.

A: Let me answer your last question

Lastly if in modern axiomatic set theory essentially everything is a set wouldn't things like this:
https://en.wikipedia.org/wiki/Set_function
Be redundant?

Yes, it's redundant. In set theory, every function is a set function.


text:
Q: In OS X Darwin, why can I interfere with text input across user sessions using cat? OS X Darwin:  Disrupting Terminal Sessions Across User Identities

How, in Brief:
with cat < /dev/ttys_, in Terminal.
My Question
This OS X 10.9.2 Darwin behaviour seems odd to me, and I would like to understand why it is happening, and whether or not it is an actual OS or Application bug.
Steps to Reproduce Behavior

*

*open two Terminal windows.

*Note their device paths, i.e. "/dev/ttys001", "/dev/ttys002"

*In one Terminal window (i.e. /dev/ttys001), execute sudo -u [some other user] sh.

*In the other Terminal window (i.e. /dev/ttys002), execute cat < /dev/ttys001 (or whatever the device  path is.)

*Back in the first window, type text.

Unexpected Behavior
When I type text in the relevant Terminal window, there is a noticeable lag;  additionally, the characters do not appear reliably in either window.  Some characters are echoed to the second window, some appear in the first window, and some seem to vanish.
Unexpected Consequences
The reason this concerns me is that it appears that a simple command executed by one unprivileged user can completely disrupt the session of another user.
Anticipated Possible Causes

*

*A text input bug in Terminal 2.4 (326)

*A user privledges bug in OS X 10.9.2 Darwin

A: 3. A misunderstanding of what is going on.
You are not interfering with text sessions across user identities. Only a single user is running a session here, let's call her Alice. Alice is logged in on the console and running a bunch of applications, including some terminal emulators.
In one of these terminals, Alice executes sudo -u bob sh. Now there is a shell running under Bob's account, but the terminal is provided by Alice. The terminal emulator process is running as the user alice.
When you run cat /dev/ttys42 as Alice, you're snooping on, and even interfering with, the terminal emulator that is executed by Alice, not with the shell that is excecuted by Bob.
You're seeing weird phenomenon when you type because each byte is transmitted somewhat randomly to any of the processes that are reading input from the terminal. Normally there is only a single foreground process in a terminal: the job control mechanism and in particular the management of the foreground process group and the SIGTTIN signal ensure that.
Notice that /dev/ttys42 is owned by Alice. If Bob runs a terminal emulator, then /dev/ttys42 will be owned by Bob and not readable or writable by Alice, so Alice won't be able to interfere at that level. However, if this terminal is in Alice's GUI session, then Alice can interfere at the GUI level (e.g. by snooping on or injecting keystrokes, or by making Bob believe that he's interacting with the terminal he started when he's in fact interacting with an application executed by Alice).

A: In order to write to a file, in this case a terminal, you need to have write permissions to it. By default, a tty file is owned (and writable) by the user who uses it, and also writable by the tty group, which again by default only contains root. So no, no messing with other people's sessions allowed.


text:
Q: Why doesn't react native register the user pressing a button? I'm trying to use a touchablehighlight component and when I press it, nothing happens. So I changed it to a button and added a console log and still, react native won't register the press.
I'm using expo and I'm relatively new to react native.
Please tell me what I'm doing wrong
import React, { useState } from "react";
import {
    Button,
  Modal,
  StyleSheet,
  Text,
  TouchableHighlight,
  View,
} from "react-native";

const customPicker = (props) => {
  const [selectedNumber, setSelectedNumber] = useState(props.pickerValues[0]);
  const [pickerDisplayed, setPickerDisplayed] = useState(false);

  function changeSelectedNumber(value) {
    setSelectedNumber(value);
    setPickerDisplayed(false);
  }
  const touchableHighlightcomponent = props.pickerValues.map((value, index) => (
    <TouchableHighlight
      style={styles.th}
      onPress={() => changeSelectedNumber({ value })}
      key={index}
    >
      <Text>{value}</Text>
    </TouchableHighlight>
  ));

  return (
    <View>

      <Button onPress={() => console.log("pressed")} title="one"></Button>

      {/* <TouchableHighlight style={styles.input} onPress={() => this.console.log("pressed")}>
        <Text>{selectedNumber}</Text>
      </TouchableHighlight> */}

      <Modal visible={() => pickerDisplayed} transparent={true}>
        <View style={styles.picker}>
          <View style={styles.pickerItems}>
            <Text>Please select a value</Text>
            {touchableHighlightcomponent}
          </View>
        </View>
      </Modal>
    </View>
  );
};

A: I have discovered the problem.
It's a bug with the iOS simulator, it doesn't register button pushes.
To fix: Simply restart the iOS simulator


text:
Q: Is it possible to protect saved games on Nintendo Switch from being played by other users? Is it possible to protect saved games of a particular user from being played by other users, while still allowing them to play all the games they normally can?
It doesn't have to be secure*, so a short PIN code would be fine, and if any non-trivial action is required to run games with a particular profile that's fine too. However, those non-trivial actions should not actually take long, or require an Internet connection.
A typical use case is when there's a party, and you want people who feel like it to enjoy a couple of games, but you don't want to spend time explaining to all guests, kids, guests' kids, etc. that you'd like to resume that Zelda adventure exactly where you have left it.
For those who don't own a Switch, this is how a profile selection screen looks like. Selecting a profile is a one click action which has to be done every time a new game is started.

(*) - by "not secure" I mean a way that doesn't have to prevent a determined person from using my profile anyway. I mostly want to prevent people from picking it by accident, but a somewhat secure way would be even better.

A: I do not own a Switch and I am not an expert but after some internet digging it seems that it's possible to sign up for another Nintendo account and use that account when your guests want to play games.
You might even be able to simply sign out but I don't know if that will prevent people from saving their progress.

My answer is based on:

Yes, if you mean the profiles on the top left they will get their separate save files no matter what account bought the game. So let's say you have one account connected to the e-shop. You can buy e-shop games from that account and all users will be able to play the game. For cartridge games it's the same, all users will get their own save file.

https://www.quora.com/Can-two-Nintendo-Switch-users-keep-their-own-saves-on-one-saved-game

A: Yes but this method would require having a Nintendo Online account.
First, make sure your current save is backed up to the cloud. Once that is done, disable cloud saves. At the end of the night, redownload the cloud save, confirming that you want to overwrite the existing save and then re-enable cloud saves again once complete.
I wouldn't call this method secure but it would allow you to maintain your save while giving people the chance to experience the game at whatever state you have it currently in.

A: When you say "It doesn't have to be secure..." just how un-secure are you willing to tolerate?
On my Switch, I have my profile attached to my Nintendo account with Nintendo Online. I then created two additional profiles for my kids. Starting a game will now prompt you to pick which user to play under and when they play, they play under their respective profiles and have their own saves under those profiles, while having access to my games. So, if you're willing to have a barrier as simple as picking a user whenever you launch a game, then you're golden.
However, there is a drawback. Since only my account is tied to an online Nintendo account and only my account has a Nintendo Online subscription, only my account can connect to online servers. While this is fine for games like BotW, Mario Kart, and Pokemon, this won't work too well for other online games. To circumvent this, you'll need to attach a Nintendo account to each of the profiles you create, and then upgrade your Nintendo Online subscription to a family plan. At that point, every profile should then have the same gameplay experience for every game.

A: One way to avoid people accidentally playing the game would be to open ~15 other games/applications so that the are the only ones easily visible on the selection screen (if the game is on cartridge you can also remove the cartridge to avoid it automatically going back to the front of the list when the switch restarts) however this wouldn't work if you wanted the guests to be able to play the game as well.


text:
Q: I'm trying to learn and understand how to simplify a proposition using the laws of logic I missed a couple of lectures in college where we where learning how to simplify propositions e.g
Use the laws of logic to show that ¬( → ) ∨ ( ∧ ) simplifies to q
I searched online for a tutorial on how to do them however there isnt really any decent tutorial on the ineternet that gives you a step instruction of what to do and why each step that was carried out was done.
It would really help if someone can simplify the following two propositions and explain how and why for each step. I know the basics of logic I just dont know how to, when, where and why to apply the laws of logic to simplify a proposition.
Here are the following laws of logic we need to know and the two questions are below.
Equivalence law p ↔ q ≡ (p→q) ∧ (q →p)
Implication law p → q ≡ ¬p ∨ q
Double negation law ¬¬p ≡ p
Commutative laws p ∨ q ≡ q ∨ p    /    p ∧ q ≡ q ∧ p
Associative laws p ∧ (q ∧ r) ≡ (p ∧ q) ∧ r  /   p ∨ ( q ∨ r) ≡ ( p ∨ q ) ∨ r
Idempotent laws p ∧ p ≡ p p ∨ p ≡ p
Distributive laws p ∧ (q ∨ r) ≡ (p ∧ q)∨ (p ∧ r)
                  p ∨ (q ∧ r) ≡ (p ∨ q)∧ (p ∨ r)
De Morgan's laws ¬(p ∧ q) ≡ ¬p ∨ ¬q   /   ¬(p ∨ q) ≡ ¬p ∧ ¬q
Identity laws p ∧ T ≡ p     /      p ∨ F ≡ p
Annihilation laws p ∧ F ≡ F    /   p ∨ T ≡ T
Inverse laws p ∧ ¬p ≡ F      /     p ∨ ¬p ≡ T
Absorption laws p ∧ (p ∨ q) ≡ p  /   p ∨ (p ∧ q) ≡ p

*

*Show using the laws of logic that ¬[ ∨ ¬( ∧ )] is a contradiction

*Use the laws of logic to show that [¬( → ) ∨ ( ∧ )] → ( ∨ ) is a      tautology.
Verify your answer using a truth table

A: HINT: I'd start by getting rid of the implication:
$$\begin{align*}
\neg(q\to p)\lor(p\land q)&\equiv\neg(\neg q\lor p)\lor(p\land q)\\
&\equiv\big(\neg(\neg q)\land\neg p\big)\lor(p\land q)\\
&=(q\land\neg p)\lor(p\land q)
\end{align*}$$
So far I've used implication, De Morgan, and double negation. Now see if you can use a commutative law, a distributive law, an inverse law, and an identity law to finish it off.

A: For 1:
$\neg [p \lor \neg(p \land q)] \equiv$ (De Morgan's Laws)
$\neg p \land \neg \neg(p \land q) \equiv$ (Double negation law)
$\neg p \land (p \land q) \equiv$ (Associative Law)
$(\neg p \land p) \land q \equiv$ (Commutative Law)
$(p \land \neg p) \land q \equiv$ (Inverse Law)
$F \land q \equiv$ (Annihilation Law)
$F$

A: ¬( → ) ∨ ( ∧ )          given
≡ ¬(¬ ∨ ) ∨ ( ∧ )       definition of if then
≡ ( ∧ ¬) ∨ ( ∧ )        de morgan's law
≡ ( ∧ ¬) ∨ ( ∧ )        just rearranged (communicative ?)
≡  ∧ ( (¬) ∨ () )        distributive prop.
( (¬) ∨ () ) is a tautology
 ∧ TRUE ≡


text:
Q: Can not find the right codes for bind_param The script is part of an login system, this part is to gather all the information about the user.
error codes:

Fatal error: Call to a member function bind_param() on a non-object in /home/s010485/domains/jcsl.nl/public_html/medewerkers/includes/main.php on line 28
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND mw_gegevens_pass=? AND mw_gegevens_p' at line 6'
       in /home/s010485/domains/jcsl.nl/public_html/medewerkers/includes/main.php:27
Stack trace: #0 /home/s010485/domains/jcsl.nl/public_html/medewerkers/includes/main.php(27): mysqli->query('?????????SELECT...') #1 /home/s010485/domains/jcsl.nl/public_html/medewerkers/index.php(13):
      include_once('/home/s010485/d...') #2 {main} thrown in /home/s010485/domains/jcsl.nl/public_html/medewerkers/includes/main.php on line 27

if(isset($_POST['login']))
{
$userpassword = md5($_POST['mw_pass']);

    $mw_gegevens_qry = $connection->query("
                                SELECT
                                        *
                                FROM
                                        mw_gegevens
                                WHERE
                                        mw_gegevens_persnr=?
                                AND
                                        mw_gegevens_pass=?
                                AND
                                        mw_gegevens_pass!=''
                                ");
            $mw_gegevens_qry->bind_param('is', $_POST['mw_user'],$userpassword);
            $mw_gegevens_qry->execute();
            $mw_gegevens_qry->close();
    ($mwgegevens = $mw_gegevens_qry->fetch_assoc());
    if($mw_gegevens_qry->num_rows == 0){
    //wrong inlog
        $error['login'] = "FOUT: Uw combinatie van je personeelsnummer en wachtwoord kon niet worden gevonden. Mogelijk heb je een typefout gemaakt.";
    }
    else
    {
        set_inlog($mwgegevens);
        if(isset($_GET['pagina']))
        {
        header("location: ?pagina=".$_GET['pagina']);
        }
        else
        {
        header("location: index.php?pagina=home");
        }
        exit;
    }
}

A: You need to prepare the statement before using bind_param.
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

Edit: The code looks good now (though I don't use mysqli, so am not totally familiar with it). As silly as it sounds, are you sure that $connection and $qry are both successful? It seems that the prepare might be failing due to a non-successful connection and prepare step?

A: as fluffeh pointed out, you need to prepare the statements before binding...
$qry = $connection->prepare("UPDATE mw_gegevens SET mw_gegevens_ckey =   ?, mw_gegevens_logintime   =   ? WHERE  mw_gegevens_id =   ?");
echo $connection->error;//displays error
$qry->bind_param('sii', $key,$onlinetijd,$list['mw_gegevens_id']);
$qry->execute();

$result_set = $qry->get_result();//grab the results

if($result_set->num_rows < 1){

echo "Wrong login";

}

else{
//do something

}

incase you want to display something you do
 while($row = $result_set->fetch_assoc()){
 //echo row
 }


text:
Q: How many times must a bounded random number generator bounded by its output run until it outputs 1? Say you have a function with input $x$ that generates a random integer between $1$ and $x$. Every time you run the function you replace its input with its output until the function outputs $1$. What is the expected number of times you will have to run the function?
For example, if $x$ is $1000$. You run $f(1000)$ and it gives you, say $500$. Then you run $f(500)$ and it gives you $1$. So it took you $2$ runs to roll a $1$, I was wondering what the expected amounts of runs would be for $x$.
I initially thought it would just be $\log_2x$ because you are expected to halve the value on each run, but that clearly doesn't work for $x=2$ because you're expected to roll twice to get $1$.
Maybe that's just because its a base case so I wrote this on python to check for 1000 -
y = 0
for j in range(100000):
    i = 1000
    z = 0
    while i>1:
        i = randrange(1, i+1)
        z+=1
    y += z
y = y/100000
print(y)

and it gives approximately ~8.5 rolls. Any ideas?

A: Let $\mathbb{N}$ refer to the positive integers.
Let $l$ be a function from $\mathbb{N}$ to $\mathbb{R}$ representing the expected number of turns needed to reach $1$.
We can tell from your example that the integer range $1 \cdots x$ is inclusive. For example, if the value at turn $t$ is $100$, the value at turn turn $t+1$ can be $100$.
If the value on turn $t$ is $x$, then every integer $\{1,2,\cdots x\}$ is equally likely to be the value on the next turn.
This process has no memory, so if our state is $50$, the expected number of turns remaining does not depend on the number of turns that have already passed.
With this, we can give a group of equations that holds for all $n$. We will temporary not address the issue of a base case.
$$ l(n) = 1 + \frac{1}{n}\sum_{i=1}^nl(i)$$
Let's define a helper function $L$ representing the number of turns left not counting the current one.
$$ L(n) = \frac{1}{n}\sum_{i=1}^nl(i) $$
Hence, the following holds
$$ l(n) = 1 + L(n) $$
$$ n \cdot l(n) = n + n \cdot L(n) $$
$$ n \cdot l(n) = n + l(n) + (n-1)\cdot L(n-1) $$
$$ (n-1)\cdot l(n) = n + (n-1) \cdot L(n-1) $$
$$ l(n) = \frac{n}{n-1} + L(n-1) $$
$$ l(n) = \frac{n}{n-1} + l(n-1) - 1$$
$$ l(n) - l(n-1) = \frac{n}{n-1} - 1 $$
$$ l(n) - l(n-1) = \frac{n-(n-1)}{n-1} $$
$$ l(n) - l(n-1) = \frac{1}{n-1} $$
Let's note that, because of how $l$ is defined, successive differences of $l$ are the same as successive differences of $L$.
Now that we have a nice formula for the difference between successive values of $L(n)$, we just need a base case.
$$ L(1) = 0 \;\;\;\text{and}\;\;\; L(2)-L(1) = 1 $$
$$ L(n) = \sum_{i=1}^{n-1} \frac{1}{i} $$
And therefore, as desired:
$$ l(n) = 1 + \sum_{i=1}^{n-1} \frac{1}{i} $$
$l(1000)$ is indeed approximately $8.5$.
>>> 1 + sum(1/x for x in range(1, 1000))
8.484470860550342

A: Let $X_n$ be the random variable representing the amount of time taken to get to $1$ and let $f(n)=\mathbb{E}[f_n]$. We know that $f(1)=1$. In general, if we start with $n$, then with probability $\frac{1}{n}$ we roll $n$ and end up back where we started except we've made one roll. If we roll $1<m<n$, then the expectation in this case is $1+f(m)$ since it's as if we began with $m$ initially expect we've made an extra roll. By the law of total expectation, this means that if $A_i$ is the event "the first roll is $i$" then:
$$f(n)=\mathbb{E}[f(n)\mid A_n]P(A_n)+\mathbb{E}[f(n)\mid A_{n-1}]P(A_{n-1})+\cdots +\mathbb{E}[f(n)\mid A_1]P(A_1)=\\
\frac{1}{n}[(f(n)+1)+(f(n-1)+1)+\cdots (f(2)+1)+1]= \frac{1}{n}(f(n)+f(n-1)+\cdots +f(2)+n)$$
which implies that
$$f(n)=\frac{1}{n-1}(f(n-1)+\cdots+f(2)+f(1) + (n-1))$$
You can use this to iteratively compute $f(n)$, but I am not sure if there is a closed form expression.


text:
Q: LocoTranslate не переводит нужную строку У становил LocoTranslate, тема подготовлена под перевод ( название темы - "crestyler". В functions.php есть строка:
load_theme_textdomain( 'crestyler', get_template_directory() . '/languages' );

Мне надо перевод слово "All" в фильтре портфолио. Строка, где прописано слово имеет вид:
$term_list .= 'post_count . '">' . esc_html__('All', 'crestyler') . '

В админке, в LocoTranslate находит это слово и я перевел на "Все", но вот в фронте это никак не отобразилось...
Вроде все нормально и должно сработать, но что-то не срабатывает. Помогите пожалуйста.

A: Попробуйте использовать хук gettext
https://developer.wordpress.org/reference/hooks/gettext/


text:
Q: SMTPTransport sendMessage stuck on connection loss i am using javamail's SMTPTransport.sendMessage method to send emails in my android app and everything works fine... but when i start sending a message and in the middle, i disable my wifi, it gets stuck. I have waited for more than 1hour now and it is still stuck; no exception is thrown... any idea how to handle this situation?
edit:
i have added a timeout
props.put("mail.smtp.connectiontimeout", "3000");
props.put("mail.smtp.timeout", "3000");

does not seem to work ... i have simulated a connection loss and it's already 5mins now and it is still in sending state and has not timed out
edit2:
timeout/error(not even sure if it is a timeout) occurred after 16mins
06-30 18:47:27.722: I/System.out(15906): javax.net.ssl.SSLException: Write error: ssl=0xdf8268: I/O error during system call, Invalid argument

edit 3:
it does not always throw an exception... i have simulated a connection loss and after 1hr, still no exception... it is in sending state..... and have not return yet :(

A: The current version of JavaMail only handles timeouts for reads, because that's all the JDK supports.  For the next JavaMail release I've added support for write timeouts.  You can experiment with it using the 1.5.1-SNAPSHOT release of JavaMail available in the maven.java.net repository.  You'll need to set the "mail.smtp.writetimeout" property.  Don't know if this will help you on Android since it's not really Java...


text:
Q: .jar file is not opening on 10.15.7 macOS Catalina I have a JAR file, which is a program. I want to open this file, but when I double click the icon flashes for half-a-second but then nothing happens.
I tried to open via java -jar Downloads/launcher.jar, which returns this:
Error: Unable to initialize main class cr.riselauncher.Launcher
Caused by: java.lang.ClassFormatError: Illegal class name "/m/Dispatcher" in class file yKMDW5EvDgdc44ye8WSaYWD53B9eVsAngQNDKLVRxnWyvkunYtFGb6p2cAYuyNtTJm4HJCGyVsb8E3TJWWzyfysdCjQGvJtFa3eXUqEj6fL8PvDedJD2EcP5yprg3B3EUWxg3eKD8CuFdd7rGG6ztcCL7qnEvspKwbCjM9tqCmuMX53evV69gZ2um3c5Q7FkgkSUyFJMCTLqHduc4SjWZYGN7WJcCjggZVFHxuaVGyURdyeLTQEGsax8dFP5mKjcm2bP8nGj2YC5Gey6TfgjhcEkeRgcpQzegYqH5Z5PfcjWxU2yRSMkjxFb8xMpAd9dvsE9PbynWEzrnpPRvw9YWYTpE7Sxw8DNMabQbhFK8MbLWfPcXVbc3TkPMDGWPvxLYWhGuFFEyFBMDmADEGcnuvWRHUaHUKBkpe7k7R4JyECw7uLHW79kfpsXqpXP6KAznrKK5qFQXGnaXFk2Vj3mmsBTZseb3Z3jwVPeAp62tdKFDG7qgc3CpnvWunhA2JqufjJuDgtKu9HB6427dVV7YyWCyKMuyQgvtrK7wyXqKZJYnwwKLhR3smRfnuPDVgY2TUdRmMSM2b6nDteEK4TpADsKFvHAUThYLQEtYb9UQs4gaQGmrp4FCP9qL6QuVeKxgrryzJZTezjhhfheckmnbekqwvseZJpQUvujzq5TsLHerz4CDzfjzGBBPaajVzaJD9Y5tnzHS26UNXnX3qJXBwNGfasVncLdfz6pFHSs4nFfqz92HtHsTq83w9h6yTP8gHeSPgwC4mCkGEwuNZkzyChF5nKvgruCr8SENNXrUhrb6uS33D3QgrvCkMy9qqHa97EE7DVRNdX8ZEhuwkuNs9qAxttjyaarAEtpmybDtDMzserHKqv4eSLLfGzVfHResxxqJZFE8SRr3ZGDkbVMUpnGSkBXjE7ht8rnQfpSpz2QstJ4HeFHJ9afhWRqLHd9vEpUY5MnHtu

So, I didn't understand a lot from here, but, is it a code error, or is it because of my computer, I have the latest Java, the code is specified for a mac, maybe one of the files in the JAR is missing (cr.riselauncher.Launcher)?
MacBook Air (13-inch, Mid 2012), macOS Catalina 10.15.7
The recommended version of Java, Java 8 Update 281, 1.8.0_281
Only one Java installed on my Mac, not more


text:
Q: Defining parent or super-logger name with logback I'm working on a big project with many submodules. When debugging component xyz, that component often accesses services in other modules. To log every debug message, we have to define many loggers in our logback.xml.
Is it possible to define overarching super loggers or parent loggers?
example:
instead of writing this:
<logger name="com.a.b.c.xyz" level="debug" />
<logger name="com.a.b.d.core.xyz" level="debug" />
<logger name="com.a.b.e.xyz" level="debug" />
<logger name="com.a.b.e.f.xyz" level="debug" />
<logger name="com.a.b.t.services.xyz" level="debug" />

It is possible to define something like this:
<logger name="xyz-super" level="debug">
    <child-logger name="..." />
    <child-logger name="..." />
    ...
</logger>

Once debugging module xyz is done, everyone forgetts which packages were relevant for it, so keeping these parent loggers would help with future problems.

A: If I understand what you're asking for, you have a concept of a "component" which crosses Java packages, and you want to handle setting the logging level on the basis of which component it's in, and not necessarily on which package it's in. I see a few approaches one could take.

*

*While the standard for logger name is based on the class name (and thus the Java package that the class is in), you don't need to use that for your logger names. That is, you could have a logger hierarchy which is different from your package hierarchy. In your com.a.b.c.xyz class, you can get a logger with:
final Logger logger = LoggerFactory.getLogger("com.a.b.xyz.c");

While in your com.a.b.d.core.xyz class, get a logger with:
final Logger logger = LoggerFactory.getLogger("com.a.b.xyz.d.core");

And then you just can use normal logger level definitions, setting the logging level for com.a.b.xyz to get all the loggers underneath that component. It's a bit unconventional, and may confuse developers new to your project, but if you really want your logging hierarchy and your package hierarchy to be different, it's a thing you can do.

*Another approach is to leave your logging name hierarchy as is, but use SLF4J/Logback's Marker mechanism to "mark" each log message for each component.
final Logger logger = LoggerFactory.getLogger(getClass());
final Marker xyzComponent = MarkerFactory.getMarker("XYZ");
…
logger.info(xyzComponent, "A log message");

You could then set up Filters in Logback based on the markers that you are looking for. It does require you to be consistent and make sure that every message that you care about is tagged with the appropriate Marker, but it's the closest thing to a "super logger" or "group logger" that the SLF4J architecture has. The Marker mechanism is really powerful and allows you to do just about anything with it, as long as your messages have the right Marker on them and you set up your logging configuration to filter to just the messages with the right filter.

*The other approach I can think of is to basically keep on doing what you're doing now, and specifying a lot of separate loggers at debug level, but have this "debug" logging configuration settings for each component in separate files. Then, when you need to debug a component, you just need to add (or uncomment?) the appropriate include element in your main logging settings.
In file xyz-debug.xml:
<included>
    <logger name="com.a.b.c.xyz" level="debug" />
    <logger name="com.a.b.d.core.xyz" level="debug" />
    <logger name="com.a.b.e.xyz" level="debug" />
    <logger name="com.a.b.e.f.xyz" level="debug" />
    <logger name="com.a.b.t.services.xyz" level="debug" />
</included>

In file abc-debug.xml:
<included>
    <logger name="com.a.b.c.abc" level="debug" />
    <logger name="com.a.b.d.core.abc" level="debug" />
    <logger name="com.a.b.e.abc" level="debug" />
    <logger name="com.a.b.e.f.abc" level="debug" />
    <logger name="com.a.b.t.services.abc" level="debug" />
</included>

And then in your main logback.xml:
<!--<include file="xyz-debug.xml"/>-->
<!--<include file="abc-debug.xml"/>-->

And you just uncomment the appropriate line when you need to debug that component. Perhaps a little fiddly and simplistic, and may be really confusing if somebody forgets to update the xyz-debug.xml when the xyz component is part of a new package, but I can imagine this working well enough for some teams. It also doesn't require any code changes, which may be a plus.
Logback and SLF4J have a lot of power and possibilities, which is (as usual) both a strength and a weakness as it can take a while to learn about everything that they can do. But usually one can find a way to get them to work the way one wants, and sometimes one can find a way even better than what one had in mind.