text:
Q: Filter Data From One Excel Tab, Paste In Another, Clear Filter I'd like to have an Excel tab that filters and returns the data from another tab based on the input of a text box, then simply clear the data. I used this code:
Sub PasteFilteredData()

Declare variables
Dim FiltRng As Range
Dim DestRng As Range

Set the range to be filtered
Set FiltRng = Range("DataTab!A1:Z100")

Filter the range based on a partial match of a string value
FiltRng.AutoFilter Field:=1, Criteria1:="*" & "L5" & "*", Operator:=xlFilterValues

Copy the filtered data to the clipboard
FiltRng.SpecialCells(xlCellTypeVisible).Copy

Set the destination range where the copied data will be pasted
Set DestRng = Range("SummaryTab!K7:Z7")

Paste the copied data into the destination range
DestRng.PasteSpecial xlPasteValues

Clear the filter
FiltRng.AutoFilter

End Sub

But got Runtime 1004.
L5 is the textbox.
A previous solution I used was:
Application.ScreenUpdating = False
ActiveSheet.ListObjects("TestTable").Range.AutoFilter Field:=3, Criteria1:=[J4] & "*", Operator:=xlFilterValues
Application.ScreenUpdating = True

Where J4 was the textbox, and that works fine, but I need the textbox to be on a different tab, show all of the filtered data from the other tab a few cells beneath it, then clear it when done.
Tried FiltRng and PasteSpecial and didn't work.
Thanks @jsleshem for the edit.


text:
Q: Description/title below unopened fancybox images I have a fancybox gallery, I want to add a name below each image as description before it is opened. For some reason I can't figure this out.
My code:

If I try to add a paragraph or something below each image it forces the next image to a new line.
Your help would be welcome, thanks

A: Please elaborate with relevant code sample and, if possible, a jsfiddle to show what exactly it is that you want.
Edit: Please see this link as it gives a simple solution How to write a caption under an image?
In your case, just try to enclose each image inside a div, and set the 'float' css property to 'left'

Some title

some Title

And your CSS property:
div
{
float:left;
}

Hope this helps

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convex Mixed-Integer for Non-Rigid Point Cloud Alignment I am trying to approach non-rigid alignment using Convex Mixed-Integer Algorithm, but I am new to computer vision. Does anyone know some sample code that is similar - so that I can use that as a reference?
The algorithm is based on this research paper:
MINA: Convex Mixed-Integer Programming for Non-Rigid Shape Alignment

A: Thank you for showing interest in our work.
We model the constrained optimization problem in MATLAB with the help of YALMIP library and solve it using MOSEK.


text:
Q: Adding maintenance plan in SQL Server with commands Is there a way to add a maintenance plan on an SQL server using SQL or a C# library?

A: Yes, look at the following SPs in msdb.
MSDN... Database Maintenance Plan Stored Procedures

*

*sp_add_maintenance_plan

*sp_delete_maintenance_plan_db

*sp_add_maintenance_plan_db

*sp_delete_maintenance_plan_job

*sp_add_maintenance_plan_job

*sp_help_maintenance_plan

*sp_delete_maintenance_plan


text:
Q: Textbox only date validation using javascript Tired to validate textbox allow only date format.If I enter text or textwithnumber or anyother without date format I want to show error message like 'please enter mm/dd/yyyy format'.Textbox should be allow only this mm/dd/yyyy format.How do it using javascript or jquery
function isDate() {

     var txt = document.getElementById("date").value;
     var regEx = /^\d{4}-\d{2}-\d{2}$/;

     if(txt.match(regEx)){

     alert("Please enter date format mm/dd/yyyy");

     }else{

      alert("Thanks..You have entered correct date");

     }

   }

DEMO:http://jsfiddle.net/nrt76dsq/1/

A: This works! Basic Javascript Validation!

function checkdate() {
  var input = document.getElementById("date");
  var validformat = /^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
  if (!validformat.test(input.value))
    alert("Invalid Date Format. Please correct and submit again.")
  else { //Detailed check for valid date ranges
    var monthfield = input.value.split("/")[0]
    var dayfield = input.value.split("/")[1]
    var yearfield = input.value.split("/")[2]
    var dayobj = new Date(yearfield, monthfield - 1, dayfield)
    if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield))
      alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
    else
      alert("You have entered the valid date format!")
  }
}
<input type="text" id="date" name="date" placeholder="dd/mm/yyyy" />
<button onclick="checkdate()">Check</button>

A: give it a try

function isDate() {

         var txt = document.getElementById("date").value;
         var regEx = /^\d{2}\/\d{2}\/\d{4}$/;

         if(!regEx.test(txt)){

         alert("Please enter date format mm/dd/yyyy");

         }else{

          alert("Thanks..You have entered correct date");

         }

}
<input type="text" id="date" name="date" value="dd/mm/yyyy" />
<button onclick="isDate();">Check</button>


text:
Q: How to call javascript function from code behind? I want to execute javascript function from code behind page.
I have two way that first that I can call javascript of html page in my code behind.
second is that i can write javascript function in to my code behind.
but i am not which one is better and how can i do this.
Please tell me that how can i do this.

A: ScriptManager.RegisterStartupScript(...)

Look here for details

A: Try the following in your codebehind
ClientScript.RegisterStartupScript(GetType(), "scrptName", "javascript: alert('hi'); ", true);

You can replace alert('hi'); with your javascript function you want to call from code behind.

A: You can call Js functions as a script registered on the codebehind itself.
Page.RegisterStartupScript("key","value")

key is the name you want to give the script eg. "PageClose"
value is the;
stringBuilder str = new StringBuilder()
str.Append("<script = language='javascript'>");
str.Append("window.close();");
str.Append("</script>")

here instead of using the window.close you coud append your js function as a string, ideally i put this string builder class and build the script in the constructor if i need it always in the page
Then use this in the event handler you want to execute the script
Page.RegisterStartUp("PageClose",str.ToString());

This would place the javascript before the closing  tag of the page thats rendered
Page.ClientScriptBlock("PageClose",str.ToString());

This would place the JS function after the opening  tag of the page thats rendered
Hope this helps


text:
Q: я использую Camera2API, как поставить изображение в кадр?
Суть такая, я хочу чтоб когда открывалась сессия просмотра, юзер на экране видел очертания формы человека. То есть, когда он включает камеру, чтоб на экране была картинка не только вывода изображения а и дополнительная прозрачная картинка в форме очертания(shape of body)...
Я так понимаю, что когда изображение выводиться нужно к нему прибавлять необходимую картинку и уже потом транслировать изображение на экран или возможно есть возможность транслировать изображение а на него наложить слой как бы сверху?
Вот мой код
public class CameraHelper {
private CameraCaptureSession mSession = null;
private CameraManager mCameraManager = null;
private CameraDevice mCameraDevice = null;
private String mCameraID = null;
private Context context;
private TextureView mTextureView;
private ImageReader imageReader;
private Handler handler;
private Surface jpegCaptureSurface;
private static ByteArrayOutputStream outputStream;

public CameraHelper(@NonNull CameraManager cameraManager, @NonNull String cameraID, Context context) {
    mCameraManager = cameraManager;
    mCameraID = cameraID;
    this.context = context;

    //нужно разобраться с этой строчкой, она 650 в коде
    handler = new Handler();
}

public static ByteArrayOutputStream getOutputStream() {
    return outputStream;
}

public void viewFormatSize(int formatSize) {

//      Получения характеристик камеры, Для получения характеристик необходимо
//      использовать метод getCameraCharacteristics(String cameraId). Этот метод возвращает объект
//      класса CameraCharacteristics, в котором сконцентрированы параметры по камере. В данном классе
//      сконцентрировано огромное количество параметров
    CameraCharacteristics cc;
    try {
        cc = mCameraManager.getCameraCharacteristics(mCameraID);

        // Получения списка выходного формата, который поддерживает камера
        StreamConfigurationMap configurationMap =
                cc.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

        // Получения списка разрешений которые поддерживаются для формата jpeg
        Size[] sizesJPEG = new Size[0];
        if (configurationMap != null) {
            sizesJPEG = configurationMap.getOutputSizes(ImageFormat.JPEG);
        }

        if (sizesJPEG != null) {
            for (Size item : sizesJPEG) {
                System.out.println("w:" + item.getWidth() + " h:" + item.getHeight());
            }
        } else {
            Log.e(MainActivity.LOG_TAG, "camera with id: " + mCameraID + " don`t support format: " +
                    formatSize);
        }

    } catch (CameraAccessException e) {
        Log.e(MainActivity.LOG_TAG, e.getMessage());
    }
}

public boolean isOpen() {
    return mCameraDevice != null;
}

public void setTextureView(TextureView mImageView) {
    mTextureView = mImageView;
}

//    В методе openCamera() с помощью нашего менеджера открываем камеры. В параметрах метода
//    указываем, какую камеру открывать, а также обработчик, который будет отслеживать состояния
//    открытия камеры.
public void openCamera() {
    try {
//            я так понимаю что здесь мы проверяем прописан ли у нас доступ к камере в манифесте и
//            если все в порядке то выполняется открытие камеры
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) !=
                PackageManager.PERMISSION_GRANTED) {
            return;
        }

        mCameraManager.openCamera(mCameraID, mCameraCallback, null);

    } catch (CameraAccessException e) {
        Log.e(MainActivity.LOG_TAG, e.getMessage());
    }
}

public void closeCamera() {

    if (mCameraDevice != null) {
        mCameraDevice.close();
        mCameraDevice = null;
    }
}

private CameraDevice.StateCallback mCameraCallback = new CameraDevice.StateCallback() {

    @Override
    public void onOpened(@NonNull CameraDevice camera) {
        mCameraDevice = camera;
        createCameraPreviewSession();
        System.out.println("----------" + mCameraDevice.getId());
        MainActivity.ToastPrint(mCameraDevice.getId());
    }

    @Override
    public void onDisconnected(@NonNull CameraDevice camera) {
        mCameraDevice.close();
        Log.i(MainActivity.LOG_TAG, "disconnect camera  with id:" + mCameraDevice.getId());
        mCameraDevice = null;
    }

    @Override
    public void onError(@NonNull CameraDevice camera, int error) {
        Log.i(MainActivity.LOG_TAG, "error! camera id:" + camera.getId() + " error:" + error);
    }
};

