text:
Q: JQuery confirm dialog not firing ASP Button OnClick server side event upon user's confirmation I want to show modal confirmation dialog on ASP Button (btnRejectAll) click event and once user selects 'OK' in the modal dialog, it needs to raise the OnClick server side event of button "btnRejectAll". The following code shows modal confirmation dialog on click, but once we hit OK button, it is not firing server side event. Can anyone help me with this?
Here is my code.
<script language="javascript" type="text/javascript">

    $(function() {

        $("#dialogReject").dialog({
            autoOpen: false,
            height: 300,
            width: 350,
            modal: true,
            buttons: {
                "Reject": function() {
                    $(this).dialog("close");
                    return true;
                },
                Cancel: function() {
                    $(this).dialog("close");
                    return false;
                }
            }
        });

        $("#btnRejectAll").click(function(event)
        {
            event.preventDefault();

            $("#dialogReject").dialog("open");
        });

    });

<asp:Button ID="btnRejectAll" runat="server" Text="Reject All" OnClick="btnRejectAll_OnClick" />

A: You prevent the default action on click of btnRejectAll but you never invoke any action on the 'Reject' action. I'm not familiar with ASP.NET but from the looks of your markup, it looks like you're cancelling the call to btnRejectAll_OnClick. If that's a JavaScript function, then you could do this:
"Reject": function() {
             $(this).dialog("close");
             btnRejectAll_OnClick();
             return true;
          },

If it's not (and I suspect it isn't) then it's probably triggering a submit of a form. So you could instead do this:
"Reject": function() {
             $(this).dialog("close");
             $('#form').submit();
             return true;
          },

