text:
Q: Laravel Echo + Redis + Socket.io Laravel 5.6
I am trying to create a Real Time App. I followed the tutorial found in google but then it seems like it doesn't work. I can't figure out why because it doesn't show error in console.
in config/app.php
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,

this is my Event
<?php

namespace App\Events;

use App\Message;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class MessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;

public $message;

/**
 * Create a new event instance.
 *
 * @return void
 */
public function __construct(Message $message)
{
     $this->message = $message;
     // $this->dontBroadcastToCurrentUser();
    //
}

/**
 * Get the channels the event should broadcast on.
 *
 * @return \Illuminate\Broadcasting\Channel|array
 */
public function broadcastOn()
{
    return new Channel('chat-channel');
}
}

Here's my controller
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Message;
use App\User;
use Auth;
use App\Events\MessageSent;

class MessageController extends Controller
{
public function index()
{
    return view('chat');
}

public function getChat()
{
    return Message::with('user')->get();
}

public function addChat()
{
    $user = Auth::user();

    $message = $user->messages()->create(['message' => request('message')]);

    event(new MessageSent($message));

    return $message->toJson();

}
}

at the bottom of my bootstrap.js
import Echo from 'laravel-echo'

window.io = require('socket.io-client');
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});

my laravel-echo-server.json
{
"authHost": "http://localhost",
"authEndpoint": "/broadcasting/auth",
"clients": [
    {
        "appId": "1461f99e6c0bcaa4",
        "key": "3dc5701da38d9c3346141db0c8e3f0ad"
    }
],
"database": "redis",
"databaseConfig": {
    "redis": {},
    "sqlite": {
        "databasePath": "/database/laravel-echo-server.sqlite"
    }
},
"devMode": true,
"host": null,
"port": "6001",
"protocol": "http",
"socketio": {},
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": "",
"apiOriginAllow": {
    "allowCors": false,
    "allowOrigin": "",
    "allowMethods": "",
    "allowHeaders": ""
}
}

my ChatComponent.vue
<template>

Chatroom

                        {{message.user.name}}

                        - {{message.message}}

                        No messages yet!

                        <input type="text" name="" class="form-control"
placeholder="Start typing..." v-model="messageText"
@keydown.enter="sendMessage()">

                        <button class="btn btn-primary"
@click="sendMessage()">Send</button>

</template>

if someone knows the solution to this one. Please help. Thank you so much!

A: I think there few things that you've miss.
If your setup like this Redis + Laravel Echo Server + Socket.io, then you can try this.

*

*Update BROADCAST_DRIVER, QUEUE_DRIVER, QUEUE_CONNECTION on .env file to redis. Run redis-server, and artisan queue:listen --tries=1 and also laravel-echo-server start

*On your Event class, there's no data you want to sent/broadcast. Try add broadcastWith method and simply return whatever data you want inside that method. You can read on Laravel official documentation https://laravel.com/docs/5.6/broadcasting#broadcast-data