private void createCameraPreviewSession() {

//        для получения изображения нам необходимо использовать  ImageReader. Для получения
//        максимально возможной скорости передачи кадров нам необходимо использовать «сырой формат». То
//        есть, jpeg нам не подойдет, поскольку он будет давать задержку на время конвертации кадра и
//        таким образом у нас возникнет очень низкий fps. Для получения максимальной продуктивности
//        следует использовать ImageFormat.YUV_420_888.
    imageReader = ImageReader.newInstance(640, 480, ImageFormat.JPEG, 2);
    imageReader.setOnImageAvailableListener(onImageAvailableListener, handler);

    //эти 2 строчки пока не понятно зачем нужны
    SurfaceTexture texture = mTextureView.getSurfaceTexture();
    texture.setDefaultBufferSize(640, 480);
    Surface surface = new Surface(texture);

    try {
        final CaptureRequest.Builder builder =
                mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);

//            builder.addTarget(jpegCaptureSurface);
        builder.addTarget(surface);

        //это добавление возможных эффектов
//            builder.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_INCANDESCENT);
//            builder.set(CaptureRequest.CONTROL_EFFECT_MODE, CaptureRequest.CONTROL_EFFECT_MODE_SEPIA);
//            builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_SINGLE);

        mCameraDevice.createCaptureSession(
//                    Collections.singletonList(imageReader.getSurface()),
                Collections.singletonList(surface),
                new CameraCaptureSession.StateCallback() {

                    @Override
                    public void onConfigured(@NonNull CameraCaptureSession session) {
                        mSession = session;
                        try {
                            mSession.setRepeatingRequest(builder.build(), null, null);
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                    }
                },
                null
        );

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

private final ImageReader.OnImageAvailableListener onImageAvailableListener =
        new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(ImageReader reader) {
                final Image image = reader.acquireLatestImage();

                jpegCaptureSurface = reader.getSurface();

//                    handler.post(new ImageSaver(context));
            }
        };

A: Нужно в RelativeLayout в котором находиться TextureView в которое будет устанавливаться наш вывод изображения с камеры, установиться еще один  RelativeLayout которому задать параметры
android:layout_width="match_parent"
android:layout_height="match_parent"

и как задний фон вложенного RelativeLayout установить наше изображение. Но естественно картинка которую будем устанавливать должна быть прозрачно, то есть без фона, просто очертания...
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextureView
    android:id="@+id/texture"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true" />

<RelativeLayout
    android:id="@+id/control"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:background="@drawable/transparentImage">

в итоге получается так

картинку можно поменять на нужную и она будет накладываться поверх изображения которое дает нам камера.


text:
Q: How to update large amount of rows in PostgreSQL? I need to update thousands of rows in a table. For example, I have 1000 rows with ids - 1, 2.. 1000:
mytable:
| id   | value1 | value2 |
|  1   |  Null  |  Null  |
|  2   |  Null  |  Null  |
...
| 1000 |  Null  |  Null  |

Now I need to change first 10 rows. I can do it like this:
UPDATE mytable SET value1=42, value2=111 WHERE id=1
...
UPDATE mytable SET value1=42, value2=111 WHERE id=10

This requires to many requests and not very fast, so I decide to do this optimization:
UPDATE mytable SET value1=42  WHERE id in (1, 2, 3.. 10)
UPDATE mytable SET value2=111 WHERE id in (1, 2, 3.. 10)

Note: In this case I can actually write SET value1=42, value2=111 but in real world applications this sets of ids is not the same, for one rows I need to set value1, for other - value2, for some subset of rows I need to set both. Because of that I need two queries.
The problem is that I have very large amount of id's. This queries is something about 1Mb!
Q1: Is this a right way to optimize this updates?
Q2: Is it right to send queries that is so large? Can I get faster update by dividing this query into several smaller parts?
I can't use where statement, I've just have lots of row id's in my program.

A: Create a TEMPORARY TABLE and populate it with your target ids and new values. Then use UPDATE with FROM clause to join to that target and do it in a single command.
In general, whenever you have large numbers of id/values like this life gets easier if you move them into the database first.

A: Q1: Is this a right way to optimize this updates?
It should be still possible to write it in one single query using the CASE ... WHEN syntactic construct:
UPDATE mytable SET
  value1 =
    CASE
      WHEN id IN ( 1, 2, 3, 10) THEN 42
      WHEN id IN (11,12,13, 20) THEN 43
      ELSE value1
    END,
  value2 =
    CASE
      WHEN id IN ( 1, 2, 3, 10) THEN 42
      WHEN id IN (11,12,13, 20) THEN 43
      ELSE value2
    END;

etc.
You mentioned that you may have to update rows in multiple spots, and the above let you do that without problem in one single query.
Update: I overlooked the fact that speed was your main concern (you said "optimize"), and my answer is not correct in that regard. Using a temporary table as explained in the chosen answer leads to much better performances.
Q2: Is it right to send queries that is so large? Can I get faster update by dividing this query into several smaller parts?
I don't think that Postgresql should have much problems handling a large query (even much larger than 1mb). Remember that SQL DB initialization scripts can be way larger that 1mb.


text:
Q: Gnome overview search triplicate of the first letter I use Gnome 40, X11, Ubuntu 21.10.
When in overview I press a letter to search I get that letter 3 times.
If I already is in the search bar, no duplicates are created.
Any ideas on what could cause that or how to fix it?

A: I don't really have a fix for you, but I have the same issue (sometimes it's more than 3 of that letter) and for me it only happens after a suspend, not off a fresh boot. After a suspend, refreshing the session (Alt+F2 > r > Enter) also "fixes" it.
I also think it might have to do with Dash to Dock. But I'm not sure of that just yet.


text:
Q: Uncaught TypeError: Cannot read properties of undefined (reading 'top')? I have a script for scrolling, everything works on my other projects, but not on one. I can't understand what the problem is. Just started learning JS. so I will be grateful for your kind tips. The project is uploaded to firebase if anyone wants to look at it in the inspector.
$(function() {
    $("[data-scroll]").on("click", function(event){
        event.preventDefault();

        blockId = $(this).data('scroll');
        blockOffset = $(blockId).offset().top;

        $("html, body").animate({
            scrollTop: blockOffset - 50
        }, 700);

    });

    $("[data-modal]").on("click", function(event){
        event.preventDefault();

        $(modal_window).addClass('show');

    });

    $(document.querySelector(".close_modal")).on("click", function() {
        $(modal_window).removeClass('show');
    });
});

and ran into a problem with the modal window, more specifically with the animation. when clicking on the GET STARTED button, a modal window pops up. you can close it in 2 ways by clicking on the cross, the animation works hum. and clicking on the send message button, and then the window disappears without animation, although the classes are the same

$(function() {
    $("[data-scroll]").on("click", function(event){
        event.preventDefault();

        blockId = $(this).data('scroll');
        blockOffset = $(blockId).offset().top;

        $("html, body").animate({
            scrollTop: blockOffset - 50
        }, 700);

    });

    $("[data-modal]").on("click", function(event){
        event.preventDefault();

        $(modal_window).addClass('show');

    });

    $(document.querySelector(".close_modal")).on("click", function() {
        $(modal_window).removeClass('show');
    });
});
.header_nav > a, .lang_select > select {
  font-family: "TT Firs Neue", sans-serif;
  font-style: normal;
  font-weight: 400;
  font-size: 16px;
  line-height: 100%;
  color: #111A45;
  text-decoration: none;
}

.header_section {
  font-family: "TT Firs Neue", sans-serif;
  font-style: normal;
  color: #FFFFFF;
}
.header_section h3 {
  font-weight: 500;
  font-size: 7.6rem;
  line-height: 100%;
}
.header_section p {
  font-weight: 400;
  font-size: 2.4rem;
  line-height: 140%;
}

