text:
Q: Unable to handle http codes in swift iOS? I am new to iOS and swift in my project I am using Alamofire, I am handling successfully data but I am not able to handle differnt kinds  of server codes in simple way can any one help me to solve my problem.
This is my service call
func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, headers : [String : String]?, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void){
    Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (responseObject) -> Void in
        //print(responseObject)
        if responseObject.result.isSuccess {
            let resJson = JSON(responseObject.result.value!)
            success(resJson)
        }
        if responseObject.result.isFailure {
            let error : Error = responseObject.result.error!
            let dic = ["NSLocalizedDescription" : error.localizedDescription]
            failure(error)
        }
    }
}

I am using in my classes like this.
AFWrapper.AFsharedInstance.requestPOSTURL(Post_Hod_Indexes_sections_URL, params: dicParams, headers: headers, success: {
    (json) in
    print(json)

    DispatchQueue.main.async {
        self.hideSpinner()

        let swiftyJsonVar = JSON(json)
        let status = swiftyJsonVar["status"].rawString() as!String

        print("status", status)
        if status.isEqual("404") {
            let message = swiftyJsonVar["message"].rawString()
            self.displayMsg(title: "Oops!", msg: message!, style: .alert)
            return
        }
        else if status.isEqual("200") {
            let message = swiftyJsonVar["message"].rawString()
            self.displayMsg(title: "", msg: message!, style: .alert)
            return
        }
        else if status.isEqual("500") {
            let message = swiftyJsonVar["message"].rawString()
            self.displayMsg(title: "", msg: message!, style: .alert)
            return
        } else {
            let message = swiftyJsonVar["message"].rawString()
            self.displayMsg(title: "", msg: message!, style: .alert)
            return

        }
    }

}, failure: {
    (error) in

    self.hideSpinner()
    self.displayMsg(title: "Oops!", msg: "Something went wrong try again after sometime", style: .alert)

})
}

A: To get status code from server response using alamofire is responseObject.response?.statusCode.(from your code)
Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (responseObject) -> Void in

    if let code = responseObject.response?.statusCode {
        print(code)

         switch code {

    case 200:
        // OK. you can convert here response in model class, like...

        /*   if responseObject.result.isSuccess {
               let resJson = JSON(responseObject.result.value!)
               success(resJson)
           }
        */
        break
    case 500:
        //Internal server error, do stuff

        break
    case 404:

        //Not fount. Do stuff

        break

     // you can add more case to manage diff. server status code

    default:
        break
    }
   }

}


text:
Q: lamp-server wants to install mysql but i want it to use already installed MariaDB i want to install lamp-server in ubuntu 10.10 (the end goal is to install redmine), i am using
sudo tasksel install lamp-server

However after downloading packages it asks for a root password for mysql, now, in my machine i have already an instance of MariaDB 5.24 and i want it to use that (not download or install real mysql), what do i need to do in order to properly configure it with the right database?
thanks

A: As bgvaughan stated, tasksel provides package 'groups' in order to setup complete and correctly configured, fully integrated services.
'M' from the 'LAMP' initials refers to mySQL, therefore tasksel will automatically try to install and configure mysql-server.
If you want to use mariaDB, you should install apache & php separately:
sudo apt-get install apache2
sudo apt-get install php5 libapache2-mod-php5
I haven't worked with mariaDB, but i've heard that it's a binary drop-in replacement for mysql, so i guess it should be working ok.

A: tasksel is just a means to install a meta-package, which is a list of packages. There's no particular configuration involved beyond installing the packages themselves. You could skip tasksel and just install the packages you intend to use, or you could use tasksel and then purge mysql, or you could just keep mysql, which shouldn't interfere with your existing database installation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does the timing of reflow / rendering work? Given this code:
$('#foo').css('height', '100px'); // or any other change to the DOM
console.log('done!');

When the 2nd statement executes, is it safe to assume that the reflow is complete?
Follow on question: if you replaced the second line with this, does it change the answer?
window.setTimeout('console.log("done");', 1);

I hope my underlying question is clear. Thanks a lot for any input.

A: Browsers usually queue DOM modifications that require a reflow/repaint, to avoid performing that expensive operation multiple times. There are exceptions to that, however, as you can see in this Q&A: When does reflow happen in a DOM environment?.
Considering the code you posted, and assuming the console will log the output synchronously*, the answer to your first question is no. If you just change the height of an element, the browser will typically finish running all other synchronous code before performing the reflow/repaint operation. But, as the answers on the link above says, some actions do trigger an immediate reflow, so it's not possible to answer the "or any other change to the DOM" part of your question.
Considering the same assumptions above, the answer to your second question would be yes. The string "done" will be logged to the console in the next tick of the browser's event loop, so it's safe to assume that's after the reflow.
Usually you don't have to worry about that kind of browser behavior, unless you're optimizing code for performance, and trying to avoid reflows.
* Sometimes the console outputs later than expected; unfortunately I couldn't find a good link about that.

A: The .css() method is not asynchronous, thus you can safely assume that any statements after it will execute as you expect.
$('#foo').css('height', '100px');
console.log($('#foo').css('height')); // will log '100px'


text:
Q: Запуск php скриптов Каким образом запускаются php скрипты (опишите подробно, пожалуйста).
A: *

*Качается и устанавливается веб сервер(apache+php).

*Запускается веб сервер(apache).

*На веб сервер закидываются php скрипты.

*?????

*PROFIT

A: Для изучения достаточно установить готовый пакет. denwer.ru
A: Ставите XAMPP на диск C. Запускаете сервер (на рабочем столе ярлычок после установки появится). Открываете на диске С папочку сервера, в ней есть папка htdoc. Кладете туда скрипт. Потом открываете браузер, пишете в нем localhost/имяскрипта.php и смотрите результат.
A: Для выполнения (запуска) пхп-скриптов, нужен ПХП интерпритатор, который преобразовывает ваш код в машинный и выполняет.
Для трансляции результатов вашего кода в браузере нужна "машина", которая будет запросы направлять к пхп интерпретатору и результат передаст вашему браузеру. Таковыми являются IIS, APACHE, NGNIX и т.д.. Все вместе называют веб-сервером.
Соответственно, чтобы "запустить" ваш скрипт под виндой нужен веб-сервер Apache+PHP[+MySQL].  Затем смело можете писать скрипты и пропускать их через пхп интерпретатор и apache.
A: Советую VertrigoServ устанавливаете, запускаете иконку на рабочем столе, в трее появится иконка вертриго, щелкаете на нее правой кнопкой мыши выбираем пункт "WWW folder" откроется папка, удаляем из нее все содержимое, и копируем сюда файлы нужного вам скрипта, далее идем в браузер и переходим на http://127.0.0.1/ и смотрим на скрипт!


text: Q: Is there a Github Actions warning state? Besides success and failed, is there any warning state for Github Actions? How to set one for an action that is not owned by me? E.g. Github Actions return code 1 (error), in this case I only want this to be considered as warning, not as error.


text:
Q: Unit testing Angular directive with $http I have an Angular directive that, when attached to an <input>, waits one second after user input before querying an endpoint with $http. In short, it's meant to check username uniqueness.
It looks like this:
.directive('sgValidUsername', ['$http', function(http) {
    var waitTimer;
    var checkIfUserExists = function(e, ctrl) {
            http.get('/publicapi/users/' + e.target.value + '/exists')
                .success(function(data) {
                    ctrl.$setValidity('unique', !data.exists);
            });
        };

    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ctrl) {
            element.on('blur keyup', function(e) {
                if (e.target.value) {
                    clearInterval(waitTimer);
                    waitTimer = setTimeout(function() {
                        checkIfUserExists(e, ctrl);
                    }, 1000);
                }
            });
        }
    };
}]);

I'm trying my best to write a good comprehensive Jasmine unit test suite, but it's not working out because I couldn't find an appropriate example to learn from. I end up reconstructing the directive in test form rather than actually testing the directive. Also, I get a 'no pending request to flush' error.
Any suggestions for the below?
describe('SignupForm directives', function () {
    var form,       // el to which directive is applied
    $scope,
    $httpBackend, // $http mock
    usernameExistsHandler;

beforeEach(function() {
    module('signupform.directives');
});

beforeEach(function() {
    inject(function ($injector, $rootScope, $compile, $q, $timeout) {
        $scope = $rootScope;
        $httpBackend = $injector.get('$httpBackend');
        usernameExistsHandler = $httpBackend.whenGET(/\/publicapi\/users\/.+?\/exists/);
        var el = angular.element('<form name="form"><input type="text" name="username" ng-model="user.username" sg-username-is-valid /></form>');

        $scope.user = { username: null };
        $compile(el)($scope);
        form = $scope.form;
    });
});

afterEach(function() {
 $httpBackend.verifyNoOutstandingExpectation();
 $httpBackend.verifyNoOutstandingRequest();
   });

   it('should invalidate with existing usernames', function() {
    form.username.$setViewValue('username_in_use');

    $scope.$digest();

    expect($scope.user.username).toEqual('username_in_use');

    usernameExistsHandler.respond('200', { exists: true });
    $httpBackend.expectGET('/publicapi/users/' + $scope.user.username + '/exists/');
    $httpBackend.flush();

    expect(form.username.$valid).toBe(false);
   });


text:
Q: Mark a point and draw plot lines in Multi Series Highchart I am using highcharts. I want to make a chart like in the image below. Need to mark a point where a line drawn from series 1 highest points connect to the series 2(shown in the image below).
Couldn't find any useful resource. Any leads would be appreciated. Thanks in advance.
Was able to achieve this, but not exactly what I want. You can use the code snippet below:
(Fiddle link)

Highcharts.chart('container', {
    xAxis: {
        plotLines: [{
            color: 'red',
            width: 2,
            value: Date.UTC(2010, 0, 4)
        }],
        tickInterval: 24 * 3600 * 1000, // one day
        type: 'datetime'
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4],
        pointStart: Date.UTC(2010, 0, 1),
        pointInterval: 24 * 3600 * 1000
    }, {
        data: [39.9, 91.5, 196.4, 159.2, 164.0, 180.0, 188.6, 187.5, 246.4],
        pointStart: Date.UTC(2010, 0, 1),
        pointInterval: 24 * 3600 * 1000
    }]
});

EDIT: I am able to achieve it to some level as answered by Gaurav. Check here.

