text:
Q: How to correct a syntax error in SQL trigger near NEW? I have written a simple trigger that calls a calculateMarketPriceCars function (it has four int arguments):
CREATE TRIGGER calculateMarketPrTriggerCars
AFTER INSERT ON FOR_SALE_CARS
FOR EACH ROW
EXECUTE PROCEDURE calculateMarketPriceCars(NEW.BOUGHT_PRICE, NEW.YEAR_OF_PRODUCTION, (SELECT
NUMBER_OF_CARS_PRODUCED FROM ABSTR_CARS WHERE ABSTR_CARS.ABSTR_CAR_ID = NEW.ABSTR_CAR_ID),
NEW.MILEAGE);

I doublechecked all the spellings and called the function manually separately from the trigger - everything else works correctly. But when I try to create the trigger (giving the above command to SQL) it shows
ERROR:  syntax error at or near "."
LINE 4: EXECUTE PROCEDURE calculateMarketPriceCars(NEW.BOUGHT_PRICE,...

Can NEW be not visible inside the brackets? How can I correct it?

A: A trigger consists of two statements in PostgreSQL: the definition of the trigger function and the CREATE TRIGGER statement. You cannot have both in a single statement.
You cannot write a trigger function in SQL, you have to use PL/pgSQL or another procedural language.


text:
Q: Wait message with full refresh in xpages I am developing an application on xpages and would like to put a wait message while there is an ongoing processing. There are several articles that indicate how to do, but this only functional with partial update. I need the message, preferably with lock and an animated gif to work with the full update.

A: Problem is that a full refresh will reload the page, to get this working you need to load the page inside an iframe and place the standby code in the top page.
If you do something you need to call parent.window.dothestandby()
and in onload on the page inside the iframe call parent.window.hidestandy()

A: Take a look at this NotesIn9 video by David Leedy and watch from 5 minutes and see if it helps:
http://www.notesin9.com/2016/02/19/notesin9-188-adding-a-please-wait-to-xpages/

A: What I did was use the technique described in the link below, from an article by Brad Balassaits. In the various techniques mentioned, I implemented the one that inserts the waiting animated gif into the triggered button. From the techniques suggested and researched this was the one that would least impact when there are changes of adjustments in the application.
Brad Balassaiti article

redpajama_set_name: RedPajamaStackExchange


text:
Q: Facebook Response to JSON Object I need to either convert my facebook Response to a JSON Object or find another way to use the response in my code.
I've successfully printed my facebook api Response to the log using this:
Log.d("Friend Response in DIB: ", FriendResponse.toString());

Which gives me this:
06-09 14:02:33.706: D/Friend Response in DIB:(12421): {Response:  responseCode: 200, graphObject: GraphObject{graphObjectClass=GraphObject, state={"data":[{"id":"1402927803328937","name":"Open Graph Test User"},{"id":"1402874766667901","name":"Jane Dickson"}],"paging":{"next":"https:\/\/graph.facebook.com\/v2.0\/277976949048048\/friends?format=json&access_token=CAAKsYnmrEh0BAGhTzCUOr6r3zMH7tt1mouEXrqsAi2fh1nYK1d1w5iSvBQEjCupMB1SA9f8G9GyAm41Bct0qwnXnHr4H81eHRHQaoEUrm9JhqRk2LNN260mZCNJwiuiqxX24zHrBINqZCcyh9VzsCM7PO2UKGfEJOcxmEhAZCl9v8XrcrBIkaeGNRC7zh7hZASZADRMTACaRUZApjkjyAuFxSWflkqMldfISgz4Lvi2gZDZD&limit=5000&offset=5000&__after_id=enc_Aey9afbBKXSo8gtNoFOb5eEu4paCRUYRSWIG0v3nSeCgpCIWIj7O-gHnmemCVpr7hQgH--aTwM6-lZA6MyqEfF6H"}}}, error: null, isFromCache:false}

This information is correct, and now I need to put the id and name of each returned user into it's own list item in a list view.
I have a code which does this already, except it gets the information from a url using makeHttpRequest.
How do I convert my facebook Response type into a type that will work with this code instead of the makeHttpRequest? :
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_videos, "POST", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        Log.d("Friend Response in DIB: ", FriendResponse.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);

etc...
All help much appreciated!

A: Look at the official Facebook docs here.
If you do an asynchronous (Request.executeAsync())request, you'll use a Request.Callback with an onCompleted(Response response) method. If you do a request in series (be sure you're not on the main thread), the Response will be the value returned by the Request.executeAndWait() method.
From the Response object, you can call response.getGraphObject().getInnerJsonObject(). Use the Graph Explorer tool to get a better idea of the structure of the JSON you get from the API call.