.modal_window > h4 {
  font-family: "TT Firs Neue", sans-serif;
  font-style: normal;
  font-weight: 600;
  font-size: 1.6rem;
  line-height: 2.1rem;
  background: linear-gradient(103.85deg, #F33F5E 0%, #FA8550 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}
.modal_window > h2 {
  font-family: "TT Firs Neue", sans-serif;
  font-style: normal;
  font-weight: 600;
  font-size: 3.6rem;
  line-height: 4.6rem;
  color: #111A45;
}

#name, #mail, #message {
  font-family: "TT Firs Neue", sans-serif;
  font-style: normal;
  font-weight: 400;
  font-size: 1.6rem;
  line-height: 2.1rem;
  color: #111A45;
}

.first_right {
  font-family: "TT Firs Neue", sans-serif;
  font-style: normal;
  color: #111A45;
}
.first_right h3 {
  font-family: "TT Firs Neue", sans-serif;
  font-style: normal;
  font-weight: 600;
  font-size: 4.8rem;
  line-height: 6.2rem;
  background: linear-gradient(103.85deg, #F33F5E 0%, #FA8550 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}
.first_right h4 {
  font-weight: 500;
  font-size: 2rem;
  line-height: 150%;
}
.first_right p {
  font-weight: 400;
  font-size: 1.7rem;
  line-height: 150%;
}

        Technology
        Advantages
        How it works
        Packages
        Contact

                <select>
                    <option value="0">ENG</option>
                    <option value="1">UKR</option>
                    <option value="2">PL</option>
                </select>

        <button type="submit" class="orange_btn" data-modal="#modal_window">Get started</button>

MapStars Technology

Get new customers regularly with the help of modern technologies

        <button type="submit" class="blue_btn" data-modal="#modal_window">Get started
        </button>

Contact Form

Drop Us a Line.

            <form action="">
                <input type="text" id="name" name="firstname" placeholder="First Name*">
                <input type="email" name="mail" id="mail" placeholder="E-mail*">
                <input type="text" name="message" id="message" placeholder="Message...">
                <button type="submit" class="close_modal orange_btn">Send a Message</button>
            </form>

Technology

GEO advertising is a technology for the automatic promotion of a business using modern technologies and
                services.

The technology is specially made to promote almost all types of businesses. Cafes, restaurants, beauty
                salons and hairdressers, hotels and hostels, service stations and tire shops, repair service centers,
                online stores, grocery stores, supermarkets, photo studios, publishing houses, confectioneries, and many
                others have already used the technology.


text:
Q: I need to review 2 seminal CompSci papers in a chosen topic, suggestions please I come from a multimedia background as opposed to a pure-CS background so I would find a heavy CS-paper about subjects like algorithms hard to review.
I'm interested mainly in web technologies, particularly areas like web standards, push technologies (comet, web hooks etc..), social graphing, online data portability. Other topic suggestions are welcome too.
The problem is that any papers that I can find on these topics couldn't really be called seminal because they are quite recent and consequently haven't been cited by very many other papers.
I'd love to hear suggestions about research topics or recommended papers in a chosen topic.

A: Probably too late, but you never know...
Trust metrics are a topic that is fairly abstract and algorithmic, but with important applications to important trends in web services, particularly recommender networks.  I wrote a brief annotated bibliography on some research on trust metrics that are relevant to Raph Levien's idea of attack-resistant trust metrics.
The original Google papers, The PageRank citation ranking: Bringing order to the Web. http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-66&format=pdf&compression=. and The Anatomy of a Large-Scale Hypertextual Web Search Engine are excellent for discussion.  Levien has explained how PageRank can be seen as an attack-resistant trust metric.

A: I think the seminal paper for the hypertext concept is As We May Think, by Vannevar Bush.
Another highly influential...system? paper? is the Xanadu approach.
Of course, the Web's seminal paper is Tim Berners-Lee's initial proposal.
I think there's a vast...unacademicalness (made that word up) here. Who wrote the academic paper for Facebook or other social media? What about Mosaic?  Livejournal is rumored to have been written in bits and pieces for student projects initially. Maybe there are papers that got written for them - I don't know. Doesn't seem like it tho'.

A: None of your areas of interest is really "foundational", which is probably why you have received so few responses.  But here are a couple of ideas of topics on which you should be able to find seminal papers with some help from a reference librarian, and they have some connection to networks and computing:

*

*Dijkstra's seminal algorithm for finding shortest paths.

*Minimum spanning tree—I'd have a look at Bernard Chazelle's paper on doing MST in inverse-Ackermann time; he'll have some older references.
One suggestion that may be further from your interests, but one I've actually read and is a stunningly good paper:

*

*Don Knuth's original paper on LR parsing.


text:
Q: JavaScript Change Cursor Icon I already have the conditions and everything worked out, only thing I need is the syntax in JavaScript to change the cursor to the hand, like the user has moused-over a link, and then I need the syntax to change the cursor to the arrow, like they moused-out of the link. Not much to it, just need the JavaScript syntax for changing cursors.
Only thing is this needs to work in IE, FF, Chrome, Safari, and preferably Opera.
Thanks in advance!

A: First, I'm shocked this question has no answers and no comments about how easy it would be to Google the answer.
The syntax you're looking for is: object.style.cursor = 'pointer', where object is the DOM object for which you're trying to change the cursor.
Here's an example: http://jsfiddle.net/3q5Yh/

A: You would be done using below syntax.
$('.className').css('cursor' , 'pointer'); // using className Selector.

Or
$('#idName').css('cursor' , 'pointer');  //Using Id Selector.


text:
Q: Not matching words with number just with regex I'm trying to match all words in a line after (After this match) except those containing a number For example in a line I have :
After this match word word1 worldtwo word3 word4 wordfive 502 875

I want to match only words without numbers the result should be :
word worldtwo wordfive

The number of words in the line could change
I tried After this match ([a-zA-Z]*) but it matched only one word
Please see here :
http://www.rubular.com/r/HykbS2Eajk
I'm using cakephp with regex but I need to do it only with regex

A: You can use this pattern:
(?:match|\G(?<!^)).*?(\b[a-zA-Z]+\b)

It's a variant of THIS "almost" general method... You can check it for more details...
Live DEMO

A: You can use word boundaries:
 (\b[a-zA-Z]+\b)

a word boundary is a zero-width limit between a word character and a non-word character. word characters are [a-zA-Z0-9_], since this class contains digits too, you can't have a word boundary between a letter and a digit.
To obtain the result you want after a precedent match (After this match in your example), you can use this pattern (in PHP, not rubular):
/(?>After this match|\G(?<!^)(?>\W*\S*[0-9]\S*)*)\W+\K\b[a-z]+\b/i

A: After this select.*?\s([^\d\s]+)(?:\s|$)

We're first matching 'After this select', then reluctantly (as little as possible) of any character, then a space, then capturing anything that is not a digit and not a space — in other words, we're capturing words without digits — then a space or an end-of-string anchor, to make sure we don't capture parts of words.
If you match repeatedly, the string you're looking for will be in your captured groups.

A: Hmm you could do this using two regex patterns:
INPUT
After this match word word1 worldtwo word3 word4 wordfive 502 875
first to get all the characters after After this match:
Pattern
(?<=After this match )(.+?$)
OUTPUT
word word1 worldtwo word3 word4 wordfive 502 875
Then use the second pattern to get the words without numbers:
PATTERN
\b[^\d\s]+?\b
OUTPUT
word
worldtwo
wordfive

Tested it here:
gskinner.com/RegExr/
I'm trying to come up with one pattern version now, so if I'll manage to do this I'll edit my post : )
EDIT
Here is a one regex version:
(?:(?<!\s)After this match|\G).+?(\b[^\d\s]+?\b)

You get the matches in the group 1
OUTPUT
Match 1: After this match word
Group 1: word
Match 2: word1 worldtwo
Group 1: worldtwo
Match 3: word3 word4 wordfive
Group 1: wordfive

A: I took some code from answers and I modified my php as this :
preg_match_all ("/(?:After this match|\G(?<!^)).*?(\b[a-zA-Z]+\b)/i", $content, $docteur); //1
print_r( $docteur[1][0].' '.$docteur[1][1].' '.$docteur[1][2].' '.$docteur[1][3].' '.$docteur[1][4].' '.$docteur[1][5]);

So it will take the 5 first words found in the line with my criteria (without numbers)


text:
Q: what are different ways to read specific lines from text file in java? I am new baby in Java Programming, i want to know what is efficient way to read specific line from text file in java?

A: Use this but it has less efficiency!
String line = FileUtils.readLines(file).get(lineNumber);

If your files's lines has same size and you want to read line 15.
RandomAccessFile random=new RandomAccessFile("filename","r");
//let say Your line size if a;
random.seek(a*14);
random.readLine();

Use this if you don't have same size and let say you wanna read 15th line
BufferedReader random=new BufferedReader(new FileReader("filename"));
            int counter=0;
              while((line=random.readLine())!=null){
                  counter++;
                  if(counter==15){
                      //do whatever
                  }
              }


text:
Q: What Python framework for a REST/JSON web service with no front end? I need to create a Python REST/JSON web service for an iOS app to interact with. There will be no front end on the web.
What will be the fastest, most lightweight framework to use for this? Learning curve to implement also considered?
From the research I've done Django-Tastypie or Djanjo-Piston look like the best options, with Tastypie winning because the codebase is being maintained actively?

A: When it comes to lightweight, CherryPy is pretty up there.
import cherrypy

class HelloWorld(object):
    def index(self):
        return "Hello World!"
    index.exposed = True

cherrypy.quickstart(HelloWorld())

A: At Pycon Australia, Richard Jones compared the most popular lightweight web frameworks.  Bottle came out on top.  Here is the full presentation.

A: If I were you I would use web.py that is really convenient to do that kind of rapid prototyping of lightweight REST applications.
Check out this snippet from the home page:
import web

urls = (
    '/(.*)', 'hello'
)
app = web.application(urls, globals())

class hello:
    def GET(self, name):
        if not name:
            name = 'World'
        return 'Hello, ' + name + '!'

if __name__ == "__main__":
    app.run()

A: In general, I think you'll find web2py to be one of the easiest frameworks to set up, learn, and use. web2py makes it very easy to generate JSON (just add a .json extension), and it now includes new functionality to automatically create RESTful web services to access database models. In particular, check out the parse_as_rest and smart_query functionality.
If you need any help, ask on the mailing list.

A: Take a look to flask and its extension flask-restful
from flask import Flask
from flask.ext import restful

app = Flask(__name__)
api = restful.Api(app)

class HelloWorld(restful.Resource):
    def get(self):
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
    app.run(debug=True)

A: You might also want to check out Parse. They are free to use right now, and will give you a nice REST API for you mobile apps.
However, as @iksnar points out, you don't write anything in Python, or anything at all for the backend. If you need to have the backend running in Python on your own servers I am a big fan of TastyPie if you are using Django already and the Django ORM already.


text:
Q: How to make Pagination using scrapy-splash Purpose
I want to crawl https://www.livecoinwatch.com using scrapy+splash(I do not want to use selenium).
but i do not know how to make Pagination . I can only crawl the first page.

*

*I want to know how to make Pagination in splash(lua)

*Is it possible?

*when click next page button the url do not change.

Here is my spider code:
import scrapy

from scrapy_splash import SplashRequest
from coins.items import CoinsItem

class CoinsSpiderSpider(scrapy.Spider):
    name = 'coins_spider'
    allowed_domains = ['livecoinwatch.com']
    start_urls = ['https://www.livecoinwatch.com']

    Pages = 3

    lua_script = '''
        function main(splash, args)
                splash.private_mode_enabled = false
                url = args.url

                headers = {
                    ['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38'
                }
                splash:set_custom_headers(headers)
                assert(splash:go(url))
                assert(splash:wait(1))

                assert(splash:wait(5))
                splash:set_viewport_full()

                return splash:html()
        end

    '''

def start_requests(self):
    for url in self.start_urls:
        yield SplashRequest(url = url,callback= self.parse,endpoint='execute',args={
            'lua_source':self.lua_script
        })

def parse(self, response):
    # 50 results in first page
    rows = response.xpath('//tr[@class="table-row filter-row"]')
    for row in rows:
        item = CoinsItem()

        item['coin'] = row.xpath('./td[2]//div[@class="item-name ml10"]/div/text()').extract_first()
        item['price'] = row.xpath('./td[3]').extract_first()
        item['marketCap'] = row.xpath('./td[4]/text()').extract_first()
        item['volumn24h'] = row.xpath('./td[5]/text()').extract_first()
        item['Liquidity'] = row.xpath('./td[6]/text()').extract_first()
        item['allTimeHigh'] = row.xpath('./td[7]/text()').extract_first()
        item['hour1_value'] = row.xpath('./td[8]/span/text()').extract_first()
        item['hour1_class'] = row.xpath('./td[8]/@class').extract_first()
        item['hour24_value'] = row.xpath('./td[9]/span/text()').extract_first()
        item['hour24_class'] = row.xpath('./td[9]/@class').extract_first()

        yield item

    # next page
    # do not know how to code!!!

A: It is much easier to scrape the website using direct request to the api than using scrapy_splash. Examining the XHR request when you click on the page navigation at the bottom you notice the request is made to https://http-api.livecoinwatch.com/coins?offset=50&limit=50&sort=rank&order=ascending&currency=USD which returns a json response. Adjust the offset and limit arguments to limit the amount of data you get back.
See sample implementation below
import scrapy
from coins.items import CoinsItem

class CoinsSpiderSpider(scrapy.Spider):
    name = 'coins_spider'
    allowed_domains = ['livecoinwatch.com']
    # start from first item and fetch 500 items in each request. Modify as suits you
    offset = 0
    limit = 500
    start_urls = [f'https://http-api.livecoinwatch.com/coins?offset={offset}&limit={limit}&sort=rank&order=ascending&currency=USD']

    def parse(self, response):
        data = response.json()

        for coin in data['data']:
            item = CoinsItem()
            item['coin'] = coin.get('code')
            item['price'] = coin.get('price')
            item['marketCap'] = coin.get('cap')
            item['volum24h'] = coin.get('volume')
            #... check the json response and add the other fields you need

            yield item

        # yield next request
        self.offset += self.limit
        next_url = f'https://http-api.livecoinwatch.com/coins?offset={self.offset}&limit={self.limit}&sort=rank&order=ascending&currency=USD'
        yield scrapy.Request(next_url)


text:
Q: How much unenecessary java ArrayList objects can effect application or memory? I was creating 16 UN-necessary object (of no use) in my Action class.
List<String> list = new ArrayList<String>();

My application is customer portal which is used by world wide users .
and that action class is accessed many times i believe in a day.
So My question is how much these 16 objects could effect the memory ? a little ? Or too much ?

A: An empty ArrayList costs 88 Bytes on a 32-bit system. See this explanation for the calculation.
So just multiply this with 16 and the number of times your action is called. But ever better would be if you find a solution where you would not need to create unnecessary list objects. Most of the time this is should not be needed.


text:
Q: asm not loading parameters on stack I have a function that is supossed to use two integers as parameters, but whenever I access to the stack, the aren't there and I cannot use them, so I get random memory values as output. As I understand, to call a function I don't need anything else apart from what its on my code. This is inline intel asm x86
#include <stdio.h>
int getNum1(int a);
int main()
{
    int num1=0, num2 = 8;
    __asm {
        // push ebp
        // mov ebp,esp

        push num1
        push num2

        call getNum1

        add esp,8
        // pop ebp

        mov num1,eax
    }
    printf("%d", num1);
    return 0;
}

//this is only supossed to return the value of a, but i get random stuff
int getNum1(int a, int b)
{
    __asm {
        push ebp
        mov ebp,esp
        push ebx

        mov ebx,[ebp+12]
        mov eax,ebx

        pop ebx
        pop ebp
    }
}


text:
Q: Android - ListFragment OnClickListener is not working I have a ListFragment in my android application, I have got it to work, but the OnClick Listener is not working, I tried just making it so that when any item on the list is selcted a Toast appears and it is not happening, there is no Error so I have no LogCat to post
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub

    View v = inflater.inflate(R.layout.main, container, false);

    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

//...

    ListAdapter adapter = new SimpleAdapter(getActivity(), menuItems,
            R.layout.list_item,
            new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
                    R.id.name, R.id.desciption, R.id.cost });

    setListAdapter(adapter);

    ListView lv = (ListView)v.findViewById(android.R.id.list);

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem

            Toast.makeText(getActivity().getApplicationContext(), "Not Configured",
                    Toast.LENGTH_SHORT).show();

        }
    });

    return v;
}

