text:
Q: Proper distance in terms of the deceleration parameter So, in an effort to connect theory to measurable quantities, in the Ryden cosmology textbook the scale factor is Taylor expanded as $$a(t) \approx 1 + H_o (t-t_o) - \frac{1}{2}q_o H^2_o (t-t_o)^2$$ and $$\frac{1}{a(t)}\approx 1 - H_o(t-t_o) + (1+\frac{q_o}{2})H^2_o (t-t_o)^2$$.
Plugging $\dfrac{1}{a(t)}$ into proper distance calculation $$d_p(t_o) = c\int_{t_e}^{t_o}\dfrac{dt}{a(t)}$$ we get to keep only the two lowest order terms $d_p(t_o) \approx c(t_o - t_e) + \dfrac{cH_o}{2}(t_o - t_e)^2$.
Since $t_o - t_e$ is not directly measurable,  we replace it in terms of $z$ making use of $z = \dfrac{1}{a(t_e)}-1$, from which we get $t_o - t_e \approx \dfrac{1}{H_o}\left[z - (1 + q_o / 2)z^2\right]$.
Finally, plugging $t_o - t_e \approx \dfrac{1}{H_o}[z - (1 + q_o / 2)z^2]$ into $d_p(t_o) \approx c(t_o - t_e) + \dfrac{cH_o}{2}(t_o - t_e)^2$, we get $$d_p(t_o) \approx \frac{cz}{H_0}[1- \frac{1+q_o}{2}z]$$
if we only keep up to $z^2$. But what I don't understand is here in the last step why only keep up to $z^2$? Does this mean this whole derivation only applies to low z? Then what's the point since we know it's linear at low z anyway?

A: In short: yes, it's because the formula is only valid at low redshifts, so higher-order terms are insignificant; the measurement of $q_0$ tells you about the composition of the universe.

First off, you have to understand that $q_0$ is more of a historical artifact than a commonly used parameter nowadays; see Ryden's text right after eqn 7.6 (on page 127–128 in the online version). Why do we only keep up to $z^2$? Because this derivation only applies to low redshifts. At small enough ranges, all (sane) functions are linear, so this shouldn't be surprising or mean that this derivation was useless.
Secondly, the reason why this slope is useful is because its value tells us about the composition of the universe. See eqns 7.10 / 7.11 in the same text (page 129):
$$ q_0 = \Omega_{r,0} + \frac{1}{2} \Omega_{m,0} - \Omega_{\Lambda,0}$$
Because we only really measure $q_0$ at low redshift (generally $z<2$; roughly $z \sim 10$ is where radiation density started being insignificant in comparison to dark energy density; $\Omega_{r,0} \sim 10^{-4}$), we can then simplify this for the modern era, as all that contribute significantly are the last two terms:
$$ q_0 = \frac{1}{2} \Omega_{m,0} - \Omega_{\Lambda,0}$$
Because people used to expect that the majority of energy in the universe was matter, followed by radiation, they defined $q_0$ in such a way that they expected $q_0$ to have a positive value. It was quite the shock then the first measurements of $q_0$ yielded negative numbers! A recent measurement by Riess et al 2021 accounting for a host of potential systematic effects found that $q_0 = -.51 \pm -.024$, over $20\sigma$ significantly negative! This is conclusive evidence that (insofar as GR is to be trusted as a theory of gravity) we live in a universe with a non-trivial amount of dark energy—in fact, in a universe currently dominated by dark energy!
Thirdly, I'll give a bit more detail about why the derivation stops at $z^2$. People have gone beyond (see Vissier 2004 for jerk $j_0$ and snap $s_0$ definitions), but most cosmologists focus on cosmological parameters (like $\Omega_m$, $\Omega_\Lambda$) directly rather than Taylor coefficients which only relate indirectly to cosmological parameters. Furthermore, the higher-order terms become harder to measure significantly, so what can be learned from them about our universe is limited.


text:
Q: Expecting a variable list of arguments in PHPUnit I have an adapter that has a method taking a variable list of arguments and forwards it to a method that takes those same arguments in a framework I am using. I want to test that my adapter correctly forwards the arguments. I however do not want my test to know about which kind of arguments the framework supports.
I have a working expects as follows:
$context->expects( $this->once() )
    ->method( 'msg' )
    ->with(
        $this->equalTo( $someMessageArguments[0] ),
        $this->equalTo( $someMessageArguments[1] ),
        $this->equalTo( $someMessageArguments[2] )
    );

This is clearly not good as it assumes the length of the variable list is 3. I want to use a data provider and test with different lengths as well, in which case this code won't cut it.
Is there a sane way to do this via the PHPUnit API? I hacked this up, which also works, though seems quite evil as well:
$invocationMocker = $context->expects( $this->once() )
    ->method( 'msg' );

$invocationMocker->getMatcher()->parametersMatcher
    = new PHPUnit_Framework_MockObject_Matcher_Parameters( $someMessageArguments );

In case there is no way to do this nicely via the PHPUnit API, is there an approach that is better then the two listed here?

A: I haven't found the way to do it with PHPUnit mocks.
Using Mockery, you can archieve that:
$mock->shouldReceive('msg')
     ->once()
     ->withArgs($someMessageArguments);

Personally I normally prefer Mockery over PHPUnit mocks.
https://github.com/padraic/mockery

A: I needed to do something similar with withConsecutive.
After building an array of my arguments for consecutive calls, the following was used.
$invocationMocker->getMatcher()->setParametersMatcher(new Matcher\ConsecutiveParameters($arguments));

The PHPUnit interface and namespace has changed a little since the original post.

redpajama_set_name: RedPajamaStackExchange


text:
Q: UltraEdit / Unix regular expressions. I want to replace all lines with a name + whitespace + number with a name + # + number SANTIAGO 80,00 UltraEdit / Unix regular expressions. I want to replace all lines with a name + whitespace + number with a name + # + number
Example : SANTIAGO 80,00 will be replaced with SANTIAGO#80,00 and all the lines will proceed like that
I can find what I want searching in Unix expression :  [^t^b][0-9]

A: UltraEdit has three regular expression engines.
First solution using UltraEdit regular expression engine with a tagged regular expression:
Find what: ^([^t ]^)^([0-9]^)
Replace with: ^1#^2
Second solution using Unix or Perl regular expression engine doing the same as above also using marking groups and backreferences:
Find what: ([\t ])([0-9])
Replace with: \1#\2
These two solutions search for a horizontal tab character or a normal space followed by a digit, tag those two characters for back-referencing them in replace string which inserts # between them.
With the most powerful Perl regular expression it is also possible to just insert # between tab/space and a digit which results in less data recorded for undo.
Find what: (?<=[\t ])(?=\d)
Replace with: #
The Perl regular expression search string uses a positive lookbehind and a positive lookahead to find a position on where to insert #.
Also possible with Perl regular expression engine:
Find what: [\t ]\K(?=\d)
Replace with: #
This is the same as above, but with simply searching for a tab or space and resetting the start location of $0 to the position after the whitespace character instead of using a positive lookbehind before checking with positive lookahead if next character is a digit.


text:
Q: Animate CC - Easeljs - Multiple Draggables and Multiple Target drops I'm new to the world of stackoverflow, Javascript, Adobe Animate CC, and EaselJS. All of which I'm in the process of learning how to use. I am trying build a drag and drop activity for html5 canvas that contains 5 draggables and 5 targets. I need the each target to be able to accept and snap [into place] any of the 5 draggable.  The idea is to have the user make 5 choices then check the answers once all 5 draggables have been placed.
There are several examples of EaselJS drag and drop activities around, but the closest one I've found that fits what I need is here on codepen. I noticed several other users have used this same example as a starting point too. I've created a branch on codepen from the original posting trying to show what I am aiming for.
I'm sure there is a better way to code this, but I feel I don't have the knowledge to do so yet. Especially in the branch on codepen where I just copied and pasted to create more draggers and targets. I have made multiple "draggers" and "destinations" each with their own .setBounds then pushed the "destinations" to an array. My plan was to put a for loop around the dragger.on("pressup", function(evt) section and replace all destinations with the array "destinations[i]" containing the pushed content in hopes it would allow me to place any draggable on any target.
This didn't work. I kept getting the same error, via google chrome's developer's tool, stating cannot read property 'getBounds' on undefined. It is referring to this section here, var objBounds2 = obj2.getBounds().clone(); of the intersect function near the end of the code.
If you're still reading this and are able to following along with what I'm trying to do, then thank you. I'm sure I'm making this more complicated than it really needs to be. I need all the help I can get.
Here is where the display objects are created [draggables and targets.]
//VARIABLES
//Drag Object Size
dragRadius = 40;
//Destination Size
destHeight = 100;
destWidth = 100;

//Circle Creation
var label = new createjs.Text("RED", "14px Lato", "#fff");
label.textAlign="center";
label.y -= 7;

var circle = new createjs.Shape();
circle.graphics.setStrokeStyle(2).beginStroke("black")
.beginFill("red").drawCircle(0,0, dragRadius);

//Drag Object Creation
//Placed inside a container to hold both label and shape
var dragger = new createjs.Container();
dragger.x = dragger.y = 100;
dragger.addChild(circle, label);
dragger.setBounds(100, 100, dragRadius*2, dragRadius*2);
//DragRadius * 2 because 2*r = width of the bounding box

var label2 = new createjs.Text("RED", "bold 14px Lato", "#000");
label2.textAlign = "center";
label2.x += 50;
label2.y += 40;

var box = new createjs.Shape();
box.graphics.setStrokeStyle(2).beginStroke("black").rect(0, 0, destHeight, destWidth);
var destination = new createjs.Container();
destination.x = 350;
destination.y = 50;
destination.setBounds(350, 50, destHeight, destWidth);

destination.addChild(label2, box);

Here is the drag and drop section:
//DRAG FUNCTIONALITY =====================
dragger.on("pressmove", function(evt){
     evt.currentTarget.x = evt.stageX;
    evt.currentTarget.y = evt.stageY;
     stage.update(); //much smoother because it refreshes the screen every pixel movement instead of the FPS set on the Ticker
     if(intersect(evt.currentTarget, destination)){
       evt.currentTarget.alpha=0.2;
       box.graphics.clear();
       box.graphics.setStrokeStyle(3)
       .beginStroke("#0066A4")
       .rect(0, 0, destHeight, destWidth);

     }else{
       evt.currentTarget.alpha=1;
       box.graphics.clear();     box.graphics.setStrokeStyle(2).beginStroke("black").rect(0, 0, destHeight, destWidth);
     }

});

//Mouse UP and SNAP====================
dragger.on("pressup", function(evt) {
  if(intersect(evt.currentTarget, destination)){
    dragger.x = destination.x + destWidth/2;
    dragger.y = destination.y + destHeight/2;
    dragger.alpha = 1;
    box.graphics.clear();
    box.graphics.setStrokeStyle(2).beginStroke("black").rect(0, 0, destHeight, destWidth);
    stage.update(evt);
  }
});

Here is the function that test the current draggable with the target:
//Tests if two objects are intersecting
//Sees if obj1 passes through the first and last line of its
//bounding box in the x and y sectors
//Utilizes globalToLocal to get the x and y of obj1 in relation
//to obj2
//PRE: Must have bounds set for each object
//Post: Returns true or false

  function intersect(obj1, obj2){
  var objBounds1 = obj1.getBounds().clone();
  var objBounds2 = obj2.getBounds().clone();

  var pt = obj1.globalToLocal(objBounds2.x, objBounds2.y);

  var h1 = -(objBounds1.height / 2 + objBounds2.height);
  var h2 = objBounds2.width / 2;
  var w1 = -(objBounds1.width / 2 + objBounds2.width);
  var w2 = objBounds2.width / 2;

  if(pt.x > w2 || pt.x < w1) return false;
  if(pt.y > h2 || pt.y < h1) return false;

  return true;
}

//Adds the object into stage
stage.addChild(destination, dragger, destination2, dragger2, destination3, dragger3);
stage.mouseMoveOutside = true;
stage.update();

*Sorry I don't have rep points to post more links showing other users posts or any images.

A: I was getting this error too. I'm also really new to EaselJS and Animate CC. What seems to have worked for me (I don't know if this is an actual fix, but it seems to be working for me). I tried using nominalBounds on it but that uses the original, untransformed size of the destination. so I tried this:
desination.setBounds(desination.x, desination.y, desination.width, desination.height);

