text:
Q: Splitting URL using JQuery I want to split the URL using JQuery and get a certain value, if that value is set I would display a certain 'div' corresponding with that value. Example:
http://www.example.com/index.php#div1

I want to split the URL from the fragment identifier '#' and get the value coming after it 'div1'.
I then want to check using javascript/jquery if the value after the '#' is 'div1', I would display 'div1'.
var url = http://www.example.com/index.php#div1,
hash = url.split('#')[1];

if(hash == 'div1'){
$('.div1').show();
//if the hash is equal to 'div1' show the div with the class 'div1'
}

A: No need to do a split, just use location.hash with an id
For example, given the URL http://yoursite.com/page#div1, the location.hash would return #div1. You can use this to select the proper element.
ID Method:
// JS
$(window.location.hash).show();

Hidden

Class method:
Alternatively, if you must use a class, you will need to remove the # from the location.hash
// JS
// The substr method removes the `#` from the beginning.
// You can just as easily use `replace`
var hash = window.location.hash.substr(1);

$('.' + hash).show();

Hidden


text:
Q: Objects not being removed without System.gc() call After having some trouble with object deletion, I ran a simple test:

*

*Created a simple class with a weak reference listener for Event.ENTER_FRAME.

*Added a trace("I Exist!") call to the listened function.

*Instantiated a single instance with one reference in the Document Class.

This worked as expected - the SWF file did nothing but print "I Exist!" every frame to the console. (In debug mode, of course.)
What I did next did not work as I expected:
I set the only reference of the object to be set to null on a mouse event, but the messages from the event listener of of said object still appeared in the console after the mouse event was fired and the reference set to null - meaning the object still existed!
Calling System.gc() in the document class IMMEDIATELY stopped the event listener from printing further messages and seemingly deleted the item.
From what I understand, calling System.gc() is discouraged, but as it seems from this simple test the garbage collector is a big FAIL.
Am I doing something wrong here in trying to dispose of the object, or should I simply call System.gc() every time I want to get rid of an object..?
Edit: Calling System.gc() with a non-weak listener also results in the object seemingly being removed from memory (?)

A: Garbage collection is almost always deferred in modern VMs (Java, Flash Player, .NET, etc.). You can read http://www.adobe.com/devnet/flashplayer/articles/garbage_collection.html for more information.
In particular:

In Flash Player 9, the garbage collector's operations are deferred. This is a very important thing to understand. Your objects will not be removed immediately when all active references are deleted. Rather, they will be removed at some indeterminate time in the future (from a developer standpoint). The garbage collector uses a set of heuristics that look at the RAM allocation and the size of the memory stack, among other things, to determine when to run. As a developer, you must accept the fact that you will have no way of knowing when, or even if, your inactive objects will get deallocated. You must also be aware that inactive objects will continue to execute indefinitely, until the garbage collector deallocates them, so your code will keep running (enterFrame events will continue), sounds will keep playing, loads will keep happening, other events will keep firing, and so on.

A: Actually this is the expected behavior of the Flash garbage collection system. The garbage collection routine runs every time System.gc() is called or a new object is created (new keyword). You should allow GC to naturally clean up objects, and anyways System.gc() only works for the debug player and does nothing for the release version.
If you want the listener from firing, it's ALWAYS best to manual remove the listener yourself with removeEventListener. However, if you don't care about the functionality existing until the next collection phase, you can just rely on the weak listener. Hope this helps.

A: Garbage collection is only triggered by allocation in Flash Player meaning setting an object to null will not cause the garbage collector to be invoked.
Setting an object to null only removes a specific reference to that object. In fact, your listener still has a reference to the object, in your case it's a weak reference so when the GC runs the object is collected but until then it's still hanging out in memory -- dispatching and receiving any events you set it up to handle.
The correct way to handle this is to explicitly remove any event listeners you no longer need, then let the GC do its thing when it's good and ready. Typically I handle this by adding a destroy() method to my classes that allow them to clean up their own mess before I do away with them.

A: Are you sure you removed all references to your object? i.e. did you remove the mouse event listener, if you added the object to the stage, did you removeChild?
Once you're sure all references have been removed, null the object
object = null;
Then importantly call System.gc() TWICE
Garbage collection cal have two phases, Mark and Sweep. Each call of System.gc() only performs one phase.
This is a great article and tool to enable you to track objects in your app to see which objects still have references to them at any point in time.
http://divillysausages.com/blog/tracking_memory_leaks_in_as3

redpajama_set_name: RedPajamaStackExchange


text:
Q: Predict Circle to Circle intersection in Time I need to find if two round objects will collide and if yes when in time they will.
My approach is this:
if (Vector3.DistanceSquared(a.Position, b.Position) < Math.Pow(a.Radius + b.Radius,2))
            {
                return 0;
            }
            else
            {
                float result;
                for (int t = 1; t < 150; t++)
                {
                    result = Vector3.DistanceSquared(a.Position + t * a.LinearVelocity, b.Position + t * b.LinearVelocity);
                    if (float.IsInfinity(result))
                    {
                        return float.PositiveInfinity;
                    }
                    if (result <= Math.Pow(a.Radius+b.Radius,2))
                    {
                        return t;
                    }
                }

                return float.PositiveInfinity;
            }

I am clearly missing something, or I am totally wrong cause the results are not as expected.
I also think performance wise the loop might be wrong but I am not sure how could I avoid it.

A: If we write squared distance between circle centers:
(x2-x1+t*(vx2-vx1))^2+(y2-y1+t*(vy2-vy1))^2=(r1+r2)^2
let dx = x2-x1, dy = y2-y1, dvx = vx2-vx1, dvy = vy2-vy1, rr = r1+r2
(dx+t*dvx)^2+(dy+t*dvy)^2=rr^2
dx^2+2*dx*t*dvx+t^2*dvx^2+dy^2+2*dy*t*dvy+t^2*dvy^2-rr^2=0
t^2*(dvx^2+dvy^2) + t*(2*dx*dvx+2*dy*dvy) + (dx^2+dy^2-rr^2)=0
t^2*a +             t*b +                   c               =0

This is quadratic equation for unknown t
D = b^2 - 4*a*c
if D<0 there are no collisions
if D=0 there is one touching in moment t = -b/(2*a)
else there are two solutions
t1 = (-b - sqrt(D)) / (2*a)
t2 = (-b + sqrt(D)) / (2*a)

One or both times might be negative - means collision "was in the past"
Smaller time is moment of collision, larger time - moment of "leaving", I think it is not needed here


text:
Q: Google Chrome - is this a BUG? Javascript issue? Touchscreen inputs are not working I have this simple button. It works on the same machine with a USB mouse click, but does not work when tapped via touchscreen (Iiyama touchscreen).

How can i make it compatible with touch input?

A: As screen touching is supported by another set of events, you should add listeners for touch-based events. Try this:
$("#vip_anytime").on("touchend", function(e){
 alert("OK we touched");
});

This should not replace the normal "click" event, but be added alongside it.
$("#vip_anytime").on("click touchend", function(e){
   alert("OK we touched");
});

If you require more information, then you might find this helpful: https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html
Edit:
Native JavaScript implementation might go as follows:
document.getElementById("vip_anytime").addEventListener("touchend", function(e) {
  alert("OK we touched");
});

And lastly, though it is not best practice you might call it by directly in your HTML code, as in your code example:

click me


text:
Q: Android Date Time I want to create a clock showing the hour and Minute of the current time like this 02:15 PM. What i want is now to keep the minutes part updating obviously after every 60 seconds as it is changed in our systems. So i want to know what is the best way to keep the time updating
thanks

A: .xml file's code,
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/txtTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

Activity file's code,
package com.example.demoproject;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.text.format.Time;
import android.widget.TextView;

public class MainActivity extends Activity
{
    private static TextView textview;
    private Timer timer;
    private Time today;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textview = (TextView ) findViewById( R.id.txtTime );

        today = new Time(Time.getCurrentTimezone());
        timer = new Timer();
        timer.schedule(new RemindTask(), 1000, 1000 );
    }

    private class RemindTask extends TimerTask
    {
        public void run()
        {

            runOnUiThread(new Runnable()
            {
                 public void run()
                 {
                        today.setToNow();
                        textview.setText(today.format("%k:%M:%S"));  // Current time
                }
            });
        }
    }
}


text:
Q: Add "I'd like to exclude..." option to Stack Exchange filters
Possible Duplicate:
Stack Exchange tags sets : exclude tag

Here's my filter: https://stackexchange.com/filters/26689/mod-rewrite
That's pretty nice, but I'd like to exclude stuff that have the iis tag.
Sometimes (hopefully not often) I'm losing some time trying to read and understand questions I'll never be able to answer, and I guess maybe I'm not the only one in this situation.
So, the Stack Exchange filters options, there's the 1. Which questions do you want to include? and I was wondering: how about adding an option, or a sub-question... or maybe a 2. Which questions do you want to exclude??


text:
Q: MongoDB Mongoose Scheme Nested Document Structure and Relations I have a project with the following document flow.
Users -> Accounts -> Projects
Users

*

*Users have specific roles

Accounts

*

*CRUD conditioned by User role

*Specific users will have access to individual accounts. I was thinking to add an array userGroup with user id's?

Projects

*

*Nested under Accounts related to a single accountToken ID

*CRUD conditioned by User role

*Specific users will have access to individual projects.

Here are example Schema models simplified for demo purposes.
UserSchema.js:
const UserSchema = new mongoose.Schema({
    email: {
      type: String,
      required: [true, 'Please add an email'],
      unique: true,
    },
    role: {
      type: String,
      enum: ['admin', 'user'],
      default: 'user'
    }
  });

  module.exports = mongoose.model('User', UserSchema);

AccountSchema.js:
const AccountSchema = new mongoose.Schema({
    accountName: {
      type: String,
    },
    accountToken: {
      type: String
    }
  });

  module.exports = mongoose.model('Account', AccountSchema);

ProjectSchema.js:
const ProjectSchema = new mongoose.Schema({
    projectName: {
        type: String,
    },
    projectType: String,
    projectToken: String
})

module.exports = mongoose.model('Project', ProjectSchema);

I am stuck on the best way to setup nested or sub-document Schema Relations and the best way to relate the data between each other. Any guidance and suggestions would be a huge help! Thanks!!!

A: Try this;
const UserSchema = new mongoose.Schema({
email: {
  type: String,
  required: [true, 'Please add an email'],
  unique: true,
},
role: {
  type: String,
  enum: ['admin', 'user'],
  default: 'user'
}
});

module.exports = mongoose.model('User', UserSchema);

const AccountSchema = new mongoose.Schema({
  userId: {
     type: mongoose.Schema.Types.ObjectId,
     required: true,
     ref: 'User'
 },
 accountName: {
     type: String,
 },
accountToken: {
    type: String
}
});

module.exports = mongoose.model('Account', AccountSchema);

const ProjectSchema = new mongoose.Schema({
  accountTokenId:{
      type: String
  },
  projectName: {
      type: String,
  },
  projectType: String,
  projectToken: String
})

module.exports = mongoose.model('Project', ProjectSchema);


text:
Q: Get boolean result whether table exists or not I don't want to commit a SQL request. I just want to known whether a specific table exists in data base or not, similar to the following pseudo statement:
IF EXISTS TABLE mytablename RETURN TRUE ELSE FALSE