Thanks

A: if your class extends ListFragment than everything you need to do is just overriding its onListItemClick method.
@Override
public void onListItemClick(ListView l, View v, int pos, long id) {
  super.onListItemClick(l, v, pos, id);
  Toast.makeText(getActivity(), "Item " + pos + " was clicked", Toast.LENGTH_SHORT).show();
}

A: The ListFragment subclass already has it's overriden onListItemClick method.
The doc says:
This method will be called when an item in the list is selected. Subclasses should override

So there is no need to declare another listner for your listview.

A: Removing .getApplicationContext() should work. I have some code similar to yours from an app I made. Its from inside a fragment as well though works without problem. The db.remove is probably irrelevant to your code though because this code was written for an app with a database. Also maybe try changing new OnItemClickListener to new AdapterView.OnItemClickListener
    listItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            db.remove( (int) l);
            Toast.makeText(getActivity(), "Item Deleted", Toast.LENGTH_LONG).show();
        }
    });

If that doesn't work, maybe try making a Context instance variable like:
private Context ctx = getActivity();

or
private final Context ctx = getActivity();

I have never worked with ListFragments before though, so I am not sure if anything I wrote will work.

A: put
android:focusable="false"
android:clickable="false"

to all itens in your row

A: Make sure you
1.shouldn't have onclicklistener  inside your Adapter
2.inside your XML layout

R.layout.main

Listview should be initialized like
 <ListView
    android:onClick="@id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@+id/textHeader"
    android:layout_margin="5dp"
    android:divider="@color/DeepPink"
    android:dividerHeight="1sp"
    android:gravity="center"
    android:horizontalSpacing="1dp"
    android:visibility="visible" >

here id   android:onClick="@id/list" important

*ListView should be initialize like ListView lv = getListView if your extending your fragment by ListFragment instead Fragment


text:
Q: How to convert FoxPro data into SQL Server and keep the data type right? I am importing FoxPro database to SQL server. I used MS SQL Server FoxPro Import, Export & Convert Software to convert and import the data into my SQL Server. It succeeded, but the data type of each column has changed to varchar(8000). Is there any better method to import FoxPro Database into SQL server and keep the data type of the imported data right?

A: I don't find a direct solution for the problem. Here is my work-around.

*

*Import all the data from foxpro to sql server.

*Create one more set of tables (with new names)

*Copy and cast the data from old tables to new tables, something like: INSERT INTO  SELECT CAST(col as your wanted data type) FROM

A: You could also try DBF Commander Pro's Export to DBMS feature. It converts field type during the export process. Choose 'Create new table' item as a destination table:


text:
Q: How to tell the difference between a channel ID and YouTube username? I need to accept a Youtube Channel ID OR Youtube username as input, and create a subscribe button for it.
Google has just changed the syntax, so that if it's a channel ID, you use this:

But if it's a channel name you omit the id from the attribute. https://developers.google.com/youtube/youtube_subscribe_button

You must specify a value for one of the following two attributes:
  data-channel – The name of the channel associated with the button. Sample value: GoogleDevelopers.
  data-channelid – The channel ID associated with the button. Sample value: UC_x5XG1OV2P6uZZ5FSM9Ttw

What would be an easy way to tell if it's a channel ID or username?
All channels I have seen start with UC but that doesn't seem to be definitive: YouTube channel and playlist ID prefixes
Who knows why they did this but it's breaking many subscribe buttons as a result :(

A: Just check if your input field starts with "UC_", "HC_", etc. for a channel per your link above. If not then it's a username.


text:
Q: Is "a normal woman" correct? Normally, we say "an ordinary woman", but I read an article about Kate Middleton recently, the Duchess of Cambridge, it says she isn't a normal woman.  From the article, I can tell that the author means she's extraordinary. But it still surprised me a lot, cause someone told me the difference between "normal" and "common" before.
He said "normal" is used to describe "standard". When it's used to say a person, it more sounds like this person doesn't have a healthy or mental problem rather than ordinary.
But now I was confused about the usage, and the difference between "normal" and "common"

A: It sounds idiomatic to me. Here are some other examples of "normal woman" being used outside of health or mental health contexts.
Normal can mean "not a radical feminist". Finding a 'Normal' Woman: Selection Processes for Board Membership:

"They told me they wanted a woman on the board who was married, who had children, who had her master's degree, who had experience in the labor market, but was still a 'normal' woman and not a radical feminist or a battle-axe. .... also someone who does not get sidetracked by details."

Normal can mean not a part of the "rigidly policed ideal of beauty – young, skinny, white, impossibly beautiful". Put a normal woman in a bikini. That's how to bust the beauty myth:

Put a normal woman in a bikini and it's obvious how little of the magic is down to the clothes, how hard magazines have to work just to make them look interesting.

Normal can mean someone who's acting like she's not a superhero. Sarah Nicole Prickett on the Myth of the Wonder Woman:

"I'm almost jealous of myself as Wonder Woman," she thinks in one early issue, from the Marston/Peter years. "Nothing I do as a normal woman, Diana Prince, ever impresses anybody." Like a normal woman, she can, as a matter of fact, do several impressive things her boss cannot. She is always loaning him confidence, free of interest. She takes excellent dictation and types like hell, and Steve says she is "quite the little psychologist."

The first one is still an example of "normal" being contrasted with something negative, but the other two are examples where "normal" means "not extraordinary", the same as it does in your context.
I don't think "common" would work here (but "ordinary" would), since "common" can mean "without rank", changing the intended meaning.


text:
Q: Search only particular folder in Directory I need to search particular folder in directory.
I dont want to go for files, no need to search files.
I can search particular folder in directory but for I have to go for loop of files like
foreach (FileInfo f in dir.EnumerateFiles())
{
      //code
}
foreach (DirectoryInfo d in dir.EnumerateDirectories())
{
   Call function recursively
}

I need to search particular folder only. Because I have so many files around 20,000 , so If I use above code than loop will go all the files, and take more time.
But I need some folders only like
Regex.IsMatch(dir.FullName, @"1293.*T.*"))

How can i do that without going in files loop.

A: If the search pattern provided by the overload of Directory.GetDirectory isn't strong enough for your needs, you can use a custom method.
static string SearchDirectory(string path, string pattern)
{
    var regex = new Regex(pattern);
    foreach (var d in Directory.GetDirectories(path))
    {
        var dirName = d.Substring(d.LastIndexOf('\\') + 1);
        if (regex.IsMatch(dirName)) return d;
        SearchDirectory(d, pattern);
    }
    return null;
    //Or throw an Exception
}

You might want to surround the foreach loop in a try/catch block.