I'd just stick that after you have the destination set up, but outside of the pressup, pressmove, or intersect functions.
this  * seems *  to be working for me for now, let me know if it works for you. :)
EDIT: also, I found this by the same guy. He added a few things to it for multiple destinations http://codepen.io/samualli/pen/azNroN/


text:
Q: what's the purpose of enclosing an interface object reference with parenthesis? I saw this code snippet in the oracle website's java tutorial
https://docs.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html
public Object findSmallest(Object object1, Object object2) {
   Relatable obj1 = (Relatable)object1;
   Relatable obj2 = (Relatable)object2;
   if ((obj1).isLargerThan(obj2) < 0)
      return object1;
   else
      return object2;
}

public boolean isEqual(Object object1, Object object2) {
   Relatable obj1 = (Relatable)object1;
   Relatable obj2 = (Relatable)object2;
   if ( (obj1).isLargerThan(obj2) == 0)
      return true;
   else
      return false;
}

you see the obj1 inside the if statement is enclosed with parenthesis while the dot is appended to it, how come? what's the purpose of enclosing it with parenthesis? , I thought for as long as an object reference is used with a dot and attach a method name , it's ok already, but how come this code enclosed it with (obj1).methodName ?

A: If the reference is a simple identifier, as in this case, parens are unnecessary, but still perfectly legal.  Thus, writing (obj1).isLargerThan(obj2) is exactly the same as writing obj1.isLargerThan(obj2).

A: Enclosing obj1 is braces is not needed, and its not creating any difference.
 Both of the below statements are same and no difference whatsoever.
if ((obj1).isLargerThan(obj2) < 0)
if (obj1.isLargerThan(obj2) < 0)
Thanks


text:
Q: Elasticsearch install custom plugins results in ERROR: `elasticsearch` directory is missing in the plugin zip When I try to install the plugin I built by calling
./elasticsearch-plugin install file:///fullpath/to/zipfile/custome_plugin.zip

It gives me this error:
ERROR: `elasticsearch` directory is missing in the plugin zip

I was reading some other similar posts and many tried to install a .jar instead of .zip. I did try installing .zip, but this same error still shows.
Additionally (might not be related to this issue), when I manually unzip the zip file and put it into plugin folder, doing elasticsearch-plugins list does list out the custom plugin. In this case the plugin is a custom analyzer, but somehow the mapping doesn't recognize the analyzer. Is it because I did not install it properly?
EDIT:
adding a little info, when I shut down the cluster and then restart after the plugin is manually unzipped and put into the plugin directory, the cluster wouldn't start. I got error that looks like
[2017-08-31T11:15:52,668][ERROR][o.e.b.ElasticsearchUncaughtExceptionHandler] [] fatal error in thread [main], exiting
java.lang.NoClassDefFoundError: org/elasticsearch/index/analysis/AnalysisModule$AnalysisBinderProcessor
    at java.lang.Class.getDeclaredConstructors0(Native Method) ~[?:1.8.0_65]
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671) ~[?:1.8.0_65]
    at java.lang.Class.getConstructor0(Class.java:3075) ~[?:1.8.0_65]
    at java.lang.Class.getConstructor(Class.java:1825) ~[?:1.8.0_65]
    at org.elasticsearch.plugins.PluginsService.loadPlugin(PluginsService.java:423) ~[elasticsearch-5.5.2.jar:5.5.2]
    at org.elasticsearch.plugins.PluginsService.loadBundles(PluginsService.java:387) ~[elasticsearch-5.5.2.jar:5.5.2]
    at org.elasticsearch.plugins.PluginsService.<init>(PluginsService.java:140) ~[elasticsearch-5.5.2.jar:5.5.2]
    at org.elasticsearch.node.Node.<init>(Node.java:312) ~[elasticsearch-5.5.2.jar:5.5.2]
    at org.elasticsearch.node.Node.<init>(Node.java:244) ~[elasticsearch-5.5.2.jar:5.5.2]
    at org.elasticsearch.bootstrap.Bootstrap$5.<init>(Bootstrap.java:232) ~[elasticsearch-5.5.2.jar:5.5.2]
    at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:232) ~[elasticsearch-5.5.2.jar:5.5.2]
    at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:351) ~[elasticsearch-5.5.2.jar:5.5.2]
    at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:123) ~[elasticsearch-5.5.2.jar:5.5.2]
    at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:114) ~[elasticsearch-5.5.2.jar:5.5.2]
    at org.elasticsearch.cli.EnvironmentAwareCommand.execute(EnvironmentAwareCommand.java:67) ~[elasticsearch-5.5.2.jar:5.5.2]
    at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:122) ~[elasticsearch-5.5.2.jar:5.5.2]
    at org.elasticsearch.cli.Command.main(Command.java:88) ~[elasticsearch-5.5.2.jar:5.5.2]
    at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:91) ~[elasticsearch-5.5.2.jar:5.5.2]
    at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:84) ~[elasticsearch-5.5.2.jar:5.5.2]
Caused by: java.lang.ClassNotFoundException: org.elasticsearch.index.analysis.AnalysisModule$AnalysisBinderProcessor
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[?:1.8.0_65]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[?:1.8.0_65]
    at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:814) ~[?:1.8.0_65]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[?:1.8.0_65]
    ... 19 more

It seems like this Analysis
Is there some library I'm missing?
EDIT 2:
After some more digging, I found this site
http://snacktrace.com/artifacts/org.elasticsearch/elasticsearch/1.7.3/org.elasticsearch.index.analysis.AnalysisModule$AnalysisBinderProcessor$AnalyzersBindings
Seems like this AnalyzersBindings is only for ES 1.x and 2.x (<2.4)? I need a way to replace this.
EDIT 3:
As requested, here's how AnalyzerBinding is used originally
package org.elasticsearch.plugin.analysis.my.analyzer;

import org.elasticsearch.index.analysis.AnalysisModule;

public class AnalyzerBinderProcessor extends AnalysisModule.AnalysisBinderProcessor {

    @Override
    public void processAnalyzers(AnalyzersBindings analyzersBindings) {
        analyzersBindings.processAnalyzer("my_name", AnalyzerProvider.class);
    }

    @Override
    public void processTokenFilters(TokenFiltersBindings tokenFiltersBindings) {
    }
}

then in my AnalyzerPlugin.java I have
public class AnalyzerPlugin extends Plugin {
    //some other code here that's not related to Binder

    public void onModule(AnalysisModule module) {
        module.addProcessor(new AnalyzerBinderProcessor());
    }
}

EDIT 4: this is neverending.......
if I keep the @Override, it throws
[ERROR] /opt/bg/analytics/src/java/src/analyzer5.0/src/main/java/org/elasticsearch/plugin/analysis/my_analyzer/AnalyzerPlugin.java:[16,5] method does not override or implement a method from a supertype

Also, facing an issue of
[ERROR] /opt/bg/analytics/src/java/src/analyzer5.0/src/main/java/org/elasticsearch/plugin/analysis/my_analyzer/AnalyzerPlugin.java:[36,17] onModule(org.elasticsearch.indices.analysis.AnalysisModule) in org.elasticsearch.plugin.analysis.my_analyzer.AnalyzerPlugin cannot override onModule(org.elasticsearch.indices.analysis.AnalysisModule) in org.elasticsearch.plugins.Plugin

because overridden method is final
Is that an update from old Plugin to new? I'm so lost......
I feel like I need a thorough tutorial of how to create a plugin for custom analyzer, all I can find so far is this
http://david.pilato.fr/blog/2016/10/16/creating-a-plugin-for-elasticsearch-5-dot-0-using-maven-updated-for-ga/
which doesn't help much. Does anyone have a good link?