A: One thing is to remove the '.' from the beginning of the event name 'MessageSent':
Echo.channel('chat-channel').listen('MessageSent', (message) => ...

Also you can check out this reply


text:
Q: How to use Grails Dependency cache in IDE? Is there a way to use the ivy cache grails dependency DSL creates within an IDE like eclipse or netbeans? Or must I manually add all dependencies to the IDE lib folder?
I've looked into plugins like ivybeans and ivyde, but they seem to require ivy.xml and ivysettings.xml files, which grails does not produce.

A: The Grails tooling provided by the SpringSource Tool Suite plugin for Eclipse has the functionality you desire.  It reads BuildConfig.groovy and modifies the project classpath accordingly.

A: I just attached the following to the Jira bug.
In snooping around the STS distribution, I found the following code in
C:\springsource\sts-2.3.2.RELEASE\configuration\org.eclipse.osgi\bundles\898\1.cp\src\com\springsource\sts\grails\core\model\GrailsBuildConfig.java
// make sure that we use the Ivy dependency resolution strategy for Grails 1.2
  // TODO CD make version number detection more flexible
  if (settings.getGrailsVersion().startsWith("1.2")) {
   jarFiles.addAll(settings.getTestDependencies());
   jarFiles.addAll(settings.getProvidedDependencies());
Based on this find, I tried downgrading my project from Grails 1.3.2 to Grails 1.2 and ran "refresh dependencies".  Sure enough, the dependencies were correctly loaded from Ivy.
Looks like someone needs to do the TODO.  I can take a stab at it once I figure out how to check out the source code...

A: IntelliJ syncs dependencies between Grails (form application.properties and BuildConfig.groovy) and the IDE very nicely.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I exclude disabled users from my user profile synchronization? I have my user profile synchronization setup and working but I have noticed that disabled users who no longer work for my company are showing up in the sync.  I would like to update the sync so that it only pulls in active users.

A: I found my solution from this blog.

*

*Go to your Central Admin website

*Go to "Application Management"

*Go to "Service Applications -> Manage Service Applications"

*Click on "User Profile Service Application"

*Click on "Synchronization -> Configure Synchronization Connections"

*Click on your connection and select "Edit Connection Filters" from the menu

*Add a new Exclusion Filter for Users and select "userAccountControl" as the attribute, "Bit on equals" as the operator, and "2" as the filter.  Make sure also that you correctly have AND and OR selected if there are any other exclusion filters already there.

userAccountControl Bit on Equals 2

*Click "OK"
The next time that it syncs your disabled accounts should be gone.


text:
Q: How do I trace the usage of functions and variables through a C++/Javascript project I'm looking to map out the usage of Javascript in the 0 A.D. project, such as the flow of operations when the mouse is clicked. I have found functions that define parts of the process, but the points where the functions are called are in different files. I'm looking for some program that will walk through all the files, find those references, and tell me which file calls what and defines what. It cannot operate through the web browser because this Javascript is not designed to work with a web browser, but with a game engine written in C++... so unless there is a way to implement the trace in the game's engine, some sort of file-walking tool would be best. I think this is called a static-trace?
Sorta what I'm looking for:
funcA() - fileA.js
  fileB.js - Line 144
  fileC.js - Line 12

A: The Eclipse IDE can do this for C++ (eclipse CDT version).
Select your function, then in the menu bar click "Navigate" -> "Open call hierarchy..."
You can then select "callers" or "callees".
There is an eclipse version for javascript, maybe it can do it, too.


text:
Q: How to align a button to the center of the screen html I am trying to make a button that goes in the centre of the screen I have tried lots of solutions which havent worked html:
      <button align="center" type="button" onclick="location.href='https://discord.gg/AsA7P9B5Mv'" class="button">
       Join Server
      </button>

css:
  .button {
  text-align: center;
  align: center;
  justify-content: center;
  align-items: center;
  height: 10vw;
  width: 25vw;
  margin: 0;
  padding: 0;
  background: #10e321;
  border: none;
  outline: none;
  border-radius: 1vw;
  overflow: hidden;
  font-size: 4vw;
  cursor: pointer;
}
.button:hover{
  background: #11d120;
}
.button:active{
  background: #0eb31b;
}

Help would be greatly appreciated :)

A: There is a couple of options to center element, e.g.

*

*CSS property position - always in the center of the screen

.button {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

}

*Flexbox - children element will be always in the center of the parent. You can make the parent full screen.

.parent-element {
    display: flex;
    justify-content: center;
    align-items: center;
}

A: You should use something like this:

    <input type="submit" />

Or you could use something like this. By giving the element a width and specifying auto for the left and right margins the element will center itself in its parent.
<input type="submit" style="width: 300px; margin: 0 auto;" />

A:

.class {
  display:flex;
  justify-content:center;
  align-items:center;
  height:100vh;
}

  <button>html</button>


text:
Q: How can I pass a Parameter via Query String to populate a lookup field on a New Item Form/DVWP? I have two lists:

*

*List A: Products

*List B: Requirements

I'd like to have a nice Create Requirement page launched from the Product Listing page.
I have a DVWP/Multi-Item View displaying all Products. Next to each product, there is a Create Requirement link. The hyperlink generates the Query String URL /Pages/Create-Requirement.aspx?Product=Product
On the Create-Requirement.aspx page, I have a DVWP/New Item Form. The form includes a lookup field back to the Products list. I would like the Query String parameter to populate that lookup field and for the field to be hidden.
I've seen different methods of using Javascript or jQuery to pass to a field on a Custom New Item Form - but not necessarily a DVWP/New Item Form. And it's easy to pass to a text field but not a lookup field. I even tried passing to a text field that would then populate the lookup by workflow on item creation but SPD won't do that (unless someone can think of workaround logic).
Hiding the field should be easy enough - I just can't make the lookup happy. (Lookups are never happy.)

A: This blog post from Microsoft is highly linked to and describes what you want to do.  I've used it before, these days I typically use jQuery and SPServices.  Setting lookups typically requires you to pass in the Lookup ID value or the ID;Descriptor.
Here's an actual example from a site of mine, it's setting a person/group field, not a lookup though.  You can experiment with looking at the source of the rendered page to see what markup the lookup field generates, then try passing in either the ID or the description in the query string and setting the field to that.  If it saves properly, then set the visibility to hidden.
var queryStringVals = $().SPServices.SPGetQueryString();
var insEmail = queryStringVals["InstructorEmail"];
  $("textarea[Title$='People Picker']").val(insEmail);

Another example from some of my code, this is setting a >20 choice lookup field.  It is using a hard coded value but so long as your query string variable passes over the proper vaule, it would work.
$("select[Title$='Department']").val('*Not Applicable - Student');

Or to abstract it to account more closely to your situation:
var queryStringVals = $().SPServices.SPGetQueryString();
var prod = queryStringVals["Product"];
$("select[Title$='Department']").val(prod);

A: Using Jquery and normal OOB Javascript functions we can easily implement this as below
<script type="text/javascript">
var url = new URL(window.location.href.toLowerCase());
var product = url.searchParams.get("Product"); //Product is the Name of Query Parameter passed through the URL
$( document ).ready(function() {
    $("select[Title='Requirements']")[0].value = product; // Title is the Display Name of the Lookup Field
});
</script>


text:
Q: JAVA - Answers are not calculating upon output? Doing a what I thought would be a very very easy output lab for AP, I thought I was doing everything correctly, but the output keeps coming out as "The area is :: " + 0.0" when the "0.0" is supposed to be the calculated area of the circle. Here are the two classes:
Circle Class:
public class Circle
{
    private double radius;
    private double area;

    public void setRadius(double rad)
    {
        rad = radius;
    }

    public void calculateArea( )
    {
        area = (3.14159*(radius*radius));
    }

    public void print( )
    {
       System.out.println("The area is :: " + area);
    }
}

Circle Runner Class:
public class CircleRunner
{
    public static void main( String[] args )
   {
        Circle test = new Circle ( );
        test.setRadius(7.5);
        test.calculateArea( );
        test.print( );

        test.setRadius(10);
        test.calculateArea( );
        test.print( );

        test.setRadius(72.534);
        test.calculateArea( );
        test.print( );

        test.setRadius(55);
        test.calculateArea( );
        test.print( );
    }
}

Thanks!

A: Your setter is wrong, so your radius stays 0, it should be
public void setRadius(double rad) {
    radius = rad;
}

A: You are assigning the variables in reverse order. It should be:
radius = rad;

And not:
rad = radius;

A: You need to use this to reference your radius in your setRadius Method. or swap the two values. You should assign  " rad " to " radius" and not vis versa, since you will be recieving rad from the method.
public class Circle {
    private double radius;
    private double area;

    public  Circle() {
    }

    public void setRadius(double rad) {
        this.radius = rad;
    }

    public void calculateArea() {
        area = (3.14159*(radius*radius));
    }

    public void print() {
        System.out.println("The area is :: " + area);
    }
}


text:
Q: Hide CPT from search engine Wordpress Let's suppose, (www.example/services/washing) - I need to hide (services) CPT, I tried this code but didn't work. Could somebody help?
add_action( 'init', 'update_my_custom_type', 99 );

function update_my_custom_type() {
    global $wp_post_types;

    if ( post_type_exists( 'services' ) ) {

        // exclude from search results
        $wp_post_types['services']->exclude_from_search = true;
    }
}

A: To hide the CPT from search engines, add the below meta tag to your header.php file. Replace your-cpt with your custom post type you want to hide.
<?php if ( is_singular( 'your-cpt' ) ) { ?>
  <meta name="robots" content="noindex, nofollow" />
<?php } ?>


text:
Q: HTTP2 request grammar Wondering if there exists a language grammar for an HTTP2 request/response. For example, a I found this which is a grammar for HTTP 1.1 dated from 1999. Not sure if there is an equivalent for HTTP2.

A: There is a spec - RFC 7540 - but not a "language grammar" (which sounds like you're looking for something like an ABNF).

A: This is what you are looking for:
tools.ietf.org/html/rfc7540
RFC's are pretty cool.


text:
Q: How to check user scrolling to left or right? How to check user scrolling to left or right?
below code is what I tried but not work....
$('.inner').scroll(function(){
    console.log('scroll');
    ol = $('.inner').scrollLeft();
    if(ol > $('.inner').scrollLeft()){
        //  console.log('right');
        //  ol = $('.inner').scrollLeft();
    }else{
        //  console.log('left');
        //  ol = $('.inner').scrollLeft();
    }
});

A: I have tried another approach for that issue, you can find it running here.
What I did is the following:
jQuery(document).ready(
    function($)
    {
        var lastLeftLocation = 0;

        $('.inner').scroll(
            function(e)
            {
                if(lastLeftLocation > $(this).scrollLeft())
                {
                    console.log('It goes left');
                }
                else
                {
                    console.log('It goes right');
                }

                lastLeftLocation     =    e.currentTarget.scrollLeft;
            }
        );
    }
);

A: I'm not sure how your HTML markup looks like, but you'll have to save scrollLeft of the container and compare it on scroll. I also added some logic to detect when scrolling start and end.
var container = $('.outer');
var initVal = container.scrollLeft();
var isScrolling = false;
container.scroll(function(e){
    var curVal = container.scrollLeft();
    if (!isScrolling) {
        $(window).one("mouseup", function(e){
            console.log("Stopped scrolling at", container.scrollLeft());
            isScrolling = false;
        });
        console.log("Started scrolling at", curVal);
    }
    if (curVal === initVal) return;
    if (curVal > initVal) {
        console.log("Scrolling right");
    } else {
        console.log("Scrolling left");
    }
    initVal = curVal;
    isScrolling = true;
});

See test case on jsFiddle.


text:
Q: Реализация 4-х мерного массива Есть функция вычисляющая f(int a,b,c,d) неизвестное кол-во раз, различных вариантов будет примерно до 3 млн. Надо эффективно размещать эти результаты для дальнейшего использования без вызова функции. Все от abs(a - b) до abs(с - d) вероятно меньше 4 и в цикле они увеличиваются от 0 до n (т.е. в начале они в среднем >= 0 в конце в среднем <= n). Сделал реализацию на unordered_map
http://en.cppreference.com/w/cpp/container/unordered_map:

*

*Функция find вызывает equal функцию (типа bool) 2 раза, зачем?, здесь нет сортировки...

*Комп - comp_func = [](const key_t &x, const key_t &y) { return !memcmp(&x, &y, 16); }; - на скорость обычно не влияет, в идеале ее удалить надо.

*Хеш - hash_func = [](const key_t &x) { return x.a * 400 - x.b * 49 - x.c * 7 - x.d + 171; }; - так думаю лучший вариант, при переполнении новые полезут на самые старые (вроде бы) и их может получится заменять.

*Может стоит написать через другой/свой контейнер?, слишком простые варианты как std::vector<std::vector<res_t>> не годны - в 2 раза быстрее, взамен много лишнего г.

*Похоже сильно быстрее не получится, может уже так не плохо? Или как в таких ситуациях правильно делать?

upd: ответить пока-что не могу, допишу здесь - хеш не просто так взят, bucket равен максимальному "числу" хеша, поэтому я его максимально упаковал, оно почти не влияет на скорость, тестировал примерно - 0.24с на 1 млн. рандом доступа. Тут раном-не-рандом все место и так заполнится и пойдут лишние прямые сравнения снижающие скорость. Обычный вектор 0.12с на млн, т.е не похоже что сильно тормозит, пока что так, может я где-то ошибся. Больше всего непонятно когда 1 элемент в куске и хеш одинаковый зачем еще 2 (!) прямых сравнения идут, хоть это и не тормозит сильно


text:
Q: Two click for dispatch action Redux I use REDUX in my REACTJS application. I want to retrieve the button ID after clicking the button and send it to my store. It's only works after the second click. Can you help me ? My code:
My function :

gotoidee (e)  {
let test= this.state.data[e.target.id];
console.log("test" +test.titre);

const action = { type: "SAVE_IDEE_ID", value:this.state.data[e.target.id]};
this.props.dispatch(action);
console.log(this.props.ideeId.titre);
}

const mapStateToProps = (state) => {
  return {

ideeId: state.saveIdee.ideeId
}
  }

export default connect(mapStateToProps)(liste_idee)

My reducer :

const initialState = { ideeId: [] }

function saveIdee  (state = initialState, action) {
  let nextState
  switch (action.type) {
    case 'SAVE_IDEE_ID':
      nextState = {
        ...state,
        ideeId: action.value
    }
    return nextState

  default:
    return state
  }
}

export default saveIdee

My button :

 <Button type="submit" id={ideeId} onClick={this.gotoidee}>Marche</Button>

A: gotoidee (e)  {
  // check here if the click is happening by putting a console here
  let test= this.state.data[e.target.id];
  console.log("test" +test);
  const action = { type: "SAVE_IDEE_ID", value:test};
  this.props.dispatch(action);
}

render(){
 console.log(this.props.ideeId); // check the updated value
}


text:
Q: Insert Image and set to circle in canvas This is my code to insert image to canvas..

<button onclick="addTexttitle()" type="button" class="text-left btn-block btn white">Set Image To Circle</button>
<input type="file" id="file">
        <canvas id="canvas" width="750" height="550"></canvas>
        Click Me!

https://jsfiddle.net/javasalden/yn04k565/
how to complete button:
<button onclick="addTexttitle()" type="button" class="text-left btn-block btn white">Set Image To Circle</button>

when I click and image/element will be CIRCLE

A: Hi I have created one example, please have a look at it, this is definatley be useful for you.

var createCache = function(requestFunction) {
    var cache = {};
    return function(key, callback) {
        if (!cache[key]) {
            cache[key] = $.Deferred(function(defer) {
                requestFunction(defer, key);
            }).promise();
        }
        return cache[key].done(drawImg);
    };
};

var loadImage = createCache(function(defer, url) {
    var image = new Image();
    function cleanUp() {
       image.onload = image.onerror = null;
    }

    defer.then(cleanUp, cleanUp);
    image.onload = function() {
        defer.resolve(url);
    };
    image.onerror = defer.reject;
    image.src = url;
});

var drawImg = function(img) {
    var tmpCanvas = document.createElement('canvas'),
        tmpCtx = tmpCanvas.getContext('2d'),
        image = new Image();

    image.src = img;
    tmpCanvas.width = image.width*2;
    tmpCanvas.height = image.height*2;

    // draw the cached images to temporary canvas and return the context
    tmpCtx.save();
        tmpCtx.beginPath();
            tmpCtx.arc(2*24, 2*24, 2*24, 0, Math.PI*2, true);
        tmpCtx.closePath();
        tmpCtx.clip();

    tmpCtx.drawImage(image, 0, 0, 4*24+2, 4*24+2);

        tmpCtx.beginPath();
            tmpCtx.arc(0, 0, 2, 0, Math.PI*2, true);
            tmpCtx.clip();
        tmpCtx.closePath();
    tmpCtx.restore();

    $('body').append(tmpCanvas);
};

var cacheImgs = function() {
    var imgs = [

        'https://cdn.pixabay.com/photo/2017/01/06/19/15/soap-bubble-1958650_960_720.jpg'
    ];

    for (var i = 0; i < imgs.length; i++) {
        var img = loadImage(imgs[i])/*.done(drawImg(imgs[i]))*/;
        // .done callback is what sends the canvases to where they need to go
    }
}
cacheImgs();
canvas { float: left; }

A: Try clipTo function
img.set({
 clipTo: function (ctx) {
  ctx.arc(0, 0, radius, 0, Math.PI * 2, true);
 }
});

Here is updated fiddle, the radius is half of uploaded image


text:
Q: How to pass props of a nested object to a component? I am having a little hard time figuring out this issue and would appreciate if someone clear this concept to me. With the following code, I can parse props to another component i.e. UserItem and it displays the username and email. I also want to display "firstname" along with other details. I can easily destructure others like: const {username, email} = this.state.user but when I add const {name: fisrtname, username, email}, then it doesn't work. But if I put this.state.user.name.firstname in the UserItem component, then I can see the firstname in the browser. So how I will destructure the nested object and/or parse the props of nested object to other component? Thanks in advance.
    users: [
      {
        username: "johndoe",
        email: "jdoe@gmail.com",
        name: {
          firstname: "John",
          id: "2",
        },
        id: "1",
      },
    ],
  };

  render() {
    return (

        {this.state.users.map((user) => (
          <UserItem key={user.id} user={user} />
        ))}

    );
  }
}

**This is UserItem component**

class UserItem extends Component {
  render() {
    const { name: firstname, email, username, phone } = this.props.user;
    // console.log(this.props.user);

    return (

{this.props.user.name.firstname}

{email}

{username}

{phone}

    );
  }
}

A: This:
const { name: firstname, email, username, phone } = this.props.user;

needs to be changed to this:
const { name: {firstname}, email, username, phone } = this.props.user;

That way you can access the nested property.