A: You can use the System.IO.Directory.GetDirectories overload that accepts a search pattern.
For example:
string[] dirs = Directory.GetDirectories(@"c:\", "c*");

A: Your question is very confusing, but do you want to get the directories that match the Regex pattern?
foreach (DirectoryInfo d in dir.EnumerateDirectories().Where(d => Regex.IsMatch(dir.FullName, @"1293.*T.*")))
{

}


text:
Q: Java / Spring model forms framework Is there any model/entity form abstraction library available i can use in Spring projects ?
I'm looking something like "Django forms framework" or "Symfony Forms" in the Java/Spring world.
The basic idea is to simplify JPA entities form creation and the easier creation of multiform handling controllers.

A: If i've understood you correctly you're after a way to bind an entity to a form (and allow a user to add/edit entities)? In which case theres no need for another framework Spring already does this really well. A quick example:
Our controller would look like this:
@Controller
@RequestMapping(value = "/addUser.html")
public class UserController {

  @Autowired
  private UserAccountService service;

  @Autowired
  @Qualifier("userValidator")
  private Validator userValidator;

  @ModelAttribute("user")
  public User getBackingObject() {
    //This gets the object we're letting the user edit.
    //This can be any POJO so a JPA entity should be fine.
    //Note that we're creating an object here but we could
    //just as easily fetch one we already have from a database/service etc
    return new User();
  }

  @RequestMapping(method = RequestMethod.GET)
  public String showForm() {
    //The form to present to the user
    return "/addUser";
  }

  @RequestMapping(method = RequestMethod.POST)
  //note: here Spring has automatically bound the entries that have been input into the webform into the User param supplied here
  protected String onSubmit(User user, Errors errors, HttpServletRequest request) {

    userValidator.validate(user, errors);
    if (errors.hasErrors()) {
      //The validator showed up some errors so send the object back to let the user correct it
      return "/addUser";
    }

    //save our new user
    service.saveUser(user);

    //best practice is to redirect to another view to make sure the backing object is cleared
    return "redirect:/success.html";
  }

}

Then we can use spring form macros in our JSP to create the form:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<title>Add a user</title>

<form:form commandName="user">
  first name
  <form:input path="firstname" /> <form:errors cssClass="errorText" path="firstname" />
  last name
  <form:input path="lastname" /> <form:errors cssClass="errorText" path="lastname" />
  <input type="submit" value="Save" />
</form:form>

A: I think spring roo does what you want to do.


text:
Q: Link and compile an assembly function I have an assembly function like so
rfact:
pushl   %ebp
movl    %esp, %ebp
pushl   %ebx
subl    $4, %esp
movl    8(%ebp), %ebx
movl    $1, %eax
cmpl    $1, %ebx
jle     .L53
leal    -1(%ebx), %eax
movl    %eax, (%esp)
call    rfact
imull   %ebx, %eax
.L53:
addl    $4, %esp
popl    %ebx
popl    %ebp
ret

I understand I can't just save this as rfact.s and compile it. There has to be certain items (such as .text) appended to the top of the assembly. What are these for a linux system? And I'd like to call this function from a main function written in normal c file called rfactmain.c

A: Here's a 'minimal' prefix of directives - for ELF/SysV i386, and GNU as:
.text
.p2align 4

.globl  rfact
.type   rfact, @function

I'd also recommend appending a function size directive at the end:
.size   rfact, .-rfact

The easiest way to compile is with: gcc [-m32] -c -P rfact.S
With the -P option, you can use C-style comments and not have to worry about line number output, etc. This results in an object file you can link with. The -m32 flag is required if gcc targets x86-64 by default.


text:
Q: Passport-local never authenticating with correct credentials I'm trying to use passport-local to bake some authentication and password hashing into a small web app. I believe I've set it up correctly, however I am sent through the failure redirect to login again, even though the credentials are 110% correct.
The passport documentation is extremely light on debugging errors, can anyone share shed some light on the possible cause of this failure redirect, or offer a solution to continue debugging?
Passport Config
passport.use(new LocalStrategy({
  usernameField: 'email',
  passwordField: 'password'
},
  function(username, password, cb) {
     UserSchema.findByUsername(username, function(err, user) {
      if (err) { return cb(err); }
      if (!user) { return cb(null, false); }
      if (user.password != password) { return cb(null, false); }
      return cb(null, user);
    });
  }));

Login Route
router.post('/login',
  passport.authenticate('local', {
    failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

Schema and findByUsername function
const UserSchema = mongoose.Schema ({
  firstName: {
    type: String,
    index: true
  },
  lastName: {
    type: String,
    index: true
  },
  email: {
    type: String,
    index: true
  },
  password: {
    type: String,
    index: true
  },
  homeAirport: {
    type: String,
    index: true
  }
})

UserSchema.plugin(passportLocalMongoose)

// Adding this function to find by username
exports.findByUsername = function(username, cb) {
  process.nextTick(function() {
    for (var i = 0, len = records.length; i < len; i++) {
      var record = records[i];
      if (record.username === username) {
        return cb(null, record);
      }
    }
    return cb(null, null);
  });
}

// Export it to the app
module.exports = mongoose.model('user', UserSchema)

A: Taken from the Passport docs:

A redirect is commonly issued after authenticating a request.

My guess is that because you only have a {failureRedirect: '/login' }
you are always redirected there. Try adding this:
app.post('/login',
  passport.authenticate('local', { successRedirect: '/',
                                   failureRedirect: '/login' }));

So in this case you have a successRedirect and a failureRedirect
Or you could also just remove the redirect after authenticating, and instead redirect the user like this:
app.post('/login',
  passport.authenticate('local'),
  function(req, res) {
    console.log('Successfully logged in');
    res.redirect('/users/' + req.user.username);
  });

Let me know if this works


text:
Q: Dispose JDialog from another class I want to dispose a JDialog from another class, because i am trying to keep classes and methods clean, and not create buttons and handle the listeners in the same class. So here is the problem.
I tried creating a get method from the first class to get the dialog and then dispose it on the third but didnt work.
public class AddServiceListener extends JFrame implements ActionListener {

/**
 * Creates listener for the File/New/Service button.
 */
public AddServiceListener() {

}

/**
 * Performs action.
 */
public void actionPerformed(ActionEvent e) {
    AddServiceWindow dialog = new AddServiceWindow();
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    dialog.setVisible(true);
}
}

public class AddServiceWindow extends JDialog {

private JPanel contentPanel;
private JFrame frame;
private JPanel buttonPanel;
private JLabel nameLabel;
private JTextField nameField;
private JLabel destinationLabel;
private JTextField destinationField;
private JButton destinationButton;
private JButton okButton;
private JButton cancelButton;

/**
 * Creates the dialog window.
 */
public AddServiceWindow() {
    ManageMinder mainFrame = new ManageMinder();
    frame = mainFrame.getFrame();

    contentPanel = new JPanel();
    contentPanel.setLayout(null);

    setTitle("New Service File");
    setSize(340, 220);
    setLocationRelativeTo(frame);
    getContentPane().setLayout(new BorderLayout());
    contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
    getContentPane().add(contentPanel, BorderLayout.CENTER);

    buttonPanel = new JPanel();
    buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
    getContentPane().add(buttonPanel, BorderLayout.SOUTH);

    createLabels();
    createTextFields();
    createButtons();
    addListeners();
}

/**
 * Creates the labels.
 */
private void createLabels() {
    nameLabel = new JLabel("Name:");
    nameLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    nameLabel.setBounds(25, 25, 52, 16);
    contentPanel.add(nameLabel);

    destinationLabel = new JLabel("Path:");
    destinationLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    destinationLabel.setBounds(7, 70, 70, 16);
    contentPanel.add(destinationLabel);
}

/**
 * Creates the text fields.
 */
private void createTextFields() {
    nameField = new JTextField();
    nameField.setBounds(87, 22, 220, 22);
    contentPanel.add(nameField);
    nameField.setColumns(10);

    destinationField = new JTextField();
    destinationField.setBounds(87, 68, 220, 20);
    contentPanel.add(destinationField);
    destinationField.setColumns(10);
}

/**
 * Creates the buttons of the window.
 */
private void createButtons() {
    destinationButton = new JButton("Select...");
    destinationButton.setBounds(87, 99, 82, 23);
    destinationButton.setFocusPainted(false);
    contentPanel.add(destinationButton);

    okButton = new JButton("OK");
    okButton.setFocusPainted(false);
    buttonPanel.add(okButton);

    cancelButton = new JButton("Cancel");
    cancelButton.setFocusPainted(false);
    buttonPanel.add(cancelButton);
}

/**
 * Adds listeners to buttons.
 */
private void addListeners() {
    ActionListener destinationAction = new AddDestinationListener(destinationField);
    destinationButton.addActionListener(destinationAction);

    ActionListener okAction = new SaveNewServiceFileListener(nameField, destinationField);
    okButton.addActionListener(okAction);
}
}

public class SaveNewServiceFileListener extends JFrame implements ActionListener {

private JTextField nameField;
private JTextField destinationField;
private String path;
private File newService;

/**
 * Creates listener for the File/New/Add Service/OK button.
 */
public SaveNewServiceFileListener(JTextField nameField, JTextField destinationField) {
    this.nameField = nameField;
    this.destinationField = destinationField;
}

/**
 * Performs action.
 */
public void actionPerformed(ActionEvent e) {
    path = destinationField.getText() + "\\" + nameField.getText() + ".csv";

    try {
        newService = new File(path);
        if(newService.createNewFile()) {
            System.out.println("Done!");
            // DISPOSE HERE
        }
        else {
            System.out.println("Exists!");
        }
    } catch (IOException io) {
        throw new RuntimeException(io);
    }
}
}

What should i do, so the dialog disposes on the third one, when OK is clicked and file is created?

A: The way to change the state of another object is to 1) have a reference to that object, and 2) call a public method on it.
Here the other object is the JDialog, and the state that you wish to change is its visibility by calling either .close() or .dispose() on it. The problem that you're having is that the reference to the JDialog is not readily available since it is buried within the actionPerformed(...) method of your AddServiceListener class.
So don't do this -- don't bury the reference but rather put it into a field of the class that needs it.
If you absolutely need to have stand-alone ActionListener classes, then I think that the simplest thing to do is to take the dialog out of the listener class and into the view class, your main GUI, and then have the listener call methods on the view. For example
Assume that the dialog class is called SomeDialog and the main GUI is called MainGui. Then put the reference to the dialog in the MainGui class:
public class MainGui extends JFrame {
    private SomeDialog someDialog = new SomeDialog(this);

And rather than have your listeners create the dialog, have them call a method in the main class that does this:
public class ShowDialogListener implements ActionListener {
    private MainGui mainGui;

    public ShowDialogListener(MainGui mainGui) {
        // pass the main GUI reference into the listener
        this.mainGui = mainGui;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // tell the main GUI to display the dialog
        mainGui.displaySomeDialog();
    }
}

Then MainGUI can have:
public void displaySomeDialog() {
    someDialog.setVisible(true);
}

An example MRE program could look like so:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.*;

import javax.swing.*;

public class FooGui002 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            MainGui mainGui = new MainGui();
            mainGui.setVisible(true);
        });
    }
}

@SuppressWarnings("serial")
class MainGui extends JFrame {
    private SomeDialog someDialog;
    private JButton showSomeDialogButton = new JButton("Show Some Dialog");
    private JButton closeSomeDialogButton = new JButton("Close Some Dialog");

    public MainGui() {
        super("Main GUI");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(500, 200));

        someDialog = new SomeDialog(this);

        showSomeDialogButton.addActionListener(new ShowDialogListener(this));
        showSomeDialogButton.setMnemonic(KeyEvent.VK_S);

        closeSomeDialogButton.addActionListener(new CloseSomeDialogListener(this));
        closeSomeDialogButton.setMnemonic(KeyEvent.VK_C);

        setLayout(new FlowLayout());
        add(showSomeDialogButton);
        add(closeSomeDialogButton);
        pack();
        setLocationByPlatform(true);
    }

    public void displaySomeDialog() {
        someDialog.setVisible(true);
    }

    public void closeSomeDialog() {
        someDialog.setVisible(false);
    }
}

@SuppressWarnings("serial")
class SomeDialog extends JDialog {
    public SomeDialog(Window window) {
        super(window, "Some Dialog", ModalityType.MODELESS);
        setPreferredSize(new Dimension(300, 200));
        add(new JLabel("Some Dialog", SwingConstants.CENTER));
        pack();
        setLocationByPlatform(true);
    }
}

class ShowDialogListener implements ActionListener {
    private MainGui mainGui;

    public ShowDialogListener(MainGui mainGui) {
        this.mainGui = mainGui;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        mainGui.displaySomeDialog();
    }
}

class CloseSomeDialogListener implements ActionListener {
    private MainGui mainGui;

    public CloseSomeDialogListener(MainGui mainGui) {
        this.mainGui = mainGui;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        mainGui.closeSomeDialog();
    }
}