A: As mentioned in the comments you can use the Highcharts SVGRenderer class to draw out a line. You can use something like a load event of Highcharts within which you can make use of the SVGRenderer to create a path line.
chart: {
     events: {
        load: function () {
                console.log(this.chart); // This will get tou the chart reference where in you can find the coordinates of the point from where you want to draw the line
var x1 = this.series[0].data[this.series[0].data.length - 1].plotX + this.plotLeft;
var y1 = this.series[0].data[this.series[0].data.length - 1].plotY + this.plotTop;
            var label = this.renderer.path(['M', x1,y1,'L', 550, y1])//M 75 223.5 L 593 223.5
        .attr({
                'stroke-dasharray': '2,2',
            'stroke-width': 2,
            stroke: 'red'
        })
        .add();
        var label = this.renderer.path(['M', 550, this.plotTop + this.plotHeight,'L', 550, y1])//M 75 223.5 L 593 223.5
        .attr({
                'stroke-dasharray': '2,2',
            'stroke-width': 2,
            stroke: 'red'
        })
        .add();

        }
    }
}

The x-coordinate 550, I selected randomly, but if you know the x-point then it is the way you do it. Here is the new fiddle link . Hope it helps


text:
Q: Must compact sets be contained in the topology? Can a set be compact but not be in the topology itself? For example, if $S$ is compact in a topological space $X$, must $S$ be in the topology $X$? Or does $S$ merely have to be covered by (finitely many) sets that are in the topology of $X$?

A: Usually, compact sets do not belong to the topology, since usually they are not open. For instance, the only compact subset of $\Bbb R$ (with its usual topology) which belongs to the topology is the empty set.

A: The sets in the topology are the open sets. Compact sets can be open, but in general they are not. For example, every finite subset of $\Bbb R$ is compact, as are the middle-thirds Cantor set and the set $\{0\}\cup\left\{\frac1n:n\in\Bbb Z^+\right\}$, and the only open set in the lot of them is $\varnothing$.
Every subset of every space is covered by an open set in the space, because the space itself is an open set. What makes a set compact is not that it can be covered by finitely many open sets: it's that it has the property that every open cover of it has a finite subcover.


text:
Q: JQuery DataTable Inline Editing With Submit Button - Post return 405 (Method Not Allowed) I am using jquery Datatables Editor and can't quite seem to figure out the set-up of how the inline editing should go.  Meaning my Controller code reads like this
[HttpGet]
[Route("api/tta")]
public JsonResult Index()
{
  var ListData = _context.TTA.FromSqlRaw("Select * from dbo.Test").ToList();
  return Json(new { Data = ListData });
}

which when I launch my asp.net core MVC append load the page the data loads exactly as expected.  However, when I try the inline edit and press the submit button for the edit, I get this error in the dev console

jquery-3.3.1.js:9600 POST https://localhost:44343/api/tta 405 (Method Not Allowed)

Now from my understanding it seems that the issue is that a POST is being attempted on an API that is only set up to make a GET request.  Which leads me to my question of what is the proper way to set this up so that the data will be submitted to the database successfully?
ASP.Net Core & MVC & Microsoft SQL Server if needed here is a link to the inline edit feature of DataTables https://editor.datatables.net/examples/inline-editing/submitButton.html

A: You need to create an method that accept POST request and recieve your data. Example:
[HttpPost]
[Route("api/tta")]
public JsonResult Post(YourType yourParameter)
{
  var result = MethodThatUpdateYourData(yourParameter);
  return Json(result);
}

A: From looking at the code given, your api/tta method allows just [HttpGet]. Simply add a new method with [HttpPost] which you can call to submit the data


text:
Q: java.lang.IllegalArgumentException: invalid value in table when trying to create an new connection I'm trying to connect to a local RabbitMQ server from Java. I've currently got my ConnectionFactory instance configured within Spring like so:
<bean class="org.rabbitmq.client.ConnectionFactory">
    <property name="host" value="localhost"/>
    <property name="port" value="5672"/>
    <property name="username" value="user"/>
    <property name="password" value="password"/>
</bean>

When I try to obtain a new connection:
connectionFactory.newConnection();

I get the following error thrown:
java.lang.IllegalArgumentException: invalid value in table
    at com.rabbitmq.client.impl.Frame.fieldValueSize(Frame.java:306)
    at com.rabbitmq.client.impl.Frame.tableSize(Frame.java:246)
    at com.rabbitmq.client.impl.ValueWriter.writeTable(ValueWriter.java:120)
    at com.rabbitmq.client.impl.MethodArgumentWriter.writeTable(MethodArgumentWriter.java:139)
    at com.rabbitmq.client.impl.AMQImpl$Connection$StartOk.writeArgumentsTo(AMQImpl.java:161)
    at com.rabbitmq.client.impl.Method.toFrame(Method.java:83)
    at com.rabbitmq.client.impl.AMQCommand.transmit(AMQCommand.java:102)
    at com.rabbitmq.client.impl.AMQChannel.quiescingTransmit(AMQChannel.java:316)
    at com.rabbitmq.client.impl.AMQChannel.quiescingTransmit(AMQChannel.java:298)
    at com.rabbitmq.client.impl.AMQChannel.quiescingRpc(AMQChannel.java:233)
    at com.rabbitmq.client.impl.AMQChannel.rpc(AMQChannel.java:224)
    at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:209)
    at com.rabbitmq.client.impl.AMQChannel.rpc(AMQChannel.java:202)
    at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:340)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:516)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:533)
    at com.tkassembled.dispatcher.service.RabbitMQQueueService.init(RabbitMQQueueService.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1581)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1522)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:876)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:818)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:735)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1184)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1091)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
    at javax.servlet.GenericServlet.init(GenericServlet.java:160)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1266)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1185)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1080)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5015)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1568)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1558)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:679)

In the RabbitMQ logs:
=ERROR REPORT==== 13-Jul-2012::15:24:30 ===
exception on TCP connection <0.1159.0> from 127.0.0.1:55154
{handshake_timeout,frame_header}

Update
I'm also now noticing something really strange. If I create the ConnectionFactory instance in Spring, then all calls to newConnection() will fail terribly, even if I'm not setting any properties on it:
<bean class="org.rabbitmq.client.ConnectionFactory">
    <!-- nothing -->
</bean>

However, if I create the ConnectionFactory instance outside of the Spring container and then call newConnection(), no errors are thrown:
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("localhost");

Connection connection = connectionFactory.newConnection();

What am I doing wrong? This seems kind of weird to get such a random error that only occurs when the ConnectionFactory was created in the Spring container. What about the Spring container would be so dramatically different than creating it in raw Java?

A: I had the same problem, it was in my header:
Map<String, Object> headers = new HashMap<>();
headers.put("user-id", event.uid);
[...]
channel.basicPublish(exchangeName, "???", new AMQP.BasicProperties.Builder().headers(headers).build(), payload.getBytes(UTF_8));

(the BasicProperties.Builder() has been shorten for visibility)
The problem was solved with a String value in the header instead of the UUID:
Map<String, Object> headers = new HashMap<>();
headers.put("user-id", event.uid.toString());

A: I implemented some wrapper of Rabbitmq ConnectionFactory. It's configured from within Spring configuration with host/port/etc. And has method getConnection() that simply do
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(getHostName());
factory.setUsername(getUserName());
factory.setPassword(getPassword());
factory.setAutomaticRecoveryEnabled(true);
Connection connection = factory.newConnection();

If you need only one connection (really?), you can use this method in the constructor...


text:
Q: How to Async Task Network Operation in Service in Android? This is my Service which does network operation. But it is throwing NetworkonMainThreadException which i understand android upper version doesn't allows network operation under main thread. Now i want to use Async Task for this purpose. I am not sure which are all code i need to add under Async Task from Service Class to actually make the code complete. Below is my Service Code :
public class NewsTickerDataService extends Service {

 @Override
    public void onStart(Intent aIntent, int aStartId) {
        super.onStart(aIntent, aStartId);
        RemoteViews _views = buildUpdatedViews(this);
        ComponentName _widget =
            new ComponentName(this, NewsTicker.class);
        AppWidgetManager _manager =
            AppWidgetManager.getInstance(this);
        _manager.updateAppWidget(_widget, _views);
    }

    @Override
    public IBinder onBind(Intent aParamIntent) {
        // not supporting binding
        return null;
    }

    private RemoteViews buildUpdatedViews(Context aContext) {
        List<Story> _stories = getStories();
        RemoteViews _result = new RemoteViews(
            aContext.getPackageName(),
            R.layout.activity_main
        );

        if (_stories.isEmpty()) {
            _result.setTextViewText(R.id.title,
                "Sadly there's nothing to read today.");
        } else {
            _result.setTextViewText(
                R.id.title, _stories.get(0).getTitle());
        }
        return _result;
    }

    private List<Story> getStories() {
        try {
            URL _url = new URL("http://search.twitter.com" +
                "/search.atom?q=%23uml&" +
                "result_type=mixed&count=5"
            );
            InputStream _in = _url.openStream();
            return parse(new InputSource(_in));
        } catch (Exception anExc) {
            Log.e("NewsTicker", anExc.getMessage(), anExc);
            return new ArrayList<Story>();
        }
    }

    private List<Story> parse(InputSource aSource)
    throws Exception {
        SAXParserFactory _f = SAXParserFactory.newInstance();
        SAXParser _p = _f.newSAXParser();
        XMLReader _r = _p.getXMLReader();

        AbstractParser _h = AbstractParser.newAtomParser();
        _r.setContentHandler(_h);
        _r.parse(aSource);

        return _h.getStories();
    }

}

Async Task Code :
public class YourAsyncTask extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... params) {
            // your load work
            //return myString;
        }

        @Override
        protected void onPostExecute(String result) {

        }

    }

Can someone please help me to integrate Async Task into same code. Thanks

A: Yes, I'd suggest IntentService too!
IntentService example
public class MyService extends IntentService {

private int STOP_DOWNLOAD = false;
public static int UPDATE_PROGRESS = 0;

public MyService() {
    super("myservice");
}

@Override
public void onCreate() {
    super.onCreate();
}

@Override
protected void onHandleIntent(Intent intent) {

    // Network Task : download ?

    // Send some data to the receiver
    Bundle resultData = new Bundle();
    resultData.putInt("progress", progress);
    receiver.send("update", resultData);
}

private void stopDownload() {
    this.STOP_DOWNLOAD = true;
    // Stop the download : use this boolean into onHandleIntent
}

}
The receiver
public class MyReceiver extends ResultReceiver {

Context context;

public MyReceiver(Context mContext) {
    super(handler);
    context = mContext;
}

@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
    super.onReceiveResult(resultCode, resultData);