A: I am just extending and describing the @Alex Yepes's Answer.
Look at your code
{
    username: "johndoe",
    email: "jdoe@gmail.com",
    name: {                   // here the name is also an object.
      firstname: "John",
      id: "2",
    },
    id: "1",
  },

Since 'name' is also an object you need to destructure that one too.
For example:
On your first destructure, you can only access directly the property of that object
const {username, email, name, id} = user;
console.log(username); //result: 'johndoe'
console.log(name); //result: {firstname: 'John', id: 2}

Here you can see that username's value is a string but the value of 'name' is an object that's why you need to destructure this one too. Other wise you have to use object or bracket notation like:
console.log(name.firstname); // result: 'John'
//or
console.log(name[firstname]) // result: 'John'

But if you destructure like this one:
const { name: {firstname}, email, username, phone } = this.props.user;

you can access 'name' directly because the 'name' object is not an object anymore.

A: you need the constructor in the object above the render.
class UserItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {


text:
Q: Can I avoid writing boilerplate code for classes that derive from an interface? I have many classes that implement an interface. Whenever I define a class I have to write something like this within the class definition:
interface Model.IModel with

        member this.Assets          = modelArg.Assets
        member this.AuxData         = modelArg.AuxData
        member this.Benchmark       = modelArg.Benchmark
        member this.CalcPeriods     = modelArg.CalcPeriods
        member this.CashTicker      = modelArg.CashTicker
        member this.Description     = modelArg.Description
        member this.FirstValidDate  = modelArg.FirstValidDate
        member this.Name            = modelArg.Name
        member this.ParamData       = modelArg.ParamData
        member this.ParamList       = modelArg.ParamList
        member this.Strategy        = modelArg.Strategy

        member this.CalcStartTime with get() = calcStartTime and
                                       set v = calcStartTime <- v

        member this.Counter with get() = counter and
                                 set v = counter <- v

Is there a way to avoid repeating this for each and every class that derives from the interface IModel? The code is identical in all cases.

A: To make the discussion a bit more concrete, and due to the limited space in the comments, something like the below would or would not work for you?
 type ModelArg = {
     Number: int
     Name: string
 }

 type IModel(modelArg: ModelArg) =
    abstract member Number: int
    abstract member Name: string
    default __.Number = modelArg.Number
    default __.Name = modelArg.Name

type ConcreteModel1(modelArg: ModelArg) =
    inherit IModel(modelArg)

type ConcreteModel2(modelArg: ModelArg) =
    inherit IModel(modelArg)

let modelArg1 = {Number=2; Name ="Joe"}
let modelArg2 = {Number=3; Name = "Jim"}

let getNumberAndName(x: IModel) =
    (x.Number, x.Name)

let model1 = ConcreteModel1(modelArg1)
let model2 = ConcreteModel2(modelArg2)

getNumberAndName(model1)
//val it : int * string = (2, "Joe")
getNumberAndName(model2)
//val it : int * string = (3, "Jim")


text:
Q: Why do I get error when ifstream is creating file with string read from keyboard? I am doing exercises from Bjarne Stroustrup's book, Programming Principles and Practice Using C++. I am on the first exercise in Chapter 10, where it says to write a program that produces the sum of all the numbers in a file of whitespace-separated integers. I based my code below on what's used for Exercise 2 of Chapter 10.5. I get an error when the ifstream object is created. Here is the code I am trying to run:
#include "../../std_lib_facilities.h"

int main(int argc, const char * argv[]) {
    // insert code here...

    cout << "Plese enter the input file name: " << endl;
    string iname;
    cin >> iname;
    ifstream ist {iname};
    if (!ist) error("Can't open input file ",iname);

    vector<int> numbers;
    int sum;
    int n;
    while(ist>>n) {
        numbers.push_back(n);
    }

    for (int i=0; i<numbers.size(); ++i) {
        sum += numbers[i];
    }
    cout << sum << endl;

    return 0;
}

Any input I enter is getting error. I tried myin, myin.txt or any other name. The error("Can't open input file ",iname); is from the library created by the author.
I know the file does exist in the same directory with main.cpp and created with TextEdit from Mac using the format for plain text.

A:
[...] in the same directory with main.cpp [...]

It does not really matter where you put the input file relative to the source file.
The file should be in the environment's current working directory when you run the program.

A: There must be some confusion in passing argument. You should try to pass absolute path of input file.
Below is your modified application. This will create One test file and use it instead of asking file name for Case 1. For case 2, it use file which doesn't exist.(Delete if present)
#include <cstdio>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
template <typename T> void error(const T &t) { cout << t; }
template <typename T, typename... Args> void error(const T &t, Args... args) {
  cout << t << " ";
  error(args...);
  cout << "\n";
}

int main(int argc, const char *argv[]) {
  // insert code here...
  // cout << "Plese enter the input file name: " << endl;
  string iname = "a.txt";
  ofstream ofs{iname};
  ofs << 1 << " " << 2 << " " << 3 << " " << 4;
  ofs.close();
  //  cin >> iname;
  // part 1
  {
    cout << "Case1: Reading file a.txt which is just created\n";
    ifstream ist{iname};
    if (!ist)
      error("Can't open input file ", iname);
    if (ist.is_open()) {
      vector<int> numbers;
      int sum = 0;
      int n = 0;
      while (ist >> n) {
        numbers.push_back(n);
      }
      for (int i = 0; i < numbers.size(); ++i) {
        sum += numbers[i];
      }
      cout << sum << endl;
      ist.close();
    } else {
      error("can't open file to read", iname);
    }
  }
  // part 2
  {
    cout << "Case2:reading file which is not present\n";
    iname = "b.txt";
    std::remove(iname.c_str()); // delete if present
    ifstream ist{iname};
    if (!ist)
      error("Can't open input file ", iname);
    if (ist.is_open()) {
      vector<int> numbers;
      int sum = 0;
      int n = 0;
      while (ist >> n) {
        numbers.push_back(n);
      }
      for (int i = 0; i < numbers.size(); ++i) {
        sum += numbers[i];
      }
      cout << sum << endl;
      ist.close();
    } else {
      error("can't open file to read", iname);
    }
  }
  return 0;
}

Note: Construct of std::ifstream always create object. You need to its object either as you did or is_open() method.


text:
Q: Treat Java warnings differently I want to ask if there is a way to treat same type of warnings differently. I mean you can choose how to treat every warning (like warning unused, error unchecked cast and so on), but can I tell the compiler to treat one unused warning as error and ignore another (somehow specify where to treat as error and where to ignore it)?

A: You can use the @SuppressWarnings annotation. The warnings that can be suppressed are listed here: What is the list of valid @SuppressWarnings warning names in Java?

A: You have two options:

*

*Explicitly suppress warnings by adding a directive in each file

*Instruct the compiler to suppress warnings for all files

The @SuppressWarnings annotation allows you to suppress a warning, and can be applied to most Java blocks. Most IDEs will create a @SuppressWarnings annotation for you, as one of the hint options when a warning occurs.

man javac describes the -Xlint command line parameter.
There's a long list of options, for example if you want to disable the "raw types" warning:
javac -Xlint:-rawtypes ...

Most IDEs and build systems provide ways of passing parameters to javac -- check the documentation for yours.


text:
Q: Running powershell from Perl and getting a return value I am running a Perl script that calls a powershell script. Is there a way for me to get a return value from this? I've tried something similar to
my @output = "powershell.exe powershellscript.ps1;
foreach(@output)
{
   print $_;
}

and I get nothing out of it. Do I need to add something to the powershell script to push the return values?

A: Try with backsticks,
my @output = `powershell.exe powershellscript.ps1`;
foreach (@output)
{
   print $_;
}

A: Use backticks to run and collect the output:
my @output = ` ...`

If you want the return code (status) too, do (by example):
perl -e '@output=`/bin/date`;print $?>>8,"\n";print "@output"'

See system for more information on interpreting the return code.
ADDENDUM
In lieu of backticks, which can sometimes be annoying to read, you can use qx(STRING) as described in perlop.  This is analogous to collecting process output in shell scripts where, in POSIX-compliant shells, capture may be done with the archaic backticks, or more readably, with OUTPUT=$(/bin/date).

A: Try using a named pipe:
open(PWRSHELL, "/path/to/powershell.exe powershellscript.ps1 |") or die "can't open powershell: $!";
while (<PWRSHELL>) {
    # do something
}
close(PWRSHELL) or warn "can't close powershell: $!";


text:
Q: Compiler throwing error as variable is not declared X++ I have the following piece of x++ code:
static void Datatypes_class_variable(Args _args)
{
    // Declare a class variable from the RentalInfo class
    RentalInfo   rentalInfo;
    ;
    // An object is created and referenced by the
    // class variable rentalInfo
    rentalInfo = new RentalInfo();
    // Call methods to set/get data to/from the object
    rentalInfo.setCar("BMW 320");
    info(strfmt("The car is a %1", rentalInfo.getCar()));
}

I don't understand why the compiler is throwing me the error:

The RentalInfo variable was not declared.

As you can see, the variable has been already declared at the beginning.
Thank you!

A: The type RentalInfo does not exist as a class.
That is why the error is in line 4 column 4.


text:
Q: ubuntu broke my windows boot I was installing ubuntu on pendrive and once finished I needed to run windows a bit, even though I chose erase and install ON THE PENDRIVE it altered my hdd boot sector
When I remove the ubu cd and pendrive it should only boot from hdd (windows) but it gives
Error: no such device : blablabla(numerbes and letters)
Grub rescue> _
If I place the pendrive inside it asks me whether to start windows or linux (windows works here)
I need to run windows without the pendrive, how can I remove grub from the hdd and also run ubuntu from the pendrive(once I remove grub from the hdd)
||
THX ArK, your information help me do wonders! :)
||
Now... it seems that without grub i can not boot the ubuntu from the pendrive anymore, blank screen and nothing loads(i did check the ubuntu with the grub from the hdd, and everything inside it worked perfectly (except the clock, it didnt find my local hour...) )
New problem: it seems that grub which is now on the pendrive is always asking me whether to boot from windows or ubuntu
Of course i want to boot ubuntu otherwise i would stick the pen inside the computer

A: Boot up Windows install DVD, & choose Repair your Computer
open command prompt and Run the Following commands
bootrec.exe/fixboot

next
bootrec.exe/fixmbr

Reboot
Now you should now boot directly to windows
P.S. you don't need GRUB to boot from the pendrive

A: I'm assuming that with the fix suggested by Ark you can boot into Windows again and that with the pendrive in the pc you get grub and have a choice between windows and Ubuntu.
If that's the case you can boot into Ubuntu and change the Grub parameters to automatically boot into Ubuntu or set a time out for it to default to Ubuntu.
You can read more about this here