How can I do this? I found several examples on how to modify a table if it doesn't exist.

A: This depends highly on the database, but this will work in many:
if exists (select 1 from information_schema.tables where table_name = 'mytablename')

(You might want to add additional conditions for the database/schema name.)
Although information_schema is supported in several databases, other databases might use all_tabs (Oracle) or some other table/view.
And, if you want a query that returns this value, use:
select max(case when table_name = 'mytablename' then 1 else 0 end) as TableExists
from information_schema.tables;

A: Try this Proc
CREATE PROCEDURE dbo.DoesTableExist (@TableName NVARCHAR(100))
AS
BEGIN
    IF EXISTS (SELECT * FROM sys.tables WHERE Name = @TableName)
        SELECT 1
    ELSE
        SELECT 0
END


text:
Q: Two different colors on one line of a list I would like two different colours on each line of a list. There is an example of the drop down list here http://deanpauley.co.uk/O-SB/categories.html
So rather that the dark grey "Photographers Gallery" being above the light grey "Deutche Borse photography prize 2011" I would like them as to be beside each other on the same line of the list.
The code is as follows:

Deutsche Börse Photography Prize 2011

—

                    Photographers Gallery

Deutsche Börse Photography Prize 2010

And the CSS:
#drop {
    font-size: 12px;
    font-weight:bold;
    position: fixed;
    z-index:inherit;
    left: 183px;
    width:700px;
    top: 15px;
    }

#drop ul {
    background: #fff;
    list-style-type: none;
    }

#drop ul li {
    width: 750px;
    float: left;
    list-style-type: none;
    margin: 0 10px -10 0;
    }

#drop ul li span {
    display: block;
    list-style-type: none;
    padding: 1px 3px;
    }

#drop ul li ul {
    background: #fff;
    opacity: 0.9;
    list-style-type: none;
    display: none;
    padding: 0 0em 0.5em 0;
    }

#drop ul li:hover ul {
    list-style-type: none;
    opacity: 0.9;
    }

#drop ul li ul li {
    border: none;
    list-style-type: none;
    float: none;
    padding-left:0px;
    }

#drop ul li ul li a {
    display: block;
    color: #808285;
    text-decoration: none;
    cursor:pointer;
    }

#drop ul li ul li a:hover {
    background: #d8d8dc;
    }

#drop ul li.section-title SPAN.section-title {
    color:#434442;
    margin-left: -3px;
    }

span.nav-title {
    border-bottom: 1px solid #808285;
    position:fixed;
    left: 223px;
    width:744px;
    top: 28px;
    cursor:pointer;

    }

I am really new at coding so any advice would be much appreciated. Can't get my head around this at all!

A: We'll start as if there was only the following HTML (the HTML of the list)

—

Deutsche Börse Photography Prize 2010

  ...

(Note that I removed the title text)
So your problem can be summed up like that:

*

*Step 1 :
You need to add the text before each item
To do that, assuming that you don't know exactly the structure of the menu, you'll have to do some copy/paste:
each line would be like that:

    Photographers Gallery
    Deutsche Börse Photography Prize 2010

You'll need to change the text for every line.

*Step 2:
You need to color the text.
This is easy, it's already done in the CSS, with the following:
#drop ul li.section-title SPAN.section-title {
  color:#434442;
  margin-left: -3px;
}

We'll change it to be a bit less specific
#drop span.section-title {
  color:#434442;
  margin-left: -3px;
}

And that should do it :)


text:
Q: How to keep alive the VPN connection? I'm using NetworkManager and OpenVPN on linux.
The problem is I get random disconnections, especially when idle.
So I was thinking maybe there was an option to keep it alive. I have seen examples for OpenVPN config files, but I don't think I'm using one. I have set up everything directly from the NetworkManager. I found the NetworkManger config file for my current connection, and it has these sections: [connection], [vpn], and [ipv4]. Does any of those have a keepalive option? What's the syntax, and how does it work?

A: According to the documentation here, the KeepAlive parameter is probably what you were looking for.

# The keepalive directive causes ping-like
   # messages to be sent back and forth over
   # the link so that each side knows when
   # the other side has gone down.
   # Ping every 10 seconds, assume that remote
   # peer is down if no ping received during
   # a 120 second time period.
   keepalive 10 120

This should either be added to the OpenVPN connection profile as a new line, or to the Advanced Configuration on the server (likely /etc/openvpn/openvpn.conf).

A: Hi there i have a similar issue.
Host a (client)
Host b (server)
host a often loses internet connection from ISP (very unstable isp). When it comes back online the vpn connections is working, but there is no internet available i need to restart openvn to fix that.
config:
client
proto udp
explicit-exit-notify
remote host_b_IP 1194
dev tun
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
verify-x509-name server_UkL6u24ryBD1b4zJ name
auth SHA256
auth-nocache
cipher AES-128-GCM
tls-client
tls-version-min 1.2
tls-cipher TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256
ignore-unknown-option block-outside-dns
setenv opt block-outside-dns # Prevent Windows 10 DNS leak
verb 3

A: Insert on the client:
keepalive 10 60

This will keep your connection up.

A: You have to do it each time you start up but what is wrong with just setting up ping xx - t in a terminal window.
Its low overhead and certainly fixes my problems in Windows 10 VPN which is locked down to a 30 minute idle timeout.


text:
Q: Using startswith() function inside lists in python I had the list with following strings below
some_list = ['9196358485','9966325645','8846853128','8-4-236/2','9-6-32/45','Need to fetch some strings']

From the above strings i want only strings that does n't start with 91,9,8 but want  strings starting with 8-, 9-
so below is my code
[i for i in some_list if all(not i.startswith(x) for x in ['91','8','9'])]

result:
['Need to fetch some strings']

In the above by using ['91','8','9'] as the condition is deleting the strings starting with 9 and 8 which is correct, but i don't want 9-, 8- also to be removed from the list, actually my intension is if the strings starting with 9 and 8 should be ignored as above and strings starting with 9- and 8- should not be ignored , can we write two conditions in a single line with concept of taking strings starting with 8-,9- and ignoring when strings starts with 9 or 8 in the above code i had written.
Can anyone please let me know hoe to do this.............
Edited code:
Thanks for  all of u r support if u don't think this is another question i had some actual output on which the below code is not working
some_list = ['Mr K V  Prasad Reddy(MD)',
 '+(91)-9849633132, 9959455935',
 '+(91)-9849633132',
 'Near NRI College,Opp Vijaya Bank,Nizam Pet Road,Nizampet,Hyderabad - 502102',
 '9196358485',
 '9966325645',
 '8846853128',
 '8-4-236/2',
 '9-6-32/45',
 'Need to fetch some strings']

When i apply the bwlow code using regex i got following output
result:
['Mr K V  Prasad Reddy(MD)',
 '+(91)-9849633132, 9959455935',
 '+(91)-9849633132',
 'Near NRI College,Opp Vijaya Bank,Nizam Pet Road,Nizampet,Hyderabad - 502102',
 '8-4-236/2',
 '9-6-32/45',
 'Need to fetch some strings']

Actually i don't want all phone numbers from the list, so they will be in the above format sometimes starting with 91 sometimes 8 sometimes 9
How can we remove all those phone numbers from the list?

A: Use a regular expression:
>>> import re
>>> [i for i in some_list if not re.match(r"[98]\B|+\(91\)", i)]
['8-4-236/2', '9-6-32/45', 'Need to fetch some strings']

\B matches only within alphanumeric strings, so it matches between 9 and 1 but not between 9 and -.


text:
Q: How to store all file names from the directory and save it in excel? Good evening Everyone.
i wrote a small piece of code (Got help from this stackoverflow Search)
I could able to get the list of files from the directory.
I tried to store in Excel Spreadsheet. I could able to store only two lines of the file in excel, but not all the file names.
Please check the code and output.
Help me a solution to list all file names in the excel.
Thanks a million.
code:-
import os
import pandas as pd
path = "//home//halovivek//Downloads//education//Jimi Kwik - Super Brain//"
list = []
for (root,dirs, file) in os.walk(path):
    for f in file:
        print(f)

my_data = pd.DataFrame(file)
my_data.to_excel("outputfile.xlsx", index = False, header= False)

output:-
/home/halovivek/PycharmProjects/yearcoding/venv/bin/python
/home/halovivek/PycharmProjects/yearcoding/26082002_listfilesfromdirectory.py
Day 12 - Implementation Day - Juggling Exercise.mp4 Day 12 -
Implementation Day - Juggling Exercise.MP3 Part 2 - Preparing For The
Quest.mp4 Part 1 - Welcome To Your 30-Day Superbrain Quest.mp4 Part 5

*

*10 Morning Habits Geniuses Use To Jump Start The Brain.mp4 Part 3 - The FAST Method For Learning Anything.mp4 Part 2 - Preparing For The
Quest.MP3 Part 1 - Welcome To Your 30-Day Superbrain Quest.MP3 Part 5

*10 Morning Habits Geniuses Use To Jump Start The Brain.MP3 Part 4 - How To Take Notes.mp4 Part 3 - The FAST Method For Learning
Anything.MP3 Part 4 - How To Take Notes.MP3 Day 27 - The Ancient
Alphanumeric Code Of Memory Part 2 - Application.MP3 Day 27 - The
Ancient Alphanumeric Code Of Memory Part 2 - Application.mp4 Day 29 -
The 5 Levels Of Transformation.MP3 Day 29 - The 5 Levels Of
Transformation.mp4 Day 14 - Memory Is As Easy As PIE.MP3 Day 14 -
Memory Is As Easy As PIE.mp4 Day 15 - The FDR Technique.MP3 Day 15 -
The FDR Technique.mp4 Day 31 - Overcoming Procrastination.mp4 Day 31 -
Overcoming Procrastination.MP3 Day 9 - Chain Linking - Part 1.mp4 Day
9 - Chain Linking - Part 1.MP3 Day 8 - Implementation Day - Morning
Routine.mp4 Day 8 - Implementation Day - Morning Routine.MP3 Day 24 -
Implementation Day - Crossovers.MP3 Day 24 - Implementation Day -
Crossovers.mp4 Day 19 - Learning Foreign Languages.mp4 Day 19 -
Learning Foreign Languages.MP3 Day 13 - BE SUAVE Remembering Names.MP3
Day 13 - BE SUAVE Remembering Names.mp4 Day 34 - Speed Reading.MP3 Day
34 - Speed Reading.mp4 Day 22 - The Location Method.MP3 Day 22 - The
Location Method.mp4 Day 5 - Nutrition _ Your Body Folders.MP3 Day 5 -
Nutrition _ Your Body Folders.mp4 Day 23 - Memorize Word For Word.MP3
Day 23 - Memorize Word For Word.mp4 Day 30 - Q&A Session with Jim.mp4
Day 30 - The 5 Levels Of Learning.mp4 Day 30 - The 5 Levels Of
Learning.MP3 Day 30 - Q&A with Jim.MP3 Day 28 - Implementation Day -
Phonetic Number Code.MP3 Day 28 - Implementation Day - Phonetic Number
Code.mp4 How To Become A Super Learner Masterclass - Jim Kwik.mp4
how_to_become_a_super_learner_by_jim_kwik_workbook_nsp.pdf Day 18 -
Keyword Substitution Method.MP3 Day 18 - Keyword Substitution
Method.mp4 Day 32 - Your 8 C's To Muscle Memory.mp4 Day 32 - Your 8
C's To Muscle Memory.MP3 Day 4 - Implementation Day - Spaced
Repetition Concept.mp4 Day 4 - Implementation Day - Spaced Repetition
Concept.MP3 Day 26 - The Ancient Alphanumeric Code Of Memory Part 1 -
The Sounds.MP3 Day 26 - The Ancient Alphanumeric Code Of Memory Part 1