text:
Q: OpenVPN speed tweaks for VPS(Windows) Background:
I have an OpenVPN server running on my Windows 10 VPS. The Internet connection of VPS is ~750 Mbps for Download and ~450 Mbps for upload (Obtained by multiple speedtest.net tests). The VPS has 2 vCPU and 8 GB RAM. The VPS serves only two clients of OpenVPN. However, the speedtest for clients normally shows 30 Mbps of the test while VPN is enabled.
What I have tried:

*

*Please see the config

Config:

*

*Server
;local a.b.c.d

--duplicate-cn

port 443

;proto tcp

proto udp

sndbuf 393216

rcvbuf 393216

push "sndbuf 393216"

push "rcvbuf 393216"

txqueuelen 4000

tun-mtu 9000

mssfix 0

fragment 0

;dev tap

dev tun

ca "ca.crt"

cert "ERVER.crt"

key "C:\\SE.key"  # This file should be kept secret

dh "dh.pem"

;topology subnet

server 10.8.0.0 255.255.255.0

ifconfig-pool-persist ipp.txt

;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100

;server-bridge

;push "route 192.168.10.0 255.255.255.0"

;push "route 192.168.20.0 255.255.255.0"

push "redirect-gateway def1 bypass-dhcp"

push "dhcp-option DNS 208.67.222.222"

push "dhcp-option DNS 8.8.8.8"

keepalive 10 120

tls-auth "tls-auth.key" 0 # This file is secret

cipher AES-128-CBC

persist-key

persist-tun

;mute 20

explicit-exit-notify 1

*

*Client
dev tun
proto udp
remote IP 443
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
key-direction 1
cipher AES-128-CBC
verb 3
<ca>
-----BEGIN CERTIFICATE-----
</ca>
<cert>
</cert>
<key>
-----BEGIN PRIVATE KEY-----
</key>
<tls-auth>
</tls-auth>

A: client
dev tun
remote-cert-tls server

compress
proto udp
cipher aes-128-cbc
ncp-disable
fast-io

sndbuf 512000
rcvbuf 512000
txqueuelen 2000

pull
nobind
reneg-sec 0
resolv-retry infinite
verb 3
persist-key
persist-tun
remote-random
mute-replay-warnings
route-delay 10

*

*Use UDP for better OpenVPN performance.

*Disable compression

*Disable cipher negotiation


text:
Q: Finding a marginal PDF If we have a Random variable X that is $$2e^{-2x}$$ and Y that is an exponential distribution with X as its parameter $\lambda$, then how do we go around solving this question? I thought that we should find its CDF first by using $$P[Xe^{-XY} < Y] $$ but then I run into the issue of how to get X on one side. I took the log  $$P[Log(X)*-XY < log(Y)] $$ and I am lost on how we can continue next. Help would be appreciated. Thanks!

A: What you wrote does not make sense.
You are given that
$$X\sim\text{Exp}(2)$$
$$(Y|X=x)\sim\text{Exp}(x)$$
Assuming that you are requested to find $f_Y(y)$ you have to use the following
$$\begin{align}
f_Y(y) & =\int f_{XY}(x,y)dx\\
& = \int_0^{\infty}2x e^{-x(2+y)}dx\\
& =\frac{2}{(2+y)^2} \underbrace{\int_0^{\infty}(2+y)^2x e^{-x(2+y)}dx}_{=1}\\
& =\frac{2}{(2+y)^2}\mathbb{1}_{[0;\infty)}(y)
\end{align} $$
The integral in the brackets is 1 as it is the integral of a $\text{Gamma}[2;(2+y)]$


text:
Q: Send asynchronous HTTP requests one after another I am trying to use aiohttp to send requests one after another like this
import aiohttp
import asyncio
from datetime import datetime

async def main():
    request_url = "https://..."
    async with aiohttp.ClientSession() as session:
        while True:
            print(datetime.now())
            async with session.get(request_url) as response:
                json_data = await response.json()
            print(json_data)
            await asyncio.sleep(0.2)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

So I would expect each datetime print to be 0.2s apart. However, they seem to be about 0.35s apart as I think it takes 0.15s to get the data from the response. Why is this happening? I want it to be asynchronous so it should just go onto the next one?
How can I fix this?

A: When you use await all next code will wait for end of this code.
If you want to run asyncio code asynchronously, you should use functions like asyncio.gather

import asyncio
import aiohttp
import datetime

async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            print('#', response.status)

async def worker(queue):
    print('START WORKER')
    while True:
        url = await queue.get()
        await fetch(url)
        queue.task_done()

async def control(queue):
    while True:
        print(datetime.datetime.now())
        queue.put_nowait('https://docs.python.org/')
        await asyncio.sleep(0.2)

async def main():
    queue = asyncio.Queue()
    await asyncio.gather(
        control(queue),
        asyncio.gather(*[worker(queue) for _ in range(10)])
    )

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

A: Sending http request and fetching response back takes some time. You need excluding this time from asyncio.sleep() call:
import aiohttp
import asyncio
import time
from datetime import datetime

async def main():
    request_url = "https://..."
    async with aiohttp.ClientSession() as session:
        while True:
            print(datetime.now())
            t0 = time.monotonic()
            async with session.get(request_url) as response:
                json_data = await response.json()
            print(json_data)
            t1 = time.monotonic()
            await asyncio.sleep(0.2 - (t1 - t0))

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())


text:
Q: separate real and imaginary part of a complex number in python I have need to extract the real and imaginary elements of a complex number in python.  I know how to make a list into a complex number... but not the other way around.
I have this:
Y = (-5.79829066331+4.55640490659j)

I need:
Z = (-5.79829066331, 4.55640490659)

and I will also need each part if there is a way to go directly without going by way of Z:
A = -5.79829066331
B = 4.55640490659

https://docs.python.org/2/library/functions.html#complex
Thanks!

A: Y = (-5.79829066331+4.55640490659j)

Z = (Y.real, Y.imag)

A = Y.real
B = Y.imag

BTW:
More: Python: Complex number - real and imaginary part

A:    import numpy as np                 #Can be done easily using Numpy Lib
   array=np.array([3,4.5,3 + 5j,0])   #Initialize complex array
   real=np.isreal(array)              #Boolean condition for real part
   real_array=array[real]             #Storing it in variable using boolean indexing
   imag=np.iscomplex(array)           #Boolean condition for real part
   imag_array=array[imag]             #Storing it in variable using boolean indexing
   print(real)
   print(imag)
   print(real_array)
   print(imag_array)

A: Z = (Y.real, Y.imag)
A = Y.real
B = Y.imag


text:
Q: How to pass an ember object to handlebars helper I want to pass an ember object to the handlebars helper, I used the helper as shown below but it is not receiving correct object. It is just printing the name of the object in console see the code below
//ember helper
Ember.Handlebars.registerHelper('act', function (value) {
            console.log(value); //It prints as item.label
            return value+"1";
        });