text:
Q: How to set next encoding to a file in Java Here is my code which is reading file and replacing on a specific line the text but when is reading  the(readAllLines method) lines and it have a symbol in the file which doesn't matches with the specified Charset it throws MalformedInputException.
For Example: I'm reading a text with UTF_8 charset but in file it has symbol "†" and it throws me MIE.
I would like to ask you how in the following code i can make a check when a MalformedInputException found and try the next encoding . For example when the encoding is UTF_8, to try the next one UTF_16 etc. and when it matches to read the file properly.
public boolean replaceTextInSpecificLine(String fileName, int lineNumber, String content, Charset cs)
{
    try
    {

        scan = new Scanner(System.in);
        File filePath = readFile(fileName, true);
        List<String> lines = null;
        if(filePath !=null)
        {
           lines = Files.readAllLines(filePath.toPath(), cs);

            while (lineNumber < 0 || lineNumber > lines.size() - 1)
            {
                System.out.print("Wrong line number or the file is empty! Enter another line: ");
                lineNumber = scan.nextInt();
                scan.nextLine();
            }
            lines.set(lineNumber - 1, content);
            Files.write(filePath.toPath(), lines, cs);
            System.out.println("Successfully saved!");

            return true;
        }

    }

    catch(IOException e)
    {

       e.printStackTrace();

    }
    finally
    {
        close(scan);
    }
    return false;
}

A: I would avoid switching encodings while reading the file and simply reread the file with the next encoding. Something like this would be sufficient:
List<String> getAllLines(File file, Charset... charsets) {
    for (Charset cs: charsets) {
        try {
            return Files.readAllLines(file.toPath(), cs);
        } catch (MalformedInputException e) {
            ...
        } catch (IOException e) {
            ...
        }
    }
    // error
}

(this is just an example, your arguments may vary based on need)
If you switched encodings while reading the document, you have the potential of interpreting some characters as valid UTF-8 characters when in fact they were ISO-8859-1 characters.


text:
Q: "put one's attention on X" vs. "put one's attention to X" I wonder which form(s) are correct amongst the following:

*

*Someone put their attention on X.

*Someone put their attention to X.

Example:

As a result of the rapid advancement of neural-network-based architectures and availability of large-scale datasets for question answering, researchers put their attention to building automatic question-answering systems.

A: In this case, "put their attention to" is correct; however, to make the sentence sound less passive, it may be better to use "attended to."

A: I think put one's attention to something means to devote oneself to solving a problem, whereas put one's attention on something merely means to decide to pay attention to it.
So, "I decided to put my attention to the cat" would entail solving some problem related to the cat; "I decided to put my attention on the cat" could mean spending quality time with the cat.


text:
Q: AudioKit AKFFTTap does not fill fftData array above bin 512 I want to increase the FFT resolution and have more bins per signal analysed.
When i leave the fftSize and all buffer lengths at default in AKSettings i get a 512 bin fft, the fftData array has all of the 512 array elements filled out.
From this I am able to get real and imag parts, magnitudes and it works.
If i setup the ffttap with a higher fftsize like so
fftTap = AKFFTTap.init(mic, fftSize: .huge)
I get an increased fftData array size, the fftData.count is 1024, but only 512 array elements are filled, everything past fftData[511] are 0.0s.
Am I missing some specific configuration step when I want to increase the FFT resolution?
Anybody with some input would be very helpful, thanks!


text:
Q: how to convert currency to decimal in Azure Data Factory's copy data activity mapping In Azure Data Factory i have a pipe line and pipeline has one copy data activity that has a source a REST api and a destination a SQL DB Table.
In the mapping of this copy activity i am telling that which columns from REST dataset (on left) will be mapped to which columns on SQL dataset (onright)

there is a json property in Rest "totalBalance" that is supposed to be mapped to "Balance" field in DB Tables.
Json has "totalBalance" as string for example "$36,970,267.07" so how to convert this into decimal so that i can map it to DataBase table?
do i need to some how use mapping activity instead of copy activity ? or just the copy activity can do that ?

A: finally what worked for me was having a copy activity and a mapping activity.
Copy activity copies data from REST to SQLtable where all the columns are VARCHAR type and from that table a mapping activity sinks data from SQL(allString) tables to actual destination SQLTable.
But between mapping and sink i added "Derived Column" for each source property i want to convert and in expression of that derived column i am using expression like this
toDecimal(replace(replace(totalAccountReceivable, '$', ''),',',''))

A: The copy activity can not do that directly.
There are two way I think can do this:
First:change decimal to varchar in DB Tables.
Second:add a lookup activity before copy activity and remove the '$' in 'totalBalance' column,then add an additional column like this:

Finally,use this additional column map to 'Balance' column.
Hope this can help you.


text:
Q: How to calculate the optimal number of bins for severly skewed data I have a data set with a sample size over three million numeric values. Close to 20% are either 0 or 1, with the maximum being nearly 18500. So the data is clearly quite heavily positively skewed.
I am trying to categorize some of this data by putting it into bins of equal width, to use the Chi-sqaure test and Cramers V to look for associations between this variable and a categorical one, so I decided to try and find the optimal number of bins. Using the Freedman-Diaconis rule it gave me a value of 126044.0262335108, this is clearly a ridiculously large number of bins for the data.
Breaking the set into the Inter-decile range also proved fruitless giving me [0, 1, 1, 2, 3, 5, 8, 17, 47]
Reading elsewhere the square root of the sample size was suggested, this gave 1732.05081 which is more reasonable. However the method is quite crude.
I also looking into Doane's formula given here. But reading up on this method it seems to have been based on an incorrect hypothesis.
How should I deal with this level of skew in the data?
What is the best way to categorize this data?


text:
Q: C++ bitwise operations on structs and classes I'm developing a generic Genetic Algorithm library, where the chromosome of each organism is its bit representation in memory. So, for instance, if I want to mutate a organism, I flip the bits themselves of the object randomly.
At first, I tried using the bitset class from the C++ standard library, but, when converting back to an object T, my only option was using the to_ullong member function, which was a problem for representations with a number of bits larger than the size of an unsigned long long.
Then I decided to create a generic library for bitwise operations on any object T, so I could apply these operations directly onto the objects themselves, instead of converting them first to a bitset.
So you can see what I'm trying to achieve, here's a function from the library:
template<typename T>
void flip(T& x, size_t const i)
{
    x ^= 1 << i;
}

And it's used in the GA library like this:
template<typename T>
void GeneticAlgorithm<T>::mutate(T& organism, double const rate)
{
    std::random_device rd;
    std::mt19937 mt(rd());

    std::uniform_real_distribution<double> dist(0, 1);

    for(size_t i = 0; i < m_nBits; ++i)
        if(dist(mt) <= rate)
            bit::flip(organism, i);
}

It would be really nice if this worked, however now I'm getting this error message from the VC++ 2015 RC compiler:

Severity  Code    Description Project File    Line Error  C2677   binary '^': no
  global operator found which takes type 'T' (or there is no acceptable
  conversion)   GeneticAlgorithm    path\geneticalgorithm\geneticalgorithm\BitManip.hpp 57

If I correct this error for the ^, I get more for the other operators.
I haven't used bitwise operators before in my code, so I guess these operators are not supposed to be used with any object? If so, how could I work around the problem?