*The Sounds.mp4 Day 2 - The Sun Is Up.mp4 Day 2 - The Sun Is Up.MP3 Day 16 - Implementation Day - Superbrain Yoga.MP3 Day 16 -
Implementation Day - Superbrain Yoga.mp4 Day 10 - Chain Linking - Part
2.MP3 Day 10 - Chain Linking - Part 2.mp4 .getxfer.14810.259.mega Day 7 - Sleep _ Stress Management.MP3 Day 7 - Sleep _ Stress
Management.mp4 Day 33 - Remembering Your Dreams.mp4 Day 33 -
Remembering Your Dreams.MP3 .getxfer.14709.10.mega
.getxfer.28947.5.mega Day 21 - How To Give A Speech Without Notes.MP3
.getxfer.27388.5.mega Day 3 - The 10 Keys To Unlocking Your
Superbrain.mp4 .getxfer.10040.5.mega Day 6 - Environments _ Killing
ANTs.MP3
_Groupinsiders.com.url Day 6 - Environments _ Killing ANTs.mp4 Day 25 - Numbers - The Basics.mp4 Day 25 - Numbers - The Basics.MP3 Day 1 - M.O.M. Can Help You Remember.MP3 Day 1 - M.O.M. Can Help You
Remember.mp4 Day 20 - Implementation Day - Counting To 10 In
Japanese.MP3 Day 20 - Implementation Day - Counting To 10 In
Japanese.mp4 Day 11 - The Peg Memory Method.MP3 Day 11 - The Peg
Memory Method.mp4 Day 17 - The Ultimate TIP To Remembering
Anything.MP3 Day 17 - The Ultimate TIP To Remembering Anything.mp4

Process finished with exit code 0

A: You're issues here... 'list' is a keyword in python.. so can't be used as a variable name when you try to declare a list..
You're not actually doing anything with your values in your loop
Glob is slightly easier for working through directories
import glob
list_of_files = []
for file_or_dir in glob.glob("//home//halovivek//Downloads//education//Jimi Kwik - Super Brain//**", recursive = True):
        if os.path.isfile(file_or_dir)
                list_of_mp3s_mp4s.append(file_or_dir)
my_data = pd.DataFrame(list_of_mp3s)
my_data.to_excel("outputfile.xlsx", index = False, header= False)

A: import os
import pandas as pd
#path of the file you want to enemurate
path = "//home//halovivek//Downloads//"
directory =[]
filename=[]

for (root,dirs, file) in os.walk(path):
    for f in file:
        directory.append(root)
        filename.append(f)
        print(f)

#column name of the sheet
df=pd.DataFrame(list(zip(directory,filename)),columns=['Directory',"filename"])
#change the file of exccl sheet
df.to_csv("all.csv")

It will list all files and store it in the spreadsheet in csv format.
I tested and its working fine.


text:
Q: what is the difference between keepUnusedDataFor and refetchOnMountOrArgsChange? I am working with RTK query and I have a project that I am working on, where I want to make an API call every 5 seconds (interval), and I do not know the difference between the keepUnusedDataFor and refetchOnMountOrArgsChange property.
Which one should I use to make the API call every 5 seconds.