A: I found a way to trigger the button's server side event on dialog confirmation. Here is the code.
function ConfirmReject(detailId) {

        var leaveId = $("#hdnLeaveReqId").val();

        $("#dialogReject").dialog({
            autoOpen: true,
            height: 300,
            width: 350,
            modal: true,
            buttons: {
                "Reject": function() {
                    $.ajax({
                        type: "POST",
                        url: "LeaveRequestForm.aspx/RejectLeave",
                        data: "{'LeaveReqId':'" + leaveId + "', 'detailId':'" + detailId
                                + "', 'rejectReason':'" + $("#txtRejectReason").val() + "'}",
                        dataType: 'json',
                        contentType: "application/json; charset=utf-8",
                        success: function(msg) { location.reload(); }
                    });

                    $(this).dialog('close');
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            }
        });

        return false;
    }

 <asp:Button ID="btnRejectAll" runat="server" Text="Reject All"
                        OnClientClick="return ConfirmReject(0);" />

In CodeBehind class:
<WebMethod()> _
Public Shared Function RejectLeave(ByVal LeaveReqId As Integer, ByVal detailId As Integer, ByVal rejectReason As String) As String

    'Do Something here

    Return "success"

End Function


text:
Q: Discord tag regular expression validation Google Forms Is there any way you can use a regular expression in Google Forms to check if their input matches a pattern for a Discord tag? I already tried this: #[0-9]{4}$, but that's only valid for input that starts with a '#' followed by 4 numeric digits. I know this regex (next line) works for Discord tags, maybe there is a way to convert that to a regular expression in Google Forms?
/^((.+?)#\d{4})/

A Discord tag is constructed by their username followed by an '#' and then finished with 4 numbers. A few examples are:

*

*Anna#1234

*Bob#5601

*Ryan Peterson#5640

Thanks in advance!

A: EDIT (following OP's revised question)
You can also use the following
.+#\d{4}

As mentioned on The Discord Wiki

A "Discord tag" is the combination of a username and their discriminator (a 4-digit number). The tag always appears as username#discriminator.

Not all regular expressions are supported in Google Forms validation.
In this case the regular expression (regex) you should use is
.+\d{4}$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to read multiple yaml files in zipped folder I want to read multiple yaml files containing in two zipped folders. The zipped folder contains nested folders.
The directory structure is as below:
C:
- file1.zip
  - aa
    - bb
      - cc
        - x.yaml
        - y.yaml
        - z.yaml
- file2.zip
  - aa
    - bb
      - cc
        - x.yaml
        - y.yaml
        - z.yaml

I am unable to read the yaml files within the zipped folder. I am getting error as File Not Found Exception even though the file is present.
I have pasted the code below.
def yaml_as_dict(filename):
    my_dict = {}
    with open(filename, 'r') as fp:
        docs = yaml.safe_load_all(fp)
        for doc in docs:
            for key, value in doc.items():
                my_dict[key] = value
    return my_dict

def extract_file1(file1):
    with zipfile.ZipFile(file1) as zip:
        text_files = zip.namelist()
        for t in text_files:
            print(t)
            yaml_as_dict(t)

def extract_file2(file2):
    with zipfile.ZipFile(file2) as zip:
        text_files = zip.namelist()
        for t in text_files:
            print(t)
            yaml_as_dict(t)

A: As I said in a comment, the members of the .zip archive must first be extracted (and uncompressed) into a actual file order to apply your yaml_as_dict() function to them. You also don't need to have a different extract() function for each filename when the only thing different between it the name of the file being process.
The code below illustrates how all of these things can be done:
import os
from pprint import pprint
from tempfile import TemporaryDirectory
import yaml
import zipfile

def yaml_as_dict(filename):
    my_dict = {}
    with open(filename, 'r') as fp:
        docs = yaml.safe_load_all(fp)
        for doc in docs:
            for key, value in doc.items():
                my_dict[key] = value
    return my_dict

def extract_files(zip_file_path):
    """Extract YMAL files from zip file and convert them to Python dicts."""
    with TemporaryDirectory() as tempdir:
        with zipfile.ZipFile(zip_file_path) as zip:
            for mbr_info in (info for info in zip.infolist() if not info.is_dir()):
                # Extract (and print) data from yaml files.
                if os.path.splitext(mbr_info.filename)[1].lower() == '.yaml':
                    tmpfile_path = zip.extract(mbr_info, path=tempdir)
                    print(f'=> Contents of {mbr_info.filename!r}:')
                    as_dict = yaml_as_dict(tmpfile_path)
                    pprint(as_dict, width=90)
                    print()

if __name__ == '__main__':

    zip_file_path1 = r'C:\path\to\YAML_Files1.zip'
    extract_files(zip_file_path1)


text:
Q: How can I convert this code to Facebook SDK v4? I need help how can I convert this code into SDKv4. Cause this code is not working already and giving me redirect loop or something about looping of redirects.
<?php
require '../config.php';
require 'lib/facebook/facebook.php';

$facebook = new Facebook(array(
        'appId'     => $appID,
        'secret'    => $appSecret,
        ));

//get the user facebook id
$user = $facebook->getUser();

if($user){

    try{
        //get the facebook user profile data
        $getUserInfo = $facebook->api('/me');
        $params = array('next' => $base_url.'logout.php');
        //logout url
        $logout =$facebook->getLogoutUrl($params);
    }catch(FacebookApiException $e){
        error_log($e);
        $user = NULL;
    }
}

if(!empty($user)){
//login url

    $userInfo = $getUserInfo;
    $_SESSION['ses_id'] = md5(microtime());
    $buid = $userInfo['id'];
    $user = mysql_query("SELECT * FROM `scgfx_user_accounts` WHERE `fbid`='".$buid."'");

    if(mysql_num_rows($user)>0) {
        $userdata = mysql_fetch_assoc($user);

        if($userdata['last_request_time']<=(time()-10800)) {
            mysql_query("INSERT INTO `scgfx_chats` VALUES('','Welcome back to ".GLOBAL_NAME." ".$userdata['fbname']."','0','global','".time()."')");
        }
        mysql_query("UPDATE `scgfx_user_accounts` SET
                                            `gender`            =   '".$userInfo['gender']."',
                                            `ses_id`            =   '".$_SESSION['ses_id']."',
                                            `active`            =   '1',
                                            `sign_time`         =   CURRENT_TIMESTAMP,
                                            `last_request_time` =   '".time()."',
                                            `ip_address`        =   '".$_SERVER['REMOTE_ADDR']."' WHERE `fbid`='".$userInfo['id']."'");

    } else {
        mysql_query("INSERT INTO `scgfx_user_accounts` VALUES('',
                                            '".$userInfo['id']."',
                                            '".$userInfo['name']."',
                                            '".$userInfo['gender']."',
                                            '0',
                                            '".$_SESSION['ses_id']."',
                                            '1',
                                            CURRENT_TIMESTAMP,
                                            '".time()."',
                                            '".$_SERVER['REMOTE_ADDR']."','0','0')");
        mysql_query("INSERT INTO `scgfx_chats` VALUES('','We have a new member :) Welcome to ".GLOBAL_NAME." ".$userInfo['name']."!
Enjoy your stay!','0','global','".time()."')");
    }

    if(isset($_SESSION['ses_id'])) {
        $getUserInfo = mysql_query("SELECT * FROM `scgfx_user_accounts` WHERE `ses_id`='".$_SESSION['ses_id']."'");
        if(mysql_num_rows($getUserInfo)>0) {
            while($data=mysql_fetch_assoc($getUserInfo)) {
                $_SESSION['fbid'] = $data['fbid'];
                $_SESSION['name'] = $data['fbname'];
                $_SESSION['gender'] = $data['gender'];
                $_SESSION['acctype'] = $data['acctype'];
                $_SESSION['points'] = $data['points'];
            }
        } else {
                    die("Invalid Session ID");
        }
    ?>

        <?php
    }
}

else {
    $loginurl = $facebook->getLoginUrl(array(
                'scope'         => 'email,read_stream,offline_access,publish_stream,user_status,user_photos',
                'display'=>'popup'
                ));
    header('Location: '.$loginurl);
}
?>

I think this is the only way I can get this code working.

A: I would try something like this:
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\GraphUser;

session_start();
FacebookSession::setDefaultApplication('app-id','app-secret');
$helper = new FacebookRedirectLoginHelper('this-same-url');
$session = $helper->getSessionFromRedirect();

if($session){
  $user_profile = (new FacebookRequest(
    $session, 'GET', '/me'
  ))->execute()->getGraphObject(GraphUser::className());

  echo "Name: " . $user_profile->getName();
  echo 'Token: ' . $session->getToken() . '
';
} else {
  // Create here your login button
  $loginUrl = $helper->getLoginURL(array('public_profile,'));
  echo("Login URL:");
  echo($loginUrl);
}

Please note that this is a rough sketch and you should never echo the user token. For a more detailed explanation, please read https://developers.facebook.com/docs/php/gettingstarted/4.0.0


text:
Q: In what part of the Wordpress core does the users table and usermeta table get joined? I have been trying to work out just where in the massive jungle of Wordpress include classes the usermeta table is joined onto the users table and if so, how does it work?
The one confusing thing about the usermeta table to me is that it is using key/value fields for the database fields and not actual values like first_name or last_name. How does Wordpress know which fields to pull out by default and are there hooks, actions and filters for adding and retrieving data from the usermeta field?

A: I'm not 100% what you are asking, it seems like several questions?  But here goes:
 $meta_value = get_user_meta($user_id, $key, $single);

For example:
 $first_name = get_user_meta($user_id, 'first_name', true);

As for adding hooks I think this answer might be what you are looking for?

*

*How To Add Custom Form Fields To The User Profile Page?
UPDATE
Based on some follow up comments I'll add:

*

*The function get_user_metavalues($user_ids) from /wp-includes/user.php will return an array of user data arrays.

*The function get_userdata() retrieves user values using get_user_metavalues($user_ids) from /wp-includes/pluggable.php and returns a user data object.

*User Meta is managed through the generic metadata functions found in /wp-includes/meta.php so if you are looking for a SQL JOIN between wp_users and wp_usermeta   you are not likely to find one. That file includes these functions:
add_metadata($meta_type,$object_id,$meta_key,$meta_value,$unique=false)
update_metadata($meta_type,$object_id,$meta_key,$meta_value,$prev_value='')
delete_metadata($meta_type,$object_id,$meta_key,$meta_value='',$delete_all=false)
get_metadata($meta_type,$object_id,$meta_key='',$single=false)
update_meta_cache($meta_type,$object_ids)


text:
Q: How to force MySQL out of TRADITIONAL mode? I have an old application that started failing after an upgrade from MySQL 5.0 to 5.1.
A bit of research indicated this is due to "strict mode" which prevents inserting certain types of "invalid" values which previously were just automatically converted to something reasonable.
I tried SET @@SESSION.sql_mode = '' and SET @@GLOBAL.sql_mode = '' but I still get the error.
Also tried commenting out sql_mode in the my.ini.
Is there a stronger, sort of "nuclear" option to fix this?

A: In my application I usually make sure that the MySQL connection is using traditional mode by issuing
SET SESSION sql_mode = 'ANSI_QUOTES,TRADITIONAL'

on each new connection. I presume that if you just issue
SET SESSION sql_mode = ''

on each new connection, you will have solved the problem.
You should be able to change the default SQL mode for new connections by issuing
SET GLOBAL sql_mode = ''

but you must use an account with sufficient privileges to do this or it won't work.
I think that if you want to make sure a particular SQL mode is in operation for your application, the most robust way to do so is to set it for each and every new connection.

A: To allow invalid dates, you need:
SET sql_mode = 'ALLOW_INVALID_DATES';

But you'd better fix your application.


text:
Q: Modify object position with AngularJS works just one time I got an array of object call $scope.postsATraiter, and I got a function who give a random x y value for each post.
 $scope.posAleatoire = function () {
        var w = window.innerWidth;
        var h = window.innerHeight;
        for (var i = 0; i < $scope.postsATraiter.length; i++) {
            var l = parseInt(Math.random() * (w - 200));
            var t = parseInt(Math.random() * (h - 200));
            $('#target'+i).css({
                'left': l + 'px',
                'top': t + 'px',
                'height' : '200px'
            })
        }
    }

This works fine but only if I use it in this function :
Posts.query({}, function() {
    $scope.postsATraiter = $scope.posts;
    $scope.posAleatoire();
});

This function is call  before every one, and she get all the post in my database and store it into $scope.postsATraiter, if I use posAleatoire in another place in my code it does nothing, why ?
I post the HTML if it can help.

A: It is because $scope.posAleatoire() is dependent on $scope.postsATraiter, so that's why  when you call $scope.posAleatoire() outside that function were you are assigning values to  $scope.postsATraiter, does not work.
Before calling $scope.posAleatoire(), you have to varify that $scope.postsATraiter has some values.


text:
Q: How to make new DRF 3.6 built-in documentation work? I tried to setup the new Django Rest Framework built-in documentation, following the (unusually succint) documentation.
For now, I get a page with a 401 unauthorized error, and I can't see my endpoints. When clicking on session authentication, I get the message bellow.

However, I'm already session-logged as a superuser in another tab.
Here is the code I have so far:
urls.py
root_urlpatterns = [
    url(r'^api/v', include('api.urls', namespace='api')),  # Api endpoints
    url(r'^admin/', admin.site.urls, name="admin"),  # Admin
    url(r'^docs/', include_docs_urls(title='My API')),  # Built-in DRF documentation
]

urlpatterns = [
    url(r'^backend/', include(root_urlpatterns))
]

api/urls.py
endpoints_urlpatterns = [

    url(regex=r'^customers/activate/$',
        view=views_customer.ActivateCustomerView.as_view(),
        name="activate-customer"),

]

VERSION = 1

urlpatterns = [
    url(r'^{}/'.format(VERSION), include(endpoints_urlpatterns))
]

All required packages (coreapi, Pygments, markdown) are pip-installed.
Any idea? Thanks a lot.

A: Ensure that SessionAuthentication is there too:
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),


text:
Q: Is it possible to execute a javascript in a new window with window.location.href? I am trying to open a new window and execute a javascript code on the new page.
I'm not really sure why it doesn't execute the code - maybe it's not possible like this - anyway, the new window opens but the javascript doesn't get executed.
Here is my code:
var nstart = window.open("http://examplepage.html");
function loginnow(){
var htmlstring = "javascript: var zTextFields = window.document.getElementsByTagName(\"input\"); for (var i=0; i < zTextFields.length; i++) {thefield=zTextFields[i].name; if (!thefield) thefield=zTextFields[i].id; if (thefield == \"login\") zTextFields[i].value=\"_ext_cancom\"; if (thefield == \"password\")zTextFields[i].value=\"canfinag?!\";} window.document.getElementById(\"sign-in\").click();";

nstart.location.href = htmlstring;
}

nstart.addEventListener('load', loginnow, true);

Is it even possible to execute code like this? Please help ^-^
I'm also using '\' as an escape character so I can use " in the string ->  \"
When I replace the \" with " and directly inject it into the page the script works fine...

A: Maybe you can add the javascript you want to execute in the new new page, and then make it run when document ready. So you will can just open the new page, JS will run automatically

A: If the new window is on the same domain you can access the contents by doing something like this.
var nstart = window.open("http://examplepage.html");

function loginnow() {
  var zTextFields = nstart.document.getElementsByTagName("input");
  for (var i=0; i < zTextFields.length; i++) {
    thefield=zTextFields[i].name;
    if (!thefield)
      thefield=zTextFields[i].id;
    if (thefield == "login")
      zTextFields[i].value="_ext_cancom";
    if (thefield == "password")
      zTextFields[i].value="canfinag?!";
  }
  nstart.document.getElementById("sign-in").click();
}

nstart.addEventListener('load', loginnow, true);

You shouldn't really try to inject code onto the new window but you can access the dom and run javascript from the parent window.


text:
Q: Fatfree routing with PHP built-in web server I'm learning fatfree's route and found it behaves unexpected.
Here is my code in index.php:
$f3 = require_once(dirname(dirname(__FILE__)). '/lib/base.php');
$f3 = \Base::instance();

echo 'received uri: '.$_SERVER['REQUEST_URI'].'<br>';

$f3->route('GET /brew/@count',
    function($f3,$params) {
        echo $params['count'].' bottles of beer on the wall.';
    }
);

$f3->run();

and here is the URL which I access: http://xx.xx.xx.xx:8090/brew/12
I get a 404 error:
received uri: /brew/12
Not Found

HTTP 404 (GET /12)

the strange thing is that the URI in F3 is now "/12" instead of "/brew/12" and I guess this is the issue.
When I check the base.php (3.6.5), $this->hive['BASE'] = "/brew" and $this->hive['PATH'] = "/12".
But if F3 only uses $this->hive['PATH'] to match the predefined route, it won't be able to match them.
If I change the route to:
$f3->route('GET /brew',

and use the URL: http://xx.xx.xx.xx:8090/brew, then the route matches without issue.
In this case, $this->hive['BASE'] = "" and $this->hive['PATH'] = "/brew". If F3 compares the $this->hive['PATH'] with predefined route, they match each other.
BTW, I'm using PHP's built-in web server and since $_SERVER['REQUEST_URI'] (which is used by base.php) returns the correct URI, I don't think there is anything wrong with the URL rewrite in my .htrouter.php.
Any idea? What did I miss here?
add the content of .htrouter.php here
<?php

#get the relative URL
$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

#if request to a real file (such as a html, image, js, css) then leave it as it is
if ($uri !== '/' && file_exists(__DIR__  . $uri)) {
    return false;
}

#if request virtual URL then pass it to the bootstrap file - index.php
$_GET['_url'] = $_SERVER['REQUEST_URI'];
require_once __DIR__ . './public/index.php';

A: Your issue is directly related to the way you're using the PHP built-in web server.
As stated in the PHP docs, here's how the server handles requests:

URI requests are served from the current working directory where PHP was started, unless the -t option is used to specify an explicit document root. If a URI request does not specify a file, then either index.php or index.html in the given directory are returned. If neither file exists, the lookup for index.php and index.html will be continued in the parent directory and so on until one is found or the document root has been reached. If an index.php or index.html is found, it is returned and $_SERVER['PATH_INFO'] is set to the trailing part of the URI. Otherwise a 404 response code is returned.
If a PHP file is given on the command line when the web server is started it is treated as a "router" script. The script is run at the start of each HTTP request. If this script returns FALSE, then the requested resource is returned as-is. Otherwise the script's output is returned to the browser.

That means that, by default (without a router script), the web server is doing a pretty good job for routing unexisting URIs to your document root index.php file.
In other words, provided your file structure is like:
lib/
    base.php
    template.php
    etc.
public/
    index.php

The following command is enough to start your server and dispatch the requests properly to the framework:
php -S 0.0.0.0:8090 -t public/

Or if you're running the command directly from the public/ folder:
cd public
php -S 0.0.0.0:8090

Beware that the working directory of your application depends on the folder from which you call the command. In order to leverage this value, I strongly advise you to add chdir(__DIR__); at the top of your public/index.php file. This way, all subsequent require calls will be relative to your public/ folder. For ex: $f3 = require('../lib/base.php');
Routing file-style URIs
The built-in server, by default, won't pass unexisting file URIs to your index.php, as stated in:

If a URI request does not specify a file, then either index.php or index.html in the given directory are returned

So if you plan to define some routes with dots, such as:
$f3->route('GET /brew.json','Brew->json');
$f3->route('GET /brew.html','Brew->html');

Then it won't work because PHP won't pass the request to index.php.
In that case, you need to call a custom router, such as the .htrouter.php you were trying to use. The only thing is that your .htrouter.php has obviously been designed for a different framework (F3 doesn't care about $_GET['url'] but cares about $_SERVER['SCRIPT_NAME'].
Here's an exemple of .htrouter.php that should work with F3:
// public directory definition
$public_dir=__DIR__.'/public';

// serve existing files as-is
if (file_exists($public_dir.$_SERVER['REQUEST_URI']))
    return FALSE;

// patch SCRIPT_NAME and pass the request to index.php
$_SERVER['SCRIPT_NAME']='index.php';
require($public_dir.'/index.php');

NB: the $public_dir variable should be set accordingly to the location of the .htrouter.php file.
For example if you call:
php -S 0.0.0.0:8090 -t public/ .htrouter.php

it should be $public_dir=__DIR__.'/public'.
But if you call:
cd public
php -S 0.0.0.0:8090 .htrouter.php

it should be $public_dir=__DIR__.

A: OK, I checked the base.php and found out when f3 calculates the base URI, it uses $_SERVER['SCRIPT_NAME'].
$base='';
if (!$cli)
    $base=rtrim($this->fixslashes(
        dirname($_SERVER['SCRIPT_NAME'])),'/');

if we have web server directly forward all requests to index.php, then
_SERVER['SCRIPT_NAME'] = /index.php, and in this this case, base is ''.
if we use URL rewriting via .htrouter.php to index.php, then
_SERVER['SCRIPT_NAME'] = /brew/12, and in this this case, base is '/brew' which causes the issue.
Since I'm going to use the URL rewrite, I have to comment out the if statement and make sure base =''.
Thanks xfra35 for providing the clue.

A: Apache like php router here:
It can url rewrite.
https://github.com/kyesil/QPHP/blob/master/router.php
Usage:
php -S localhost:8081 router.php


text:
Q: Multi threading wait() notify() Can someone please tell me whats wrong with the current program
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package evenodd;

import java.util.logging.Level;
import java.util.logging.Logger;

public class EvenOdd {

    public static Integer i;
    public static Integer y;

    public static void main(String[] args) {
        EvenOdd eo = new EvenOdd();
        EvenThread et = new EvenThread(eo);
        et.setName("EvenThread");
        OddThread ot = new OddThread(eo);
        ot.setName("OddThread");
        et.start();
        ot.start();

    }
}
class EvenThread extends Thread{
    EvenOdd eo;
    public EvenThread(EvenOdd eo)
    {
        this.eo=eo;
    }
    public void run()
    {

        System.out.println("inside run "+Thread.currentThread().getName());
        if(eo.y==null)
        {
        try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            Logger.getLogger(EvenThread.class.getName()).log(Level.SEVERE, null, ex);
        }
        }

        synchronized(eo)
        {

       if(eo.y==null)
       {
           eo.y=2;
           System.out.println("Even Number " + eo.y);

       }
       else if(eo.y!=null)
       {
           System.out.println("Even Number " + eo.y+2);
       }
       System.out.println("notifying "+Thread.currentThread().getName());
       eo.notify();

    }
    }

}

class OddThread extends Thread{
     EvenOdd eo;
    public OddThread(EvenOdd eo)
    {
        this.eo=eo;
    }

   public void run()
   {

       System.out.println("inside run "+Thread.currentThread().getName());
       synchronized(eo)
       {

       if(eo.i==null)
       {
           eo.i=1;
           System.out.println("Odd NUmber " + eo.i);
       }
       else if(eo.i!=null)
       {
           System.out.println("Odd NUmber " + eo.i+2);
       }
         try {
             System.out.println("waiting "+Thread.currentThread().getName());
             eo.wait();
         } catch (InterruptedException ex) {
             Logger.getLogger(OddThread.class.getName()).log(Level.SEVERE, null, ex);
         }
   }
   }
}

When EvenThread notifies why control is not going to OddThread. I am using teo threads to print odd and even numbers, one thread to print odd numbers and one thread to print even numbers.
First i am trying to print 1 and 2 and later increment both  values by 2.

A: How do you expect to add 2 if your code already passed the point of adding 2 and you dont have any loop to return there ?

A: Your code does exactly what you've coded it to do.

*

*You start both threads

*even goes to sleep for 200 ms

*odd initializes the shared variable to 1, then goes to sleep waiting for even

*even wakes up, increments the shared variable to 2, notifies, and then exits

*odd wakes up by the notification, then exits.

If you want to endlessly print numbers, you need to loop in both threads and restructure your code a little.


text:
Q: How do I robustly parse malformed CSV? I'm processing data from government sources (FEC, state voter databases, etc). It's inconsistently malformed, which breaks my CSV parser in all sorts of delightful ways.
It's externally sourced and authoritative. I must parse it, and I cannot have it re-input, validated on input, or the like. It is what it is; I don't control the input.
Properties:

*

*Fields contain malformed UTF-8 (e.g. Foo \xAB bar)

*The first field of a line specifies the record type from a known set. Knowing the record type, you know how many fields there are and their respective data types, but not until you do.

*Any given line within a file might use quoted strings ("foo",123,"bar") or unquoted (foo,123,bar). I haven't yet encountered any where it's mixed within a given line (i.e. "foo",123,bar) but it's probably in there.

*Strings may include internal newline, quote, and/or comma character(s).

*Strings may include comma separated numbers.

*Data files can be very large (millions of rows), so this needs to still be reasonably fast.

I'm using Ruby FasterCSV (known as just CSV in 1.9), but the question should be language-agnostic.
My guess is that a solution will require preprocessing substitution with unambiguous record separator / quote characters (eg ASCII RS, STX). I've started a bit here but it doesn't work for everything I get.
How can I process this kind of dirty data robustly?
ETA: Here's a simplified example of what may be in single file:

"this","is",123,"a","normal","line"
"line","with "an" internal","quote"
"short line","with
an
"internal quote", 1 comma and
linebreaks"
un "quot" ed,text,with,1,2,3,numbers
"quoted","number","series","1,2,3"
"invalid \xAB utf-8"

A: It is possible to subclass Ruby's File to process each line of the the CSV file before it is passed to the Ruby's CSV parser. For example, here's how I used this trick to replace non-standard backslash-escaped quotes \" with standard double-quotes ""
class MyFile < File
  def gets(*args)
    line = super
    if line != nil
      line.gsub!('\\"','""')  # fix the \" that would otherwise cause a parse error
    end
    line
  end
end

infile = MyFile.open(filename)
incsv = CSV.new(infile)

while row = incsv.shift
  # process each row here
end

You could in principle do all sorts of additional processing, e.g. UTF-8 cleanups. The nice thing about this approach is you handle the file on a line by line basis, so you don't need to load it all into memory or create an intermediate file.

A: First, here is a rather naive attempt: http://rubular.com/r/gvh3BJaNTc
/"(.*?)"(?=[\r\n,]|$)|([^,"\s].*?)(?=[\r\n,]|$)/m

The assumptions here are:

*

*A field may start with quotes. In which case, it should end with a quote that is either:

*

*before a comma

*before a new line (if it is last field on its line)

*before the end of the file (if it is last field on the last line)

*Or, its first character is not a quote, so it contains characters until the same condition as before is met.

This almost does what you want, but fails on these fields:

1 comma and
linebreaks"

As TC had pointed out in the comments, your text is ambiguous. I'm sure you already know it, but for completeness:

*

*"a" - is that a or "a"? How do you represent a value that you want to be wrapped in quotes?

*"1","2" - might be parsed as 1,2, or as 1","2 - both are legal.

*,1 \n 2, - End of line, or newline in the value? You cannot tell, specially if this is supposed to be the last value of its line.

*1 \n 2 \n 3 - One value with newlines? Two values (1\n2,3 or 1,2\n3)? Three values?

You may be able to get some clues if you examine the first value on each row, which as you have said, should tell you the number of columns and their types - this can give you the additional information you are missing to parse the file (for example, if you know there should another field in this line, then all newlines belong in the current value). Even then though, it looks like there are serious problems here...

A: I made an app to reformat CSV files, doubling the single quotes inside fields and replacing the new lines inside them with a string like '\n'.
Once the data is inside the database we can replace back the '\n' to new lines.
I needed to do this because the apps I had to process CSV does not deal correctly with new lines.
Feel free to use and change.
In python:
import sys

def ProcessCSV(filename):
    file1 = open(filename, 'r')
    filename2 = filename + '.out'
    file2 = open(filename2, 'w')
    print 'Reformatting {0} to {1}...', filename, filename2
    line1 = file1.readline()
    while (len(line1) > 0):
        line1 = line1.rstrip('\r\n')
        line2 = ''
        count = 0
        lastField = ( len(line1) == 0 )
        while not lastField:
            lastField = (line1.find('","') == -1)
            res = line1.partition('","')
            field = res[0]
            line1 = res[2]
            count = count + 1
            hasStart = False
            hasEnd = False

            if  ( count == 1 )  and  ( field[:1] == '"' ) :
                field = field[1:]
                hasStart = True
            elif count > 1:
                hasStart = True

            while (True):
                if  ( lastField == True )  and  ( field[-1:] == '"' ) :
                    field = field[:-1]
                    hasEnd = True
                elif not lastField:
                    hasEnd = True

                if lastField and not hasEnd:
                    line1 = file1.readline()
                    if (len(line1) == 0): break
                    line1 = line1.rstrip('\r\n')
                    lastField = (line1.find('","') == -1)
                    res = line1.partition('","')
                    field = field + '\\n' + res[0]
                    line1 = res[2]
                else:
                    break

            field = field.replace('"', '""')

            line2 = line2 + iif(count > 1, ',', '') + iif(hasStart, '"', '') + field + iif(hasEnd, '"', '')

        if len(line2) > 0:
            file2.write(line2)
            file2.write('\n')

        line1 = file1.readline()

    file1.close()
    file2.close()
    print 'Done'

def iif(st, v1, v2):
    if st:
        return v1
    else:
        return v2

filename = sys.argv[1]
if len(filename) == 0:
    print 'You must specify the input file'
else:
    ProcessCSV(filename)

In VB.net:
Module Module1

Sub Main()
    Dim FileName As String
    FileName = Command()
    If FileName.Length = 0 Then
        Console.WriteLine("You must specify the input file")
    Else
        ProcessCSV(FileName)
    End If
End Sub

Sub ProcessCSV(ByVal FileName As String)
    Dim File1 As Integer, File2 As Integer
    Dim Line1 As String, Line2 As String
    Dim Field As String, Count As Long
    Dim HasStart As Boolean, HasEnd As Boolean
    Dim FileName2 As String, LastField As Boolean
    On Error GoTo locError

    File1 = FreeFile()
    FileOpen(File1, FileName, OpenMode.Input, OpenAccess.Read)

    FileName2 = FileName & ".out"
    File2 = FreeFile()
    FileOpen(File2, FileName2, OpenMode.Output)

    Console.WriteLine("Reformatting {0} to {1}...", FileName, FileName2)

    Do Until EOF(File1)
        Line1 = LineInput(File1)
        '
        Line2 = ""
        Count = 0
        LastField = (Len(Line1) = 0)
        Do Until LastField
            LastField = (InStr(Line1, """,""") = 0)
            Field = Strip(Line1, """,""")
            Count = Count + 1
            HasStart = False
            HasEnd = False
            '
            If (Count = 1) And (Left$(Field, 1) = """") Then
                Field = Mid$(Field, 2)
                HasStart = True
            ElseIf Count > 1 Then
                HasStart = True
            End If
            '
locFinal:
            If (LastField) And (Right$(Field, 1) = """") Then
                Field = Left$(Field, Len(Field) - 1)
                HasEnd = True
            ElseIf Not LastField Then
                HasEnd = True
            End If
            '
            If LastField And Not HasEnd And Not EOF(File1) Then
                Line1 = LineInput(File1)
                LastField = (InStr(Line1, """,""") = 0)
                Field = Field & "\n" & Strip(Line1, """,""")
                GoTo locFinal
            End If
            '
            Field = Replace(Field, """", """""")
            '
            Line2 = Line2 & IIf(Count > 1, ",", "") & IIf(HasStart, """", "") & Field & IIf(HasEnd, """", "")
        Loop
        '
        If Len(Line2) > 0 Then
            PrintLine(File2, Line2)
        End If
    Loop

    FileClose(File1, File2)
    Console.WriteLine("Done")

    Exit Sub
locError:
    Console.WriteLine("Error: " & Err.Description)
End Sub

Function Strip(ByRef Text As String, ByRef Separator As String) As String
    Dim nPos As Long
    nPos = InStr(Text, Separator)
    If nPos > 0 Then
        Strip = Left$(Text, nPos - 1)
        Text = Mid$(Text, nPos + Len(Separator))
    Else
        Strip = Text
        Text = ""
    End If
End Function

End Module


text:
Q: Libreoffice menus come up in incorrect language Fresh install of Xubuntu 16.04.2. Everything seems correct, but all the Libreoffice menus are in the wrong language. I've checked - locale is correctly set (en_GB.UTF8), and other GUI applications are coming up correctly in English.
I found that some of the support files I'd normally expect for UK use were not installed (hunspell-en, the UK hyphenation support, the normal en_GB language support. Adding them in makes no difference at all - menus are still in the wrong language (no idea what it is - could be Arabic, characters are not the normal alphabet I would expect...).
As another attempt at a fix, I copied the ~/.config/libreoffice files from another Xubuntu 16.04 install (in which Libreoffice is using the selected English menus). Still no change.
Has anyone else seen this sort of problem, and (hopefully!) have suggestions as to how to fix it? I've done some searching but so far I've not found anything that matches this rather peculiar fault.
Any help gratefully accepted...
I've added a screenshot showing the language selection menu. If someone can identify the language and tell me how to select English, it would be a bit help. Seems odd that the heading is in English, but the rest isn't.
http://imgur.com/a/FTw2N


text:
Q: SQLite cursor randomly returning no results - what might be the cause? I'm trying to track down a bug I see coming back from remote crash uploads from my clients where it's as if there is no data in my SQLLiteDatabase when previously queries had been working fine and data was clearly present. For example, in this code here, assume that there is one Profiles table that holds one profile row:
Profile p = null;
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(ProfileDbKeys.PROFILES_TABLE_NAME);
builder.setProjectionMap(ProfileDbKeys.ColumnMap);
Cursor cursor = builder.query(db, ProfileDbKeys.ProfileFields, null, null, null, null, null, null);
if (cursor.moveToNext()) {
  p = Profile.fromCursor(cursor);
}

cursor.close();

Normally p is set to a value, but in some instances it remains null and causes a crash down the line. The crash itself is intentional, because if my client datastore isn't working I would rather crash the activity vs. potentially corrupt state further.
In my logs I know that there are no SQLLite exceptions being thrown; it's as if the database is empty.
Can anyone offer any insight into why the cursor.moveToNext() might return no data every so often?


text:
Q: Long load times due to "Unloading 0 Unused Serialized files (Serialized files now loaded: 0)" When running my unity game on android, it now takes an extremely long time to load new scenes.
I looked at the logcat while the game was running, and I see this entry 1000's of times:
Unloading 0 Unused Serialized files (Serialized files now loaded: 0)
It finally stops after multiple minutes depending on how complex the previous scene was.
This started happening when I updated to the latest version of Unity. No code changed, and before the update, the scenes all loaded instantly on android, even on low end devices.
I'm in desperate need of help.
Is there some way to simply unload the entire scene all at once? It seems that this used to be the case.


text:
Q: Aligning buttons in Dash I want to align the my buttons - 'left_button' and 'right_button' so it fits on the edges of each of the right left most corner of the images and right most corner of the images.
right now it looks like this image of buttons not correctly in positions
Here is the code for the layouts
any tips would be great. Thanks
layout = dbc.Container(
    [
        html.Div(
            [
                dbc.Row(
                    dbc.Col(
                        navbar,
                    ),
                ),
                dbc.Row(
                    [
                        dbc.Col(headwear, width=3),
                        dbc.Col(topwear, width=3),
                    ],
                    justify="center",
                    className="mt-3",
                ),
                dbc.Row(
                    [
                        dbc.Col(bottomwear, width=3),
                        dbc.Col(footwear, width=3),
                    ],
                    justify="center",
                    className="mt-3",
                ),
                dbc.Row(
                    [
                        dbc.Col(left_button, width=3),
                        dbc.Col(right_button, width=3),
                    ],
                    justify="center",
                ),
            ],
        )
    ]
)


text:
Q: How to read data into array in MATLAB? I'm writing a code to solve Ax=b using MATLAB's x=A\B. I believe my problem lies within getting the data from the files into the array. Right now, the solution vector is coming out to be a load of 0's
The matrices I'm using have 10 rows respectively. They are aligned correctly in the text files.
% solve a linear system Ax = b by reading A and b from input file
% and then writing x on output file.
clear;
clc;
input_filename = 'my_input.txt';
output_filename = 'my_output.txt';
% read data from file
fileID = fopen('a_matrix.txt', 'r');
formatSpec = '%d %f';
sizeA = [10 Inf];

A = load('b_matrix.txt');

A = A'

file2ID = fopen('b_matrix.txt','r');
formatSpec2 = '%d %f';
sizeB = [10 Inf];

b = load('b_matrix.txt');
fclose(file2ID);

b = b'

% solve the linear system
x = A\b;

% write output data on file

dlmwrite('my_output.txt',x,'delimiter',',','precision',4);
% print screen
fprintf('Solution vector is: \n');
fprintf('%4.2f \n', x);

A: I answered my own question but I felt the need to share in case anyone else has similar troubles.
% solve a linear system Ax = b by reading A and b from input file
% and then writing x on output file.
clear;
clc;
input_filename = 'my_input.txt';
output_filename = 'my_output.txt';
% read data from file
f = textread('a_matrix.txt', '%f');
vals = reshape(f, 11, []).';
A = vals(:,1:10);
b = vals(:,11);

% solve the linear system
x = A\b;

% write output data on file

dlmwrite('my_output.txt',x,'delimiter',',','precision',4);
% print screen
fprintf('Solution vector is: \n');
fprintf('%4.2f \n', x);

I ended up combining the 'a' and 'b' matrix into a single text file for simplicity. Now, MATLAB reads data in by columns, so it is necessary to use 'reshape' in order to fit the data within the array correctly. Then, I filtered out the information from the single matrix by columns, using the 'vals' function as seen in my code. The 'A' matrix is essentially all numbers in columns 1 through 10, while the 'B' matrix is the 11th (and final) column.
Using MATLAB's x=A\b function, I was able to solve the linear system of equations.


text:
Q: Is there "man" command equivalent in python3 to view the use of methods? Is there any "man" command equivalent in python3 to view the use of certain built in methods?

A: You can use built-in function "help".
You can use it in your interpreter like this:
 help (int)

You'll find this answer:
Help on class int in module builtins:

class int(object)
 |  int(x=0) -> integer
 |  int(x, base=10) -> integer
 |
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 ...

You can find the documentation for help function here:
https://docs.python.org/3/library/functions.html#help


text:
Q: How to skip unnecessary sequence in text with flex/bison? I have a large text document, with some plain text and class definitions in it. What I want is to separate class definitions from plain text using flex/bison.
I tried next tip:
test.l
...
"class" :  { return CLASS;}
"aligned": { return ALIGNED;}
"extends": { return EXTENDS;}
...
.* {return UNKNOWN;}

test.y
DocText : plainText
 | classDefinitions
 | plainText classDefinitions DocText
 { printf (" parsed iso doc!\n" );};

plainText: UNKNOWN | UNKNOWN plainText;

This doesn't work. Could anyone please give me some advice about how I can fix this problem.
PS: sorry for my English.

A: *

*Don't use colons in your flex patterns (unless you want to match a colon). The pattern
"class":

will only match
class:

*Flex always chooses the longest possible match. It only prefers earlier rules if more than one rule matches the longest possible match. So if you have
class { return CLASS; }
.*    { return LINE; }

and the input is
class something

Flex will match the entire line as LINE. The class rule will only be selected for a line which only contains the word class (without whitespace).
So you need to be a bit more precise in your token recognition. In general, even for simple applications, you need to correctly handle (almost) all tokens, including string literals and comments. (In this case, you could let many keywords be matched as identifiers, since you only care about a few keywords, but that is only a small simplification.)


text:
Q: With the phone Vibration why the whole bed vibrates While we are lying on the bed and there is a phone placed somewhere on the bed, when the phone vibrates we can feel the vibration all over the bed,
but in the scenario when we are lying on the floor and our phone starts vibrating we couldn't feel the vibration as same as we feel on the bed.
Why does it happen

A: I tried it actually on my bed, a wood floor, a wood table, and a tiled floor. On the tiled floor, I didn't feel the vibration, on the rest it was clear. I believe the reason for the difference is the difference in the elasticity of the materials. For materials with high elasticity, the wave is transmitted more than reflected, on the other hand, for materials with low elasticity, the wave is reflected more than transmitted.

A: First: Because some waves under a certain frequency in a certain material are eliminated / cannot propagate. Try with a higher frequency and see if it travels better.
Second: The material surface needs to be stretched enough with each pulse to draw enough power from phone-vibration so the phonons will have more and more amplitude. Ground:does not stretch. Bed surface: streches.
Third: you may not have put your ear to ground properly. Have you?
Fourth: Your body can not be coupled with the ground but can couple with bed-vibrations in terms of vibration. Because your body's natural-vibration-frequency is not equal to ground materials' but is equal to bed.


text:
Q: Duplicate answers (not questions) What should we do when we find the answer to question A in the answers to question B? For example, this answer is copied directly from another answer on Stack Overflow (exact duplicate), but the question is clearly not a duplicate. Copy and paste the answer? Link to it? Both?
While copy-paste seems most useful to the reader, it sets off alarms in that part of my brain that hates duplicate code.
Return to FAQ index

A: Copy paste, if not by the original person who answered should at the very least be accompanies by a link to the original answer.
If you have found such a duplicate, without attribution, by someone different, by all means comment with a link to the original.
Note that I say "should" and not "must" - all content on the site is licensed as CC with Attribution Required - this means on other sites. Within the SE family of sites, it is not required, but a nice to have.

A: I quote the answer, with a link.
Done it many times:
https://physics.stackexchange.com/a/23239/7433
https://physics.stackexchange.com/a/24341/7433
https://physics.stackexchange.com/a/21787/7433
https://physics.stackexchange.com/a/24196/7433
https://meta.stackexchange.com/a/130264/178438
Note that I try to add more meat to each answer. The answers are 'tailored' for a different question, so I add some extra explanation below.
IMO, the answer you linked to is fine, though he could have explained what was going on.


text:
Q: Почему выскакивает ошибка "The function is not implemented"? Почему у меня вылазит эта ошибка?
C:\Users\iliya\PycharmProjects\OpenCV\venv\Scripts\python.exe C:/Users/iliya/PycharmProjects/OpenCV/OpenCV.py
3
3
3
3
Traceback (most recent call last):
  File "C:\Users\iliya\PycharmProjects\OpenCV\OpenCV.py", line 26, in <module>
    cv.imshow('Result', result)
cv2.error: OpenCV(4.5.4) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:1274: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowImage'

Process finished with exit code 1

Я когда переустановил opencv-python на предпоследнюю у меня появилась эта ошибка. Подскажите как её исправить?


text:
Q: How to limit number of threads/sub-processes used in a function in bash My question  is how change this code so it will use only 4 threads/sub-processes?
TESTS="a b c d e"

for f in $TESTS; do
  t=$[ ( $RANDOM % 5 )  + 1 ]
  sleep $t && echo $f $t &
done
wait

A: You can do something like this by using the jobs builtin:
for f in $TESTS; do
  running=($(jobs -rp))
  while [ ${#running[@]} -ge 4 ] ; do
    sleep 1   # this is not optimal, but you can't use wait here
    running=($(jobs -rp))
  done
  t=$[ ( $RANDOM % 5 )  + 1 ]
  sleep $t && echo $f $t &
done
wait

A: GNU Parallel is designed for this kind of tasks:
TESTS="a b c d e"
for f in $TESTS; do
  t=$[ ( $RANDOM % 5 )  + 1 ]
  sem -j4 sleep $t && echo $f $t
done
sem --wait

Watch the intro videos to learn more:
http://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

A: Interesting question. I tried to use xargs for this and I found a way.
Try this:
seq 10 | xargs -i --max-procs=4 bash -c "echo start {}; sleep 3; echo done {}"

--max-procs=4 will ensure that no more than four subprocesses are running at a time.
The output will look like this:
start 2
start 3
start 1
start 4
done 2
done 3
done 1
done 4
start 6
start 5
start 7
start 8
done 6
done 5
start 9
done 8
done 7
start 10
done 9
done 10

Note that the order of execution might not follow the commands in the order you submit them. As you can see 2 started before 1.

A: Quick and dirty solution: insert this line somewhere inside your for loop:
while [ $(jobs | wc -l) -ge 4 ] ; do sleep 1 ; done

(assumes you don't already have other background jobs running in the same shell)

A: I have found another solution for this question using parallel (part of moreutils package.)
parallel -j 4 -i bash -c "echo start {}; sleep 2; echo done {};" -- $(seq 10)

-j 4 stands for -j maxjobs
-i   uses the parameters as {}
--   delimits your arguments
The output of this command will be:
start 3
start 4
start 1
start 2
done 4
done 2
done 3
done 1
start 5
start 6
start 7
start 8
done 5
done 6
start 9
done 7
start 10
done 8
done 9
done 10

A: This tested script runs 5 jobs at a time and will restart a new job as soon as it does (due to the kill of the sleep 10.9 when we get a SIGCHLD. A simpler version of this could use direct polling (change the sleep 10.9 to sleep 1 and get rid of the trap).
#!/usr/bin/bash

set -o monitor
trap "pkill -P $$ -f 'sleep 10\.9' >&/dev/null" SIGCHLD

totaljobs=15
numjobs=5
worktime=10
curjobs=0
declare -A pidlist

dojob()
{
  slot=$1
  time=$(echo "$RANDOM * 10 / 32768" | bc -l)
  echo Starting job $slot with args $time
  sleep $time &
  pidlist[$slot]=`jobs -p %%`
  curjobs=$(($curjobs + 1))
  totaljobs=$(($totaljobs - 1))
}

# start
while [ $curjobs -lt $numjobs -a $totaljobs -gt 0 ]
 do
  dojob $curjobs
 done

# Poll for jobs to die, restarting while we have them
while [ $totaljobs -gt 0 ]
 do
  for ((i=0;$i < $curjobs;i++))
   do
    if ! kill -0 ${pidlist[$i]} >&/dev/null
     then
      dojob $i
      break
     fi
   done
   sleep 10.9 >&/dev/null
 done
wait

A: This is my "parallel" unzip loop using bash on AIX:
for z in *.zip ; do
  7za x $z >/dev/null
  while [ $(jobs -p|wc -l) -ge 4 ] ; do
    wait -n
  done
done

Notes:

*

*jobs -p     (bash function) lists jobs of immediate parent

*wait -n     (bash function) waits for any (one) background process to
finish


text:
Q: Using annotations with Apache Olingo for OData v4 I see there is documentation that describes using annotations with Olingo for Odata v2:
https://olingo.apache.org/doc/odata2/tutorials/AnnotationProcessorExtension.html
So for example, instead of manually creating a provider that details all the EDM metadata, I'd like to add annotations to my model and have a generic EDM provider to generate all the meta data. And similarly for the data provider. It would like something like this:
@EdmEntityType
@EdmEntitySet
public class Car {
  @EdmKey
  @EdmProperty
  private String id;
  @EdmProperty
  private String model;
  @EdmNavigationProperty
  private Manufacturer manufacturer;
}

Is there similar functionality for Olingo Odata4? I couldn't find any examples and searching didn't seen the annotations defined in their source code. As I recall this approach works with other frameworks, .Nets web API, SDL Odata, Olingo Odata2, etc.
Update: I ended up using SDL Odata instead which also supports Odata v4 and has notations. For an example look here: https://github.com/sdl/odata-example
Here is what a model looks like in Scala:
@EdmEntity(namespace = "SDL.OData.Example", key = Array("id"), containerName = "SDLExample")
@EdmEntitySet
case class Person (
  @(EdmProperty @field)(name="id",       nullable = false) var personId: String,
  @(EdmProperty @field)(name="firstName",nullable = false) var firstName: String,
  @(EdmProperty @field)(name="lastName", nullable = false) var lastName: String,
  @(EdmProperty @field)(name="age",      nullable = false) var age: Int
)

A: There is currently no documentation on this topic. I would suggest you look at the Olingo TechSvc module which is used in their integration tests. There you can see how the annotations are set for an EntitySet: https://github.com/apache/olingo-odata4/blob/2e24ffd1d3c343fdec45f8dbf0398783a0a86f3f/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/provider/ContainerProvider.java#L179
Basically you use the classes you can find in the org.apache.olingo.commons.api.edm.annotation package and add instances of those clases to you CsdlProvider elements which you want to be annotated.


text:
Q: how to set or know scaling driver in linux kernel I am trying to modify the scheduler/governor. For the same I need to know what CPUFreq Driver  or scalling driver am I configured to run.
1.Where can I find what scaling driver am I configured to run?
Also , Since I couldn't figure out what scaling driver I was running, I tried to look to do the following from adb shell on my android emulator running kernel version 3.4.67 =>
cat /sys/devices/system/cpu/cpu2/cpufreq/scaling_driver

I found that /sys/devices/system does not exist there.
I also tried to look at sysfs on my android device Nexus 5(Unrooted). It also did not have the above directory in it.
So how do I find out what scaling driver am I running ?


text:
Q: Is there a limit to cloud servers I can own? On Blockheads, it is possible to create a server that others can join.
Is there a limit to the amount of servers I can have?

A: I'm pretty sure there is no limit to the mount of servers you can have. All you need is a lot of time crystals if you want to have a lot of servers.


text:
Q: Apply style to selected text not selected box this is going to be easy for any VBA expert out there so, apologies for the novice question! I have a code to condense text into a text box. At the moment the code condensed all the text inside the text box but I want the code to work for selected text only. How can I modify this code to make it work?
Many thanks on advance!
PJ
Sub CondenseText()
On Error GoTo Catch

Dim o As Shape, b As Boolean
Set o = ActiveWindow.Selection.ShapeRange(1)
If Not o Is Nothing Then
    With o
        .TextFrame2.TextRange.Font.Spacing = .TextFrame2.TextRange.Font.Spacing - 0.1
    End With
End If
Exit Sub

Catch:
    If Err.Number = -2147188160 Then MsgBox CG_NOTHING_SELECTED
End Sub

A: Sub CondenseText()

Dim oTextRange2 As TextRange2

' You can check Selection.Type rather than relying
' on an errorhandler if you like
If ActiveWindow.Selection.Type = ppSelectionText Then

    Set oTextRange2 = ActiveWindow.Selection.TextRange2

    If Not oTextRange2 Is Nothing Then
        oTextRange2.Font.Spacing = oTextRange2.Font.Spacing - 0.1
    End If

' and you could add an Else clause with msg for the
' user here if you like:
Else
    MsgBox "Yo! Select some text first, OK?"
End If

End Sub


text:
Q: How to decode result of LZ78 compression of string with numbers? I wrote a code for LZ78 compression algorithm in C. It works perfectly for strings such as "aabcccbac". But what if I have string: "1233" I get result: 01020333.
The problem is I don't know how to decode this kind of result. What should i do?
UPD:
Code that reads file and compress it:
FILE *file = fopen("test.txt", "rb");
FILE *pathFile = fopen("result.txt", "wb");
fread(text, 1, 100, file);

strcpy(result, lz78(text));
fwrite(result, 1, 100, pathFile);


text:
Q: How to create an alias with multiple commands that accepts parameters in Cmder? I would like to know how to create one alias with multiple commands in Cmder, that accepts parameters and injects them into the commands.

A: To separate commands in a single alias $t would do the trick.
To retrieve all the parameters passed to an alias $* would do the trick.
Examples:

*

*Multiple Commands: alias serveApp=cd "C:\app" $t grunt serve

*Parameters: alias nav=cd $*, usage: nav "C:\app"

*Combination: alias servePath=cd $* $t grunt serve


text:
Q: changing time format objective c i"m fetching time from server in this format "dd-MM-yyyy HH:mm:ss a" and converting it to this format "dd-MM-yyyy HH:mm a". While converting, time goes an hour before the original time.
This the time I fetched from server
Date Created 29-Jun-2017 01:44:43 PM
And converted time
Date Modified 29-06-2017 12:44 PM
Can anyone help me to remove seconds from time fetched from server

A: You can set the time zone of your date formatter like this:
[gmtDf setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

Sample:
NSString *str = @"29-Jun-2017 01:44:43 PM";
NSDateFormatter* gmtDf = [[NSDateFormatter alloc] init];
[gmtDf setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[gmtDf setDateFormat:@"dd-MM-yyyy HH:mm:ss a"];
NSDate* gmtDate = [gmtDf dateFromString:str];
NSLog(@"%@",gmtDate);

Other time zones names:
    ADT = "America/Halifax";
    AKDT = "America/Juneau";
    AKST = "America/Juneau";
    ART = "America/Argentina/Buenos_Aires";
    AST = "America/Halifax";
    BDT = "Asia/Dhaka";
    BRST = "America/Sao_Paulo";
    BRT = "America/Sao_Paulo";
    BST = "Europe/London";
    CAT = "Africa/Harare";
    CDT = "America/Chicago";
    CEST = "Europe/Paris";
    CET = "Europe/Paris";
    CLST = "America/Santiago";
    CLT = "America/Santiago";
    COT = "America/Bogota";
    CST = "America/Chicago";
    EAT = "Africa/Addis_Ababa";
    EDT = "America/New_York";
    EEST = "Europe/Istanbul";
    EET = "Europe/Istanbul";
    EST = "America/New_York";
    GMT = GMT;
    GST = "Asia/Dubai";
    HKT = "Asia/Hong_Kong";
    HST = "Pacific/Honolulu";
    ICT = "Asia/Bangkok";
    IRST = "Asia/Tehran";
    IST = "Asia/Calcutta";
    JST = "Asia/Tokyo";
    KST = "Asia/Seoul";
    MDT = "America/Denver";
    MSD = "Europe/Moscow";
    MSK = "Europe/Moscow";
    MST = "America/Denver";
    NZDT = "Pacific/Auckland";
    NZST = "Pacific/Auckland";
    PDT = "America/Los_Angeles";
    PET = "America/Lima";
    PHT = "Asia/Manila";
    PKT = "Asia/Karachi";
    PST = "America/Los_Angeles";
    SGT = "Asia/Singapore";
    UTC = UTC;
    WAT = "Africa/Lagos";
    WEST = "Europe/Lisbon";
    WET = "Europe/Lisbon";
    WIT = "Asia/Jakarta";


text:
Q: nginx rewrite rule for friendly url I have problems with nginx to get the .php index files to to friendly urls.
for example my apache setup thats working perfect:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^([a-z]+)/([a-z\-]+)$ /$1/$2.php [L]
</IfModule>

RewriteBase /
RewriteCond %{HTTP_HOST} !^http://domain.local$ [NC]
RewriteRule ^(.*)$ http://domain.local$1 [L,R=301]
RewriteRule ^start index.php [L]
RewriteRule ^side2 side2.php [L]
RewriteRule ^side3 side3.php [L]
RewriteRule ^side4 side4.php [L]
RewriteRule ^side5 side5.php  [L]
RewriteRule ^side6 side6.php [L]

But if i try to convert them to nginx there is no way for me to just get it to work. I  have search a bit but nothing found.
this is what i have try
location / {
rewrite ^/([a-z]+)/([a-z\-]+)$ /$1/$2.php break;
if ($http_host !~ "^domain.local$"){
rewrite ^(.*)$ http://domain.local/$1 redirect;
}
}
location /start {
rewrite ^/start /index.php break;
}
location /side1 {
rewrite ^/side1 /pages/side1/side1.php break;
}
location /side2 {
rewrite ^/side2 /pages/side2.php break;
}
location /side3 {
rewrite ^/side3 /pages/side3.php break;
}
location /side4 {
rewrite ^/side4 /pages/side4.php break;
}
location /side5 {
rewrite ^/side5 /pages/side6.php break;
}
location /side6 {
rewrite ^/side6 /form.php break;
}

I get it worked by my self.
 rewrite ^/([a-z]+)/([a-z-]+)$ /$1/$2.php last;
 if ($http_host !~* "^domain.local$"){
 set $rule_1 1$rule_1;
 }
 if ($rule_1 = "1"){
rewrite ^/(.*)$ http://domain.local/$1 permanent;
}
rewrite ^/start /index.php last;
rewrite ^/side1 /pages/side1/side1.php last;
rewrite ^/side2 /pages/side2.php last;
rewrite ^/side3 /pages/side3.php last;
rewrite ^/side4 / pages/side4.php last;
rewrite ^/side5 /pages/side5.php last;
rewrite ^/side6 /form.php last;

A: Even if this "works" atm you are doing it (really) wrong.
server {

    listen X.X.X.X:80;
    server_name domain.local;

    location / {
        rewrite ^/([a-z]+)/([a-z-]+)$ /$1/$2.php last;
        rewrite ^/start /index.php last;
        rewrite ^/side([2-6]) /pages/side$1.php last;
    }

   location ~ \.php$ {
       [ ... ]
   }

}

server {

    listen X.X.X.X:80 default_server;
    server_name _;
    return 301 http://domain.local$request_uri;

}

A: Thanks for your advice,
but the side1 - side6 was just some examples how i want it to be.
it will be like , start forum contact news etc.
I have rebuild it a little now.
 location / {
    index   index.php;
    rewrite ^/([a-z]+)/([a-z-]+)$ /$1/$2.php last;
    rewrite ^/start /index.php last;
    rewrite ^/rent /pages/rent/rent.php last;
    rewrite ^/news /pages/news.php last;
    rewrite ^/info /pages/info.php last;
    rewrite ^/faq /pages/faq.php last;
    rewrite ^/contact /pages/contact.php last;
    rewrite ^/form /form.php last;

}


text:
Q: Is the for loop what is causing the error in this code? So for this part of my code, I was wondering why my test class was not working. I followed the instructions exactly, but I'm not sure why my I'm getting errors.
Basically for both parts,
If the array parameter is null, it must throw a BadArrayException with the message "Array is null".
If the array parameter is length 0, it must return -1.
It must not alter the array parameter contents,  nor copy the entire array parameter contents to another array.
To find the first occurrence, it must search through the array parameter once.
It doesn't read or print anything.
So should I fix how the intvalue=0 at first?  Or is my for loop faulty? Or in the second loop, should I just not have int last as list.length?
 public static int indexOf(int[] list, int searchValue) throws BadArrayException
    {
        int indexValue = 0;

        if(list == null)
            throw new BadArrayException("Array is null");
        else if(list.length == 0)
            return -1;

        for(int i = 0; i < list.length; i++){
            if(list[i] == searchValue)
                indexValue = i;
        }
        return indexValue;
    }

    public static int lastIndexOf(int[] list, int searchValue) throws BadArrayException
    {
        int indexValue = 0;
        int last = list.length;

        if(list.length == 0)
            return -1;

        for(int i = last; i >= 0; i--){
            if(list[i] == searchValue)
                indexValue = i;
        }
        return indexValue;
    }
}

I am supposed to be getting this as my result but I am not, I keep getting ERROR got unexpected on this portion. Thank you.
--- Testing indexOf and lastIndexOf method ---

Getting indexOf of a null array
  OK - indexOf threw exception for null array: BadArrayException: Array is null

Getting lastIndexOf of a null array
  OK - lastIndexOf threw exception for null array: BadArrayException: Array is null

Getting lastIndexOf(5) of: []
  OK - expected lastIndexOf to return -1 and got: -1

Getting indexOf(5) of: [5,10,5,15,5]
  OK - expected indexOf to return 0 and got: 0

Getting indexOf(0) of: [5,10,5,15,5]
  OK - expected indexOf to return -1 and got: -1

Getting indexOf(15) of: [5,10,5,15,5]
  OK - expected indexOf to return 3 and got: 3

And here is what I get instead
--- Testing indexOf and lastIndexOf method ---
Getting indexOf of a null array
  OK - indexOf threw exception for null array: BadArrayException
Getting lastIndexOf of a null array
  ERROR - lastIndexOf threw an unexpected exception: java.lang.NullPointerException
Getting indexOf(5) of: []
  OK - expected indexOf to return -1 and got: -1
Getting lastIndexOf(5) of: []
  OK - expected lastIndexOf to return -1 and got: -1
Getting indexOf(20) of: [20]
  OK - expected indexOf to return 0 and got: 0
Getting indexOf(25) of: [20]
  ERROR - expected indexOf to return -1 but got: 0
Getting lastIndexOf(20) of: [20]
  OK - expected lastIndexOf to return 0 and got: 0
Getting lastIndexOf(25) of: [20]
  ERROR - expected lastIndexOf to return -1 but got: 0
Getting indexOf(5) of: [5,10,15,20,10,15,5,10,15,20]
  ERROR - expected indexOf to return 0 but got: 6
Getting indexOf(10) of: [5,10,15,20,10,15,5,10,15,20]
  ERROR - expected indexOf to return 1 but got: 7
Getting indexOf(15) of: [5,10,15,20,10,15,5,10,15,20]
  ERROR - expected indexOf to return 2 but got: 8
Getting indexOf(20) of: [5,10,15,20,10,15,5,10,15,20]
  ERROR - expected indexOf to return 3 but got: 9
Getting indexOf(0) of: [5,10,15,20,10,15,5,10,15,20]
  ERROR - expected indexOf to return -1 but got: 0
Getting lastIndexOf(5) of: [5,10,15,20,10,15,5,10,15,20]
  ERROR - expected lastIndexOf to return 6 but got: 0
Getting lastIndexOf(10) of: [5,10,15,20,10,15,5,10,15,20]
  ERROR - expected lastIndexOf to return 7 but got: 1
Getting lastIndexOf(15) of: [5,10,15,20,10,15,5,10,15,20]
  ERROR - expected lastIndexOf to return 8 but got: 2
Getting lastIndexOf(20) of: [5,10,15,20,10,15,5,10,15,20]
  ERROR - expected lastIndexOf to return 9 but got: 3
Getting lastIndexOf(0) of: [5,10,15,20,10,15,5,10,15,20]
  ERROR - expected lastIndexOf to return -1 but got: 0
Done - press enter key to end program

A: Let's start with indexOf.
When you find the number you are searching for, you store the index in a variable, and then return the variable when you're done. Let's see what happens in the [5,10,5,15,5] test:

*

*Test list[0] == 5. True, so indexValue = 0.

Ideally, we should return 0 at this point. But that's not what happens:

*

*Test list[1] == 5. False, so do nothing.

*Test list[2] == 5. True, so indexValue = 2.

*Test list[3] == 5. False, so do nothing.

*Test list[4] == 5. True, so indexValue = 4.

*Return 4. Not 0, as it should.

As it turns out, indexOf is working like lastIndexOf should. Instead of returning the index of the last time you find the value, return the index as soon as you find the value.
lastIndexOf has the same problem, but it also has another problem, which is how you initialize last. Let's say we have a 1-element array, like this:
[1]

The last index of this array is 0, but you are initializing last with list.length, which is 1, not 0. You have to subtract 1.

A: The problem is of your initialization of last.
Taking a String of SAMPLE.  The vale of "SAMPLE".toCharArray().length would be 5, but in you loop you want to loop from "SAMPLE".toCharArray()[4] to "SAMPLE".toCharArray()[0]
i.e. change last to "SAMPLE".toCharArray().length - 1


text:
Q: Keeping line breaks in jsoup to display in android listview Heu guys i have an app where i'm parsing an html file using jsoup to display selected texts in a listview in android. However i cant seem to find a way to keep the carriage returns.
Here is what i have attempted :
Elements br = doc.select("br");

    for (Element src : br) {
         src.append("\n");
     }

To give you an example with a string

Is parsed and displays :
This is a string another string

I have tried using
src.append("\\n");

Which displays
This is a string \n another string

I am using an arraylist of strings to store these variables.
Ive been trying to find a solution to this problem with no luck i have attempted solutions from the following threads:
How do I preserve line breaks when using jsoup to convert html to plain text?
Removing HTML entities while preserving line breaks with JSoup

A: When you tried src.append("\\n"); it looks like you had just one backslash to much.
Regardless, the first link you posted should point you in the right direction, something like this should work:
// parse the doc and select the element containing the text
Elements es = Jsoup
    .parse("
a \ntext
is a text
</body")
    .select("div");

// find
 tags and replace them (using an arbitrary placeholder '~n~')
es.select("br").append("~n~");
// clean all tags
String clean = Jsoup.clean(es.html(), Whitelist.none());
// replace the placeholder with a real newline
String disp = clean.replaceAll("~n~", "\n");

Now disp will print:
a text
is a text


text:
Q: Using Srand With Enums I have an enum of colours:
enum colour_t {red, blue, green, yellow, orange, white};

and I'm making a Rubik's Cube scrambler, so I need to use srand or some sort of randomizer to select a colour for each square. Is it possible to use srand with enum values or will I have to give it some integer parameters (1-6) and have a case for each number corresponding to a colour.
Thanks,
Tristan

A: You can cast:
static_cast<colour_t>(rand() % (white + 1))


text:
Q: Eloquent: Has Many Through Relationships I am trying to figure out a relationship but I can't seem to solve the issue.
So what my script does first is checking if there is a valid session where status = 0.
Then I want to check if there is a valid trial where status = 0 ->first() associated with that session.  And if so, I want to grab all the relevant data related by trial_id.
I understand what logic is required. However, I am wondering if there is a method to do this with as little commands as possible using Eloquent relationships.
Specifically, once i have the $session object. How can I filter the trials, in order to get the appropriate stimuli_tracker data?
The important components to the relationships for the table is as follows:
Sessions

*

*id (has one to many relationship to trials(sessions_id)

*user_id (foreign key)

*status

Trials

*

*id (one to many relationship with stimuli_tracker)

*sessions_id (foreign key)

*status

Stimuli_Tracker

*

*trials_id (foreign key)

*stimulus

*stimulus_type

Sessions Model
class Sessions extends Model
{
    protected $table = 'sessions';

    public function stimuliTracker()
    {
        return $this->hasManyThrough('App\StimuliTracker', 'App\Trials', 'sessions_id','trials_id');
    }
}

Trials Model:
class Trials extends Model
{
    public function stimuli()
    {
       return $this->hasMany(App\StimuliTracker);
    }
}

EDIT
I have tried in artisan tinker to
$object = \App\Session::where(arg);

then I tried to
$object->stimulus

but didn't work. I tried a few other fields but I only received null. Maybe I'm not getting how to grab the content properly

A: $object->stimulus is an undefined attribute based on what you've shown in your code.
To access the stimulus information for your session, you have to use the name of the relationship, which in this case is:
$object->stimuliTracker

The thing is that this will return an Eloquent Collection because it is a hasManyThrough relationship (which is a hasMany of a hasMany).
I'm assuming that the 'stimulus' attribute belongs to the StimuliTracker class. If this is the case, then you will need to loop through your StimuliTracker Collection to extract it:
foreach ( $object->stimuliTracker as $record )
{
    $stimulus = $record->stimulus;
    // do something with $stimulus
}

EDIT (Added):
If you are just looking for an array of the values in the 'stimulus' attribute, you can get that with the lists() method:
$stimulus_values = $object->stimuliTracker->lists('stimulus');


text:
Q: What's mean 'fb' and 'b' in Jena rules //OWL, RDFS
There is a Jena rules
I don't know prefix b and fb.
What different things each OWL and RDFS files?
PS.
download URL is
https://jena.apache.org/download/index.cgi and click jena-2.11.1-source-release.zip (MD5, PGP)
rules dir -> jena-core/src/main/resources/etc

A: The *.rules files are files with rules used by all the different Jena reasoners.
See the comments in the headers of the files. For example for the owl-fb.rules file it is:

OWL rule set v0.3
   This rule set is designed to implement owl(f)lite using the hybrid
   rule system (mixture of forward and backward chaining). It differs
   from earlier versions by more consistently sticking to instance reasoning
   by being design to work with the LP backward engine.
It includes an experimental forward version of the equality reasoning which
   not yet scalable.

So b stands for backward chaining, f for forward chaining, and fb for a combination of the two.


text:
Q: Hole filling of color pictures I would like to perform some image editing by removing annoying element on these image such as electric poles, grids, ... (pic. 1)
The amount of edits to perform is quite significant and I wonder if it is possible to automatize the refilling (pic. 3) process after deleting the annoying parts with GIMP (pic. 2).

What are the possibilities (scripts, processes, extensions modules, softwares, ...) to automatize the refilling process from picture 2 to picture 3 ? Preferably with GIMP, imagemagick, or any open source softwares ?

A: The most efficient way in Gimp is to use the resynthesizer plugin. I don't know how up-to-date the code on the Gimp reigsitry is but AFAIK it is bundled in the Windows and OSX Gimp builds from partha.com, and is in the repository of some Linux distros.


text:
Q: Replace column in dataframe based on condition for unknow length of arguments I have a dataframe like this:
dataset <- matrix(sample(c(NA, 1:5), 25, replace = TRUE), 5)
df <- as.data.frame(dataset)

I want to get a new dataframe with a new column name "V6" which is based on conditions which I want to pass through a function:
testDF <- createFactor(df,
                    'V6',
                    c('V1>V2', 'V3>V5', 'V2<V5'),
                    c('low', 'medium', 'high'))

This is my try so far:
createFactor <- function(df, column, equation, factors){
    eq <- equation
    fa <- factors
    df[column] <- ifelse(eval(parse(text=eq[1]), df), fa[1],
                  ifelse(eval(parse(text=eq[2]), df), fa[2],
                  ifelse(eval(parse(text=eq[3]), df), fa[3], 'NULL')))
  return(df)
}

I know that I can nest the ifelse() and get the output I want but how can I nest if I don't know the number of arguments. What if I want to pass ten conditions? How can I build a funtion like that. The conditions can exclude each other.
Is there a simple solution to this which is effienct also? Thanks in advance.


text:
Q: Strange session variables behavior and devise before and after signing in I set some session variables before my users login with devise.. Expecting them to be available after they sign in as well..
Sometimes Sessions variables are kept after signing in with devise (before signing in) and sometimes the sessions variables I set before signing in are not transferred over to the signed in session...
Have you noticed this too? Why is this happening?


text:
Q: Python strip function In python when I try this :-
ac = "Pearl Riverb-Vaccines"
b = ac.strip("-Vaccines")
b = b.strip()
print(b)

The output is :- Pearl Riverb
But when I try this :-
ac = "Pearl Rivera-Vaccines"
b = ac.strip("-Vaccines")
b = b.strip()
print(b)

The output is :- Pearl River
So why is the 'a' missing in the second code?
I have tried every other letter and it is printing but what is the problem with letter 'a' ?

A: strip() does not respect count or order when it removes characters from the end of your string. The argument you passed it, "-Vaccines", contains an "a", so it will remove the "a" from "Rivera". It does not matter that it already removed an "a" from "Vaccines" and it does not matter that it doesn't come between a V and a c.
Consider another example:
>>> "abcXqrqqqrrrqrqrqrqrqqrr".strip("qr")
'abcX'

Many qs and rs are removed here, even though the argument to strip contains only one of each.
In general, strip is not suitable for removing a static number of characters from the end of a string. One possible alternative is to use regex, which can match a literal character sequence that appears at the end of a string:
>>> import re
>>> ac = "Pearl Rivera-Vaccines"
>>> re.sub("-Vaccines$", "", ac)
'Pearl Rivera'

In his answer, Tom Karzes observes that this approach doesn't readily work on strings that contain characters that have special meanings in a regex. For instance,
>>> import re
>>> s = "foo^bar"
>>> re.sub("^bar$", "", s)
'foo^bar'

^ has a special meaning in regex, so the pattern "^bar$" fails to match the end of the string s. If the string you want to match contains special characters, you should escape it, either manually or with an re.escape call.
>>> import re
>>> s = "foo^bar"
>>> re.sub(r"\^bar$", "", s)
'foo'
>>> re.sub(re.escape("^bar") + "$", "", s)
'foo'

A: The problem is that the argument to strip isn't used the way you think it is.  The argument isn't treated as a sequence of characters, but rather as a set of characters.  Any character in the argument string is removed.  For example:
"abaca".strip("ac")

Produces:
'b'

since all instances of "a" and "b" have been removed.
If you just want to remove a suffix from a string, you can do something like:
ac = "Pearl Rivera-Vaccines"
s = "-Vaccines"
b = ac
if b.endswith(s):
    b = b[:-len(s)]

This will result in b having the value:
'Pearl Rivera'

Note that this will be faster than using the re module.  It will also be more flexible, since it will work with any non-empty string (whereas creating a regular expression will require escaping certain characters).


text:
Q: How to access representation of the hidden layers in CNTK 2.2? Assume I have a simple model.
def create_model(out_classes):
    f1 = Dense(16, activation=C.relu,bias=True,init_bias=0,name='FLayer')
    l1 = Dense(16, activation=C.relu, bias=True, init_bias=0, name='LLayer')(f1)
    c1 = Dense(out_classes,name='CLayer')(l1)
    return c1

model = create_model(nClasses)
z = model(feature)

How do I access the representation of the FLayer or LLayer during the testing of my trained model?

A: By representation you mean accessing the functions of the hidden layers correct? I created a sample code to show it. I tested two approaches, the first one builds on what you did and the second one uses the functional API of CNTK which I prefer.
The easy way to get access to the functions is to return them:
import cntk
import numpy as np

def create_model(output_dimension):
    l0 = cntk.layers.Dense(shape=1, activation=None, init=1, init_bias=1)
    l1 = cntk.layers.Dense(shape=output_dimension, activation=None, init=1, init_bias=1)(l0)
    l2 = cntk.layers.Dense(shape=output_dimension, activation=None, init=1, init_bias=1)(l1)
    return l0, l1, l2

input_dim = 1
output_dim = 1
l0, l1, l2 = create_model(output_dim)
input = cntk.input_variable(shape=1)
layer0 = l0(input)
layer1 = l1(input)
layer2 = l2(input)

print("Non functional API")
print("output of layer 0: {}".format(layer0.eval({input: np.array([0], dtype=np.float32)})))
print("output of layer 1: {}".format(layer1.eval({input: np.array([0], dtype=np.float32)})))
print("output of model: {}".format(layer2.eval({input: np.array([0], dtype=np.float32)})))

The above model takes an input of dimension 1 and output a vector of dimension 1. I also set the weights and biases to 1 in each layer so it is easy to follow the computation. The function create_model returns a tuple which contains all the layers so these can be accessed externally.
The functional API approach is better in my opinion. Below, I create a list containing the different layers and then I build the model using cntk.layers.Sequential. Then, create_model2 returns a tuple whose entries are 1) the list containing all the layers and 2) the final model. This is cleaner when you have several layers. Also, it gives you better control with regards to what you can do with each layer.
def create_model2(output_dimension):
    layers = [cntk.layers.Dense(shape=1, activation=None, init=1, init_bias=1),
              cntk.layers.Dense(shape=output_dimension, activation=None, init=1, init_bias=1),
              cntk.layers.Dense(shape=output_dimension, activation=None, init=1, init_bias=1)]
    m = cntk.layers.Sequential(layers)

    return m, layers

m, layers = create_model2(output_dim)
layer0 = layers[0](input)
layer1 = layers[1](input)
layer2 = layers[2](input)
layer01 = cntk.layers.Sequential(layers[0:2])(input)
layer012 = cntk.layers.Sequential(layers[0:3])(input)
model = m(input)

print("Functional API")
print("output of layer 0: {}".format(layer0.eval({input: np.array([0], dtype=np.float32)})))
print("output of layer 1: {}".format(layer1.eval({input: np.array([0], dtype=np.float32)})))
print("output of layer 2: {}".format(layer2.eval({input: np.array([0], dtype=np.float32)})))
print("output of model: {}".format(model.eval({input: np.array([0], dtype=np.float32)})))
print("output of layer 0 and 1: {}".format(layer01.eval({input: np.array([0], dtype=np.float32)})))
print("output of layer 0 and 1 and 2: {}".format(layer012.eval({input: np.array([0], dtype=np.float32)})))


text:
Q: Does this algorithm exist - a secret secret? I'm not quite sure how to phrase this question mathematically, so I am going to express it in words first:
Let us suppose I have a secret $m_1$ and a plausible innocent secret $m_2$. Is there an encryption algorithm which takes $m_1$ and $m_2$ and combines them with 2 public keys $e_1$ and $e_2$ into a ciphertext $c$ such that when a publicly known decryption algorithm is used on $c$ with private key $d_1$, $m_1$ is returned, but if $d_2$ is used instead, $m_2$ is returned, but without knowing the encryption algorithm used it must be plausible that there is only 1 hidden message?
ie:
$$D(E(m_1,m_2,e_1,e_2),d_k)=m_k \qquad k\in\lbrace 1,2\rbrace$$
I am thinking it would require a pair of one-way trapdoor functions mingled together somehow so that it would be difficult to compute $d_k$ from $e_k$.  But I also have no idea how to make it plausible that there is only 1 possible $d$ (assuming the ENcryption algorithm is unknown to the enemy).
For example, one naive attempt I had was to append two RSA messages together using the same $n$ value but differing $e$, and then decryption involves splitting $c$ into two parts and discarding the irrelevant half depending which private key is used (can be simply indexed as part of each key).  The obvious downside to this method is that if you examine the decryption algorithm it is blatantly discarding half the ciphertext, and the enemy will know straight away that he has not recovered the whole message.


text:
Q: How to sort Vector> on multiple elements keeping sub items grouped together? So I am returning JSON data from a REST API where the data is already ordered by a date field and then is added to a Vector> which is used in a JTable. I need to group items with the same 5 digit key together and then order those by an additional identifier desc order (3,2,1) where date decides what 5 digit key is next.
For example:
[[28696, 2, 11/15/19 17:57]]
[[28696, 1, 11/15/19 17:56]]
[[00972, 2, 11/15/19 17:55]]
[[28696, 3, 11/15/19 17:54]]
[[00972, 1, 11/15/19 17:53]]

Should be
[[28696, 3, 11/15/19 17:54]]
[[28696, 2, 11/15/19 17:57]]
[[28696, 1, 11/15/19 17:56]]
[[00972, 2, 11/15/19 17:55]]
[[00972, 1, 11/15/19 17:53]]

See that 28696 is first one of the items in the group is the newest in the entire data set.

A: What you want is not doable with a single sort operation. Instead you can use streams to meet your requirements of grouping, sorting the groups, and sorting the data within the groups.
First note that I converted your List<List<String>> into a List<Data> (as recommended by Max Vollmer) to make this easier to work with and understand. If you really need it as a List you can replace Data with List<String> and the Data.get??() with List.get(?):
public static void main(String[] args) throws IOException, TransformerException {
    List<Data> list = Arrays.asList( //
            new Data("28696", "2", "11/15/19 17:57"), //
            new Data("28696", "1", "11/15/19 17:56"), //
            new Data("00972", "2", "11/15/19 17:55"), //
            new Data("28696", "3", "11/15/19 17:54"), //
            new Data("00972", "1", "11/15/19 17:53"));

    Comparator<Data> sortByTimestamp = Comparator.comparing(Data::getTimestamp).reversed();
    Comparator<Data> sortByOccurrence = Comparator.comparing(Data::getOccurrence).reversed();

    // LinkedHashMap keeps the insertion order
    Collector<Data, ?, LinkedHashMap<String, List<Data>>> groupByIdKeepInsertOrder
            = Collectors.groupingBy(Data::getId, LinkedHashMap::new, Collectors.toList());

    List<Data> result = list.stream()
            .sorted(sortByTimestamp) // sort all data by timestamp, if it's already sorted by timestamp you can skip this
            .collect(groupByIdKeepInsertOrder) // group them by id keeping the timestamp order
            .values().stream() // stream the lists of data grouped together
            .peek(l -> l.sort(sortByOccurrence)) // sort each list of data by occurrence
            .flatMap(Collection::stream) // flatten the lists into a single stream
            .collect(Collectors.toList()); // collect all Data into a single list

    System.out.println(result);
    // [[28696, 3, 11/15/19 17:54],
    //  [28696, 2, 11/15/19 17:57],
    //  [28696, 1, 11/15/19 17:56],
    //  [00972, 2, 11/15/19 17:55],
    //  [00972, 1, 11/15/19 17:53]]
}

private static class Data {
    private final String id;
    private final String occurrence;
    private final String timestamp;

    public Data(String id, String occurrence, String timestamp) {
        this.id = id;
        this.occurrence = occurrence;
        this.timestamp = timestamp;
    }

    public String getId() { return id; }
    public String getOccurrence() { return occurrence; }
    public String getTimestamp() { return timestamp; }
    @Override public String toString() { return "[" + id + ", " + occurrence + ", " + timestamp + "]";}
}


text:
Q: Three.js events effect the DOM Simple can/can't question.
Can you set click events in the three.js scene to make changes to the DOM?
e.g. An object in the scene is clicked, and a panel outside the scene is made visible?
Cheers.

A: you have to attatch click event to the renderer DOM element as you would to any other
renderer.domElement.addEventListener( 'mousedown', onDocumentMouseDown, false );

then calculate where the click occured
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

and raycast to determine what object you pointed at
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( objects );

you can see this used in the draggable cube example http://threejs.org/examples/#webgl_interactive_draggablecubes
after you have you object you can do something to any other (acessible) dom element i.e. display object properties/ position etc outside the screen
if you had in mind something like this
myObject.addEventListener

then, you would have to code in that yourself and it would still have to be done somehow like the example above because the renderer target is essentially a canvas - an image without information about the objects it holds


text:
Q: Regex to match word preceding parentheses, inside an specific XML tag I'd like to write a regular expression to match a word that requires two conditions.

*

*Be inside an XML action tag. I wrote a regex for that:
([^<>])*(?=<\/action>)

*Match the word preceding a parentheses. Like this:
((\w+)(?=\s?\())
Combining both expressions into one didn't work. Any ideas?
([^<>])((\w+)(?=\s?\())(?=<\/action>)

Using the following text, the regex should match all the occurrences of the word add:
<action>add();</action>

<action name="foo">add();</action>

<action>
   add();
</action>

A: Here is the regex you are looking for which needs to satisfy your two regex conditions,
(?s)(?:<action[^>]*>\s*\K)\w+(?=\s?\(\).*<\/action>)

This regex will match your both conditions that are,

*

*Word should be enclosed between <action> tag

*Word precedes by a parenthesis

Explanation:

*

*(?s) --> Need to enable dot matching a new line as I see your tags can be spread in multiple lines.

*(?:<action[^>]*>\s*) --> This matches an action tag where action tag may optionally included any kind of attributes. Here \s* is to eat any white space which we don't want it to get matched with the word.

*\K --> Resets whatever matched, so only the word gets matched as per OP's post. Why I had to do this, because negative look behind group doesn't allow quantifiers and at the same time to make the regex robust by allowing it to match any variable length input inside  tag.

*\w+ --> Captures the intended word

*(?=\s?\(\).*<\/action> --> Positive lookahead to ensure it is followed by () followed by zero or more any characters followed by </action> tag.

Click here for demo
Also, the way you wanted this regex ([^<>])*(?=<\/action>) to ensure it matches a word between <action> tags, this regex is not enough because it will also match this,
add</action>

which isn't enclosed in <action> tag.
Hope this helps and let me know if you have any queries further.


text:
Q: Harmonic functions which vanish on the real line Let $u:\mathbb{C}\to \mathbb{R}$ be harmonic on the entire plane.
Is there a nice classification, maybe a nice basis, for the set of such functions that satisfy $u\equiv 0$ on $\mathbb{R}$?
Examples:

*

*$u(x,y)=0$

*$u(x,y)=y$

*$u(x,y)=\mathrm{Im}( (x+iy)^2)=2xy$

A: Say $v$ is a harmonic conjugate of $u$. Then $f=iu-v$ is an entire function, so $f(z)=\sum a_n z^n$. Now saying $u=0$ on $\Bbb R$ says that $f$ is real-valued on $\Bbb R$, which is easily seen to imply that $a_n$ is real. So:

$u$ is a real-valued harmonic function in $\Bbb C$ vanishing on $\Bbb R$ if and only if there exists a sequence $(a_n)$ of real numbers with $|a_n|^{1/n}\to0$ and $u(z)=\Im\sum a_nz^n.$


text:
Q: How to Allow New User to Add Products in opencart or nopcommerce I am going to build my own Ecommerce site . But the thing i want is any user that come to my site can add products like what happens in olx . It means i want any user that came to my site if want to add or sell his/her own products or thing can upload that product
I have three options for This site
Nopcommerce
opencart
woocommerce

A: nopCommerce has multi-vendor support. This way registered vendors can manage its own catalog and sell products. But please note that vendors are registered by a store owner out of the box. If you want to allow customers to be registered as vendors manually (not by a store owner), then it'll require some minor customization. But other 99% of your requirements are already implemented

A: Opencart MultiVendors Module tried it, works good, price is not that big of a deal in case of modding existing nopCommerce in ASP.NET, server cost will be lower.


text:
Q: Large image in Scrollview pinch zoom not working I am building an application where I want to display a floor plan where the image is 1260x1000, larger than the size of my view controller. I want the user to be able to pan the image and zoom in and out, similar to how a map behaves in Mapview.
Below is the code in my view controller. When I run the simulator, the image is panning but the zooming in and out isn't working. Any suggestions on how to fix my code would be helpful.

class ViewController: UIViewController, UIScrollViewDelegate {
 var scrollView: UIScrollView!
    var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        imageView = UIImageView(image: UIImage(named: "myMap.pdf"))
        scrollView = UIScrollView(frame: view.bounds)
        scrollView.contentSize = imageView.bounds.size
        scrollView.addSubview(imageView)
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.3
        scrollView.maximumZoomScale = 5
        view.addSubview(scrollView)
    }
       func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }

}

A: Your function signature is wrong:
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return imageView
}

Note: If you want to be able to scale your pdf image while keeping the vector-based rendering (so it doesn't get blurry when zoomed), you should probably use PDFKit and a PDFView.
Add your myMap.pdf file to your bundle... not to your Asset Catalog.
import UIKit
import PDFKit

class ZoomingPDFViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let fileURL = Bundle.main.url(forResource: "myMap", withExtension: "pdf") else {
            fatalError("Could not load myMap.pdf!")
        }

        // Add PDFView to view controller.
        let pdfView = PDFView(frame: self.view.bounds)
        pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        self.view.addSubview(pdfView)

        // Load myMap.pdf file from app bundle.
        pdfView.document = PDFDocument(url: fileURL)

        pdfView.autoScales = true
        pdfView.maxScaleFactor = 5.0
        pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit

    }

}


text: Q: Column name start with underscore (_) I am trying to use column which name is started with underscore like _name in where clause or in select clause, but can't use it. Can anyone suggest how to deal in such scenario.


text:
Q: Truth Tables Using XS-3 I was asked to build truth tables using XS-3 and I wanted to know how I refer to a situation in which the output is not set, for example, for 1110 I will not get anything.
Little explanation $0000 = 0 => 0+3 = 3 => 0011$ this is the meaning of XS-3.
Wiki

Thanks!

A: Excess-3 is defined strictly on the domain ranging from decimal $-3$ to $12$ for four bits.  That's where it's defined for four bits. It's output ranges from $0000$ to $1111$. $1111$ is the output for an input value of decimal $12$, so the largest defined input on four bits is $1100$.
So if you're adding $0011=3_{10}$ to a four-bit number, $1110 = $ decimal $14$, you'll have a carry, $(1)0001,$ i.e. "overflow"...when you're limited to four bits. I.e. XS-3 is not defined on $N = 4$ bits. If you had five bits (which you don't), XS-3 of $1110$ would be $10001$.
I.e. $1110$ is "out of the domain of definition" on four-bits: $\operatorname{XS-3}(1110)$ is not defined on four bits.