//template
     {{#each item in content}}

{{act item.label}}

                {{/each}}

 // Ember model which i am using

  App.AllRoutes = [Ember.Object.create({
            label: "index",
            link:"#/",

        }),
  Ember.Object.create({
            label: "second",
            link: "#/second",
        }),

Update
Even though srinivasan solution works It doesn't work for problem shown below. registerBoundHelper return the value with script elements. So for  It cannot be used inside tags. Any other help ?
//ember helper
Ember.Handlebars.registerBoundHelper('act', function (value) {
            console.log(value); //It prints as item.label
          if (value == "somevalue"){ return  new Handlebars.SafeString("class='active'"); }

        });

//template
     {{#each item in content}}

{{label}}

                {{/each}}

I am using
Ember.VERSION : 1.0.0-rc.7,
Handlebars.VERSION : 1.0.0
Thanks in advance...

A: I'm not sure I understand your question. You're passing item.label into the helper, but you expect to get the item as an argument? Why not just do {{act item}}?
Also, why are you trying to emulate the {{#linkTo}} helper that already exists in Ember?

A: Kindly check the following.
JAVASCRIPT:
App=Em.Application.create({});

App.Router.map(function(){
    this.route('all');
    this.route('index');
    this.route('second');
});

Ember.Handlebars.registerBoundHelper('act', function (value) {
        return value+"1";
    });

App.IndexRoute=Em.Route.extend({
    redirect:function(){this.transitionTo('all');}
});

App.AllRoute =Em.Route.extend({
    model:function(){
        return  [Ember.Object.create({
        label: "index",
        link:"#/"
    }),
      Ember.Object.create({
        label: "second",
        link: "#/second"
    })];
 }
});

HTML


text:
Q: Assign value to 3D array, but it fills too much values EDIT:
This is a Vue component, with a canvas that draws a grid, the canvas has and EventListener attached, and this.grid stores where the user has made click (inside canvas).
init this.grid
init(){

            console.log("init this.grid")
            //here grid is get from data() and inicialized
            this.grid = []
            var row = [];
            var row2 = []
            for(var i=0;i<this.SIZE;i++){
                row.push(0);
            }
            for( i=0;i<this.HEIGHT;i++){
                row2.push(row);
            }
            for( i=0;i<this.SIZE;i++){
                this.grid.push(row2);
            }
            console.log("this.grid 0s")
            console.log(this.grid);

            var canvas = document.getElementById("canvasDraw");
            this.rect = canvas.getBoundingClientRect();
            this.ctx = canvas.getContext("2d");
            this.ctx.fillStyle = "white";
            this.ctx.fill();

            for (i=0; i <= this.SIZE*this.big; i += this.big) {
            this.ctx.moveTo(0,i);
            this.ctx.lineTo(this.SIZE*this.big,i);
            this.ctx.stroke();
            }
            for (i=0; i <= this.SIZE*this.big; i += this.big) {
            //ctx.lineWidth(3);
                this.ctx.moveTo(i,0);
                this.ctx.lineTo(i,this.SIZE*this.big);
                this.ctx.stroke();
            }
            canvas.addEventListener('click',this.write,false);
        },

This is write() function, which writes in this.grid
write(evt){
            var x = Math.floor((evt.clientX - this.rect.left)/this.big);
            var y =  Math.floor((evt.clientY- this.rect.top)/this.big);

            console.log("write(evt) call, check if");
            console.log(this.grid[x][this.h][y] == 0);
            console.log("Old value: "+this.grid[x][this.h][y]);

            if(this.grid[x][this.h][y] == 0){
                 this.grid[x][this.h][y] = 1
            }else{
                 this.grid[x][this.h][y] = 0;
            }
            console.log("New value: "+this.grid[x][this.h][y]);
            console.log(this.grid)

            this.posUpdated += "posicion xhy: "+x+" "+this.h+" "+y+"<br/>";
            this.ctx.beginPath();
            this.ctx.rect((x*this.big), (y*this.big), this.big, this.big);
            this.ctx.fillStyle = (this.grid[x][this.h][y] == 1)? "white": "black" ;
            this.ctx.fill();
            //console.log(this.grid)
            //alert((evt.clientX%this.big) + ',' + evt.clientY%this.big);
        }

this.grid is a 3d array, initializated with zeros. Then I want to asign 1 to position(2,0,2)(x,h,y), but this code asigns 1 all over this.grid it looks like
but some how, now all positions where x==2 are asigned to 1.
Why? I just want (2,0,2) to be 1, not all positions(2,h,y).
It should be pretty simple but.. Thanks!.
The log

A: I think that issue is when you were creating the 3d array. You probably used fill which would make references to the same array and thus result would be what you have shown.
Here is a working example:

const size = 5
const fill = 0
const arr = new Array(size).fill(0).map(() => new Array(size).fill(0).map(() => new Array(size).fill(fill)))

arr[0][0][0] = 1

console.info(arr)


text:
Q: Undefined property error while detecting device in PHP I am creating a page which will detect a device. I using Detect Device for detecting. But I am getting an error:

My Index.php
<?php include 'detect.php';

if (Detect::isMobile()) {

}

// Gets the device type ('Computer', 'Phone' or 'Tablet').
echo Detect::deviceType();

// Any phone device
if (Detect::isPhone()) {

}

// Any tablet device.
if (Detect::isTablet()) {

}

// Any computer device (desktops or laptops).
if (Detect::isComputer()) {

}

// Get the IP address of the device.
echo Detect::ip();

// Get the ID address host name of the device.
echo Detect::ipHostname();

// Get the IP address organisation of the device.
echo Detect::ipOrg();

// Get the country the IP address is in (IP address location inaccurate).
// (JS function available which uses GPS)
echo Detect::ipCountry();

// Get the name & version of operating system.
echo Detect::os();

// Get the name & version of browser.
echo Detect::browser();

// Get the brand of device (only works with mobile devices otherwise return null).
echo Detect::brand();

// Check for a specific platform with the help of the magic methods:
if (Detect::isiOS()) {

}

if (Detect::isAndroidOS()) {

}
?>
<head>
    ...
    <script type="text/javascript" src="path_to/detect.js"></script>
    ...
</head>
<script>
// Get screen width in pixels.
detect.screenWidth();

// Get screen height in pixels.
detect.screenHeight();

// Get viewport (browser window minus any toolbars etc) width in pixels.
detect.viewportWidth();

// Get viewport (browser window minus any toolbars etc) height in pixels.
detect.viewportHeight();

// Get latitude from GPS & update html conent of ID element passed.
// Null, if GPS unavailable.
detect.latitude("latitude");

// Get longitude from GPS & update html conent of ID element passed.
// Null, if GPS unavailable.
detect.longitude("longitude");

// Get address from GPS & update html conent of ID element passed.
// Null, if GPS unavailable.
detect.address("address");
</script>

How to solve that error?
Is there any other website which provide function to detect the device?
I am creating a page which will detect a device. I using Detect Device for detecting. But I am getting an error: See Here.

A: The problem is not caused by your code, but by a bug in the code of the DeviceDetect class. It calls http://ipinfo.io/json. The code assumes that a property called "hostname" always exists, but clearly it's not (based on your error).
Is there a reason why you want to use this DeviceDetect class, and not the http://mobiledetect.net/ variant?
If you want to keep using the DeviceDetect class, you could fix the bug by replacing the lines at 246 with this:

self::$ipInfo = json_decode(file_get_contents('http://ipinfo.io' . self::$ipUrl . '/json'));
self::$ipAddress = !empty( self::$ipInfo->ip ) ? self::$ipInfo->ip : '';
self::$ipInfoHostname = !empty( self::$ipInfo->hostname ) ? self::$ipInfo->hostname : '';
self::$ipInfoOrg = !empty( self::$ipInfo->org ) ? self::$ipInfo->org : '';
self::$ipInfoCountry = !empty( self::$ipInfo->country ) ? self::$ipInfo->country : '';


text:
Q: Unable to start kde Rebooting my laptop after a few days of uptime (so I don't know what could have triggered the issue) I have found that I am unable to login from lightdm. My password is accepted and the fields disappear but I am stuck with the lightdm wallpaper and my (movable) cursor.
I can however

*

*login as guest

*startx from a tty

If I try from kdm, the same thing happens.
If I try to launch project-neon, the desktop progressbar appear, but I am thrown back to lightdm wallpaper when it is done loading, also a prompt for keyring password appeared, and after entering it, the desktop briefly flashed in.
.xsession says that dbus pre-start process terminated with status 2. I don't know if it is relevant.
Edit: I am able to launch lxde without issues. I have tried plasma-active, I have the same symptoms as with project-neon so clearly this is a kde/plasma issue. But since starting from startx works, the issue seem to lie in lightdm/kdm-kde interactions. Is there a way to track how lightdm starts kde (kwin, plasma)?
Also the issue is not with login, the graphical session appears in who and dm-tool list-seats shows a Session0 with my username.
Edit: I have tried a few more things. I mentionned a password prompt in project-neon. If I let it sit for a moment, the desktop eventually appears and works.
I have also tried adding debug outputs to startkde and startactive. Those in startactive work but not those instartkde (when starting from lightdm or kdm, but it works from xinit /usr/bin/startkde) so it may be that lightdm doesn't even start startkde, though it does according to lightdm.log.

A: TL;DR there was a permission issue with ~/.cache/upstart/dbus-session, rm -rf .cache/upstart and a reboot solved it.
Newbie debug insights for future readers (which may well include me).
The ~/.xsession message I mentioned in the question, along the lines of
init: dbus pre-start process (PID XXXX) terminated with status 2

was actually very important. I learnt what it meant while investigating, I found it this way

*

*First, I thought that the issue was with kde, so I tried to find how lightdm started kde

*I tried to look into /etc/lightdm/ (as suggested by man lightdm) but the lightdm config files were not here but (I found it by looking into /var/log/lightdm.log) in /usr/share/lightdm/lightdm.conf.d where I found  the relevant file /usr/share/lightdm/lightdm.conf.d/40-kde-plasma.conf

*According to it, what lightdm started for kde was the script /usr/bin/startkde, so I added some debug echo 'startkde is at line ##' > /home/evpok/delog lines to it to see where it failed, but none of them were executed.

*checking again /var/log/lightdm.log I saw the line
Running command /usr/sbin/lightdm-session /usr/bin/startkde
so I looked into usr/sbin/lightdm-session, to which I again added debugging echo lines

*After some fumbling, I found that the issue was with loading an Xsession script: /etc/X11/Xsession.d/99x11-common_start. So I looked into that one. It seemed to load normally and had only one line exec $STARTUP. Adding an echo to see what was in $STARTUP I found it was init --user. Now I didn't want to mess with init so I just traced its outputs by commenting this line out and adding instead
exec init -v --user > /home/evpok/initlog 2> /home/evpok/initerrlog

*Looking into these logs, I saw this message in initerrlog
dbus pre-start process (PID XXXX) terminated with status 2
but I still didn't know what to make of it, so I looked into initlog and saw
Loading configuration from /usr/share/upstart/sessions

*I looked into that dir, where I saw a startkde.conf. After some looking into documentation for upstart job confs, I saw that it had
start on started dbus and xsession SESSION=kde-plasma
obviously that was why startkde didn't start. It needed dbus, which had an error, so I looked into dbus.conf

*There, there was a pre-start script stanza, hey! That's what's in the errlog of init and in .xsession-errors. So for I added again some echoes, to find that the issue was at the line
echo "DBUS_SESSION_BUS_ADDRESS=${DBUS_SESSION_BUS_ADDRESS}" >$HOME/.cache/upstart/dbus-session (Not one of my debug echoes)

*After some fumbling, I found that I couldn't touch the non-existent file ~/.cache/upstart/debus-session because of a permission issue. I tried creating it under sudo and chown it to me with appropriate permissions but it didn't work. So I just rm -rf'ed .cache/upstart.

*After a reboot, everything worked as expected.

After all I just needed to stop being afraid of the internals and getting my hands dirty.

A: I had the same problem after upgrade from Ubuntu 13.10 to Ubuntu 14.04. I had also in .xsession-errors file the last line reading:
init: dbus pre-start process (PID XXXX) terminated with status 2

The problem was also in .cache/upstart directory. It had permissions drw------- - so I was not even able to go into it. I just added an execute bit, restarted X and it works now.


text:
Q: Having trouble with my set/get methods for my class in c++ First off, I'm very amateur with programming. My issue is in my main.cpp file when I run the code and go through my case 1 switch. I want my program to print out the customer's name and address when they are finished shopping. "myCustomerInfo.getName()" and "myCustomerInfo.getAddress()" aren't doing anything. My instructor has been MIA all week and is of no help. What am I doing wrong?
//This is my class
#pragma once
#include <string>
using namespace std;

class CustomerInfo
{
private:
    string custName;
    string custAddress;
public:

    CustomerInfo(string name, string userAddress) : custName(name), custAddress(userAddress) {}
    void setName(string);
    void setAddress(string);
    string getName();
    string getAddress();
    CustomerInfo();
};

// Defining setName
void CustomerInfo::setName(string name) {
    custName = name;
}
// Defining setAddress
void CustomerInfo::setAddress(string userAddress) {
    custAddress = userAddress;
}
// Defining getName
string CustomerInfo::getName() {
    return custName;
}
// Defining getAddress
string CustomerInfo::getAddress() {`enter code here`
    return custAddress;
}

//End of class
//This is my main.cpp
#include <iostream>
#include <Windows.h>
#include <cstdlib>
#include <string>
#include "customerclass.h"
using namespace std;

//***** Functions to calculate the price of multiple items *****
void finalPrice1(int itemQuantity) {
    float price;
    price = itemQuantity * 3.00;
    cout << "Your total is $" << price << endl;
    cout << "Thank you for using my shop" << endl;
    exit(0);
}
void finalPrice2(int itemQuantity) {
    float price;
    price = itemQuantity * 2.50;
    cout << "Your total is $" << price << endl;
    cout << "Thank you for using my shop" << endl;
    exit(0);
}
void finalPrice3(int itemQuantity) {
    float price;
    price = itemQuantity * 1.25;
    cout << "Your total is $" << price << endl;
    cout << "Thank you for using my shop" << endl;
    exit(0);
}   //***** End of functions that calculate price of multiple items *****

int main(void)
{
    char selection = ' ';
    string lname = "";
    string luserAddress;
    int itemQuantity;
    string orderFinalized;
    CustomerInfo myCustomerInfo;

    myCustomerInfo.setName(lname);
    myCustomerInfo.setAddress(luserAddress);

    do
    {  // Displaying menu
        cout << "Hello, welcome to my online shop! What is your name? " << endl;
        cout << " And what is your shipping address? " << endl;
        cin >> lname >> luserAddress;

        cout <<  lname + ", nice to meet you. Here are the items in my shop followed by the price, please enter the number that corresponds to the item you want. \n " << endl;

        cout << "Products \n";
        cout << "1 - Chocolate candy bar - $3.00" << endl;
        cout << "2 - Sour hard candy - $2.50" << endl;
        cout << "3 - Mints - $1.25" << endl;
        cout << "4 - Exit" << endl << endl;
        cout << "Enter selection ";
        // Reading User Selection
        cin >> selection;
        switch (selection)
        {
        case '1':
            cout << "You've chosen a Chocolate candy bar. How many would you like? ";
            cin >> itemQuantity;
            cout << "Ok, will this finalize your order? Type and enter either 'Yes' or 'No' " << endl;
            cin >> orderFinalized;
            if (orderFinalized == "Yes" || "yes" || "YES") {
                cout << myCustomerInfo.getName() + " your items will be shipped to " << myCustomerInfo.getAddress() << endl;
                cout << "Printing your receipt now..." << endl;
                finalPrice1(itemQuantity);
            }
            else if (orderFinalized == "No" || "no" || "NO") {

            }

            break;
        case '2':
            cout << "You've chosen Sour hard candy. How many would you like? ";
            cin >> itemQuantity;
            cout << "Ok, will this finalize your order? Type and enter either 'Yes' or 'No' " << endl;
            cin >> orderFinalized;
            if (orderFinalized == "Yes" || "yes" || "YES") {
                finalPrice2(itemQuantity);
                cout << "What's the address your items will be shipped to? " << endl;
                cin >> luserAddress;
                cout << "Ok, your order will be shipped to " << luserAddress << endl;
            }
            break;
        case '3':
            cout << "You've chosen Mints. How many would you like? ";
            cin >> itemQuantity;
            cout << "Ok, will this finalize your order? Type and enter either 'Yes' or 'No' " << endl;
            cin >> orderFinalized;
            if (orderFinalized == "Yes" || "yes" || "YES") {
                finalPrice3(itemQuantity);
                cout << "What's the address your items will be shipped to? " << endl;
                cin >> luserAddress;
                cout << "Ok, your order will be shipped to " << luserAddress << endl;
            }
            break;
        case '4':
            cout << "Thank you for using my shop. <exiting now...>" << endl;
            break;

        default: cout << "Invalid selection. Please try again";
        }
        cout << endl << endl;
    } while (selection != '4');
    return 0;
}

A: Take a closer look at your code:
string lname = "";
string luserAddress;
int itemQuantity;
string orderFinalized;
CustomerInfo myCustomerInfo;

myCustomerInfo.setName(lname);

Because at this point that you set the name it is "". You need to set it after you update the lname.
Few other things. Changes this:
if (orderFinalized == "Yes" || "yes" || "YES")
to this:
if (orderFinalized == "Yes" || orderFinalized == "yes" || orderFinalized == "YES")
You have it in multiple places. Same goes for the "No"s.
[EDIT]: A more elegant way as suggested by @user4581301 is to transform the string to the lower case and make only one comparison:
std::transform(orderFinalized.begin(), orderFinalized.end(), orderFinalized.begin(), ::tolower);
if (orderFinalized == "yes"){
    // the rest of the code
}

A: orderFinalized == "Yes" || "yes" || "YES"should be orderFinalized == "Yes" || orderFinalized  == "yes" || orderFinalized  == "YES"


text:
Q: Testing a method using recursion in binary search tree This toRoot method is supposed to return a list containing all the keys in the tree between the parameter key and the root. I have used a System.out.println statement in both the class and the junit test method. Why are the outputs of the two print statements different? The output printed in the toRoot method is what I want, but I am printing only the root in the junit test method. How do I fix this?
public List<K> toRoot(K key) {
        List<K> list=new LinkedList<K>();
        int i = key.compareTo(this.key);
        if(i == 0){
            list.add(this.key);
        }
        else if(i < 0){
            left.toRoot(key);
            list.add(this.key);
        }
        else if(i > 0){
            right.toRoot(key);
            list.add(this.key);
        }
        System.out.print(list); //prints "i o n p s z i"...these are the desired
        //outputs of the two assertEquals combined together
        return list;
    }

JUnit Testing
@Test public void testToRoot() {
    Tree<Character, Integer> tree = tree1();
    System.out.print(tree.toRoot('o')); //prints 'i'
    assertEquals("i", tree.toRoot('i'));
    assertEquals("o n p s z i", tree.toRoot('o'));
}
private static Tree<Character, Integer> tree1() {
    Tree<Character, Integer> tree = EmptyTree.getInstance();

    tree= tree.add('i', 1);
    tree= tree.add('z', 2);
    tree= tree.add('e', 3);
    tree= tree.add('s', 4);
    tree= tree.add('p', 5);
    tree= tree.add('n', 6);
    tree= tree.add('b', 7);
    tree= tree.add('h', 8);
    tree= tree.add('o', 9);
    tree= tree.add('f', 10);

    return tree;
}

additional details:
The tree class is an interface that the NotEmptyTree class implements and includes an overwritten toRoot.
public NonEmptyTree<K, V> add(K key, V value);

Here is the overwritten add method in the NotEmptyTree class
public NotEmptyTree<K, V> add(K key, V value) {
        if(key.compareTo(this.key) == 0){
            this.value = value;
        }else if(key.compareTo(this.key) < 0){
            left = left.add(key, value);
        }else{
            right = right.add(key, value);
        }
        return this;
    }

Letters near the front of the alphabet are smaller than those towards the end. In this case, 'i' is the parent node of 'e' and 'z'. 'z' has a left child of 's', which has left child of 'p', which has left child of 'n', which has right child of 'o'. 'e' has left child of 'b', which has right child of 'h'.

A: Your toRoot method may be printing a string to System.out, but it does not return a String. Instead, it returns a List. Thus your assertion is going to be always false because a String does not equal a List.
If you want to compare against a String, then you'll need to write a function that converts a List<K> into a space delimited String and then invoke that function before calling assertEquals.
Another alternative, would be to use a Hamcrest-style matcher like contains:
assertThat(tree.toRoot(), contains('o', 'n', 'p', 's', 'z', 'i'));

Note that despite the name, the contains does an in-order check, so even if the keys were out of order this test would fail, which should give identical behavior to the assertEquals check you were making before.


text:
Q: osgexport for Blender: Imported meshes impact scene ( possibly the lighting? ) Blender Version 2.79
OSG Version: 3.4.0-9
Operating System: Fedora
I have been using Blender's export utility to export obj files and then using osgconv to convert them to osg files. The files are then imported and rendered into a scene that looks like:
Image of the working scene before using the export tool
Today I installed osgexport by Cedric Pinson ( Github page: https://github.com/cedricpinson/osgexport ) to directly export from Blender to osgt files. I get the following results when I import those files and render them.
Image of the scene where everything goes dark and the lighting is wierd
Additional Details:

*

*The code is set to follow the human character. The rest of the scene
is static.

*When I use the old human model I get the working effect,
but the whole purpose of using the converter is to be able to export
its animations.

Any ideas? I saw the effect and I don't really even know where to start. The only difference is the outputted file from the converter. Everything else is the same. Also, if there is a newer/better way to export blender files into files that OSG can read, then I'm open to any and all suggestions.
Thank you in advance,

A: For what it's worth, the OSG forum/mailing list is usually pretty good about answering questions, and I believe I've seen Cedric's name there regularly, along with all the main contributors: http://forum.openscenegraph.org/
New users usually have to have their questions go through moderation, to cut down on spam, so just have some patience.
On this specific question, I have 3 suggestions:

*

*Convert both files to osgt and run a diff. Ignore any numerical differences, look for things like node arrangement, material types, etc.

*Try opening your exported model in osgviewer, just to see how the default settings display it. You can also easily play with things like backfaces, lighting settings, clipping planes, before dropping it into your application - press h to see all the run-time options.

*Instantiate your light with all 3 types of lighting enabled. Particularly, I have found some models depend heavily on specular lighting, but some of the examples don't turn it on. Of course, if you use the full-white values shown here, you may oversaturate, but this is for an example:
osg::Light *light = new osg::Light;
light->setAmbient(osg::Vec4(1.0,1.0,1.0,1.0));
light->setDiffuse(osg::Vec4(1.0,1.0,1.0,1.0));
light->setSpecular(osg::Vec4(1.0,1.0,1.0,1.0));  // some examples don't have this one


text:
Q: Masonry grid layout with scaling to fit container So I'm trying to do something like this: http://prothemeus.com/demo/litho/
I've come across:
http://masonry.desandro.com/, http://isotope.metafizzy.co/ and http://packery.metafizzy.co/ all of them are really similar but none of them offer the scaling like the website at top does. How would I go about creating something like that with one of these plugins or does anyone know of one that offers the option to scale to fit container by default?
As far as the demo goes, I was able to find out that isotope handles the layout but I wasn't able to track down the code that does the actual scaling.
Any help would be greatly appriciated.

A: I finished with ignoring all the plugins, only the smartresize which I minified because it uncompressed wherever I found it. Not sure if it was from Paul Irish or someone else, either way here's the jsfiddle for it. http://jsfiddle.net/matthewabrman/6R2DU/
//smartresize
(function(e,t){var n=function(e,t,n){var r;return function(){function u(){if(!n)e.apply(s,o);r=null}var s=this,o=arguments;if(r)clearTimeout(r);else if(n)e.apply(s,o);r=setTimeout(u,t||100)}};jQuery.fn[t]=function(e){return e?this.bind("resize",n(e)):this.trigger(t)}})(jQuery,"smartresize")

function redraw_UI() {
    var content_width = $('.content').width()+20;
    images_per_row = Math.floor(content_width / 240);
    var width = Math.round(content_width / images_per_row);
    var height = Math.round(width/3*2);
    $('.content .item').each(function(id){
        var x = Math.round((id % images_per_row) * width);
        var y = Math.floor(id/images_per_row) * height + Math.floor(id/images_per_row) * 20;
        if (navigator.appName.indexOf("Internet Explorer")!=-1){
            $(this).animate({width: width-20+'px', height: height+'px', left: x, top: y},600);
        } else {
            $(this).css({'width': width-20+'px', 'height': height+'px', 'left': x, 'top': y });
        }
    });

    if (images_per_row == 1) {
        closeImagePreview();
    }
}

$(window).smartresize(redraw_UI);
$(window).ready(redraw_UI);

A: Masonry does support this using the bindResize method: http://masonry.desandro.com/methods.html#bindresize
$container.masonry(options);
$container.masonry('bindResize')

This will trigger a layout on resize.  You could also do
$(window).resize(function () {
   $container.masonry();
});

which will trigger a re-layout, though you should throttle it to avoid it being called to offten.  This will scale to fit the container by default.
What you then have to do is make the container responsive so that it resizes according to the window size.  For that you can look into bootstrap or roll your own.