A: RTK Query keeps an internal counter for each endpoint+cacheKey combination. It increases the counter for each component that wants to read that data, ie, useGetPokemonQuery("pikachu").  When components unmount or change the cache key, it decreases the counter.
When a subscription counter goes to 0, RTK Query sets a timer, and by default that timer is 60s.  If no components have asked to read that data when the timer expires, it will remove the data from the cache.
keepUnusedDataFor changes the timer delay.  If you set it to, say, 60 * 60, it will wait for one hour before checking if the data should be removed.  If you did 60 * 60 * 24 * 365 * 10, it would wait for 10 years before checking to remove the data (ie, "basically forever").
refetchOnMountOrArgChange`, on the other hand, can be used to force re-fetching more often than usual.
See these explanations in the docs:

*

*https://redux-toolkit.js.org/rtk-query/usage/cache-behavior#reducing-subscription-time-with-keepunuseddatafor

*https://redux-toolkit.js.org/rtk-query/usage/cache-behavior#encouraging-re-fetching-with-refetchonmountorargchange

A: To anybody from the future, Here is what I came up with, I used refetch which is returned by RTK-query hooks.

// stocks component

import { useGetStocksQuery } from '../features/stocksList/stocksListApiSlice';
import { useEffect, useRef } from "react";

const Stocks = () => {

    const tickerArray = [
        "AAPL",
        "TSLA",
        "NKE",
        "MSFT",
        "AMZN",
        "GOOGL",
        "META",
        "SNAP",
        "NFLX"
    ];

    const stockTimerId = useRef();

   let {
        data: list,
        refetch
    } = useGetStocksQuery({tickerArray});

    useEffect(() => {

   stockTimerId.current = await setInterval(() => refetch(), 10000);

  }

        return () => clearInterval(stockTimerId.current)
    })

return (
  <>Your JSX goes here</>
)

}

export default Stocks


text:
Q: how to create Webservice in asp.net for requesting page filled in textbox using authorized password and username i'm trying to make webservice ,
it includes usename field, password field and page-name field and click button
after clicking click-button, using webservice , username and password must be authenticated
and page-name in text-field must be browsed in the browser.
I'm trying in localhost.
Can anyone provide me information, as i'm trying first time.

A: Well, there's a lot of big concepts in the question you just asked.   I would probably start with looking at ASP.NET's membership provider.  http://msdn.microsoft.com/en-us/library/ff184050.aspx
That link is a nice basic walkthrough on how to create a simple login form.  You could likely extrapolate to add a text box where a user could type a URL.


text:
Q: Double pointer to a 1D array Please bear with me as I've got little to no idea what I'm talking about. I'm trying to read the data (excluding the header) from a PGM file. I've got a function (read_data) which accepts  accepts a double pointer (char** data) as a parameter.
Within the function, I'm able to put the data into an array (arr) but my problem is assigning that pointer (**data) to that array. Here is my code thus far:
read_data(char* file, char** data) {
FILE *fp = fopen(file, "rb");
char type[3], dump;
int i =0, data_length;
int w, h; // width & height

fgets(type, sizeof(type), fp);
fscanf(fp, "%d", &w);
fscanf(fp, "%d", &h);

if (strcmp(type, "P5 ")) {
    data_length = w * h;
    }
else {
    data_length = (w * h) * 3;
    } // this is to work out the size of the array (how many bits of data are in the    file)

char arr[data_length];

while ((dump = fgetc(fp)) != '\n'); // just to skip the header

for (i; i < data_length; i++) {
arr[i] = fgetc(fp);
}

data = &arr; // <--- The problem

fclose(fp);

return data_length;

}

main () {
int data_length;
char **data = malloc(sizeof(int*)*data_length);

read_data("file.pgm",data);

}

Hope this is readable.  Thanks.

A: You are combining two different problems: file I/O and pointer handling. Since the real problem is the pointer handling, let's use a simpler example. First, a function that can create and fill an array of char:
#include <stdio.h>
#include <string.h>

void foo()
{
  char arr[6];
  strcpy(arr, "hello");
  printf("%s\n", arr);
}

So far, so good. (And from here on I'll leave out the #include directives.) But this is an array on the stack, so it turns back into wilderness when control passes out of the function. We want dynamic allocation, on the heap:
void foo()
{
  char *arr = malloc(6*sizeof(char));
  strcpy(arr, "hello");
  printf("%s\n", arr);
}

(Note: in your question you declare the array outside the function, but that means that you must do so without knowing what length it should be, which doesn't seem to be what you intend. This is a cleaner approach, and if you really want to declare the array outside, you can do that with only slight alteration.)
Now about the pointer. It's easy to assign the address of this array (which is the value assigned to arr) to another pointer:
char *p;
p = arr;

but we don't want to assign that value to some local pointer variable in the function; we want to assign it to a pointer value back in the scope of the code calling the function. The way to do that with an ordinary variable is by use of a pointer to that variable:
void bar(int *k)
{
  *k = 5;
}

...
int n;
bar(&n);
...

So we do the same with this pointer variable:
void foo(char **p)
{
  char *arr = malloc(6*sizeof(char));
  strcpy(arr, "hello");
  *p = arr;
}

int main()
{
  char *z;
  foo(&z);
  printf("%s\n", z);
}

(We could even do away with arr, but let's take things slowly.)
Once this is clear, you can splice it to the code that handles file I/O. Remember, always develop new functionality in isolation.

A: Try this
int n = 0;

while(condition)
    nextchar = fgetc(filepointer);
    (*image_data)[n]= nextchar;
    // or (*data)[n]= nextchar;
    n++;


text:
Q: Google Sheets API V4 adding new row of data The documentation says:

"The Sheets API v4 does provide an AppendCells request that can be used with the spreadsheets.batchUpdate method to append a row of data
  to a sheet (and simultaneously update the cell properties and
  formatting, if desired). However, it is usually easier to simply
  determine the A1 notation of the row you wish to add, and then issue a
  spreadsheets.values.update request to overwrite that row."

How do you determine the A1 notation of the row you wish to add and/or how does the AppendCells request get made? I'm using php.


text:
Q: Word Problems - Racer
There are two racers in a circular
  racetrack of 1200 meters. When both
  are moving in the same sense, the
  first racer comes across the second one
  every 200 seconds. But in different
  sense, they come across each other
  every 100 seconds. What speeds have
  each one ?

I tried to figure it out but I have no idea how to do it. It's supposed to be a kinematics exercise, since kinematics is mathematics, I asked here. My doubts lay on doing word problems with speed, time and space. I'm so frustrated.
editing...
$1200 = (v1 - v2)*200$
$1200 = (v1 + v2)*100$
$v1 - v2 = 6$
$v1 + v2 = 12$
$2v1 = 18$
$v1 = 9$
$v2 = 12 - 9$
$v2 = 3$
Is it right or I made any mistakes ?

A: HINT: Let us denote with $v_1$ ($v_2$) the speed of the first (second) racer.
If they are going in opposite directions, the relative speed is the sum $v_1 + v_2$. Going in the same direction, the relative speed is $|v_1 - v_2| = v_1 - v_2$, where we have assumed WLOG that $v_1 \geq v_2$.


text:
Q: Mongodump pipeline into docker swarm I've issue with dumping data from mongo container into swarm. I can't use run into swarm, I can't connect other container (run'mongodump because main network not manually attachable).
I googled this issue and I've found only solutions with docker-compose --link which doesn't work in swarm.
My plane was:

*

*Run other mongo container with command mongodump --host
main_mongo_container --out some_volume.

*Compress dump into tar

*Upload dump onto S3.

*Run script in cron.

I don't have enough experience for solving this issue myself. Had anyone experience in automatization dumping mongo data from swarm container onto s3?
Many thanks in advance!

A: Why not run a swarm service that runs an hourly back and then you can automate it with a script to upload where you need it, or just store it in an EBS volume. Here's a simple example using digitalocean block storage.


text:
Q: Knex sometime return an empty string I'm using knex with MYSQL. I have a function that I called to show the data to the user, Also I'm using a view table which has 5 right join on it and I think it will take some time to return values from the table plus I added the WHERE condition on my knex and it looks like this :
var showClass = (teacherId , ClassId){
return new Promise((resolve , reject)=>{

        knex.select().from('v_cardex_details').where({teacherId }).andWhere({id : ClassId}).then(classes =>{

            resolve(classes)

        }).catch(err=>{
            console.error(`Show Teacher class Error: ${err}`)
            reject (err)
        })
    })
}

and I call this general function to response some request something like this
exports.EditClass = (req,res)=>{
 knex('Table').update({//Some update stuff here}).then(()=>{
  showClass(req.user.id, req.params.id).then(data=>{
   return res.status(200).json({data , message:''})
})
}).catch()
}

With the same input, this function after updating returns value and some times it returns an empty string, especially when it's on the hosting server most of the time it returns nothing but { message : '' }

A: Try to create simplified code by removing all the unnecessary wrappers and you might find where your problem is. AFAIK there is no way that that your {data , message:''} would create an object containing just {message: ''} without any additional attributes.
> var data = []
undefined
> {data, foo:1}
{ data: [], foo: 1 }
> data = undefined
undefined
> {data, foo:1}
{ data: undefined, foo: 1 }
> {data1, foo:1}
ReferenceError: data1 is not defined

The problem you are experiencing does not exist in from the code you have shared (though there are syntax errors and other problems).
EDIT:
res.json() uses JSON.stringify() to convert js object to JSON strings. So if value of data in your code is undefined instead of and array, that could explain the behavior you are experiencing:
λ node
> JSON.stringify({ test: undefined })
'{}'

As you can see JSON.stringify() omits the attributes with value undefined from the output JSON string.


text:
Q: Add label from SPSS as column name in R I try to import an SPSS file (.sav) into R. I used:
library(forigin)
read.spss("file.sav", to.data.frame = TRUE, use.value.labels = TRUE)

For the original data Label is coded like "Q8A_10 - some text". See the picture below (i.e. "Language" in the first line):

But the column name which I get from read.spss says just "Q8A_10" (i.e. without the text). How can I get the complete Label from SPSS as column name.
If I view() the data frame it´s OK,

but not if I use glimpse() or str()
library(dplyr)

file %>%
select(1:2) %>%
head()

  RESPID        SAMPLE
1    524 Client Sample
2   1362 Client Sample
3   1872 Client Sample
4   1894 Client Sample
5   2063 Client Sample
6   2077 Client Sample


text:
Q: REST API INTEGRATION WITH APACHE NIFI (Getting data from kafka -transform ->generate token (POST)-> post API ) I am trying to create a flow in Apache Nifi - Situation is like this
1- Consume message from kafka (DONE)
2- transform to a valid request body (DONE)
3- Preserve the transformed message
4- Generate a oauth2 token (it is a post api )
5- Invoke a post api with transformed json as request body and send token in header
I have tried few ways like putting transformed json in cache and getting it after token generation but the problem is I am not able to pass token to fetchdistributedcache processor .
I tried putting json file on my server but getfile doesn't take any input so not able to trigger it after getting token .

A: If Step 4 (OAuth) is returning the token as the body, there is an option in InvokeHTTP to put the response body in an attribute rather than FF content, thus preserving original FF content.
So, you could skip step 3 completely.
Consume kafka -> transformations -> InvokeHTTP for OAuth token (with Put Response Body In Attribute) -> UpdateAttribute (optional - assuming you will need to do some formatting on the response body)  -> InvokeHTTP (OAuth token is already in an attribute and the FF content is unchanged)
https://nifi.apache.org/docs/nifi-docs/components/org.apache.nifi/nifi-standard-nar/1.12.1/org.apache.nifi.processors.standard.InvokeHTTP/


text:
Q: Azure DevOps Multiple Build pipeline under single Repo Drain the build server memory when using Git I have more than 20 solutions under single repository. Even I added path filter under the trigger, each build pipeline checkout save entire repository under build agents _work/x/s folder. It is draining the server memory. Anybody could help me in this situation to apply a path filter for the checkout or each build pipeline should refer same source. I'm using Git pipeline.

A: Assuming with Memory, you mean the disk space, I can see how 20 solutions, with their own pipeline, each with their own working folder can cause it to consume a lot of disk space. Each pipeline gets it's own workspace folder, this is to allow them to change independently, yet give them the greatest speed. In your case each pipeline accesses the same repo, but each may have different repo settings. This way the agent doesn't have to care about that.
There are a few options, some already mentioned by others.

*

*Use shallow clones. You can configure the pipeline to only fetch up to X amount of commits of history. This may greatly reduce the working folder size for each pipeline, but may slow down your builds a bit if you build many different branches. You can enable shallow clones by setting the fetchDepth a small number. If you depend on GitVersion to calculate a build number, or any other tasks that depend on the repo history, they may break when setting fetchDepth too low.
steps:
- checkout: self | none | repository name # self represents the repo where the initial Pipelines YAML file was found
  clean: boolean  # if true, run `execute git clean -ffdx && git reset --hard HEAD` before fetching
  fetchDepth: number  # the depth of commits to ask Git to fetch; defaults to no limit
  lfs: boolean  # whether to download Git-LFS files; defaults to false
  submodules: true | recursive  # set to 'true' for a single level of submodules or 'recursive' to get submodules of submodules; defaults to not checking out submodules
  path: string  # path to check out source code, relative to the agent's build directory (e.g. \_work\1); defaults to a directory called `s`
  persistCredentials: boolean  # if 'true', leave the OAuth token in the Git config after the initial fetch; defaults to false

*Clean-up at the end of each build. You could add a script step to the end of the pipeline to clean up your local working folders. A simple script step with condition: always() should do the trick. That way you can remove large build outputs from the drive when the build is done. You could use a YAML template to auto-inject this task into every job/pipeline.

*Take control over the checkout process As others mentioned, you can tell Pipelines to not checkout the repo, that way you can take control of that process yourself. You have a few options here:
    - checkout: none

a. worktree, this command will allow your build pipelines to share their .git folder. Instead of cloning the repo each time, you clone it once, then each pipeline creates a new worktree in the $(build.sourcesdirectory). This can be a massive space saver, yet keeping all the history on the build agent for fast branch switching and support for tools like gitversion. Follow the general steps from Vitu Liu.
b. sparse-checkout this command will allow you to configure which folders to check out in your local working directory. The git commandline client is clever enough to also fetch only the data needed for those folders. Follow the steps from Vitu Liu.
c. Use a custom checkout task. This custom checkout task will use a single folder on the agent and uses a symlink to make sure each pipeline uses the same repo under the hood. It doesn't seem to be released to the marketplace though, so you'll have to install if using tfx-cli.
cd drive:\path\to\extracted\zip
tfx login
tfx build tasks upload --task-path .

*Create a single pipeline and include parameterized YAML files. By creating a single pipeline, the agent will create a single working folder. Then, based on the files that were changed, execute the pipeline files of the solutions you want to build. See the Parameters to select at runtime docs. Other answers have already explained how to use the git command line to iterate the files that have changed and setting a variable based on their outcome.
steps:
- ${{ if eq(parameters.experimentalTemplate, true) }}:
  - template: experimental.yml
- ${{ if not(eq(parameters.experimentalTemplate, true)) }}:
  - template: stable.yml

*Use the new Scale-set agent. Azure Pipelines now offers a way to setup your own agent in the same way the hosted pipelines run. One of the advantages is that you control when an image is reset. Basically allowing you to  have a clean image every build with all your dependencies pre-installed or your npm/nuget caches pre-populated. The low-cost parallelization features are probably also very useful to your scenario.

*Configure maintenance, You can enable a cleanup job on the agent pool. It will queue a special job to clean up the working folders, old tasks, temporary files etc. It may help in case not all 20 solutions run on the same day. You can find this option on the account level.

There is an open issue on the Azure Pipelines Agent repo.

A: In Azure DevOps, we don't have option to get only part of the repository, but there is a workaround: Disable the "Get sources" step and get only the source you want by manually executing the according git commands in a script.
a. Disable "Get sources"
- checkout: none

b. In the pipeline add task cmd or PowerShell to get the sources manually with git sparse-checkout. For example, get only the directories src_1 and src_2 within the test folder
parameters:
  access: '{personal access token}'
  repository: '{dev.azure.com/organisation/project/_git/repository}'
  sourcePath: '{path/to/files/}'

- task: CmdLine@2
      inputs:
        script: |
          ECHO ##[command] git init
          git init
          ECHO ##[command] git sparse-checkout: ${{ parameters.sourcePath }}
          git config core.sparsecheckout true
          echo ${{ parameters.sourcePath }} >> .git/info/sparse-checkout
          ECHO ##[command] git remote add origin https://${{ parameters.repository }}
          git remote add origin https://${{ parameters.access }}@${{ parameters.repository }}
          ECHO ##[command] git fetch --progress --verbose --depth=1 origin master
          git fetch --progress --verbose --depth=1 origin master
          ECHO ##[command] git pull --progress --verbose origin master
          git pull --progress --verbose origin master

You can refer to this ticket to get more details

A: Note : you have not provided your YAML file for reference, so making some standard assumptions that you are using a simple YAML schema.
multiple solutions in a single repo, so a classic mono repo setup. you are looking at something like this.
- script: npm install
  workingDirectory: service-b/

Change your working directory at the beginning of the CICD Pipeline code in your YAML. Once the working directory, rest of it goes as usual with your existing YAML
Note a few things.

*

*it is possible to setup triggers based on specific folder changes. So, if you have

Repository Root
--ProjectOne
--ProjectTwo
.
.
.
--ProjectThree
It is possible to setup triggers for each folder, and then, in your YAML, change the working Directory, and accordingly do your business.

*

*Further, for deployment, if you are new, i would simply build a new pipeline for each project to make it easy.

*Or, if you really want to have it all in one file, you can add conditions and route the entire mono repo in a single YAML. Depending on a specific variable (for example, a project name), you can route the deployment to your desired target.
more details at the following locations.

*

*https://learn.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=azure-devops&tabs=schema%2Cparameter-schema

*https://julie.io/writing/monorepo-pipelines-in-azure-devops/

*https://learn.microsoft.com/en-us/azure/devops/pipelines/customize-pipeline?view=azure-devops


text:
Q: Error in receiving JSON by Buffered Reader My Server is sending some JSON String to my Android Client, but some errors occured. Please Help:
My Server is trying to send the following text to my android client
Server Output: ( 2D String Array)
[
    [
      "testingg",
      "3",
      "24:df:6a:e7:47:3c",
      "f8:e7:1e:1e:21:58",
      "f8:e7:1e:1d:fd:3c"
    ],
    [
      "moreee",
      "4",
      "24:c9:a1:36:03:48",
      "24:c9:a1:35:fe:38",
      "24:c9:a1:36:05:08",
      "24:c9:a1:36:04:38"
    ],
    [
      "lailailai",
      "4",
      "24:c9:a1:36:03:48",
      "24:c9:a1:36:05:08",
      "24:c9:a1:35:fe:38",
      "24:c9:a1:36:03:48"
    ],
    [
      "tryyyy",
      "2",
      "24:c9:a1:36:03:48",
      "24:c9:a1:35:fe:38"
    ],
    [
      "testyyy",
      "2",
      "24:c9:a1:36:03:48",
      "24:c9:a1:36:05:08"
    ],
    [
      "hahaha",
      "3",
      "24:c9:a1:36:03:48",
      "24:c9:a1:35:fe:38",
      "24:c9:a1:36:05:08"
    ],
    [
      "ehyyy",
      "2",
      "24:c9:a1:36:03:48",
      "24:c9:a1:36:05:08"
    ],
    [
      "offlinet",
      "2",
      "24:c9:a1:36:03:48",
      "e8:de:27:5b:a2:ea"
    ],
    [
      "opop",
      "4",
      "24:c9:a1:36:03:48",
      "24:c9:a1:36:02:98",
      "24:c9:a1:36:03:48",
      "24:c9:a1:36:02:98"
    ],
    [
      "tt",
      "5",
      "24:c9:a1:36:03:48",
      "24:c9:a1:36:05:08",
      "24:c9:a1:35:fe:38",
      "24:c9:a1:36:03:48",
      "24:c9:a1:36:05:08"
    ],
    [
      "Input",
      "6",
      "24:c9:a1:36:03:48",
      "24:c9:a1:35:fe:38",
      "70:8b:cd:b3:17:2c",
      "24:c9:a1:36:03:48",
      "70:8b:cd:b3:17:2c",
      "24:c9:a1:36:03:48"
    ],
    [
      "cekkk",
      "5",
      "24:c9:a1:36:03:48",
      "24:c9:a1:36:05:08",
      "24:c9:a1:35:fe:38",
      "24:c9:a1:36:05:78",
      "24:c9:a1:36:03:48"
    ],
    [
      "oo",
      "5",
      "24:df:6a:e7:47:3c",
      "e8:de:27:5b:a2:ea",
      "70:8b:cd:b3:17:2c",
      "f4:f2:6d:d1:20:20",
      "e8:50:8b:f3:a9:2a"
    ]
    ]

** Client Code:** ( Receiving entity )
  public class databrowsing extends AppCompatActivity {
  Socket myclient = null;
  private String jsonString = "";
   Gson gson = new Gson();
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_databrowsing);
    socketHandler CLIENT = new socketHandler();
    myclient = CLIENT.getSocket();

    PrintWriter pw = null;
    try {
        pw = new PrintWriter(myclient.getOutputStream(), true);
    } catch (IOException e) {
        e.printStackTrace();
    }
    pw.println("OnlinePositiongforIndoorPositioning");

   new receiveJson().execute(myclient);

 }

private class receiveJson extends AsyncTask< Socket,Void,String> {
    @Override
    protected String doInBackground(Socket... params ){
        myclient=params[0];
        try {
            StringBuffer buildString=new StringBuffer();
            BufferedReader in = new BufferedReader(new InputStreamReader(myclient.getInputStream()));
            while((jsonString=in.readLine())!=null){
                buildString.append(jsonString);
            }
            return jsonString;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        String[][] tableconfig = gson.fromJson(jsonString, String[][].class);
        System.out.println(Arrays.deepToString(tableconfig));
    }
}

Error Logcat of the Android Studio:
java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:545)
at libcore.io.IoBridge.recvfrom(IoBridge.java:509)
at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
 at java.io.InputStreamReader.read(InputStreamReader.java:233)
 at java.io.BufferedReader.fillBuf(BufferedReader.java:145)
 at java.io.BufferedReader.readLine(BufferedReader.java:397)
 at com.utm.jeechunhian.indoorpositioning.databrowsing$receiveJson$override.doInBackground(databrowsing.java:53)
 at com.utm.jeechunhian.indoorpositioning.databrowsing$receiveJson$override.access$dispatch(databrowsing.java)
 at com.utm.jeechunhian.indoorpositioning.databrowsing$receiveJson.doInBackground(databrowsing.java:0)

 at com.utm.jeechunhian.indoorpositioning.databrowsing$receiveJson.doInBackground(databrowsing.java:44)
 at android.os.AsyncTask$2.call(AsyncTask.java:288)
 at java.util.concurrent.FutureTask.run(FutureTask.java:237)
 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
 at java.lang.Thread.run(Thread.java:841)
 Caused by: libcore.io.ErrnoException: recvfrom failed: ECONNRESET (Connection reset by peer)
at libcore.io.Posix.recvfromBytes(Native Method)
at libcore.io.Posix.recvfrom(Posix.java:141)
at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)
at libcore.io.IoBridge.recvfrom(IoBridge.java:506)


text:
Q: How can I have a function with interface input parameter and interface of same type return value? I am trying to implement a function in my utility package for pagination of slices with any types of slice given. It is supposed to accept an slice of interfaces plus the page and pagesize and must return an interface of the same type.
However, when I try to use the function I get the error that my input does not match the
interface{} input

cannot use result (variable of type []entity.Something) as []interface{} value in argument to utility.PaginateSlice compilerIncompatibleAssign

Here is my function:
// PaginateList, paginates a slice based upon its page and pageSize.
func PaginateSlice(x []interface{}, page, pageSize int) []interface{} {
    var maxSize int = len(x)

    start := (page - 1) * pageSize
    end := start + pageSize - 1

    if start > maxSize || page < 1 || pageSize < 1 {
        start = 0
        end = 0
    } else if end > maxSize {
        end = maxSize
    }

    return x[start:end]
}

and here is an example of me trying to use it leading to failure:
var result []entity.Something

tmps := utility.PaginateSlice(dataOfSomethingType, pagination.Page, pagination.PageSize)
for _, tmp := range tmps {
    if value, ok := tmp.(entity.Something); ok {
    result = append(result, value)
}

A: Use type parameters:
func PaginateSlice[S ~[]T, T any](x S, page, pageSize int) S {
    // insert body of function from question here
}


text:
Q: Jquery Find, Sort and then Append only specific 'N' numbers child element I am finding child elements from the parent element and sorting them and then adding them on the parent element again:
$('#parentElement').find('.childElement').sort(function(a, b) {
    var contentA = parseInt($(a).attr('data-name'));
    var contentB = parseInt($(b).attr('data-name'));
    return (contentA < contentB) ? 1 : (contentA > contentB) ? -1 : 0;
}).appendTo('#parentElement');

But I want to append only the first 5 sorted child elements on the parent element. I don't want to append all child elements. Any solution?

A: To get the first 5 sorted elements from that collection you can use .slice(). Also note that the code can be made more succinct by using data() to retrieve the attributes (as this will negate the need to manually call parseInt()) and also by combining the original selectors:

$('#parentElement .childElement').remove().sort((a, b) => {
  var contentA = $(a).data('name');
  var contentB = $(b).data('name');
  return (contentA < contentB) ? 1 : (contentA > contentB) ? -1 : 0;
}).slice(0, 5).appendTo('#parentElement');

1

9

4

10

3

6

5

8

2

7


text:
Q: Applying Jensen's inequality to determine lower bound I want to solve this exercise:
Let $X \sim \mathrm{Geometric}(1/11)$. Use Jensen's inequality to determine a lower bound on $\mathrm{E}(X^4)$, by applying Jensen's inequality to $X^2$ with $f(x) = x^2$.
I'm not sure where to start. If it had said to apply the inequality to $X$, the answer simply would have been $(\mathrm{E}(X))^2$, correct? The issue for me is that is says to apply it to $X^2$.
Any hints?

A: Hint. As $f(x) = x^2$ is convex, for any random variable $Y$ we have
$$ \def\E{\mathbf E}\E[Y]^2 = f(\E[Y]) \le \E[f(Y)] = \E[Y^2]  $$
apply this for $Y := X^2$, as said, giving
$$ \E[X^2]^2 = \E[Y]^2 \le \E[Y^2] = \E[(X^2)^2] = \E[X^4]. $$


text:
Q: ¿cómo detecto los mensajes que no fueron enviados por número que no tiene WhatsApp o no existe? Tengo esta macro que envia mensajes masivos por whatsApp, todo funciona vastante bien, pero me gustari poder recopilar cuales fueron los clientes a los que no se pudo enviar el mensaje (porque no tiene WhatsApp hablitado o el numero no fue bien escrito, etc). Mi idea es poder detectar de alguan manera este mensaje que sale cuando no se puede enviar el mensaje (ver imagen), pero no se como hacer o que otra forma podria hacer lo que deseo.
Dim ruta As String
Sub WhatsApp()
Dim telefono As String
Dim mensaje As String
Set datos = ActiveSheet.ListObjects("Tabla_Datos")
num = -1
For Each fila In datos.ListRows
    telefono = "+51" & fila.Range(2).Value
    mensaje = fila.Range(3).Value & " " & fila.Range(1).Value & fila.Range(4).Value
    ActiveWorkbook.FollowHyperlink Address:=" whatsapp://send?phone=" & telefono
    Espera (2000)
    Call SendKeys(mensaje, True)
    Espera (800)
    Call SendKeys("{ESC}", True)
    Call SendKeys("~", True)
    Espera (1000)
    aux = num
    num = fila.Range(5).Value
    If aux = num Then
        Call SendKeys("^v")
        Call SendKeys("~")
        Espera (1000)
        Call SendKeys("~")
        Espera (2000)
    Else
        ruta = "C:\foto\" & num & ".jpeg"
        Call imagen
    End If
Next
MsgBox "Mensajes enviados", vbInformation, "Macro Elaborada por Jonnathan"
End Sub

Function Espera(ByVal tiempo As Double)
   Application.Wait (Now() + tiempo / 24 / 60 / 60 / 1000)
End Function

Sub imagen()
Dim imagen As Object

Set imagen = ActiveSheet.Pictures.Insert(ruta)
 With imagen
    .Copy
    .Delete
 End With
 Call SendKeys("^v")
 Call SendKeys("~")
 Espera (1000)
 Call SendKeys("~")
 Espera (2000)
End Sub


text:
Q: Variable for a directory but get error when calling it I'm trying to assign a variable to read a directory but I get this error:

"cannot use &home (value of type *[]fs.FileInfo) as string value in argument to viper.AddConfigPath"

I also tried the pointer inside viper.AddConfigPath(&home) but to no avail as well
Here is a snippet of the code:
// Find home directory
        home, err := ioutil.ReadDir("../db-dump")
        cobra.CheckErr(err)

        // Search config in home directory with name ".config" (without extension)
        viper.AddConfigPath(home)

I'm looking to transform the type *[]fs.FileInfo into a string so viper.AddConfigPath()can read it.
Update
I've tried now this way and I'm getting no error compiling, but I can't really test the code yet because of runtime errors:
home := "working directory"
        fileSystem := os.DirFS(home)

        fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error {
            if err != nil {
                log.Fatal(err)
            }
            fmt.Println(path)
            return nil
        })

        // Search config in home directory with name ".config" (without extension)
        viper.AddConfigPath(home)

A: Your mistake is that you have type mismatch: home is of type []fs.FileInfo (reference) while viper.AddConfigPath() expects a string (reference).

A: 1. You can read the error message as:
cannot use &home because value of type *[]fs.FileInfo is inserted instead of as string value ...
Meaning that viper.AddConfigPath requires a variable of type string and not a pointer to an array of fs.FileInfo.
2. A quick search here listed this another topic that may have the same issue and probably a tip to your question.

A: first create new config file (just for test code):
echo "key1: value" > AppName.yaml

and run the code
package main

import (
    "errors"
    "fmt"
    "log"

    "github.com/spf13/viper"
)

func main() {
    v := viper.GetViper()
    if err := readConfig(v, ""); err != nil {
        log.Fatal(err)
    }
    fmt.Println(v.AllKeys())

}

func readConfig(v *viper.Viper, configPath string) error {
    var err error

    if configPath != "" {
        v.SetConfigFile(configPath)
        if err := v.ReadInConfig(); err != nil {
            return fmt.Errorf("unable to read application config=%q : %w", configPath, err)
        }
        return nil
    }
    // look for .<AppName>.yaml (in the current directory)
    v.AddConfigPath(".")
    v.SetConfigName("AppName")
    if err = v.ReadInConfig(); err == nil {
        return nil
    } else if !errors.As(err, &viper.ConfigFileNotFoundError{}) {
        return fmt.Errorf("unable to parse config=%q: %w", v.ConfigFileUsed(), err)
    }

    return nil
}

out:
[key1]

You can load config by path:
    if err := readConfig(v, "app.yml"); err != nil {
        log.Fatal(err)
    }


text:
Q: Overriding the Back Button in PhoneGap Android I`m trying to accomplish more than one addEventListener, but something is wrong?
For example if we have 3 divs on page and first one is displayed on the beginning and other two hidden.