text:
Q: How do I pass values between React Redux components? I have tried and failed to understand react/redux and have inherited some code (very simplified version shared here). There is a navigator:
class processNavigator extends React.Component<Props, State> {
  render() {
    switch (this.props.processStatus) {
      case processStatus.ended:
        return <Page2 />;
      case processStatus.notStarted:
        return <Page1 myToken={this.myToken} />;

which renders either page1 or page2.
Page1:
interface StateProps {
  processId: number | undefined;
  processStatus: processStatus | undefined;
}
interface DispatchProps {
  startprocess: () => void;
}
type Page1Props = RouteComponentProps &
  DispatchProps &
  NavigatorProps &
  StateProps;

class Page1 extends React.Component<Page1Props, {state variables
}> {
  constructor(props: any) {
    super(props);
    this.state = { state variables
    };
  }
   startTypeGetPromise = async (myToken: string): Promise<any> => {
    DB lookup here
    return aValue;
  };
  loadResult = async () => {
    await this.startTypeGetPromise(this.props.myToken).then(ret => this.setState({startTypeValue: ret}));
  };

  componentDidMount () {this.loadResult();};
  render() {return (...);}
}

const mapStateToProps = (state: RootState): StateProps => ({
  processId: state.process.processId,
  processStatus: state.process.processStatus,
});

const mapDispatchToProps = (dispatch: Dispatch): DispatchProps => ({
  startprocess: () => dispatch(startprocess()),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(withTranslation()(Page1)));

Page2:
interface StateProps {
  processId: number | undefined;
  processStatus: processStatus;
}

type Page2Props = RouteComponentProps & StateProps;

class Page2 extends React.Component<Page2Props> {
  render() {...);}
}

const mapStateToProps = (state: RootState): StateProps => ({
  processId: state.process.processId,
  processStatus: state.process.processStatus,
});

export default connect(mapStateToProps)(
  withRouter(withTranslation()(processPage2))
);

How do I pass the state value startTypeValue from Page1 to Page2? (Apologies for all the code, I am not sure what is boiler plate and what is needed).

A: You can move startTypeValue to the upper component's state and pass it as a prop to Page2. For changing startTypeValue from Page1 component one can pass a callback function-prop:
class processNavigator extends React.Component<Props, State> {
  state = {
    startTypeValue: null // or some other initial value you want
  }

  render() {
    switch (this.props.processStatus) {
      case processStatus.ended:
        return <Page2 startTypeValue={this.state.startTypeValue} />;
      case processStatus.notStarted:
        return <Page1
                 myToken={this.myToken}
                 onValueChange={(value) => this.setState({ startTypeValue: value })}
                />;
  }
}

In Page1 component:
loadResult = async () => {
  await this.startTypeGetPromise(this.props.myToken)
    .then(ret => this.props.onValueChange(ret));
};


text:
Q: WCF DataServices Expand 12 Limitations I'm using WCF DataServices in a Silverlight app. My issues is that with the model I'm referencing I need access to more than 12 expanded properties. The reason is that I am referencing a service with recursive model and basically I need 5 expands on 4 levels which exceeds the max number of expands which is apparently 12. Is there another solution rather than calling BeginLoadProperty hundreds or times to get the desired effect?

A: You could build multiple queries on the client which together will get you all the data you need and then use the DataServiceContext.ExecuteBatch to get them all in a single request. It will still run multiple queries against the database, but you will get just one HTTP request and one response.


text:
Q: Type class with conversion from a given type I would like to implement a class with a function conv that converts from a given T type.
The pseudo-code (that doesn't compile) would look like this:
data T a b c d  = List [a] | Tup1 a | Tup2 a b | Tup3 a b c deriving (Show)

class ConvT t where
  conv :: T a b c d -> t

instance ConvT [a] where
  conv (List x) = x

instance ConvT (a,b) where
  conv (Tup2 a b) = (a,b)

How can I do that?
Note that I don't plan to use that in production -- I'm just interested in understanding the Haskell type system more.

A: Your typeclass promises that you can convert (T a b c d) into t, for any types a b c d t. But the instance declarations only work if there's some correspondence between the types. For example, the List case only works if t is [a], so it is not a valid instance of the typeclass you defined.
I'm not a Haskell expert, but I think this is impossible, simply because there is no way to write a correct type signature for conv.

A: First of all, note that this does not make much sense, since you are trying to define a a family of functions that are each inhernetly partial.  It can be done though, it just requires extensions.
solution 1: MPTC
class ConvT a b c d t where
  conv :: T a b c d -> t

instance ConvT a b c d [a] where
  conv (List x) = x

instance ConvT a b c d (a,b) where
  conv (Tup2 a b) = (a,b)

solution 2: constraint kinds and type families.
class ConvT t where
  type ConvC t a b c d :: Constraint
  conv :: ConvC t a b c d => T a b c d -> t

instance ConvT [a] where
  type ConvC [a] a' b c d = a ~ a'
  conv (List x) = x

instance ConvT (a,b) where
  type ConvC (a,b) a' b' c d = (a ~ a', b ~ b')
  conv (Tup2 a b) = (a,b)

note: this code is not tested but gets the idea across.  Also, don't do this.


text:
Q: ORA-30089 when execute CREATE TABLE with a DATE type field I'm getting the following error when creating the following table:
CREATE TABLE EVENTO(
    ID_EVENTO NUMBER PRIMARY KEY,
    ID_COMPLEJO NUMBER NOT NULL,
    N_COMISARIOS NUMBER,
    FECHA_EVENTO DATE,
    N_PARTICIPANTES NUMBER,
    DURACION INTERVAL,
    EQUIPAMIENTO VARCHAR2(255),
    FOREIGN KEY (ID_COMPLEJO) REFERENCES COMPLEJO
);

I do not know if it is because of Oracle's permission to the user because I am on the desktop and here he does not let me create the table.
Error que empieza en la línea: 28 del comando :
CREATE TABLE EVENTO(
    ID_EVENTO NUMBER PRIMARY KEY,
    ID_COMPLEJO NUMBER NOT NULL,
    N_COMISARIOS NUMBER,
    FECHA_EVENTO DATE,
    N_PARTICIPANTES NUMBER,
    DURACION INTERVAL,
    EQUIPAMIENTO VARCHAR2(255),
    FOREIGN KEY (ID_COMPLEJO) REFERENCES COMPLEJO
)
Informe de error -
ORA-30089: falta <campo datetime> o no es válido
30089. 00000 -  "missing or invalid <datetime field>"
*Cause:    A <datetime field> (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND) is
           expected but not found, or a <datetime field> specified the
           <end field> in an <interval qualifier> is more significant
           than its <start field>.
*Action:

The other tables I create them well but with the DATE datatype I do not know if I'm getting it wrong ...

A: The CREATE TABLE statement declares column DURACION as datatype INTERVAL
INTERVAL is not a valid datatype. You can either use INTERVAL YEAR TO MONTH, or INTERVAL DAY TO SECOND (with various precision).
Consider, for example:
CREATE TABLE EVENTO(
    ID_EVENTO NUMBER PRIMARY KEY,
    ID_COMPLEJO NUMBER NOT NULL,
    N_COMISARIOS NUMBER,
    FECHA_EVENTO DATE,
    N_PARTICIPANTES NUMBER,
    DURACION INTERVAL YEAR TO MONTH,
    EQUIPAMIENTO VARCHAR2(255),
    FOREIGN KEY (ID_COMPLEJO) REFERENCES COMPLEJO
);

Demo on DB Fiddle
Reference: Oracle datatypes.

A: The type  INTERVAL in duration field is not valid, it doesn't exist as a datatype. I recommend you use a start date and end date, which is better and can provide much better information. Working with intervals can bring a lot of issues in the future.
 CREATE TABLE EVENTO(
    ID_EVENTO NUMBER PRIMARY KEY,
    ID_COMPLEJO NUMBER NOT NULL,
    N_COMISARIOS NUMBER,
    FECHA_EVENTO DATE,
    N_PARTICIPANTES NUMBER,
    FECHA_INICIO DATE,
    FECHA_FIN DATE,
    EQUIPAMIENTO VARCHAR2(255),
    FOREIGN KEY (ID_COMPLEJO) REFERENCES COMPLEJO
)


text:
Q: accessing view controller's view I am inside a class on a view-based app, one that was creating with one view controller.
WHen I am inside the view controller I can access its view using self.view, but how do I access the same view if I am inside a class?
[[UIApplication sharedApplication] delegate]... //??? what do I put here?

thanks

A: Assuming that the view controller is a member of your application delegate. you can access it like this: ("YourAppDelegate" should be replaced with the actual type name of your application delegate)
( ( YourAppDelegate *) [ [ UIApplication sharedApplication ] delegate ] ).viewController.view;

A: If you're trying to give a singleton a reference to your main viewController, a better solution might be to get your MyAppDelegate to set a viewController property on your singleton at launch:
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
    [MySingletonClass sharedSingleton].viewController = self.viewController;
}

If you plan on re-using a Singleton like this in multiple projects, it often makes more sense to set these sort of properties from your AppDelegate.

A: A subview really shouldn't be manipulating a parent view, each class should manage it's own view.
Anyway, if your class is a subclass of UIView and is a subview of the viewController, you can get the viewController's view by accessing the superview property to get your parent view.


text:
Q: Having a problem with making this function typescript conform So I have this code:
import * as Icons from "../../icons"

const Icon = ({ icon, ...props }) => {
  const Icon = Icons[icon]
  return <Icon {...props} />
}

and I am trying to find the correct types for it but no matter what I do, it won´t work.
Pls HELP
My errors:

A: Declare an interface for the Icons import by import * as Icons from './icons' statement.
./icons/SquareIcon.tsx:
import React from 'react';

export default function SquareIcon() {
  return
square icon
;
}

./icons/CycleIcon.tsx:
import React from 'react';

export default function CycleIcon() {
  return
cycle icon
;
}

./icons/index.ts:
import CycleIcon from './CycleIcon';
import SquareIcon from './SquareIcon';

export interface IconType {
  cycle: typeof CycleIcon;
  square: typeof SquareIcon;
}

export { CycleIcon as cycle, SquareIcon as square };

Icon.tsx:
import React from 'react';
import * as Icons from './icons';
import type { IconType } from './icons';

const Icon = ({ icon, ...props }: { icon: keyof IconType }) => {
  const Icon = Icons[icon];
  return <Icon {...props} />;
};

function Test() {
  return <Icon icon="cycle"></Icon>;
}

A: Specify the data types as follows,
const Icon = ({ icon , ...props } : {icon : string , props : any}) => {
    const Icon = Icons[icon]
    return <Icon {...props} />
}

If the data has only one type you can use the proper data type without using any.


text:
Q: Using TextOptions.TextFormattingMode with FormattedText With WPF4 you can have non-blurry text by adding TextOptions.TextFormattingMode="Display" and TextOptions.TextRenderingMode="Aliased" to your xaml:
<Window
   TextOptions.TextFormattingMode="Display"
   TextOptions.TextRenderingMode="Aliased">

This works fine for me except for when I draw text with DrawingContext.DrawText like this:
void DrawText(DrawingContext dc)
{
  FormattedText ft = new FormattedText("Hello World",
    System.Globalization.CultureInfo.CurrentCulture,
    System.Windows.FlowDirection.LeftToRight,
    new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),
    FontSize,
    brush);
  dc.DrawText(ft, new Point(rect.Left, rect.Top));
}

How can I draw non-blurry text with FormattedText? ie I want TextOptions.TextFormattingMode="Display" and TextOptions.TextRenderingMode="Aliased" to be used.

A: There's an overloaded constructor for FormattedText that allows specifying a TextFormattingMode: http://msdn.microsoft.com/en-us/library/ee474866.aspx
void DrawText(DrawingContext dc)
{
  FormattedText ft = new FormattedText("Hello World",
    System.Globalization.CultureInfo.CurrentCulture,
    System.Windows.FlowDirection.LeftToRight,
    new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),
    FontSize,
    brush,
    null,
    TextFormattingMode.Display);
  dc.DrawText(ft, new Point(rect.Left, rect.Top));
}

A: Follow the example here for Advanced Text Formatting and create a TextFormatter object and use TextLine.Draw()


text:
Q: How do I have a TABLE grow to be the same height as its container? (or, battling IE JavaScript slowness) I have a web page where I have a table nested inside of a TD tag (don't flame me for this, I have a good reason for doing it this way).  When the page loads, I want to expand the height of the nested table to be the height of the TD cell that contains it.  Currently I do it with code like this:
$(document).ready(function()
{
    $('.TakeOffItemGroupTable').each(function()
    {
        $(this).height($(this).closest('td').height());
    });
}

This works, but if there are a lot of tables to resize on the page, it can take ~20 seconds for IE8 to do it (FF takes a second or two, of course).  That's because $(this).height($(this).closest('td').height()); takes:

*

*1ms in Chrome

*18ms in Firefox

*330ms in IE8

Is there some other way that I can have the nested table always take on the height of its container?
Things I have tried:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>Untitled</title>

       JKLSD FASJDFKLSA DFKLADFJL KASDJFKLSAD JFSAKLDF

                    I should be 100% tall!

This works in Firefox but not in IE.

A: I think with a correct HTML Doctype your 2nd example will work in IE as well, without any Javascript.
The following works for me in FF, and IE 6, 7, and 8:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<title>Untitled</title>

                I am 100% tall!

A: If you give the outer td a pixel height, it should work. I guess currently the td is already at 100% of it's container's height.

A: Why can't you just specify the table to be 100% height in the HTML markup?  This should just work without javascript.

  ...

A: i know everyone loves jquery, but maybe simpler js will help?
      var t = document.getElementById("nestedTable");
      t.style.height = t.parentNode.offsetHeight.toString() + "px";

adjust for border/padding/margin as necessary.


text:
Q: control moto's state transitions of EC2 instances? To test that my application handles state transitions correctly, I'd like control over the lifecycle of moto's fake EC2 instances:
Rather than have instances start immediately in running, it would be nice to have them start in pending, let me confirm some things, and then explicitly transition them to running.
Relatedly, there are some actions I'd like to trigger in my tests when the instances switch to running.
Is any of this possible? I found InstanceBackend in moto's code -- is there a way for users to hook into or override methods there?

A: There are a few feature requests for more control over the transition cycle, but nothing has been implemented yet.
It is possible to  use the internal API to set the status directly, as you said, using the InstanceBackend.
If you only have one instance, you can use the following code:
ec2_backend = moto.ec2.models.ec2_backends[my-region]
list(ec2_backend.reservations.values())[0].instances[0].state = "..."

If you have multiple reservations, you can use the reservation ID like this:
ec2_backend.reservations["r-7df1884b"].instances[0].state = "..."

Note that both AWS and Moto use two properties to track state, state and state_code. Only updating state may result in undefined behaviour, so you may want to update both to ensure they are in sync:
ec2_backend.reservations["r-7df1884b"].instances[0].state_code = ..

Note that this is an internal API, so changes to this data structure may occur without warning.


text:
Q: integrating IDM to chrome or firefox I have installed IDM through wine. But cannot integrate it to chrome or firefox. I want the feature like popping up the download menu on websites like youtube and other video websites. To be specific I would like to use IDM as same as in Windows, Can anyone help me? Or please suggest any alternatives that has the features like IDM.
Thanks in advance

A: Windows users are usually stuck with the flexibility of IDM when we switch to linux.
When I moved to Linux I have to find alternatives.

*

*youtube-dl (Its available in the command line- $ man youtube-dl to see usage)

*VideoDownloadHelper. --Firefox addon

*4kdownloader. I use this everyday. Download playlist and individual files, extract only the audio as well. Its paid app but the trick is, look for an older version and install. It works so well.
I am using version 4.2.0


text:
Q: Sylow structure of $A_6$ I want to analyze the Sylow structure of $A_6$ (the alternating group of order 6), which has order $|A_6|=\frac{|S_6|}{2}=\frac{6!}{2}=360=2^3 3^2 5$.
Starting with $p=5$.
We have that there are $\binom 65(5-1)!=144$ elements of order 5 in $A_6$, but given that 5 is prime, we have that the elements of order 5, are the 5-cycles, the group generated by one of this 5-cycles has $\varphi(5)=5-1=4$ generators, so we have that $|{\rm Syl}_5(A_6)|=\frac{144}{4}=36$.
If $P\in{\rm Syl}_5(A_6)$, we have that $36=|{\rm Syl}_5(A_6)|=|A_6:N_{A_6}(P)|=\frac{360}{|N_{A_6}(P)|}$, so in consequence $|N_{A_6}(P)|=10$ and I want to prove that $N_{A_6}(P)\cong D_{10}$.
By classification of groups of order 10, we have only two options for $N_{A_6}(P)$, which are $D_{10}$ (Symmetry group of a pentagon) or $C_{10}$ (Cyclic group of order 10). The difference between those is that the latter is abelian.
I don't know if part of the argument I need has to do with the fact that $A_6$ is not simple.


text:
Q: Can I add the bootstrap responsive navbar into an existing site? I have an existing site developed using Dreamweaver's Fluid Grid system. It works fine. The one thing I would like to add is the bootstrap responsive navbar that collapses to an icon on devices smaller than a tablet. The existing menu structure is a simple horizontal spry menu bar. I've experimented with loading some of the bootstrap css and js files and trying to model the layout structure, but I'm just not doing it correctly.  Has anyone done this and have a step by step approach of what they did?
Thanks,
CJ

A: If navigation is the only thing that you want from Bootstrap, you can just download a customized version of the package from Bootstrap customizer, where you'll only select the necessary things, from the sections mentioned below:
LESS components
Toggle all check boxes off, then check 'Navbar', which will in turn select a few other check boxes. 'Grid system' might be necessary as well.
jQuery plugins
Select from Magic => Collapse, plus Transitions if you care about the unrolling of the collapsed menu with animation
LESS variables
Adjust styles from under Navbar, plus the variable @grid-float-breakpoint - which is responsible for defining the resolution at which your menu will go from full-sized to collapsed state.
Compile and enjoy. After the file download has started, you'll see that your URL of the customization page has changed. If you save it, you can later on open the same customization page with all fields filled in and check boxes checked.


text:
Q: Find which node my selenium-grid remote driver is running on? I obtain a RemoteWebDriver from the hub as follows:
RemoteWebDriver driver = new RemoteWebDriver(
                                      new URL("http://whatever:4444/wd/hub"),
                                      DesiredCapabilities.internetExplorer() );

Is there a way to programatically find out which node in the grid the remote driver is running on?
I want to log this in an effort to track down intermittent test failures.

A: Please refer to this blog post of mine to learn how to find out the node ip and port to which the test was routed to.
Blog post : https://rationaleemotions.wordpress.com/2016/01/15/where-did-my-test-run/
In a nutshell, here's what you need to do (The blog I shared has elaborate explanation and required code )

*

*Get the session id from webdriver via Webdriver.getSessionId()

*You then append the session id obtained from the previous step to the URL http://localhost:4444/grid/api/testsession?session= (replace localhost with the actual Grid IP/host and replace 4444 with the port on which grid is listening to) and trigger a POST call.

*From the JSON response you parse the value of attribute proxyId as a URL and extract out the IP and port from it.

This is now available for ready consumption via the library talk2grid that I built.


text:
Q: How to separate a string with a char? Say I have two string; "fruit;mango;apple;banana" and "animal;dog;cat;cow". What i want is a function to check the first word before 1st semi colon and then if its "fruit" get the other 3 elements(without semi colon) and store it in an array called fruit and if animal take the elements and store is animal array. I thought of using loop and chatAt() but that code will be kinda messy.
So I want to know is there any function to separate a string with char?

A: Try this:
String s =  "fruit;mango;apple;banana" ;
String[] elements = s.split(";");
if(elements.length > 0){
    if(elements[0].equals("fruit")){
        String[] fruits = new String[elements.length-1];
        System.arraycopy(elements, 1,fruits , 0, elements.length-1);
        System.out.println(Arrays.toString(fruits));
    }
}

A: Here's use following code:
String data="fruit;mango;apple;banana";
    List<String> fruitList=new ArrayList<String>();
    List<String> animalList=new ArrayList<String>();
    String tok[]=data.split(";");
    if(tok[0].equals("fruit"))
    {
        for(int i=1;i<tok.length;i++)
        {
            fruitList.add(tok[i]);
        }
    }
    else
    {
        for(int i=1;i<tok.length;i++)
        {
            animalList.add(tok[i]);
        }
    }
    if(!fruitList.isEmpty())
        System.out.println(fruitList);
    if(!animalList.isEmpty())
        System.out.println(animalList);

Output
[mango, apple, banana]

Now the data string can be any of animal or fruit type.

A: String str1 = "fruit;mango;apple;banana";
String str2 = "animal;dog;cat;cow";

String[] arrStr1 = str1.split(";");
String[] arrStr2 = str2.split(";");

ArrayList<String> fruit = null;
if(arrStr1[0].equals("fruit")) {
    fruit = new ArrayList<String>(Arrays.asList(arrStr1));
    fruit.remove("fruit");
}

ArrayList<String> animal = null;
if(arrStr2[0].equals("animal")) {
    animal = new ArrayList<String>(Arrays.asList(arrStr2));
    animal.remove("animal");
}


text:
Q: Determining how a Jenkins job was started (I'm new to Jenkins and curl, so please forgive any imprecision below.)
I am running a Jenkins job on one network that sends a curl command to a second network that is used to start a Jenkins job on that second network.
Sometimes I have to log onto that second network and restart the job using the Rebuild button provided by the Rebuild plugin.
I need to know how to determine whether the job on the second network was started by the original curl command or restarted via the Rebuild plugin, without the user having to do anything but restart the job with the same parameters.
I could use an extra boolean-parameter in the job on the second network that can be set to true by the curl command and to false when using the Rebuild button, but that requires the user to manually change the value of that parameter. I don't want the user to have to do that.

A: I think this only possible by using different users, or lets say an own user for the remote invocation. Anything more informative would have to be done manually for instance by an own paramter for the job. Normally jobs are started by developers, schedulers, hooks or by other jobs on the same instance. If triggered remotelly the job is triggered by a user as well, without authentication its the anonymus user who triggers the job.
Do you know the Jenkins CLI, could replace your curl commands?
https://jenkins.io/doc/book/managing/cli/


text:
Q: Finding html string index using plan string start index and end end index I have an html text string and also start index and end index of its text form (without HTML). Like -
var htmlstr = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
var startindex = 0; // can be change
var endindex = 123; // can be change

/* Text form (0 to 123) without html tag
   "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
*/

Can anybody suggests how we can find the same index for htmlstr?
Expected result:-
inside htmlstring that index will be 130.
/*
   "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
*/

A: let span = document.createElement('span');
span.innerHTML = htmlstr;

setTimeout(function() {  // wait for `span` to be rendered
    let target = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
    let [i, j] = [0, 0];
    for (let child of span.childNodes) {
        let rest = target.substring(j);
        if (rest.startsWith(child.textContent)) {
            if (child.nodeType === Node.TEXT_NODE)
                i += child.textContent.length;
            else
                i += child.outerHTML.length;
            j += child.textContent.length;
        } else if (child.textContent.startsWith(rest)) {
            i += rest.length;
            if (child.nodeType !== Node.TEXT_NODE)
                i += child.outerHTML.indexOf('>') + 1;
            break;
        }
    }
    console.log(i);
}, 1000);

htmlstr will be rendered as DOM element. Then you have both outerHTML and textContent for each element.
For each step, we can decide which one of child node and the rest of target startsWith the other. If textContent of achild node startsWith the rest of the target text, it is done.
So, if target text startsWith textContent of a child node, index will increase by the length of outerHTML or the length of textContent.
Exceptionally, if target text ends inside non-TEXT_NODE element, index will increase by the length of textContent plus the length of an opening tag.


text:
Q: my prim function isnt working quite right any help appreciated im supposed to haveit start from any given location which it does but it just prints the same set over and over. any help would be appreciated
   void graph::primms(int x)
     {
        int mincost = 0;
        int min = infinite;
        int oldindex;
        int index;
        bool mark[num+1];
        int a,v;
        for(int i = 1; i<num+1; i++)
        {
                mark[i] = false;
        }
        mark[x] = true;
    for(int x = 1; x<num; x++){
        for(a =1; a<num+1; a++)
        {

                for(v=1; v<num+1; v++)
                {
                        if(!mark[v] && !mark[a] && garr[a][v] < min && garr[a][v] > 0)
                        {
                                min = garr[a][v];
                                index = v;
                                oldindex = a;
                        }
                }
          }
                                mark[v] = true;
                                    cout <<  oldindex <<" -> "<< index<<endl;
                                    mincost += min;
        }
         cout<<" total cost is"<<mincost;
     }

example of my output:
2 -> 3
2 -> 3
2 -> 3
 total cost is 3

this is the graph i am working with:
0 1 2 3 4
1 0 0 0 1
2 0 0 1 3
3 0 1 0 3
4 1 3 3 0


text:
Q: DataContract works without DataContractAttribute (until obfuscation) I have the following layered JSON object represented by a DataContract that I can parse normally using JavascriptSerializer
[DataContract]
public class ClassOuter{
    [DataMember(Name = "stringProperty1")]
    public string stringProperty1 {get;set;}

    [DataMember(Name = "objectProperty")]
    public ClassInner objectProperty {get;set;}
}

//NOTE:No DataContract Attribute here!
public class ClassInner{
    [DataMember(Name = "stringProperty2")]
    public string stringProperty2 {get;set;}
}

But when I call
string inputText = "{\"stringProperty1\":\"Hello\",\"objectProperty\":{\"stringProperty2\":\"World\"}}";
ClassOuter myObject = new JavascriptSerializer().Deserialize<ClassOuter>(inputText);
Console.WriteLine(myObject.stringProperty2);

Everything works fine.
However, running the app through an obfuscator after building, stringProperty2 becomes null. *Can't say what obfuscator, sorry!
No warnings from CodeAnalysis.
I'm not very familiar with compilers, but here's my guess: the compiler recognizes the intent and makes the link internally, despite not having a DataContract attribute. However, it doesn't make some sort of internal marking, so the obfuscator feels free to jumble it and the link breaks. If it was just a block of continuous memory though, I would guess that things would break much harder than they do, not just becoming null
Can anyone verify or dispute my naive hypothesis?
(Adding in the DataContract attribute for ClassInner solves the problem, even with obfuscation!)

A:
Can anyone verify or dispute my naive hypothesis?

Unobfuscated, it will work without the [DataContract] because what happens is that the serializer will just fall back to not using attributes and serialize it by the property names only. They are identical to your attribute, so you don't notice this. You should be able to verify that by giving the [DataMember] that came without a proper [DataContract] another Name text, the serializer will still use the property name and ignore the attribute. Those attributes work as a pair. Set both or fall back to "none".
public class ClassInner
{
    // This is ignored because no [DataContract] was found
    [DataMember(Name = "nonexistentProperty")]

    // This will still be set unobfuscated because the property name matches
    public string stringProperty2 { get; set; }
}

So when you obfuscate it, the property names change. Without a [DataContract] to start with, the serializer will fall back to the attributes and find only random letter combinations that he cannot match with the input. Hence you will get null.


text:
Q: MySQL equivalent for pg_fetch_all() i created the following PHP file:
if (isset($_GET['review']))
    $query = "SELECT text, rating, date, member FROM reviews WHERE users = '" . mysqli_real_escape_string($link, $_GET['review']) . "'";
else if (isset($_GET['rating']))
    $query = "SELECT ROUND(avg_rating, 2) as avg, num_recensioni FROM avg_voti WHERE users = '" . mysqli_real_escape_string($link, $_GET['rating']) . "'";
else if (isset($_POST['usersId']))
    $query = "SELECT id, name, desc, addr FROM users WHERE id = '" . mysqli_real_escape_string($link, $_POST['usersId']) . "' ORDER BY name ASC";

$result = pg_query($link, $query);
$arr = pg_fetch_all($result);
echo json_encode($arr);

Now, since i changed the database from Postegres to MySQL i need to "convert" that code. So i changed the last three lines in this way:
$result = mysqli_query($link, $query);
$arr = mysqli_fetch_all($result);
echo json_encode($arr);

But mysqli_fetch_all() seems to be undefined. What can i use the get the same of pg_fetch_all() ? Thanks in advance
EDIT: My PHP version is 5.4.39

A: As the PHP Docs said for the function mysqli_fetch_all() it requires a PHP version >= 5.3.0. Check yours

HOW TO check PHP version:
  http://php.net/manual/en/function.phpversion.php

UPDATE:

*

*Check if in your server is installed the mysqlnd driver (See same DOCs page)

*Try with mysqli_fetch_array()

UPDATE 2:
METHOD 1:

HOW TO use mysqli_fetch_array() to fetch all rows:
  mysql_fetch_array add all rows?

Next code is mysql function instead of mysqli but it will work if you change the function name
$rows = array();

while(($row = mysql_fetch_array($result))) {
    $rows[] = $row;
}

METHOD 2:

HOW TO use mysqli_fetch_assoc() to fetch all rows:
  http://php.net/manual/en/function.mysql-fetch-array.php#87201

// Read records
$result = mysqli_query("SELECT * FROM table;") or die(mysql_error());
// Put them in array
for($i = 0; $array[$i] = mysqli_fetch_assoc($result); $i++) ;
// Delete last empty one
array_pop($array);

"You need to delete the last one because this will always be empty.
By this you can easily read the entire table to an array and preserve the keys of the table columns. Very handy."

A: Here is the final solution:
pg_fetch_all() use (for Postegres):
$result = mysqli_query($link, $query);
$arr = mysqli_fetch_all($result);
echo json_encode($arr);

Equivalent for MySQL:
$result = mysqli_query($link, $query);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
}
echo json_encode($rows);


text:
Q: How can I align the text size in tkinter Canvas with scrollbar motions? Hello I'm korean student currently studying in Korea.
class Layout(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root)
        self.canvas = tk.Canvas(self, width=400, height=750, background="bisque")
        self.xsb = tk.Scrollbar(self, orient="horizontal", command=self.canvas.xview)
        self.ysb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.ysb.set, xscrollcommand=self.xsb.set)
        self.canvas.configure(scrollregion=(0,0,1000,1000))

        self.xsb.grid(row=1, column=0, sticky="ew")
        self.ysb.grid(row=0, column=1, sticky="ns")
        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        #self.canvas.create_text(50,10, text="Click and drag to move the canvas\nScroll to zoom.")

        # This is what enables using the mouse:
        self.canvas.bind("<ButtonPress-1>", self.move_start)
        self.canvas.bind("<B1-Motion>", self.move_move)
        #linux scroll
        self.canvas.bind("<Button-4>", self.zoomerP)
        self.canvas.bind("<Button-5>", self.zoomerM)
        #windows scroll
        self.canvas.bind("<MouseWheel>",self.zoomer)

    #move
    def move_start(self, event):
        self.canvas.scan_mark(event.x, event.y)
    def move_move(self, event):
        self.canvas.scan_dragto(event.x, event.y, gain=1)

    #windows zoom
    def zoomer(self,event):
        if (event.delta > 0):
            self.canvas.scale("all", event.x, event.y, 1.1, 1.1)
        elif (event.delta < 0):
            self.canvas.scale("all", event.x, event.y, 0.9, 0.9)
        self.canvas.configure(scrollregion = self.canvas.bbox("all"))

    #linux zoom
    def zoomerP(self,event):
        self.canvas.scale("all", event.x, event.y, 1.1, 1.1)
        self.canvas.configure(scrollregion = self.canvas.bbox("all"))
    def zoomerM(self,event):
        self.canvas.scale("all", event.x, event.y, 0.9, 0.9)
        self.canvas.configure(scrollregion = self.canvas.bbox("all"))

as you can see the codes above
I have made the codes to display the Canvas widget.
and I have also aligned the scrollbars with the materials displayed in the canvas widget.
 monitor1.canvas.create_rectangle(50 + 200*(l-3*ll) + 800*(k % 3), 250 + 150*(ll) + 150*(vertical_append//3 + 2*kk), 90 + 200*(l-3*ll) + 800*(k % 3), 300 + 150*(ll) + 150*(vertical_append//3 + 2*kk) + 10*(int(each_info[5]) - 4), fill = "green")
                monitor1.canvas.create_rectangle(90 + 200*(l-3*ll) + 800*(k % 3), 245 + 150*(ll) + 150*(vertical_append//3 + 2*kk), 110 + 200*(l-3*ll) + 800*(k % 3), 305 + 150*(ll) + 150*(vertical_append//3 + 2*kk) + 10*(int(each_info[5]) - 4), fill = "red")
                monitor1.canvas.create_rectangle(110 + 200*(l-3*ll) + 800*(k % 3), 250 + 150*(ll) + 150*(vertical_append//3 + 2*kk), 150 + 200*(l-3*ll) + 800*(k % 3), 300 + 150*(ll) + 150*(vertical_append//3 + 2*kk) + 10*(int(each_info[5]) - 4), fill = "green")

                # Labelling
                monitor1.canvas.create_text(70 + 200*(l - 3*ll) + 800*(k % 3), 275 + 5*(int(each_info[5]) - 4) + 150*(ll) + 150*(vertical_append//3 + 2*kk), text = each_info[1], font =("Helvetica", 10))
                monitor1.canvas.create_text(100 + 200*(l - 3*ll) + 800*(k % 3), 270 + 5*(int(each_info[5]) - 4) + 150*(ll) + 150*(vertical_append//3 + 2*kk), text = each_info[2], font = ("Helvetica", 10))
                monitor1.canvas.create_text(130 + 200*(l - 3*ll) + 800*(k % 3), 275 + 5*(int(each_info[5]) - 4) + 150*(ll) + 150*(vertical_append//3 + 2*kk), text = each_info[3], font = ("Helvetica", 10))
                monitor1.canvas.create_text(110 + 200*(l - 3*ll) + 800*(k % 3), 235 + 150*(ll) + 150*(vertical_append//3 + 2*kk), text = each_info[0] + " " + each_info[4], font = ("Helvetica", 10))
                monitor1.canvas.create_text(110 + 200*(l - 3*ll) + 800*(k % 3), 205 + 150*(ll) + 150*(vertical_append//3 + 2*kk), text = key, font = ("Helvetica", 10))
                monitor1.canvas.create_text(110 + 200*(l - 3*ll) + 800*(k % 3), 220 + 150*(ll) + 150*(vertical_append//3 + 2*kk), text = "width: " + each_info[5], font = ("Helvetica", 10))

as you can see the codes above
I have created the rectangles and texts above
rectanges & text in canvas before zoom out
rectanges & text in canvas after zoom out
and as you can see in the images of png formats,
the rectangles in the canvas widgets are aligned well with the scrollbar motions
they get smaller as I zoom out with scroll bar
they get bigger as I zoom in with scroll bar
but the texts in the canvas widgets are not aligned with the scrollbar motions
what can I do to align the text widgets created in the canvas with the scrollbar motions


text:
Q: How can one change the FocusState of a SwiftUI app with TextFields in different child views without having View refresh which causes a bounce effect? My Problem: I want the user to be able to go from Textfield to TextField without the view bouncing as shown in the gif below.
My Use Case: I have multiple TextFields and TextEditors in multiple child views. These TextFields are generated dynamically so I want the FocusState to be a separate concern.
I made an example gif and code sample below.

Please check it out, any suggestions appreciated.
As suggested in the comments I made some changes with no effect to the bounce:
 - Using Identfiable does not change the bounce
 - A single observed object or multiple and a view model does not change the bounce

I think this is from the state change refresh. If it's not the refresh causing the bounce(as the user suggests in the comments) what is? Is there a way to stop this bounce while using FocusState?
To Reproduce: Create a new iOS app xcode project and replace the content view with this code body below. It seems to refresh the view when the user goes from one textfield to the next textfield causing a bounce of the whole screen.
Code Example
import SwiftUI

struct MyObject: Identifiable, Equatable {
    var id: String
    public var value: String
    init(name: String, value: String) {
        self.id = name
        self.value = value
    }
}

struct ContentView: View {

    @State var myObjects: [MyObject] = [
        MyObject(name: "aa", value: "1"),
        MyObject(name: "bb", value: "2"),
        MyObject(name: "cc", value: "3"),
        MyObject(name: "dd", value: "4")
    ]
    @State var focus: MyObject?

    var body: some View {
        VStack {
            Text("Header")
            ForEach(self.myObjects) { obj in
                Divider()
                FocusField(displayObject: obj, focus: $focus, nextFocus: {
                    guard let index = self.myObjects.firstIndex(of: $0) else {
                        return
                    }
                    self.focus = myObjects.indices.contains(index + 1) ? myObjects[index + 1] : nil
                })
            }
            Divider()
            Text("Footer")
        }
    }
}

struct FocusField: View {

    @State var displayObject: MyObject
    @FocusState var isFocused: Bool
    @Binding var focus: MyObject?
    var nextFocus: (MyObject) -> Void

    var body: some View {
        TextField("Test", text: $displayObject.value)
            .onChange(of: focus, perform: { newValue in
                self.isFocused = newValue == displayObject
            })
            .focused(self.$isFocused)
            .submitLabel(.next)
            .onSubmit {
                self.nextFocus(displayObject)
            }
    }
}

A: After going through this a bunch of times, it dawned on me that when using FocusState you really should be in a ScrollView, Form or some other type of greedy view. Even a GeometryReader will work. Any of these will remove the bounce.
struct MyObject: Identifiable, Equatable {
    public let id = UUID()
    public var name: String
    public var value: String
}

class MyObjViewModel: ObservableObject {

    @Published var myObjects: [MyObject]

    init(_ objects: [MyObject]) {
        myObjects = objects
    }
}

struct ContentView: View {
    @StateObject var viewModel = MyObjViewModel([
        MyObject(name: "aa", value: "1"),
        MyObject(name: "bb", value: "2"),
        MyObject(name: "cc", value: "3"),
        MyObject(name: "dd", value: "4")
    ])

    @State var focus: UUID?

    var body: some View {
        VStack {
            Form {
                Text("Header")
                ForEach($viewModel.myObjects) { $obj in
                    FocusField(object: $obj, focus: $focus, nextFocus: {
                        guard let index = viewModel.myObjects.map( { $0.id }).firstIndex(of: obj.id) else {
                            return
                        }
                        focus = viewModel.myObjects.indices.contains(index + 1) ? viewModel.myObjects[index + 1].id : viewModel.myObjects[0].id
                    })
                }
                Text("Footer")
            }
        }
    }
}

struct FocusField: View {

    @Binding var object: MyObject
    @Binding var focus: UUID?
    var nextFocus: () -> Void

    @FocusState var isFocused: UUID?

    var body: some View {
        TextField("Test", text: $object.value)
            .onChange(of: focus, perform: { newValue in
                self.isFocused = newValue
            })
            .focused(self.$isFocused, equals: object.id)
            .onSubmit {
                self.nextFocus()
            }
    }
}

edit:
Also, it is a really bad idea to set id in the struct the way you did. An id should be unique. It works here, but best practice is a UUID.
Second edit: tightened up the code.


text:
Q: Save python compile object in database or cache I'm designing an online compiler where multiple users can run some python code, for which I use exec in my back end. I want to optimize it as the code that users run seldom changes.  Security is not a concern here as of now. How do I optimize this python compilation, I found some solutions online like

*

*Using python Compile and saving it as pickled data.

*Compile with Redis.

*SqlAlchemy (but how do I store this object in database)

Any help or a different view is appreciated.


text:
Q: How to select rows in google sheets by condition I've been researching this for a couple of hours now and have had no luck.
I am trying to search for emails in my spreadsheet that contain "@google.com" and have them all selected so that I can copy them instead of going through them 1 by 1. There are around 90K so this would be a considerable undertaking.
This is the formula that I am currently using:
=QUERY(Data!A:A,"select A where(A =@google.com)")

All of the data is in column A.
Hope I've just made a dumb error somewhere.
Thanks in advance :)

A: Perhaps what you might try is:
=QUERY(Data!A:A,"where A contains '@google.com'")


text:
Q: How to fix programmatically the search bar in swift I programmatically created a search bar in ViewController.
But when I scroll up the screen, the search bar goes up.
How can I freeze the search bar?
class searchbarTable:  UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {
    @IBOutlet var tableview: UITableView!

    let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        definesPresentationContext = true
        self.tableview.tableHeaderView = searchController.searchBar
    }
}

A: You can try this and set searchbar in Navigation Bar
self.navigationController?.searchDisplayController = searchController

OR
lazy var searchBar = UISearchBar(frame: CGRectZero)

override func viewDidLoad() {
    super.viewDidLoad()

    searchBar.placeholder = "Search"

    navigationItem.titleView = searchBar
}

OR
var leftNavBarButton = UIBarButtonItem(customView:Yoursearchbar)
  self.navigationItem.leftBarButtonItem = leftNavBarButton

OR
searchController.hidesNavigationBarDuringPresentation = false

it hide naviationbar when we present okay
Hope it helps You :)


text:
Q: Track file download from sql database I am developing an appstore application for andriod.
I want to sort items according to the count they have been downloaded. Android application uses Json for getting the information of the files and files information is located in a sql database.
How can I query the count of downloads for each file so that I can sort them by the number of downloads?

A: Add an ORDER BY clause to your SQL query
something like ORDER BY COUNT(Downloads) DESC


text:
Q: Fluent Assertions: Approximately compare two 2D rectangular arrays I'm able to approximately compare two 2D rectangular arrays in Fluent Assertions like this:
float precision = 1e-5f;
float[,] expectedArray = new float[,] { { 3.1f, 4.5f}, { 2, 4} };
float[,] calculatedArray = new float[,] { { 3.09f, 4.49f}, { 2, 4} };

for (int y = 0; y < 2; ++y)
{
    for (int x = 0; x < 2; ++x)
    {
        calculatedArray[y,x].Should().BeApproximately(expectedArray[y,x], precision);
    }
}

but is there a cleaner way of achieving this (without the for loops)? For example, something in the same vein as this (which is for 1D arrays):
double[] source = { 10.01, 8.01, 6.01 };
double[] target = { 10.0, 8.0, 6.0  };

source.Should().Equal(target, (left, right) => Math.Abs(left-right) <= 0.01);

The above solution for a 1D array comes from the question: Fluent Assertions: Compare two numeric collections approximately

A: There doesn't appear to be anything currently in the framework that supports this.  If you don't want to have the loop in your tests, then one option would be for you to add your own extensions to cover this scenario.
There are two elements to this.  The first is to add an extension method that adds the Should ability to 2D arrays:
public static class FluentExtensionMethods
{
    public static Generic2DArrayAssertions<T> Should<T>(this T[,] actualValue)
    {
        return new Generic2DArrayAssertions<T>(actualValue);
    }
}

You then need to implement the actual assertion class, which will contain the comparison loop:
public class Generic2DArrayAssertions<T>
{
    T[,] _actual;

    public Generic2DArrayAssertions(T[,] actual)
    {
        _actual = actual;
    }

    public bool Equal(T[,] expected, Func<T,T, bool> func)
    {
        for (int i = 0; i < expected.Rank; i++)
            _actual.GetUpperBound(i).Should().Be(expected.GetUpperBound(i),
                                                 "dimensions should match");

        for (int x = expected.GetLowerBound(0); x <= expected.GetUpperBound(0); x++)
        {
            for (int y = expected.GetLowerBound(1); y <= expected.GetUpperBound(1); y++)
            {
                func(_actual[x, y], expected[x, y])
                     .Should()
                     .BeTrue("'{2}' should equal '{3}' at element [{0},{1}]",
                      x, y, _actual[x,y], expected[x,y]);
            }
        }

        return true;
    }
}

You can then use it in your tests like other assertions:
calculatedArray.Should().Equal(expectedArray,
                               (left,right)=> Math.Abs(left - right) <= 0.01);

I think your comment is asking how you go about testing the extension code I'm suggesting.  The answer is, the same way you go about testing anything else, pass in values and validate the output.  I've added some tests below (using Nunit) to cover some of the key scenarios.  Some things to note, the data for the scenarios is incomplete (it seems out of scope and isn't that hard to generate).  The tests are using a func of left == right, since the point is to test the extension, not the evaluation of the approximation.
[TestCaseSource("differentSizedScenarios")]
public void ShouldThrowIfDifferentSizes(float[,] actual, float[,] expected)
{
    Assert.Throws<AssertionException>(()=>actual.Should().Equal(expected, (l, r) => l == r)).Message.Should().Be(string.Format("Expected value to be {0} because dimensions should match, but found {1}.", expected.GetUpperBound(0), actual.GetUpperBound(0)));
}

[TestCaseSource("missMatchedScenarios")]
public void ShouldThrowIfMismatched(int[,] actual, int[,] expected, int actualVal, int expectedVal, string index)
{
    Assert.Throws<AssertionException>(()=>actual.Should().Equal(expected, (l, r) => l.Equals(r))).Message.Should().Be(string.Format("Expected True because '{0}' should equal '{1}' at element [{2}], but found False.", actualVal, expectedVal, index));
}

[Test]
public void ShouldPassOnMatched()
{
    var expected = new float[,] { { 3.1f, 4.5f }, { 2, 4 } };
    var actual = new float[,] { { 3.1f, 4.5f }, { 2, 4 } };
    actual.Should().Equal(expected, (l, r) => l.Equals(r));
}

static object[] differentSizedScenarios =
{
    new object[] {
        new float[,] { { 3.1f, 4.5f }, { 2, 4 } },
        new float[,] { { 3.1f, 4.5f }, { 2, 4 }, {1,2} }
    },
    new object[] {
        new float[,] { { 3.1f, 4.5f }, { 2, 4 } },
        new float[,] { { 3.1f, 4.5f }}
    }
    // etc...
};
static object[] missMatchedScenarios =
{
    new object[] {
        new int[,] { { 1, 2}, { 3, 4 } },
        new int[,] { { 11, 2}, { 3, 4 } }
        ,1, 11, "0,0"
    },
    new object[] {
        new int[,] { { 1, 2}, { 3, 14 } },
        new int[,] { { 1, 2}, { 3, 4 } }
        ,14, 4, "1,1"
    },
    // etc...
};

A: I haven't fully tested this, but the following seems to work.
float precision = 0.1f; // Test passes with this level of precision.
//float precision = 0.01f; // Test fails with this level of precision.
float[,] expectedArray = new float[,] { { 3.1f, 4.5f }, { 2, 4 } };
float[,] calculatedArray = new float[,] { { 3.09f, 4.49f }, { 2, 4 } };

calculatedArray.Should().BeEquivalentTo(
    expectedArray,
    options => options
        .ComparingByValue<float>()
        .Using<float>(ctx => ctx.Subject.Should().BeApproximately(ctx.Expectation, precision))
        .WhenTypeIs<float>());


text:
Q: Initiate service group check Is there a way to initiate a check of all services in a service group from either the Nagios web GUI or via the command line?
For example, I have a service group with a check that runs on 30 machines.  I'd like to initiate a command that would force the check on all of those 30 machines.  I know you can do it via the GUI on a single machine, but it would be great if it could be done against an entire service group.

A: I am not aware of any way through the standard GUI to accomplish this.
But one thing you can do is install the livestatus module.  This module makes Nagios listen on a socket, and you can run queries against it, and retrieve information.  With this API enabled you should then be able write a script that gets information about the servicegroup, and then runs a series of commands.
Your system must also have External Commands enabled.  Livestatus is how you get information out.  External commands is how you send in your requests for an action to be performed.
This example script might be able to get you started.  This script sends a query to live status to find all hosts with a non OK state.  It then forces an immediate re-check for each host host found in this state.
#!/bin/bash
LIVESTATUSSOCKET=/var/lib/nagios3/rw/live
NAGIOS_CMD_SOCKET='/var/lib/nagios3/rw/nagios.cmd'

export IFS=';'
echo "GET hosts
Columns: state host_name
Filter: state != 0
" | unixcat $LIVESTATUSSOCKET \
  | (

  while read -a LINE ; do
     /usr/bin/printf "[%lu] SCHEDULE_HOST_CHECK;%s;%s\n" \
                      $(date +%s) \
                      "${LINE[1]}" \
                      $(date +%s) | tee -a $NAGIOS_CMD_SOCKET
  done
)


text:
Q: DNS Server and Private HTTP / SOCKS Proxy this is just a small hacking attemp to our router.
I'm trying to setup a small DNS and forward webpages through proxy behind the scene. I've successfully implement the DNS server that will do the resolving or anything involved in address resolve.
But is there anyway I can forward the user using DNS to a proxy instead of request directly to the server? Are there any software/opensource that I can use?
I notice on paid wireless, they can provide a login page if user is not login yet, i think this is a way of implementing proxy.
Also the hardware is very basic with linksys and netgear router which connect directly to the internet. It's a basic LAN

A: I may be answering the wrong question because you are talking about using DNS to give false replies, but I will give this answer any way in case this is what you really want to be doing (if you want to implement a login-type page for all users).
You want to implement something known as a "Walled Garden" or, if you look in Wikipedia, a "Captive Portal".
Learn IPTables - you will most likely want a default rule that forwards all traffic to your HTTP server. Your HTTP server will then have an intelligent page that updates a database or similar with the IP addresses that have a valid login and consequently a script will update your iptables rules with those ip addresses permitted access to the Internet.
You would create a chain called "garden", and add the following rules to it which would force all traffic except DNS to be forwarded to 192.168.1.1:
iptables -A garden -p tcp --dport ! 53 -j DNAT --to 192.168.1.1
iptables -A garden -p udp --dport ! 53 -j DNAT --to 192.168.1.1

Then in the appropriate chain (be it NAT or whatever) add a rule to jump to the "garden" chain if not a registered valid IP address.


text:
Q: Can't get data from MongoDB database for web app I'm new to using MongoDB. Currently, I am making a web application that requires some data storage. I established an HTTP server on Node.js that runs on localhost:3000. I also built a virtual development environment using Vagrant and VirtualBox. I am accessing the Mongo shell from PuTTy (if that is relevant at all). Before incorporating MongoDB, it worked fine as I was storing the data in the Node.js program memory.
This web app is an online to-do-list. The first error that I am getting is with the get route. The list of "to-do"s that I have inserted into the Mongo database would not appear on the site in localhost. It seems to not be getting the data from the database. The second error that I am getting is with the post route. When I insert a "to-do" through the user interface at localhost and I refresh the page, the to-do-list on localhost gets updated with that particular to-do (but not with the ones I inserted in the database). But, it doesn't seem to add it into the database, and I still get this error on the console:
vagrant@precise32:~/app$ node server.js
{ description: 'descTest3', tags: [ 'tagTest3' ] }
Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html

I'm not sure why I got that error since I do not seem to be using any promises.
server.js
var express = require("express"), http = require("http"), app = express(), mongoose = require("mongoose");

app.use(express.static(__dirname + "/client"));

app.use(express.urlencoded());

mongoose.connect('mongodb://localhost/WatNext');//connect to the WatNext data store in mongoDB

var ToDoSchema = mongoose.Schema({
    "description": String,
    "tags": [ String ] //array of Strings
});

var ToDo = mongoose.model("ToDo", ToDoSchema)

http.createServer(app).listen(3000);
//get and post routes:

app.get("/toDos.json", function (req, res) {
    ToDo.find({}, function (err, toDos) {
        if (err != null){
            console.log(err);
        }
        res.json(toDos);
    });
});

app.post("/todos", function (req, res) {
    console.log(req.body);
    var addedToDo = new ToDo({"description" : req.body.description, "tags" : req.body.tags});
    //save function saves object into the database
    addedToDo.save(function (err, result) {
        if (err != null){//if there is an error
            console.log(err);
            res.send("ERROR SAVING");
        }
        else {
            ToDo.find({}, function (err, result) {
                if (err != null){//if there is an error in finding
                    res.send("ERROR FINDING");
                }
                res.json(result);
            });
        }
    });
});

app.js
var main = function (toDoObjects) {
//do stuff with ToDoObjects including outputting the list of ToDos
};
$(document).ready(function() {
    $.getJSON("toDos.json", function(toDoObjects) {
        main(toDoObjects);
    })
});

mongo shell
> show dbs
WatNext 0.0625GB
local   0.03125GB
> use WatNext
switched to db WatNext
> show collections;
system.indexes
toDoCollection
todos
> db.toDoCollection.find();
{ "_id" : ObjectId("58b38dd8fb355f57162d9cf1"), "description" : "Get groceries and eat afterwards", "tags" : [  "shopping",  "chores" ] }
{ "_id" : ObjectId("58b38dd8fb355f57162d9cf2"), "description" : "Make up some new To-Dos", "tags" : [  "writing",  "work" ] }
{ "_id" : ObjectId("58b38dd8fb355f57162d9cf3"), "description" : "Prep for Monday's class", "tags" : [  "work",  "teaching" ] }
{ "_id" : ObjectId("58b38dd8fb355f57162d9cf4"), "description" : "Answer emails", "tags" : [  "work" ] }
{ "_id" : ObjectId("58b38dd8fb355f57162d9cf5"), "description" : "Take April to the park", "tags" : [  "chores",  "pets" ] }
{ "_id" : ObjectId("58b38dd8fb355f57162d9cf6"), "description" : "Finish writing this book", "tags" : [  "writing",  "work" ] }

EDIT:
I found out it was just an error of naming.
I also found out that
mongoose.Promise = require("bluebird");

solved the problem with the promise error. Remember to install the module first though:
npm install --save bluebird

A: I found out what was wrong. It was an error in naming for the GET and POST routes. It should have been:
app.get("/todos.json", function (req, res) { //get the data from the collection called 'todos' in MongoDB

as well as:
$.getJSON("todos.json", function(toDoObjects) {

I should have used the todos collection instead of toDoCollection:
 "description" : "descTest1", "_id" : ObjectId("58b39a1fb1a30305075408fa"), "tags" : [  "tagTest2" ], "__v" : 0 }
{ "description" : "descTest2", "_id" : ObjectId("58b4c837d47a5604c7c0609a"), "tags" : [  "tagsTest2" ], "__v" : 0 }
{ "description" : "descTest3", "_id" : ObjectId("58b4ca0491f4c804d200cda9"), "tags" : [  "tagTest3" ], "__v" : 0 }
{ "description" : "descTest4", "_id" : ObjectId("58b4e636b71d0a05ebb7a71a"), "tags" : [  "tagTest4" ], "__v" : 0 }
{ "description" : "descTest5", "_id" : ObjectId("58b60211428520053a4714ed"), "tags" : [  "tagTest5" ], "__v" : 0 }
{ "_id" : ObjectId("58b6037839e65d96e13cf68e"), "description" : "descTestMONGO", "tags" : [  "tagTestMONGO" ] }
{ "_id" : ObjectId("58b605b339e65d96e13cf690"), "description" : "Take April to the park", "tags" : [  "chores",  "pets" ] }


text:
Q: {} + [] - why it is 0 or [object Object]? If you open a JS Console in your browser (in my case Chrome) and type:
{} + []

you will get 0, but when you type
console.log({} + [])

you get [object Object]... any ideas why the result is different? I've always thought that when you type there it always wrap it with console.log?

A: When you see {} character at the beginning it is interpreted as a empty block or empty object literal(when you're creating objects).
When you're using an expression or statement, + represent the plus operator, which coerces its operand(in this case it will be []) to a number.
So +[] is the same as Number([]), which evaluates to 0.
The unary plus operator internally use the ToNumber abstract operation.
Read more about Type Conversions and operators.

console.log(Number([]));

With the other words, {} + [] expression is an empty code block followed by an array which will be constraint to a number(Number[]).
In the second example you're providing you just concat an object literal(empty object) to an array. That't why you're receiving [object Object].

A: Empty object as {} returns "[object Object]" when you call its toString() method. Empty array returns "" when you call its toString() method. Thus, console.log({} + []) will output "[object Object]"

A: {} can either be an empty block or a empty object literal depending on context.
+ can either be the unary plus operator or the concatination operator depending on context.
The first code example is an empty block it might as well not be there, making the expression the same as +[], meaning "An empty array converted to a number".
You can't have a block as a function argument, so the second code example {} is an object and the code means "Concatinate an object with an array" (implicitly converting both object and array to strings).

A: it's because {} is an object notation so whatever you concatenate with {} it will give you an [object Object]. I  your case [] is an empty so it just shows an [object Object]. so if you could try the following you will got what you want.
 console.log({} + 5);
 [object Object]5  ///console shows
      //And
console.log({} + "test");
VM65:1 [object Object]test //console shows


text:
Q: I have a problem with sceneManager.LoadScene I have this piece of code
                if(personajeCreado == "0")
                {
                Debug.Log("hi");
                UnityEngine.SceneManagement.SceneManager.LoadScene("CreandoPersonaje");

                Debug.Log("bye");

                }

In the debugger I only read hi, but my scene does not change, there are no errors, there is nothing to indicate a problem. please help.

A: Possibilities:
 - You do not have the target scene included in the build
 - The name of the scene is not correct (I would copy the name from the scene file itself)
 - Your target scene is same as your starting scene and you did not notice the change of scene
 - You have error message in your console but you have disabled the error message view and did not see the actual error


text:
Q: RSpec & Rails: Stub request.path for helper spec I have this method in ApplicationHelper:
def home_link_class
  classes = ['navbar-brand']
  classes << 'active' if request.path == root_path
  classes
end

I want to test it like this:
describe '#home_link_class' do
  before  { allow(helper.request).to receive(:path).and_return '/some-path' }
  subject { home_link_class }

  it { should eq ['navbar-brand'] }
end

Sadly the stubbing doesn't seem to work, the request object in the helper itself is set to nil, even though in the spec it seems to be an ActionController::TestRequest object.
How do I make sure that request is available in the spec?

A: You need to stub the request itself as well as the return value of path. Define a test double for the request that stubs path:
describe '#home_link_class' do
  let(:request) { double('request', path: '/some-path') }

  before  { allow(helper).to receive(:request).and_return(request) }
  subject { home_link_class }

  it { should eq ['navbar-brand'] }
end


text:
Q: PHP get "Application Root" in Xampp on Windows correctly I found this thread on StackOverflow about how to get the "Application Root" from inside my web app.
However, most of the approaches suggested in that thread can hardly be applied to my Xampp on Windows. Say, I've got a "common.php" which stays inside my web app's app directory:
/
/app/common.php
/protected/index.php

In my common.php, what I've got is like this:
define('DOCROOT', $_SERVER['DOCUMENT_ROOT']);
define('ABSPATH', dirname(__FILE__));
define('COMMONSCRIPT', $_SERVER['PHP_SELF']);

After I required the common.php inside the /protected/index.php, I found this:
C:/xampp/htdocs     //<== echo DOCROOT;
C:\xampp\htdocs\comic\app //<== echo ABSPATH
/comic/protected/index.php //<== echo COMMONSCRIPT

So the most troublesome part is the path delimiters are not universal, plus, it seems all
superglobals from the $_SERVER[] asso array, such as $_SERVER['PHP_SELF'], are relative to the "caller" script, not the "callee" script.
It seems that I can only rely on dirname(__FILE__) to make sure this always returns an absolute path to the common.php file.
I can certainly parse the returning values from DOCROOT and ABSPATH and then calculate the correct "application root". For instance, I can compare the parts after htdocs and substitute all backslashes with slashes to get a unix-like path
I wonder is this the right way to handle this? What if I deploy my web app on a LAMP environment? would this environment-dependent approach bomb me out?
I have used some PHP frameworks such as CakePHP and CodeIgniter, to be frank, They just work on either LAMP or WAMP, but I am not sure how they approached such a elegant solution.
Many thanks in advance for all the hints and suggestions.

A: dirname(__FILE__) is a common method of getting the path. Actually, if your script will only run on PHP 5.3 or later, __DIR__ will do the same thing and is a little shorter to type.
I think your strategy involving common.php is a little redundant. For starters, DOCROOT and COMMONSCRIPT are useless - they just duplicate some data that is already global. (All PHP developers know what $_SERVER['PHP_SELF'] is, but I personally would not know what COMMONSCRIPT means without looking it up.)
Second, it may be more trouble than it's worth. Compare some different ways of getting the path to /protected/protected2.php from /protected/protected.php:
ABSPATH . "/../protected/protected2.php";
"protected2.php"
dirname(__FILE__) . "/protected2.php";

All of these are valid, but some are easier than others. This just illustrates that what you are asking for (getting the application root) may not always be what you need. So I would say, there is no magic path bullet that will solve all of your problems. If you find yourself in a situation in which the ABSPATH constant helps you, use it.
Second part of your question: Forward slashes will work on Windows, even mixed with backslashes. For example:
include("c:\whatever\whatever/something/anything.php");

will work in PHP on Windows (at least on any 5.0+ version; not sure about 4.x). Backslashes will not work on Unix, so just always type forward slashes and you'll be cross-platform-safe.
If you are writing a cross-platform script, you never want to code in a drive letter. Instead, write it like this:
include("/whatever/whatever/something/anything.php");

The initial / will be interpreted by PHP on Windows as c:\. (I don't know how to point to a different drive letter in a cross-platform way.)
HTH


text:
Q: Split a file name and only take one part for use I have a $value such as 22214-HAV.jpg or 22214 HAV.jpg (notice no dash)
I want to run a quick function to pull only the number from filename.

A: A quick solution, which make use of PHPs type juggling
$number = (int) $filename;

A: preg_match('/^\d+/' ,'22214-HAV.jpg', $matches);
var_dump($matches[0]);

Observations:

*

*This will only match numbers starting exactly from the beginning. Any position can be allowed by removing ^.

*This will match any sequence of digits and not actual numbers. Numbers can be restricted by using ([1-9]\d*|0) in place of \d+.

*If no match is found $matches[0] will be null and not an empty string.

Further reading:

*

*http://www.php.net/manual/en/function.preg-match.php

*http://www.regular-expressions.info/reference.html

A: You can use explode for this
   //for '-'
            list($reqval)=explode('-', $value);
    //for space
            list($reqval)=explode(' ', $value);

        echo $reqval


text:
Q: Should pruning be avoided for bagging (with decision trees)? I came by several posts and papers claiming that pruning trees in a "bagging" ensemble of trees is not needed (see 1).
However, is it necessarily (or at least in some known cases) damaging to perform pruning (say, with the OOB sample) on the individual trees in an ensemble?
Thanks!

A: Tal,
Generally speaking, pruning will hurt performance of bagged trees.
Tress are unstable classifiers; meaning that if you perturb the data a little the tree might significantly change. They are low bias but high variance models. Bagging generally works by "replicating" the model to drive the variance down (the old "increase your sample size" trick).
However, if you end up averaging models that are very similar, then you don't gain much. If the trees are unpruned, they tend to be more different from one another than if they were pruned. This has the effect of "decorrelating" the trees so that you are averaging trees that are not overly similar. This is also the reason that random forests add the additional tweak of the random predictor selection. That coerces the trees into being very different.
Using unpruned trees will increase the risk of overfiting, but model averaging more than offsets this (generally speaking).
HTH,
Max


text:
Q: How can I pass a function to a route with a form, that gets ran after submission and sets the state in previous Route? The Context
I have a little app where you basically can submit ideas.
It exists of the Home Component that renders the ideas in state.
And another component that the user have access to via a React-Router Route where he sees a little form and can submit a new "idea".
The Question
I stumbled upon this problem several times, and now i want to solve it. How can I submit this form, get back to the Home Component, this component grabs the "title" and "body" from the form, creates a new idea and set's the state (rerenders) with the new idea?
More Information
In said Home Component I have this function already added:
addNewIdea = (title, body) => {
    const newIdea = { id: 2, title, body, claimed: false, likes: 0 }
    this.setState({
        ...this.state.ideas,
        newIdea
    })
}

What can I do with it? I can't directly pass it to the "/new/ route right?
So what should actually happen when the user presses "submit" on the form on "/new" route? It should redirect back to home (with the typed in information) and the Home Component should receive this and rerender with a new Idea.
Do I need Redux for this or is this working with blank React?
The NewIdea Component looks like this:
return (

Create a new IDEA

                <input className="new-idea-input-title" type="text" placeholder="Title" value={this.state.title} onChange={(e) => this.setState({ title: e.target.value })} />

 this.setState({ body: e.target.value })}>{this.state.body}

                    <input className="new-idea-submit-btn" type="submit" value="Submit" onClick={this.handleSubmitBtn} />
                    <Link className="new-idea-cancel-btn" to="/">
                        <input className="new-idea-cancel-btn" type="submit" value="Cancel" />
                    </Link>

    )

Just a link that brings the user back when he click on submit button.
Here are my routes:
render() {
return (
  <Router>

      <Route exact path="/" component={Home} />
      <Route exact path="/new" component={NewIdea} />

  </Router>
);
}

Another example what I want to achieve:
Imagine I have the component Home that has as state an array of the ideas (objects).
Now without React Router I would do it like this.
Create a new Component AddIdea - this gets passed a callback function as props (the one from above addNewIdea). The child component AddIdea now fetches the title and body from the user and after hitting submit I run the function from props, which will update the state in the parent component.
But I can't do this in react router. At least not that I know of, so I'm asking, maybe there is a whole other way around this. There has to be, right?
Here is the whole project: https://github.com/dhuber666/Ideas


text:
Q: Moving JavaScript output into other area I'm having trouble moving my JavaScript output (start) from the black box into the grey box. I'm not entirely sure what to put into the functions (moveRight and moveLeft) to get the output to move from one to another.
I've tried searching up a solution but was not able to find one. I'm sure there is a nicer way to present this code but I'm still currently learning the basics. Thank you.

function start() {
  var txt;
  var person = prompt("Please enter your name:", "");
  if (person == null || person == "") {
    txt = "User cancelled the prompt.";
  } else {
    txt = person;
  }
  document.getElementById("text").innerHTML = txt;
}

function moveRight(start) {

}

function moveLeft(start) {

}
.blackbox {
  width: 250px;
  height: 125px;
  background: #000000;
  float: left;
  color: white;
  text-align: center;
  height: 90px;
  line-height: 90px;
}

.greybox {
  width: 250px;
  height: 125px;
  background: #323232;
  float: left;
  text-align: center;
  height: 90px;
  line-height: 90px;
}

.button {
  position: relative;
  float: left;
  padding-left: 10px;
}

.part3 {
  position: relative;
  float: left;
}

  <button type="button" onclick="start()">Start</button>
  <button type="reset">Clear</button>

      <button type="button" onclick="moveRight(start)">--></button>

      <button type="button" onclick="moveLeft(start)"><--</button>

A: This code makes the buttons swap the value between the black and gray boxes

var txt;

function start() {
    var person = prompt("Please enter your name:", "");
    if (person == null || person == "") {
        txt = "User cancelled the prompt.";
    } else {
        txt = person;
    }
    document.getElementById("text").innerHTML = txt;
}

function moveRight() {
    document.getElementById('name').innerHTML = txt;
    document.getElementById('text').innerHTML = '';
}

function moveLeft() {
    document.getElementById('text').innerHTML = txt;
    document.getElementById('name').innerHTML = '';
}
.blackbox{
    width:250px;
    height:125px;
    background:#000000;
    float: left;
    color: white;
    text-align: center;
    height: 90px;
    line-height: 90px;
}

.greybox{
    width:250px;
    height:125px;
    background:#323232;
    float: left;
    text-align: center;
    height: 90px;
    line-height: 90px;
}

.button{
    position: relative;
    float: left;
    padding-left: 10px;
}

.part3{
    position: relative;
    float: left;
}
<!DOCTYPE html>

<title>Test</title>
<meta charset="UTF-8">

<button type="button" onclick="start()">Start</button>
<button type="reset">Clear</button>

    <button type="button" onclick="moveRight()" >--></button>

    <button type="button" onclick="moveLeft()" ><--</button>


text:
Q: ASP.Net MVC: How to add validation to any model property on the fly i am curios to know how could i add validation to any property of my model at run time without touching the code. so looking for guide line how to achieve what i am after in asp.net mvc.
sample model property
[Required(ErrorMessage = "The field {0} is required")]
[Display(Name = "Company")]
public string Name { get; set; }

the above code is a sample where validation has been added when coding but i do not want to attach validation at coding time rather i want to code in such a way as a result at the run time i will be able to inject validation to any model property.
i search a google and found a sample but do not understand how to use it to achieve my task. here is a sample code what i found but not clear how to use it for my purpose.
in Model:
[Domainabcd(20, "Bar", "Baz", ErrorMessage = "The combined minimum length of the Foo, Bar and Baz properties should be longer than 20")]
public string strAccessionId { get; set; }

in DomainabcdAttribute.cs:
public class DomainabcdAttribute : ValidationAttribute, IClientValidatable
 //Domain is the Attribute name
//if you do not inherit IClientValidatable ,the server validation still will work ,but the Client validation will not work.

    {
        public DomainAttribute(int minLength, params string[] propertyNames)
// this is where to get parameters from you pass
//such as : 20, "Bar", "Baz",
        {
            this.PropertyNames = propertyNames;
            this.MinLength = minLength;
        }

        public string[] PropertyNames { get; private set; }
        public int MinLength { get; private set; }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
           ///this is where to decide if to display error ,or not.
            //var properties = this.PropertyNames.Select(validationContext.ObjectType.GetProperty);
            //var values = properties.Select(p => p.GetValue(validationContext.ObjectInstance, null)).OfType<string>();
            //var totalLength = values.Sum(x => x.Length) + Convert.ToString(value).Length;
            //if (totalLength < this.MinLength)
            //{
               //this is the place to return the validation result
             //so you may just use this line code:   return new ValidationResult(validationContext.DisplayName)
                return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
            //}
            //return null; //no error massage

       }
        //this is for Client to display error message
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var modelClientValidationRule = new ModelClientValidationRule
            {
                ValidationType = "requiredif",
                ErrorMessage = ErrorMessage //Added ,pass the error message

            };

            modelClientValidationRule.ValidationParameters.Add("param", this.PropertyNames); //Added
            return new List<ModelClientValidationRule> { modelClientValidationRule };

        }
        // public override string FormatErrorMessage(string name) //to custom format for error message
        //{
        //    string[] values = this.Values.Select(value => string.Format("'{0}'", value)).ToArray();
        //     //return string.Format("{0}{1}", name, string.Join(",", values));
        //     return string.Format(base.ErrorMessageString, name, string.Join(",", values));
        // }
    }

my objective as follows
1) suppose first day i will add validation to name property at run time like name should be required
2) after few days i will add another validation to name property on the fly suppose name should not have special character like @ , : # etc.
3) again after few days i will add another validation to name property on the fly suppose name's length should not be less than 10 character.
hope i am clear what i am trying to achieve. so please anyone who did it just help me with sample code.
thanks

A: Sure you can. E.g. you could validate your object using regular expressions and store them in a web.config.
Sample (this code is just a quick example and should not be used on production):
Modify your web.config to store validator's rules. Add this to <configuration></configuration> section:
<configSections>
    <sectionGroup name="CustomConfig">
    <section name="UniversalValidatorConfig" type="System.Configuration.NameValueSectionHandler" />
    </sectionGroup>
</configSections>

<CustomConfig>
    <UniversalValidatorConfig>
        <add key="EMail" value="^[a-zA-Z0-9_.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$"/>
        <add key="CurrencyIsoCode" value="^([a-zA-Z]{3})$" />
    </UniversalValidatorConfig>
</CustomConfig>

Here we have added validation for EMail and CurrencyIsoCode properties.
To apply validations you should create attribute like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

using System.Configuration;
using System.Collections.Specialized;
using System.Text.RegularExpressions;

namespace WebApplication1.Attributes
{
    [AttributeUsage(AttributeTargets.Class)]
    public class UniversalValidatorAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(Object value, ValidationContext validationContext)
        {
            if (value == null)
                return ValidationResult.Success;

            var validatorConfig = (NameValueCollection)ConfigurationManager.GetSection("CustomConfig/UniversalValidatorConfig");
            var validationRules = validatorConfig.AllKeys
                .Select(key => new { PropertyName = key, ValidationRule = validatorConfig.GetValues(key).FirstOrDefault() })
                .ToList();

            var errorMessages = new List<string>(validationRules.Count);

            foreach (var validationRule in validationRules)
            {
                var property = value.GetType().GetProperty(validationRule.PropertyName);
                if (property == null) continue;

                var propValue = property.GetValue(value)?.ToString();
                var regEx = new Regex(validationRule.ValidationRule, (RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline) | RegexOptions.IgnoreCase);
                var isValid = regEx.IsMatch(propValue);

                if (!isValid)
                    errorMessages.Add(FormatErrorMessage(validationRule.PropertyName));
            }

            if (errorMessages.Any())
                return new ValidationResult(string.Join("\r\n", errorMessages));

            return ValidationResult.Success;
        }
    }
}

Create a class that will be used as input parameter for your action and mark that class with UniversalValidatorAttribute:
using WebApplication1.Attributes;

namespace WebApplication1.ActionParameters
{
    [UniversalValidator]
    public class IndexParameters
    {
        public string EMail { get; set; }
        public string CurrencyIsoCode { get; set; }
    }
}

Now we can use parameters in some action. E.g. modify Home/Index action to consume IndexParameters:
public ActionResult Index(IndexParameters parameters)
{
    if (!ModelState.IsValid)
    {
        foreach(var error in ModelState.Where(ms => ms.Value.Errors.Any()).SelectMany(ms => ms.Value.Errors))
            Debug.WriteLine(error.ErrorMessage);
    }

    return View();
}

To test Validator we can use such URLs (first one will contain two validation errors, second one is valid):

http://localhost:9316/Home/Index?email=admini.net&currencyIsoCode=U
http://localhost:9316/Home/Index?email=admin@i.net&currencyIsoCode=USD

That will allow you change validation rules on-the-fly in web.config

Example with custom rules:
web.config:
<CustomValidatorConfig>
  <add key="FirstName" value="LENGTHGREATER(10)" />
  <add key="BirthDate" value="DATEBETWEEN(01.01.2017, 01.02.2017)" />
</CustomValidatorConfig>

Validator attribute:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Collections.Specialized;
using System.Text.RegularExpressions;

namespace WebApplication1.Attributes
{
    public class CustomValidatorAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(Object value, ValidationContext validationContext)
        {
            if (value == null)
                return ValidationResult.Success;

            var validatorConfig = (NameValueCollection)ConfigurationManager.GetSection("CustomConfig/CustomValidatorConfig");
            var validationRules = validatorConfig.AllKeys
                .Select(key => new { PropertyName = key, ValidationRule = validatorConfig.GetValues(key).FirstOrDefault() })
                .ToList();

            var errorMessages = new List<string>(validationRules.Count);

            foreach (var validationRule in validationRules)
            {
                var property = value.GetType().GetProperty(validationRule.PropertyName);
                if (property == null) continue;

                var propValue = property.GetValue(value);
                var isValid = CustomValidator.IsValid(propValue, validationRule.ValidationRule);

                if (!isValid)
                    errorMessages.Add(FormatErrorMessage(validationRule.PropertyName));
            }

            if (errorMessages.Any())
                return new ValidationResult(string.Join("\r\n", errorMessages));

            return ValidationResult.Success;
        }
    }
}

Attribute applied to model
[CustomValidator]
public class TestValidatorParameters
{
    public string FirstName { get; set; }
    public DateTime BirthDate { get; set; }
}

Action that use Attribute:
public ActionResult TestValidator(TestValidatorParameters parameters)
{
    if (!ModelState.IsValid)
    {
        foreach (var error in ModelState.Where(ms => ms.Value.Errors.Any()).SelectMany(ms => ms.Value.Errors))
            Debug.WriteLine(error.ErrorMessage);

        return Json("Validation failed", JsonRequestBehavior.AllowGet);
    }

    return Json("Validation passed", JsonRequestBehavior.AllowGet);
}

URLs to test (first - validation is ok, second - validation is failed):

http://localhost:9316/Home/TestValidator?FirstName=KowalskiPinguin&BirthDate=01.01.2017
http://localhost:9316/Home/TestValidator?FirstName=Kowalski&BirthDate=01.01.2016

A: One possible solution will be to implement on your model IValidatableObject interface (https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.ivalidatableobject(v=vs.110).aspx) and in the Validate method create your validation messages using Fluent Validation (https://github.com/JeremySkinner/FluentValidation) or similar mechanism/framework. That will still require compilation/distribution of the changes in order to see the effect. In order to avoid that, you could implement an interpreter pattern to create, in the Validate, the validation rules to execute at run-time.


text:
Q: Tool for 'Flattening' (simplifying) C# Source I need to provide a copy of the source code to a third party, but given it's a nifty extensible framework that could be easily repurposed, I'd rather provide a less OO version (a 'procedural' version for want of a better term) that would allow minor tweaks to values etc but not reimplementation using the full flexibility of how it is currently structured.
The code makes use of the usual stuff: classes, constructors, etc.  Is there a tool or method for 'simplifying' this into what is still the 'source' but using only plain variables etc.
For example, if I had a class instance 'myclass' which initialised this.blah  in the constructor, the same could be done with a variable called myclass_blah which would then be manipulated in a more 'flat' way.  I realise some things like polymorphism would probably not be possible in such a situation.  Perhaps an obfuscator, set to a 'super mild' setting would achieve it?
Thanks

A: My experience with nifty extensible frameworks has been that most shops have their own nifty extensible frameworks (usually more than one) and are not likely to steal them from vendor-provided source code.  If you are under obligation to provide source code (due to some business relationship), then, at least in my mind, there's an ethical obligation to provide the actual source code, in a maintainable form.  How you protect the source code is a legal matter and I can't offer legal advice, but really you should be including some license with your release and dealing with clients who are not going to outright steal your IP (assuming it's actually yours under the terms you're developing it.)

A: As had already been said, if this is a requirement based on restrictions of contracts then don't do it. In short, providing a version of the source that differs from what they're actually running becomes a liability and I doubt that it is one that your company should be willing to take. Proving that the code provided matches the code they are running is simple. This is also true if you're trying to avoid license restrictions of libraries your application uses (e.g. GPL).
If that isn't the case then why not provide a limited version of your extensibility framework that only works with internal types and statically compile any required extensions in your application? This will allow the application to continue to function as what they currently run while remaining maintainable without giving up your sacred framework. I've never done it myself but this sounds like something ILMerge could help with.

A: If you don't want to give out framework - just don't. Provide only source you think is required. Otherwise most likely you'll need to either support both versions in the future OR never work/interact with these people (and people they know) again.
Don't forget that non-obfuscated .Net assemblies have IL in easily de-compilable form. It is often easier to use ILSpy/Reflector to read someone else code than looking at sources.
If the reason to provide code is some sort of inspection (even simply looking at the code) you'd better have semi-decent code. I would seriously consider throwing away tool if its code looks written in FORTRAN-style using C# ( http://www.nikhef.nl/~templon/fortran/fortran_style ).
Side note: I believe "nifty extensible frameworks" are one of the roots of "not invented here" syndrome - I'd be more worried about comments on the framework (like "this code is @#@#@ because it does not use YYY pattern and spacing is wrong") than reuse.


text:
Q: Add skipauthorization to request object using Restangular I'm using Satellizer to handle authentication on my app, by default Satellizer intercepts all request and adds the Authorization header.
I do all the request to my API using Restangular but I don't want to send the Authorization header in all the request I make, for example the login and signup endpoints doesn't need this header. If I add skipauthorization: true to the request object, Satellizer won't add the Authorization header. So my question is, how can I add the the skipauthorization property to some of my request using Restangular.
I tried
Restangular.all('signup').withHttpConfig({'skipAuthorization': true}).post(user)

But "withHttpConfig" is not the function I'm loooking for.

A: You need to write request interceptor:
// set full request interceptor

RestangularProvider.setFullRequestInterceptor(function (element, operation, route, url, headers, params, httpConfig) {

  return {
    element: element,
    params: params,
    headers: headers,
    httpConfig: _.extend(httpConfig, {skipAuthorization: true})
  };

});


text:
Q: IPTables disrupts WebServer Connections on Startup Alright, this has not happened before in my past experience in coding and using Linux but right now, when I start up IPTables, I cannot access my website in every way possible. SSH still works.
My operating system:
CentOS Linux release 7.2.1511 (Core)
And the things inside my IPTables:
# sample configuration for iptables service
# you can edit this manually or use system-config-firewall
# please do not ask us to add additional ports/services to this default configuration
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

If anyone could help me fix this problem, it'd be great.

A: iptables -I INPUT 3 -p tcp -m state --state NEW -m tcp -m multiport --dports 80,443 -j ACCEPT

If you could read the manual of iptables, it also would be great.