A: What you want to achieve can be done like that (see Peter Schneider's comment):
template<typename T> void flip(T& x, size_t const i) {
    unsigned char* data = reinterpret_cast<unsigned char*>(&x);
    data[i/8] ^= (1 << (i%8));
}

what it does is reinterpreting your data x as an array of bytes (unsigned char), then determining which byte should be flipped (i/8), then which bit within the byte (i%8).
Note: in addition, it may be safe to add at the beginning of the function:
assert(i < sizeof(T)*8)

A: I am under the impression that you are not yet fully appreciating the object oriented features C++ offers. (That's not untypical when coming from a more data-centric programming in C. C++ is specifically designed to make that transition at the desired speed and to make it painless.)
My suggestion is to encapsulate the flip operation in an organism and let the organism handle it. As an illustration (untested, but compiles):
#include<climits>  // CHAR_BIT
#include<cstdlib>  // exit()

class string;
void log(const char *);

// inaccessible from the outside
constexpr int NUM_TRAITS = 1000;
constexpr size_t TRAIT_ARR_SZ = (NUM_TRAITS+CHAR_BIT-1)/CHAR_BIT;

class Organism
{

    char traits[TRAIT_ARR_SZ];
    int flips[NUM_TRAITS];

    /////////////////////////////////////////////////////////////
    public:

    Organism()  {  /* set traits and flips zero */  }

    // Consider a virtual function if you may derive
    /** Invert the trait at index traitIndex */
    void flipTrait(int traitIndex)
    {
        if( traitIndex >= NUM_TRAITS ) { log("trait overflow"); exit(1); }

        int charInd = traitIndex / CHAR_BIT;
        int bitInd = traitIndex % CHAR_BIT;

        traits[traitIndex] ^= 1 << bitInd;
        flips[traitIndex]++;
    }

    // Organisms can do so much more!
    void display();
    void store(string &path);
    void load(string &path);
    void mutate(float traitRatio);
    Organism clone();
};


text:
Q: What happens if memory leaks on rootfs? I have a linux totally on rootfs ( which as I understand is an instance of ramfs ). There's no hard disk and no swap. And I got a process that leaks memory continuously. The virutal memory eventually grows to 4 times the size of physical memory, shown with top. I can't understand what's happening. rootfs is supposed to take RAM only, right ? If I have no disk to swap to, how does the Virtual Memory grows to 4 times the physical memory ?

A: Not all allocated memory has to be backed by a block device; the glibc-people consider this behavior a bug:
BUGS
   By default, Linux follows an optimistic memory allocation
   strategy.  This means that when malloc() returns non-NULL
   there is no guarantee that the memory really is available.
   This is a really bad bug.  In case it turns out that the
   system is out of memory, one or more processes will be killed
   by the infamous OOM killer.  In case Linux is employed under
   circumstances where it would be less desirable to suddenly
   lose some randomly picked processes, and moreover the kernel
   version is sufficiently recent, one can switch off this
   overcommitting behavior using a command like:

       # echo 2 > /proc/sys/vm/overcommit_memory

   See also the kernel Documentation directory, files
   vm/overcommit-accounting and sysctl/vm.txt.


text:
Q: When a library doesn't return promises, how can I use Promise.all to wait for the callbacks to be done? fs.readdir doesn't seem to return a promise. So in a situation like this, how can I apply a promise-like approach for avoiding "indent hell"?
let tasks = []
fs.readdir(testDir, (err, files) => {
  files.forEach((file) => {
    console.log("file", file);
    // do stuff
  });
  // tasks[0].resolve() // I was trying to create promises to pass to tasks and then resolve
  // but couldn't figure out how to do it neatly.
});
console.log('tasks', tasks)

fs.readdir(trainDir, (err, files) => {
  files.forEach((file) => {
    console.log("file", file);
    // do stuff
  });
  // tasks[1].resolve()
});
Promise.all(tasks).then(() => {
    console.log('tasks done')
})

Obviously I could just trigger each progressive step as another callback:
fs.readdir(testDir, (err, files) => {
  files.forEach((file) => {
    console.log("file", file);
    // do stuff
    fs.readdir(trainDir, (err, files) => {
      files.forEach((file) => {
        console.log("file", file);
        // do stuff
      });
      console.log('tasks done')
    });
});

But Promises were made to avoid this indention pattern. So how do I use them here?

A: fs.promises in any reasonably recent version of Node will give you promisified versions of each fs function.
const fs = require('fs').promises;
Promise.all([
    fs.readdir(testDir).then((files) => {
        // ...
    }),
    fs.readdir(trainDir).then((files) => {
        // ...
    })
])
    .then(() => {
        console.log('tasks done')
    })
    .catch((err) => {
        console.log('encountered error')
    });


text:
Q: How do I nest data from one Spark dataframe in another dataframe based on a condition I have 2 dataframes:
val df1 = sc.parallelize(Seq((123, 2.23, 1.12), (234, 2.45, 0.12), (456, 1.112, 0.234))).toDF("objid", "ra", "dec")

val df2 = sc.parallelize(Seq((4567, 123, "name1", "val1"), (2322, 456, "name2", "val2"), (3324, 555, "name3", "val3"), (5556, 123, "name4", "val4"), (3345, 123, "name5", "val5"))).toDF("specid", "objid", "name", "value")

They look like below:
df1.show()

+-----+-----+-----+
|objid|   ra|  dec|
+-----+-----+-----+
|  123| 2.23| 1.12|
|  234| 2.45| 0.12|
|  456|1.112|0.234|
+-----+-----+-----+

df2.show()
+------+-----+-----+-----+
|specid|objid| name|value|
+------+-----+-----+-----+
|  4567|  123|name1| val1|
|  2322|  456|name2| val2|
|  3324|  555|name3| val3|
|  5556|  123|name4| val4|
|  3345|  123|name5| val5|
+------+-----+-----+-----+

Now I want to nest df2 inside df1 as a nested column so the schema should look like below:
val new_schema = df1.schema.add("specs", df2.schema)

new_schema: org.apache.spark.sql.types.StructType = StructType(StructField(objid,IntegerType,false), StructField(ra,DoubleType,false), StructField(dec,DoubleType,false), StructField(specs,StructType(StructField(specid,IntegerType,false), StructField(objid,IntegerType,false), StructField(name,StringType,true), StructField(value,StringType,true)),true))

The reason I wanted to do it this way was because there is a one to many relationship between df1 and df2, which means there are more than 1 specs per objid. And I am not going to join only these two tables. There are about 50 tables that I want to ultimately join together to create a mega table. Most of those tables have 1 to n relationships and I was just thinking about a way to avoid having a lot of duplicate rows and null cells in the ultimate join result.
The ultimate result would look something like:
+-----+-----+-----+----------------------+
|                 |          specs       |
|objid|   ra|  dec| specid| name  | value|
+-----+-----+-----+------+----+-------+  |
|  123| 2.23| 1.12| 4567  | name1 | val1 |
|                 | 5556  | name4 | val4 |
|                 | 3345  | name5 | val5 |
+-----+-----+-----+----------------------+
|  234| 2.45| 0.12|                      |
+-----+-----+-----+----------------------+
|  456|1.112|0.234| 2322  | name2 | val2 |
+-----+-----+-----+----------------------+

I was trying to add the column to df1 using .withColumn but ran into errors.
What I actually wanted to do was to select all the columns from df2 with the condition where df2.objid = df1.objid to match the rows and make that the new column in df1 but I am not sure if that's the best approach. Even if so, I am not sure how to do that.
Could someone please tell me how to do this?

A: As per my knowledge, you cannot have dataframe inside another dataframe(same is the case with RDDs).
What you need is a join between two dataframes. You can perform different types of joins and join the rows from two dataframes(this is where you make nest df2 columns inside df1)

A: You need to join both the dataframes based on the column objid like below
val join = df1.join(df2, "objid")
join.printSchema()

output:
root
 |-- objid: integer (nullable = false)
 |-- ra: double (nullable = false)
 |-- dec: double (nullable = false)
 |-- specid: integer (nullable = false)
 |-- name: string (nullable = true)
 |-- value: string (nullable = true)

and when we say
join.show()

the output will be
+-----+-----+-----+------+-----+-----+
|objid|   ra|  dec|specid| name|value|
+-----+-----+-----+------+-----+-----+
|  456|1.112|0.234|  2322|name2| val2|
|  123| 2.23| 1.12|  4567|name1| val1|
+-----+-----+-----+------+-----+-----+

for more details you can check here
Update:
I think you are looking for something like this
df1.join(df2, df1("objid") === df2("objid"), "left_outer").show()

and the output is:
+-----+-----+-----+------+-----+-----+-----+
|objid|   ra|  dec|specid|objid| name|value|
+-----+-----+-----+------+-----+-----+-----+
|  456|1.112|0.234|  2322|  456|name2| val2|
|  234| 2.45| 0.12|  null| null| null| null|
|  123| 2.23| 1.12|  4567|  123|name1| val1|
|  123| 2.23| 1.12|  5556|  123|name4| val4|
|  123| 2.23| 1.12|  3345|  123|name5| val5|
+-----+-----+-----+------+-----+-----+-----+


text:
Q: In LibreOffice Calc, can be a digit added directly after a regex match in single find/replace operation? I want to add character 5 after certain pattern found in the column (e.g. 4 digits).
Example:   aa1234bb → aa12345bb
Method:
Find: ([0-9]{4})  with Regular Expressions option checked
Replace: $15   - of course, this won't work, but workaround as $1\u0035 does not work, too, it creates 1234\u0035.
The workaround can be made using additional step, i.e. Find: \u0035, no regex, Replace: 5. But can be the replacement made without this workaround which adds one step?

A: If $15 doesn't work in your version, then &5 works for a single group reference.


text:
Q: How did intent-filter change from Android 2 to Android 4? I have the following intent-filter in my AndroidManifest.xml which works perfectly well in Android 2.x.x and does not do anything in Android 4.x.x:
  <intent-filter
    android:icon="@drawable/ic_fx_603p_pf"
    android:label="FX-603P Program File"
    android:priority="1"
  >
    <category
      android:name="android.intent.category.DEFAULT"
    ></category>
    <action
      android:name="android.intent.action.VIEW"
    ></action>
    <data
      android:host="*"
      android:pathPattern=".*\\.pf"
      android:scheme="file"
    ></data>
  </intent-filter>

The question is: What has changes and how can I make the intent work again?
The expected behaviour: In selecting a file with *.pf extension in a file-manger (like Astro) my application should be started and the file should be opened. Also the file-manger should use us the provided icon to visualize the file.

A: Well after some experimenting I found out that android:mimeType is not mandatory. Therefore the solution is:
  <intent-filter
    android:icon="@drawable/ic_fx_602p_pf"
    android:label="FX-602P Program File"
    android:priority="1"
  >
    <category
      android:name="android.intent.category.DEFAULT"
    ></category>
    <action
      android:name="android.intent.action.VIEW"
    ></action>
    <data
      android:host=""
      android:mimeType="*/*"
      android:pathPattern=".*\\.pf"
      android:scheme="file"
    ></data>
    <data
      android:host="*"
      android:mimeType="application/x-fx-602p.program"
    ></data>
  </intent-filter>

As a little extra I found out that an <intent-filter> can have two ore more <data> tags. If either match the intent is called (logical OR)
Inside a  tag all attributes must match (logical AND).
However there is a problem with this solution: It seems there is a bug in Android 2.x and the attributes of the <data> are not strictly treated logical AND resulting in all files being matched when the android:mimeType attribute is set. Ah well, you can't have it both ways and will go with the future if that is the case.


text:
Q: ZeroDivisionError: float division by zero on a pandas dataFrame I have a function that run over dataFrames and do some manipulations such as division,
My issues is that some of the values are 0 and I get an error ZeroDivisionError: float division by zero
my goal that if I have a 0 as denominator it return Nan
my function look like this:
def get_roic(BS, KPI, IC):
     table = KPI.loc['fcf'].to_frame('fcf')
     table['Invested Capital'] = (BS.loc['st_debt'] + BS.loc['other_current_liabilities'] +
     BS.loc['lt_debt'] + BS.loc['other_lt_liabilities'] + BS.loc['total_equity'])
     table['roic'] = table['fcf'].divide(table['Invested Capital'])
     table['revenue'] = IC.loc['revenue']
     table['fcf/revenue'] = table['fcf'].divide(table['revenue'])
     return table

I tried many things such as:
def get_roic(BS, KPI, IC):
    table = KPI.loc['fcf'].to_frame('fcf')
    table['Invested Capital'] = (BS.loc['st_debt'] + BS.loc['other_current_liabilities'] + BS.loc['lt_debt'] + BS.loc['other_lt_liabilities'] + BS.loc['total_equity'])
    table['roic'] = table['fcf'].divide(table['Invested Capital'].where(table['Invested Capital'] != 0.0, np.nan))
    table['revenue'] = IC.loc['revenue']
    table['fcf/revenue'] = table['fcf'].divide(table['revenue'].where(table['revenue'] != 0.0, np.nan))
    return table

But I do not get to make it work ..
any ideas  ?

A: Have you tried this:
df['fcf/revenue'] = df['fcf'].divide(df['revenue'])
df['fcf/revenue'] = df['fcf/revenue'].replace(np.inf, np.nan)

   a   fcf  revenue  fcf/revenue
0  1  23.0     45.0     0.511111
1  2  34.0     56.0     0.607143
2  3  23.0      0.0          NaN


text:
Q: How can we set different height for particular UITabBarItem's image in UITabBar?
I have an image for middle UITabBarItem which should start from the bottom and align with existing UITabBar. How can I change the height of UITabBarItem for middle item?

A: To achieve this you need to use your custom TabBarView. It is a simple view, that pinned to the bottom. Design like you want and that's all! This is the best way without issues with working default TabBar.
every "not default looking" tab bar - it is custom


text:
Q: Is there a way in CSS to move an element in the DOM I think this is very unlikely but is there any way in CSS to achieve moving elements in the DOM? Like moving jt-menu-item-price into the jt-header in the following?

this is what I need done

37.23

this is what I need done
37.23

A: Not using CSS, no. You can manipulate the DOM using JavaScript, but not with CSS. You could 'visually' move it with CSS, but that wouldn't affect the DOM structure, just how it is presented.

A: You have to use Javascript to manipulate the DOM. CSS never affects the DOM, just let you style it.


text:
Q: How long is Spring temporary CSRF token expiration time? I enabled CSRF with spring security and it is working as expected.
I read Spring official documentation about CSRF
http://docs.spring.io/spring-security/site/docs/3.2.7.RELEASE/reference/htmlsingle/#csrf
I also read this tutorial about CSRF with Spring and AngularJS
http://www.codesandnotes.be/2015/07/24/angularjs-web-apps-for-spring-based-rest-services-security-the-server-side-part-2-csrf/

What Spring Security does is that it sets up a temporary session for
  that. So basically it goes like this:

*

*The client asks a token with an OPTIONS request.

*The server creates a temporary session, stores the token and sends back a JSESSIONID and the token to the client.

*The client submits the login credentials using that JSESSIONID and CSRF token.

*The server matches the CSRF stored for the received JSESSIONID and, if all is green-lighted, creates a new definitive JSESSIONID and a new session-based CSRF token for the client to validate its requests after the login.

As I have understood, when you are not logged in, you can get your first CSRF token by sending an OPTIONS request on any API endpoint, for example /api/login
Spring will then create a CSRF token bound to a temporary session (temporary CSRF and JSESSIONID cookies)
Thus, if I ask the CSRF token than wait a few minutes and finally try to login, the CSRF token may have expîred and I will have to ask another one.
I couldn't find how to configure the temporary Spring session expiration time and I couldn't find what was its exact default duration.
Does anyone has any information about that ?

A:
creates a new definitive JSESSIONID and a new session-based CSRF token

this is a session fixation strategy.
there are at least 2 strategies for CSRFToken generation.

*

*per session

*per request
The default behaviour should be per session. It means that as long as session would be alive one and only CSRFToken would be bound to it (but this can be changed).
after successful authentication, because of session fixation, a new session would be created with new CSRFToken.

Thus, if I ask the CSRF token than wait a few minutes and finally try
  to login, the CSRF token may have expîred and I will have to ask
  another one

this is wrong. it would stay as long as session would be active.

I couldn't find how to configure the temporary Spring session
  expiration time and I couldn't find what was its exact default
  duration

temporary session is called temporary, because it would be valid until authentication and would be replaced by a new one. But same timeout policy is applied to them as for common session. you can configure session-timeout in web.xml using session-config. the default value of Tomcat is 30 minutes.


text:
Q: How to add carousel between four images? In this code you will find 4 divs of images every one takes 50% of the full width so there always will be 2 images appeared (50% 1st one + 50% 2nd one) and the other 2 images should be appeared when the use click the arrows at right and left for example.
I added the html code with nice caption but I want to know how can I make this carousel working and I don't want dots buttons, I want arrows at right and left ??

.section-news {
    padding: 0;
}

.newbox {
    width: 100%;
    display: inline-block;
}

.newsbox .imgbox {
    float: left;
    width: 50%;
    position: relative;
    overflow: hidden;
    background-color: #000;
}

.newsbox .imgbox img {
    max-width: 100%;
    height: auto;
    transform: scale(1.15);
    transition: transform 2s;
}

.newsbox .imgbox:hover img {
    transform: scale(1.03);
}

.newsbox .imgbox .details {
    position: absolute;
    top: 40px;
    bottom: 40px;
    left: 40px;
    right: 40px;
    background: rgba(0,0,0,.8);
    transform: scaleY(0);
    transition: transform 0.5s;
}

.newsbox .imgbox:hover .details {
    position: absolute;
    top: 40px;
    bottom: 40px;
    left: 40px;
    right: 40px;
    background: rgba(0,0,0,.8);
    transform: scaleY(1);
}

.newsbox .imgbox .details .content {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    text-align: center;
    padding: 15px;
    color: #fff;
}

.newsbox .imgbox .details .content h3 {
    color: #fff;
    font-size: 170%;
}

Hello to the world

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Hello to the world

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Hello to the world

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Hello to the world

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

A: Are you trying to use jQuery in the process or only css?


text:
Q: EOL Handling for Windows Pipelines I have windows apps with XML text files that I edit on windows and check into GitHub.   The files have correct Windows EOL formatting on my dev machine.  Then I feed it through a Concourse CI pipeline using the Git resource and a windows worker to build an MSI.   When I install the MSI on a Windows machine the XML text files have Linux EOL formatting.
What is the best way to fix this?  If I understand Concourse correctly the Git resource is a docker container running on Linux so I can see why the files would get checked with Unix EOL formatting but I don't understand why it doesn't get converted to Windows formatting when the container is made available to the windows task.
Update: Slightly more complicated I have some steps that run on the Linux worker so the files need to have Linux EOL formatting when being used on the Linux worker.    Example... pull a repos and pass it off to a job running on Linux to do a bunch of npm | grunt | bower type stuff then shuttle the files over to a Windows worker to build some ASP.NET Web API projects and use the Linux output as the Web UI and package it all up into an MSI.

A: One better way to ensure eol keep consistent is to manage them through .gitattributes core.eol rules
That will avoid the effect of global configurations (applying to all repos) like
git config core.autocrlf

If true, that global rule (possibly active on ConcourseCI) would change eol automatically.
But a .gitattribute can be added to your repo, and will have precedence. That will ensure consistency.


text:
Q: Как адаптировать виджет комментариев? Я адаптировал виджет по ширине блока, в котором он находится; но дело в том, что при публикации в нем картинки большого размера (имеется в виду, что виджет шириной к примеру 500px, а картинка 800px) картинка обрезается. Для того чтобы она встала полностью на весь размер в чате нужно обновлять страницу.
Так выглядит картинка после публикации:

А так картинка выглядит после обновления страницы сайта:

A: Никак, даже если выставить width: 'auto', то сработает расчет размеров только при загрузке виджета. Можно конечно переписать стили индивидуально для кнопок, записей и картинок, но смысл?


text:
Q: how to infere new datatype property I have created a simple ontology and am trying to execute an SWRLrule (Please see the owl file). I use Pellet reasoner, but I didn't find the result of the inference. my rule is: Rule: Patient(?x), hasBloodSugar(?x, ?y), hasBloodSugarLevel(?y, 90) -> hasPatientStateLevel(?x, "Normal").Please tell me what I've done wrong?
<?xml version="1.0"?>

<!DOCTYPE Ontology [
    <!ENTITY xsd "http://www.w3.org/2001/XMLSchema#" >
    <!ENTITY xml "http://www.w3.org/XML/1998/namespace" >
    <!ENTITY rdfs "http://www.w3.org/2000/01/rdf-schema#" >
    <!ENTITY rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns#" >
]>

<Ontology xmlns="http://www.w3.org/2002/07/owl#"
     xml:base="http://www.semanticweb.org/acer/ontologies/2015/10/medicalOntology"
     xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
     xmlns:xml="http://www.w3.org/XML/1998/namespace"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
     xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
     ontologyIRI="http://www.semanticweb.org/acer/ontologies/2015/10/medicalOntology">
    <Prefix name="" IRI="http://www.semanticweb.org/acer/ontologies/2015/10/medicalOntology#"/>
    <Prefix name="p1" IRI="http://example.org/file1#"/>
    <Prefix name="owl" IRI="http://www.w3.org/2002/07/owl#"/>
    <Prefix name="rdf" IRI="http://www.w3.org/1999/02/22-rdf-syntax-ns#"/>
    <Prefix name="xsd" IRI="http://www.w3.org/2001/XMLSchema#"/>
    <Prefix name="onto" IRI="http://www.semanticweb.org/acer/ontologies/2015/10/untitled-ontology-104#"/>
    <Prefix name="rdfs" IRI="http://www.w3.org/2000/01/rdf-schema#"/>
    <Prefix name="swrl" IRI="http://www.w3.org/2003/11/swrl#"/>
    <Prefix name="swrlb" IRI="http://www.w3.org/2003/11/swrlb#"/>
    <Prefix name="Ontology" IRI="http://www.semanticweb.org/acer/ontologies/2015/10/"/>
    <Declaration>
        <Class abbreviatedIRI="onto:BloodPressure"/>
    </Declaration>
    <Declaration>
        <Class abbreviatedIRI="onto:BloodSugar"/>
    </Declaration>
    <Declaration>
        <Class abbreviatedIRI="onto:Doctor"/>
    </Declaration>
    <Declaration>
        <Class abbreviatedIRI="onto:HealthStatue"/>
    </Declaration>
    <Declaration>
        <Class abbreviatedIRI="onto:Patient"/>
    </Declaration>
    <Declaration>
        <Class abbreviatedIRI="onto:Person"/>
    </Declaration>
    <Declaration>
        <Class abbreviatedIRI="onto:Temperature"/>
    </Declaration>
    <Declaration>
        <Class abbreviatedIRI="onto:VitalBodyMeasurement"/>
    </Declaration>
    <Declaration>
        <ObjectProperty IRI="#hasBloodSugar"/>
    </Declaration>
    <Declaration>
        <ObjectProperty abbreviatedIRI="onto:hasMeasurement"/>
    </Declaration>
    <Declaration>
        <DataProperty IRI="#hasBloodSugarLevel"/>
    </Declaration>
    <Declaration>
        <DataProperty IRI="#hasBloodSugarUnits"/>
    </Declaration>
    <Declaration>
        <DataProperty IRI="#hasPatientStateLevel"/>
    </Declaration>
    <Declaration>
        <NamedIndividual IRI="#BloodSugar001"/>
    </Declaration>
    <Declaration>
        <NamedIndividual IRI="#Patient1"/>
    </Declaration>
    <SubClassOf>
        <Class abbreviatedIRI="onto:BloodPressure"/>
        <Class abbreviatedIRI="onto:VitalBodyMeasurement"/>
    </SubClassOf>
    <SubClassOf>
        <Class abbreviatedIRI="onto:BloodSugar"/>
        <Class abbreviatedIRI="onto:VitalBodyMeasurement"/>
    </SubClassOf>
    <SubClassOf>
        <Class abbreviatedIRI="onto:Doctor"/>
        <Class abbreviatedIRI="onto:Person"/>
    </SubClassOf>
    <SubClassOf>
        <Class abbreviatedIRI="onto:Patient"/>
        <Class abbreviatedIRI="onto:Person"/>
    </SubClassOf>
    <SubClassOf>
        <Class abbreviatedIRI="onto:Temperature"/>
        <Class abbreviatedIRI="onto:VitalBodyMeasurement"/>
    </SubClassOf>
    <ClassAssertion>
        <Class abbreviatedIRI="onto:BloodSugar"/>
        <NamedIndividual IRI="#BloodSugar001"/>
    </ClassAssertion>
    <ClassAssertion>
        <Class abbreviatedIRI="onto:Patient"/>
        <NamedIndividual IRI="#Patient1"/>
    </ClassAssertion>
    <ObjectPropertyAssertion>
        <ObjectProperty IRI="#hasBloodSugar"/>
        <NamedIndividual IRI="#Patient1"/>
        <NamedIndividual IRI="#BloodSugar001"/>
    </ObjectPropertyAssertion>
    <DataPropertyAssertion>
        <DataProperty IRI="#hasBloodSugarLevel"/>
        <NamedIndividual IRI="#BloodSugar001"/>
        <Literal datatypeIRI="&xsd;integer">90</Literal>
    </DataPropertyAssertion>
    <SubObjectPropertyOf>
        <ObjectProperty IRI="#hasBloodSugar"/>
        <ObjectProperty abbreviatedIRI="onto:hasMeasurement"/>
    </SubObjectPropertyOf>
    <ObjectPropertyDomain>
        <ObjectProperty IRI="#hasBloodSugar"/>
        <Class abbreviatedIRI="onto:Patient"/>
    </ObjectPropertyDomain>
    <ObjectPropertyDomain>
        <ObjectProperty abbreviatedIRI="onto:hasMeasurement"/>
        <Class abbreviatedIRI="onto:Patient"/>
    </ObjectPropertyDomain>
    <ObjectPropertyRange>
        <ObjectProperty IRI="#hasBloodSugar"/>
        <Class abbreviatedIRI="onto:BloodSugar"/>
    </ObjectPropertyRange>
    <ObjectPropertyRange>
        <ObjectProperty abbreviatedIRI="onto:hasMeasurement"/>
        <Class abbreviatedIRI="onto:VitalBodyMeasurement"/>
    </ObjectPropertyRange>
    <DataPropertyDomain>
        <DataProperty IRI="#hasBloodSugarLevel"/>
        <Class abbreviatedIRI="onto:BloodSugar"/>
    </DataPropertyDomain>
    <DataPropertyDomain>
        <DataProperty IRI="#hasBloodSugarUnits"/>
        <Class abbreviatedIRI="onto:BloodSugar"/>
    </DataPropertyDomain>
    <DataPropertyDomain>
        <DataProperty IRI="#hasPatientStateLevel"/>
        <Class abbreviatedIRI="onto:Patient"/>
    </DataPropertyDomain>
    <DataPropertyRange>
        <DataProperty IRI="#hasBloodSugarLevel"/>
        <Datatype abbreviatedIRI="xsd:integer"/>
    </DataPropertyRange>
    <DataPropertyRange>
        <DataProperty IRI="#hasBloodSugarUnits"/>
        <Datatype abbreviatedIRI="xsd:string"/>
    </DataPropertyRange>
    <DataPropertyRange>
        <DataProperty IRI="#hasPatientStateLevel"/>
        <Datatype abbreviatedIRI="xsd:string"/>
    </DataPropertyRange>
    <DLSafeRule>
        <Body>
            <ClassAtom>
                <Class abbreviatedIRI="onto:Patient"/>
                <Variable IRI="urn:swrl#x"/>
            </ClassAtom>
            <ObjectPropertyAtom>
                <ObjectProperty IRI="#hasBloodSugar"/>
                <Variable IRI="urn:swrl#x"/>
                <Variable IRI="urn:swrl#y"/>
            </ObjectPropertyAtom>
            <DataPropertyAtom>
                <DataProperty IRI="#hasBloodSugarLevel"/>
                <Variable IRI="urn:swrl#y"/>
                <Literal datatypeIRI="&xsd;integer">90</Literal>
            </DataPropertyAtom>
        </Body>
        <Head>
            <DataPropertyAtom>
                <DataProperty IRI="#hasPatientStateLevel"/>
                <Variable IRI="urn:swrl#x"/>
                <Literal datatypeIRI="&rdf;PlainLiteral">Normal</Literal>
            </DataPropertyAtom>
        </Head>
    </DLSafeRule>
</Ontology>

<!-- Generated by the OWL API (version 3.5.1) http://owlapi.sourceforge.net -->


text:
Q: Select, open and split a file I'm trying to reuse the below code to select, open and split a file. The code opens a dialog box and the file is selected, after that it looks like it is doing something but it terminates with no errors, but the split never happen. Am I missing something?
import os
from tkinter import *
from tkinter.filedialog import askopenfilename
root = Tk()
filename = askopenfilename(title="Hi slect a file")
root.destroy()

filename_n = 0
done = False
with open (filename) as in_file:
     while not done: #loop over output file names
        with open(f"out{filename_n}.dat", "w") as out_file:
            while not done:
                try:
                    line = next(in_file).strip()
                except StopIteration:
                    done = True
                    break
                if "EOD" in line:
                    break
                else:
                    out_file.write(line + '\n')
            filename_n += 1 #increment output file name integer

A: It is my fault - sorry, the code is working fine, but the output was written to the script folder and I overlooked it. I modified the code to include an output directory selection. Here is the working code.
import os
from tkinter.filedialog import askopenfilename
from tkinter import *
from tkinter.filedialog import askopenfilename
root = Tk()
filename = askopenfilename(title="Please slect a file")   #Select input file
path = filedialog.askdirectory(initialdir=os.getcwd(), title="Please select a folder:") #Select output directory
root.destroy()          #Close the dialog box

filename_n = 0
done = False
with open (filename) as in_file:
    while not done:
            with open(os.path.join(path,f"out{filename_n}.dat"), "w") as out_file:
             while not done:
                try:
                    line = next(in_file).strip()
                except StopIteration:
                    done = True
                    break
                if "EOD" in line:
                    break
                else:
                    out_file.write(line + '\n')
            filename_n += 1


text:
Q: Changing order of characters in a string using JavaScript I'm catching the date from a form as a string and pass it to a API-Request-URL.
The date string is in this format:  16022019
But the API accepts a date string only in this format: 20190216.
Basically, in my string, I need to change the position of the first 2 characters with the position of the last 4 characters.
I fixed the issue as follow:

let date = e.target.elements.date.value; // 16022019

const dateFirst = date.slice(0, 2);
const dateMiddle = date.slice(2, 4);
const dateLast = date.slice(4, 8);
date = `${dateLast}${dateMiddle}${dateFirst}`; // 20190216

But I'm not sure if this is a good solution. Is there any better way to achieve the same result?

A: I don't see any problem with your method. in case you want to know alternate you can try this.
This uses regex to capture digits of desired width and than places to desired place.

let str = `16022019`
console.log(str.replace(/(\d{2})(\d{2})(\d{4})/,"$3$2$1"))

A: You can also use destructuring assignment and rest parameter syntax to do it.

const str = `16022019`;
[d, d1, m, m1, ...year] = str.split("");
const dateStr = [...year,m,m1,d,d1].join("");
console.log(dateStr);

A: How about mapping the positions:
[/*y*/ 4, 6, /*m*/ 2, /*d*/ 0].reduce((acc, p) => acc + date.slice(p, p + 2), "")

A: using substring

var a = '16022019';
console.log(a.substring(a.length - 4, a.length) + a.substring(2, 4) + a.substring(0, 2))

using substr

var a = '16022019';
console.log(a.substr(a.length-4,4)+a.substr(2,2)+a.substr(0,2))

A: Here is a way working with dates:

function yyyymmdd() {
  var x = new Date();
  var y = x.getFullYear().toString();
  var m = (x.getMonth() + 1).toString();
  var d = x.getDate().toString();
  (d.length == 1) && (d = '0' + d);
  (m.length == 1) && (m = '0' + m);
  var yyyymmdd = y + m + d;
  return yyyymmdd;
}

console.log(yyyymmdd("16022019")) // outputs 20190216

References: https://codereview.stackexchange.com/q/184459

A: You could also do something like this by using Array#reverse and Array#join.

const data = "16022019"

const res = data.split(/(\d{2})(\d{2})(\d{4})/).reverse().join("");

console.log(res);


text:
Q: Getting name of shapefile from its path with PyQGIS I am making a Plugin and I uploaded my shp file using my shp file path, how can I extract the name of the file from it?
Example: D:/Qgis files/sub_folderName/FileName.shp
I want to save the FileName in a string as FileName using PyQGIS.

A: Utilizing the "os" library of python will provide the solution to this problem. You can use the following command to extract the filename from the complete path:
import os
os.path.basename("Write the path here").split(".")[0]

os.path.basename() extracts the filename from the given path. So, in your example case, it would be FileName.shp. Then, I split this FileName.shp with "." using the split function. So, the split function will return a list with the filename and its extension. Then, I used indexing "[0]" to extract the filename from that list. Hope I'm able to explain it properly.


text:
Q: Nativescript-vue simple select component like web I want to achieve below layout in nativescript-vue. Is there any plugin available through which I can design layout like this and it will work same as web <select> element? I just looked ListPicker component but its layout is different. Or how can I achieve a layout like this with ListPicker component?

Any help or suggestion will be appreciated.

A: Checkout nativescript-drop-down
npm i --save nativescript-drop-down

Register UI component
Vue.registerElement("DropDown", () => require("nativescript-drop-down/drop-down").DropDown)

Now you should be able to use DropDown tag in your templates.


text:
Q: A process just won't die For context: I have been playing with stable diffusion on my home server lately, but because my GPU is pretty old, the process often crashes and hangs when I try to go too far. Usually, I'd just kill it with ctrl+C and restart the process.
But today,no matter what I do, it seems like the process refuses to die.
I've looked it up a bit, it is not a "zombie" process, both sudo top and ps ux | awk '{if($8=="Z") print}' confirm it, but I cannot kill it with a sudo kill <PID> -9
If it's relevant, the process is a python virtual environment (.venv)
I can, of course, just reboot the whole machine, but I'd like to understand why it's happening, and how to prevent/fix it
Edit: It happened once again, this time I didn't ctrl+C before trying sudo kill <PID> -9 and the process closed quickly. I'm guessing the ctrl+C tries to close the process, but hangs somewhere, so the kill -9 doesn't take effect properly. If someone knows why it happens, I'd still appreciate the explanation


text:
Q: Search Multiple Items in Multiple columns I have 6 select items in a form. I want to search those 6 in MYSQL DB. I can retrieve results if I use only one, like:
$result = mysql_query("SELECT * FROM wsinmuebles WHERE Property_Type LIKE '%{$_POST['Property_Type']}%'");

But when I try more, I get no results!
$result = mysql_query("SELECT * FROM wsinmuebles WHERE
Property_Type LIKE '%{$_POST['Property_Type']}%' AND
Estado LIKE '%{$_POST['Estado']}%' AND
Ciudad LIKE '%{$_POST['Ciudad']}%' AND
Urbanizacion LIKE '%{$_POST['Urbanizacion']}%' AND
Operacion LIKE '%{$_POST['Operacion']}%' AND
Precio_bsf LIKE '%{$_POST['Precio_bsf']}%'");

This comes from a form by the POST method.
What I need is to look for Property_Type, Estado, Ciudad, Urbanizacion, Operacion and Precio_bsf variables in MYSQL DB, and receive only the results that match all those values.

A: Dont use And use Or between criteria, and after all you should know that concatenating strings and executing queries is giving possible SQL Injection, that is when instead of your search string I end your query and execute given action, for example "' and 1=1; delete wsinmuebles" if this is my serach query you will lose all your data.
  $result = mysql_query("select * from tbl1 where Name='".mysql_escape_string ($_POST["value"]."'" );

A: First, escape the post values using mysql_real_escape_string (Link) to avoid any SQL injection attacks and also issues with the data having ' characters.
Second echo the query and run it against the database and check the table data to see if the
query indeed should return some values or may be there are no matches when include the rest   of criteria since you mentioned that you are expecting the results that match all those values.

A: If a field, say Urbanizacion is null, your query will not return it.
Urbanizacion LIKE '%%'   =>   FALSE when Urbanizacion is Null

You will need to handle Nulls.  I also strongly urge you to protect the code from SQL Injection using mysql_real_escape_string
$result = mysql_query("
    SELECT * FROM wsinmuebles WHERE
    IFNULL(Property_Type,'') LIKE '" . mysql_real_escape_string($_POST['Property_Type']) ."' AND
    IFNULL(Estado,'') LIKE '" . mysql_real_escape_string($_POST['Estado']). "' AND
    IFNULL(Ciudad,'') LIKE '" . mysql_real_escape_string($_POST['Ciudad']) ."' AND
    IFNULL(Urbanizacion,'') LIKE '" . mysql_real_escape_string($_POST['Urbanizacion']) ."' AND
    IFNULL(Operacion,'') LIKE '" . mysql_real_escape_string($_POST['Operacion']) ."' AND
    IFNULL(Precio_bsf,'') LIKE '" . mysql_real_escape_string($_POST['Precio_bsf']) ."'");


text:
Q: The committee who have been working hard or the committee which has been working hard? When referring to a committee that has been working hard, which of the following would you say?

*

*The committee which has been working hard.

*The committee who have been working hard.
The committee is made up of people I know, it is not a group of unknown people so I feel strange referring to them as which, but my husband insists that is the correct usage.

A: Since you are addressing the "hard work", which is the product of individuals, it may be preferable to say who have.
When discussing the committee as an entity - say, the consensus, or location of - which has may be preferable.


text:
Q: How do I use yolk from within a python script to get the latest version for a specific package? I would like something like:
yolk.get_lastest_version_number(package_name)

which would return a version number.
Thanks!

A: Here is a function that will return the latest version number of a package, or None if there is no such package.
from yolk.pypi import CheeseShop

def get_lastest_version_number(package_name):
    pkg, all_versions = CheeseShop().query_versions_pypi(package_name)
    if len(all_versions):
        return all_versions[0]
    return None

>>> get_lastest_version_number('requests')
'2.7.0'
>>> get_lastest_version_number('pip')
'6.1.1'
>>> get_lastest_version_number('django')
'1.8.1'
>>> get_lastest_version_number('Django')    # case insensitive
'1.8.1'
>>> print get_lastest_version_number('dunno')
None


text:
Q: Constraints not working with iAd and UIImageView I have an application which has three components: ADBannerView, Bottom view and top view. The top view and bottom view share equal heights, and the top has four image views having equal widths. I have set all the required constraints and it works as expected like this:

However, as soon as I add a fourth image, AdBannerView disappears and the height of remaining two views increases like this:

I have reviewed the constraints multiple times but I am unable to understand how adding an image makes a difference. Please help, I am stuck here. I have also shared the source code here: https://www.dropbox.com/s/o8madq1fi2qfesi/AutoLayoutIssue.zip?dl=0
Thanks in advance.

A: If you add image to ImageView, then go to Document Outline, you will see the red error icon at the top right corner.
And if we tap it shows a lot of information about issue.
Let's use the standard instruments to fix this and click Change Priority. And it will works fine.


text:
Q: System keeps changing power mode while gaming Recently my laptop keeps changing power mode while gaming, like if i disconnected the charger physically.
I don't have another charger to test, this is the stock one which has been running fine for 3 years until now.
Everything works without a problem if i'm not gaming, could this be a charger problem?
What can i do to verify what's the problem if not?

A: This sometimes occurs when the graphic adapter is drawing too much current. Typically happens when you are gaming. Basically, what happens is that when you are heavily gaming, your graphic adapter becomes the main consumer of the power. When the current drawn from the charger is reaching the limit defined by the manufacturer, the overcurrent protection is triggered and all current is stopped. In this case, the laptop reacts as if the charger was disconnected and switches to the battery simultaneously reducing the CPU and GPU clock frequencies. After a while, it detects the charger and attempts to switch power source to it and the whole thing repeats again.
I have heard that several Asus laptops are suffering from this issue. It often happens that the laptop is compatible with more than one model of charger and the manufacturer supplies the one with the lowest power rating.

*

*One way to address the problem is to buy an adapter with higher power rating that is still compatible with your laptop (make sure to check compatibility).

*Another option is to play around with your graphic adapter settings and also change game settings to be less demanding.

*One more alternative method is to run the laptop without the battery. (Obviously, you will need to shut the laptop down before removing the battery). Sometimes this resolves the problem, though resulting into the lower performance in the games.


text:
Q: Disable spring-context-indexer by profile I want to enable Spring Context Indexer on a project but I am having issues with Swagger3 (check here and here).
I understand the limitations and would like to enable it, at least, at the DEV profile where we do not need Swagger running.
My goal is to disable indexing on PROD environment. From docs:
you can fallback to a regular classpath arrangement (as though no index was present at all) by setting spring.index.ignore to true, either as a system property or in a spring.properties file at the root of the classpath.

My first approach (without success) was setting an env var (Windows 10) with the following:
SPRING_APPLICATION_JSON={"spring":{"index":{"ignore":true}}}

If I create a spring.properties file and set the value accordingly it works. But I can't figure how to use different properties for each profile, I imagined it was something like the application.properties file but I was wrong.
How can I achieve that?
EDIT:
Just to be clear, this config (spring.index.ignore) will just work if inside a spring.properties file, not an application.properties one. (Just double-checked before this edit)
Actually I have one application-prod.properties and one application-dev.properties.
I don't know the difference between spring.properties and application.properties but the first one doesn't seem to work with multiple profiles as the later.
Edit 2:
Just went through org.springframework.context.index.CandidateComponentsIndexLoader and it uses SpringProperties.getFlag(IGNORE_INDEX) to read the value.
SpringProperties class is clear about the file it uses:
Reads a spring.properties file from the root of the Spring library classpath, and also allows for programmatically setting properties through setProperty. When checking a property, local entries are being checked first, then falling back to JVM-level system properties through a System.getProperty check.

I think I will need to pass a property to Java runner during initialization. Will research a little bit more about it.

A: you can use different application.properties file as follow:
add the following files to the resource folder:
application.properties
spring.profiles.active=dev #place profile name you want to use

application-dev.properties
#dev properties
...

You can create many application-env.properties you may wish
application-env.properties
#env properties
...

A: Spring Boot supports profile-specific properties files. You have to name these files with the following format: application-{profile}.properties. You can activate a profile via JVM system parameter: -Dspring.profiles.active=dev. You can read more about this subject here: https://www.baeldung.com/spring-profiles


text:
Q: Can I accomplish css transform rotateY effects in canvas I want to have a circle rotate according to its y-axis, like using rotateY in CSS.
I have looked up the document, I noticed the transform function:
http://bucephalus.org/text/CanvasHandbook/CanvasHandbook.html#transform-a-b-c-d-e-f
but I have no idea how to calculate the variable or I need a 3D library?
Any help is thankful.


text:
Q: Call a function "dynamically" in JS with something like  I'm trying to learn how to dynamically create objects and apply functions to them with JS and HTML. How can I use a <select> dropdown's text/value to call a function on an object as directly as possible? In the past I've used functions in an array, if then statement, or conditional chain but this seems like extra work.
I'm open to suggestions on dynamic object instance creation as well because I'm not sure my method in this example is best practice.
Here is my example:
HTML
<!DOCTYPE html>

        <input id="name" placeholder="name">
        <button id="new">add new object</button>

        <input id="property" placeholder="property value">
        <select id="functions">
            <option>apply a function</option>
            <option value="myFunction()">sum</option>
            <option value="myFunction2()">multiply</option>
        </select>

JS
// Class and its functions
function myClass() {
    this.existingProperty = 5
}
myClass.prototype.myFunction = function () {
    this.resultProperty = this.newProperty + this.existingProperty
}
myClass.prototype.myFunction2 = function () {
    this.resultProperty = this.newProperty * this.existingProperty
}

// Memory
const locoParentis = []
let nameField = ''
let propField = 0

// Name of object instance of myClass (for example: type dogs into the brower/HTML "name" input)
document.querySelector('#name').addEventListener('change', (e)=>{
    nameField = e.target.value
})
// Add the new objeect instance to the array (for example: click add new object to create an object called dogs with an existingProperty of 5)
document.querySelector('#new').addEventListener('click', ()=>{
    locoParentis[nameField] = new myClass()
    console.log(locoParentis)
})
// Create/set new property in object instance (for example: typing 9 in the property value input sets dogs' newProperty to 9)
document.querySelector('#property').addEventListener('input', (e)=>{
    locoParentis[nameField].newProperty = Number(e.target.value)
    console.log(locoParentis)
})

// Apply prototypical functions on object instance (for example: chosing sum outputs 14 into the console.)
document.querySelector('#functions').addEventListener('change', (e)=>{
    console.log(e.target.value)
    //HOW CAN I CHANGE THIS INTO SOMETHING LIKE locoParentis[nameField].e.target.value()
    e.target.value === "myFunction()" ? locoParentis[nameField].myFunction() : locoParentis[nameField].myFunction2()
    console.log(locoParentis[nameField].resultProperty)
})

Description: I can create a new object instance of myClass dynamically by typing a name into the name <input> but I would like to do a similar approach with the <select> and the prototypical functions of myClass.

A:

// Class and its functions
function myClass() {
    this.existingProperty = 5;
}
myClass.prototype.myFunction = function () {
    this.resultProperty = this.newProperty + this.existingProperty;
}
myClass.prototype.myFunction2 = function () {
    this.resultProperty = this.newProperty * this.existingProperty;
}

// Memory
const locoParentis = {};
let nameField;

// Name of object instance of myClass (for example: type dogs into the brower/HTML "name" input)
document.querySelector('#name').addEventListener('change', (e)=>{
    nameField = e.target.value;
})
// Add the new objeect instance to the array (for example: click add new object to create an object called dogs with an existingProperty of 5)
document.querySelector('#new').addEventListener('click', ()=>{
    locoParentis[nameField] = new myClass();
    console.log(locoParentis);
})
// Create/set new property in object instance (for example: typing 9 in the property value input sets dogs' newProperty to 9)
document.querySelector('#property').addEventListener('input', (e)=>{
    locoParentis[nameField].newProperty = Number(e.target.value);
    console.log(locoParentis);
})

document.querySelector('#functions').addEventListener('change', (e)=>{
    // you can check here for undefined
    locoParentis[nameField][e.target.value]();
    console.log(locoParentis[nameField].resultProperty);
})
<!DOCTYPE html>

        <input id="name" placeholder="name">
        <button id="new">add new object</button>

        <input id="property" placeholder="property value">
        <select id="functions">
            <option>apply a function</option>
            <option value="myFunction">sum</option>
            <option value="myFunction2">multiply</option>
        </select>

Try this one.
But there is something to consider. You don't need to add a seperate `add new object` button. A new instance can be created when you select whether to sum or multiply.