<a onClick="
document.addEventListener("backbutton", show_div1, false);
$('#d1').hide();
$('#d2').show();
"

 - initially hidden

 - initially hidden

It shows div 2, hides div 1 and sets listener for back button to show_div1(), and everything works OK. On back key pressed it alerts "I should show #div1", as it should (//$('#d1').show();  is comented)
show_div1(){
//$('#d1').show(); $('#d2').hide();
alert ('I should show #div1');
}

But now comes the problem

<a onClick="
document.removeEventListener("backbutton", show_div1, false);
document.addEventListener("backbutton", show_div2, false);
$('#d2').hide();
$('#d3').show();
"

It immediately fires "I should show #div2" even back button is not pressed! addEventListener like started main function show_div2() and not just set listener on back button to that function.
show_div2(){
//$('#d2').show(); $('#d3').hide();
alert ('I should show #div2');
}

What could be the possible reason for this happening?

A: try this,
on device ready add a listener for backbutton like this
var onBackButton = function(){show_div2();}; //the initial state
document.addEventListener("backbutton", onBackButton, false);

And

don't use onClick with phoneGap

use href, or ontouchend and be sure that your  is visible because you dont have anything inside(display block in your css file)

    //  will be better

in javascript
function onDivClick(var case)
{
    switch(case)
    case 1:
        $('#d1').hide();
        $('#d2').show();
        onBackButton = function(){show_div1();};
    break;
    case 2:
        $('#d2').hide();
        $('#d1').show();
        onBackButton = function(){show_div2();};
    break;
}


text:
Q: What is suitable version(s) for Dymamic web module with JavaSE 1.6 SDK, Tomcat 6 x64? We need maintain old system and research arround. I am using Windows 10 x64, Eclipse IDE 2022-12, JDK 1.6, Tomcat 6 and Spring 2.5.6 (include spring-jms-2.5.6.jar , spring-orm-2.5.6.java , spring-context-support-2.5.6.jar , spring-tx-2.5.6.jar , spring-aop-2.5.6.jar , spring-web-2.5.6.jar , spring-jdbc-2.5.6.jar , spring-beans-2.5.6.jar , spring-core-2.5.6.jar , spring-context-2.5.6.jar ), Ant build inside Eclipse IDE 2022-12.
. What is suitable version(s) for Dymamic web module with JavaSE 1.6 SDK, Tomcat 6 x64? Please give me official/reference links about these if you know.

A: Dyamic web version = Servlet specification version.

Full Java 6 and Java EE 5 support (JDBC 4.0, JTA 1.1, JavaMail 1.4,
JAX-WS 2.0)

and

Spring 2.5 is still compatible with JDK 1.4.2+ and J2EE 1.3+. Java 1.4
users

https://spring.io/blog/2007/11/19/spring-framework-2-5-released
https://docs.oracle.com/javaee/5/tutorial/doc/bnafd.html
https://www.ibm.com/docs/en/radfws/9.6.1?topic=project-dynamic-web-projects-applications
https://www.oracle.com/java/technologies/javaee/javaeetechnologies.html#javaee5

==> Choose 2.5


text:
Q: Flutter Material Icons rendering random icons on web So in my flutter app, the material icons show properly in native, but in web, all have a different icon. What should or can I do with it?

A: This seems to be a cache problem which can either be solved by running flutter pub cache repair or running flutter clean between every step of changing a channel and upgrading it.


text:
Q: Slice/split string Series at various positions I'm looking to split a string Series at different points depending on the length of certain substrings:
In [47]: df = pd.DataFrame(['group9class1', 'group10class2', 'group11class20'], columns=['group_class'])
In [48]: split_locations = df.group_class.str.rfind('class')
In [49]: split_locations
Out[49]:
0    6
1    7
2    7
dtype: int64
In [50]: df
Out[50]:
      group_class
0    group9class1
1   group10class2
2  group11class20

My output should look like:
      group_class    group    class
0    group9class1   group9   class1
1   group10class2  group10   class2
2  group11class20  group11  class20

I half-thought this might work:
In [56]: df.group_class.str[:split_locations]
Out[56]:
0   NaN
1   NaN
2   NaN

How can I slice my strings by the variable locations in split_locations?

A: This works, by using double [[]] you can access the index value of the current element so you can index into the split_locations series:
In [119]:
df[['group_class']].apply(lambda x: pd.Series([x.str[split_locations[x.name]:][0], x.str[:split_locations[x.name]][0]]), axis=1)
Out[119]:
         0        1
0   class1   group9
1   class2  group10
2  class20  group11

Or as @ajcr has suggested you can extract:
In [106]:

df['group_class'].str.extract(r'(?P<group>group[0-9]+)(?P<class>class[0-9]+)')
Out[106]:
     group    class
0   group9   class1
1  group10   class2
2  group11  class20

EDIT
Regex explanation:
the regex came from @ajcr (thanks!), this uses str.extract to extract groups, the groups become new columns.
So ?P<group> here identifies an id for a specific group to look for, if this is missing then an int will be returned for the column name.
so the rest should be self-explanatory: group[0-9] looks for the string group followed by the digits in range [0-9] which is what the [] indicate, this is equivalent to group\d where \d means digit.
So it could be re-written as:
df['group_class'].str.extract(r'(?P<group>group\d+)(?P<class>class\d+)')

A: Use a regular expression to split the string
 import re

 regex = re.compile("(class)")
 str="group1class23"
 # this will split the group and the class string by adding a space between them, and using a simple split on space.
 split_string = re.sub(regex, " \\1", str).split(" ")

This will return the array:
 ['group9', 'class23']

So to append two new columns to your DataFrame you can do:
new_cols = [re.sub(regex, " \\1", x).split(" ") for x in df.group_class]
df['group'], df['class'] = zip(*new_cols)

Which results in:
      group_class    group    class
0    group9class1   group9   class1
1   group10class2  group10   class2
2  group11class20  group11  class20

A: You can also use zip together with a list comprehension.
df['group'], df['class'] = zip(
    *[(string[:n], string[n:])
      for string, n in zip(df.group_class, split_locations)])

>>> df
      group_class    group    class
0    group9class1   group9   class1
1   group10class2  group10   class2
2  group11class20  group11  class20


text:
Q: css - shrink a parent div to fit one child's width and constrain the width of the other child Say, a parent div has two child divs, one containing text, the other containing an image of known (but variable) width & height.
I would like

*

*the width of the first child (image-containing) div to shrink to fit the width of the image (this i can do)

*the parent div (of unspecified width) to shrink to fit the width of the image-containing div (this is ok too)

*the text-containing second child div (also of unspecified width) to match the parent div's width irrespective of the quantity of text it contains (this is where it gets tricky).

I have a working version that does what I want until the quantity of text in the second child pushes the parent div's width wider than that of the image.
Here's my code:
css:
#container{border:1px solid #f00;display:inline-block;}
#child1{border:1px solid #0f0;}
#child2{border:1px solid #00f;}
img {border:1px solid #000;}

html:

Lorem ipsum dolor sit amet.

and here's a jsfiddle:
http://jsfiddle.net/BmbAS/1/
you can see where it's going wrong by clicking the 'lengthen/shorten text' link to increase the quantity of text
tldr - i want all the divs to be the same width which is equal to the width of the image
ps. modern browser solution only necessary

A: The answer provided by @Chris leads me to the following, great solution of my case, where I need to fit the container div only to the first child element (and leave the rest child elements to auto fit to the container's width):

div.container {
    width: fit-content;
    max-width: 100%;
    margin: 16px auto;
    display: table;
}

div.inner-primary {
    display: block;
}

div.inner-rest {
    margin-top: 8px;
    display: table-caption;
    caption-side: bottom;
}

This is the main element that drives the width of the container.

This is the first of the rest divs that fit automatically to the container...

This is the second element...

A: See this edited version of your jsFiddle.
Here's what's added to the CSS:
#container {
    display: table-cell;
}
#child1 {
    display: table-row;
    width: 1px;
}
#child2 {
    display: table-cell;
    width: 1px;
}