    if (resultCode == "update") {

        String something = resultData.getString(MyService.SOMETHING);

    }
}

}
Start the service in an Activity : startService(...)

A: From the onStart() of your service class make network operation
        YourAsyncTask.execute(url);

Async task code
    public class YourAsyncTask extends AsyncTask<String, Void, String>{

    @Override
    protected String doInBackground(String... params) {
        // your load work
        DefaultHttpClient client = new DefaultHttpClient();
         HttpGet httpGet = new HttpGet(url);
    try {
      HttpResponse execute = client.execute(httpGet);
      InputStream content = execute.getEntity().getContent();

      BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
      String s = "";
      while ((s = buffer.readLine()) != null) {
        response += s;
      }

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

  return response;
        //return myString;
    }

    @Override
    protected void onPostExecute(String result) {
       //HERE CALL YOUR PARSE METHOD

       //AFTER PARSING CALL buildUpdatedViews(Context aContext , stories)
    }

}


text:
Q: Converting CloudFront access logs to Parquet format What is the best way to convert CF access logs to parquet format and write it back to S3.
Currently I know of two common ways:

*

*Trigger lambda on original log write to s3 and send it to AWS Kinesis
Firehose for conversion

*Using CTAS periodically to convert an entire table

Which option should I use and what are the main differences between them?

A: For the ease of use: Glue crawler
Next thing in-line I can think of is glue job, then the more controlled approach would be emr spark cluster job for faster processing.
ECR/Kubernates are also brings a good argument.


text:
Q: How to protect Python source code, while making the file available for running? So, I recently made a Python program that I want to send to someone with them being able to execute it, but not read the code I have typed in it. Any ideas how to do it?
BTW, I want it to be irreversible
In short, here are my Parameters:

*

*Should remain a Python file

*Can't be reversed

*Code should not be readable

*Should still have the ability to be run

A: The criteria you've posted are inconsistent.
Python is an interpreted language.  The entity running the language (i.e. Python interpreter) is reading your code and executing it, line by line.  If you wrap it up to send to someone, their Python interpreter must have read permissions on the file, whether it's source code or "compiled" Python (which is easily decompiled into equivalent source code).
If we take a wider interpretation of "send to someone", there may be a business solution that serves your needs.  You would provide your functionality, rather than the code: deploy it as a service from some available server: your own, or rented space.  To do this, you instead provide an interface to your functionality.
If this fulfills your needs, you now have your next research topic.


text:
Q: check discord bot dm's so i'm new to discord bots and i wanted to make it so when someone dm's the bot the bot sends that dm to me
@bot.event
async def on_message(message):
    if message.content.startswith("$suggest"):
        await message.channel.send("check dm's", delete_after=5, reference=message)
        await message.author.send("please type $suggest (suggestion)")
    #if person dms me and content startswith $suggest:
        #send the dm to me or suggestions chat

A: You can check for DMChannels using isinstance(message.channel, discord.DMChannel) and then send a message to you using me = bot.get_user(your_discord_id) and then me.send(f"Suggestion by {message.author}:\n{message.content}").
All of this in your code would be:
@bot.event
async def on_message(message):
    if message.content.startswith("$suggest"):
        await message.channel.send("check dm's", delete_after=5, reference=message)
        await message.author.send("please type $suggest (suggestion)")
    if message.content.startswith("$suggest") and isinstance(message.channel, discord.DMChannel)
        me = bot.get_user(your_discord_id)
        me.send(f"Suggestion by {message.author}:\n{message.content}")

References:

*

*Client.get_user(id)


text:
Q: How to check if a .txt file is in ASCII or UTF-8 format in Windows environment? I have converted a .txt file from ASCII to UTF-8 using UltraEdit. However, I am not sure how to verify if it is in UTF-8 format in Windows environment.
Thank you!

A: Open it in a hex editor and make sure that the first three bytes are a UTF8 BOM (EF BB BF)

A: If you use Windows 10 and has Windows Subsystem for Linux (WSL), it can be easily done by typing "file " from the shell.
For example:
$ file code.cpp

code.cpp: C source, UTF-8 Unicode (with BOM) text, with CRLF line terminators

A: Open the file in Notepad. Click 'Save As...'. In the 'Encoding:' combo box you will see the current file format.

A: Text files in Windows don't have a format. There's an unofficial convention that if the file starts with the BOM codepoint in UTF-8 format that it's UTF-8, but that convention isn't universally supported. That would be the 3 byte sequence "\xef\xbf\xbe", i.e.  in the Latin-1 character set.

A: Open the file using Notepad++ and check the "Encoding" menu, you can check the current Encoding and/or Convert to a set of encodings available.

A: I had a directory of files that I wanted to check.  I created an Excel macro to determine ANSI vs. UTF-8.  This worked for me.
        Sub GetTextFileEncoding()
        Dim sFile As String
        Dim sPath As String
        Dim sTextLine As String
        Dim iRow As Integer

        'Set Defaults and Initial Values
        iRow = 1
        sPath = "C:textfiles\"
        sFile = Dir(sPath & "*.txt")

        Do While Len(sFile) > 0
            'Get FileType
            'Debug.Print sFile & " - " & FileEncodeType(sPath & sFile)

            'Show on Excel Worksheet
            Cells(iRow, 1).Value = sFile
            Cells(iRow, 2).Value = FileEncodeType(sPath & sFile)

            'Get next file
            sFile = Dir

            'Increment Row
            iRow = iRow + 1
        Loop
    End Sub

    Function FileEncodeType(sFile As String) As String
        Dim bEF As Boolean
        Dim bBB As Boolean
        Dim bBF As Boolean

        bEF = False
        bBB = False
        bBF = False

        Open sFile For Input As #1
            If Not EOF(1) Then
                'Read first line
                Line Input #1, textline
                'Debug.Print textline
                For i = 1 To 3
                    'Debug.Print Asc(Mid(textline, i, 1)) & " - " & Mid(textline, i, 1)
                    Select Case i
                        Case 1
                            If Asc(Mid(textline, i, 1)) = 239 Then
                                bEF = True
                            End If
                        Case 2
                             If Asc(Mid(textline, i, 1)) = 187 Then
                                bBB = True
                            End If
                        Case 3
                             If Asc(Mid(textline, i, 1)) = 191 Then
                                bBF = True
                            End If
                        Case 4

                    End Select
                Next
            End If
        Close #1

        If bEF And bBB And bBF Then
            FileEncodeType = "UTF-8"
        Else
            FileEncodeType = "ANSI"
        End If
    End Function


text:
Q: Passing value to JS with php return? I have a php method that should return some values as JSON :
function pass_value() {
 ....
 $output[] = 'some value';
 ...

 if() {
  //JS get it right
  echo json_encode(array('response' => $output));
  return;
 }
 ...
 //eventually another echo

}

Where's the problem to do it like this ?
function pass_value() {
 ....
 $output[] = 'some value';
 ...

 //js doesn't get it ?
 return json_encode(array('response' => $output));
}

I want to terminate the other part of the method after it passes the array, but seems that JS doesn't get the JSON when it's not echoed.

A: That's because if you do not echo, the server never sends it to the client and the JavaScript never sees it. Remember, PHP is server-side, JavaScript is client-side.
You can of course do this with the last function:
echo pass_value();


text:
Q: Using Picocli, how do I require a positional argument and then optional arguments depending on the value of the positional argument I have a situation where I need to have three mandatory arguments (field1, field2 and field3. I then want the user to enter a command name (mandatory, values can be create, list, etc). The command name must be entered, and must be singular (only one of them can be entered).
Some of the commands will have arguments, some of them will not. How do I handle that?
I tried the following, but I get an error:
ArgGroup has no options or positional parameters, and no subgroups

public class CliParserArgs {
    @Option(names = {"--field1"}, required = true)
    private String field1;

    @Option(names = {"--field2"}, required = true)
    String field2;

    @Option(names={"--field3"}, required = true)
    String field3;

    @Option(names = {"-h", "--help"}, usageHelp = true) boolean help;

    class Create {
        private final String val;
        public Create(final String val) {
            this.val = val;
        }
    }

    class ListObjects {
        private final String val;
        public ListObjects(final String val) {
            this.val = val;
        }
    }

    @ArgGroup(heading = "Command", exclusive = true, multiplicity = "1")
    Create create;
    ListObjects listObjects;

    public static void main(String[] args) {
        CliParserArgs cliParserArgs = new CliParserArgs();
        CommandLine cmd = new CommandLine(cliParserArgs);
        CommandLine.ParseResult parseResult = cmd.parseArgs(args);
        System.err.println("parse results: " + parseResult.matchedArgs().toString());

        try {
        if (cmd.isUsageHelpRequested()) {
            cmd.usage(System.out);
        }
        } catch (CommandLine.ParameterException e) {
            System.err.println("error: " + e.getMessage());
            System.err.println(e.getStackTrace());

        }
    }
}

A: It sounds like you want to create a command with subcommands. You can do this in picocli by either marking a method with the @Command annotation or by creating a separate command class and registering it as a subcommand of your parent command. If your subcommand has many options, you probably want to create a separate class for it.
Once you have created subcommands, you want to call the logic for the subcommand that the user specified. You can do this manually, using the CommandLine.parseArgs method, but this is a lot of work. I would recommend using the CommandLine.execute method instead.
The execute method will parse the user input, handle --help and --version requests, handle invalid user input, and finally (if the user input was valid) invoke the business logic of the subcommand that the user specified. It will also return an exit code.
The execute method requires subcommands to be either a @Command-annotated method or a @Command-annotated class that implements Runnable or Callable.
Below is an example based on your example code, implemented as subcommands.
@Command(name = "cli", version = "1.0",
    mixinStandardHelpOptions = true,
    subcommands = {Create.class, ListObjects.class})
public class Cli implements Runnable {
    @Option(names = {"--field1"}, required = true)
    private String field1;

    @Option(names = {"--field2"}, required = true)
    String field2;

    @Option(names={"--field3"}, required = true)
    String field3;

    // not needed because we have mixinStandardHelpOptions=true
    //@Option(names = {"-h", "--help"}, usageHelp = true) boolean help;

    public void run() {
        // business logic of the top-level cmd here
        System.out.println("hi, field1="+field1);
    }

    public static void main(String[] args) {
        int exitCode = new CommandLine(new Cli()).execute(args);
        System.exit(exitCode);
    }
}

@Command(name = "create", description = "create ...",
        mixinStandardHelpOptions = true, version = "1.0")
class Create implements Callable<Integer> {
    @Option(names = {"-x", "--times"}, description = "...")
    int x;

    @Override
    public Integer call() {
        // business logic for "create" here...
        return ok ? 0 : 1; // exit code support
    }
}

@Command(name = "list", description = "create ...",
        mixinStandardHelpOptions = true, version = "1.0")
class ListObjects implements Runnable {
    @Option(names = {"-x", "--times"}, description = "...")
    int x;

    @Override
    public void run() {
        // business logic for "list" here...
    }
}


text:
Q: how to get the correct index in a datGrid when I use the MVVM pattern and I have a filter in the dataGrid? I have a DataGrid in my view, and I would like to select a row. In my view model I have a property to bind the SelectedIndex of the dataGrid.
When I add a new row to the dataGrid, this element is add at the end of the elements, show in the dataGrid I can see it in the last position.
However, if i have shorted the elements in the dataGrid because I click in a column name and this filter makes that the new element it will be in the first position of the dataGrid, then I select the incorrect element, because internally the position of the new element is in the N position, not the first.
For example. I have a table that has the name and username of people. I get some persons in the dataGrid and I short them by name. now I insert a new person whose name is AAAA. When I add the new person, in the dataGrid I can se this person in the first row, but I select the last person because in my view model I select the index of my new person, that internally is add at the end.
How can I select in the datagrid the correct row when I have a used a filter?
Thanks.

A: you could use an ICollectionView to handle your SelectedItem
this._myView= CollectionViewSource.GetDefaultView(this.MySourceCollection);
...
this._myView.MoveCurrentTo(newitemwithAAAA);

then your new element is selected


text:
Q: VUE JS Fetch JSON data and display single value in HTML as plain text i have a .json file with the following structure:
{
  "d": {
    "value1": "300",
    "value2": "0000000002",
    "value3": "AAAA",
  }
}

I want to access 300 in my vue-app and display it as plain text.
That's it.
Question may be stupid, but I don't get it and my code won't work.
Could you give me an example of how to do that?
Greetz,
Simon
app.vue:
new Vue({
    el: "#vue-root",
    data: {
        items:[]
    },
    created(){
        this.fetchData()
    },
    methods: {
     fetchData() {
       this.$http.get('test.json')
         .then(result => {
            this.items = result.data
          })
     }
   }
 })

index.html:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Simon VueJS</title>
    <link href="styles.css" rel="stylesheet" />

           {{ d.value1}}

A: solution:

           {{ d && d.value1}}


text:
Q: Display div over video (iframe or object) I have a website where the header and footer are in fixed position, while the middle content can be scrollable. In fact, when we scroll the content should go under the header or footer, because the website takes 100% height and I chose to apply overflow: auto; to the body. It's not possible to have a specific height for the middle content, 'cause header and footer are fixed sizes.
I applyed z-index to all elements, and it works great but I need to embed videos from Youtube, Vimeo or other... Ordinary, these videos are displayed using iframe or object ; my client puts directly the embed code in the backoffice. Here is my problem : when I scoll, the videos are displayed over header and footer even if I set a specific z-index ; other elements in middle content are well hidden...
Do you have an idea to solve this problem ?
Thanks !

A: Without using jquery you can simple use this in your 'iframe' tag
src="http://www.youtube.com/embed/yourVideo?wmode=transparent"

A: you have to set wmode to transparent in your flash. so in your embed / object code add wmode="transparent"
or
<param name="wmode" value="transparent" />

A: Adding to Hans' answer:
$(document).ready(function (){
    $('iframe').each(function(){
        var url = $(this).attr("src");
        $(this).attr("src",url+"?wmode=transparent");
    });
});

(you still have to use z-index)

A: Adding to Yisela's answer:
$(document).ready(function (){
    $('iframe').each(function(){
        var url = $(this).attr("src");
        $(this).attr("src",url+"?wmode=transparent");
    });
});


text:
Q: How can I fix "React Hook useEffect has a missing dependency. Either include it or remove the dependency array" problem? I want to use useEffect, but when I add getGroup method, I get warning:

React Hook useEffect has a missing dependency: 'getGroups'.
Either include it or remove the dependency array"

My code is:
useEffect(() => {
  getGroups();
  setContent(contentGroup);
}, [contentGroup]);

const [content, setContent] = useState([]);
const [groups, setGroups] = useState({});

const getGroups= () => {

   let newGroups = groups;

   contentGroup.forEach(content=>{
     newGroups = {...newGroups , [content.id]: content.title};
   })

   setGroups(newGroups);
}

A: If getGroups does not get re-assigned, or you don't mind the useEffect running again if it does, then it should be safe to include it in the dependency array, like the message is eluding to:
useEffect(() => {
  getGroups();
  setContent(contentGroup);
}, [contentGroup, getGroups]);


text:
Q: Why is plt.figure() defined outside the for loop? In the following code why I have to define fig and ax at the beginning of for loop? When I write it at the end of loop it gives me only one graph not the two.
fig = plt.figure()
ax = fig.add_subplot(111)
Ls = [2, 4]
for L in range(len(Ls)):
    x = np.arange(10)
    y = np.random.randint(0, 11, size=10)
    print(y)
    ax.plot(x,y)
    ax.set_label("x")
    ax.set_label("y")
    plt.savefig("jj.png")
    plt.show()

A: Consider defining the figure as getting a sheet of paper to draw upon. So, if you want to draw several plots into the same diagram you need to define it once (before the loop) and draw several plot onto it (in the loop). For this to work, you need to move savefig() and show out of the loop body:
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

Ls = [2, 4]
for L in range(len(Ls)):
    x = np.arange(10)
    y = np.random.randint(0, 11, size=10)
    print(y)
    ax.plot(x,y)
    ax.set_label("x")
    ax.set_label("y")

plt.savefig("jj.png")
plt.show()

Which will give you something like this:

If you want two plots, you can use the subplots() method to create several axes on which you can then call plot() like this:
import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(2, 1) # This creates two axes objects, one for the upper one for the lower plot
for ax in axes:
    x = np.arange(10)
    y = np.random.randint(0, 11, size=10)
    ax.plot(x,y)
    ax.set_xlabel("x")
    ax.set_ylabel("y")

fig.tight_layout()
plt.savefig("jj.png")
plt.show()

This will give you something like this:

A: Your for loop has two steps.
If you create fig = plt.figure() inside the loop, there will be two plots, one per iteration; if you put fig = plt.figure() outside the for loop, then plt.plot(...) will plot in the only figure that was created.
When the plt.figure() is outside the for loop, there are still two plots but one figure, but because of the line plt.show() one plot is replacing the other or plotting over the other.
If you delete the line plt.show() you'll see the two plots in the same figure.


text:
Q: Set html textBox value from Webmethod I have a ajax method which is passing data between pages ...I need to set one html textbox value at retrieving end ..
I tried to do it ...it gives error :

         //Err : cant set static value to non static member

I am only seeing examples of returning static string ...But no other examples
this is my ajax method :
 $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "WebForm1.aspx/GetData",
                data: JSON.stringify({ cc: cc }),
                dataType: "json",
                async: false,
                success: function () {

            },
            });

