text:
Q: Looping Increment Not Working I am a beginner to programming and am new to the forum. I have been working on a beginning project, a game of Hangman. I am using an iteration constant, numberGuesses to track how many guesses the user has inputted. However, my program is not iterating properly and I cannot figure why for whatever reason. Any help is greatly appreciated!
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string userWord = " ";
    char userLetter = ' ';
    int numberGuesses = 0;
    string board1 =
        " -------|\n"
        " |      |\n"
        "        |\n"
        "        |\n"
        "        |\n"
        "        |\n"
        "      -----";
    string board2 =
        " -------|\n"
        " |      |\n"
        " O      |\n"
        "        |\n"
        "        |\n"
        "        |\n"
        "      -----";
    string board3 =
        " -------|\n"
        " |      |\n"
        " O      |\n"
        " |      |\n"
        "        |\n"
        "        |\n"
        "      -----";
    string board4 =
        " -------|\n"
        " |      |\n"
        " O      |\n"
        "-|      |\n"
        "        |\n"
        "        |\n"
        "      -----";
    string board5 =
        " -------|\n"
        " |      |\n"
        " O      |\n"
        "-|-     |\n"
        "        |\n"
        "        |\n"
        "      -----";
    string board6 =
        " -------|\n"
        " |      |\n"
        " O      |\n"
        "-|-     |\n"
        "/       |\n"
        "        |\n"
        "      -----";
    string board7 =
        " -------|\n"
        " |      |\n"
        " O      |\n"
        "-|-     |\n"
        "/ \\     |\n"
        "        |\n"
        "      -----";

    cout << "Enter a word to guess: ";
    cin >> userWord;
    for (int i = 0; i < userWord.length(); i++)
       {
           userWord[i] = toupper(userWord[i]);
       }
    cout << "You entered: " << userWord << endl;

    do
    {

        if (numberGuesses = 0)
        {
            cout << board1;
        }
        if (numberGuesses = 1)
        {
            cout << board2;
        }
        else if (numberGuesses = 2)
        {
            cout << board3;
        }
        else if (numberGuesses = 3)
        {
            cout << board4;
        }
        else if (numberGuesses = 4)
        {
            cout << board5;
        }
        else if (numberGuesses = 5)
        {
            cout << board6;
        }
        else if (numberGuesses = 6)
        {
            cout << board7;
        }

        cout << "\nEnter a letter to guess: ";
        cin >> userLetter;
        userLetter = toupper(userLetter);
        cout << "You entered: " << userLetter << endl;

        if (userWord.find(userLetter) != string::npos)
            cout << userLetter << " is in the word to guess." << endl;
        else
            cout << userLetter << " is NOT in the word to guess." << endl;

        numberGuesses++;

    }

    while (numberGuesses <= 6);

    return 0;
}