A: If you're willing to use a little javascript (jQuery in this example), you could set the width of the text div with the width of the image div.
Try adding $("#child2").css({'width': $('#child1').width()}); to the end of the JS in your fiddle, or check out the fork here: http://jsfiddle.net/VXEMu/


text:
Q: 1.5 IQR in finding outliers What motivates the choice of 1.5 IQRs for finding outliers in a set of data? The the lower quartile minus 1.5 times the IQR would give the lower fence, and the upper quartile plus 1.5 times the IQR gives the upper fence, with any data points falling outside either fence categorized as "outliers". But I don't know why 1.5 is used and not some other value.

A: Like pretty much any method for detecting/defining outliers, the fence at 1.5*IQR is a rule of thumb. It will be a reasonable strategy for detecting outliers in some circumstances, and not in others. You can get an idea for the logic behind it by considering its application to a normal distribution. If the data are normally distributed, the fence will be 2.7 standard deviations from the mean, so cases outside of it will be quite rare (0.4%). So the idea is that unless you have quite a large dataset, it's unlikely that you'll have many cases more than 1.5*IQR below the 1st quartile or above the 3rd quartile; when you see cases there, they may represent some weird deviation in your data (e.g. a coding error, equipment malfunction) and you probably want to exclude them from your analyses. Really, the main goal is to help you identify extreme points in your data, so that you can examine them to a) look for and correct errors and b) make decisions about how to handle cases that may have undue influence on your model estimation, as outliers often do.
If your data are NOT normally distributed, then that all changes --- if you have skewed data, for example, it's very common to detect a lot of "outliers" using standard techniques like the boxplot cutoffs you mention.
For example, check out a boxplot of the skewed data, drawn from an F distribution (Note that if you run this yourself you'll get slightly different results because of the random number generator, unless you use first set.seed() to coordinate with me):
set.seed(24601)
skewed_data <- rf(100, 1, 30)
boxplot(skewed_data)

It looks like there are several outliers there. But if you look at a histogram, you'll see that those outliers are just a continuation of the skewed tail of the data:
hist(skewed_data, breaks=30)

Should all of those cases be excluded from your analysis, but not the ones that happen to fall right inside the fence cutoff? Probably not. (In this situation, you may want to transform the data to correct the skew instead, and that will probably take care of the outliers for you.) There is no test that will work regardless of the data and the model to tell you for sure whether a case is a "significant" outlier. Instead, I recommend that you use outlier analyses to better understand your data and guide your decisions about your analysis plan.


text:
Q: How to get the return value of a method in a $.ajax (typ get) call? I have an ASP.NET MVC Application where I have a method, which returns a list of Objects:
public List<FileObject> GetAllFilesFromDirectory()
        {
            string filePath = @"C:\FilesToWatch";
            string[] fileEntries = Directory.GetFiles(filePath, "*.txt", SearchOption.TopDirectoryOnly);

            FileObject fo;

            List<FileObject> list = new List<FileObject>();

            foreach (var file in fileEntries)
            {
                FileInfo info = new FileInfo(file);

                fo = new FileObject
                {
                    FileName = info.Name,  //asdf.txt
                    FilePath = info.FullName //C:\FilesToWatch\asdf.txt
                };

                list.Add(fo);
            }
            return list;
        }

Now I want to return this list in javascript:
$.ajax({
            type: "GET",
            url: "Home/GetAllFilesFromDirectory",
            data: ???,
            success: function () {
                console.log('success');

            },
            error: function () {
                console.log('error');

            },
            complete: function (data) {
                console.log('complete');

            }
        });

I know, that I have to add the data: attribute, but I do not really know, what I should write after data: to return this list.

A: You do not need to pass data as your controllerAction accepting no arguments. Here is more clear result you can return from your controllerAction  as follow:
  public ActionResult GetAllFilesFromDirectory()
    {
        string filePath = @"C:\FilesToWatch";
        string[] fileEntries = Directory.GetFiles(filePath, "*.txt",
       SearchOption.TopDirectoryOnly);

        FileObject fo;

        List<FileObject> list = new List<FileObject>();

        foreach (var file in fileEntries)
        {
            FileInfo info = new FileInfo(file);

            fo = new FileObject
            {
                FileName = info.Name,  //asdf.txt
                FilePath = info.FullName //C:\FilesToWatch\asdf.txt
            };

            list.Add(fo);
        }
        return Json(new { filesList = list }, JsonRequestBehaviour.AllowGet);
    }

And then you can read the response in ajax as follow:
    $.ajax({
        type: "GET",
        url: "Home/GetAllFilesFromDirectory",
        success: function (resp) {

          if(resp.filesList)
          {
              $.each(function( index, element ) {
                     console.log(element.FileName ); // i.e log the file name
             });
          }

        },
        error: function () {
            console.log('error');

        },
        complete: function (data) {
            console.log('complete');

        }
    });


text:
Q: Disable Bubble notifications in Empathy using Ubuntu 13.04 How do I Disable Bubble notifications in Empathy using Ubuntu 13.04? There are a couple threads out there like this one:
how to disable Empathy notifications in ubuntu 13.04
but there isn't an org directory anywhere I can find. The notification options were removed in empathy's preferences, so that won't work. Any help would be appreciated.

A: When in this Answer says "org > gnome > empathy > notifications" it means the schema in dconf-editor.
Disable Empathy notifications With Dconf-Editor
Make sure you have dconf-tool installed.
1) Open a Terminal window and type:

*

*sudo apt-get install dconf-tools
2) Go to the dash home and search for the "dconf-editor" to open it

3) Navigate to the org.gnome.empathy.notifications and uncheck the key "notifications-enabled"

Disable Empathy notifications With gsettings command
If you prefer... you can do it with one command.
1) Open a Terminal window and just type:

*

*gsettings set org.gnome.Empathy.notifications notifications-enabled false
Hope it helps.


text:
Q: How to estimate that this task is in class NP? Here is my problem: Given numbers x1, ... xn. Numbers meet n files size and memory disk capacity D. We must understand, can we that files divided into 3 disks. The amount of file size recorded on any disc cannot exceed the disk capacity D. Let's estimate that this computational task is in class NP. What is extra information (certificate), that in this case is required for check algorithm?
Here is my idea, but I am really not sure:
Extra information: 3 sets in one set, that contains x1, ..., xn files. That sets could be recognized if string supplement by variables y1,y2,y3, which would be placed at the beginning of the thought set and contain a symbol, which is different from a number so that it doesn't interfere with the file size string.
Checker: Must be able to check if the total size of each set of files does not exceed the disk D capacity. The algorithm might be simple for this by introducing a variable. To variable would add the downloaded file size until either this amount exceeds the capacity of the D disk or until the new set start symbol is reached. At the moment when the capacity of D disk is exceeded, a negative response is issued, otherwise positive. The time consuming of this algorithm is O (n).
I don't know how to estimate that this algorithm is class NP. Because NP can be solved by a non-deterministic Turing machine in O(n^k) time.

A: Informally, NP means "given the answer to the problem, it is possible to check whether the answer is correct in polynomial time".
The checking algorithm in your post has complexity O(n), which is polynomial. Therefore, your problem is in NP.
Note: The set of NP-complete problems is a subset of NP. Your problem also belongs to the set of NP-complete problems. However, you don't need to prove that. In a context of computer science learning, attempting to do that would hint to the teacher that you don't understand your task.


text:
Q: testing PUT update is not working on RSPEC ( Ruby on Rails) So I'm testing one of my controller in RSPEC and I'm trying to test the whole update shenanigans. This is what i have in the RSPEC
 describe 'PUT update' do
         before :each do
           @user = Factory(:user,name: "Lawrence Smith")
         end

      context "valid attributes" do
        it "located the requested @user" do
          put :update, :id => @user, user: Factory.attributes_for(:user)
          assigns(:user).should eq(@user)
        end

        it "changes @user's attributes" do
          put :update, :id=> @user.id, user: Factory.attributes_for(:user, name: "Larry Smith")
          @user.reload
          @user.name.should eq("Larry Smith")

        end

      end

And this is what i have in the controller
def update
#update and save
@user = User.find(params[:id])
respond_to do |format|
if @user.update_attributes(params[:user])
  sign_in @user
  format.json{render :json => @user ,:status => :created, :location => @user }
else
  format.json { render :json => @user.errors, :status => :unprocessable_entity }
end
end

end
So apparently the the @user.reload doesn't really refresh the ActiveRecord, as my errors showed that the name has not been changed at all. Any idea what is wrong?

A: I don't know how you can pass object in get or post parameters. Anyways try like this
describe 'PUT update' do
         before :each do
           @user = Factory(:user,name: "Lawrence Smith")
         end
  context "valid attributes" do
    it "located the requested @user" do
      put :update, :id => @user, user: Factory.attributes_for(:user)
      assigns(:user).should eq(@user)
    end

    it "changes @user's attributes" do
      put :update, :id=> @user.id, :user_name => Factory.attributes_for(:user, name: "Larry Smith").name
      @user.reload
      @user.name.should eq("Larry Smith")

    end

  end

and this in controller
def update
#update and save
@user = User.find(params[:id])
respond_to do |format|
if @user.update_attributes(:name => params[:user_name])
  sign_in @user
  format.json{render :json => @user ,:status => :created, :location => @user }
else
  format.json { render :json => @user.errors, :status => :unprocessable_entity }
end
end

I think you are getting what I explained here.
Thanks


text:
Q: Delete ArrayList Entry from server side on pressing "Delete" Key in the JSP I'm currently using Spring MVC wherein I need to add and delete elements in my <form:select>:
<form:select path="listElements">
    <form:options items="${myList}" />
</form:select>

As of now, I'm populating elements in and deleting elements from the ArrayList, myList, from different pop-up pages and using AJAX to update the parent page.
I now want to change the deletion such that when I click on a populated option and press Del, it gets deleted (from the server side).
I've been stuck on this issue for a couple of days now; any help would be greatly appreciated!

A: 1 You have to catch the Delete event using JS.
2 After catching the event get selected index value of the drop down or multi select window.
3 send this value / values to the server which will delete these fields in the Data base / what ever source you are using.
4 in response send an json which will send the fresh records for the drop down.
5 Populate these values into the drop down.
For drop down population and deleting the contents please refer some other tutorials.


text:
Q: PySpark. Merge schemas by casting to string when reading parquet? I read data from parquet files, which has a Map type field as below:
>>> df = spark.read.parquet('path/to/partiton')
>>> df.collect()
Row(field={'a': 'SomeString', 'b': '1234'})

>>> df.printSchema()
field: map (containsNull = true)
 |-- key: string
 |-- value: string(valueContainsNull = true)

The problems is that in other partitions key a is None, causing key b to be read as long type:
>>> df = spark.read.parquet('path/to/otherPartiton')
>>> df.collect()
Row(field={'a': None, 'b': 1234})

>>> df.printSchema()
field: map (containsNull = true)
 |-- key: string
 |-- value: long(valueContainsNull = true)

This produces a clash schema when reading all partitions at the same time:
>>> df = spark.read.parquet('path/to/')
>>> df.collect()
SparkException: ... java.lang.UnsupportedOperationException: org.apache.parquet.column.values.dictionary.PlainValuesDictionary$PlainLongDictionary

I have try to specify the schema manually as below:
>>> struct = StructType([ StructField('field', MapType(StringType(), StringType())) ])
>>> df = spark.read.schema(struct).parquet('path/to/')
>>> df.collect()
fails with same error

Is there any way to fix this? Am I force to rewrite wrong partitions?

A: You can enforce your own schema on the dataframe.
Schema Definition
customschema = StructType([
    StructField("col_01", IntegerType()),
    StructField("col_02", StringType()),
    StructField("col_03", DateType())
])

In your application code you can this as below
df = spark.read.csv(filename, header=True, nullValue='NA', schema=customschema)
df.show()