A: Looks like you already have fixed your error.
However, I thought I would add my learning in case there are people who are getting ERROR: 'elasticsearch' directory is missing in the plugin zip becasue of the same mistake that I made.
As it is stated in Elasticsearch documentation (https://www.elastic.co/guide/en/elasticsearch/plugins/current/plugin-authors.html), the folder name of the plugin should be "elasticsearch" before the folder is compressed to a zip file.
So, regardless of the zip file's name like "elasticsearch-analysis-mecab-ko-5.5.3.0.zip", the plugin folder before compressed should be called "elasticsearch". If the folder name is not "elasticsearch", when you run elasticsearch-plugin install, your elasticsearch simply gives you ERROR: 'elasticsearch' directory is missing in the plugin zip
Thus, after you make or amend your custom plugin folder, compress it:
$ zip -r elasticsearch-analysis-mecab-ko-5.5.3.0.zip elasticsearch
then install the plugin
$ ./elasticsearch-plugin install file:///Users/btaek/Desktop/ElasticSearch/elasticsearch-analysis-mecab-ko-5.5.3.0.zip

A: Currently, in ES 5.x we have org.elasticsearch.plugins.AnalysisPlugin, which is the main point for creating custom analysis components. You need to adapt your plugin code, so you could register whatever custom analyzer/tokenizer/etc you have.
Example of the plugin, that should do the trick for you:
public class MyAnalyzerPlugin implements AnalysisPlugin {

@Override
public Map<String, AnalysisModule.AnalysisProvider<AnalyzerProvider<? extends Analyzer>>> getAnalyzers() {
    final Map<String, AnalysisModule.AnalysisProvider<AnalyzerProvider<? extends Analyzer>>> objectObjectHashMap = new HashMap<>();
    objectObjectHashMap.put("my_analyzer", new MyAnalyzerProviderFactory());
    return objectObjectHashMap;
}

class MyAnalyzerProviderFactory implements AnalysisModule.AnalysisProvider<AnalyzerProvider<?>> {

    private final MyAnalyzerProvider analyzerProvider;

    public MyAnalyzerProviderFactory() {
        analyzerProvider = new MyAnalyzerProvider(AnalyzerScope.INDICES);
    }

    public AnalyzerProvider<?> create(String name, Settings settings) {
        Version indexVersion = Version.indexCreated(settings);
        if (!Version.CURRENT.equals(indexVersion)) {
            PreBuiltAnalyzers preBuiltAnalyzers = PreBuiltAnalyzers.getOrDefault(name, null);
            if (preBuiltAnalyzers != null) {
                Analyzer analyzer = preBuiltAnalyzers.getAnalyzer(indexVersion);
                return new MyAnalyzerProvider(AnalyzerScope.INDICES);
            }
        }

        return analyzerProvider;
    }

    @Override
    public AnalyzerProvider<?> get(IndexSettings indexSettings, Environment environment, String name, Settings settings)
            throws IOException {
        return create(name, settings);
    }

    public Analyzer analyzer() {
        return analyzerProvider.get();
    }
}

class MyAnalyzerProvider implements AnalyzerProvider<StandardAnalyzer> {

    private final StandardAnalyzer analyzer;
    private final AnalyzerScope scope;

    public MyAnalyzerProvider(AnalyzerScope scope) {
        this.scope = scope;
        this.analyzer = new StandardAnalyzer();
    }

    @Override
    public String name() {
        return "my-standard-analyzer";
    }

    @Override
    public AnalyzerScope scope() {
        return scope;
    }

    @Override
    public StandardAnalyzer get() {
        return analyzer;
    }
}

Of course, you need to adapt your Analyzer as well, since Lucene version has been changed and some API may be deprecated or removed.


text:
Q: What's the default version of a binary marked as both modified in Git? If the conflict happen on a binary or any non-text files that can't be resolved by using text editor, I should use git checkout --theirs or git checkout --ours instead, then add them into the staging area.
But, if I just do nothing, add those unmerged binaries into staging area directly, without resolving the conflict, without choosing a proper version, which version will be added into staging area ? Ours or theirs ?
Unmerged paths:
  (use "git add/rm <file>..." as appropriate to mark resolution)

      both modified: test.bin
      both modified: test.a

A: There are times when it is appropriate to check in a binary file, images, videos, office documents... but they cannot be merged. You have to pick one or the other or make a new version.
But these look like build artifacts; files generated as part of the build process. Those should not be checked in. They will fall out of date with their source code, and they will be different on different people's machines who have different compilers and different libraries.
Remove them with git rm and then add them to the project's .gitignore so they don't come back. You'll probably want to ignore entire classes of files like *.a and *.o and *.bin. gitignore.io can generate a good starting ignore file for your project.

A:
If the conflict happen on a binary or any non-text files that can't be resolved by using text editor, I should use git checkout --theirs or git checkout --ours instead ...

This is not necessarily true.  Just as with plain text files, where sometimes the correct resolution is in fact a combined change, the correct resolution of some binary files may be a combined change.  It's just that Git cannot do this for you.  The only way to do it correctly may be to find a source file or files, and some sort of source-to-binary translator.  You may need to combine the source changes, compile / translate the result to a new, third binary, and use that.
Nonetheless, this question has an answer.  It just may be pointless to study and memorize it.

But, if I just do nothing, add those unmerged binaries into staging area directly ...

What git add does is to copy whatever is in the work-tree into the index / staging-area at slot zero, removing any higher-stage entries.  What you have during the conflict is three different binaries, in the index / staging area, but using slots 1 (merge base), 2 (ours), and 3 (theirs).
Hence, this just means Copy the work-tree file into slot zero and remove the entries in slots 1, 2, and 3.  So the question is the same as:
What does Git leave in the work-tree in the case of a conflict in a binary file?
The answer to that is in both the git merge documentation and the gitattributes documentation.  This makes it hard to read.
The first one says, regarding the recursive and resolve strategies, that there are additional arguments that affect the result.  These additional arguments are the -X ours and -X theirs arguments, which mean:

ours
    This option forces conflicting hunks to be auto-resolved cleanly by favoring our version. Changes from the other tree that do not conflict with our side are reflected to the merge result. For a binary file, the entire contents are taken from our side.
    ...
theirs
    This is the opposite of ours; note that, unlike ours, there is no theirs merge strategy to confuse this merge option with.

The gitattributes documentation adds this:

Performing a three-way merge
    ...
    The attribute merge affects how three versions of a file are merged when a file-level merge is necessary ...

and then goes on to say that most of them "[k]eep the version from your branch in the work tree".  So in general the work-tree matches index-slot-2, which you can test by doing git checkout-index --temp --stage=2 test.bin and comparing the resulting file to test.bin.
It's not clear whether such attributes override -X theirs; you will have to test this, if you set your own merge attributes and use -X theirs, by comparing what's in the work-tree against what's in index slots 2 and 3.
In general, though, most approaches mostly leave the "ours" version in the work-tree.  If that's appropriate, you can use git add to copy the work-tree version back to slot zero and erase slots 1-3, marking the file as resolved.  Just be sure that if you have used -X theirs and/or some sort of interesting merge setting, that you know what you are doing and have double checked everything.
(Your best bet, of course, is to avoid merging binary files this way.)


text:
Q: pass associative array in input field in form PHP I want to know the best and easiest way to pass associative array in form inside input field. So far Ive done this and it all started to look messy and hard to handle.
$dish_result = $obj->getAll_dish();// this returns array all the rows in dish table
<form action='order_process.php' method='post'>
   foreach ($dish_result as $dish){
     echo '<input id="" name="dish_name[]" type="checkbox" value="'. $dish['dish_name'].'">';
     echo '<input id="" name="dish_number[]" type="checkbox" value="'. $dish['dish_number'].'">';
     }
</form>

Now on the order_process.php I have
 foreach($_POST['dish_name'] as $dish){
        echo $dish;
  }
 foreach($_POST['dish_number'] as $num){
       echo $num;
 }

What I wanted is an associative array, but how can I associate it the form dynamically. in other words I wanted to achieve this on the order_process.php.
 $dishes = array(
       //'dish_name' => dish_number
      'chickencurry' => '70',
      'onionbhajis'  =>  '22'
       // and so on.
  );

Thank you very much in advance.

A: Create a grouping name first, then to get that kind of structure, make the dish name as key, then the value attribute holds the number. The basic idea is this:
name="dish[dishname]" value="dish_number"

It'll be like this:
echo '<input id="" name="dish['.$dish['dish_name'].']" type="checkbox" value="'. $dish['dish_number'].'" />';

When you submit it with all the checkbox checked, it should be something like:
Array
(
    [chickencurry] => 1
    [onionbhajis] => 2
)

On the order_process.php page, just call it just like you normally do:
$dishes = $_POST['dish'];
foreach($dishes as $dish_name => $dish_number) {

}

Sample Output

A: You can add an index to array postdata. Try this:
  foreach ($dish_result as $dish){
      echo '<input id="" name="dishes['.$dish['dish_name'].']" type="checkbox" value="'. $dish['dish_number'].'">';
  }

Your data will then be an associative array of the checked elements when posted back.


text:
Q: Angular 2.0.0 final - Custom Pipe filtering with multiple from field conditions I am trying to filter foods with multiple from field conditions (input & drop-down). I can filter them separately, but I can't figure out how to make them work together.
I've created two separate Custom Pipes (one for the input filter and one for the drop-down filter) to make thing more modular.
Here is the logic behind the Input Pipe:
// Input Filter
transform(value: IProduct[], filter: string): IProduct[] {
    filter = filter ? filter.toLocaleLowerCase() : null;
    return filter ? value.filter((product: IProduct) =>
        product.prodName.toLocaleLowerCase().indexOf(filter) !== -1) : value;
}

the logic behind the Dropdown Pipe:
// Dropdown Filter
transform(value: IProduct[], filter: string): IProduct[] {
    return filter ? value.filter((product: IProduct) =>
        product.prodCategory.indexOf(filter) !== -1) : value;
}

This is the custom pipe in the template view:
<tr *ngFor='let _product of _products | DropdownProductFilter: ddlistFilter.name ||  InputProductFilter: listFilter'

Here is a the example
http://plnkr.co/qwsk86hHLbI26w3HVMdV

A: I think you have a typo in your template, change your || to | will do the trick:
<tr *ngFor='let _product of _products | DropdownProductFilter: ddlistFilter.name |  InputProductFilter: listFilter'>


text:
Q: Java - editable and searchable list of strings I want to make a searchable and editable list of strings. So I want to search in it and I want to add strings to it when the program is running.
Something like this:
String[] list  // how should this line look like?
list.add("qq");
list.add("ww");
if(list.contains("qq")) {
    //do something
}

How should I do it?


text:
Q: Pre-Build Output file to Release project directory C# I'm new on pre-build and have a external file to copy:
G:\temp\andre\InstaladorCertificados.zip
And i need to put this .zip file in \bin\Release in my project in Pre-Build event command line.
I'm trying that script: xcopy "$G:\temp\andre\InstaladorCertificados.zip" "$(OutDir)"
And i get that error: The command "xcopy "$G:\temp\andre\InstaladorCertificados.zip" "$(OutDir)"" exited with code 4.
Is there a way to copy a external file to my project in pre-build event ?


text:
Q: Check if this series is convergent or not I've been going crazy for a long time in determining if this series converges or diverges. Most likely it converges.
$\displaystyle \sum_{n=1}^\infty \left(\frac{n}{2}\, \sin\frac{1}{n}\right)^\frac{n^2+1}{n+2}$
I am stuck in the necessary condition.
I tried to solve in this way :
$\displaystyle \frac{1}{2}\lim_{n \to \infty} \left(\frac{\sin\frac{1}{n}}{\frac{1}{n}}\right)^\frac{n^2+1}{n+2} = \frac{1}{2}\lim_{n \to \infty} (1)^\infty$
To solve this indeterminate form, I tried to use the exponential in this way
$\displaystyle  \frac{1}{2}\lim_{n \to \infty} \left(e^{\frac{n^2+1}{n+2}log \left(\frac{sin \frac{1}{n}}{\frac{1}{n}}\right)}\right)$
In this way I always get an indeterminate form
$\displaystyle \frac{1}{2}\lim_{n \to \infty} (e^{\infty *0})$
could you kindly give me support for the resolution of the character of this series?

A: Letting
$$
a_n
=
\left(
\frac{n}{2}
\cdot
\sin\Bigl(\frac{1}{n}\Bigr)
\right)
^{\large{\frac{n^2+1}{n+2}}}
$$
we have $a_n > 0$ for all positive integers $n$, so we get
$$
\lim_{n\to\infty}
|a_n|
^
\frac{1}{n}
=
\lim_{n\to\infty}
(a_n)
^
\frac{1}{n}
=
\lim_{n\to\infty}
\left(
\frac{1}{2}
\cdot
\frac
{\sin\Bigl({\large{\frac{1}{n}}}\Bigr)}
{\Bigl({\large{\frac{1}{n}}}\Bigr)}
\right)
^{{\large{\frac{n^2+1}{n^2+2n}}}}
=
\Bigl(
\frac{1}{2}
\cdot
1
\Bigr)
^1
=
\frac{1}{2}
$$
hence by the root test, ${\displaystyle{\sum_{n=1}^\infty a_n}}$ converges.

A: Using the ratio test
$$a_n
=
\left(
\frac{n}{2}
\,
\sin\Bigl(\frac{1}{n}\Bigr)
\right)
^{\large{\frac{n^2+1}{n+2}}}\implies
\log(a_n)=\frac{n^2+1}{n+2}\log\left(
\frac{n}{2}
\,
\sin\Bigl(\frac{1}{n}\Bigr)
\right)$$
For large $n$, compose Taylor expansion
$$\log(a_n)=\frac{n^2+1}{n+2}\bigg[-\log (2)-\frac{1}{6 n^2}+O\left(\frac{1}{n^4}\right) \bigg]$$
$$\log(a_n)=n \log (2)+2 \log (2)+\frac{-\frac{1}{6}-5 \log (2)}{n}+\frac{\frac{1}{3}+10 \log (2)}{n^2}+O\left(\frac{1}{n^3}\right)$$ Replace $n$ by $n+1$ and continue with long division
$$\log(a_{n+1})-\log(a_n)=-\log (2)+\frac{\frac{1}{6}+5 \log (2)}{n^2}+O\left(\frac{1}{n^3}\right)$$
Now
$$\frac {a_{n+1}}{a_n}=e^{\log(a_{n+1})-\log(a_n)}=\frac{1}{2}+\frac{\frac{1}{6}+5 \log (2)}{2 n^2}+O\left(\frac{1}{n^3}\right)$$


text:
Q: make random numbers for each row and column I will edit some fake data in my database. But if I will make random numbers for each row and column, it is not so random as I want it. The result can you see on image below.

Here is my code I use:
WITH x AS
(
    SELECT mintwee, mineen, nul, pluseen, plustwee
    FROM Topic
)
SELECT mintwee = CAST(RAND()*100 AS INT),
       mineen = CAST(RAND()*100 AS INT),
       nul = CAST(RAND()*100 AS INT),
       pluseen = CAST(RAND()*100 AS INT),
       plustwee = CAST(RAND()*100 AS INT)
FROM x

and this:
WITH x AS
(
    SELECT
        mintwee = CAST(RAND()*100 AS INT),
        mineen = CAST(RAND()*100 AS INT),
        nul = CAST(RAND()*100 AS INT),
        pluseen = CAST(RAND()*100 AS INT),
        plustwee = CAST(RAND()*100 AS INT)
    FROM Topic
)
SELECT mintwee, mineen, nul, pluseen, plustwee
FROM x ;

But both has the same result. I know, I must use an UPDATE statement, but this is only for try if the result is good. After it, I am going to use the UPDATE statement.
I use SQL server with an express 2014 version.

A: Since there is no correlation between the table rows and the RAND function, the expression is evaluated only once in the query.
One method to generated random values is with the NEWID() function.  The example below generates random integer values between 0-99 range.  The modulo value can be adjusted for a different range and you can use this basic technique to generate random values for dates, character, etc.
WITH x AS
(
  SELECT mintwee, mineen, nul, pluseen, plustwee
  FROM Topic
)
SELECT mintwee = CAST(SUBSTRING(CAST(NEWID() AS binary(16)),1, 3) AS int) % 100,
       mineen = CAST(SUBSTRING(CAST(NEWID() AS binary(16)),1, 3) AS int) % 100,
       nul = CAST(SUBSTRING(CAST(NEWID() AS binary(16)),1, 3) AS int) % 100,
       pluseen = CAST(SUBSTRING(CAST(NEWID() AS binary(16)),1, 3) AS int) % 100,
       plustwee= CAST(SUBSTRING(CAST(NEWID() AS binary(16)),1, 3) AS int) % 100
FROM x;

EDIT:
Per Aaron's comment, the expression can be simplified if you need only 32-bit integers.  Additional examples:
--postive int
SELECT ABS(CHECKSUM(NEWID()));
--postive and negative int
SELECT CHECKSUM(NEWID());
--postive bigint
SELECT CAST(SUBSTRING(CAST(NEWID() AS binary(16)),1, 7) AS bigint);
--negative and postive bigint
SELECT CAST(SUBSTRING(CAST(NEWID() AS binary(16)),1, 8) AS bigint);
--dates between now and 1 year ago
SELECT DATEADD(day, -ABS(CHECKSUM(NEWID())) % 365, GETDATE());
--random uppercase character
SELECT CAST(CAST(65 + ABS(CHECKSUM(NEWID()) % 26) AS binary(1)) AS char(1));

A: Try this:
select Rand1.n as RandomIntegerBetweenAB
     , Rand2.n as RandomIntegerBetweenXY
     , DateAdd(Day, Rand2.n, GetDate()) as RandomDateAddBetweenXY
     , Rand3.n as RandomInteger
from api.RandomIntBetween(0, 100) as Rand1
cross apply api.RandomIntBetween(-365, 365) as Rand2
cross apply api.RandomIntBetween(default, default) as Rand3;

We use this view to generate a random integer (only because SQL Server won't simply let us use Crypt_Gen_Random() in a UDF):
create view api.vw_RandomInt
with schemabinding
as (
    select Cast(Crypt_Gen_Random(4) as int) as n
);

Using this view as a base we can get whatever random integer and then do some maths to rescale it:
create function api.RandomIntBetween (
    @x int = -2147483648
  , @y int = 2147483647
)
returns table
with schemabinding as
return (
    select Cast(Round(c.f, 0, 0) as int) as n
    from (values(
        case when @x < @y then @x else @y end
      , case when @y > @x then @y else @x end
    )) a ([Min], [Max])
    cross join api.vw_RandomInt as b
    cross apply api.NormalizeBetween(
        b.n
      , -2147483648
      , 2147483647
      , a.[Min] - 0.5
      , a.[Max] + 0.5
    ) as c
);

Where the definition of NormalizeBetween is:
create function api.NormalizeBetween (
    @f float = 1.
  , @x float = 0.
  , @y float = 1.
  , @a float = 0.
  , @b float = 1.
)
returns table
with schemabinding as
return (
    select ((@f - @x) * (@b - @a)) / NullIf(@y - @x, 0) + @a as f
);


text:
Q: update row with additional value only I have a column called tags which includes various tags for an item. It looks like this:
news,article,sunday,times
I want to update this to
news,article,sunday,times,dining
Is there a way to do it with an update query? For an integer value you can mention in your query col_name=col_name+100, is there a way for a string value to do the same?
Any help will be appreciated.

A: You can do concat() something as
update table
set
tags = concat(tags,',','dining');


text:
Q: SSO to Apps on AWS Can someone help me with my understanding?
So i understand how one can use ADFS and SAML to provide SSO access to the Console via IAM. However im not as clear how this can be done at the application level
So take MS Dynamics as an example. It will be on an EC2 instance which is on a domain controller hosted in the VPC (for mgt etc). However the users themselves will be in an on-prem AD server and we'd want to authenticate users accessing the dynamics web front end with that on-prem AD server. Is this as simple as setting up ADFS between the two sites and configuring the app itself to use ADFS / SAML for claims based authentication?

A: For application level support, it depends on the ability of the app to support claims based/SAML authentication. CRM supports ADFS configuration. You have one of 2 choices

*

*You can hook it up directly to your on-premises ADFS if it is really about just providing access to your corporate employees. If it requires partner access that ADFS can still federate to other ADFS/IDP organizations.

*You can set one up in AWS next to or on the DC that it has and treat it as a Federation Provider and then set up trust to the corporate ADFS where the users live.

I'd recommend #1 as it is simpler. Go with #2 only if you are operating this as a different company or you are building multiple server apps in this AWS site that require local ADFS for things like server to server communication.
Thanks
//Sam


text:
Q: Interpret predicted probabilities in multiclass logistic regression I have a dataset as given below where A,B,C,D,E are features and 'T' is Target Variable.
A     B    C     D     E       T
32    22   55    76    98      3
12    41   90    56    33      2
31    78   99    67    89      1
51    85   71    21    37      1
......
......

Now, I have applied multiclass logistic regression classifier using Scikit Learn and get predict values and matrix of probablities as:-
 A     B    C     D     E       T   Predicted    Probablity
32    22   55    76    98       3     3           0.35
12    41   90    56    33       2     1           0.68
31    78   99    67    89       1     3           0.31
51    85   71    21    37       1     1           0.25

Now just want to ask how to I interpret the outcome probablities,
1) As far I have studied that python by default gives the probablity of event to be 1. So if this is the case, is 0.35 considered to be  probablity of being event 1?
OR
2) is value 0.35 is possibility of 1st case to be belongs from class "3"?
How could I calculate probablities for remaining two classes. Something like:-
 A     B    C     D     E       T   Predicted     P_1    P_2    P_3
32    22   55    76    98       3     3           0.35   0.20   0.45
12    41   90    56    33       2     1           0.68   0.10   0.22
31    78   99    67    89       1     3           0.31   0.40   0.29
51    85   71    21    37       1     1           0.25   0.36   0.39

A: from sklearn.linear_classifier import LogisticRegression

lr = LogisticRegression(random_state = 1)
lr.fit(x_train,y_train)

We fit our training data.
lr.predict_proba(x_test)

Suppose the dataset contains three classes.The output will be something like:
array([[  2.69011925e-02,   5.40807755e-01,   4.32291053e-01],
   [  9.32525056e-01,   6.73606657e-02,   1.14278375e-04],
   [  5.24023874e-04,   3.24718067e-01,   6.74757909e-01],
   [  4.75066650e-02,   5.86482429e-01,   3.66010906e-01],
   [  1.83396339e-02,   4.77753541e-01,   5.03906825e-01],
   [  8.82971089e-01,   1.16720108e-01,   3.08803089e-04],
   [  4.64149328e-02,   7.17011933e-01,   2.36573134e-01],
   [  1.65574625e-02,   3.29502329e-01,   6.53940209e-01],
   [  8.70375470e-01,   1.29512862e-01,   1.11667567e-04],
   [  8.51328361e-01,   1.48584654e-01,   8.69851797e-05]])

In given output array, each row has 3 columns, showing respective probability for each class. Each row represents a sample.
lr.predict_proba(x_test[0,:]) **OR** lr.predict_proba(x_test)[0,:]

Output:
array([ 0.02690119,  0.54080775,  0.43229105])

i.e probability for that sample.

A: Not sure where your results table came from (which API call(s)) but your second hypothesis is correct. In the table below
 A     B    C     D     E       T   Predicted    Probablity
32    22   55    76    98       3     3           0.35
12    41   90    56    33       2     1           0.68
31    78   99    67    89       1     3           0.31
51    85   71    21    37       1     1           0.25

you have the results of what  I assume are 4 different samples (instances), with the target variable (correct class), predicted class, and the probability of the predicted class.
I think you have a problem with an indexing routine in your code. Let's focus on the last row
 A     B    C     D     E       T   Predicted    Probablity
51    85   71    21    37       1     1           0.25

The probability of the predicted class is 0.25 or 25% and you have a three class problem. This means that the total probability mass for the other two classes is 1 - 0.25 = 0.75, if you divide that 75% evenly between the remaining two classes (that were supposedly not the prediction of the classifier) you get 0.75 / 2 = 0.375 - or 37.5% probability for both class 2 and 3 (you predicted 1). Of course the classifier won't have equal probability for both 2 and 3 so one will be lower while the other will be higher. The problem is that the 37.5% is already higher than the probability of your predicted class 1, which is not logically possible. If the classifier gives probability 37.5% to class 2 and 25% to class 1 then surely the prediction should be class 2, not class 1 like you have above.
The output from logistic regression is a table of probabilities with a row for each instance and a column for each class, for instance
probs = array([[  2.69011925e-02,   5.40807755e-01,   4.32291053e-01],
   [  9.32525056e-01,   6.73606657e-02,   1.14278375e-04],
   [  5.24023874e-04,   3.24718067e-01,   6.74757909e-01],
   [  8.70375470e-01,   1.29512862e-01,   1.11667567e-04],
   [  8.51328361e-01,   1.48584654e-01,   8.69851797e-05]])

The probability of the 3rd class for the first instance is in the third column of the first row probs[0, 2]. If you want the predicted classes from the array you can do predicted_idx = np.argmax(probs, axis=1), that gives you array([1, 0, 2, 0, 0]) for the above data, which is the column index of the highest predicted probability. You can then extract the probability of only the predicted classes by
probs[range(probs.shape[0]), predicted_idx]
>> array([ 0.54080776,  0.93252506,  0.67475791,  0.87037547, 0.85132836])

Finally, you have to keep in mind that the column index in the results table does not necessarily correspond to the way your data set is indexed. If you use something like sklearn.preprocessing.LabelEncoder it may be the case that the class you thought was at index 0, is not in fact at index 0. You can check this from label_binarizer.classes_ - the order of that array corresponds to column indices in the probability array you get from logistic regression.


text:
Q: Relationship between Naive Bayes and MLE I have found various references describing Naive Bayes and they all demonstrated that it used MLE for the calculation. However, this is my understanding:
$P(y=c|x)$ $\propto$ $P(x|y=c)P(y=c)$
with $c$ is the class the model may classify $y$ as.
And that's all, we can infer $P(x|y=c)$ and $P(c)$ from the data. I don't see where the MLE shows its role.

A: The relationship is that the overall model is Naive Bayes, but there is an MLE estimate for parameters in this model. We have two kinds of parameters in a Naive Bayes model: $q(y)$ and $q_j(x_j|y)$ in the model $$p(y, x_1, \dots, x_d) = q(y)\prod q_j(x_j|y)$$ and each of them have an MLE given by $\hat{q(y)} = \frac{\text{count}(y)}{n}$ and $\hat{q_j} = \frac{\text{count}_j(x|y)}{\text{count(y)}}$.
More details can be found in these lecture notes.


text:
Q: Is there a way to combine partial pattern matching with return? I'm writing a Haskell program that uses blaze-html to construct an HTML document. When a title :: Maybe Text is not Nothing, I want to produce an h1 from it. I can do it like this:
case title of
  Just t  -> H.h1 $ toHtml t
  _       -> return ()

Or, in the specific case of Maybe, I can do it like this:
when (title /= Nothing) $ H.h1 $ toHtml $ fromJust title

Can I have (perhaps with a GHC extension) something that looks more like the second example, but for arbitrary ADTs? Something like partial pattern matching that just defaults to return (). I imagine syntax like this:
-- imaginary syntax
when title of Just t -> H.h1 $ toHtml t

A: What you want is a function of the following type:
Applicative f => Maybe a -> (a -> f ()) -> f ()

Using Hoogle you can find several options. So it seems like the most common name for this function is whenJust. You can find it for example in the relude library.
If you're interested in a generic solution for this problem, the closest thing to achieve is to use prisms from the lens library. Below I provide the complete code with a followup explanation:
{-# LANGUAGE Rank2Types      #-}
{-# LANGUAGE TemplateHaskell #-}

module Prism where

import Control.Lens (Prism', makePrisms, preview)

data Foo
    = Bar String
    | Baz Int
    | Quux Bool

makePrisms ''Foo

whenMatched :: Applicative f => Prism' s a -> s -> (a -> f ()) -> f ()
whenMatched prism val f = case preview prism val of
    Nothing -> pure ()
    Just a  -> f a

Function makePrisms is a Haskell macro which requires to enable TemplateHaskell extension. This function will generate prisms with names _Bar, _Baz and _Quux. You can inspect their type in GHCi:
λ: :t _Bar
_Bar
  :: (profunctors-5.3:Data.Profunctor.Choice.Choice p,
      Applicative f) =>
     p String (f String) -> p Foo (f Foo)
λ: :t _Baz
_Baz
  :: (profunctors-5.3:Data.Profunctor.Choice.Choice p,
      Applicative f) =>
     p Int (f Int) -> p Foo (f Foo)

Types probably look scary but this is because of complicated internals of the lens library. I've implemented whenMatched function that should help to work with prisms in a simpler way. Here is how you can use it:
λ: whenMatched _Bar (Bar "foo") putStrLn
foo
λ: whenMatched _Bar (Baz 42) putStrLn


text:
Q: How to fix following error: InvalidArgumentException: Auth guard [jwt] is not defined I have followed following guide to make an Authentication Api, and an api which uses the authentication from the first one. I have done everything exactly the same, but i still get this error:
InvalidArgumentException: Auth guard [jwt] is not defined. in file folder/to/project/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on line 84
The guide i have followed is: https://medium.com/swlh/build-jwt-authentication-between-multiple-api-with-laravel-fbd03352aaa3
My config/auth looks like this:
'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
        // 'hash' => false,
    ],
],

Then my app/guard/JWTGuard.php looks exactly like in the guide.
My routes/api.php look the following:
Route::middleware('auth:jwt')->resource('projects', ProjectController::class);

Does anybody has this issue before and know how to solve it?

A: The problem was in routes/api.php. The middleware shouldn't be "auth:jwt", but "auth:api". This did the trick for me.


text:
Q: Limit without using the L'HÔPITAL rule:$\lim_\limits {x \to \pi} \frac{(e^{\sin x} -1)}{(x-\pi)}$ $$\lim_\limits {x \to \pi} \frac{(e^{\sin x} -1)}{(x-\pi)}$$
I found $-1$ as the answer and what I did was:
$\lim_\limits {x \to \pi} \frac{(e^{\sin x} -1)}{(x-\pi)}$ $\Rightarrow$ $\lim \frac{(f(x) - f(a))}{(x-a)}$ $\Rightarrow$ $f(x)=(e^{\sin x})$
$f(a)=1$
$x=x$
and $a=\pi$
So I concluded that the limit of the first function would be the same as the derivative of $f(x)$ so I did:
$\frac{d}{dx} (e^{\sin x})$ $\Rightarrow$ $-1$
But isn't it the same as using the L'HÔPITAL rule??

A: If you want more than just the limit, Taylor series are simple and convenient.
First, let us set $x=\pi+y$ and we shall consider what happens around $y=0$. $$\frac{(e^{\sin (x)} -1)}{(x-\pi)}=\frac{e^{-\sin (y)}-1}{y}$$ Now, let us use $$e^z=1+z+\frac{z^2}{2}+O\left(z^3\right)$$ So, by Taylor, $$e^{-\sin (y)}=1-\sin(y)+\frac{\sin^2(y)}{2}+\cdots$$ $$\sin(y)=y-\frac{y^3}{6}+O\left(y^4\right)$$ Combining $$e^{-\sin (y)}=1-y+\frac{y^2}{2}+O\left(y^3\right)$$ $$\frac{e^{-\sin (y)}-1}{y}=-1+\frac{y}{2}+O\left(y^3\right)$$ which shows the limit and also how it is approached.

A: The given limit $$\lim_{x \to \pi} \frac{e^{\sin x} - 1}{x - \pi}$$ is by definition the derivative of $f(x) = e^{\sin x}$ evaluated at $x = \pi$, since $$f'(a) \equiv \lim_{x \to a} \frac{f(x) - f(a)}{x-a}.$$  Thus $$f'(x) = \cos x e^{\sin x},$$ and $$f'(\pi) = (\cos \pi) e^{\sin \pi} = -1.$$  This is completely distinct from L'Hopital's rule, which requires the consideration of the derivatives of the numerator and denominator of particular indeterminate forms.


text:
Q: How can write on click function on same button in two js file I want to check a form by two levels.
1st level: preventDefault if unfilled any required field.
2nd level: if 1st is okay and is going to be submitted then I want to do ajax with the form data.
Here is my form:
<form  id="form_sample_1" class="form-horizontal normalForm">

                            <input type="text" id="c_name"  class="form-control required" placeholder="Type your Name here"/>

                            <input  id="c_email" class="form-control required" type="email" placeholder="Type your Email Address">

                            <button type="button" id="start_chat" class="btn green">Start Chat</button>

            </form>

My 1st level Jquery:
$(document).on("click", ".normalForm button", function (event) {
   event.preventDefault();
       if(noError){
                    $(this).closest('form').unbind('submit').submit();
                }

});

Here noError has Boolean value true or false. If error exist its value is false otherwise its value is true.I do not show all codes due to simplicity. My code works fine. But after this validation succeeded I want to prevent normal submission again. I want to do this by 'start_chat' id as follows:
   $('#start_chat').click(function(){
// if first level validation is okay then Do Ajax with form values.
});

In this situation $('#start_chat').click(function(){ and $(document).on("click", ".normalForm button", function (event) refer same button and occurs an ambiguity problem. And one possible solution is  wringing code of 2nd level js into 1st level js. But in my situation I want to use first level js for general purpose and 2nd level is more specific purpose. Any idea

A: Instead of selecting $('.normalForm button) and binding your first level logic to its click event, add a specific class to the buttons that you want to execute the first level. So just name those specific buttons $('.firstlevelbutton') or something. Then you can bind events to $('#start_chat') and do whatever you want there.


text:
Q: HTML content locking? A new client asked me to edit their web site.  The site was created with Xara Web Developer Premium.  I discover existing HTML code positioning EACH WORD of content on the page relative to the Left and Top margins!(?) Below:
Can you identify how this locking was created and how it can be repaired?

 Beg'n
 Bark
 isnt
 just
 another
 pet
 sitting
 service.

 It's
 all
 about
 how
 we
 love
 animals!
 Our
 entire
 staff
 treats
 each
 animal
 with
 respect
 and
 care,
 in
 a
 professional
 manner.


text:
Q: Modify Canvas Colors after Creation Using canvas I am creating a collection of triangles on a page and then overlaying them all with a large gradient.
Once these triangles are created is there a way to reference them to change their color with javascript on a certain event? Or do I have to draw the triangle again?
The for loop that makes the triangles:
context.fillStyle = color[i-1];
context.beginPath();
context.moveTo(1,leftStart+(itemStartHeight*(i-1))); //Tl
context.lineTo(width,(itemHeight*(i-1))); //Tr
context.lineTo(width,(itemHeight*i)+1); //Br
context.lineTo(1,leftStart+(itemStartHeight*i)+(i!=items ? 1 : 0)); //Bl
context.closePath();
context.fill();

A: Theres no way to reference individual things drawn on the canvas element by default, to change the colors you have to redraw them


text:
Q: Adding image to page using PIXI I am using a simple example from PIXI
The link to the example is:
http://www.goodboydigital.com/pixi-js-tutorial-getting-started/
So I changed it a bit and the code in the script tag is now this:
<script>
      // create an new instance of a pixi stage
      var stage = new PIXI.Stage(0x66FF99);
      console.log(stage);
      // create a renderer instance.
      var renderer = PIXI.autoDetectRenderer(400, 300);
      console.log(renderer);
      // add the renderer view element to the DOM
      document.body.appendChild(renderer.view);

      // create a texture from an image path
      var texture = PIXI.Texture.fromImage("bunny.png");
      // create a new Sprite using the texture
      var bunny = new PIXI.Sprite(texture);

      // center the sprites anchor point
      bunny.anchor.x = 0.5;
      bunny.anchor.y = 0.5;

      // move the sprite t the center of the screen
      bunny.position.x = 200;
      bunny.position.y = 150;

      stage.addChild(bunny);
      renderer.render(stage);

      // requestAnimFrame( animate );

      function animate() {
          requestAnimFrame(animate);
          // render the stage
          renderer.render(stage);
      }
</script>

So instead of using requestAnimFrame( animate );
I am using renderer.render(stage);  instead.
What happens is on FF 32.0.3 it runs fine the bunny.png appears on the screen inside the stage.
On Chrome Version 37.0.2062.124 m (64-bit), the stage appears but no bunny.
I am also serving up the webpage using Xampp so the path is via a webserver, so no CORS issue using the File path.
Does anyone know why this happens?
Thanks,
Jim

A: When you call render only once you need to ensure all the assets you need are loaded upfront. Try preloading with the pixi asset manager. cheers!

A: Try to preload image before calling render
var img = new Image();
img.onload = function() {
    renderer.render(stage);
}
img.src = 'bunny.png';


text:
Q: Entropy and temperature of small systems I've been struggling for a while now in understanding the concept of entropy as a function of the internal energy. Textbooks typically call $g(E)$ the number of microstates compatible with an energy $E$ of the system. Then they say that the entropy is given by the Boltzmann formula as $S(E)=k \ln g(E)$. Here the energy is precisely fixed to be $E$.
Consider now two systems, isolated from the outside. They are brought into contact, allowing for an exchange of energy. Equilibrium is then said to be established when $g_1(E_1)g_2(E_2)$ has a maximum, or, equivalently, $S_1(E_1) + S_2(E_2)$ has a maximum. From this condition then the temperature is introduced as $1/T = \partial S_1(E_1) / \partial E_1 = \partial S_2(E_2) / \partial E_2$. Now, however, $E_1$ and $E_2$ can fluctuate because of the interchange of energy between the two system, thus we have no precise knowledge of either of them. One could argue that, if the system is big enough, then $g(E)$ is so narrow that fluctuations in the energies are negligible and $E_1$ and $E_2$ can simply be replaced by their mean values.
My question is, what happens in the case of small systems? There are examples of single particle systems put in contact with a heat bath and equilibrium properties of those systems are calculated as if they were infinitely large. In particular, how would one define temperature for such a single particle system? Is its temperature $\partial S(E) / \partial E$ or $\partial S(\langle E \rangle ) / \partial \langle E \rangle$? If the former, how can we say the system is at constant temperature if $E$ fluctuates? If the latter, how would you go from the Boltzmann formula $S = k \ln g(E)$ to $S = k \ln g(\langle E \rangle)$?


text:
Q: checkbox remain checked after submit laravel I have this simple checkbox.
My problem is, if I select any of the checkbox, it should remain checked after form submission.

    <input type="checkbox" name="services_offered[]" value="water jet cutting"> Water Jet Cutting

    <input type="checkbox" name="services_offered[]" value="plasma cutting"> Plasma Cutting

    <input type="checkbox" name="services_offered[]" value="CNC router cutting"> CNC Router Cutting

I tried to use my code before but no luck,
<?php
function isChecked($value)
{
    return (!empty($_REQUEST['services_offered']) && in_array($value,$_REQUEST['services_offered']));
}

    <input type="checkbox" name="services_offered[]" value="water jet cutting" <?php if(isChecked('water jet cutting')) echo ' checked' ?>> Water Jet Cutting

    <input type="checkbox" name="services_offered[]" value="plasma cutting" <?php if(isChecked('plasma cutting')) echo ' checked' ?> > Plasma Cutting

    <input type="checkbox" name="services_offered[]" value="CNC router cutting" <?php if(isChecked('CNC router cutting')) echo ' checked' ?>> CNC Router Cutting

I want it to convert in "laravel way" but I dont know how.
Hope you understand me.
Thanks.

A: I don't know if I understand you correct but:
The form does not post values of the checkboxes.
So I made hidden inputs associated with each checkbox and maintain there values with javascript something like:
 $("#services_offered").change(function() {
        if(this.checked) {
            $('#services_offeredHidden').attr('value','1');
        }
        else {
            $('#services_offeredHidden').attr('value','0');
        }
    });

In laravel controller I play only with hidden inputs which I get the from Request $request.
When you return the view from a controller you do like this
return view('nameOfView')->with('checkbox',$checkboxValue);

and the in the blade you can access the value using:
 {{$checkbox}}

Hope it helps!

A: If you want the "Laravel way" of doing things then I suggest you check out the HTML package by Laravel Collective for marking up the HTML forms in your view. Also make sure the methods on your controller are receiving a Request as it's argument and maybe even checkout Laravel's built-in Form Request Validation as well.
Note, your current code is very old fashioned so it might take a while to learn how to do things the modern way but stick with it and you will be rewarded.
In your view you will open your form like this:
{!! Form::open(['url' => 'foo/bar']) !!}
//
{!! Form::close() !!}

Your method on the controller that receives the form will look something like this:
public function store(Request $request)
{
    $name = $request->input('name');

    //
}

But in general, because your question is too broad to answer clearly without basically re-writing your code for you, you need to start doing some tutorials to learn Laravel properly. I recommend Jeff Way's video tutorial courses on Laracasts.

A: I had a similar problem - here is how I solved it:
My blade template rendered a list of checkboxes as html:
<input type='checkbox' name='sIds[]' id="sId1" value="1"  checked >Draft
<input type='checkbox' name='sIds[]' id="sId2" value="2"  checked >Submitted

I wanted to a) default them all to checked; and b) preserve their checked/unchecked status between validations.
The key is to use the laravel helper function old() - and to realise the old() function returns an array - so you need to do an in_array(value,old()). You also need to cover when the old() is empty on first load by checking is old()==null:
Here is the blade template snippet I used to do it:
@foreach($wfStatusIdsArray as $wfsId=>$statusName)
<input type='checkbox' @if(old('sIds')==NULL || in_array($wfsId,old('sIds'))) checked @endif name='sIds[]' id="sId{{$wfsId}}" value="{{$wfsId}}">{{$statusName}}
@endforeach

There is a bug in this - if ALL checkboxes are cleared, on validation, the checkboxes are reloaded as all ticked. This is fine for my situation so I have not fixed it. Let me know if you fix that bug!


text:
Q: Sensenet: Initialize ClientContent using Sensenet Client API On my application I have my own API that saves content in different repositories. One of them is the Sensenet.
I use the Client API to store the content on Sensenet, but I'm having a problem when I initialize the Client Context:
ClientContext.Initialize(new[]
            {
                new ServerContext
                {
                    Url = siteUrl,
                    Username = userName,
                    Password = userPassword
                }
            });

When I start my Application, the first call on the methods initializes well, but on the second call and so on it launches an exception...
I believe that the solution can pass by using ClientContext.Current... But I don't know how I should implement it...

A: The client context's Initialize method should be called only once per app domain. This is why you get an exception on the second call.
In your case (as you call Sense/Net from another web application) you should call it only once somewhere in your app start process. As a different example: from a command line tool it should be called somewhere in the Main method.
The Initialize method does not do much currently, just stores the provided server information. This is useful if you want to call Sense/Net with a single admin user from an importer tool for example, so that you do not have to provide user credentials on every call.
But if you want to call methods with different user credentials (to make use of Sense/Net's permission system), you can simply provide server information on every call. For example:
var server = new ServerContext
{
    Url = "http://example.com",
    Username = "johnsmith",
    Password = "password"
};

// see the server parameter here!
var content = await Content.LoadAsync(1234, server);
content["MyField"] = "value";

// no server parameter, we already know it
await content.SaveAsync();


text:
Q: Receiving Error: xhr poll error socket.io client React I am receiving an Error: xhr poll error in the connect_error event when trying to connect to my websocket gateway.
I am using "socket.io-client": "^4.2.0".
import { io } from "socket.io-client";

const ENDPOINT = "http://localhost:3001";

const socket = io(ENDPOINT);

socket.on("connect_error", (e: any) => {
   console.log(e);
});

A: You can try to set up the client connection to use only websocket transport. By default it is using weboscket and polling.
{
   transports: ['websocket']
}

So your code will become:
const socket = io(ENDPOINT, {
   transports: ['websocket']
});

A: set server.listen instead of
 app.listen


text:
Q: SqLite3 NFS mount issue with locking - can I use something like CIFS nobrl? I'm having a locking problem where an SQLITE3 databse is permanently locked when created on an NFS file system.  I have read that an option called nobrl can help this issue when the file system in question is CIFS. (its an option to the mount command).
From: http://linux.die.net/man/8/mount.cifs

nobrl
Do not send byte range lock requests to the server. This is
  necessary for certain applications that break with cifs style
  mandatory byte range locks (and most cifs servers do not yet support
  requesting advisory byte range locks).

Is there any way to stop byte-range-lock requests in NFS if they occur, or am I running in the wrong direction by even thinking about this?  I'm happy to change the mount command as was done for the CIFS solution.

A: I recommend to open you sqlite db by software with nolock parameter enabled, golang exg.:
sql.Open("sqlite3", "file:/media/R/Databases//your.db?nolock=1")

while /media/R is a mounted windows nfs-network-drive. Be carefull because you have to lock your db interactions by software otherwise you could corrupt your db, when accessing it simultaneously.
You can read more about sqlite parameters here:
https://www.sqlite.org/c3ref/open.html


text:
Q: Creating PL/SQL procedure to fill intermediary table with random data As part of my classes on relational databases, I have to create procedures as part of package to fill some of the tables of an Oracle database I created with random data, more specifically the tables community, community_account and community_login_info (see ERD linked below). I succeeded in doing this for tables community and community_account, however I'm having some problems with generating data for table community_login_info. This serves as an intermediary table between the many to many relationship of community and community_account, linking the id's of both tables.
My latest approach was to create an associative array with the structure of the target table community_login_info. I then do a cross join of community and community_account (there's already random data in there) along with random timestamps, bulk collect that result into the variable of the associative array and then insert those contents into the target table community_login_info. But it seems I'm doing something wrong since Oracle returns error ORA-00947 'not enough values'. To me it seems all columns the target table get a value in the insert, what am I missing here? I added the code from my package body below.
ERD snapshot
PROCEDURE mass_add_rij_koppeling_community_login_info
IS
TYPE type_rec_communties_accounts IS RECORD
(type_community_id community.community_id%type,
type_account_id community_account.account_id%type,
type_start_timestamp_login community_account.start_timestamp_login%type,
type_eind_timestamp_login community_account.eind_timestamp_login%type);
TYPE type_tab_communities_accounts
IS TABLE of type_rec_communties_accounts
INDEX BY pls_integer;
t_communities_accounts type_tab_communities_accounts;
BEGIN
SELECT community_id,account_id,to_timestamp(start_datum_account) as start_timestamp_login, to_timestamp(eind_datum_account) as eind_timestamp_login
BULK COLLECT INTO t_communities_accounts
FROM community
CROSS JOIN community_account
FETCH FIRST 50 ROWS ONLY;
FORALL i_index IN t_communities_accounts.first .. t_communities_accounts.last
SAVE EXCEPTIONS
INSERT INTO community_login_info (community_id,account_id,start_timestamp_login,eind_timestamp_login)
values (t_communities_accounts(i_index));
END mass_add_rij_koppeling_community_login_info;

A: Your error refers to the part:
INSERT INTO community_login_info (community_id,account_id,start_timestamp_login,eind_timestamp_login)
values (t_communities_accounts(i_index));

(By the way, the complete error message gives you the line number where the error is located, it can help to focus the problem)
When you specify the columns to insert, then you need to specify the columns in the VALUES part too:
INSERT INTO community_login_info (community_id,account_id,start_timestamp_login,eind_timestamp_login)
VALUES (t_communities_accounts(i_index).community_id,
        t_communities_accounts(i_index).account_id,
        t_communities_accounts(i_index).start_timestamp_login,
        t_communities_accounts(i_index).eind_timestamp_login);

If the table COMMUNITY_LOGIN_INFO doesn't have any more columns, you could use this syntax:
INSERT INTO community_login_info
VALUE (t_communities_accounts(i_index));

But I don't like performing inserts without specifying the columns because I could end up inserting the start time into the end time and vice versa if I haven't defined the columns in exactly the same order as the table definition, and if the definition of the table changes over time and new columns are added, you have to modify your procedure to add the new column even if the new column goes with a NULL value because you don't fill up that new column with this procedure.

A: PROCEDURE mass_add_rij_koppeling_community_login_info
IS
TYPE type_rec_communties_accounts IS RECORD
(type_community_id community.community_id%type,
type_account_id community_account.account_id%type,
type_start_timestamp_login community_account.start_timestamp_login%type,
type_eind_timestamp_login community_account.eind_timestamp_login%type);
TYPE type_tab_communities_accounts
IS TABLE of type_rec_communties_accounts
INDEX BY pls_integer;
t_communities_accounts type_tab_communities_accounts;
BEGIN
SELECT community_id,account_id,to_timestamp(start_datum_account) as start_timestamp_login, to_timestamp(eind_datum_account) as eind_timestamp_login
BULK COLLECT INTO t_communities_accounts
FROM community
CROSS JOIN community_account
FETCH FIRST 50 ROWS ONLY;
FORALL i_index IN t_communities_accounts.first .. t_communities_accounts.last
SAVE EXCEPTIONS
INSERT INTO community_login_info (community_id,account_id,start_timestamp_login,eind_timestamp_login)
values (select community_id,account_id,start_timestamp_login,eind_timestamp_login
from table(cast(t_communities_accountsas type_tab_communities_accounts)) a);
END mass_add_rij_koppeling_community_login_info;


text:
Q: mysql server does not shutdown with the error : 'the server quit without updating pid file' environment
OS X El Capitan 10.11 , Mysql 5.6.26
What I did
mysql port was 3307 when I installed it. ( I didn't install it using brew.)
I changed the port 3306 to 3306 by editing /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist after using mysql with 3307 port for 6 months well.
I revised <string>--port=3307</string> to 3306.
I tried to stop and It didn't work. So I used following:

sudo kill -9 [PID]

It's killed and didn't start. So I changed the port 3006 to 3007.
I tried to start mysql server with following command and got a error.

sudo /usr/local/mysql/support-files/mysql.server start
ERROR! The server quit without updating PID file (/var/lib/mysql/nhnui-MacBook-Pro.local.pid).

And I found some helpful advices in follwing link.
reference link :
After MySQL install via Brew, I get the error - The server quit without updating PID file
I tried to change ownership of files, checking my.cnf file, checking error log file and all didn't work for me.
Finally, I removed /usr/local/mysql/datamysqld.local.err , /usr/local/mysql/datamysqld.local.pid and rebooted mac.and I can start mysql server.
The Problem
Then, the problem is above tip is not perfect for me.
mysql server was running after restarting mac. I checked it with 'ps-ef | grep mysql'.
Stop and start was success and then it didn't stop it again cause of same error!
Screenshot of the error :

Of course, I did it again (I mean deleting .err , .pid file / rebooting mac / cheking mysql ps / stop - start (well) / stop (got error)) and checked that it has same error.
Here is the error log : /usr/local/mysql/data/mysqld.local.err

Now, mysql server can't stop.
What can I do to solve this?
P.S - If it will be better to reinstall mysql, I should do that.

A: Make a backup of your system.
Dump your data into text files.
Uninstall everything releated to mySql (a quick Google search will point you to several how-tos)
Reinstall mySql from the package in the .dmg available from mySql website.
You can choose the latest 5.6.x or 5.7.x
Set the mySql root password and you're done.
When things get messy and all you can do is guessing what's the fix it's faster to reinstall given that a package installer is provided for mySql (you don't have to compile it yourself or play with brew/macports).


text:
Q: How to get frequency and time values from .wav file and save in to 2D array ? I want to get frequency and time from .wav file and save into 2D array. I have already recorded sound into .wav file , but i don't know how to get the frequency values in android. But using MatLab i already print the frequency values.
  package com.example.soundrecordingexample2;

  import android.os.Bundle;
  import android.app.Activity;
  import android.util.Log;
  import android.view.Menu;

  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.IOException;

 import android.media.AudioFormat;
 import android.media.AudioRecord;
 import android.media.MediaRecorder;
 import android.os.Environment;
 import android.view.View;
 import android.widget.Button;

 public class MainActivity extends Activity {
     private static final int RECORDER_BPP = 16;
     private static final String AUDIO_RECORDER_FILE_EXT_WAV = ".wav";
     private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
     private static final String AUDIO_RECORDER_TEMP_FILE = "record_temp.raw";
     private  final int RECORDER_SAMPLERATE = 44100;
     private  final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_STEREO;
     private  final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;

     private AudioRecord recorder = null;
     private int bufferSize = 0;
     private Thread recordingThread = null;
     private boolean isRecording = false;

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

      setButtonHandlers();
      enableButtons(false);

      bufferSize = AudioRecord.getMinBufferSize(44100,
            AudioFormat.CHANNEL_IN_STEREO,
            AudioFormat.ENCODING_PCM_16BIT);
    Log.d( String.valueOf(bufferSize), "nadeeBufferaaaaaaaaaaaaaaaa");
}

 private void setButtonHandlers() {
         ((Button)findViewById(R.id.btnStart)).setOnClickListener(btnClick);
 ((Button)findViewById(R.id.btnStop)).setOnClickListener(btnClick);
 }

 private void enableButton(int id,boolean isEnable){
         ((Button)findViewById(id)).setEnabled(isEnable);
 }

 private void enableButtons(boolean isRecording) {
         enableButton(R.id.btnStart,!isRecording);
         enableButton(R.id.btnStop,isRecording);
 }

 private String getFilename(){
         String filepath = Environment.getExternalStorageDirectory().getPath();
         File file = new File(filepath,AUDIO_RECORDER_FOLDER);

         if(!file.exists()){
                 file.mkdirs();
         }

         return (file.getAbsolutePath() + "/" + System.currentTimeMillis() +     AUDIO_RECORDER_FILE_EXT_WAV);
 }

 private String getTempFilename(){
         String filepath = Environment.getExternalStorageDirectory().getPath();
         File file = new File(filepath,AUDIO_RECORDER_FOLDER);

         if(!file.exists()){
                 file.mkdirs();
         }

         File tempFile = new File(filepath,AUDIO_RECORDER_TEMP_FILE);

         if(tempFile.exists())
                 tempFile.delete();

         return (file.getAbsolutePath() + "/" + AUDIO_RECORDER_TEMP_FILE);
 }

 private void startRecording(){
         recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                                         RECORDER_SAMPLERATE, RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING, bufferSize);

         int i = recorder.getState();
         Log.e(String.valueOf(i), "recorder");
         if(i==1)
         {
            recorder.startRecording();
             Log.d("aaa"," equal 1");
         }
         else
         {
             Log.d("hhhh","not equal 1");
         }

         isRecording = true;

         recordingThread = new Thread(new Runnable() {

                 @Override
                 public void run() {
                         writeAudioDataToFile();
                 }
         },"AudioRecorder Thread");

         recordingThread.start();
 }

 private void writeAudioDataToFile(){
         byte data[] = new byte[bufferSize];
         String filename = getTempFilename();
         FileOutputStream os = null;

         try {
                 os = new FileOutputStream(filename);
         } catch (FileNotFoundException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
         }

         int read = 0;

         if(null != os){
                 while(isRecording){
                         read = recorder.read(data, 0, bufferSize);

                         if(AudioRecord.ERROR_INVALID_OPERATION != read){
                                 try {
                                         os.write(data);
                                 } catch (IOException e) {
                                         e.printStackTrace();
                                 }
                         }
                 }

                 try {
                         os.close();
                 } catch (IOException e) {
                         e.printStackTrace();
                 }
         }
 }

 private void stopRecording(){
         if(null != recorder){
                 isRecording = false;

                 int i = recorder.getState();
                 if(i==1)
                    recorder.stop();
                 recorder.release();

                 recorder = null;
                 recordingThread = null;
         }

         copyWaveFile(getTempFilename(),getFilename());
         deleteTempFile();
 }

 private void deleteTempFile() {
         File file = new File(getTempFilename());

         file.delete();
 }

 private void copyWaveFile(String inFilename,String outFilename){
         FileInputStream in = null;
         FileOutputStream out = null;
         long totalAudioLen = 0;
         long totalDataLen = totalAudioLen + 36;
         long longSampleRate = RECORDER_SAMPLERATE;
         int channels = 2;
         long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels/8;

         byte[] data = new byte[bufferSize];

         try {
                 in = new FileInputStream(inFilename);
                 out = new FileOutputStream(outFilename);
                 totalAudioLen = in.getChannel().size();
                 totalDataLen = totalAudioLen + 36;

                 AppLog.logString("File size: " + totalDataLen);

                 WriteWaveFileHeader(out, totalAudioLen, totalDataLen,
                                 longSampleRate, channels, byteRate);

                 while(in.read(data) != -1){
                         out.write(data);
                 }

                 in.close();
                 out.close();
         } catch (FileNotFoundException e) {
                 e.printStackTrace();
         } catch (IOException e) {
                 e.printStackTrace();
         }
 }

 private void WriteWaveFileHeader(
                 FileOutputStream out, long totalAudioLen,
                 long totalDataLen, long longSampleRate, int channels,
                 long byteRate) throws IOException {

         byte[] header = new byte[44];

         header[0] = 'R';  // RIFF/WAVE header
         header[1] = 'I';
         header[2] = 'F';
         header[3] = 'F';
         header[4] = (byte) (totalDataLen & 0xff);
         header[5] = (byte) ((totalDataLen >> 8) & 0xff);
         header[6] = (byte) ((totalDataLen >> 16) & 0xff);
         header[7] = (byte) ((totalDataLen >> 24) & 0xff);
         header[8] = 'W';
         header[9] = 'A';
         header[10] = 'V';
         header[11] = 'E';
         header[12] = 'f';  // 'fmt ' chunk
         header[13] = 'm';
         header[14] = 't';
         header[15] = ' ';
         header[16] = 16;  // 4 bytes: size of 'fmt ' chunk
         header[17] = 0;
         header[18] = 0;
         header[19] = 0;
         header[20] = 1;  // format = 1
         header[21] = 0;
         header[22] = (byte) channels;
         header[23] = 0;
         header[24] = (byte) (longSampleRate & 0xff);
         header[25] = (byte) ((longSampleRate >> 8) & 0xff);
         header[26] = (byte) ((longSampleRate >> 16) & 0xff);
         header[27] = (byte) ((longSampleRate >> 24) & 0xff);
         header[28] = (byte) (byteRate & 0xff);
         header[29] = (byte) ((byteRate >> 8) & 0xff);
         header[30] = (byte) ((byteRate >> 16) & 0xff);
         header[31] = (byte) ((byteRate >> 24) & 0xff);
         header[32] = (byte) (2 * 16 / 8);  // block align
         header[33] = 0;
         header[34] = RECORDER_BPP;  // bits per sample
         header[35] = 0;
         header[36] = 'd';
         header[37] = 'a';
         header[38] = 't';
         header[39] = 'a';
         header[40] = (byte) (totalAudioLen & 0xff);
         header[41] = (byte) ((totalAudioLen >> 8) & 0xff);
         header[42] = (byte) ((totalAudioLen >> 16) & 0xff);
         header[43] = (byte) ((totalAudioLen >> 24) & 0xff);

         out.write(header, 0, 44);
 }

 private View.OnClickListener btnClick = new View.OnClickListener() {
         @Override
         public void onClick(View v) {
                 switch(v.getId()){
                         case R.id.btnStart:{
                                 AppLog.logString("Start Recording");

                                 enableButtons(true);
                                 startRecording();

                                 break;
                         }
                         case R.id.btnStop:{
                                 AppLog.logString("Start Recording");

                                 enableButtons(false);
                                 stopRecording();

                                 break;
                         }
                 }
         }
 };

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

A: You can do it by dividing the file size by the length of the audio in seconds, for instance, from a random AAC encoded M4A in my library:

File Size 5MB
Length 183 sec
Which gives: 40000000 (5MB)/183= 218579.234973 bits/sec or ~218kbps

Actual Bitrate: 200kbps

Since most audio files have a known set of valid bitrate levels, you can use that to step the bit rate to the appropriate level for display.


text:
Q: Get name of current table being scanned over using MultiTableInputFormat When using the new new MultiTableInputFormat class is it possible to obtain the name of the table that is currently giving you the key and values?
I tried searching for a special attribute in the context & configuration but came up unlucky.

A: I found out the answer to this issue.  I dug around in the source for the various classes and found that internally they do something similar to this to get the table name.
String tableName = Bytes.toString(((TableSplit) context.getInputSplit()).getTableName());


text:
Q: Python NFL Fantasy CSV Excuse my ignorance here but I'm having a difficult time getting Python to do what I want it to do. So basically, I have a CSV file that contains National Football League(NFL) data that includes four rows which are Position, PlayerName, Salary, and Average fantasy points a game(AFPG). So for example of what it would look like in the CSV file would be Position(RB), PlayerName(Le'Veon Bell) Salary(9800) AvgFantasyPoints(28.6). What I would like to do is select a PlayersName who averages at least 14 AFPG and is less than 7000 Salary. Here is the code I have so far below. Any help is appreciated thanks.
import csv

out=open("NFL.csv", "rb")
reader = csv.reader(out, delimiter = ",")
data = csv.reader(out)
data = [row for row in data]

for row  in data:
    Position = row[0]
    Name = row[1]
    Salary = row[2]
    Game_info = row[3]
    Avg_points = row[4]
    Players = (Name)
    for field in Salary:
        print(if Salary <= 7000)

out.close()

A: You can try this:
import csv

data = csv.DictReader(open('filename.csv'))

players = [i['Name'] for i in data if i['Salary'] < 7000 and i['Ave_points'] >= 14]

If you do not have file headers in the form Position,Name,Salary,Game_pts,Ave_pts, you can use collections.namedtuple:
from collections import namedtuple

stats = namedtuple("stats", "position, name, salary, gamepts, avepts")

data = map(stats._make, csv.reader(open("filename.txt")))

new_data = [i.name for i in data if i.salary > 7000 and i.avepts >= 14]


text:
Q: Phing property: fallback from environment variable to property file Is there an elegant way of determining a value for a property?
For example, I'd like to allow a property to be read from a file, but also to be grabbed from an environment variable. If the environment variable is present, I'd like to prioritize it over the file's value.
Here's what I have (with the example property deploy.destination):
<property environment="env" />
<if>
    <isset property="env.DEPLOY_DEST" />
    <then>
        <property name="deploy.destination" refid="env.DEPLOY_DEST"/>
    </then>
</if>
<property file="build.properties"/>

However, it's fairly bulky (especially for more than more property).
Is there a way I can do something like this?
<property environment="env" />
<property name="deploy.destination" refid="env.DEPLOY_DEST"/>
<property file="build.properties"/>

With this example, it fails if env.DEPLOY_DEST is not set.
Thanks!

A: Given your statement:

If the environment variable is present, I'd like to prioritize it over the file's value.

you can do
<property environment="env" />
<if>
    <available file="custom.properties"/>
    <then>
        <property file="custom.properties" override="false"/>
    </then>
</if>

The key shall be override="false" to allow env property values to stay.

A: Environment variables are widely used in CI/CD platforms, if this is your case maybe the following will be useful.
First I show you my buildfile build.xml:
<project name="Demo" default="deployment">

    <target name="deployment">
        <property file="build.properties.ini"/>
        <echo message="Your host is: ${destination}"/>
    </target>

</project>

My propertyfile build.properties.ini:
destination = localhost

If we execute the only target in our buildfile, $ phing deployment, the output will be the expected one:
$ phing deployment
[echo] Your host is: localhost

Now execute the following $ phing deployment -Ddestination=example.com, the output is:
$ phing deployment -Ddestination=example.com
[echo] Your host is: example.com

As you can see my buildfile and propertyfile remain unchanged.  however I was capable change the value of  destination property, this is because when properties are set as a command line argument they have higher priority than properties declared in a property file.
To conclude:
// Use the following in development
$ phing deployment

// And override "destination" in your CI/CD config
$ phing deployment -Ddestination=$DEPLOY_DEST

Source: https://www.phing.info/phing/guide/en/output/chunkhtml/ch04s03.html


text:
Q: Will Schema change of a replicated object will affect replication? We have two DB instances in our SQL 2000 server and some 10 tables from DB 'A' is replicated in DB 'B'. Whatever change we make in DB 'A' tables are replicated to DB 'B' tables. We have added a column to one of the table in DB 'A'. Do we need to alter the table in DB 'B' also? Or else it depends on how the replication was setup(which i don't know since it is setup by someone else)? Will it throw any error when replicating data?

A: It depends whether the 'Replicate schema changes' option in the Susbcriptions pane of the publication was True or False when you set up replication. By default is True, meaning the schema changes are replicated.
For more details, restrictions and exceptions, including differences between merge and transactional replication, see Making Schema Changes on Publication Databases. Don't miss this little nugget:

Schema changes to tables must be made
  by using Transact-SQL or SQL Server
  Management Objects (SMO). When schema
  changes are made in SQL Server
  Management Studio, Management Studio
  attempts to drop and re-create the
  table. You cannot drop published
  objects, therefore the schema change
  fails.

A: Replication will add the new column to table 'B'.


text:
Q: He could do it if he wanted/wants to I've recently asked the question on Quora which sentence is correct

He could do it if he wanted to

or

He could do it if he wants to

and got answered that the first one is correct and the second one isn't. I would like to get some explanation of why the second one isn't correct. What part of grammar does it violate? I thought the

He could do it if he wanted to

would refer to the past and

He could do it if he wants to

would refer to the future possible action.

A: In grammatical terms, both statements are correct. Which one you might prefer depends on the context and what you want to say or to imply. Take a typical situation in which a promising athlete is not training hard enough to win a race.
Then you are more likely to remark to your friend:

He could do it if he wanted to.

The implication is that he does not want to put in the effort.
On the other hand, if you don't know whether the athlete is prepared to train hard, you might say:

He could do it if he wants to.

This leaves open the question of whether the athlete does or does not want to.
Neither of these constructions refers to the past. They both refer to hypothetical situations in the future. But the first implies that the person concerned is unwilling to do what is necessary to achieve the goal although he/she has the potential; the second leaves it open.
An alternative is to say: He can do it if he wants to. It's a more direct way of speaking. He could do it.... is a more guarded or reserved way of saying the same thing. It implies that there's a condition to be met.


text:
Q: Adobe Illustrator SVG to WPF xaml weird error Makes PNG I designed this nice user interface in Adobe Illustrator.  Now I am trying to convert it over to WPF   Xaml.
Normally I use inkscape to  blend,  but that has not been working for this   illustration.   So I decide to use  Microsoft Express designer 4.
So it is working,  however;  it is giving me a PNG.
And I am very confused about that.  Also it seems to make my system run slower I'm assuming because there's a PNG involved.
below, is a link to all the files, I am talking about:
[enter link description here][1]
How do I Fix this ?
Ps
This particular component is one of the ones that's causing problems and that is making these PNGs.
It is not the only one.
https://drive.google.com/drive/folders/1FhaKPc75BnoACBQu1kUTNHqrU0OQorVy?usp=sharing

A: Your original SVG contains bitmap images.  So that means your AI and XAML versions will also.
If you don't want your XAML to use bitmaps, then make sure your SVG and AI files don't either.
Also be aware that some effects that you can apply with Illustrator may not be supported in XAML. In those situations what Illustrator may do is generate a bitmap version of that object in order to preserve the look of the effect.


text:
Q: Linq GroupBy and multiple columns class ExpenseClaim
{
    int EmployeeId;
    int Team;
    double Cost;
}

List<EmployeeExpense> GetEmployeeExpenses()
{
    return _expenseClaims // `_expenseClaims` is `List<ExpenseClaim>`
             .GroupBy(e => e.EmployeeId)
             .Select(x =>
                new EmployeeExpense(
                        x.Key,
                        // TODO: employee team?
                        x.Sum(e => e.Cost)
                );
}

Excuse the rather contrived example.
How do I get the employee team in GetEmployeeExpenses? I'm assuming I need a second group by but I can't work out the syntax.
Note that for a given employee, their Team will always be the same anyway, so I'd be happy to take the Team of for example the first grouped by record.
so...
ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 100 }
ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 50 }

=>

EmployeeExpense { EmployeeId = 1, Team = Sales, Cost = 150 }

A: In your particular case, you could use x.First().Team inside your Select to get your team information.
For other cases of actually needing to group on multiple fields, you could group on an anonymous type. Such as
someQuery.GroupBy(f => new { f.Foo, f.Bar }).Select(...);

A: Query expression version of it (might be easier to read, depending on situation and amount of grouping):
IEnumerable<EmployeeExpense> GetEmployeeExpenses(List<ExpenseClaim> claims)
{
    return
        from c in claims
        group c by c.EmployeeId into groupedById
        from g in groupedById
        group g by g.Team into groupedByTeam
        let firstElement = groupedByTeam.First()
        select new EmployeeExpense {
            EmployeeId = firstElement.EmployeeId,
            Team = firstElement.Team,
            Cost = groupedByTeam.Sum(e => e.Cost)
        };
}


text:
Q: Cannot get rid of old values in a loop I'm scraping this website: http://housing.ucdavis.edu/dining/menus/dining-commons/tercero/. The following is my code:
import requests #For request to the website
from bs4 import BeautifulSoup  #For parsering
from warnings import warn #For non-200 status code

url = 'http://housing.ucdavis.edu/dining/menus/dining-commons/tercero/'
page = requests.get (url)
if page.status_code != 200:
    warn('Search: {}; Status code: {}. Status of the request is not normal.'.format (search, page.status_code))
else:
    soup = BeautifulSoup(page.content, 'html.parser')

    main_content = soup.find('div', attrs = {'id': 'tab4content'})
    meal_tag = main_content.find_all('h4')

meal_list = []
for meal in meal_tag:
    meal_name = meal.text
    meal_list.append(meal_name)
print ('The meals we have today are: '+", ".join(meal_list))
print (meal_list)

for meal_pick in meal_list:
    print (meal_pick)
    locations_per_meal = main_content.find('h4',text=str(meal_pick)).find_next_siblings('h5')

    for location in locations_per_meal:
        print (location.text)
        dish_list = main_content.find ('h5',text=location.text).find_next_sibling('ul')

        real_dish_list = []
        for dish in dish_list:
            real_dish_list = dish_list.findChildren('span')

            real_item_list = []
            for item in real_dish_list:
                item = item.text
                real_item_list.append(item)
        print (real_item_list)

Basically, I want to reproduce all the dish names, where they are and which meal they belong to. However, my code only works for Breakfast and other meals will have the exact same dishes as the Breakfast, unless a location didn't show up in the Breakfast. I think somehow I cannot overwrite the old dishes by the new ones. Could someone have a review and help me out on this issue? Thanks~

A: You have a logic error, and it's difficult to debug because you're attempting to print unformatted HTML straight to the console.
To make it easier on yourself, you should populate a dict with your structured data as early as possible, using either dict.update() or dict.setdefault().
In either an interactive Python console, or in a running program, you can also access the most recent item from a loop outside of its scope, i.e.
menu = {}
for meal in meal_tag:
   # some loops later...
   menu.update({meal.text: {}})
# ...
import json
print(json.dumps(menu, indent=4))
print(meal.find_next_siblings('h5')[0].find_next_sibling('ul').find_all('li', recursive=False)[0].span.text)

I encourage you to experiment in the interpreter as much as you can.
Back on topic--your logic error probably has something to do with the fact that print(real_item_list) is on a different scope than I would expect you to put it, but I found debugging your code annoying enough to not look too deeply into it.
Again, emphasizing the importance of making debugging as easy as possible.
In fact, it was easier to just rewrite it. You should be able to do the meat of your looping in about 7 lines and 3 loops.