this is webmethod at recieving end :
[WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static void GetData(tbl1 cc)
        {
         //Getting data in cc
         //Not able to set value to textbox ..
         //Err : cant set static value to non static method
        }

How can I set the simple Html input textbox value from CodeBehing(WebMethod) or by at client End  ..I searched a Lot..but couldnot found the relevant solution ..More post I found is about that not able to "get data in WebMethod "One solution i was suggest to try Request.Form[] ...But it also not working ..
Some codes are complicated ..is it possible to retrieve data from WebMethod to html controls  ?
Please Suggest


text:
Q: Switching Views Programmatically in Swift I am trying to switch to the second view by pressing the "feeling lucky" button. When I try out my simulator and press it, it just goes to a black screen. How could I fix this?
@IBAction func FeelingLuckyPress(sender: UIButton) {

    let secondViewController:SecondViewController = SecondViewController()

    self.presentViewController(secondViewController, animated: true, completion: nil)
}

A: You can add a segue between the two scenes in your storyboard by control dragging from the view controller icon at the top of the first scene to the second scene:

You can then select that segue and give it a unique storyboard identifier, and then you can just perform the segue using that identifier:
performSegue(withIdentifier: "SegueToSecond", sender: self)

Alternatively, you can do something like:
guard let controller = storyboard?.instantiateViewController(withIdentifier: "Second") as? SecondViewController else {
    return
}
present(controller, animated: true) // or `show(controller, sender: self)`

where "Second" is a storyboard identifier I specified for that destination scene in Interface Builder.

By the way, there are alternatives if you are creating your destination scene programmatically or using NIBs, but storyboards are more common, so I focused on that in my examples above.


text:
Q: What does a "cannot open include file" error mean in Visual C++ 2010? Could you please help me in solving the below error:

fatal error C1083: Cannot open include file: 'graphics.h': No such file or directory

#include<dos.h>
#include<graphics.h>
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
union REGS in,o;

circ()
{
    int i;
    for(i=0;i<15;i++)
        circle(320,240,i*10);
    rectangle(240,160,400,320);
}

bulb()
{
    int i=1,c=1;
    randomize();
    while(!kbhit())
    {
        if((i%2)==0)
            setcolor(c++);
        setfillstyle(1,getcolor());
        circle(320,240,i*20);
        putpixel(320-i+2,240-i+2,1);
        floodfill(320-i+2,240-i+2,getcolor());
        delay(1000);
        i++;
        if(i>=5)
            i=1;
    }
}

dot()
{
    int i,j,of=40,wid=5;
    setcolor(8);
    setfillstyle(1,getcolor());
    for(i=of;i<getmaxx();i+=of)
        bar(i,0,i+wid,getmaxy());

    for(i=of;i<getmaxy();i+=of)
        bar(0,i,getmaxx(),i+wid);

    for(i=of;i<getmaxx();i+=of)
        for(j=of;j<getmaxy();j+=of)
        {
            setcolor(15);
            setfillstyle(1,getcolor());
            circle(i+2,j+2,4);
            floodfill(i+2,j+2,getcolor());
        }

}

void main()
{
    int x=0,y=10,gd=DETECT,gm,i;
    initgraph(&gd,&gm,"c:\tc\bgi");
    setcolor(YELLOW);
    settextstyle(1,0,6);
    outtextxy(0,240,"Count the black dots.....");
    sleep(4);
    cleardevice();
    dot();
    getch();
    cleardevice();
    setcolor(YELLOW);
    settextstyle(1,0,4);
    outtextxy(0,240,"I bet the lines of rectangle are straight.....");
    sleep(4);
    getch();
    cleardevice();
    circ();
    getch();
    closegraph();
}

A: You are trying to compile code that includes the header file graphics.h, but your compiler cannot find that file. There are a couple of possible reasons why not:

*

*The include directive that you've written at the top of your code file may be incorrect. There are two syntactical forms, and you need to make sure that you've used the right one in order for the pre-processor to search in the correct location. For a complete run-down, check the documentation.

*You may not have the Windows SDK installed, which includes the header files you need to call functions from the Win32 API. You can download the latest version of the SDK here.

*I have no idea where you got this code, but the only graphics.h that I know about is an extremely old graphics library for Borland Turbo C/C++ compilers. It works with 16-bit MS-DOS applications, not modern day Windows programs. This is not a standard Windows header. You need to be using windows.h instead for all of your graphics functions.
EDIT: I see you've posted your code. Unfortunately, you're not going to have much luck with including dos.h, either. Refer specifically to my third suggestion above. I don't know where you got this code, but you're not going to be able to compile it on Visual C++. The "Visual" part means you're creating a Windows application. The code you're using is including proprietary header files included with versions of Borland's Turbo C/C++ compilers that ran under MS-DOS (the text-based predecessor to Windows). You need to find some updated code or use a (much) older compiler.
If you absolutely need to compile that code, it looks like you can download an ancient copy of Borland Turbo C++ 3.0 here. I assume that it's abandonware at this point, but you're on your own. I wasn't even programming that long ago.

A: Both graphics.h and conio.h are only available on Borland compilers (they are vendor specific extensions).
(Note: I believe conio.h actually exists on recent msvc++ compilers, but it's not 100% compatible with Borland's version)
If you're using MSVC, you're going to have to implement your logic using the Windows API's Console Functions instead.


text:
Q: Complex MySQL Query - Checking for overlapping DATE intervals I'm trying to write a function to move an scheduled task.  The schedule can not overlap with any other event. My user inputs are as follows:

*

*schedule_id (int)

*new_start_time (DATETIME)

My table structure is as follows:
Schedules
| schedule_id | start_time              | end_time              |   task_id
|     1       | 2015-12-21 02:00:00     | 2015-12-21 04:00:00   |      1
|     2       | 2015-12-21 08:30:00     | 2015-12-21 09:30:00   |      1
|     3       | 2015-12-22 01:00:00     | 2015-12-22 02:00:00   |      2

Tasks
| task_id     | name                    | max_duration
|       1     | do things               |    2
|       2     | do stuff                |    1

A user has between start_time and end_time to start a "task".  The user can not begin the "task" until that window.  Once that user begins the task they have whatever the max_duration for that task ID is to complete it.  There is also a 15 minute window to set up for the next task.  That means a user who starts a task 1 second before the end of the window still has max_duration amount of time to complete the task.  Therefore the "actual window" that nothing can be scheduled in is start_time to (end_time+max_duration+15).  I would like to move an event (or insert a new one) but I must check for overlaps.  Essentially I must ensure:

*

*Does the start_time from user input run into any other schedule's end_time+max_duration+15?

*Does the end_time+max_duration+15 run into any other schedule's start time.  end_time is simply obtained by taking the new start_time and adding the original duration (end_time = (orig_end_time-orig_start_time)+start_time
For example, the above table is valid for schedule_id's 1 and 2 because a user can start any time between 2:00 and 4:00.  Assuming he starts right at the end, 3:59:59 the event will last at max until 5:59:59.  Even with the cleanup window of 15 minutes this still leads to 6:14:59 and since the next schedule starts at 8:30 this is ok.
I've been wrapping my head around this for hours.  I would like to do it in pure MySQL however I am considering using PHP if I really have to.  Even in PHP this problem seems difficult.  Sure I could grab every schedule with a start time a day or two earlier and an end time a day or two later then compare my interval but that seems very hacky.
Any ideas?


text:
Q: IE11 / Edge : css hover behavirour on resizing / moving elements I have a IE-specific problem with a menu on my site.
When the user hovers on a menu object, a sub-menu opens with the related choices.
This is made with a small div getting bigger (max-height change) with a :hover css rule.
I force-close the menu by hiding it momentarily (this makes chrome & firefox properly give up the :hover behaviour).
Problem:
On IE : as long as the mouse did not move, the :hover is still active, so the menu stays open.
The problem is the same on moving elements :
If I hover a moving div, the css behavior works, but if I stop moving my mouse and the div is moved by a script, it keeps the hover behavior altought its not under the mouse anymore.
Question :
How can I force IE to reset/recheck its hover behavior ?
Thanks in advance.


text:
Q: Initializing C char array using curly braces, is it okay to omit null byte '\0'? So I read that:
char pattern[] = "ould";
is basically the easier way of writing:
char pattern[] = { 'o', 'u', 'l', 'd', '\0' };
I understand that the null character \0 marks the end of a string, but what if I write it like:
char pattern[] = { 'o', 'u', 'l', 'd'}; (without the \0)
It still compiles.
Where would pattern without the \0 cause problems, because it seems to be compile without warnings (-Wall)

A: What's wrong with this behaviour? It is perfectly valid to have a char array without a '\0' on the end. Its just an array. The only reason the '\0' exists is to delimit the string. If you know what the length is, you don't need it!
Char arrays aren't special from other arrays. The only thing you need the '\0' for are the standard string functions.

A: Its not a compiler warning, but a logical one. If you use strcpy without the \0 you potentially could corrupt your stack.

A: it wouldn't cause problems with the compiler, where it would cause problems is that many functions, e.g. printf assume that when you pass something in with the %s format specifier it will be '\0' terminated.
But if you are only passing that array into functions you write, or where you pass in the length of the array as a separate parameter and they all know how long it is it won't cause a problem.

A: char string[] = "abcd"; /*is valid at the end is the \0, 5 chars were allocated*/

char str[3] = {'\0'}; /* all are \0 */

strncpy(str, string, 2); /*strcpy doesn't add \0*/

str[3] = '\0'; /* now is everything fine! */

A: If you leave off the terminating zero, you no longer have a null terminated string, just an array of char, so passing it to any function that expects a string would be an error. E.g. strlen, as the source parameter to strcpy, as a ... parameter to printf with a %s format specifier, etc.

A: It's a problem if ever you treat it as a string. For example, using strcmp, strcpy, printf. They all expect to find the null terminator, so will definitely encounter problems.
A plain old array of characters is OK as long as you're only ever treating it as an array of characters. e.g.
char c = pattern[2];

A: Of course it compiles -- it's a valid C program.   The problems would occur if you tried to pass in your character array to a function expecting a null-terminated string (an array of characters ending with '\0').

A: For example getting the length of the string will produce unpredictable results.
strlen(pattern)


text:
Q: How many pairs of adjacent numbers each have a prime number of factors? Let $a,b\in\Bbb{N}\,|\,a+1=b$ and, $a$ and $b$ each have a prime number of factors
Question: how many pairs (a,b) satisfy these conditions?
I recommend trying this on your own first.
There is a thorough explanation on my progress on the problem. If you don't want to read that and just want to skip to the part of the problem that I am unable to solve you can scroll to the bottom of this page where I lay out the problem in it's final form along with the pairs i have found already.
The number of factors a number has is related to it's prime factorization.
If  $c=p_1^{e_1}\cdot p_2^{e_2}\cdot p_3^{e_3}... p_k^{e_k}$ where $p_i$ is a prime and $e_i \in \Bbb{N}$, then the number of factors of $c$ is $(e_1+1)(e_2+1)(e_3+1)...(e_k+1)$. The only way for this product to be a prime is if there is only one $p_i$ and $e_i=p-1$ for some prime p. Therefore $a=p_1^{p_2-1}$ and $b=p_3^{p_4-1}$. The problem then is to find all solutions to the equation $p_1^{p_2-1}+1=p_3^{p_4-1}$. Since $a$ and $b$ differ by one. They have opposite parities so exactly one of them is even. This means there are two cases:$$p_1^{p_2-1}+1=2^{p_4-1}\qquad\qquad 2^{p_2-1}+1=p_3^{p_4-1}$$
Case 1 : $p_1^{p_2-1}+1=2^{p_4-1}$ $$\\$$
$p_1^{p_2-1}=2^{p_4-1}-1\quad$(1)$$\\$$
if $p_4=2$ then the right hand side (rhs) of (1) equals 1, however the left hand side (lhs) can't equal 1. therefore $p_4$ is odd. $\exists\,x\in\Bbb{N}\,|\,2x=p_4-1$ $$\\$$
$p_1^{p_2-1}=2^{2x}-1\quad$ (2) $$\\$$
$3|2^{2x}-1$ therefore $p_1=3$. The expression $2^{2x}-1$ can be factored into $(2^x-1)(2^x+1)$. $$\\$$
$3\,|\,(2^x-1)\quad$ xor $\quad 3\,|\,(2^x+1)$
the only prime factor of the lhs of (2) is three so the rhs can't have any other prime factors. The only possibility then is $2^x-1=1$ and $2^x+1=3$ so the first solution is $(3,4)$.$$\\$$
Case 2 : $2^{p_2-1}+1=p_3^{p_4-1}$ $$\\$$
Case 2a : $p_4$ is odd. $\exists\, y\in\Bbb{N}\,|\,2y=p_4-1$ $$\\$$
$2^{p_2-1}=p_3^{2y}-1\quad$(3)$$\\$$
$p_3^{2y}-1$ can be factored into $(p_3^{y}-1)(p_3^{y}+1)$ $$\\$$
$2\,|\,(p_3^{y}-1)\quad$and$\quad2\,|\,(p_3^{y}+1)\quad$ also, $\quad4\,|\,(p_3^{y}-1)\quad$xor$\quad4\,|\,(p_3^{y}+1)\quad$ $$\\$$
similarly to the first case the only prime factor on the lhs of (3) is two so the rhs can't be divisible by any other prime factors. The only possibility is $(p_3^{y}-1)=2$ and $(p_3^{y}+1)=4$. This results in the pair (8,9) but 8 doesn't have a prime number of factors therefore this isn't a solution.$$\\$$
case 2b: $p_4=2\quad\rightarrow\quad2^{p_2-1}+1=p_3
\quad$ (4)  $$\\$$
If $(p_2-1)$ has an odd prime factor then $2^{p_2-1}+1$ can be factored. let $d\cdot f=p_2-1$
where $d$ is odd number (other than 1) then $$2^{d\cdot f}+1=(2^f+1)(2^{f\cdot(d-1)}-2^{f\cdot(d-2)}+2^{f\cdot(d-3)}-2^{f(d-4)}...+2^{2f}-2^f+1)$$. For example if  $p_2-1=10$ then $(2^{10}+1)=(2^2+1)(2^8-2^6+2^4-2^2+1)$.The rhs of (4) is prime so $(p_2-1)$ can't have an odd prime factor. This implies the only odd number $(p_2-1)$ can be is one. $(p_2-1)=1$ results in the second solution (2,3). Otherwise $(p_2-1)$ must be a power of two. $\exists \,m \in \Bbb{N}\,|\,(p_2-1)=2^m \rightarrow 2^m+1=p_2$. The same argument that was used to show $p_2-1$ is a power of two can be used to show $m$ is a power of two.$$\exists\, n \in \Bbb{N}\,|\qquad2^{2^n}+1=p_2\quad and \quad2^{2^{2^n}}+1=p_3 $$
so the problem boils down to for what values of n makes the two exponential expressions directly above both prime simultaneously?
Plugging in 0,1,2 for n gives three more solutions (4,5) (16,17) (65536,65537) respectively $$\\$$
This is where I got stuck I don't know if there are any more solutions or how to prove there aren't any more solutions.
Numbers of the form of $2^{2^n}+1$ are called fermat numbers. There are only five known fermat numbers that are prime (3,5,17,255,65537). Finding all fermat primes seems to be a very challenging problem but I'm hoping that since this a subset of the problem that this might actually be doable.
Bonus fact: Gauss proved that all N sided polygons that can drawn using a ruler and compass if and only if $\phi(N)=2^a$ where $\phi()$ is the totient function.  N can be a power of two times the product of different fermat primes.
The problem in it's final form:
$$2^{2^{2^n}}+1\qquad2^{2^n}+1$$
for what values of $n$ are both of the above expressions prime simultaneously (other than 0,1,2)?
The pairs I have found for a and b are (2,3)(3,4)(4,5)(16,17)(65536,65537)


text:
Q: jQuery data() JSON Encoding issues In my current jQuery Mobile application I trap click events on a variety of HTML elements, extract the whole set of data-* attributes for the element using
var data = $(element).data();

package it all into JSON string
var json = JSON.stringify(data);

and send it off elsewhere for downstream processing.
The problem I have run into (and I am pretty sure it has only started with the recent versions of jQuery Mobile) is with some elements such as radios, checkboxes and buttons which have annonymous functions as part of the data() array. Serializing such functions is

*

*not relevent to my application

*more importantly, triggers a JavaScript along the lines of "An attempt was made to use an object that is no longer valid"...

By dint of some experiment I have found that the issue is to do with anonymous functions that turn up in the raw data() object as

*

*buttonElements

*mobile-checkboxradio

etc.  I then build my own object to serialize that is devoid of these offending entities.
This is OK but I have found another issue.  Change the jQM version and BOOM, the problem crops up all over again since the attribute name has changed (e.g. mobileCheckboxRadio in place of mobile-checkboxradio).
Question - could anyone suggest a more generic, attribute name agnostic, way of stripping out these offensive bits?  My own efforts and trying to figure out the typeof of the object attribute have failed since what I get is always a string.  I suppose I could always check for the phrase "annonymous function" in that string but that sounds clumsy.

A: I figured out a way to do this.  One can do the following
var data = $(element).data();
$.each(data,function(key,prop){if ('object' != typeof(prop)) /*do something */)}

Here is a fiddle demonstrating what happens with a radio button.  As you will note two of the data-* attributes returned are objects.  One of them, mobileCheckboxradio is an anonymous function.  Try to serialize data as is and you get an exception - which is being trapped and reported.  With the safely cloned object, which is shorn of the anon function all goes well.
This has the benefit of being "version proof".  Whether it is better than simply checking for the small handful of attributes that are liable to cause such errors is debatable.


text:
Q: Using blob images with a "fancybox" plugin I`m trying to display blob images from my db with a fancybox plugin (fancybox.net) like this:
<a class="fancybox" href="data:image/jpeg;base64,<?php echo base64_encode($vinyl['f_pic']); ?>" data-fancybox-group="4">

But that doesn't work. When i press on my eyey.png i get just blob data (in text) in my fancybox window.
Can you even do that ? Display images in blob format in a fancybox window ?

A: You probably want to link the fancy box to a page and put the code to display the image on that page.   I don't think you can use href=data: in a fancybox.


text:
Q: Optimze post call to save performnace I've Node application which is getting zip file from rest API request. I use the following code for file in size 2MB and it takes almost 10 sec , There is a way to improve performance here ?
The file should be extracted and saved in local system...
This codes works fine except the performance...

`1. if the request should invoked from client and its take to long
  when I should send the response? if I'll wait until the process
  finish this can take 10 sec...
2.Should I use promise in this case if yes can you provide example please with the following code(blue bird,q...)
3.there is a way to optimize somehow the performance

 var unzip = require('unzip');
    app.post('/', function(req, res) {
        var ext = unzip.Extract({
            path: 'C://myFolder'
        }).on('close', function() {
            res.sendStatus(200);
        }).on('error', function(err) {
            // res.sendStatus(500);
        });
        req.pipe(ext);
    });

A: The code isn't the problem, when I run the exact code it takes 750ms to extract a 7.5MB ZIP file. I used this to time it:
app.post('/', function(req, res) {
  console.time('unzip');
  var ext = unzip.Extract({ path: ... }).on('close', function() {
    console.timeEnd('unzip');
    res.sendStatus(200);
  }).on('error', function(err) {
    console.timeEnd('unzip');
    res.sendStatus(500);
  });
  req.pipe(ext);
});

Uploading the file:
$ ls -al test.zip
-rw-rw-r-- 1 robert wheel 7553635 Jul 17 09:31 test.zip
$ curl -XPOST localhost:3012 --data-binary @test.zip

This is on a Macbook Pro.
You don't say how exactly you're timing the code, but my guess is that it takes 10 seconds between the client starting the upload to until it receives a response, which introduces a lot of extra variables (speed of upload, network connection, particular middleware in your Express app, etc).
Run the extraction code completely separate from Express to see if that really is the bottleneck. Here's a simple standalone script to test with:
var fs    = require('fs');
var unzip = require('unzip');

console.time('unzip');
fs.createReadStream('test.zip').pipe(unzip.Extract({ path : ... })).on('close', function() {
  console.timeEnd('unzip');
});

If that takes 10 seconds for a 2MB file, I would think that your hardware is just wildly underpowered, which can't be solved from Node.js.


text:
Q: How to pass props from mobx-observable to mobx-react observable? I cant figure out mobx-react...
How do I pass props from a mobx observable to a mobx-react observer?
The code below doesn't works, but I feel like it should. Can someone tell me what is going wrong?
let mobxData = observable({information: "this is information"});

@observer class Information extends React.Component {
    render() {
        console.log(this.props.mobxData.information);
        return (

class: {this.props.mobxData.information}

        )
    }
};

const StatelessInformation = observer(({mobxData}) => {
    console.log(mobxData.information);
    return
stateless: {mobxData.information}

});

ReactDOM.render(

        <Information/>
        <StatelessInformation/>

,
    document.getElementById('app')
);

A: I've not done much mobx lately and not tested this but typically you'd have a provider somewhere and then use the @inject to pass stores as props
Consumer of information:
import { observer, inject } from 'mobx-react'

@inject('information')
@observer
class Information extends React.Component {
  render(){
    {this.props.information.foo}
  }
}

model level - very basic
import { observable, action } from 'mobx'

class Information {
  @observable foo = 'bar'
  @action reset(){
    this.foo = 'foo'
  }
}

export new Information()

Root provider level
import { Provider } from 'mobx-react'
import Information from ./information'

<Provider information={Information}>
  <Information />
</Provider>

// test it...
setTimeout(() => {
  Information.foo = 'back to foo'
}, 2000)

but ultimately you can probably work with whatever you pass in the Provider
Under the hood, the provider is probably just passing context via childContextType and contextType when a HOC memoises it and maps to props.


text:
Q: How can I iterate over a recordset within a stored procedure? I need to iterate over a recordset from a stored procedure and execute another stored procedure using each fields as arguments. I can't complete this iteration in the code. I have found samples on the internets, but they all seem to deal with a counter. I'm not sure if my problem involved a counter. I need the T-SQL equivalent of a foreach
Currently, my first stored procedure stores its recordset in a temp table, #mytemp. I assume I will call the secondary stored procedure like this:
while (something)
    execute nameofstoredprocedure arg1, arg2, arg3
end

A: You need to create a cursor to loop through the record set.
Example Table:
CREATE TABLE Customers
(
    CustomerId INT NOT NULL PRIMARY KEY IDENTITY(1,1)
    ,FirstName Varchar(50)
    ,LastName VARCHAR(40)
)

INSERT INTO Customers VALUES('jane', 'doe')
INSERT INTO Customers VALUES('bob', 'smith')

Cursor:
DECLARE @CustomerId INT, @FirstName VARCHAR(30), @LastName VARCHAR(50)

DECLARE @MessageOutput VARCHAR(100)

DECLARE Customer_Cursor CURSOR FOR
    SELECT CustomerId, FirstName, LastName FROM Customers

OPEN Customer_Cursor

FETCH NEXT FROM Customer_Cursor INTO
    @CustomerId, @FirstName, @LastName

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @MessageOutput = @FirstName + ' ' + @LastName

    RAISERROR(@MessageOutput,0,1) WITH NOWAIT

    FETCH NEXT FROM Customer_Cursor INTO
    @CustomerId, @FirstName, @LastName
END
CLOSE Customer_Cursor
DEALLOCATE Customer_Cursor

Here is a link to MSDN on how to create them.
http://msdn.microsoft.com/en-us/library/ms180169.aspx
This is why I used Raise Error instead of PRINT for output.
http://structuredsight.com/2014/11/24/wait-wait-dont-tell-me-on-second-thought/

A: It's very easy to loop through the rows in SQL procedure. You just need to use a cursor. Here is an example:
Let us consider a table Employee with column NAME and AGE with 50 records into it and you have to execute a stored procedure say TESTPROC which will take name and age parameters of each row.
create procedure CursorProc
as
begin
   declare @count bigint;
   declare @age varchar(500)
   declare @name varchar(500)
   select @count = (select count(*) from employee)
   declare FirstCursor cursor for select name, age from employee
   open FirstCursor
   while @count > 0
      begin
         fetch FirstCursor into @name, @age
         Exec TestProc @name, @age
         set @count = @count - 1
      end
   close FirstCursor
   deallocate FirstCursor
end

Make sure you deallocate the cursor to avoid errors.

A: try this (cursor free looping):
CREATE TABLE #Results  (RowID  int identity(1,1), Col1  varchar(5), Col2 int, ... )
DECLARE @Current  int
       ,@End      int
DECLARE @Col1  varchar(5)
       ,@Col2 int
       ,...

--you need to capture the result set from the primary stored procedure
INSERT INTO #Results
    (Col1, COl2,...)
    EXEC nameofstoredprocedure_1 arg1, arg2, arg3
SELECT @End=@@ROWCOUNT,@Current=0

--process each row in the result set
WHILE @Current<@End
BEGIN
    SET @Current=@Current+1

    SELECT
        @Col1=COl1, @Col2=Col2
        FROM #Results
        WHERE RowID=@Current

    --call the secondary procedure for each row
    EXEC nameofstoredprocedure_2  @Col1, @Col2,...

END

working example:
CREATE PROCEDURE nameofstoredprocedure_1
(@arg1 int, @arg2 int, @arg3 int)
AS
SELECT 'AAA',@arg1 UNION SELECT 'BBB',@arg2 UNION SELECT 'CCC',@arg3
GO

CREATE PROCEDURE nameofstoredprocedure_2
(@P1 varchar(5), @P2 int)
AS
PRINT '>>'+ISNULL(@P1,'')+','+ISNULL(CONVERT(varchar(10),@P2),'')
GO

CREATE TABLE #Results  (RowID  int identity(1,1), Col1  varchar(5), Col2 int)
DECLARE @Current  int
       ,@End      int
DECLARE @Col1  varchar(5)
       ,@Col2 int

INSERT INTO #Results
    (Col1, COl2)
    EXEC nameofstoredprocedure_1 111, 222, 333
SELECT @End=@@ROWCOUNT,@Current=0

WHILE @Current<@End
BEGIN
    SET @Current=@Current+1

    SELECT
        @Col1=COl1, @Col2=Col2
        FROM #Results
        WHERE RowID=@Current

    EXEC nameofstoredprocedure_2  @Col1, @Col2

END

OUTPUT:
(3 row(s) affected)
>>AAA,111
>>BBB,222
>>CCC,333


text:
Q: Python deleting half the elements in a list after iterating through it I've been completely stumped on this one:
I have the following python code:
def remove(self, widgets):
    for widget in widgets:
        widget_found = False
        for widget_sig in self.widgets:
            if widget_sig.id == widget:
                #remove all objects from selected widget
                widget_found = True
                to_remove = widget_sig.objs
                for obj in to_remove:
                    #objs are all intances of oo_canvas classes
                    obj.destroy()
                    self._build(widget, obj)
        if not widget_found:
            #if we iterated through the entire list and still couldn't find anything
            raise mockingbird_errs.InternalMockingbirdError("The requested widget was not registered with this builder: "+str(widget))

This should be pretty straight forward. The thing is, it never iterates through to_remove correctly. For some reason, it skips every other element. Even more baffling, is if I have it print the length of to_remove before and after the for loop, it prints 254 and 127. Huh? As far as I know, iterating through a list does not involve deleting every other element.
Am I missing something straightforward? What on earth is going on?

A:
... it skips every other element.

That's because you keep deleting them, shortening the list by 1. And then you move on to the next index. Either work backwards, or iterate over a copy of the list.


text:
Q: Deserialize JSON C# Json.net I am trying to deserialize a Json response from an API.
The data looks like this
{
"response": {
    "6112": {
        "ID": 6112,
        "Title": "AdditionalPhotos"
    },
    "5982": {
        "ID": 5982,
        "Title": "BikeRide"
    },
    "total_records": "20",
    "returned_count": 10,
    "returned_records": "1-10"

}
}

C# class:
public class Products
{
    public class Product
    {
        public string Id { get; set; }
        public string Title { get; set; }
    }
    public Product product { get; set; }
}

public class ss
{
    public Dictionary<string, Products.Product> Response { get; set; }
    public string total_records { get; set; }

}

Serialization code
 ss res = Newtonsoft.Json.JsonConvert.DeserializeObject<ss>(jsonData());

I can get it to work without the total_records entry and below by deserializng to a Dictionary <string , Product>. But I cannot figure out how to get it to work. This is the error I get

Error converting value "20" to type 'Products+Product'. Path 'response.total_records'

I know why I get the error, but I'm unsure how I can proceed without going in and substringing from total_records down. I have no control over the API data.
Edit: you guys are fast, I was still getting to putting the classes up

A: First you json is not valid one, it should look like this
{
 "response":{
    "6112":{
        "ID":"6112",
        "Title":"Additional Photos",
    },
    "5982":{
        "ID":"5982",
        "Title":"Bike Ride",
    },
    "total_records": "20",
    "returned_count": "10",
    "returned_records": "1-10",
    }
}

If you mean the response to contain list it should look like this
{
 "response":{
    "myArray": [
        {
            "ID":"6112",
            "Title":"Additional Photos",
        },
        {
            "ID":"5982",
            "Title":"Bike Ride",
        }
    ],
    "total_records": "20",
    "returned_count": "10",
    "returned_records": "1-10",
    }
}

So your code look like this
public class MyArray
{
    public string ID { get; set; }
    public string Title { get; set; }
}

public class Response
{
    public List<MyArray> myArray { get; set; }
    public string total_records { get; set; }
    public string returned_count { get; set; }
    public string returned_records { get; set; }
}

public class RootObject
{
    public Response response { get; set; }
}

A: If you have control over API response then please refer to Mzf's answer.
If you don't have control over API then it may not be possible to do this particular deserialization on one go. You might have to loop.
Here's my take.
Update
Modified my approach:
Created a class Response which inherits from Dictionary<string, Product>, and added the metadata parts like total_records, records_count to it's public properties. And created a JsonConverter that can deserialize JObject to Response class.
The logic used for deserialization is quite simple:

*

*Extract the metadata parts like total_records, records_count to variables.

*Then remove those metadata from the JObject, so that the key values becomes homogeneous.

*Now Json.net will be easily able to serialize JObject to Response object, as key values are homogenous.

*Assign the metadata extracted previously to the properties of Response object
public void Deserialize()
{
    var json = @"{
      'response':{
        '6112':{
           'ID':6112,
           'Title':'Additional Photos',
        },
        '5982':{
            'ID':5982,
            'Title':'Bike Ride',
        },
        'total_records': '20',
        'returned_count': 10,
        'returned_records': '1-10',
        }
    }";
    var responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject<ss>(json, new ResponseConverter());

}