text:
Q: filter table by value with react redux and firebase I am trying to filter a table in a react component by a value inside a document in firebase.
The important code looks like this. Claims is being parsed into another component for the table rows.
class Claims extends Component {
  componentDidMount() {
    this.props.getClaims();
  }
  render() {
    const { Claims, loading } = this.props.data;
    let recentClaimsMarkup = !loading ? (
      Claims.map(Claim => <ClaimsTable Claim={Claim} />)
    ) : (

Loading...

    );
    return (
      <Grid>
        <Paper className = {mergeClasses.root}>
          <Typography> {this.props.match.params.Project} Claim's</Typography>{" "}
        </Paper>
        <Paper className={mergeClasses.root}>

            <TableHead>
              <TableRow>
                <TableCell>Claim ID</TableCell>
                <TableCell align="right">Date received</TableCell>
                <TableCell align="right">Progress</TableCell>
                <TableCell>Edit Claim</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>{recentClaimsMarkup}</TableBody>

        </Paper>

I am wanting to filter it by the url Project, shown below
{this.props.match.params.Project}

This is due to the claims being tied to the project name.
If this was in Python I would just use a for loop or something similar, but a little bit confused how to filter what Claims are able to be mapped.
Basically want it to be, for claims with Project == {this.props.match.params.Project}: map claims.
Appreciate any help :)
Thanks

A: So basically filter also returns a new copy of array and you can read more here, but the problem is you can't create the jsx element, if you want to know more
you can read this question
so in your case you need to first filter and then you need to render the jsx element using map like shown below
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route } from "react-router-dom";

import "./styles.css";

const User = props => {
  const claimsUserHasAccess = props.data.claims.filter(
    claim => claim.project === props.match.params.access
  );
  return (
    <>
      {claimsUserHasAccess.map(claim => (

{claim.name}

      ))}
    </>
  );
};

const userData = {
  claims: [
    { project: "enabled", name: "job" },
    { project: "enabled", name: "nick" },
    { project: "disabled", name: "jef" }
  ]
};

function App() {
  return (

      <BrowserRouter>
        <Route
          path="/user/:access"
          render={props => <User data={userData} {...props} />}
        />
      </BrowserRouter>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

in the url you need to enter enabled or disabled to see the users. I hope this will give a better view of your problem.
working codesandbox


text:
Q: ErrorException Method Illuminate\Auth\SessionGuard::company does not exist I am having a problem using Laravel Framework. I am trying to build a simple@ifand@elsefunction.

ErrorException Method Illuminate\Auth\SessionGuard::company does not exist

Here is my code for my layout app.blade.php
@if(auth::user())
      {{auth::user()->name}}
    @else
      {{auth::company()->name}}
    @guest

i am here

    @endguest

A: {{auth::user()->name}} does work because user() will return the currently logged in auth model
{{auth::company()->name}} doesn't work because company() is not a default function for the auth facade.
You can use return view('example')->with('company' => Company::first()); in your controller to be able to use {{ $company->name }} in your code. This is assuming that the Company model exists and you just want the first one to display.


text:
Q: How to vertically align radio buttons in Struts2
Possible Duplicate:
How to make Struts radio tag create a vertical list of radio buttons

How to vertically align radio buttons in Struts2, as the generated radio buttons are aligned horizontally by default.
I am iterating it over a list.
<s:radio theme="simple" list="masterList" name="selectedDatabase" onclick="gotoAction(this)"/>

A: <s:iterator value="masterList">
  <s:radio theme="simple" name="selectedDatabase" list="#{id:name}"/><br>
</s:iterator>

where id will be the property of the list, you want to submit and name will be the label of the radio button.


text:
Q: Insert and Select at the same time in a stored procedure I have the following stored procedure:
create procedure Insert_Maintenance
(
@PlateNo nvarchar(10),
@MaintenanceType nvarchar(150),
@Name nvarchar(300),
@MaintenanceDate date,
@Qty int,
@IndivisualVal float,
@TotalVal float,
@Notes nvarchar(300)
)
as
insert into Maintenance(MaintenanceNo, PlateNo, MaintenanceType, AutoCenterNo,MaintenanceDate, Qty, IndivisualVal, TotalVal, Notes)
values ((1+(select Max(MaintenanceNo) from Maintenance)), @PlateNo, @MaintenanceType, (select AutoCenterNo from AutoCenter where Name = @Name), @MaintenanceDate, @Qty, @IndivisualVal, @TotalVal, @Notes)
Select Max(MaintenanceNo) AS MNo from Maintenance

A user will insert new maintenance operation via VB.NET interface. The information of the maintenance will be inserted into the database. The ID of the maintenance will increase by 1; as it is shown in the code. Since this is the case, after inserting the information I want to show a message that tells the user that information entered correctly and the ID of this operation is the value of MNo.
Basically, the problem is not with the VB.NET code because the message works fine but the problem is related to the select statement that shows the maintenance ID to the user.
The code in VB.NET
Dim ConnectString As String
        ConnectString = ""
        Dim connection As New SqlConnection(ConnectString)

        'Dim parm1 As SqlParameter
        'parm1 = New SqlParameter("@MaintenanceNo", SqlDbType.Int)
        'parm1.Value = MaintenanceNoTextBox.Text

        Dim parm2 As SqlParameter
        parm2 = New SqlParameter("@PlateNo", SqlDbType.NVarChar)
        parm2.Value = PlateNoComboBox.Text

        Dim parm3 As SqlParameter
        parm3 = New SqlParameter("@MaintenanceType", SqlDbType.NVarChar)
        parm3.Value = MaintenanceTypeTextBox.Text

        Dim parm4 As SqlParameter
        parm4 = New SqlParameter("@Name", SqlDbType.NVarChar)
        parm4.Value = NameComboBox.Text

        Dim parm5 As SqlParameter
        parm5 = New SqlParameter("@MaintenanceDate", SqlDbType.Date)
        parm5.Value = MaintenanceDateDateTimePicker.Value

        Dim parm6 As SqlParameter
        parm6 = New SqlParameter("@Qty", SqlDbType.Int)
        parm6.Value = QtyTextBox.Text

        Dim parm7 As SqlParameter
        parm7 = New SqlParameter("@IndivisualVal", SqlDbType.Float)
        parm7.Value = IndivisualValTextBox.Text

        Dim parm8 As SqlParameter
        parm8 = New SqlParameter("@TotalVal", SqlDbType.Float)
        parm8.Value = TotalValTextBox.Text

        Dim parm9 As SqlParameter
        parm9 = New SqlParameter("@Notes", SqlDbType.NVarChar)
        parm9.Value = NotesTextBox.Text

        Dim cmd As SqlCommand = New SqlCommand()
        cmd.Connection = connection
        cmd.CommandType = CommandType.StoredProcedure
        cmd.CommandText = "Insert_Maintenance"
        'cmd.Parameters.Add(parm1)
        cmd.Parameters.Add(parm2)
        cmd.Parameters.Add(parm3)
        cmd.Parameters.Add(parm4)
        cmd.Parameters.Add(parm5)
        cmd.Parameters.Add(parm6)
        cmd.Parameters.Add(parm7)
        cmd.Parameters.Add(parm8)
        cmd.Parameters.Add(parm9)

        Try
            connection.Open()
            cmd.ExecuteNonQuery()
            Dim dreader As SqlDataReader
            dreader = cmd.ExecuteReader()
            Dim a As String
            a = dreader("MNo").ToString
            MessageBox.Show("Information entered, ID is " + a)
            dreader.Close()
            'MaintenanceNoTextBox.Text = ""
            PlateNoComboBox.Text = ""
            MaintenanceTypeTextBox.Text = ""
            NameComboBox.Text = ""
            'MaintenanceDateDateTimePicker.Value = ""
            QtyTextBox.Text = ""
            IndivisualValTextBox.Text = ""
            TotalValTextBox.Text = ""
            NotesTextBox.Text = ""
        Catch ex As Exception
            MessageBox.Show("Something wrong  (" + ex.Message + ")")
        Finally
            connection.Close()
        End Try

Any suggestions guys !! Thanks

A: I think ID of Maintainance table should be auto-increment. For achieving that you can set Is Identity to Yes
In the end of insert if you want the ID than you can get by
Select SCOPE_IDENTITY()

If you want to increment ID manually then try this :
declare @newid int
Select  @newid = Max(ISNULL(MaintenanceNo, 0)) from Maintenance
set @newid = @newid + 1

then use @newid for insert and in the end Select @newid

A: To solve your problem you need to just change one line and remove a bunch of unnecessary code
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = connection cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Insert_Maintenance"
.... you need to build the parameters collection here .....
Try
     connection.Open()
     Dim result = cmd.ExecuteScalar() ' <- Instead of ExecuteNonQuery '
     if result IsNot Nothing Then
        Console.WriteLine("The Mno is:" & Convert.ToInt32(result)
     End If

ExecuteScalar returns the first column of the first row in your results. This should resolve the VB.NET side of your code. Of course, if you don't need to control the values inserted in the column MaintenanceNo then the next action to take is to set the Identity property to Yes in the field properties. In this way you could remove the last lines of your storedprocedure and forget to pass anything for the MaintenaceNo field
 INSERT INTO Maintenance(PlateNo, MaintenanceType, AutoCenterNo,MaintenanceDate, Qty,
                         IndivisualVal, TotalVal, Notes)
           VALUES (@PlateNo, @MaintenanceType,
                   (select AutoCenterNo from AutoCenter where Name = @Name),
                   @MaintenanceDate, @Qty, @IndivisualVal, @TotalVal, @Notes)

 SELECT SCOPE_IDENTITY()


text:
Q: What to name a field that includes Store and Version ID I am building a database that manages the definitions for a POS system (menu items, cashiers etc). It will include many stores and many versions.
So, typical table will look like this (MenuItems table)...
StoreID PK
VersionID PK
MenuItemID PK
MenuItemName

But I would like to merge the StoreID and VersionID into a single ID that represents the store and version (so, version 5 for store 101). So, I simplify the primary key on each table (because every table is going to need this)
And then have my tables looks like this...
SomethingID PK
MenuItemID PK
MenuItemName

Please help me name that StoreIDAndVersionID field. I have not idea what to call it.

A: You should not retain two (or more) different values, each from a distinct domain, within the same column, because that procedure would only introduce unnecessary complexity to the restriction, manipulation (insertion, modification, deletion and retrieval), general maintenance and interpretation of the data. See this relevant Stack Overflow post by @PerformanceDBA  for some related aspects.
I definitely would keep each contextually individual datum in its corresponding, dedicated, constrained and meaningful column. So, in your scenario, I would set (a) one specific column to hold the StoreId and (b) one separate column to hold the VersionId in all the pertinent tables, such as you have presented in your first sample. This approach avoids the manual extraction and validation of each of the individual values contained in a combined column, which is very important since said operations would undermine the system speed and, most likely, would also eventually compromise the data integrity.
In case you want to merge those columns to meet some particular information display requirements, you can concatenate their values on the fly by means of a SELECT statement or, perhaps, with the aid of your application program code, and then show them inside a single column to your data users. Some feasible names for this computed or derived column could be, for instance, StoreId and VersionId, StoreId & VersionId, StoreId – VersionId, StoreId / VersionId or VersionId for StoreId, since these denominations would express the —purely expository— blend of two distinct data points.


text:
Q: Swift - How to pause a playing audio by clicking the same button? So I have a list of audio files and when a cell is pressed it plays the audio. This works fine but I am not able to pause it by clicking the same cell again.
My code for the table view:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
    let a = indexPath.section;
    let b = indexPath.row;

    var path = NSBundle.mainBundle().pathForResource(musicArray[b], ofType: "mp3")
    var error:NSError?

    do{
        audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!))
    }
    catch
    {
        print("Something bad happened")
    }

    if (audioPlayer.playing)
    {
        audioPlayer.pause();
    }
    else
    {
        audioPlayer.play();
    }
}

musicArray has the titles of the audio files

A: You're creating a new AVAudioPlayer every time you select the cell. You need to keep a reference to the previous one and tell that audio player to pause.

A: You can create a singleton object.
import AVFoundation
class SomeAudioManager: NSObject, AVAudioPlayerDelegate
{
    class var sharedInstance: SomeAudioManager {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: SomeAudioManager? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = SomeAudioManager()
        }
        return Static.instance!
    }
    func audioView(songname: String,format: String) {
        let audioPlayer: AVAudioPlayer

        do {
            audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(songname, ofType:format)!), fileTypeHint: AVFileTypeMPEGLayer3)
            audioPlayer.delegate = self;
            audioPlayer.play()
        } catch {
            // error
        }
    }
}

It will be alive through the whole app.
How to implement AVAudioPlayer Inside Singleton Method?
You can just create a singleton of the player so that you will always know if it's playing or not.