A: = is the assignment operator. To check for equality, you should use the == operator:
if (numberGuesses == 0) {
    // Here -------^
    // (and do the same for the other conditions)


text:
Q: why is this if,elif and if statement not working with raw_input name = raw_input("What is your name? ")
quest = raw_input("What quest do you chose?, 1 for slaying a dragon, 2 for defeating the evil wizard and 3 for killing the kraken ")
if quest == 1
  quest == "so you want to slay a dragon."
   elif quest == 2
    quest == "do you have something against wizards, relax im joking"
     elif quest = 3
      quest == "have you got a boat, better jet a submarine?"
      else quest = "so you have no quest, hm... in that case GET OUT OF MY SWAMP"

print quest

it keeps giving me  this error:
File "python", line 3
    if quest == 1
                ^
SyntaxError: invalid syntax

A: *

*"==" is a logical operator you can't assign a value to quest using it.

*after putting the if elif condition you should put ":"

*indenting in python is crucial and essential.

*print is a method you need parenthesis to print quest

*check the code snippet below it is a working version of your code

name = raw_input("What is your name? ")
quest = raw_input("What quest do you chose?, 1 for slaying a dragon, 2 for defeating
the evil wizard and 3 for killing the kraken\n")

if quest == "1":
   quest = "so you want to slay a dragon."
elif quest == "2":
   quest = "do you have something against wizards, relax im joking"
elif quest == "3":
   quest = "have you got a boat, better jet a submarine?"
else:
   quest = "so you have no quest, hm... in that case GET OUT OF MY SWAMP"

print(quest)

If this helped you mark it as the answer to your question!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Runtime version information from manifest in Java I have a Java application (compiled with NetBeans 12.5 and OpenJDK 11) where the manifest file is correct, but looks like I'm retrieving the properties from the wrong file(?).
Browsing the built jar I have correctly in META-INF/MANIFEST.MF the properties I'm expecting, as in
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.10.8
Created-By: 11.0.11+9-Ubuntu-0ubuntu2.20.04 (Ubuntu)
Bundle-Name: AppName
Bundle-Version: 1.1.3-b000
Bundle-Date: 2021-10-13 10:47:03 CEST
Implementation-Title: AppName
Implementation-Version: 1.1.3-b000
Implementation-URL: http://www.example.com
...

though when my code reads in
String swVersion = getClass().getPackage().getImplementationVersion();

the result is null
Now, with a more complex
  try {
      InputStream is = getClass()
              .getResourceAsStream("/META-INF/MANIFEST.MF");
      if (is != null) {
          Properties p = new Properties();
          p.load(is);
          swRelease = p.getProperty("Implementation-Version");
      }
  } catch ( IOException e )
  {
  }

what I see from debug is that after p.load(is); the properties listed in p are just three
[0] = (ConcurrentHashMap$MapEntry) "Manifest-Version => 1.0"
[1] = (ConcurrentHashMap$MapEntry) "Created-By => 11.0.5 (Ubuntu)"
[2] = (ConcurrentHashMap$MapEntry) "Main-Class => org.GNOME.Accessibility.AtkWrapper"

So that's clearly not my MANIFEST.MF ...
I'm a bit confused: any hint?
[Edit]
The result wanted is that somewhere, somewhat, I just want to be able to do something like System.out.println(swVersion); and have the output 1.1.3-b000 from the version code as in my manifest

A: What you are doing matches what I did for Read the jar version for a class.
Therefore I strongly believe you are only seeing an issue when running from within Netbeans, where - as Joachim explained - the application is run from the compiled classes directly - no JAR file involved. I perceive the exact same effect.


text:
Q: Arcpy UpdateCursor not Updating, but no Error Reported Below is the code I'm using in an SDE GDB, on ArcMap 10.4.1:
import arcpy

# Variables
inputAsbuilt = arcpy.GetParameterAsText(0)
transmedia = inputAsbuilt + "\\Transmedia"
structure = inputAsbuilt + "\\Structure"
spliceClosure = inputAsbuilt + "\\SpliceClosure"
span = inputAsbuilt + "\\Span"
equipment = inputAsbuilt + "\\Equipment"
buildingfootPrint = inputAsbuilt + "\\BuildingFootPrint"
attachment = inputAsbuilt + "\\Attachment"

spliceClosure1 = '\\\\Bvweb104draco\\e\\03_MapServices\\SDE_CONNECTIONS\\bvtampadev.sde\\bvtampadev.sde.Telecom\\bvtampadev.sde.SPLICECLOSURE'
buildingfootPrint1 = '\\\\Bvweb104draco\\e\\03_MapServices\\SDE_CONNECTIONS\\bvtampadev.sde\\bvtampadev.sde.Telecom\\bvtampadev.sde.BUILDINGOUTLINE'

fcList = [transmedia, structure, spliceClosure, span, equipment, buildingfootPrint, attachment]
sdefcList = [spliceClosure1, buildingfootPrint1, fiberEquipment1, conduit1, structure1, fiberCable1]

# Print out FQNID's of feature classes inside As-Built GDB
fqnList = []
for fc in fcList:
    with arcpy.da.SearchCursor(fc, "FQN_ID") as cursor:
        for row in cursor:
             fqnList.append(row)

for fqn in fqnList:
arcpy.AddMessage(fqn)

# Update "bv_asbuilt_gdb_uploaded" field in SDE feature classes
for fc in sdefcList:
    with arcpy.da.UpdateCursor(fc, ["bv_fqn_id", "bv_asbuilt_gdb_uploaded"])      as cursor:
    for row in cursor:
        if row[0] in fqnList:
            row[1] = "Y"
        else:
            row[1] = "N"
            cursor.updateRow(row)`

What I want the code to do:

*

*Make a list of unique values from a field in the input feature class

*Take that list of unique values, check it against a field in another feature class to see if they're ==, if not write N in the "FQN_ID" field, if yes wrote Y in the "FQN_ID" field
The code is throwing no errors and appends a string "N" where I want it to, but it's not checking the row[0] against "fqnList" correctly, so it populates the entire field with "N" even if there the list matches a value in the feature class field and should populate as "Y"

A: You are creating a list of tuples with fqnList.append(row), for example somelist = [(1,),(2,)], 1 is not in this list, (1,) is.
So when you then check for the id's in list there will never be a match. Change it to fqnList.append(row[0])
You also need to fix the indentation after for row in cursor:
fqnList = []
for fc in fcList:
    with arcpy.da.SearchCursor(fc, "FQN_ID") as cursor:
        for row in cursor:
            fqnList.append(row)

Can be shorter using list comprehension:
fqnList = [i[0] for i in arcpy.da.SearchCursor(fc,"FQN_ID")]

A: fcList = [transmedia, structure, spliceClosure, span, equipment, buildingfootPrint, attachment]
sdefcList = [spliceClosure1, buildingfootPrint1, fiberEquipment1, conduit1, structure1, fiberCable1]
I wasn't creating a full list of the features, such a simple error, but easy to overlook.


text:
Q: Adjoint of an operator on an inner product space Find the adjoint of
$$\left ( Lf \right )\left ( t \right )=t^{2}\frac{df}{dt}+tf$$ where $$f\left ( 0 \right )=1$$ and$$ f'\left ( 1 \right )=2$$
under $$\left \langle f,g \right \rangle=\int_{0}^{1} f\left (t  \right )g\left ( t \right )dt$$
Working out I get
$$\int_{0}^{1}\left ( t^{2}f'\left ( t \right )g+tf\left ( t \right )g\left ( t \right ) \right )dt$$
The 'second' integral that is the terms $$tf\left ( t \right )g\left ( t \right )$$ is a concern. Can I have some help?

A: The first term is given by integration by parts, the second one by noticing that
$$(tf(t))g(t) = f(t)(tg(t)).$$
Therefore,
$$\langle tf(t),g(t)\rangle = \langle f(t),tg(t)\rangle$$
so that the operator $f(t)\mapsto tf(t)$.


text:
Q: TypeError: undefined is not an object (evaluating 'props.navigation.navigate') I'm using react-navigator 4.x and I have only one page to navigate But when I click <Button onPress={() => {props.navigation.navigate({ routeName: 'Login' })}} title="Go To" /> in photos page, I got this error:
import React, { useEffect, useRef } from 'react';
import { View, Button, Text, StyleSheet, TouchableOpacity } from 'react-native';
import 'react-native-gesture-handler';

const NextButton = props => {

    return (

        <View>
            <Button onPress={() => {
                props.navigation.navigate({ routeName: 'Login' })
            }} title="Go To" />
        </View>
    );
}
export default NextButton;

import { createStackNavigator } from "react-navigation-stack";
import { createAppContainer } from "react-navigation";
import Onboarding from "../components/Onboarding";
import Login from './../screens/Login';

const AppNavigator = createStackNavigator({
    Intro: Onboarding,
    Login: Login,
});

export default createAppContainer(AppNavigator);

A: Your NextButton is not really a part of your navigation stack, and hence props.navigation will be undefined, unless you are passing it as prop from your screen, thus the error TypeError: undefined is not an object (evaluating 'props.navigation.navigate').
To get navigation inside your NextButton component, you can either pass it as a prop from the screen you are rendering your NextButton. Or since you are using an older version of the library, you can wrap your NextButton with the withNavigation HOC to get access to navigation props.
import { withNavigation } from 'react-navigation';

const NextButton = props => {
  return (
    <View>
      <Button
        onPress={() => {
          props.navigation.navigate({ routeName: 'Login' })
        }}
        title="Go To"
      />
    </View>
  );
}
export default withNavigation(NextButton);

A: Use NavigationContainer  instead of createAppContainer, I think that changed from v4 to v5.
import { NavigationContainer } from '@react-navigation/native';


text:
Q: Swift 3 - performSegue when animation sequence stop I need help because i can't find example to do exactly what I want need anywhere.
I want to animate a simple png sequence, then call a performSegue once it's completed (that's my main problem)
So I tried with
InitImage.animationImages = [
    UIImage(named:"load1.png")!,
    UIImage(named:"load2.png")!,
    UIImage(named:"load3.png")!,
 /* 20 more images... */
]

InitImage.animationDuration = 2.5
InitImage.animationRepeattCount = 1
InitImate.startAnimating()

so it animates but call the segue too soon.  I found that i should probably use
UIView.animate(withDuration : ...)

But I can't find an example written in Swift3 that animates a sequence of files.
Could someone show me the way?
thanks.

A: The simplest way I think is to make a timer
Timer.scheduledTimer(timeInterval: InitImage.animationDuration * Double(InitImage.animationImages?.count ?? 0), target: self, selector: #selector(push), userInfo: nil, repeats: false)

and selector
func push() {
.... perform segue
}

A: The simplest option is to use performSelector with afterDelay, since the self is an @objc UIViewController:
self.perform(#selector(segueToDetailViewController), with: self, afterDelay: InitImage.animationDuration)

And selector:
func segueToDetailViewController() {
    self.performSegue( ... etc ... )
}

The code above is not multiplying the animation duration by the number of images because when I ran the code, I found that the animation duration for all images was 2.5 seconds.


text:
Q: jquery menus not appearing in front of wrap with back color containing a div with background image The problem that I am facing, is that the circular menus using jquery, after opening I can't see all of the choices in the scree, I've got two menus, the first appears on top of the wrap, and the other appear below the first menu.
What a I'm trying to do is, when I do mousehover to the first menu, I want to view all the choices, and the wrap element stretches to englobe all the choices, I need a scrollbar to appear so I can move up a see the choices.
Here is the code.
default.css
.socials {
display:block;
width:32px;
height:32px;
background:url(../img/socials/share.png) no-repeat;
cursor:pointer;
position:relative;
}

.nature {
display:block;
width:150px;
height:150px;
background:url(../img/nature/img1.png) no-repeat;
cursor:pointer;
position:relative;

}

.socials, .nature {
margin:0 auto;
}

.socials {
margin-bottom:50px;
}

ul.reset,
ul.reset li {
display:block;
list-style:none;
padding:0;
margin:0;

}

ul.reset li {
position:absolute;
}

ul.reset li a {
outline:none;
}

#content {
margin:100px auto 0;
width:560px;
}

a {
color:#fff;
}

a img {
border:none;
}

the style.css
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {
border: 0 none;
font-family: inherit;
font-size: 100%;
font-style: inherit;
font-weight: inherit;
margin: 0;
outline: 0 none;
padding: 0;
vertical-align: baseline;
}
body {
background-color: #000000;

}
 #wrap {
background-color:#FECC80;
margin:25px auto;
width: 940px;
min-height:560px;

 }
.centered {
 margin:25px auto;
width: 940px;
min-height:560px;
background:url("../Images/logo.png") no-repeat center center;

 position:fixed;
 }

/*menu em cima*/
nav {width: 100%;
position:fixed;
list-style: none;
padding: 0;
margin: 0;
top:0;

 }

    nav ul {
        list-style: none;
        margin:0;
        padding:0;
        display: table;

        width: 100%;
    }
    nav li {
        z-index:10;
        text-align: center;
        display: table-cell;
               width: 120px
    }
    nav a {
             opacity: 0.5;
   filter: alpha(opacity=50);
        color: #fff;
        text-decoration: none;
        padding: 5px 10px ;
        height: 30px;
        line-height: 20px;
        display: block;
        text-align: center;
        background: #D98134;
        border-right:1px solid white;

    }

    nav  a:hover {
          opacity:1;
 filter: alpha(opacity=100);
background-color: #D98134;
}

 /*menu de baixo*/

 nav2 {width: 100%;
position:fixed;
list-style: none;
padding: 0;
margin: 0;
bottom:0;

}

    nav2 ul {
        list-style: none;
        margin:0;
        padding:0;
        display: table;

        width: 100%;
    }
    nav2 li {
        z-index:10;
        text-align: center;
        display: table-cell;
               width: 120px
    }
    nav2 a {
             opacity: 0.5;
  filter: alpha(opacity=50);
        color: #fff;
        text-decoration: none;
        padding: 5px 10px ;
        height: 30px;
        line-height: 20px;
        display: block;
        text-align: center;
        background: #D98134;
        border-right:1px solid white;

    }

    nav2  a:hover {
          opacity:1;
 filter: alpha(opacity=100);
background-color: #D98134;
}

And here goes the part  from  produtos.php
 where i have the problems

You can view the site working in
http://ocafe.pt/Teste/produtos.php and view in first hand the problem.

A: I have been playing with some ideas:
for starters, your fixed attribute on the .centered div is mucking you around big time.
Here is a possible solution at: http://jsfiddle.net/webwarrior/LSn6F/34/
Changed some css, and added some elements:

CSS:
#wrap2 {
    background-color:#FECC80;
    margin:25px auto;
    width: 940px;
    min-height:560px;
    position: absolute;
    top: 20px;
    left: 50%;
    margin-left: -25%;
}
#wrap {
    background-color:#FECC80;
    margin:25px auto;
    width: 940px;
    min-height:560px;
    position: absolute;
    top: 200px;
    left: 50%;
    margin-left: -25%;
    overflow: visible;
}
.centered {
    margin:25px auto;
    width: 940px;
    min-height:560px;
    background:url("http://ocafe.pt/Images/logo.png") no-repeat center center;
    overflow: auto;
    position: absolute;
    position: absolute;
    top: -25%;
    left: 0%;

}

hth
we will get there after a bit of fiddling...


text:
Q: Dynamic combo box list issue Using switch case i wanted to add different list to combobox,when i compile i dont see any error. The following is my code, can any one please suggest what could be the reason for not updating combobox list ??
public void comboboxlist(Composite parent,String fruit) {
    Combo combobox = new Combo(parent,SWT.NONE | SWT.DROP_DOWN | SWT.READ_ONLY);
    switch(fruit) {
        case "apple":
            combobox.setItems(new String[]{"Red","green"});
            combobox.addModifyListener( new ModifyListener() {
                public void modifyText(final ModifyEvent e) {
                }
            });
            break;
        case "mango":
            combobox.setItems(new String[]{"Yellow","green"});
            combobox.addModifyListener( new ModifyListener() {
                public void modifyText(final ModifyEvent e) {
                }
            });
            break;
            default : break;
    }
}

A: The most plausible explanation for me would be that your fruit is neither "apple" nor "mango". Have you checked that?


text:
Q: Use props inside emotion's css string template I'm in the middle of migrating my design system from styled-components to emotion.
In SC, The following syntax is considered valid:
export interface AvatarProps {
  // ...
  shape: AvatarShape;
  size: AvatarSize;
}

const borderRadiusByShape = css<Pick<AvatarProps, "shape" | "size">>`
  border-radius: ${(props) => {
    return match(props.shape)
      .with("circle", () => `${props.size}px`)
      .with("square", () => "0px")
      ...
      .exhaustive();
  }}
`;

const StyledAvatar = styled.div<AvatarProps>`
  /* ... */
  ${borderRadiusByShape};
`;

This pattern allows me to reuse my borderRadius across multiple styled.[x] declarations.
Looking at emotion's css function, it looks like emotion doesn't support that syntax. Is there any workaround that won't require me to wrap this functionality with a new component?

A: Afer a bit of digging, it turns out I can extract the props from css and create a function that accept these props and return the corresponding CSS:
export interface AvatarProps {
  // ...
  shape: AvatarShape;
  size: AvatarSize;
}

const borderRadiusByShape = (props: Pick<AvatarProps, "shape" | "size">) => css`
  border-radius: ${match(props.shape)
    .with("circle", () => `${props.size}px`)
    .with("square", () => "0px")
    /* ... */
    .exhaustive()};
`;

const StyledAvatar = styled.div<AvatarProps>`
  /* ... */
  ${borderRadiusByShape};
`;


text:
Q: JxBrowser related I am trying to create a browser app with JxBrowser. I have imported all the jar files in my project but it still throws an error for the statement
import com.teamdev.jxbrowser.chromium.BrowserContext;

and further on for
Browser browser = BrowserFactory.createBrowser(BrowserType.Mozilla);

frame.add(browser.getComponent(), BorderLayout.CENTER);

browser.navigate("http://www.google.com");

I am running this code on a MAC OS X and have the appropriate jar file imported as well.
Can someone help me with this

A: I suppose you use one of the latest JxBrowser versions. Probably 4.x. In this case please note that public API in 4.x has been changed. Now, to create Browser instance you need to use the following way:
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

import javax.swing.*;
import java.awt.*;

/**
 * This sample demonstrates how to create Browser instance,
 * embed it into Swing BrowserView container, display it in JFrame and
 * navigate to the "www.google.com" web site.
 */
public class BrowserSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.loadURL("http://www.google.com");
    }
}


text:
Q: Friendly warning when page doesn't exist I'm building an offline version of one of our websites using phonegap. It's working fine, however there may be a time when I miss one of the links that's in the static html, and if clicked accidentally the app will fall over.
Is there a 'catch' for this, or something so i can pop up a message box saying something like "This is only a demo version, this link is disabled"
Thanks a lot for any help!
Tom

A: Just check if the page exists by an ajax request
$.ajax({
    url:'http://www.example.com/somefile.ext or relative path',
    type:'HEAD',
    error: function()
    {
        //file not exists
    },
    success: function()
    {
        //file exists
    }
});

A: You can add an event handler on click, check if the page exists, if not call event.preventDefault (go to the page) & stopPropagation
$('.classLink').on('click', function (event) {

            event.preventDefault();
            event.stopPropagation();
});

You can use return false to achieve the same result. From http://api.jquery.com/on/:

Returning false from an event handler will automatically call
  event.stopPropagation() and event.preventDefault(). A false value can
  also be passed for the handler as a shorthand for function(){ return
  false; }. So, $("a.disabled").on("click", false); attaches an event
  handler to all links with class "disabled" that prevents them from
  being followed when they are clicked and also stops the event from
  bubbling.


text:
Q: Ruby-On-Rails model level class array I'm trying to think of a best solution for following scenario. I've a model called an 'Article' with an integer field called 'status'. I want to provide class level array of statuses as shown below,
 class Article < ActiveRecord::Base
 STATUSES = %w(in_draft published canceled)

 validates :status, presence: true
 validates_inclusion_of :status, :in => STATUSES

  def status_name
    STATUSES[status]
  end

  # Status Finders

  def self.all_in_draft
    where(:status => "in_draft")
  end

  def self.all_published
    where(:status => "published")
  end

  def self.all_canceled
    where(:status => "canceled")
  end

  # Status Accessors

  def in_draft?
    status == "in_draft"
  end

  def published?
    status == "published"
  end

  def canceled?
    status == "canceled"
  end

end

So my question is if this is the best way to achieve without having a model to store statuses? And secondly how to use these methods in ArticlesController and corresponding views? I'm struggling to understand the use of these methods. To be specific, how to do following?
article = Article.new
article.status = ????
article.save!

or
<% if article.in_draft? %>

<% end %>

I greatly appreciate any sample code example.  I'm using rails 4.0.0 (not 4.1.0 which has enum support).

A: You could define all the methods using define_method, and use a hash instead of an array:
STATUSES = {:in_draft => 1, :published => 2, :cancelled => 3}

# Use the values of the hash, to validate inclusion
validates_inclusion_of :status, :in => STATUSES.values

STATUSES.each do |method, val|
  define_method("all_#{method)") do
    where(:status => method.to_s)
  end

  define_method("#{method}?") do
    self.status == val
  end
end

In that way, you can add statuses in the future without needing to create the methods manually. Then you can do something like:
article = Article.new
article.status = Article::STATUSES[:published]
...

article.published? # => true


text:
Q: Allow connection only over HTTPS in Xamarin.Android Was trying to disable any HTTP connections in my Xamarin app.
I set flag in AndroidManifest.xml to disable clear text
android:usesCleartextTraffic="false"

Enabled TLS in "Android options" in my project. But I can still make calls to unsecured websites like
http://neverssl.com/
How can I achieve it?


text:
Q: MySQL EXPLAIN type:ALL problem I have the following tables:
CREATE TABLE `categories` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `path` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '/',
 PRIMARY KEY (`id`),
 UNIQUE KEY `path` (`path`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `items` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `category_id` int(11) NOT NULL DEFAULT '1',
 `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'no name',
 PRIMARY KEY (`id`),
 KEY `category_id` (`category_id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

And the query is matter:
SELECT c.path, i.name
FROM categories c
JOIN items i ON i.category_id = c.id
WHERE c.path LIKE CONCAT( (
 SELECT path
 FROM categories ci
 WHERE ci.id =2
),  '/%' )
OR c.id =2
mysql> EXPLAIN SELECT c.path, i.name FROM categories c JOIN items i ON i.category_id = c.id WHERE c.path LIKE CONCAT( (  SELECT path FROM categories ci WHERE ci.id =2 ),  '/%' )  OR c.id =2
   -> ;
        +----+-------------+-------+--------+---------------+---------+---------+--------------------+------+-------------+
        | id | select_type | table | type   | possible_keys | key     | key_len | ref                | rows | Extra       |
        +----+-------------+-------+--------+---------------+---------+---------+--------------------+------+-------------+
        |  1 | PRIMARY     | i     | ALL    | category_id   | NULL    | NULL    | NULL               |    8 |             |
        |  1 | PRIMARY     | c     | eq_ref | PRIMARY,path  | PRIMARY | 4       | tree.i.category_id |    1 | Using where |
        |  2 | SUBQUERY    | ci    | const  | PRIMARY       | PRIMARY | 4       |                    |    1 |             |
        +----+-------------+-------+--------+---------------+---------+---------+--------------------+------+-------------+

The 'category_id''s type is ALL;
How to not use type ALL?
Do you have best solutions?
Addition:
 I tried on InnoDB
mysql> EXPLAIN SELECT c.path, i.name FROM categories c JOIN items i ON i.category_id = c.id WHERE c.path LIKE CONCAT( (  SELECT path FROM categories ci WHERE ci.id =2 ),  '/%' )  OR c.id =2;
+----+-------------+-------+-------+---------------+-------------+---------+-----------+------+--------------------------+
| id | select_type | table | type  | possible_keys | key         | key_len | ref       | rows | Extra                    |
+----+-------------+-------+-------+---------------+-------------+---------+-----------+------+--------------------------+
|  1 | PRIMARY     | c     | index | PRIMARY,path  | path        | 767     | NULL      |    7 | Using where; Using index |
|  1 | PRIMARY     | i     | ref   | category_id   | category_id | 4       | tree.c.id |    1 |                          |
|  2 | SUBQUERY    | ci    | const | PRIMARY       | PRIMARY     | 4       |           |    1 |                          |
+----+-------------+-------+-------+---------------+-------------+---------+-----------+------+--------------------------+

A: try
 create index idx_id_path on categories(id, path)

(path, id) may or may not work better
often, mysql only uses one index per table, so having additional columns in the index, may allow it to be used better if the index has the right columns, in the right order, for that specific query.


text:
Q: Social networks and genetic algorithms in R I am trying to implement a network core-periphery measure from an article (link: Borgatti & Everett 2000) in R. The basic approach applied by the authors is to:

*

*Arrange the rows and columns of the network matrix so that actors that are well connected to each other occupy the top left corner.

*Create an ideal pattern matrix based on the row/column arrangement in step 1

*Assess the correlation between the two matrices
According to the authors the trick in step one is to find the row/column arrangement of the matrix that correlates the highest with its induced pattern matrix, and they recommend using a genetic algorithm to find the best row/column arrangement. I am stuck at the first steps of the algorithm:

*

*How do I in R create random row/column matrix arrangements that preserve the order of the column/row entries?

*Once I have assessed the fit between the matrix arrangements and the patterns matrices, how do I "breed" new matrix arrangements based on the "fittest" matrices?
Thanks.

A: Given a matrix of a particular size, you can generate random row/column matrix arrangements as such
#create fake data
mydata.block1 <- matrix (rep(1, times=100), ncol=10)
mydata.block2 <- matrix (rep(0, times=900), ncol=90)
mydata.block3 <- matrix (rep(0, times=900), ncol=10)
mydata.block4 <- matrix (rep(1, times=8100), ncol=90)

mydata <- rbind(cbind (mydata.block1, mydata.block2), cbind (mydata.block3, mydata.block4))

#Mix mydata
mix.order <- sample(1:dim (mydata)[1])
mydata <- mydata[mix.order,mix.order]

#create 100 random orderings

##preallocate matrix
rand.samp <- matrix (rep(NA, times=10000), ncol=100)
##create orderings
for (i in 1:100){
rand.samp[i,] <- sample(1:dim (mydata)[1])
}
##Eliminate duplicate orderings (unlikely to occur)
rand.samp <- unique (rand.samp)

#Reorder and measure fitness
##preallocate fitness measure
fit.meas <- rep (NA, times=100)

for (i in 1:100){
mydata.reordered <- mydata[rand.samp[i,],rand.samp[i,]]
fit.meas[i] <- myfitnessfunc(mydata.reordered)
}

After you have measured fitness, you will need some way to determine which areas are contributing to the fitness and fix those while altering other areas ("breed").  Perhaps dist() will be of some use.  Maybe a heatmap or clustering, hclust(), would also be of use?  Can you provide more detail on how you would determine localized fitness?

A: OneWhoIsUnnamed response is the same as I interpreted your need for #1.
Here's a fitness based recombination method for two adjacency matrices, #2:
Say you have two matrices, A and B, who have fitness cores Fa and Fb of 2.3 and 1.1, respectively.  Breed the matrices by constructing a new matrix, C, where C_{i} = A_{i} with probability Fa/(Fa+Fb) or C_{i} = B_{i} with probability 1-Fa/(Fa+Fb).  This is just one of unlimited ways of breeding matrices.  M is the mated result of A and B based on their fitness.
# lets define a function to create random adjacency matrices
random_adjacent <- function(dimension)
{
    ret  <- matrix(runif(dimension^2)>0.5,dimension,dimension)
    retl <- ret * lower.tri(ret)
    return( retl + t(retl) )
}
# set fitness
Fa <- 2.3
Fb <- 1.1
# initialize matrices
A  <- random_adjacent(4)
B  <- random_adjacent(4)
# compute symmetric fitness probability matrix
C  <- matrix(runif(16)<Fa/(Fa+Fb),4,4)
Cl <- C * lower.tri(C) # take the lower triangular portion
C  <- Cl + t(Cl)       # reflect the lower triangular portion into the upper
# compute mated result
M  <- matrix(0,4,4)
M[C]  <- A[C]
M[!C] <- B[!C]


text:
Q: Intersection of a cone and a plane. I need a proof that the intersection of a cone with a plane parallel to the cone's axis is a hyperbola.

A: Cone equation: $x^2+y^2 = z^2 \hspace{3mm}$    (1)
Plane equation parallel to the cone's axis: $ax+by = c \hspace{3mm} $  (2)
If you isolate the variable $y$ in equation (2) and substitute in (1), you will find a equation in the form
$$\frac{z^2}{d_z^2} -\frac{(x-x_0)^2}{d_x^2} = 1,$$ where $x_{0}, d_x$ and $ d_y$ are constants.
Remark 1: if $b=0$, isolate $x$ and you have a similar result.
Remark 2: For simplicity, I have considered  the vertex of the cone in $(0,0,0)$. The general case is just a translation/rotation.

A: Define the cone as points $(x,y,z)$ on the surface defined by the equation
$$
z^2=x^2+y^2
$$
and make the cut $y=\sqrt k$. Then
$$
z^2-x^2=k
$$
If the plane is not of the form $y=\sqrt k$ we can always rotate the situation around the cone's axis (using the symmetry of the cone) to obtain such a situation.

Comparing $z^2-x^2=k$ to the $y=\frac{a}{x}$ version of a hyperbola, one can make a change of coordinates:
We can rotate $(x,z)$ in the $xz$-coordinate system by an angle of $45$ degrees clockwise to obtain $(x',z')=\frac{\sqrt 2}{2}(x+z,-x+z)$. This will make $(x',z')$ describe the same curve as $(x,z)$, but with the axis of symmetry rotated from the $z$-axis to the line $x'=z'$:

Considering the inverse rotation we see that $(x,z)=\frac{\sqrt 2}{2}(x'-z',x'+z')$. So with this the equation $z^2-x^2=k$ becomes
$$
\left(\tfrac{\sqrt 2}2(x'+z')\right)^2-\left(\tfrac{\sqrt 2}2(x'-z')\right)^2=k
$$
and since $\left(\frac{\sqrt2}2\right)^2=\frac{1}{2}$ and $(x'+z')^2-(x'-z')^2=4x'z'$ it follows that
$$
2x'z'=k\iff z'=\frac{0.5k}{x'}
$$
which is an equation of the form $y=\frac{a}{x}$. The figure above shows as an example how $z^2-x^2=4$ transforms into $z'=\frac{2}{x'}$ after being rotated 45 degrees.


text:
Q: Twilio & NodeJS: can't find and delete Media instances/resources I'm using Twilio's NodeJS module & API to send out MMS messages with images attached (from a remote URL), and I want to delete the Media instances that get created on Twilio servers as soon as I send out the messages.
My messages send out correctly, and in the callback, I'm trying to 1) list media instances for the current message, then 2) loop through those instances and delete. The problem is that the mediaList array that comes back from the API for a current message is always empty.
Here's my code:
twilio_client.messages.create({
    body: "Thanks for taking a photo. Here it is!",
    to: req.query.From,
    from: TWILIO_SHORTCODE,
    mediaUrl: photo_URL,
    statusCallback: STATUS_CALLBACK_URL
    }, function(error, message) {
        if (!error) {

            twilio_client.messages(message.sid).media.list(function(err, data) {
                console.log(data);
                // The correct object comes back as 'data' here per the API
                // but the mediaList array is empty
            }

            console.log('Message sent via Twilio.');
            res.status(200).send('');
        } else {
            console.log('Could not send message via Twilio: ');
            console.log(error);
            res.status(500).send('');
        }
});

A: So, it turns out that trying to get the media list at the point I was trying to doesn't work because the media instances didn't exist yet.
I have a separate little app running at the statusCallback (I supply a URL via a constant in the code above, STATUS_CALLBACK_URL), that until now, just checked to see if a message I tried to MMS to a user wasn't handled properly by Twilio, and alerted the user to a problem via SMS. So, I added a check in that same app to see if the message was actually 'sent' to the user, and then checked for and deleted the media instance(s) associated with the message at that point, and it works fine. Here's my code:
// issue message to user if there's a problem with Twilio getting the photo
if (req.body.SmsStatus === 'undelivered' || req.body.SmsStatus === 'failed') {
    twilio_client.messages.create({
    body: "We're sorry, but we couldn't process your photo. Please try again.",
    to: req.body.To,
    from: TWILIO_SHORTCODE
    }, function(error, message) {
        if (!error) {
            console.log('Processing error message sent via Twilio.');
            res.send(200,'');
        } else {
            console.log('Could not send processing error message via Twilio: ' + error);
            res.send(500);
        }
    });
}

// delete media instance from Twilio servers
if (req.body.SmsStatus === 'sent') {
    twilio_client.messages(req.body.MessageSid).media.list(function(err, data) {
        if (data.media_list.length > 0) {
            data.media_list.forEach(function(mediaElement) {
              twilio_client.media(mediaElement.sid).delete;
              console.log("Twilio media instance deleted");
            });
        }
    });
}


text:
Q: How can I get my LAN IP address using Java I want to get my LAN IP address. But I it shows Localhost address using this code.
public static void main(String[] args)
{
try
{
    InetAddress add=InetAddress.getLocalHost();
    System.out.println("Local IP: " + add.getHostAddress());
}
catch(Exception ex)
{
    System.out.println(ex.getMessage());
}
}

It shows IP is : 127.0.1.1 .
But my LAN ip address is 10.107.46.88

A: The easiest way I know is to use NetworkInterface.getNetworkInterfaces() and the linked Javadoc notes that you can use getNetworkInterfaces()+getInetAddresses() to obtain all IP addresses for this node. That might look something like
try {
    Enumeration<NetworkInterface> nics = NetworkInterface
            .getNetworkInterfaces();
    while (nics.hasMoreElements()) {
        NetworkInterface nic = nics.nextElement();
        Enumeration<InetAddress> addrs = nic.getInetAddresses();
        while (addrs.hasMoreElements()) {
            InetAddress addr = addrs.nextElement();
            System.out.printf("%s %s%n", nic.getName(),
                    addr.getHostAddress());
        }
    }
} catch (SocketException e) {
    e.printStackTrace();
}

and I get (for my network)
wlan0 192.168.2.9
lo 127.0.0.1

if you don't want to display loop-back you can test the NetworkInterface with isLoopback().
while (nics.hasMoreElements()) {
    NetworkInterface nic = nics.nextElement();
    if (!nic.isLoopback()) {
        // ... as before
    }
}


text:
Q: IIS7: How do I allow one site to bind to port 443 and prevent binding on other sites We have a Win 2008 server running IIS7. The webserver runs several sites, one of which requires SSL for its e-commerce / data-capture components:

*

*www.domainA.com :80 & 443

*www.domainB.com :80

*www.domainC.com :80

*www.domainD.com :80

I have installed a certificate for domainA and added an HTTPS/443 binding for the www.domainA.com website. However, if I try to access https://www.domainB.com, I am shown the content from the domainA site.
How can I prevent all sites using the 443 binding from domainA? When I add the certificate to the binding, I am unable to set the hostname. If I use appcmd to set a hostname, the site gets 2 bindings and access via SSL doesn't work.
Only domainA should allow access on port 443 and other sites should refuse the connection.
Thanks
James

A: SSL starts connection BEFORE any HTTP header is sent - so clearly the server has now way of distinguishing what domain this connection is for until SSL connection is established.
Your binding is correct - the other sites are NOT bound to port 443... but by the time the SSL connection is established and the first HTTP header is sent it is already on the IP address (the name has been resolved via DNS).
As to a solution:
To circumvent what you see you need to bind domainA.com to a different IP address than the rest (and modify DNS accordingly).


text:
Q: Not able to access node server on heroku I have a very basic node.js based http server that I want to use as a proxy. I setup the hostname and port in my system wide proxy settings for all http requests to make sure all the http requests go to this server.
The problem is - When I run the server locally, using foreman start and set localhost as hostname and 5000 as port, all my http requests are captured by this server. But when I deploy to Heroku, and using that host name and their port my page doesn't load.
Here is the code for the http server
var my_http = require("http");

var url = require('url');
var port = Number(process.env.PORT || 8080);

my_http.createServer(function(request, response) {
    var url_parts = url.parse(request.url, true);

    response.writeHeader(200, {
        "Content-Type": "text/plain"
    });
    response.write(request.method + ": " + port + ': ' + url_parts.href);
    response.end();
}).listen(port);

console.log("Server Running on " + port);

Note
Foreman runs the application on port 5000 locally and runs on port 23536 on heroku.
My understanding of the problem
We have a website traffic filter in the company that doesn't allow us to access most of the websites, directly. You need to click on a link (saying continue) every time you access a them. My understanding is that since I am trying to access those blocked websites, they are getting blocked or something (Though the request is proxied)?


text:
Q: Mobile browser - Say smartphones to take 480px The iPhone and other smartphone render a virtual window with of 320px. To work with this I used the meta-tag viewport:
<meta name="viewport" content="width=device-width">

The only problem is that my designer wants every smartphone to take 480px to render. Thus I tried width=480px, but I don't want tablets involved. Only smartphones should take this width of 480px. Is there a professional way to solve this problem (without PHP or JavaScript)?


text:
Q: Select table row using HQL with param I want to use this HQL query in order to select table row value:
String hql = "select e.token, e.name from Terminals e where e.token = ?";
Terminals terminal = entityManager
    .createQuery(hql, Terminals.class)
    .setParameter(0, terminalToken)
    .getSingleResult();

But I get this result:
java.lang.IllegalArgumentException: Cannot create TypedQuery for query with more than one return using requested result type [org.api.entity.Terminals]

What is the proper way to implement this?

A: Your query return two Objects token and name and not a Terminals Object.
Instead you can use :
Object[] obj = entityManager
    .createQuery(hql)
    .setParameter(0, terminalToken)
    .getSingleResult();

if(obj != null){
    Terminals terminal = new Terminals((String) obj[0], (String) obj[1]);
}

Or you can create a constructor in Terminals class which hold two fields :
public Terminals(String token, String name){
   this.token = token;
   this.name = name;
}

then change your code to be :
String hql = "select new com.package.Terminals(e.token, e.name) from Terminals e where e.token = ?";
Terminals terminal = entityManager
    .createQuery(hql, Terminals.class)
    .setParameter(0, terminalToken)
    .getSingleResult();

A: IMO, you should not directly call createQuery to assign to a custom object. And there is a possiblity of returning a list.
Query query = entityManager.createQuery(hql).setParameter(0, "something");<br>
List<Object[]> terminals = query.getResultList();

and retrieve the objects with an index as the ff as an example:
        StudentDto dto = new StudentDto();
        for(Object[] a: std) {
            dto = new StudentDto();
            dto.setId((long) a[0]); //id
            dto.setName(a[1].toString()); //first name
            dto.setPassportNumber(a[2].toString()); //last name
        }


text:
Q: (WPF DataGrid) How to copy Datagrid header text with a context menu? I'm using WPF  DataGrid.
I added a context menu to the column header, but i don't know how can I copy the header text in a menu item click event.
I try to use DataGrid.CurrentColumn but it is null
Thanks a lot !

A: try to get columns header by get it using the selected cells:
foreach (var item in e.SelectedCells)
{
    DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromItem(item.Item);
    var col = item.Column as DataGridColumn;
    MessageBox.Show("" + col.Header);
}

EDIT
if you want to get the column header that you are currently on add the following codes:
in resource put this:
<ContextMenu x:Key="cm">
            <MenuItem Header="Click"
                                  Click="mi_Click"
                                  CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Parent}" />
        </ContextMenu>

then add column header style like this:
<Style TargetType="{x:Type DataGridColumnHeader}">
            <Setter Property="ContextMenu" Value="{StaticResource cm}"></Setter>
</Style>

and put code behind like this:
private void mi_Click(object sender, RoutedEventArgs e)
{
    MenuItem mi = sender as MenuItem;
    if (mi != null)
    {
        ContextMenu cm = mi.CommandParameter as ContextMenu;
        if (cm != null)
        {
            var ch = cm.PlacementTarget as System.Windows.Controls.Primitives.DataGridColumnHeader;
            if (ch != null)
            {
                MessageBox.Show(ch.Content.ToString());
            }
        }
    }
}


text:
Q: Disappointing response from a moderator I have down-voted an answer and left a comment asking the user to add more details to his answer. I always tend to leave a comment when I down-vote a question/answer to explain the reason of my action.

This happened many times and it started to be annoying. It's not about reputation, it's about down-voting an accepted correct answer without a reason. I also left a comment notifying the user that revenge isn't a good behavior, but I got no response from him.
I flagged the answer and explained to moderator asking for intervention. I got an answer after eight days and it was disappointing unfortunately.
All I'm asking is such users should be warned for behaving in a such way.

Down-voting:

A: I'm the one who declined your flag. As you noted in your screen shot, this is what your flag said:

Why whenever I downvote a bad answer I get a revenge? I've left a comment for why I've downvoted his answer, also, a comment notifying the user that "revenge" is a bad idea. I've been through the same many times and downvoters never leave a comment. Thank you in advance

Your big focus there seemed to be the phenomenon of getting 'revenge' down votes for leaving comments when down voting; that in fact was your question in your flag. My flag response was meant to answer your question. My flag decline was meant for the reasons Bill the Lizard notes in his answer

That said, I could have been a bit more clear and explained a bit better what I meant. Basically, what I said above probably should have been included.
Also, there is one particular word in my flag response that I think was just plain a mistake: "often". I should probably have said "at times".

A: I understand that this can be frustrating, but we're not going to be able to give someone a warning for one downvote for several reasons.

*

*Votes are anonymous (even to moderators), so we don't have any proof that it was this person who downvoted you.

*The warning would be empty. How could we enforce it? Votes are anonymous.

*How do we know that the downvote wasn't for some other (legitimate) reason?

If there's a pattern of many downvotes from a single user in a short period of time, they will be reversed automatically.  If we notice that a user engages in this type of behavior frequently we'll send them a warning.  If it continues we'll suspend them.


text:
Q: How do I consistently increase a counter cache column? Lets say I have a counter cache that needs to to be incremented on every page load. Say I have 10 web instances. How do I consistently increase a counter cache column?
Consistency is easy with one web instance. but with several instances running, A race conditions may occur.
Here is a quick explanation. Let's say my counter cache column is called foo_counts and its starting value is 0. If 2 web instance are loaded at the same time, both realize the count as 0. When it comes time to increase the count. They both increment the count from 0 to 1.
I looked at http://guides.rubyonrails.org/active_record_querying.html#locking-records-for-update
Any ideas would be greatly appreciated.

A: You could use update_counter:

increment_counter(counter_name, id)
Increment a number field by one, usually representing a count.

This does a direct UPDATE in SQL so Model.increment_counter(:c, 11) sends this SQL to the database:
update models set c = coalesce(c, 0) + 1 where id = 11

so you don't have to worry about race conditions. Let the database do its job.

A: Consider queueing the increments, and having workers do the actual incrementation in the background. You won't have completely up-to-the-millisecond data, but at least it will be accurate.


text:
Q: Faster way of redirecting all requests to sanic? I'm attempting to redirect all requests in sanic web server. So, for example, if someone went to localhost:5595/example/hi it would forward to a website. I know how to normally do that in sanic, but it would be to slow to redirect 100 urls. Is there any faster way of doing this?

A: I am not 100% sure if this is the answer you are looking for. But, if you are asking about making a super crude proxy server in Sanic to redirect all requests, something like this would do (see server1.py).
# server1.py
from sanic import Sanic
from sanic.response import redirect

app = Sanic("server1")

@app.route("/<path:path>")
async def proxy(request, path):
    return redirect(f"http://localhost:9992/{path}")

app.run(port=9991)

And so we have a place for traffic to go:
from sanic import Sanic
from sanic.response import text

app = Sanic("server1")

@app.route("/<foo>/<bar>")
async def endpoint(request, foo, bar):
    return text(f"Did you know {foo=} and {bar=}?")

app.run(port=9992)

Now, let's test it out:
$ curl localhost:9991/hello/world -Li
HTTP/1.1 302 Found
Location: http://localhost:9992/hello/world
content-length: 0
connection: keep-alive
content-type: text/html; charset=utf-8

HTTP/1.1 200 OK
content-length: 35
connection: keep-alive
content-type: text/plain; charset=utf-8

Did you know foo='hello' and bar='world'?


text:
Q: Why was 568a / 568b developed for structured cabling, why wasnt alphabetic order used ? Why was 568a / 568b developed and why didnt they just do it alphabetically eg blue, blue white, brown, brown white, green, green white, orange, orange white.
I understand that according to structured cabling standards you have to use 568a / 568b but the cable will still work what ever you do, as long as its the same on both ends (unless you intentionally want a cross over cable)

A: UTP cables used in the 586 standard inherited their colors from the 25 pair color code developed by AT&T for cabling used in telecommunication purposes.
The following table shows the combination of colors to be used for each pair

This gives us these combinations:

UTP cabling simply used the first four combinations of twisted pairs.
The order used in 586a is compatible with 1-pair and 2-pair Universal Service Order Codes (USOC) pinouts that are a requirement in federal contracts by the U.S. government.
Pair 1 connects to the center pins (4 and 5) of the connector. It gives compatibility with the first line of RJ11, RJ14, RJ25, and RJ61 connectors that all have the first pair in the center pins of these connectors.
The position of the other wires is because signal shielding would be optimized by alternating the "live" and "earthy" pins of each pair. However it isn't possible because the outermost pair would be too far to meet the electrical echo requirements of high-speed LAN protocols.  That's why only one pair is "untwisted" and used as a shielding for the central pair.


text:
Q: On the relationship between Borel sigma algebra generated by a space and its "soberified" space Suppose given a topological space $(X,\mathcal O_X)$. Then we know its soberification is defined as a tuple $(X^s,\mathcal O_{X^s})$, where

*

*The set $X^s$ is the set of all irreducible closed subset of $X$.

*For an open set $U$, define $U^s=\{A \in X^s \mid A \cap U \neq \emptyset\}$. Then the set of all open sets on $X^s$ is defined as:
$$\mathcal O_{X^s}= \{U^s \mid U\in \mathcal O_X\}.$$

Among other things, it is well-known that the two set of open sets are isomorphic, i.e., $\mathcal O_X \cong \mathcal O_{X^s}$. Here, by isomorphism, I mean there is a bijection between the sets of open sets.
Now my question is: do we have any relationship with the Borel sigma-algebras generated by the two sets of open sets? For instance, is it true that $\sigma(\mathcal O_X) \cong \sigma(\mathcal O_{X^s})$? Here, $\sigma(\mathcal O_X)$ is the smallest sigma-algebra generated by the collection $\mathcal O_X$.
Thank you.
PS: The above construction is detailed in the document http://stacks.math.columbia.edu/download/topology.pdf; see Lemma 8.14 on Page 10.


text:
Q: (Oracle)Getting 30 days before My goal is to get 30 days before.
The data are stored as varchar2 type, '20200630' and '20200613'.
The expected result is '20200531' and '20200514' for each.
I have simply subtracted 30 from my varchar2 '20200630' and '20200613' and
it shows result by casting, but the result are not expected such as '20200600','20200583' which are not form of date.
Could I know how to modify my code as below
WITH A AS
 (SELECT '20200630' YEARMONTHDAY  FROM DUAL
  UNION ALL
  SELECT '20200613' FROM DUAL)
SELECT YEARMONTHDAY - 30 FROM A;

A: Store your data using the appropriate type!  That is, use date rather than a string.
If you are stuck with data in this format, convert to date:
select to_date(yearmonthday, 'YYYYMMDD') - interval '30' day

I would not recommend converting the value back to a string.  Dates should be dates.


text:
Q: How to communicate a SWAG estimate I support a large enterprise software project which frequently receives enhancement requests from our customer. The customer will only pay for the work up front in fixed-price contracts.  We provide a SWAG estimate first, then provide a detailed estimate after they green light the SWAG. The detailed estimates are time consuming and we are only compensated for the estimation time when they sign off on the enhancement, so the SWAG estimate provides a level of protection for us.
We communicate our SWAG estimate as Small, Medium, Large, or Very Large, and we have communicated ranges associated with each of these values.  For example,
Small: < 5 days
Medium: 5 - 15 days
Large: 15 - 50 days
Very Large: > 50 days

Having put this into practice for a couple of years, I have some concerns:

*

*Sometimes the SWAG estimate is expected to be at the high end of a range.  This form of estimate can make it difficult to manage customer expectations, a 15 day effort is very different from a 50 day effort, and the customer can green light a SWAG under the optimistic assumption.

*If the customer approves of a SWAG estimate, we can feel obliged to cap our detailed estimate at the high range of the SWAG.  If we move up a range then there are usually additional billing discussions which are painful, slow, and lacking guarantees for compensation.

Are there any kind of standard practices, or tried and true methods for communicating SWAGs that can help us better manage customer expectations?
Is it better to use use ranges on a per case basis, rather than the fixed ranges that I have noted?  Should I switch to single number instead of a range?

A: I've been asked to estimate jobs in every conceivable way. I've seen estimates go wrong in many ways.
I can hit any deadline with a fuzzy enough scope of work.
So, presuming a scope of work with some meaningful acceptance tests in it I'll tell you the secret to generating the only meaningful time estimates I've ever encountered.
Imagine the work you've been asked to do is harder than anyone expected.  Imagine that it's already been however much time anyone thought it would take and it's still not done.  Now how much longer are you willing to waste time on it before you're sick of this and want to try doing anything else?
That process generates the most realistic time estimates I've ever seen. Has nothing at all to do with the poorly defined, not yet understood problem. It's all about how patient we are with getting the solution this way before we want to tear up the whole plan.
The only way I've ever improved on this was to prototype a solution before the job ever starts so I already know it will work. Some people work cookie cutter jobs that are the same thing over and over. That's pretty much the same as prototyping. Those kinds respond best to detailed specs. Mostly because those jobs are about not forgetting to do something.
For SWAG it's really about how people feel. The reality around the problem. Not the problem. The job ends when it's done or people get sick of waiting and try something else. We're really estimating our patience with the problem.
As for communicating a SWAG estimate you've already taken care of one of the biggest sources of misunderstandings. By expressing time durations as jobs that are small, medium, large, and very large you prevent the perception that you said it'd be done in exactly 50 days. Such numbers are always fuzzy. Customers shouldn't be led to think that they aren't.
However you communicate it, listen to your customer. Try to get a sense of how well you're being understood. What seems perfectly obvious to your might come as a complete surprise to them. This process has enough uncertainty in it without adding needless surprises.

Sometimes the SWAG estimate is expected to be at the high end of a range. This form of estimate can make it difficult to manage customer expectations, a 15 day effort is very different from a 50 day effort, and the customer can green light a SWAG under the optimistic assumption.

This is exactly why I explicitly tie a SWAG estimate to how people feel about the work. If the customer is obviously uncomfortable with the idea that a task could be a 50 day effort then don't give into the temptation to sell it as a 15 day effort without nailing down the scope of work to something that fits well within a 15 day effort. Never let how you feel about time get compressed without saying what will be lost by doing that.

If the customer approves of a SWAG estimate, we can feel obliged to cap our detailed estimate at the high range of the SWAG. If we move up a range then there are usually additional billing discussions which are painful, slow, and lacking guarantees for compensation.

Well you are obliged. In fact you are obliged to not wait to start the additional billing discussions. If after the first day on a 15 day job it becomes clear it's going to be a 40 day job you the report this then. Not after 15 days. If the customer says no the responsible thing to do isn't to go crazy trying to get done in 15 days. It's to be willing to walk away.
Personally, I like to give the customer the best understanding of progress as I can. When I'm working with a deadline I give daily updates about how likely  we feel it is that we'll meet the deadline.  When I'm working a checklist on estimated work I encourage evidence based scheduling. That is, to use velocity to take how closely we're matching our estimates and extrapolate our completion date. This can be recalculated after every milestone. It's good to see this recalculated often.
Doing that doesn't do a thing to make the work go faster but it gives those waiting on it the feeling that they understand what's going on. Managing those feelings is actually the most important thing if you want them to keep giving you work.

A: There's actually an old approach that addresses this kind of problem that comes from the PERT and CPM practices.  You might get resistance if you mention that since this is associated with waterfall and PMI.  But it really has nothing to do with waterfall and I haven't seen much evidence that certified project managers know anything about it (despite it being part of certification).
You come up with 2 or 3 estimates for each item.  You give a best-case scenario i.e. in lower bound i.e it will not get done faster than this.  Then you come up with a high-end estimate i.e. it should never take long than that.  Optionally, you provide a 'best-guess' estimate that falls somewhere in between.  This helps to weight the estimate towards the high or low end but it's not strictly needed.  You do this for each high-level deliverable.  Part of what people get wrong about this approach is they try to do it at an extremely fine-grained level.  That doesn't work / isn't worth the effort.
Then you lay out and dependencies and using a well-known algorithm, you can come up with an overall estimate with a confidence level for the entire bundle.  One thing that's good to understand that the more items you estimate this way, the more reliable the overall estimate as things tend to even out.
You could use this approach with t-shirt sizes for the component deliverables.  If the ranges are pretty reliable, then it should be fine.  Some people may try to tell you that this is incompatible with agile methodologies but that's really not the case.  It's simply a way to take a bunch of estimates and turn it into a composite one using well-studied statistical approaches.  Really good agile practitioners use statistical methods.  It's generally not something most of the team sees, however, and much of Agile has become simply a cargo-cult process.

A: Its an inherent problem with high level estimates. You're bound to make some assumptions as you haven't done deep dive analysis. Sometimes, you get punished for this assumptions as and when they turn out incorrect.
I would recommend creating S, SM, M, MH, H ranges as <5, 5-10, 10-15, 15-20, >20
AS part of conveying your TShirt size estimates, do highlight any high level assumptions so  sponsor is clear on implications.
For what its worth!

A: Usually when I'm communicating with someone about estimates, whether they are SWAGs or more detailed analysis estimates I'll try to express and emphasize the uncertainty in the estimate.
For example, you've talked about giving a range on the time a feature would take and I think that's good.  It shows that there is a range of times something could take.  However, I'm not sure I would always respond with those small, medium and large labels with those assigned time ranges.  There is a large difference between a project that will take 14 to 18 days and one that will take 40 to 50 days.  Yet they would both be classified as "large".  I think a better estimate would be giving those ranges outright.  If a client knew upfront that you thought a task would take 40-50 days, they shouldn't ever be so optimistic that they believe it'll get done in 15 days (and if they do, well, that's on them when they don't get what they expect).
I also tend to try to give people estimates with confidence metrics.  What that means is that I'll come up with a range of time for the estimate and express how confident I am that we could hit that estimate as a percentage, usually for different parts of the range.  So for example, say a client comes to me with a new feature they want.  And we'll say that this is a feature on a website that will involve some UI work and making some new database and API calls / endpoints.  So I might break that down like this:
Database work:
Create new sprocs for getting data - .5 days
Testing sprocs (correct returns, validating performance, etc) - .5 days + up to .5 days

API work:
Create new stubbed endpoint - .25 days
Create hook stubbed endpoint to DB and call sproc - .25 days
Test endpoint - .25 days + up to .5 days (for bug fixes)

UI work (we'll assume the front end is a mess and doing anything there is a nightmare of brittle, interdependent code):
Adding button to existing page for feature - .25 days
Making AJAX call to endpoint - 1 day
Fixing everything that has broken so far in the UI - .5 days + up to 1 day
Testing the UI / end to end tests - .25 days
Fixing more broken things the test uncovered - .5 days

So add all that up and I get 4.25 days + up to 2 days extra.  Then I add in some guesses based on how much variance I expect in my estimates (either high or low) and I might come up with a range like 3 - 8 days with an expected time of 5 days.  Then I would tell someone something like this:
Estimate (days)  Confidence
3                40%
5                80%
8                90%

And that might get told to the client like this:

So we've looked briefly into doing feature X for you.  We came up with
  an estimate of 3-8 days to do it.  We expect that it will most likely
  take about 5 days to do.  What all that means is that we are about 40%
  confident we could get it done in 3 days, 80% confident we could get
  it done in 5 and 90% confident we can get it done in 8 days.  This is
  just a preliminary guess that we made based on our experience with
  they system and similar features.  This is meant to be a guess only
  and should not be used as a guarantee that this feature will be done
  in any specific time frame.

I realize that some of that is a bit awkwardly worded, but I believe I've made the point here.  That point being that if you can communicate how certain or uncertain you are about something, it lets people make better choices about what you are telling them.  And being explicit about your uncertainty keeps others from making assumptions about that.
Compare the previous example to one like this:

We've done an analysis on feature Z.  There are a lot of unknowns here
  and we would be working in a delicate part of the system that has been
  known to cause problems if we aren't extremely careful.  We've
  estimated that this will take between 40 and 80 days (30% confident
  for 40 days, 50% confident for 70 days and 55% confident for 80 days).
  We think it might even take as long as 120 days.  We recommend doing
  more thorough requirements and planning to nail this down a bit more
  if you are still interested.

This might be enough for a client to say "nope, not worth it".  But it also prepares them for the idea that this isn't a quick fix and that more work is required to get a better estimate.

I'd recommend reading Software Estimation: Demystifying the Black Art by Steve McConnell.  There are a few chapters about how to communicate estimates to different people depending on what they need them for and how to get them to understand what you are trying to say.  (I'm not affiliated with this book in any way, I just like it.)

A: Hy,
my experience is that such high level estimations go terribly wrong and some boundaries should be established.

*

*Define until when is the customer willing to spend money. Every customer has a budget and wants a max out of it the problem begins when he has no clue what his needs are or his wishes are unrealistic. In you case this sounds like somebody tried something strange and now there is no trust.

*Define hard requirements and deliveries. In your case must everything be hard defined so you have to define milestones. Some caution is advised here. Every change request must be negotiated separately, every milestone has to be renegotiated and any change in a a milestone comes with a premium.

*One way how to solve the time estimation issue is to write to the estimation a certainty factor in percent, this factor would give a value how certain success is in the estimated time. Mostly this scares the hell out of the management.

*The next problem is resource allocation (developers, architects, etc.) and the order of task execution. Most problems arise when the customer identifies some feature that he needs tomorrow. That why a signed time table with milestones is key. It saves you alot of trouble.

If I come up with anything else I'l edit my post.


text:
Q: NSOperationQueue Pause & Resume? I implemented Thread pooling using NSOperationQueue. In which i set maxConcurrentOperationCount to 25. i.e. concurrently 25 threads are running at a time.
I am uploading chunks to a server by using this NSOperationQueue. So chunks are allocated to  the first 25 threads. After the NSOperationQueue is full, I want to pause the chunking reading part, then whenever threads from the queue complete, resume the chunking part to allocate new threads to NSOperationQueue to replace the thread which complete.
My Code:
NSOperationQueue *operationQueue = [NSOperationQueue new];
operationQueue.maxConcurrentOperationCount=5;

NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self                                                                         selector:@selector(upload:)                                                                            object:f_objChunkDetails->FileStream];

NSUInteger oprCnt=operationQueue.operationCount;

if(oprCnt >= 5) {
    // wait till queue has a free slot
} else {
    [operationQueue addOperation:operation];
}

So how to pause and resume is used in NSOperationQueue? How to implement ManualResetEvent in Objective-C?

A: Don't wait or pause. Instead, move your job creation (and check) into a new method. That method should loop to create jobs up to the available limit and then return. Each job that is created should have a completionBlock added which calls the job creation method.
In this way you are event triggered instead of blocking.
Generally, the completionBlock should change to the main thread before calling the job creation method.


text:
Q: JavaFX 8 FXML TextField (maybe other variables) are always null I am practicing a small chat box window and I try to make it so the user must enter a name into the textfield box (a username) but I been having problems and I am sure this will not be the first time. I keep getting nullpointerexception every time I try to use one of the variables, for right now, it is textfield. So I initialize it but then it is always blank string even when I type in a username.
app.java
public class app extends Application {

@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("FXMLApp.fxml"));

    Scene scene = new Scene(root);

    stage.setScene(scene);
    stage.show();
}

public static void main(String[] args) {
    launch();
}

}

FXMLApp.fxml (deleted what was not needed)
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" maxHeight="900.0" maxWidth="800.0" minHeight="300.0" minWidth="200.0" prefHeight="600.0" prefWidth="500.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="chatappclient.FXMLChatAppClientController">
    <children>
      <TextField fx:id="username" layoutX="176.0" layoutY="488.0" promptText="enter username" />
      <Button fx:id="login" layoutX="176.0" layoutY="519.0" mnemonicParsing="false" onAction="#login" text="Login" />
    </children>
</AnchorPane>

as you can see the login button calls
onAction="#login"

last file: FXMLAppController
    package chatappclient;

    import java.net.URL;
    import java.util.ResourceBundle;
    import javafx.application.Platform;
    import javafx.event.ActionEvent;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.control.TextArea;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.Pane;
    import javax.swing.JOptionPane;

    public class FXMLAppController implements Initializable
    {
        @FXML
        private Pane top_container;
        private Pane bottom_container;
        private TextField username ;
        private String name;
        private Button login;

        public FXMLChatAppClientController ()
        {
           // without this, I get nullpointerexception
            // with it, the textfield is always null
            username = new TextField();
        }

        @Override
        public void initialize(URL url, ResourceBundle rb)
        {}

        @FXML
        private void login()
        {
            // this returns empty string, if I did not initialize it, it would be an exception
            System.out.println("DEBUG: " + username.getText());
        }
    }

A: You need to annotate each of the fields defined in the FXML file with @FXML:
private Pane top_container;
private Pane bottom_container;
@FXML
private TextField username ;
private String name;
@FXML
private Button login;


text:
Q: CSS Grid column alignment I need to align columns to center, but with no luck. I tried justify-content, justify-items, align-items, but nothing works.
.row {
  display: grid;
  grid-template-columns: repeat(12,1fr);
  justify-content: center;
  align-items:center;
}

.col-2 {
  grid-column-start: span 2;
}

.col-4 {
  grid-column-start: span 4;
}

here is basic demo - https://jsfiddle.net/k0apdg5s/1/
EDIT:
What I really want to achieve is to align the last two cols to center in grid like this - http://jsfiddle.net/cez04sw4/2/

A: Again as an complete answer: Why are you using css grid like flex? That is not what it is meant for. Grid is an addition to flex, not an replacement.
The correct answer here is to use display: flex; instead of display: grid;. You can use grid around a flex-container or use justify-items or justify-self with items in the same area.
Here is a correct working example:

img {
  max-width: 100%;
  display: block;
}
.row {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items:center;
}

.col-2 {
  width: 16.66%; /* 100/6 */
}

.col-4 {
  width: 33.33%; /* 100/3 */
}


text:
Q: AndEngine ResolutionPolicy with GenyMotion I have the following code:
public static final int CAMERA_WIDTH = 1080;
public static final int CAMERA_HEIGHT = 1920;

public EngineOptions onCreateEngineOptions() {
        mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
        EngineOptions op = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED,
                new FillResolutionPolicy(), mCamera);
        return op;
    }

I am also adding a sprite of 256x256 dimensions.
But when I run this code on GenyMotion emulator with Samsung S5, I get the image stretched.
I also tried to use the RatioResolutionPolicy but it require that I switch the order of width/height in its arguments because of Landscape option, which I don't think it makes sense.
Any ideas why stretching is happening?
thanks


text:
Q: Idiom for a Shy Girl What do you tell a girl who shies away from expressing her feelings and avoids saying what you expect her to?

A: Wallflower

informal
  a person who has no one to dance with or who feels shy, awkward, or excluded  at a party.

A: Maybe also Buttoned-down

conservatively traditional or conventional; especially :  adhering to conventional norms in dress and behavior

A: Quiet as a mouse

(of a person or animal) extremely quiet or docile.

Wallflower

a shy or excluded person at a dance or party, especially a girl without a partner.

Shrinking violet/Modest violet

A person referred to as a shrinking violet is a timid or shy person.

Reserved

slow to reveal emotion or opinions.

Uncommunicative

unwilling to talk or impart information.

Source: Oxford Dictionaries
In a more general sense, you could use 'introvert', though this is not a specific term. Anyone who keeps things to himself and doesn't disclose his thoughts to many people is an 'introvert'.

A: The adjective Demure also describes a woman in this way:

(Of a woman or her behavior) reserved, modest, and shy: 'a demure little wife who sits at home minding the house'; see, Oxford Dictionaries

A: You could use
reticent

Not revealing one's thoughts or feelings readily:
she was extremely reticent about her personal affairs

Synonyms include:
Diffident

Modest or shy because of a lack of self-confidence:

Guarded

(of a person or a remark they make) careful; not showing feelings or giving much information

Taciturn

(Of a person) reserved or uncommunicative in speech; saying little:

(Oxford)


text:
Q: Additional Drivers page does not see my graphics card 16.04 I am using a fresh install of Ubuntu 16.04 with all of the updates installed. When I go to additional drivers it simply shows one option with "Unknown: unkown".
The model is a Thinkpad P50s, it is supposed to have a m500m, but when I run
lshw -C display

I receive this
 *-display UNCLAIMED
   description: 3D controller
   product: GM108GLM [Quadro K620M]
   vendor: NVIDIA Corporation
   physical id: 0
   bus info: pci@0000:06:00.0
   version: a2
   width: 64 bits
   clock: 33MHz
   capabilities: cap_list
   configuration: latency=0
   resources: memory:f1000000-f1ffffff memory:c0000000-cfffffff memory:d0000000-d1ffffff ioport:d000(size=128)

I'm unsure of what else to do. I had this problem before and used bumblebee, but I would just like to install the drivers and have the card work. It is my only gripe with Ubuntu.
How do I make the card show up in additional drivers?

A: After some time I found the proper way to do this online. This is the webpage, but I'll explain it here incase that link dies one day.
This will not show the card in the addition drivers page, and this bricked my machine the first time I did it. It bricked because I installed the wrong driver version the first time, so back up your data.
1) Check the PPA site for the latest nvidia driver here and check that your graphics card supports it (search the nvidia driver site for the supported cards.
check your card with the command:
sudo lshw -c display

2) I didn't need to do this, but remove all nvidia drivers with
sudo apt-get purge nvidia*

3) add the PPA and then update
sudo add-apt-repository ppa:graphics-drivers
sudo apt-get update

4) Install the driver! Replace the X with the driver number
sudo apt-get install nvidia-XXX

Reboot your computer.
Check if this is working with
lsmod | grep nvidia

if this returns nothing then the install failed, as the website indicates.
This is a problem that I had been trying to fix for months.
I downgraded all the way from Ubuntu 18 to 16 for this to work.

A: Follow the above answer's steps from step (1) to (3), add the PPA and update.
Then you can detect the model of your nvidia graphic card and the recommended driver, the command is:
ubuntu-drivers devices
Then you can install your prefer drivers
sudo apt install nvidia-XXX XXX is the version of the driver
or
if you trust the system, then you can install all recommended drivers:
sudo ubuntu-drivers autoinstall
Last step, reboot your machine.
The above solution is from linuxconfig.


text:
Q: Codeigniter - captcha for login is not working I made a captcha login it is working so far but there is two problem and that problem is that first, when your username or password is wrong the page went to blank. Second, when both of the username,password and captcha are wrong the page went blank
but when your username and password are correct and the captcha is wrong it will call the echo'captcha is not correct';
function aksi_login(){
        $data = array('username' => $this->input->post('username', TRUE),
                        'password' => md5($this->input->post('password', TRUE))
        );

        $this->load->model('m_model'); // load model_user
        $hasil = $this->m_model->cek_user($data);
        if ($hasil->num_rows() == 1 && $this->input->post('submit')){
            $inputCaptcha = $this->input->post('captcha');
            $sessCaptcha = $this->session->userdata('captchaCode');
            if($inputCaptcha === $sessCaptcha){
            foreach ($hasil->result() as $sess) {
                $sess_data['logged_in'] = 'Sudah Login';
                $sess_data['id_user'] = $sess->uid;
                $sess_data['username'] = $sess->username;
                $sess_data['level'] = $sess->level;
                $this->session->set_userdata($sess_data);
            }

            if ($this->session->userdata('level')=='1') {
                redirect('admin');
            }
            elseif ($this->session->userdata('level')=='2') {
                redirect('guru');
            }
            elseif ($this->session->userdata('level')=='3') {
                redirect('siswa');
            }

        else {
            echo'username or password is wrong'
        }
    }
    else{
                echo "captcha code is not correct";
            }
    }
}

I think so far is because of the controller code and i have made some changes I tried putting another elseif like
elseif ($this->session->userdata('username')== FALSE && $this->session->userdata('password')==FALSE){
echo'username or password is wrong';
}
else {
            echo'username or password is wrong';
    }

but unfortunately is not working

A: Its better to check for captcha first in a separate condition then check for validation, so if you got everything right and your post values are all ok then you should do it like this:
if (this->captcha_validation($this->input->post('captcha')))
{
    $this->form_validation->set_rules($this->rules);
    if ($this->form_validation->run() === TRUE)
    {
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        // your magic
    }
    else
    {
        // array of validation errors
        validation_errors = $this->form_validation->error_array();
    }
}
else
{
    // wrong captcha
    $this->recaptcha();
}

Now you have isolated the two checks and made it way easier for recaptcha, but more importantly you don't need to make form validation if the captcha is wrong in the first place.
...
Not sure how your code works but in // your magic up there put your logic like this:
$this->load->model('m_model'); // load model_user
$hasil = $this->m_model->cek_user($data);
if ($hasil->num_rows() > 0)
{
    foreach ($hasil->result() as $sess)
    {
        $sess_data['logged_in'] = 'Sudah Login';
        $sess_data['id_user'] = $sess->uid;
        $sess_data['username'] = $sess->username;
        $sess_data['level'] = $sess->level;
        $this->session->set_userdata($sess_data);
    }
    if ($this->session->userdata('level') == '1')
    {
        redirect('admin');
    }
    elseif ($this->session->userdata('level') == '2')
    {
        redirect('guru');
    }
    elseif ($this->session->userdata('level')=='3')
    {
        redirect('siswa');
    }
}

A: My suggestion to to rewrite your controller and use Form Validation as it is also codeigniter standard library
Check the official documentation here
https://www.codeigniter.com/userguide3/libraries/form_validation.html
//your validation config should be something like this
public function login() {
  $form_rules = [
            [
                'field' => 'username',
                'label' => 'Username',
                'rules' => 'required',
            ],
            [
                'field' => 'password',
                'label' => 'Password',
                'rules' => 'required',
            ],
            [
                'field' => 'captcha',
                'label' => 'No HP',
                'rules' => 'rules' => 'required|callback_check_captcha'
            ],

  ];

  $this->form_validation->set_rules($this->form_rules);

  if ($this->form_validation->run() == TRUE) {
    //check username & password
    //if you're sure that username is unique, you can directly get 1 data with ->row()
    $check = $this->m_model->cek_user($data)->row();

    if($check) {
       switch($check->level) {
         case '1' :
           break;
         case '2' :
         ......
         ......
       }
    } else {
        //wrong username / password
    }

  } else {
    //show login form with view
  }

}

/*callback fro form validation*/
public function check_captcha($str) {
if(!empty($this->session->cap_word)) {
    $expiration = time() - $this->config->item('captcha_expiration');
    if($this->session->cap_time > $expiration) {
        if($this->session->cap_word == $str) {
            return TRUE;
        } else {
            $this->form_validation->set_message('check_captcha', 'Wrong captcha.');
            return FALSE;
        }

    } else {
        $this->form_validation->set_message('check_captcha', 'Session captcha expired.');
        return FALSE;
    }

} else {
    $this->form_validation->set_message('check_captcha', 'KWrong captcha.');
    return FALSE;
}
}


text:
Q: Passing variables through two of the same foreach loops I have a foreach loop at the beginning of my document that is pulling data from an array and settings some variables to use later on. Let's say for this example $foo has 10 arrays in it with keys of ID and Name.
foreach($foo as $bar) {
    $id = $bar['id'];
    $name = $bar['name'];
}

Then, what I'd like to do is, further along in my document where I actually want to display these results for each $bar, I'd like to do this.
foreach($foo as $bar) {
    // display all ids
    echo $id;
    // display all names
    echo $name;
}

But I am running into an issue.  When trying to display the IDs and Names in the second foreach loop, it's returning 10 cases of an ID, but the IDs are all the same, and it's the ID from the last array in $foo.
10, 10, 10, 10, 10, 10, 10, 10, 10, 10

If I echo out the $id and $name in the first foreach loop, I see all 10 different names and ids.
1,2,3,4,5,6,7,8,9,10

Can I not call a second foreach loop on the same array? How would I go about doing this without throwing everything into a single foreach loop? I'd like to keep it organized and have the variables near the top, while outputting everything later on in the document.

A: Although for this purpose you do not require two loops, but let's say you do, then your second loop should look like
foreach($foo as $bar) {
$id = $bar['id'];
$name = $bar['name'];
// display all ids
echo $id;
// display all names
echo $name;
}

Currently with every iteration you are assigning new values to your id and name variables and hence after the end of the loop you see the last ones.
Also just for the sake of argument if you need those two loops separately you could then create an array of values in first loop and use that in second loop. But again its a waste of resource, duplicating everything
$data=array();
foreach($foo as $bar) {
    $data[]["id"] = $bar['id'];
    $data[]["name"] = $bar['name'];
}

and then
foreach($data as $bar) {
$id = $bar['id'];
$name = $bar['name'];

echo $id;
echo $name;
}

But this is utterly needless

A: Do you mean you want to display all the ids, then all the names?
If so, you could use the following example.
First loop would be.
foreach ($foo as $bar) {
    $ids[] = $bar['id'];
    $names[] = $bar['name'];
}

Then instead of the second loop you could use.
echo explode($ids,",");
echo explode($names,",");


text:
Q: Templated move assignment operator deleted when there is a user defined move assignment operator I have a class with a copy constructor that is only enabled when a condition is satisfied, say for this example, when the type parameter is not a reference.  And a member that is neither movable nor copyable (say a mutex).
 For example (https://wandbox.org/permlink/hRx51Ht1klYjN7v5)
#include <iostream>
#include <tuple>
#include <mutex>

using std::cout;
using std::endl;

template <typename T>
class Something {
public:
    Something() {}

    template <typename Type = T,
              std::enable_if_t<!std::is_reference<Type>{}>* = nullptr>
    Something(const Something&) {}

    Something& operator=(Something&&) {
        return *this;
    }

    std::mutex mutex_;
};

int main() {
    auto&& one = Something<int>{};
    auto two = one;
    std::ignore = two;
}

When I compile this code, I get an error saying
 copy constructor is implicitly deleted because 'Something<int>' has a user-declared move assignment operator
    Something& operator=(Something&&) {
               ^
1 error generated.

Ok, so I try to apply the same constraint to the move assignment operator
template <typename T>
class Something {
public:
    Something() {}

    template <typename Type = T,
              std::enable_if_t<!std::is_reference<Type>{}>* = nullptr>
    Something(const Something&) {}

    template <typename Type = T,
              std::enable_if_t<!std::is_reference<Type>{}>* = nullptr>
    Something& operator=(Something&&) {
        return *this;
    }

    std::mutex mutex_;
};

The error changes to this
copy constructor of 'Something<int>' is implicitly deleted because field 'mutex_' has an inaccessible copy constructor
    std::mutex mutex_;
               ^
1 error generated.

Any ideas on how I can go about this?  Why is the compiler complaining when I clearly want to default construct the non-movable non-copyable member?  When I remove the constraints, this compiles fine https://wandbox.org/permlink/daqWAbF40MyfDJcN

A: The special member functions (copy/move) are identified by their signature. When you attempt to template them, you are defining templates with another signature, since the template parameters are part of a templates signature, and that function is unrelated to the copy/move c'tors you are attempting to disallow.
And for completeness, to quote the standard, emphasis mine:

[class.copy]/2
A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments ([dcl.fct.default]).

Similar wording appears when describing the other special members. They must be non-templates.
So you aren't affecting those functions with SFINAE. And you can't affect them directly with SFINAE, since the compiler makes sure they always exist. The only way to affect their generation or lack-thereof is by inheriting (conditionally, even) from base classes, or having member data, that would cause them to be defined as deleted.

The silver lining, assuming nothing changes in two years, is that in C++20 it will possible to constrain a copy constructor (or any special member) with a requires clause:
Something(const Something&) requires !std::is_reference_v<T> {}

A: Suggested workaround (if I understand the requirement correctly) is to defer copy/move capability and synchronisation to base classes (which could be mixins if necessary):
#include <iostream>
#include <tuple>
#include <mutex>

using std::cout;
using std::endl;

// A class for handling synchronisation
struct Synchro
{
    std::mutex mutex_;
};

// a class defining capabilities given a data type
template<class T>
struct DataManager : Synchro
{
    DataManager() {}

    DataManager(DataManager const&);
    DataManager& operator=(DataManager const&);
    DataManager(DataManager&&);
    DataManager& operator=(DataManager&&);

};

// special treatment for references
template<class Ref>
struct DataManager<Ref&> : Synchro
{
    DataManager() {}

    DataManager(DataManager const&) = delete;
    DataManager& operator=(DataManager const&) = delete;
    DataManager(DataManager&&) = delete;
    DataManager& operator=(DataManager&&) = delete;
};

// derive something from the specialised DataManager
template <typename T>
class Something : private DataManager<T>
{
public:
    Something() {}

};

int main() {
    auto&& one = Something<int>{};
    auto two = one;
    std::ignore = two;
}

Answers to questions in first comment:

Thanks! If you have a template function in Something that is basically a move constructor (but with a template), then when you move an instance of Something in the case where DataManager has the move constructor deleted. Then what happens?

The reason for deferring move/copy capability to the base class is that we want to remove this concern entirely from Something.

Can Something delegate construction to the default constructor of DataManager?

Yes

What effect does inheriting from a class with a deleted constructor have?

If you don't define special constructors/destructor in the derived class (which we deliberately have not done), and we define no data objects in the derived class, it has the same effect as deferring the copy/move constructor rules to the base class. This is not the fully correct description but is effectively what happens.

Does it implicitly delete the corresponding constructor of the derived class?

In this case, yes.

Do the derived class constructors/assignment operators get correspondingly deleted?

Effectively in this case, yes.
Remember to define all data objects in the base class.


text:
Q: Adding tmap_icon to legend in r The tmap_icons() function within the tmap package allows users to call a png file into tmap to be used on a map. However, I can't seem to find out how to add custom symbols to the tmap legend. See the reprex below showing the issue:
library(tmap)
#> Warning: package 'tmap' was built under R version 3.6.3
library(sf)
#> Warning: package 'sf' was built under R version 3.6.3
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 3.6.2
#> Warning: package 'tidyr' was built under R version 3.6.2

tdir=tempdir()
Stateshpurl= "https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_state_5m.zip"
if(file.exists(paste(tdir,"/cb_2018_us_county_5m/cb_2018_us_county_5m.shp",sep=""))==FALSE){
 download.file(Stateshpurl, destfile = file.path(tdir,"State_Boundaries.zip"))
 unzip(file.path(tdir,"State_Boundaries.zip"),exdir = tdir)}
US_states=read_sf(paste(tdir,"/cb_2018_us_state_5m.shp",sep=""))

US_states = st_transform(US_states, 5070)

L48 = US_states %>%
 filter(STATEFP != "02") %>%
 filter(STATEFP != "15") %>%
 filter(STATEFP != "60") %>%
 filter(STATEFP != "64") %>%
 filter(STATEFP != "66") %>%
 filter(STATEFP != "68") %>%
 filter(STATEFP != "69") %>%
 filter(STATEFP != "70") %>%
 filter(STATEFP != "72") %>%
 filter(STATEFP != "74") %>%
 filter(STATEFP != "78")

icon_url="http://29.media.tumblr.com/tumblr_m0q2g8mhGK1qk6uvyo1_500.png"
download.file(icon_url, destfile = file.path(tdir,"Image.png"),mode = 'wb')

Icon=tmap_icons(file=paste(tdir,"/Image.png",sep=""))

tm_shape(L48)+
 tm_borders()+
tm_symbols(shape=Icon)

tm_shape(L48)+
  tm_borders()+
  tm_symbols(shape=Icon)+
  tm_add_legend(type="symbol",shape = Icon)
#> Error in shapes[i] - 999: non-numeric argument to binary operator

Perhaps I am going about this wrong, but it seems like there should be a way to add one of the custom symbols created with tm_icons() into the legend.

A: One approach would be to add a new column with a legend label:
# add new variable
L48$icon = "my label"

# create a map
tm_shape(L48)+
  tm_borders()+
  tm_symbols(shape = "icon", shapes = Icon,
             title.shape = "My icon")