public class Response : Dictionary<string, Product>
{
    public int total_records { get; set; }

    public int returned_count { get; set; }

    public string returned_records { get; set; }
}

public class Product
{
    public string Id { get; set; }
    public string Title { get; set; }
}

public class ss
{
    public Response Response { get; set; }
}

public class ResponseConverter : Newtonsoft.Json.JsonConverter
{
    private Response CreateResponse(Newtonsoft.Json.Linq.JObject jObject)
    {
        //preserve metadata values into variables
        int total_records = jObject["total_records"].ToObject<int>();
        var returned_records = jObject["returned_records"].ToObject<string>();
        var returned_count = jObject["returned_count"].ToObject<int>();

        //remove the unwanted keys
        jObject.Remove("total_records");
        jObject.Remove("returned_records");
        jObject.Remove("returned_count");

        //once, the metadata keys are removed, json.net will be able to deserialize without problem
        var response = jObject.ToObject<Response>();

        //Assign back the metadata to response object
        response.total_records = total_records;
        response.returned_count = returned_count;
        response.returned_records = returned_records;

       //.. now person can be accessed like response['6112'], and
       // metadata can be accessed like response.total_records

        return response;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Response);
    }

    public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
    {
        var jObject = Newtonsoft.Json.Linq.JObject.Load(reader);

        Response target = CreateResponse(jObject);

        serializer.Populate(jObject.CreateReader(), target);

        return target;
    }

    public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

A: In my opinion this is how the JSON file should look like:
{
"response": {
    "5982": {
        "ID": 5982,
        "Title": "BikeRide"
    },
    "6112": {
        "ID": 6112,
        "Title": "AdditionalPhotos"
    },
    "total_records": "20",
    "returned_count": 10,
    "returned_records": "1-10"
}
}

and this is how the class should look like
public class __invalid_type__5982
{
 public int ID { get; set; }
 public string Title { get; set; }
}

public class __invalid_type__6112
{
  public int ID { get; set; }
  public string Title { get; set; }
}

public class Response
{
 public __invalid_type__5982 __invalid_name__5982 { get; set; }
 public __invalid_type__6112 __invalid_name__6112 { get; set; }
 public string total_records { get; set; }
 public int returned_count { get; set; }
 public string returned_records { get; set; }
}

public class RootObject
{
 public Response response { get; set; }
}


text:
Q: NoMethodError in Users#show on rails project I keep getting a NoMethodError in Users#show.
undefined method `downcase' for nil:NilClass

I don't understand where exactly the error is when trying to use gravatar. I posted the relevant code to help assist with my question. Is there something I am missing?

show.html.erb

 Welcome to <%= @user.username %>'s page

        <%= gravatar_for @user %>

<%= @user.username %>'s articles

users_controller.rb
class UsersController < ApplicationController

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
        flash[:success] = "Welcome to the alpha blog #{@user.username}"
        redirect_to articles_path
    else
        render 'new'
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update(user_params)
      flash[:success] = "Your account was updated successfully"
      redirect_to articles_path
    else
      render 'edit'
    end
  end

  def show
    @user = User.find(params[:id])
  end

  private

    def user_params
      params.require(:user).permit(:username, :email, :password)
    end
end

application_helper.rb
module ApplicationHelper
    def gravatar_for(user)
        gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
        gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}"
        image_tag(gravatar_url, alt: user.username, class: "img-circle")
    end
end

A: The error is on the first line of the gravatar_for method.
user.email is nil, so you get this error when it tries to call downcase on a nil object. This happens because the user does not have an email.
You should check if the user has an email before you try to get his gravatar or just make sure every user has an email by putting a validation on User model.

A: I would guess that you're getting the error on this line:
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)

which would mean that user.email is returning nil


text:
Q: How to add rows with conditions together raw_data = {'id': [1,1,1,2,2,2,3,3,3],'v': [2,3,4,3,2,4,6,5,4]}
df = pd.DataFrame(raw_data, columns = ['id','v'])

I want to add "v" together if the "id" is the same. It should look like that:
       id  v
       1   9
       2   9
       3   15

I tried something like:
for i in range(1, max(df_tracks["id"])+1):
    if df_tracks["id"] == i:
        pass

But it looks pretty wrong.

A: You can use groupby to achieve this:
In [5]: df.groupby("id", as_index=False).sum()
Out[5]:
   id   v
0   1   9
1   2   9
2   3  15


text:
Q: TAB break for line split in a dictionary in Python I am attempting to run a python program that can run a dictionary from a file with a list of words with each word given a score and standard deviation. My program looks like this:
theFile = open('word-happiness.csv' , 'r')

theFile.close()

def make_happiness_table(filename):
   '''make_happiness_table: string -> dict
      creates a dictionary of happiness scores from the given file'''
   with open(filename) as f:
      d = dict( line.split('    ')  for line in f)
   return d

make_happiness_table("word-happiness.csv")

table = make_happiness_table("word-happiness.csv")
(score, stddev) = table['hunger']
print("the score for 'hunger' is %f" % score)

My .csv file is in the form
word{TAB}score{TAB}standard_deviation

and I am trying to create the dictionary in that way. How can I create such a dictionary so that I can print a word such as 'hunger' from the function and get its score and std deviation?

A: def make_happiness_table(filename):
   with open(filename) as f:
      d = dict()
      for line in f:
         word,score,std = line.split() #splits on any consecutive runs of whitspace
         d[word]=score,std # May want to make floats:  `d[word] = float(score),float(std)`
   return d

Note that if your word can have a tab character in it, but you're guaranteed that you only have 3 fields (word, score, std), you can split the string from the right (str.rsplit), only splitting twice (resulting in 3 fields at the end).  e.g. word,score,std = line.rsplit(None,2).
As mentioned in the comments above, you can also use the csv module to read these sorts of files -- csv really shines if your fields can be "quoted".  e.g.:
"this is field 0" "this is field 1" "this is field 2"

If you don't have that scenario, then I find that str.split works just fine.

Also, unrelated, but your code calls make_happiness_table twice (the first time you don't assign the return value to anything).  The first call is useless (all it does is read the file and build a dictionary which you can never use).  Finally, opening and closeing theFile at the beginning of your script is also just a waste since you don't do anything with the file there.

A: If you are sure your word will not have space, you can just split the line e.g.
word, score, stddev = line.split()

But if word can have space use tab char \t to split e.g.
word, score, stddev = line.split('\t')

But for a very generic case when word may have tab itself use the csv module
reader = csv.reader(filename, dialect='excel-tab')
for word, score, stddev  in reader:
    ...

and then you can create dict of word and score, stddev e.g.
word_dict[word] = (score, stddev)


text:
Q: How to install RabbitVCS in Ubuntu 11.10 Ocelot? I tried to install RabbitVCS on my machine following this guide but failed.
I'm stuck since the guide is officially from RabbitVCS. What should I do?

A: Looks like the PPAs are not available (going by the 404 and a cursory glance over here). I'd wait a bit till the PPAs are available.

A: First, download the tarball from here http://code.google.com/p/rabbitvcs/downloads/detail?name=rabbitvcs-0.15.0.5.tar.bz2&can=2&q=
Then, you'll need to extract it somewhere (I put it on the desktop)
Next step, open a terminal and:
cd ~/Desktop/rabbitvcs-0.15.0.5/

Then run the following command:
sudo python setup.py install --install-layout=deb

Next, run the following command:
sudo cp ./clients/nautilus-3.0/RabbitVCS.py /usr/share/nautilus-python/extensions

then run:
nautilus -q

then:
pgrep -f service.py | xargs kill

then:
nohup nautilus > /dev/null &

Good luck ;P


text:
Q: Azure maps indoor module : How to draw a path between two points in indoor navigation using azure maps? I am working on POC for Azure maps indoor navigation using WEB SDK. For this, I have followed all the documentation (Using creator upload sample_drawing_package.zip, you can check this link for doc: Use Creator to create indoor maps.
Requirement: I want to to draw a path in between two points (these points configured as datasets/tiles/units in indoor map).
**For more Info, please check this GitHub query  conversation : Get Navigable Lat and Long between two Units
I request someone help me on this.

A: Indoor routing is not yet supported, but is planned.


text:
Q: How to handle a generic dictionary whose types are unknown and don't matter? If 'value' is an incoming generic dictionary whose types are unknown/don't matter, how do I take its entries and put them into a target dictionary of type IDictionary<object, object> ?
if(type == typeof(IDictionary<,>))
{
    // this doesn't compile
    // value is passed into the method as object and must be cast
    IDictionary<,> sourceDictionary = (IDictionary<,>)value;

    IDictionary<object,object> targetDictionary = new Dictionary<object,object>();

    // this doesn't compile
    foreach (KeyValuePair<,> sourcePair in sourceDictionary)
    {
         targetDictionary.Insert(sourcePair.Key, sourcePair.Value);
    }

    return targetDictionary;
}

EDIT:
Thanks for the responses so far.
The problem here is that the argument to Copy is only known as type 'object'. For example:
public void CopyCaller(object obj)
{
    if(obj.GetType() == typeof(IDictionary<,>)
         Copy(dictObj); // this doesn't compile
}

A: Make your method generic as well and then you'll be able to do what you're doing.  You won't have to change your usage pattern since the compiler will be able to infer generic types from input types.
public IDictionary<object, object> Copy(IDictionary<TKey, TValue> source)
{

    IDictionary<object,object> targetDictionary = new Dictionary<object,object>();

    foreach (KeyValuePair<TKey, TValue> sourcePair in sourceDictionary)
    {
         targetDictionary.Insert(sourcePair.Key, sourcePair.Value);
    }

    return targetDictionary;
}

If you don't really need to convert it from IDictionary<TKey, TValue> to IDictionary<object, object> then you can use the copy constuctor of Dictionary<TKey, TValue> which accepts another dictionary as input and copies all values--just like you're doing now.

A: You can exploit the fact that generic dictionaries implement the IDictionary interface.
public static Dictionary<object, object> CreateCopy(IDictionary source)
{
    var copy = new Dictionary<object, object>(source.Count);
    foreach (DictionaryEntry entry in source)
    {
        copy.Add(entry.Key, entry.Value);
    }
    return copy;
}

Usage example:
var source = new Dictionary<int, string>() { { 1, "Foo" }, { 2, "Bar" }, };
var copy = CreateCopy(source);
Console.WriteLine(String.Join(", ", copy.Values));

Output:
Foo, Bar

A: Here is a method (don't leave it as static, unless you need it to be, I wrote it in a quick console app) that basically converts a Dictionary of any type to an object/object dictionary.
    private static Dictionary<object,object> DeTypeDictionary<T,U>(Dictionary<T,U> inputDictionary)
    {
        Dictionary<object, object> returnDictionary = new Dictionary<object, object>();
        foreach(T key in inputDictionary.Keys)
        {
            if( (key is object) && (inputDictionary[key] is object))
            {
                returnDictionary.Add(key, inputDictionary[key]);
            }
            else
            {
                //sorry these aren't objects. they may be dynamics.
                continue;
            }

        }
        return returnDictionary;
    }

...and here is how you use it...
        Dictionary<string, DateTime> d = new Dictionary<string, DateTime>();
        d.Add("rsgfdg", DateTime.Now);
        d.Add("gfdsgd", DateTime.Now);

        Dictionary<object, object> newDictionary = DeTypeDictionary<string, DateTime>(d);

A: So you have an object that may be a Dictionary and you want to:

*

*Test it's a dictionary

*Act on it appropriately if it is

Let's start with a generic function that does what you want if you knew the type arguments:
class Bar
{
    public static void Foo<TKey, TValue>(Dictionary<TKey, TValue> input) { ... }
}

Now we'll just have to do some reflection
bool TryHandleDictionary(object o)
{
    var t = o.GetType();
    if (!t.IsGenericType || t.GetGenericTypeDefinition() != typeof(Dictionary<,>)) return false;

    var m = typeof(Bar).GetMethod("Foo", BindingFlags.Public | BindingFlags.Static);
    var m1 = m.MakeGenericMethod(t.GetGenericArguments());
    m1.Invoke(null, new[] { o });
    return true;
}

A: This may be a fix for you but you'll need .net 3.5 or greater to use the var keyword.
// this should compile
foreach (var sourcePair in sourceDictionary)
{
     targetDictionary.Insert(sourcePair.Key, sourcePair.Value);
}


text:
Q: In JIRA is there a way to create a nested table? The JIRA documentation does not mention a way to create a nested table something like

|outer-col1|outer-col2|
|col1 val1||inner-col1|inner-col2|
           |icol1 val1|icol2 val1|
           |icol1 val2|icol2 val2|
|col1 val2||col2 val2|

(or) atleast something where I can span a multiple rows for a column value
i.e.

|outer-col1|outer-col2|outer-col-3
|col1 val1 |col2 val1a|col3 val1a|
           |col2 val1b|col3 val1b|
|col1 val2||col2 val2 |col3 val2 |

The only way I can span now is to have empty values in the column and have the reader assume that it represents the previous rows value for that column.

A: Found a way around to make nested tables at below linked page
https://community.atlassian.com/t5/Confluence-questions/Nested-table-in-wiki-markup-Confluence-4/qaq-p/18355
The solutions suggest many tags that can be used to achieve this. A simple one is {panel}  tag. Just wrap the Inner table inside two {panel} tags.
Below is a sample and its result
Sample
||Tabe1Column1||Table1Column2||
|item1.1|item1.2|
|item2.1|Sub table {panel}
||Table2Coumn1||Table2Column2||
|sub item1.1|sub item 1.2|
|sub item 2.1|sub item 2.2|{panel}|

A: No, this is not supported in JIRA out of the box.
However, the JEditor add-on that is available on the marketplace does support this.
Since JEditor replaces JIRA's wiki editor it can have quite some impact on a JIRA instance, depending on how your users are used to work with mark-up. It can also affect other add-ons, so best to test properly before buying.