text:
Q: How to change current page link colours? so I've tried a few different things out. But ultimately no success. I'm trying to change the colour of the "Home" link to stay a different colour than the rest when we are specifically on the homepage. So for example, say I'm on the homepage, I specifically want that colour to be orange for the home link, and then when I click on About link, about link changes to orange and the home goes to default white
Html:

Home

About

Order

Contact

Cart

Copyright Bakingwithwill

Bakingwithwill

Welcome!

Get a slice of the best bread in

                        Chatham-Kent!

CSS:
/*Base styles*/
body {
    font-family: 'Oswald', sans-serif;
}

h1 {
    font-family: 'Satisfy', cursive;
}

/*Home styles*/
header {
    width: 100%;
    height: 585px;
}

/*Side bar navigation menu*/
.navigation {
    height: 100%;
    width:160px;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: #3D3732;
    overflow-x: hidden;
    padding-top: 20px;
    opacity: 90%;
}

.navigation a {
    text-decoration: none;
}

.logo {
    border-radius: 50%;
    height: 70px;
    width: 70px;
    margin-top: 10px;
    margin-left: 45px;
}

#active-home:link, #active-home:visited {
    color:#E88F2A !important;
}

.navigation li, p {
    text-decoration: none;
    color: #FFFFFF;
    display: block;
    text-align: center;
}

.navigation .nav-items {
    padding-right: 30px;
    padding-top: 10px;
    text-align: center;
}

.navigation .social-icons {
    list-style-type: none;
    text-align: center;
    display: inline;
    font-size: 15px;
    padding: 5px;
    margin-top: 50px;
    color: #FFFFFF;
    margin-left: 15px;
    text-decoration: none;
}

.navigation li:hover {
    color: #E88F2A;
}

.navigation p {
    font-size: 10px;
    text-align: center;
    padding: 6px 8px 6px 16px;
}

.main {
    margin-left: 160px;
    padding: 0px 10px;
}

.footer-nav {
    margin-top: 200px;
}

/*Social media icons*/
.navigation i {
    text-decoration: none;
    color: #FFFFFF;
}

.navigation i:hover {
    color: #E88F2A;
}

/*Text overlaying the image*/
.baking-heading {
    color: #E88F2A;
    font-family: 'Satisfy', cursive;
    position: relative;
    margin-top: 40px;
    padding-left: 50px;
    font-size: 50px;
}

.welcome-heading, .intro-heading {
    font-family: 'Oswald', sans-serif;
    position: relative;
}

.welcome-heading, .baking-heading {
    transform: rotate(-13deg);
}

.welcome-heading {
    padding-left: 130px;
    font-size: 50px;
    color: #FFFFFF;
}

.intro-heading {
    padding-top: 200px;
    font-size: 50px;
    text-align: center;
    color: #FFFFFF;
}

.header-banner {
    /*Image styles*/
    margin-top: -40px;
    position: absolute;
    width: 100%;
    height: 585px;
}

A:
So for example, say I'm on the homepage, I specifically want that
colour to be orange for the home link, and then when I click on About
link, about link changes to orange and the home goes to default white

One CSS-only approach is to:

*

*add a class to the  element of each page

*add classes to each of your links (or to the list-items containing the links)

Home Page:

Home

About

Order

Contact

Cart

About Page:

Home

About

Order

Contact

Cart

Then you can change the color of the relevant link on each page:
.nav-items a {
  color: white;
}

.home-page .nav-items.home a,
.about-page .nav-items.about a {
  color: orange;
}

A: You need to add a class to the active link and #id is not recommended for styling. Also, the pseudo classes that you're using is blocking your desired outcome. Try changing :
#active-home:link,
#active-home:visited {
    color: #e88f2a !important;
}

to:
.active {
    color: #e88f2a !important;
}

Afterwards, place the .active class into your link code for each page. So for home it would be:

Home

and for your about page:

Home

About

and so on...


text:
Q: python: how to use a variable (time_convert)of a class (stopwatch)in other python3 script class stopwatch(object):
    def __init__(self):
        global time_convert,time_convert1,draw,start_time,padding,padding_2,top,top_2,x,x_2,font,font_2,image,width,height
        #self.width = width
       # self.height = height
        #self.image = image
        #self.draw = draw
        #self.padding = padding
        #self.padding_2 = padding_2
       # self.top = top
        #self.top_2 = top_2
       # self.font = font
       # self.font_2 = font_2
    def main():
        global time_convert,time_convert1,draw,start_time,padding,padding_2,top,top_2,x,x_2,font,font_2,image,width,height
        global flag
        flag = True #flag = True #flag x ciclo while
    #reset display
        disp.begin()
        disp.clear()
        disp.display()
    #preparazione display con immagine vuota
        width = disp.width
        height = disp.height
        image = Image.new('1', (width, height))
        draw = ImageDraw.Draw(image)
        draw.rectangle((0,0,width,height), outline=0, fill=0)
    #ridimensionamento caratteri padding= alza/abbassa carattere, x= destra/sinistra carattere
        padding = 0
        padding_2 = 3.5 # per carattere decimali più piccolo
        top = padding
        top_2 = padding_2 # per carattere decimali più piccolo
        x = 10
        x_2 = 75 # per carattere decimali più piccolo

        font = ImageFont.truetype('/home/albe/Documents/Progetti/schiuma150/Calculator.ttf',30)
        font_2 =ImageFont.truetype('/home/albe/Documents/Progetti/schiuma150/Calculator.ttf',20)
        #print("Press button red to start and green to stop")
        #GPIO.wait_for_edge(23,GPIO.FALLING)
        #print("crono iniziato")
    #def run():
     #   global time_convert,time_convert1,draw,start_time,padding,padding_2,top,top_2,x,x_2,font,font_2,image,width,height
      #  flag = True
        start_time = time.time()
        while (flag):
            #global time_convert,time_convert1,draw,start_time,padding,padding_2,top,top_2,x,x_2,font,font_2,image,width,height
            #global flag
            current_time = time.time()
            timer = current_time - start_time
            sec =  int (timer)
            decs = math.modf(timer)
            decs1 = int (decs[0]*60) #parte decimale
            sec1 = int(sec % 60)
            mins = int(sec // 60)
        #hour = int(mins // 60)
        #time_convert ="{:02n}:{:02n}:{:02n}:".format(hour,mins,sec1)#creazione indice x formattazione
            time_convert ="{:02n}':{:02n}'':".format(mins,sec1)#creazione indice x formattazione
            time_convert1 ="{}".format(decs1) # per carattere decimali più piccolo
            return time_convert
            return main.time_convert1
            draw.text((x, top),str(time_convert),font=font,fill=255), draw.text((x_2, top_2),str(time_convert1),font=font_2,fill=255)
            disp.image(image)
            disp.display()
            draw = ImageDraw.Draw(image)
            draw.rectangle((0,0,width,height), outline=0, fill=0)
            #print("crono run")
            #x = 0
            #cam = os.popen("./vcmipidemo-pi3 -i 1 -s 2180250 -g 0x88 -o && mv img00000.pgm /home/albe/Documents/Progetti/schiuma150/test_images/all_img/img"+str(x)+".pgm")
            #time.sleep(1)
            #img = Image.open("/home/albe/Documents/Progetti/schiuma150/test_images/all_img/img"+str(x)+".pgm")
            #x +=1
            #draw = ImageDraw.Draw(img)
            #font = ImageFont.truetype("Calculator.ttf", 25)
            #draw.text((500, 350), text= str('Timer: ' + time_convert + time_convert1) ,fill=255,font=font)
            #img.save('/home/albe/Documents/Progetti/schiuma150/test_images/results/img'+str(x)+'stamp.pgm')
           # print("image saved")
        else:
            exit()
    if __name__ == '__main__': main()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using multiple bootstrap buttongroups in one page Let's say I would like to have 2 different button groups on my page.

    <button type="button" name="fruits" class="btn btn-default">apple</button>
    <button type="button" name="fruits" class="btn btn-default">cherry</button>
    <button type="button" name="fruits" class="btn btn-default">melon</button>

    <button type="button" name="vegetables" class="btn btn-default">cucumber</button>
    <button type="button" name="vegetables" class="btn btn-default">aubergine</button>
    <button type="button" name="vegetables" class="btn btn-default">pepper</button>

Whenever I click on a button, the selected button on other group became deselected.
I have added, different "ids", "names", "classes" to each buttongroup and button. But unfortunately no success. How can I have multiple buttongroups on a page without affecting eachother?
All the examples on official bootstrap page are even like that. When you click on o buttongroup, other buttongroup deselected. Bootstrap Button Group
Thanks for any idea.

A: Here is what you can do.

Checkbox / Radio
Add data-toggle="buttons" to a .btn-group containing checkbox or radio inputs to enable toggling in their respective styles.

$('input').on('change', function () {
  console.clear();
  console.log(this.value)
})
@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
body {
  margin: 12px 0 0 0;
}

          <input type="radio" name="options" value="left" autocomplete="off"> Left

          <input type="radio" name="options" value="middle" autocomplete="off"> Middle

          <input type="radio" name="options" value="right" autocomplete="off"> Right

          <input type="radio" name="options" value="left 2" autocomplete="off"> Left 2

          <input type="radio" name="options" value="middle 2" autocomplete="off"> Middle 2

          <input type="radio" name="options" value="right 2" autocomplete="off"> Right 2


text:
Q: Acts-as-taggable-on - Is there a method to delete a tag with ownership? For my rails app I need to be able to remove a current users owned tag with a controller action.
Per the documentation you can view tags with @item.tag_list but this won't show tags with owners.  For that you should use @item.all_tags_list.
To add tags you can do @item.tag_list.add("tag1") and to add a tag with an owner you can do @some_user.tag(@item, :with => "tag1", :on => :tags).
To remove a tag you can do @item.tag_list.remove("tag1"), but I can't find a way to remove a tag with an owner.

A: I ended up using these methods:
def stringify(tag_list)
    tag_list.inject('') { |memo, tag| memo += (tag + ',') }[0..-1]
end

def remove_owned_tag
    @some_item = Item.find(params[:id])
    owned_tag_list = @some_item.all_tag_list - @some_item.tag_list
    owned_tag_list -= [(params[:tag])]
    @tag_owner.tag(@some_item, :with => stringify(owned_tag_list), :on => :tags)
    @some_item.save
end

I found this buried in another answer but I can't find it now to credit the author.
EDIT: Here it is https://stackoverflow.com/a/33797298/4584963


text:
Q: how to change the grayscale of an image with javascript in the "current page"? This question is concerned about the usage of javascript to chnage the grayscale of the image in the "current link" in navigation.
In the following navigation bar, there are four squares with the corresponding colors. Their grayscale is supposed to change when hover, focus and active and also, the grayscale of the current page should change and I have tried to do it with the js graying function to show which page we are in. But the the java script code is not working and only the first page changes its grayscale by the js code

var current = document.getElementById('default');

function graying(el) {
  if (current != null) {
    current.className = "";
  }
  el.className = "graying";
  current = el;
}
#nav {
  width: 100px;
  list-style: none;
  margin: 100px auto;
}
#nav img:active,
#nav img:focus,
#nav img:hover {
  filter: grayscale(0%);
  -webkit-filter: grayscale(0%);
  filter: gray;
  -webkit-transition: all .5s ease;
}
#nav img.graying {
  filter: grayscale(100%);
  -webkit-filter: grayscale(100%);
  filter: gray;
  -webkit-transition: all .5s ease;
}

. Is it correct to use "onclick" in this case?
Any help is appreciated.

A: You can use this code

img {
  filter: gray; /* IE6-9 */
  filter: grayscale(1); /* Microsoft Edge and Firefox 35+ */
  -webkit-filter: grayscale(1); /* Google Chrome, Safari 6+ & Opera 15+ */
}

/* Disable grayscale on hover */
img:hover {
  filter: none;
  -webkit-filter: grayscale(0);
}


text:
Q: Solution of a simple optimization problem Let $\mathbf{U}_1$ and $\mathbf{U}_2$ be two arbitrary unitary matrices and $\mathbf{D}$ be a diagonal matrix. What is the solution of the following optimization problem?
\begin{align}
\min_{\mathbf{D}}\|\mathbf{U}_1\mathbf{D}\mathbf{U}_2-\mathbf{I}\|_F ,
\end{align}
where $\mathbf{I}$ is the identity matrix and $\|\cdot\|_F$ is the Frobenius norm.


text:
Q: How to merge two text files in Matlab and duplicate the resulting file? I need to generate a number of text (or dat) files to be fed into another software. I have two text files (aa.txt and bb.txt) and an equation that generates random numbers.
The produced text (or .dat) file is to be comprised of three parts:
1- The contents of aa.txt.
2- Randomly generated numbers.
3- the contents of bb.txt.
the files' contents are :
aa.txt -->
first file ,,, first line

First file ,,, second line

1234.1234

bb.txt -->
second file ,,, first line

second file ,,, second line

6789.6789

I wrote the following code, but it will only produce one file with the contents of the first source file (aa.txt).
Why do I end up with 1 file?
Why is the variable A not written in the generated file?
NOF =3;                     % start with a goal to produce 3 files (small scale)
for ii = 1:NOF
ffid= fopen ('aa.txt','r');    % open the first source file (aa.txt), the idntifier is ffid
df = fopen (['file' sprintf('%d',ii) '.txt'], 'a'); % open a new (destination) file the identifier is df
line=fgets (ffid);            % Read line from first source file

while ischar (line)
    fprintf ('%s\n',line);
    line =fgets (ffid);
    fprintf (df , line);    % write the newly-read line from first file to the destination file
end
fclose (ffid);               % closing the first source file

A=randn(2,2); % this is just a randonly generated value for checking purposes and will be replaced later with a many sets of equations
save (['file' sprintf('%d',ii) '.txt'],'A', '-append');

sfid=fopen ('bb.txt','r');      % open the second source file, the idntifier is sfid
line2=fgets (sfid);             % Read line from source file

while ischar (line2)
    fprintf ('%s\n',line2);
    line2 =fgets (sfid);
    fprintf (df , line2);
end
fclose (sfid);                  % closing the first source file
end
fclose (df);
fclose('all');

A: This should basically produce what you are looking for:
for ii = 1:3
    % Create the output file...
    fid_out = fopen(['file' num2str(ii) '.txt'],'w');

    % Read the whole content of the first file into the output file...
    fid_aa = fopen('aa.txt','r');

    while (~feof(fid_aa))
        fprintf(fid_out,'%s\n',fgetl(fid_aa));
    end

    fclose(fid_aa);

    % Generate the random matrix and write it to the output file...
    random = cellstr(num2str(randn(2)));

    for jj = 1:numel(random)
        fprintf(fid_out,'%s\n',random{jj});
    end

    % Read the whole content of the second file into the output file...
    fid_bb = fopen('bb.txt','r');

    while (~feof(fid_bb))
        fprintf(fid_out,'%s\n',fgetl(fid_bb));
    end

    fclose(fid_bb);

    % Finalize the output file...
    fclose(fid_out);
end

Given, for example, the file aa.txt with the following content:
A - Line 1
A - Line 2
A - Line 3

and the file bb.txt with the following content:
B - Line 1
B - Line 2
B - Line 3

the output files would present the structure below:
A - Line 1
A - Line 2
A - Line 3
0.18323     0.94922
-1.0298     0.30706
B - Line 1
B - Line 2
B - Line 3

For the sake of optimization, since I/O is very expensive, I suggest you to read the content of aa.txt and bb.txt only once outside the loop that produces the output files, and save their content into cell arrays. Here is how:
fid = fopen('file.txt','r');
data = cell(0);

while (~feof(fid))
    data{end+1} = fgetl(fid);
end

Inside the loop that produces the output files, you can then iterate the cell array contents in order to print them:
for jj = 1:numel(data)
    fprintf(fid_out,'%s\n',data{jj});
end


text:
Q: Move to another subscription: Cannot move resources because some site(s) are hosted by other resource group(s) but located in resource group 'XXX' I have resource group "MyResources", that contains 4 resources:

*

*AppService - myserver,

*AppServicePlan - MyServerWestEuFarm,

*ApplicationInsights - myserver-insights,

*StoregeAccount - myserverstorage
When I try to move them to another subscription, I get error message:

Cannot move resources because some site(s) are hosted by other resource group(s) but located in resource group 'MyResources'. The list of sites and corresponding hosting resource groups: myserver:vyvojari.sk'. This may be a result of prior move operations. Move the site(s) back to respective hosting resource groups and try again. (Code: BadRequest, Target: Microsoft.Web/serverFarms)

What does that mean? Especially myserver:vyvojari.sk is confusing.
"vyvojari.sk" is another resource group and it may be possible that I've created myserver appservice in that resource group in the past and moved. So what?
In the resource explorer for the myserver AppService I see:
{
  "id": "/subscriptions/xxxxxxxx-d9e0-4769-8440-8cd7968bf94d/resourceGroups/MyResources/providers/Microsoft.Web/sites/myserver",
  "name": "myserver",
  "type": "Microsoft.Web/sites",
  "kind": "app",
  "location": "West Europe",
  "properties": {
    "name": "myserver",
    "state": "Running",
    "hostNames": [
      "myserver.azurewebsites.net"
    ],
    "webSpace": "vyvojari.sk-WestEuropewebspace",
    "selfLink": "https://waws-prod-am2-071.api.azurewebsites.windows.net/subscriptions/xxxxxxxx-d9e0-4769-8440-8cd7968bf94d/webspaces/vyvojari.sk-WestEuropewebspace/site/myserver",
    "repositorySiteName": "myserver",

But what is webspace and selflink? How can I change it?

A: This may be too obvious but I think, they want you to move back the 'myserver' resource to the 'vyvojari.sk' resource group. Once that is done, do the subscription operation.
It is possible that although, myserver is in the current resource (you have said that you may have moved it here) is still 'hosted' in that vyvojari resource group despite being part of the current group. By this logic, looks like moving it back to vyvojari should allow you do your subscription related task.

A: You need to consider the following limitations when moving the App Services to another Resource Group/Subscription.
When working with App Service apps, you cannot move only an App Service plan. To move App Service apps, your options are:

*

*Move the App Service plan and all other App Service resources in that
resource group to a new resource group that does not already have App
Service resources. This requirement means you must move even the App
Service resources that are not associated with the App Service plan.

*Move the apps to a different resource group, but keep all App Service
plans in the original resource group.
The App Service plan does not need to reside in the same resource group as the app for the app to function correctly.
For more details about limitations, refer to this documentation. You will be able to move the resources only if all the requirements/conditions are met.

A: You should have moved the resources back to original resource group (as per the error, myResources), migrate to different subscription, and than re-segment them into respected resource groups, as needed.


text:
Q: Passing values to a PUT JSON Request in C# I am working with an API and trying to do a JSON PUT request within C#. This is the code I am using:
    public static bool SendAnSMSMessage()
    {
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://apiURL");
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = "PUT";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = **// Need to put data here to pass to the API.**

            streamWriter.Write(json);
        }
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var responseText = streamReader.ReadToEnd();
            //Now you have your response.
            //or false depending on information in the response
            return true;
        }
    }

The problem is I can't figure out how to pass the data to the API. So like in JavaScript I would do something like this to pass the data:
        type: 'PUT',
        data: { 'reg_FirstName': 'Bob',
                'reg_LastName': 'The Guy',
                'reg_Phone': '123-342-1211',
                'reg_Email': 'someemail@emai.com',
                'reg_Company': 'None',
                'reg_Address1': 'Some place Dr',
                'reg_Address2': '',
                'reg_City': 'Mars',
                'reg_State': 'GA',
                'reg_Zip': '12121',
                'reg_Country': 'United States'

How would I go about doing the same in C#? Thanks!

A: httpWebRequest.ContentType = "text/json";

should definitely be:
httpWebRequest.ContentType = "application/json";

Other than that I don't see anything wrong with your current code.
As far as the JSON generation part is concerned you could use a JSON serializer:
var serializer = new JavaScriptSerializer();

string json = serializer.Serialize(new
{
    reg_FirstName = "Bob",
    reg_LastName = "The Guy",
    ... and so on of course
});

In this example I have obviously used an anonymous object but you could perfectly fine define a model whose properties match and then pass an instance of this model to the Serialize method. You might also want to checkout the Json.NET library which is a third party JSON serializer which is lighter and faster than the built-in .NET.

But all being said, you might also have heard of the ASP.NET Web API as well as the upcoming .NET 4.5. If you did, you should be aware that there will be an API HTTP web client (HttpClient) which is specifically tailored for those needs. Using a WebRequest to consume a JSON enabled API will be considered as obsolete code in a couple of months. I am mentioning this because you could use the NuGet to use this new client right now and simplify the life of the poor soul (tasked to migrate your code to .NET X.X) that will look at your code a couple of years from now and probably wouldn't even know what a WebRequest is :-)

A: If you want to mimic the JavaScript behavior from a .NET C# Client you must also set a few additional configs on the Request object, apart from ContentType, here is a working example:
string serializedObject = Newtonsoft.Json.JsonConvert.SerializeObject(entity);
HttpWebRequest request = WebRequest.CreateHttp(storeUrl);
request.Method = "PUT";
request.AllowWriteStreamBuffering = false;
request.ContentType = "application/json";
request.Accept = "Accept=application/json";
request.SendChunked = false;
request.ContentLength = serializedObject.Length;
using (var writer = new StreamWriter(request.GetRequestStream()))
{
    writer.Write(serializedObject);
}
var response = request.GetResponse() as HttpWebResponse;

This way the full content will be sent along with the request, therefore the ASP.NET MVC WebAPI data binders can work their magic.
Needless to say you should be careful on the content size as it will be sent all at once, not streamed/chunk-ed.


text:
Q: Количество связанных записей в БД Имею sql запрос вида:
SELECT g.id, g.user_id, g.name, count(ud.device_id) as c
FROM public.groups g inner join public.user_devices ud on g.id = ud.group_id
group by g.id
having g.id in (1, 2)

Запрос берет группы указанные группы и выводит нужный поля из таблицы и количество связанных с это группой записей в другой таблице.
Если связанные записи есть, то запрос выводит строку с группой и выводит количество связанных данных, но если данных нет совсем запрос вообще не выводит данных о группе.
Можно ли сделать запрос, чтобы он не не выводит группу без связей, а вместо этого писал 0?


text:
Q: Ruby on rails server app + IOS iphone client? What is the best way to have a regular ruby on rails app be delivered true an IOS iphone app?
The Idea is to build, for fun and education schoolproject, an simple Iphone app that connects to the ruby on rails app for its data. Seen some articles outdated, would like to ask some advise on this server - client model for ruby and an ios app.

*

*How to move data from ruby app to IOS app xml ?

*How to interact from IOS app back with the Ruby on Rails Application?

*Are there opensource example apps or recent updated resources you would recommend on this topic ( gems, opensource projects, tutorials, documentations )

Also what would be good websites to checkout when doing ruby on rails and Iphone apps?
Would love to hear some feedback, I already investigated and have rough idea on above concepts but as said on older resources. Some first hand experience from you experts would be higly appreciated thx!

A: The general setup for a Rails backend like this could be:
Authentication: use a basic authentication sceme to authenticate to the rails backend. I would use Devise and CanCan for this, they are easy to set up and work great. If you do not want people to log in but want authentication nonetheless, you could use a token.
Push Notifications : use the APN Gem
GET data: use the GET controllers of your Rails backend, you can either specifically ask for json or just return json as default /articles/:id.json
def show
  begin
    @article = Article.find(params[:id])
  rescue Exception => e
    render :text => "unknown article id", :status => 404
  else
    render json: @article
  end
end

If you would want a custom JSON returned. You can override it in the model:
#overide default json output
def as_json(options)
  # this ignores the user's options
  super(:only => [:id , :type, :title, :content])
end

CREATE data: use the Create controller of you Rails backend, you can just submit like you would a form, so a POST with fields like article[:title]=value. If you like you could return a plain text or json if the create was succesfull.
UPDATE data: use the Update controller of your rails backend. You use a PUT here instead of a POST.

A: In addition to the given answer: we have very good experiences with RABL: https://github.com/nesquena/rabl
We are generating plist-files to send the data to iOS-Devices.


text:
Q: How to show that there are no decimal representations of $1$ other than $1.000\dots$ and $0.999\dots$? I know that $1.000\dots$ and $0.999\dots$ are two different decimal representations of $1$, but how can I prove that they are unique?
I mean, there is no other decimal representation $a_n\dots a_0. a_{-1}a_{-2}\dots$ of $1$, different from $1.000\dots$ and $0.999\dots$

A: There can be no other decimal representation of $1$.
Let $$p.s_1s_2...$$ be a decimal representation of $1$ where $p$ is the integer prefix and $s_1s_2...$ is the sequence of digits after the decimal place.
If $p\gt 1$ then $p.s_1s_2...\ge p\gt 1$ so $p\le 1$.
If $p=1$ then $1.s_1s_2...\text{ }-\text{ } 1.00....=.s_1s_2...=0$ so $s_1s_2...=0$ which only happens when all of the digits are zero.
If $p=0$ then consider $0.99...-0.s_1s_2...$
Since no digit can be greater than $9$ we can do this subtraction from left to right because no borrowing is required. If $s_1s_2...\ne 99...$ then there will be a first position $i$ such that $s_i\ne 9$. In that case $0.99... - 0.s_1s_2...\ge (9-s_i)\times 10^{-i}\ne 0$
Since the difference is not zero $p.s_1s_2...$ cannot represent $1$. But this is a representation of $1$ so $s_1s_2...$ must equal $99...$


text:
Q: Nginx serving off the wrong root I have 2 sites-enabled, with server_name as follows:
server_name www.mysite.com mysite.com

and
server_name dev.mysite.com

Problem: When I access the website via its IP address, by looking at the access/error logs, it appears that nginx is serving off the root of dev.mysite.com.
How does nginx decide which to serve? Can we force it to serve off the root of www.mysite.com when the site is visited using its ip address?
conf
server {
    listen   80;
    server_name www.mysite.com mysite.com;
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
    root /var/www/mysite/public;

    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$args ;
    }
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_read_timeout 300;
    }

}

A: Briefly: you haven't told Nginx which server {...} to choose from - so it chose the first one.
Nginx passes requests to the default server. To do this, it matches the Host header against the server_name. If an IP address is used, the Host header will contain the IP address (which means it can be used to match against the server_name).
In the case where no server_name matches the Host header, nginx will choose the server in the following way:

*

*The server explicitly set as default.

*

*This is done (in the case of port 80) with listen 80 default_server

*If there is no default_server, the first server listed in the configuration is used.

*

*It is important to note that, when using wildcards, the order of file inclusion in nginx is indeterminate

To quote from the Nginx wiki:

If the directive has the default_server parameter, then the enclosing
  server {...} block will be the default server for the address:port
  pair. This is useful for name-based virtual hosting where you wish to
  specify the default server block for hostnames that do not match any
  server_name directives. If there are no directives with the
  default_server parameter, then the default server will be the first
  server block in which the address:port pair appears. The
  default_server parameter appeared in version 0.8.21 thus deprecating
  the parameter default.

Recommended reading:

*

*Nginx Documentation: Server Names

*Nginx Documentation: How Nginx Processes a Request

A: root can also be defined under http scope before server. You can set your default root there.
html {
    root /default/root

    server {
        root /site/root
    }
}

A: My case was not an IP address issue, but this post is the first that shows up when searching nginx serving the wrong root. My nginx was configured with 3 different domain names with 3 different server blocks each with a different root. 1 of the domain names was serving from the wrong root.
In my case I discovered that one of my server blocks contained these 2 lines:
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot

While I had 2 other server blocks that contained only:
listen 443 ssl; # managed by Certbot

Each server block had a different server_name and different root, but 2 of them ended up showing web pages from the same root.
It all worked correctly after removing the following line from the first case:
listen [::]:443 ssl ipv6only=on; # managed by Certbot

I assume this line showed up because of a copy paste error on my part. But I don't really recall where it came from.


text:
Q: What data type is returned by the following python code? In the following python code what type is returned by the function bruteforce_list?
import paramiko, sys, os, socket, threading, time
import itertools,string,crypt

PASS_SIZE = 5

def bruteforce_list(charset, maxlength):
    return (''.join(candidate)
        for candidate in itertools.chain.from_iterable(itertools.product(charset, repeat=i)
        for i in range(1, maxlength + 1)))

letters_list = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQSTUVWXYZ1234567890!@#$&()'

for i in bruteforce_list(letters_list, PASS_SIZE):
     print i

I have never seen for loops used the way they are after the join(candidate) in this way.  I am very new to python and an overall explanation would be appreciated.

A: In general in python, you can show the type of a variable using type() function.
so try doing something like this in you loop print type(i), that should give you a brief idea what is i.

A: As @Mad Physicist stated it returns a generator expression.
The syntax to create generator expressions is the same as that for list comprehensions, except that list comprehensions use square brackets.
Generator expressions take the general form:
(expression for variable in iterable)
You can optionally include conditions:
(expression for variable in iterable if conditions)
Finally, you can have multiple for clauses:
(expression for variable_a in iterable_a for variable_b in iterable_b)
The generator expression does not materialize every element at once; instead, you can iterate over the generator to get an element at a time.  This can be effective when you want to avoid holding large collections in memory.


text:
Q: Problems Installing and working with "pgmpy" I am trying to use pgmpy and have used:
! pip install pgmpy --user --upgrade pip

I then get the error message
"TypeError: 'module' object is not callable".

I then run the command:
from pgmpy.factors import TabularCPD

and get a further error message:
"No module named 'torch'"

Is there a good way to start to work with conditional probability models using Jupyter notebooks?

A: You can try this, it worked for me:
conda install -c ankurankan pgmpy

A: Try this installation as pgpy requires pytorch to be installed
pip install pgmpy
pip install torch


text:
Q: Flipping a card in Javascript using API data Using the PokeAPI I am trying have cards display data, and then when you click on them they flip and display a different set of data.
Here is my JavaScript:
  const poke_container =
  document.getElementById('poke_container');
  const dex_id = 151;
  const colors = {
    grass: '#63BB5B',
    fire: '#FF9C54',
    water: '#4E90D5',
    electric: '#F3D23B',
    ice: '#74CEC0',
    poison: '#AB6AC8',
    ground: '#D97746',
    rock: '#C7B78B',
    bug: '#90C12C',
    dragon: '#0A6DC4',
    normal: '#f9199A1',
    flying: '#8FA8DD',
    fighting: '#D80A49',
    psychic: '#F97176',
    ghost: '#5269AC',
    dark: '#5A5366',
    steel: '#5A8EA1',
    fairy: '#EC8FE6',
  };
//Fetch card colors
  const main_types = Object.keys(colors);

//Get Pokemon from API
  const fetchPokemon = async () => {
    for (let i = 1; i<= dex_id; i++) {
      await getPokemon(i);
    }
  };

  const getPokemon = async id => {
    const url = `https://pokeapi.co/api/v2/pokemon/${id}`;
    const res = await fetch(url);
    const pokemon = await res.json();
    createPokemonCard(pokemon);

  };

  fetchPokemon();

//Variables for Pokemon Card data from API
  function createPokemonCard(pokemon) {
    const pokemonEl = document.createElement('div');
    const pokemonElBack = document.createElement('div');
    pokemonEl.classList.add('pokemon');
    const poke_types = pokemon.types.map(el => el.type.name);
    const type = pokemon.types[0].type.name;
    //const stats = pokemon.stats[0].stat.name;
    const ability = pokemon.abilities[0].ability.name;
    const name = pokemon.name[0].toUpperCase() + pokemon.name.slice(1);
    const card_color = colors[type];

    pokemonEl.style.backgroundColor = card_color;

    //Card Front data and HTML
    const pokeInnerHTML = `

      #${pokemon.id.toString().padStart(3, '0')}

${name}

      ${type.charAt(0).toUpperCase() + type.slice(1)}

    `;

    pokemonEl.innerHTML = pokeInnerHTML;

    poke_container.appendChild(pokemonEl);

// Back of the card data
  const pokeCardBack = `

        #${pokemon.id.toString().padStart(3, '0')}

${name}

        ${ability}

    `;

    pokemonElBack.innerHTML = pokeCardBack;

    //Flip card from front to back function
    const back = document.querySelectorAll('.pokemon');

    function flipCard() {
      this.classList.toggle('flipped');
    }
    back.forEach((card) => card.addEventListener("click", flipCard));

}});

Here's my CSS related to my Pokemon data.
.poke_container {
  display: flex;
  flex-wrap: wrap;
  align-items: space-between;
  justify-content: center;
  margin: 0 auto;
  max-width: 1200px;
}

.pokemon {
  background-color: #eee;
  border-radius: 20px;
  box-shadow: 0 3px 15px rgba(100, 100, 100, 0.5);
  margin: 10px;
  padding: 20px;
  text-align: center;
  transition: transform .3s;
      &:hover {
    transform: scale(1.2);
  }
}

.pokemon .img-container {
  background-color: rgba(255, 255, 255, 0.6);
  border-radius: 50%;
  width: 120px;
  height: 120px;
  text-align: center;
}

.pokemon .img-container img {
  margin-top: 20px;
  max-width: 90%;
}

.pokemon .info {
  margin-top: 20px;
}

.pokemon .number {
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  font-size: 0.8em;
  padding: 5px 10px;
  font-family: 'Josefin Sans', sans-serif;
}

.pokemon .name {
  margin: 15px 0 7px;
  letter-spacing: 1px;
  font-family: 'Cabin', sans-serif;
}

.pokemon .type {
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  font-size: 0.8em;
  padding: 5px 10px;
  font-family: 'Josefin Sans', sans-serif;
}

.pokemon.flipped {
  transform: rotateY(180deg);
}

Currently when I click on the card, it just flips and reverses the text instead of displaying the pokeCardBack data. Also it for some reason only works for every other card.
How can I get the flipCard function to show the InnerHTML data from the pokeCardBack variable?


text:
Q: Status of Airflow task within the dag I need the status of the task like if it is running or upforretry or failed within the same dag. So i tried to get it using the below code, though i got no output...
Auto = PythonOperator(
    task_id='test_sleep',
    python_callable=execute_on_emr,
    op_kwargs={'cmd':'python /home/hadoop/test/testsleep.py'},
    dag=dag)

logger.info(Auto)

The intention is to kill certain running tasks once a particular task on airflow completes.
Question is how do i get the state of a task like is it in the running state or failed or success

A: Take a look at the code responsible for the command line interface operation suggested by Priyank.
https://github.com/apache/incubator-airflow/blob/2318cea74d4f71fba353eaca9bb3c4fd3cdb06c0/airflow/bin/cli.py#L581
def task_state(args):
    dag = get_dag(args)
    task = dag.get_task(task_id=args.task_id)
    ti = TaskInstance(task, args.execution_date)
    print(ti.current_state())

Hence, it seem you should easily be able to accomplish this within your DAG codebase using similar code.
Alternatively you could execute these CLI operations from within your code using python's subprocess library.

A: Okay, I think I know what you're doing and I don't really agree with it, but I'll start with an answer.
A straightforward, but hackish, way would be to query the task_instance table. I'm in postgres, but the structure should be the same. Start by grabbing the task_ids and state of the task you're interested in with a db call.
SELECT task_id, state
FROM task_instance
WHERE dag_id = '<dag_id_attrib>'
  AND execution_date = '<execution_date_attrib>'
  AND task_id = '<task_to_check>'

That should give you the state (and name, for reference) of the task you're trying to monitor. State is stored as a simple lowercase string.

A: I am doing something similar. I need to check for one task if the previous 10 runs of another task were successful.
taky2 sent me on the right path. It is actually fairly easy:
from airflow.models import TaskInstance
ti = TaskInstance(*your_task*, execution_date)
state = ti.current_state()

As I want to check that within the dag, it is not neccessary to specify the dag.
I simply created a function to loop through the past n_days and check the status.
def check_status(**kwargs):
    last_n_days = 10
    for n in range(0,last_n_days):
        date = kwargs['execution_date']- timedelta(n)
        ti = TaskInstance(*my_task*, date) #my_task is the task you defined within the DAG rather than the task_id (as in the example below: check_success_task rather than 'check_success_days_before')
        state = ti.current_state()
        if state != 'success':
            raise ValueError('Not all previous tasks successfully completed.')

When you call the function make sure to set provide_context.
check_success_task = PythonOperator(
    task_id='check_success_days_before',
    python_callable= check_status,
    provide_context=True,
    dag=dag
)

UPDATE:
When you want to call a task from another dag, you need to call it like this:
from airflow import configuration as conf
from airflow.models import DagBag, TaskInstance

dag_folder = conf.get('core','DAGS_FOLDER')
dagbag = DagBag(dag_folder)
check_dag = dagbag.dags[*my_dag_id*]
my_task = check_dag.get_task(*my_task_id*)
ti = TaskInstance(my_task, date)

Apparently there is also an api-call by now doing the same thing:
from airflow.api.common.experimental.get_task_instance import get_task_instance
ti = get_task_instance(*my_dag_id*, *my_task_id*, date)

A: You can use the command line Interface for this:
 airflow task_state [-h] [-sd SUBDIR] dag_id task_id execution_date

For more on this you can refer official airflow documentation:
http://airflow.incubator.apache.org/cli.html


text:
Q: Correctly allocate stack for clone a thread So I want to create a thread without CLONE_FILES flag. I try to call clone directly, but has some strange problem. I think it is related to incorrect memory allocation.
#ifndef _GNU_SOURCE
    #define _GNU_SOURCE
#endif
#include <iostream>
#include <sys/mman.h>
#include <pthread.h>
#include <unistd.h>

const int clone_flags = (CLONE_VM | CLONE_FS | CLONE_SYSVSEM
            | CLONE_SIGHAND | CLONE_THREAD
            | CLONE_SETTLS | CLONE_PARENT_SETTID
            | CLONE_CHILD_CLEARTID
            | 0);

static int cloneThread(void* arg)
{
    long arg2 = (long)arg + (long)arg;
    long* arg2_ptr = &arg2;
    return 0;
}

int main(int argc, char** argv)
{
    const int STACK_SIZE = 0x800000;
    void* stackaddr = malloc(STACK_SIZE);
    void* stacktop  = (char*)stackaddr + STACK_SIZE; // assuming stack going downwards

    clone(cloneThread, stacktop, clone_flags, (void*)1);
    sleep(1); // wait for cloneThread running before exit
}

As you can see here, I am using malloc for stack allocation. lldb shows the program crashes at the beginning of cloneThread. But if I remove long* arg2_ptr = &arg2;, the program exit successfully.
I also read source code of pthread_create.c, allocatestack.c. With strace, I replaced malloc with the following
void* stackaddr = mmap(NULL, STACK_SIZE, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_STACK, -1, 0);
mprotect(stackaddr, STACK_SIZE, PROT_READ|PROT_WRITE);

But it has the same behavior as using malloc. So how should I use clone?
OS: Ubuntu 18.04 LTS, g++ 7.3.0

A: When you supply the CLONE_SETTLS, CLONE_PARENT_SETTID and CLONE_CHILD_CLEARTID flags you must provide the newtls, ptid and ctid arguments to clone() respectively.
If all you want is a normal thread with a separate FD table though, just use pthread_create() and call unshare(CLONE_FILES) as the first operation in the new thread.


text:
Q: is there any Framework to implement a spectrum analyzer? I want to Implement the Music Tracker as like below image.

I want to implement it in to the iphone. So is there any Music API or any Sound Library available to implement it in to iPhone ??
Please help me regarding this.

A: This isn't a 'tracker', but is a visual representation of the frequency domain for a given time period during playback.
You'll need a library that can do Fast Fourier Transforms (FFT) such as this.


text:
Q: Picture of magnons/spin waves is misleading right? I am talking about this picture you can find in any textbook on solid state physics:

In the picture the upper level is a view from the side onto the spins whereas the lower level is a view from above.
If you have a system as a ferromagnet and the magnetisation is saturated, the energy required to flip one spin state (from up to down) is proportional to the thermal energy at the Curie temperature. Now many textbooks just say that a energetically more favourable excitation of your spin system is the one given in the picture, where you have a collective precession of the spins around the axis of magnetisation in your material.
It is often said that a magnon reduces the spin in the System by 1 (meaning effectively one spin is turned down from up to down). But in the given picture the spins are all still facing the up direction. Spin is theoretically handled by introducing $m_s$ as a quantum number reffering to the projection of the spin onto the z axis. This value can be $\pm1/2$ where the "+" stands for the orientation as can be seen in the picture (given the z axis points upwards). How is this represented in the picture?
The only explenation I came up with was:
Maybe it is just meant to be a lower energy excitation of the system (which this precession is) but does not imediately have to do anithing with flipping a spin. This however is contradicted by the wikipedia entry on Spin waves where it sais:
"The combined effect of the two operators (raising and lowering operator of spin) is therefore to propagate the rotated spin to a new position, which is a hint that the correct eigenstate is a spin wave, namely a superposition of states with one reduced spin. The exchange energy penalty associated with changing the orientation of one spin is reduced by spreading the disturbance over a long wavelength."
So I guess that in the picture above on spin should be flipped but quantum mechanics doesn't really tell you which one, so each one of them are flipped at the same time in a superposition of states (with normalisation) giving an overall lower energy to excite this as flipping one fixed spin. This of corse is an over simplification but please tell me where I go wrong.

A:
It is often said that a magnon reduces the spin in the System by 1 (meaning effectively one spin is turned down from up to down). But in the given picture the spins are all still facing the up direction.

There are exist different spin models: xy-model, Ising model, Heisenberg model, etc. Some of them come in classical and quantum varieties. Thus, how exactly spins move depends on the choice of the model. E.g., if we think of spins as classical magnetic moments coupled via their components perpendicular to the magnetic field, the excitations like the one shown in the OP are very likely. On the other hand, once we talk about spin-1, we imply quantum description, and showing perpendicular and longitudinal components simultaneously is meaningless (since they cannot be simultaneously measured.)

Picture of magnons/spin waves is misleading right?

On a more general level, most spin Hamiltonians do not have boson excitations as their solutions. These appear either as a result of approximations (see, e.g., Holstein-Primakoff transformation), usually implying that only few waves are present or, more formally, as poles in the Green's function (if applying QFT methods.)


text:
Q: [updated]Intergrating NextJS and Redux State Management this my updated version of intergrating redux and NextJS. Just to elobarate what I have done so far...
STEP 1. I've created a store.js file to set up my global store in reference to github's explanation from nextJS developers.
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { createWrapper, HYDRATE } from 'next-redux-wrapper';
import thunkMiddleware from 'redux-thunk';
import { customerListReducer } from './customerReducers';

const bindMiddleware = (middleware) => {
  if (process.env.NODE_ENV !== 'production') {
    const { composeWithDevTools } = require('redux-devtools-extension');
    return composeWithDevTools(applyMiddleware(...middleware));
  }
  return applyMiddleware(...middleware);
};

const combinedReducer = combineReducers({
  customerList: customerListReducer,
});

const reducer = (state, action) => {
  console.log('Just Displaying the Store', state);
  if (action.type === HYDRATE) {
    const nextState = {
      ...state, // use previous state
      ...action.payload, // apply delta from hydration
    };
    if (state.count) nextState.count = state.count; // preserve count value on client side navigation
    return nextState;
  } else {
    return combinedReducer(state, action);
  }
};

// create a makeStore function
const store = () =>
  createStore(
    reducer,
    bindMiddleware([thunkMiddleware])
  );

// export an assembled wrapper
export const wrapper = createWrapper(store);

STEP 2: Imported the wrapper above in my _app file to make the wrapper available across all pages in my application
import Nav from '../components/Nav';
import {wrapper} from '../reducers/store';

function MyApp({ Component, pageProps }) {
  return (
    <>

      <Component {...pageProps} />
    </>
  );
}
export default wrapper.withRedux(MyApp);

STEP 3: CONFIGURATIONS
A) My Action that calls external API
import axios from 'axios';
import {
  CUSTOMER_LIST_REQUEST,
  CUSTOMER_LIST_SUCCESS,
  CUSTOMER_LIST_FAIL,
} from '../constants/customerConstants';

export const listCustomers = () => async (dispatch) => {
  try {
    dispatch({
      type: CUSTOMER_LIST_REQUEST,
    });

    const { data } = await axios.get(
      'https://byronochara.tech/gassystem/api/v1/customers'
    );
    const result = data.results;

    dispatch({
      type: CUSTOMER_LIST_SUCCESS,
      payload: result,
    });
  } catch (error) {
    dispatch({
      type: CUSTOMER_LIST_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

B)My Action Reducer
import {
  CUSTOMER_LIST_REQUEST,
  CUSTOMER_LIST_SUCCESS,
  CUSTOMER_LIST_FAIL,
} from '../constants/customerConstants';
import { HYDRATE } from 'next-redux-wrapper';

export const customerListReducer = (state = { customers: [] }, action) => {
  switch (action.type) {
    case HYDRATE:
      return { loading: true, customers: [] };
    case CUSTOMER_LIST_REQUEST:
      return { loading: true, customers: [] };
    case CUSTOMER_LIST_SUCCESS:
      return {
        loading: false,
        customers: action.payload,
      };
    case CUSTOMER_LIST_FAIL:
      return { loading: false, error: action.payload };
    default:
      return state;
  }
};

C)The finally bringing it all together in my index.js page to display the results:
import React, { useEffect } from 'react';
import Head from 'next/head';
import { useSelector} from 'react-redux';
import { listCustomers } from './../actions/customerActions';
import { wrapper } from '../reducers/store';
import styles from '../styles/Home.module.css';
const Home = () => {

  //Select the loaded customers' list from central state
  const customerList = useSelector((state) => {
    console.log(state);
    return state.customerList;
  });
  const { loading, error, customers } = customerList;
//displaying the customers data from the external API
  console.log('Fetched Customers Data', customers);

  return (

        <title>Home | Next</title>

Welcome to Home Page

      {/* {loading &&
Loading...
} */}
      {/* {error &&
Error Occured...
} */}
      {/* {customers.map((customer) => (

{customer.customerName}

      ))} */}
      {/* <ArticleList customers={customers} /> */}

  );
};

// getStaticProp at build time
// getServerSideProp at every request slower
// getStaticPath to dynamically generate paths based on the data we are fetching

export const getStaticProps = wrapper.getServerSideProps(async ({ store }) => {
  // console.log('STORE', store);
  store.dispatch(listCustomers());
});

export default Home;

COMMENT ON THE PROBLEM I'M FACING FROM THE ABOVE CODE: once everything has been set up if you follow the code above, the code seems to run well the store is successfully created when I log the result on the console ``{ customerList: { loading: true, customers: [] } }. But then I guess this is the result from the HYDRATE action type since it will always be dispatch since am using getStaticProps``` that creates a new store instance in the server.
MAIN QUIZ: My challenge is how do I bypass the HYDRATED action and reconcile the server side state with the client side store and persist it and at least to finally be able to view the list from the external API. Thanks in advance. :)

A: I totally recommend you to use reduxjs/toolkit. It's very simple , less code, no wrappers, clean. And no matter your project on nextjs or created via CRA. Also you dont need to configure redux-thunk and redux-devtools cause they are enabled by default. Read documentation for more information ( how to persist state without any npm package and so on )
Here is a little example.
store.js
import { combineReducers, configureStore } from "@reduxjs/toolkit";
import userSlice from './user.slice.js';

//reducers
const rootReducer = combineReducers({
  user: userSlice
});

const store = configureStore({
  reducer: rootReducer,
});

export default store;

Wrap with Provider (in your case _app.js)
  <Provider store={store}>
     <Component {...pageProps} />
  </Provider>

user.slice.js ( action + reducer )
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

const initialState = {
  id: '',
  email: '',
  roles: []
};

// export async action
export const signIn = createAsyncThunk('user/signIn', async (data) => {
  try {
    const payload = await api.auth.signin(data).then((res) => res.data);
    // do some stuff if you want
    return payload ;
  } catch (err) {
    console.log(err.response);
  }
});

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    removeUser(state, payload) {
      //cant be an async method
      return initialState;
    },
    extraReducers: (builder) => {
     builder.addCase(signIn.fulfilled, (state, { payload }) => {
       // payload from the async method above (asyncThunk)
       return payload;
     });
   },
  },
});

// export actions
export const { removeUser } = userSlice.actions;
// export reducer
export default userSlice.reducer;

Thats it. Last step to call actions from any component e.g.
import { useDispatch, useSelector } from 'react-redux';
import { signIn, removeUser } from '../actions/userSlice';

  // in function component
  // call hooks
  const dispatch = useDispatch();
  // read the store
  const { user } = useSelector((state) => state);

  // dispatch any action , example below
  dispatch(signIn(userCredentials));
  // or
  dispatch(removeUser());

A: I has an Issue with setting Redux with NextJS and this is my final answer after some insight from mirik999 too.
A. my store.
import { configureStore } from '@reduxjs/toolkit';
//importing the slice file with sliced reducers
import customerListReducer from '../slices/customerSlice';

// const composedEnhancer = composeWithDevTools(applyMiddleware(thunkMiddleware));

const store = configureStore({
  reducer: {
    customerList: customerListReducer,
  },
});
export default store;

B. The store is provided in my app component
function MyApp({ Component, pageProps }) {
  return (
      <Provider store={store}>

        <Component {...pageProps} />
      </Provider>
  );
}
export default MyApp;

C. The Slice file that automatically creates action creators and the reducer
import { createSlice } from '@reduxjs/toolkit';

//creating and action that calls API from a REST API backend
export const customersFetchedList = createAsyncThunk(
  'customersList/customersListSuccess',
  async () => {
    try {

      const { data } = await axios.get(
        'https://example.com/api/your/endpoint'
      );
      const result = data.results;
      //the payload
      const payload = result;
      return payload;
    } catch (error) {
      console.log(error.response);
      const payload =
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message;
      return payload;
    }
  }
);

const initialState = {
  loading: true,
  customers: [],
  error: false,
};

const customerListSlice = createSlice({
  name: 'customersList',
  initialState,
  reducers: {
    //reducer functions we've provided
    customersRequest(state, action) {
      if (state.loading == true) {
        return state;
      }
    },
  },

  extraReducers: (builder) => {
    initialState,
      builder.addCase(customersFetchedList.fulfilled, (state, action) => {
        state.loading = false;
        state.customers = action.payload;
        state.error = false;
        return state;
      });
  },
});

export const {
  customersRequest,
  customersLoadingError,
} = customerListSlice.actions;

export default customerListSlice.reducer;

D. Then finally fired this action above in my component using the useEffect()
import React, { useEffect } from 'react';
import Head from 'next/head';

const Home = () => {
  //method to fire the action
  const dispatch = useDispatch();

  //Select the loaded customers' list from central state
  const customerList = useSelector((state) => state);
  // const { loading, error, customers } = customerList;

  useEffect(() => {
     dispatch(listCustomers());
  }, []);

  return (

        <title>Home | Next</title>

Welcome to Home Page

      {loading &&
Loading...
}
      {error &&
Error Occured...
}
      {customers.map((customer) => (

{customer.customerName}

      ))}

  );
};

Thanks so much for your contribution. :)


text:
Q: How to join two conditions in bash script? Note: Update Jun 28
I have an iptables script.sh (interpreted by bash) with the rules:
function run_ips(){
for ip in $(sed '/#.*/d' ips.txt); do
  if echo $ip | grep -q "-" >/dev/null; then
    iptables -A FORWARD -m mac --mac-source $mac -o eth0 -p tcp --dport 443 -m iprange --dst-range "$ip" -j ACCEPT
  else
    iptables -A FORWARD -m mac --mac-source $mac -o eth0 -p tcp --dport 443 -d $ip -j ACCEPT
  fi
done
}
for mac in $(awk -F";" '{print $2}' macs.txt); do
   iptables -t nat -A PREROUTING -i eth1 -m mac --mac-source $mac -p tcp --dport 80 -j REDIRECT --to-port 8080
   iptables -A INPUT -i eth1 -m mac --mac-source $mac -p tcp --dport 8080 -j ACCEPT
   run_ips
done

Where macs.txt contains macs addresses and ips.txt contains ips addresses or ranges separates with "-"

Error: Another app is currently holding the xtables lock. Perhaps you want to use the -w option?

(this is generated by function "run_ips")
How can I unify both parts?

A: I don't see a need for a function here. If you do need a function, it might be best to pass the variable as a parameter, rather than attempting to use it as a global variable. However, it seems pretty straight forward to just nest the loops:
for mac in $(awk -F";" '{print $2}' macs.txt); do
    iptables -t nat -A PREROUTING -i eth1 -m mac --mac-source $mac -p tcp --dport 80 -j REDIRECT --to-port 8080
    iptables -A INPUT -i eth1 -m mac --mac-source $mac -p tcp --dport 8080 -j ACCEPT
    for ip in $(sed '/#.*/d' ips.txt); do
      if echo $ip | grep -q "-" >/dev/null; then
        iptables -A FORWARD -m mac --mac-source $mac -o eth0 -p tcp --dport 443 -m iprange --dst-range "$ip" -j ACCEPT
      else
        iptables -A FORWARD -m mac --mac-source $mac -o eth0 -p tcp --dport 443 -d $ip -j ACCEPT
      fi
    done
done

As for the error message, it would seem that you have a process being run at the same time these rules are being processed. Perhaps you should just add -w to your iptables lines, as the error suggests. This option should causes iptables to wait for the xtables lock to release.


text:
Q: How do I overcome 'unicodeescape' in constructing HEX string to INT conversion in Python? The challenge is to take a hex value in string format "FF" and convert it to its decimal equivalent.
I know that using the string format "\xFF", this is as easy as ord("\xFF").
However, I would like to parse a string of hex without the \x tag, i.e. "01 02 03 04".
My approach has been to try to format the later string in the "\xFF" format, doing something like:
input = "01 02 03 04"
s = ""
s += "\x" + input[0:2]

However, any attempt to put the "\", "\x", or even "\x0" character into a string, I get the following error:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
  in position 0-1: truncated \xXX escape

Since strings are immutable, I cannot create a string with the full "\xFF" format and then change the values after the fact.  Does anyone have a tip to get past this?
Thanks in advance... I hope what I'm asking makes sense!

A: The int constructor takes an optional second argument giving its base, and will parse hex string representations if you tell it to use base 16:
input = "01 02 03 04"
s = input[0:2]
>>> int(s, 16)
1
>>> int('FF', 16)
255

A: you dont
my_input = "01 02 03 04"
s +=chr(int(my_input[0:2],16)) #results in "\x01" (note the 16 makes it hex chars)

as an aside dont use input as a variable name
what I think you actually want is
s = "".join(chr(int(c,16)) for c in "01 02 03 04".split())
#s is now "\x01\x02\x03\x04"
#or maybe
s = [int(c,16) for c in "01 02 03 04 0a".split()]
#s is now [1,2,3,4,10]


text:
Q: why keyframe animation is not happening as desired i'm trying to do animation so that my continue button should come from top from anywhere to make animation look good.
Below is the main css for that i wrote (animation is not hapenning correctly)
.gl-mo{
  position: absolute;
  animation: buttonAnimation 3s;
}

.gl-mo button{
   position: relative;
}

@keyframes buttonAnimation{
    0%   {top: 40px;}
    50%  {top: 90px;}
    100% {top: 150px;position: relative;}
}

  html, body {
      height: 100%;
      width: 100%;
  }

  html {
      display: table;
      margin: auto;
  }

.header{
    width: 100%;
    height: 34px;
    background: #3a5795;
    margin-top: 3px;
}

.box-content-wrapper{
    min-height: 250px;
    padding: 15px;
    margin-right: auto;
    margin-left: auto;
    padding-left: 15px;
    padding-right: 15px;
    background: #FFF;
    margin-right: 51px;
    min-width: 497px;
    box-shadow:8px 8px 5px #8E7373;
    border-top: 3px solid #D2CACA;
    margin-bottom: 38px;
}

.box-placement{
  position: relative;
  left: 61px;
}

ol {
  /* Name counter and set it to zero */
  counter-reset: list;

  list-style: none;
}

li.status-progress-round{
  /* Increment counter with every li */
 counter-increment: list;

  margin-bottom: 10px;
}

li.status-progress-round::before {
  /* Use ::before pseudoelement to show a custom counter with a leading zero */
  content: counter(list, decimal-leading-zero);

  /*background: #2b4353;*/

  font-family: Arial, sans-serif;
  color: #fff;
  font-size: 13px;
  text-align: center;

  border-radius: 50%;
  width: 2.2em;
  height: 2.2em;
  line-height: 2.3em;
  display: inline-block;
  margin-right: 1em;
}

li.status-progress-round.green::before{
   background: #07844B;
}

li.status-progress-round.pending::before{
   background: #2b4353;
}

li.status-progress-round.error::before{
   background: #A11A06;
}

.downloading-status{
    font-size: 17px;
    background: rgba(140, 137, 137, 0.075);
    width: 100%;
    color: #186C7C;
}

.check-placement{
    left: auto;
    /*color: #12A560;*/
    font-size: 20px;
    padding: 16px;
}
.green{
   color: #07844B;
}
.voilet{
  color: #2b4353;
}
.error{
  color: #A11A06;
}
.next-button{
    width: 100%;
    background: #777;
    border: none;
    border-radius: 11px;
    height: 25px;
    color: #fff;
    font-size: 15px;
}

.next-button:hover{
   background: #5394A0;
}

.box-header h4{
   color: #6D5555;
}

.spinnner{
   padding: 42px;
}

/* for animation */

.gl-mo{
  position: absolute;
  animation: buttonAnimation 3s;
}

.gl-mo button{
   position: relative;
}

@keyframes buttonAnimation{
    0%   {top: 40px;}
    50%  {top: 90px;}
    100% {top: 150px;}
}

Progress Status

Environment

downloading

installation

configuration

<button class="next-button">Continue</button>

A: You just need to addanimation to the button it self
button {
  position: absolute;
  animation: buttonAnimation 3s;
 -webkit-animation: buttonAnimation 3s; /* Safari 4+ */
 -moz-animation:   buttonAnimation 3s; /* Fx 5+ */
 -o-animation:      buttonAnimation 3s; /* Opera 12+ */

}

      html, body {
          height: 100%;
          width: 100%;
      }

      html {
          display: table;
          margin: auto;
      }

    .header{
        width: 100%;
        height: 34px;
        background: #3a5795;
        margin-top: 3px;
    }

    .box-content-wrapper{
        min-height: 250px;
        padding: 15px;
        margin-right: auto;
        margin-left: auto;
        padding-left: 15px;
        padding-right: 15px;
        background: #FFF;
        margin-right: 51px;
        min-width: 497px;
        box-shadow:8px 8px 5px #8E7373;
        border-top: 3px solid #D2CACA;
        margin-bottom: 38px;
    }

    .box-placement{
      position: relative;
      left: 61px;
    }

    ol {
      /* Name counter and set it to zero */
      counter-reset: list;

      list-style: none;
    }

    li.status-progress-round{
      /* Increment counter with every li */
     counter-increment: list;

      margin-bottom: 10px;
    }

    li.status-progress-round::before {
      /* Use ::before pseudoelement to show a custom counter with a leading zero */
      content: counter(list, decimal-leading-zero);

      /*background: #2b4353;*/

      font-family: Arial, sans-serif;
      color: #fff;
      font-size: 13px;
      text-align: center;

      border-radius: 50%;
      width: 2.2em;
      height: 2.2em;
      line-height: 2.3em;
      display: inline-block;
      margin-right: 1em;
    }

    li.status-progress-round.green::before{
       background: #07844B;
    }

    li.status-progress-round.pending::before{
       background: #2b4353;
    }

    li.status-progress-round.error::before{
       background: #A11A06;
    }

    .downloading-status{
        font-size: 17px;
        background: rgba(140, 137, 137, 0.075);
        width: 100%;
        color: #186C7C;
    }

    .check-placement{
        left: auto;
        /*color: #12A560;*/
        font-size: 20px;
        padding: 16px;
    }
    .green{
       color: #07844B;
    }
    .voilet{
      color: #2b4353;
    }
    .error{
      color: #A11A06;
    }
    .next-button{
        width: 100%;
        background: #777;
        border: none;
        border-radius: 11px;
        height: 25px;
        color: #fff;
        font-size: 15px;
    }

    .next-button:hover{
       background: #5394A0;
    }

    .box-header h4{
       color: #6D5555;
    }

    .spinnner{
       padding: 42px;
    }

    /* for animation */
    .box-body{
     position: relative;
   }
    button {
      position: absolute;
      animation: buttonAnimation 3s;
     -webkit-animation: buttonAnimation 3s; /* Safari 4+ */
     -moz-animation:   buttonAnimation 3s; /* Fx 5+ */
     -o-animation:      buttonAnimation 3s; /* Opera 12+ */

    }

    .gl-mo button{
       position: relative;
    }

    @keyframes buttonAnimation{
        0%   {top: 40px;}
        50%  {top: 90px;}
        100% {top: 150px;}
    }

Progress Status

Environment

downloading

installation

configuration

<button class="next-button">Continue</button>


text:
Q: Información proyecto flask estoy con un proyecto de python en flask y estoy atascado. Voy a intentar resumir mi problema para simplificar. Tengo un input con un check
<input onclick="/preguntas-selec/{{ preguntas.id }}" class="check" type="checkbox" value="">
               - Estándar

y quiero que cuando le clicke, se ejecute esta función de mi main
@app.route("/preguntas-selec/<id>")
def selec(id):
    pregunta_seleccionada = db.session.query(Preguntas).filter_by(id=id).first()
    tipo = pregunta_seleccionada.tipo
    result = db.session.query(Preguntas).filter(Preguntas.tipo == tipo).all()
    db.session.commit()
    db.session.close()
    return redirect(url_for("paginacomenzar"))

Tengo una tabla en un .db que contiene preguntas, las cuales tienen id, y tipo. Mi objetivo es referirme en el check a un tipo de pregunta, para luego guardar todas las de ese tipo en una variable. Creo que la función del main está bien, pero el check sé que no, porque no sé como indicarle que al clickar me estoy refiriendo a una pregunta cuyo parametro tipo sea el 1 por ejemplo.
Disculpen si me expliqué mal, pero estoy totalmente bloqueado y no salgo de este problema.


text:
Q: Pointers/Class C++ I am trying to solve this pointers/class problem and I am stuck with creating a function call add(string t). What is the best way to write the add(string t) function? I cannot modify inside main(). This is just a silly code that you move your train around. Here is an example of the output:
Current train: Engine

Do you wish to go to the (n)ext train, (p)revious train, (a)dd a train, or (q)uit?
a

Which train is this?
4

Current train: Engine

Previous train: 4

Do you wish to go to the (n)ext train, (p)revious train, (a)dd a train, or (q)uit?
a

Which train is this?
1
Current train: Engine

Previous train: 1

Do you wish to go to the (n)ext train, (p)revious train, (a)dd a train, or (q)uit?
p

Any tip is greatly appreciated. Thanks! Happy Holiday.
  #include <iostream>

  using namespace std;

  class train
  {
     private:
     string s;
     train* next_train;
     train* previous_train;
     train* has_next;
     train* has_previous;

     public:
     train(string name);
     string getName();
     train* nextTrain();
     train* previousTrain();
     train* hasNext();
     train* hasPrevious();
     void add(train *t);
  };

  int main()
  {
     train engine = train("Engine");
     train* current = &engine;
     string choice;
     do
     {
         if(current -> hasNext())
         {
           cout << "Next train: " << current -> nextTrain() -> getName() <<
                                       endl;
         }
         cout << "Current train: " << current -> getName() << endl;

         if(current -> hasPrevious())
         {
        cout << "Previous train: " << current -> previousTrain() -> getName()
         << endl;
         }

        cout << "Do you wish to go to the (n)ext train, (p)revious train,
        (a)dd a train, or (q)uit?\n";
        getline(cin,choice);

        if(tolower(choice[0]) == 'n' && current -> hasNext())
        {
        current = current -> nextTrain();
        }
        else if(tolower(choice[0]) == 'p' && current -> hasPrevious())
        {
        current = current -> previousTrain();
        }
        else if(tolower(choice[0]) == 'a')
        {
        cout << "Which train is this?\n";
        string name;
        getline(cin, name);
        current->add(name);
        }

    }while(tolower(choice[0]) != 'q');
 }

  train::train(string name)
  {
    s = name;
  }

  string train::getName()
  {
    return s;
  }

  train* train::nextTrain()
  {
   return next_train;
  }

  train* train::previousTrain()
  {
    return previous_train;
  }

  train* train::hasNext()
  {
    return has_next;
  }

 train* train::hasPrevious()
 {
   return has_previous;
 }

 void train::add(string *t)
 {
  train* current;
  current = &t;
 }

A: Take a look at the train::add function. It accepts a train * as an argument:
 void train::add(train *t)

You are attempting to pass it a std::string here:
current->add(name);
You need to create a new train object somehow and pass a pointer to it to train::add.

A: You need a doubly-linked list. This list uses a node class, in this case you can call it train. Each node has a name, as well as next and previous node. The list class will store the nodes.
The example below is a simple version where all the members are public. You can improve it by declaring next, prev, head, tail as private, then provide public methods to access them.
The list should also cleanup after itself. In add method there is a call to train *node = new train(s). This memory should be freed in destructor using delete. You have to walk the list and delete the memory for each node.
See also these references:
https://en.wikipedia.org/wiki/Doubly_linked_list
http://www.dailyfreecode.com/Code/double-linked-list-cpp-3422.aspx
class train
{
public:
    string name;
    train *next, *prev;
    train(const string &s) {name = s; next = prev = nullptr;}
};

class linked_list
{
public:
    train *head, *tail;
    linked_list() { head = tail = nullptr;  }
    linked_list() { /*add cleanup routine*/ }
    train* add(const string &s)
    {
        train *node = new train(s);
        if(!head) {
            head = tail = node;
        }
        else {
            node->prev = tail;
            tail->next = node;
            tail = node;
        }
        return node;
    }
};

int main()
{
    linked_list list;
    train *walk, *node = nullptr;
    string name;
    while(true) {
        char choice = 'a';
        if(node) {
            cout << "(A)dd, (L)ist, (N)ext, (P)revious, (Q)uit ?\n";
            cin >> choice;
            choice = tolower(choice);
        }

        switch(choice) {
        case 'a':
            cout << "enter name:\n";
            cin >> name;
            node = list.add(name);
            break;
        case 'l':
            cout << "list:\n";
            walk = list.head;
            while(walk) {
                cout << walk->name << "\n";
                walk = walk->next;
            }
            break;
        case 'n':
            if(node->next) {
                node = node->next;
                cout << "next: " << node->name << "\n";
            }
            break;
        case 'p':
            if(node->prev) {
                node = node->prev;
                cout << "previous: " << node->name << "\n";
            }
            break;
        default: break;
        }
        if(choice == 'q')
            break;
    }
    return 0;
}


text:
Q: Merge multiple connection strings and models In an ASP.NET MVC project I'm currently working on there are multiple connection strings sharing the same information (approximately 40 strings which could be stored in 8 or so). Similarly, there are many models which could be grouped together had there been more planning.
Is there a tool, process or recommended procedure for merging these into something more manageable?
Many thanks

A: You can use Repository Pattern Unit of Work Concept where you can define all repository methods by instantiating respective DbContext. For more information please have look at the following link.
[https://www.codeproject.com/Articles/770156/Understanding-Repository-and-Unit-of-Work-Pattern][1].


text:
Q: iPhone extracting songname from the icecast streaming radio I am looking to extract the Song name from an ice cast streaming radio.  I am getting the icy-genre,icy-name n stuff. but not the song name. Can we extract it from the stream?

A: From your question I presume you already added Icy-Metadata: 1 to you request.
You'll have to read the "icy-metaint" response header, that will tell you how bytes to read between each metadata update in the stream.
The following is pseudocode:
byteinterval = int(response.getHeader("icy-metaint"))
stream = response.getBodyStream()
stream.read(byteinterval)
metadata_len = byte(stream.read(1)) * 16
metadata = stream.read(metadata_len)

The metadata will look something like this:
StreamTitle='Some Song Name Stream Client Sent';StreamUrl='http://someurl.com/';

Unfortunately there's no absolute standard for either encoding of the complete metadata buffer, or the contents of the StreamTitle.
Song name may or may not contain album name, artist name and complete song name or other fields.
The metadata buffer itself may or may not be UTF-8. It's up to the streaming client to decide on what to inject. Most decent clients will use UTF-8 when forced to send non ASCII data, but not all (and they may send some native encoding like Windows-1521 or UTF-16).
If you want to keep getting metadata updates you can simply consume blocks of "byteinterval" length of bytes to get more metadata updates, or disconnect and poll the stream later.


text:
Q: How to get parent props from child composition component React My goal is reduce every letter prop from child (Palata) component, how can i achieve this ?
index.js
<Block letter="I" mb={16}>
  <Palata letter="I" start={4} end={9}/>
  <Wall/>
  <Empty/>
  <Palata letter="I" start={10} end={15}/>
  <Empty/>
  <Palata letter="I" start={16} end={17}/>
  <Empty/>
  <Palata letter="I" start={18} end={21}/>
  <Wall/>
  <Palata letter="I" start={22} end={27}/>
  <Empty/>
  <Palata letter="I" start={28} end={33}/>
</Block>

Block.js
export default function Block({ letter, mb, children }) {

    return (

            {children}

    )
}

there is a question, how to pass Block component letter prop as data to Palata component or
Palata.js
export default function Palata ({ letter, start, end }) {
  // med postlar
  const mps = ['I4', 'G1', 'E1', 'C1', 'A1', 'I13', 'G10', 'E10', 'C10', 'A10', 'I27', 'G25', 'E25', 'C25', 'A21',]
  const palataNumbers = []

  for (let index = start; index <= end; index++)
    palataNumbers.push(index)

  return (
    <>
      {palataNumbers.map((item, index) => {
        const isMP = mps.includes(letter + item)

        return (
          <button key={index} className={isMP ? 'med-post' : 'palata'}>
            {isMP ? 'MP' : letter + item}
          </button>
        )
      })}
    </>
  )
}

or how to get parent letter prop from inside Palata component?
Thanks for help!

A: You can't access props of parent component.
Also don't mutate data in body of function, it will run on every render.
  for (let index = start; index <= end; index++)
    palataNumbers.push(index)

Can use context
export const LetterContext = React.createContext('');

export default function Block({ letter, mb, children }) {
  return (
    <LetterContext.Provider value={letter}>

{children}

    </LetterContext.Provider>
  );
}

export default function Palata({ start, end }) {
  // med postlar
  const mps = [
    'I4',
    'G1',
    'E1',
    'C1',
    'A1',
    'I13',
    'G10',
    'E10',
    'C10',
    'A10',
    'I27',
    'G25',
    'E25',
    'C25',
    'A21',
  ];
  const palataNumbers = Array(end - start)
    .fill(0)
    .map((_el, index) => index);

  // context
  const letter = React.useContext(LetterContext);

  return (
    <>
      {palataNumbers.map((item, index) => {
        const isMP = mps.includes(letter + item);

        return (
          <button key={index} className={isMP ? 'med-post' : 'palata'}>
            {isMP ? 'MP' : letter + item}
          </button>
        );
      })}
    </>
  );
}

But this way Palata should always be used only inside Block component.
Should be a better way to solve your task.


text:
Q: Access user-created Google Maps via API? Is it possible to access data users have added to "open collaboration" Google maps via API?
I am building a service that involves users inputting travel plans. I want to make my service backwards-compatible for users who already use Google Maps (in open collaboration mode, where one user creates a map that other users can add markers to). If I have users authenticate with Google via oauth, is it possible to access these user-created markers in order to import them to my service?


text:
Q: Insert Into EXEC xp_dirtree with derived column I'm trying to use the xp_dirtree stored procedure to create a complete file path in a SSRS report using :
CREATE TABLE #tt1 (
       id int IDENTITY(1,1)
      ,subdirectory nvarchar(512)
      ,depth int
      ,isfile bit);

INSERT #tt1
EXEC xp_dirtree @dir, 10, 1

however as an addition i would like to add a column into the insert on-top of the stored procedure. so something like
CREATE TABLE #tt1 (
       id int IDENTITY(1,1)
      ,subdirectory nvarchar(512)
      ,depth int
      ,isfile bit
      ,NewColumn nvarchar(100)
      );

INSERT #tt1
EXEC xp_dirtree @dir, 10, 1, 'NEW COLUMN'

However this doesn't work and kicks out
Msg 213, Level 16, State 7, Procedure xp_dirtree, Line 1 [Batch Start Line 0]
Column name or number of supplied values does not match table definition.

A: You need to fix the column while using insert into . . statement :
INSERT INTO #tt1 (subdirectory, depth, isfile, NewColumn)
     EXEC xp_dirtree @dir, 10, 1, 'NEW COLUMN'


text:
Q: SQL: Stored procedure I am implementing a library management system in SQL. I have the following table structure and some values inserted in them:
create table books
(
IdBook number(5),
NameBook varchar2(35),
primary key(IdBook)
);

create table users
(
IdUsers number(5),
NameUser varchar2(20),
primary key(IdUsers)
);

create table borrowed
(
IdBorrowed number(5),
IdUsers number(5),
IdBook number(5),
DueDate date,
DateReturned date,
constraint fk_borrowed foreign key(IdUsers) references users(IdUsers),
constraint fk_borrowed2 foreign key(IdBook) references books(IdBook)
);

insert into books values(0,'FairyTale');
insert into books values(1,'Crime and Punishment');
insert into books values(2,'Anna Karenina');
insert into books values(3,'Norwegian Wood');

insert into users values(01,'Robb Dora');
insert into users values(02,'Pop Alina');
insert into users values(03,'Grozavescu Teodor');
insert into users values(04,'Popa Alin');

insert into borrowed values(10,02,3,'22-Jan-2017',null);
insert into borrowed values(11,01,1,'25-Jan-2017','19-Dec-2016');
insert into borrowed values(12,01,3,'22-Jan-2017',null);
insert into borrowed values(13,04,2,'22-Jan-2017','13-Dec-2016');

What I want now is that my db to allow "borrowing" books for the users(i.e insert into the borrowed table) that have no unreturned books(i.e date returned is not null) and if they have unreturned books I want to abandon the whole process. I thought to implement this in the following way:
create or replace procedure borrowBook(IdBorrowed in number,IdUsers number,IdBook number,DueDate date,DateReturned date) as begin
if exists (SELECT u.IdUsers, u.NameUser, b.DateReturned
        FROM users u, borrowed b
        WHERE  u.IDUSERS = b.IdUsers and DateReturned is not null),
insert into borrowed values(IdBorrowed,IdUsers,IdBook,DueDate,DateReturned);
end borrowBook;

The above procedure does not check if the parameter I pass to this function is the same as the one in my select and I do not know how to do this and correctly insert a value in my table.
Any help would be much appreciated. Thank in advance!

A: You should not name your parameters the same as columns also used inside the procedure.
You can also simplify your procedure to a single INSERT statement, no IF required:
create or replace procedure borrowBook(p_idborrowed in number, p_idusers number, p_idbook number, p_duedate date, p_datereturned date)
as
begin

  insert into borrowed (idborrowed, idusers, idbook, duedate, datereturned)
  select p_idborrowed, p_idusers, p_idbook, p_duedate, p_datereturned
  from dual
  where not exists (select *
                    from users u
                      join borrowed b on u.idusers = b.idusers
                    and b.datereturned is not null);

end borrowBook;

It's also good coding style to explicitly list the columns for an INSERT statement. And you should get used to the explicit JOIN operator instead of using implicit joins in the where clause.

A: You would seem to want something like this:
create or replace procedure borrowBook (
    in_IdBorrowed in number,
    in_IdUsers number,
    in_IdBook number,
    in_DueDate date,
    in_DateReturned date
) as
    v_flag number;
begin
    select (case when exists (select 1
                              from borrowed b
                              where b.IdUsers = in_IdUsers and b.DateReturned is not null
                             )
                 then 1 else 0
            end)
    into v_flag
    from dual;

    if (flag = 0) then
        insert into borrowed
            values(in_IdBorrowed, in_IdUsers, in_IdBook, in_DueDate, v_DateReturned);
    end if
end -- borrowBook;

A: What about this one:
create or replace procedure borrowBook( p_IdBorrowed  in number   ,
                                        p_IdUsers        number   ,
                                        p_IdBook         number   ,
                                        p_DueDate        date     ,
                                        p_DateReturned   date        )
as
begin
    if (SELECT COUNT(*)
          FROM borrowed
         WHERE  IDUSERS = p_IdUsers
           AND DateReturned IS NULL) = 0 THEN

        insert into borrowed values (p_IdBorrowed   ,
                                     p_IdUsers      ,
                                     p_IdBook       ,
                                     p_DueDate      ,
                                     p_DateReturned   );
    end if ;
end borrowBook;


text:
Q: Print a String 'X' Times (No Loop) Is it possible to print a string 'x' times?
For example if given the string
String q = "*";

Let's say the user entered the number '4' for the amount of times that they wanted the string repeated.
The program would print:
****

A: From the Apache commons common-lang, use StringUtils.repeat:
System.out.println(StringUtils.repeat(q,4));

A: Although it probably loops internally, you could use Guava's Strings avoiding loops in the user code:
System.out.println(Strings.repeat("*", 4));

A: In recursion
printStar(int x)
{
   if(x > 0)
   {
     System.out.print("*");
     printStar(x-1);
   }
}

A: You can use recursion like this
private void printStar(int n){
    if(n > 0){
        System.out.print("*");
        printStar(n-1);
    }
}

And call the method like this initially - printStar(4);

A: You can make use of a char[] array of given length to build a String, then replace each character with *:
String repeatedStar = new String(new char[4]).replace('\0', '*');

Well, that would use a loop internally though.

A: I know the point is probably to use recursion, but recursion in this case is a horrible solution. Here's a solution that is more efficient (though it very likely uses a loop in Arrays.fill!)
public static void printNX(int n)
{
    char[] c = new char[n];
    Arrays.fill(c, 'x');
    System.out.println(new String(c));
}

Of course, it's possible that Arrays.fill is calls into native code which is optimized to use an efficient instruction for filling the array and avoids a loop. But you never know.
I don't necessarily agree that using recursion "isn't looping"; all this is doing is thrashing the stack; the the CPU will still technically loop by continually jumping back to the top of the recursive function.


text:
Q: What is the advantage of declaring String s= new String("abc").intern(); over String s="abc"(or vice versa) As I understand that
1) String s="abc"; creates "abc"  in string pool and
2) String s=new String("abc").intern(); string pool reference is returned irrespective of whether "abc"  exists in pool before or not.
My question is
What is the advantage of 1) over 2) (or vice versa) since both of these returns the reference from pool.
Which syntax is preferred?
In 2) irrespective of "abc"  present in pool, will the object gets created in heap initially and then its lost? (eligible for gc)

A: This is simplest and fastest
 String s = "abc";

Using new String("abc").intern() is not only slower but much more complex and confusing.
In short, don't make the code any more complicated than needed.


text:
Q: Visual Studio Code - Debug Angular 2 against specific environment I'm new in Angular, i'm trying debug code in Visual Studio code. For debug i'm use extension Debugger for Chrome, with this configuration:
**launch.json**
{
    "version": "0.2.0",
    "configurations": [
      {
        "name": "ng serve",
        "type": "chrome",
        "request": "launch",
        "url": "http://localhost:4200/#",
        "webRoot": "${workspaceRoot}"
      },
      {
        "name": "ng test",
        "type": "chrome",
        "request": "launch",
        "url": "http://localhost:9876/debug.html",
        "webRoot": "${workspaceRoot}"
      },
      {
        "name": "ng e2e",
        "type": "node",
        "request": "launch",
        "program": "${workspaceRoot}/node_modules/protractor/bin/protractor",
        "protocol": "inspector",
        "args": ["${workspaceRoot}/protractor.conf.js"]
      }
    ]
  }

It works fine. But i have a problem with environments. I have 3 different environments. In environemnt.ts i have route to localhost, and next two are api on server, for example environemnt.tst1.ts and environemnt.tst2.ts.
If i want to exec against some envrionment by angular cli, it's ok. I write ng serve --env=ts and working against environment ts1. But if i want to debug. I must write npm start (it is condition for debug mode) and it generate following code :
npm start

> web-client@0.0.0 start C:\GitProjects\web-client
> ng serve --host 0.0.0.0 --port 4200

But it working against basic environment.ts
And my question is, how i can choose agaist another environment. I'm trying f.e. some add param env with value ts1 to config file, but it wrote's mi, Property env is not allowed.
Do you have experience with this problem ?
Thanks.

A: Problem solved, i think, so i must set it in config debugger, but i set it in package.json. Add param env=tst1.
{
  "name": "web-client",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --host 0.0.0.0 --port 4200 --env=tst1",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
....


text: Q: How to identify points of change in a curve? I'm working with some datasets that have a repeated pattern like shown below, often with dozens or hundreds of these peaks. My aim is to identify the average point across all of the peaks where the curve has quickly dropped off and begun to level out (the top arrow). I also want to find the average point where the curve begins to flatten out (the bottom arrow). I'm hoping to use python to identify these points.


text:
Q: With Spring, how do I get a list of classes having a particular instance? I have tried using BeanPostProcessor
@Override
    public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException
    {
        log.info("postProcessBeforeInitialization bean : " + beanName);
        if (bean instanceof TestAware)
        {
            testaware.add(((TestAware) bean).getClass());
            log.info("Added testAware bean : " + beanName);
        }
        return bean;
    }

But the problem, there are some classes which does not have bean definition.
Is there any alternative or improved way to get .
Thanks in advance.

A: Assuming you are asking how to find subtypes of TestAware
As suggested by it's name, BeanPostProcessor only "processes" spring managed beans, from the doc:

Factory hook that allows for custom modification of new bean instances

So you are using the wrong tool here. You probably should use some reflection to do what you want, for example, using Reflections:
// adapted from the home page sample
Reflections reflections = new Reflections("your.package");
Set<Class<? extends TestAware>> testAwares = reflections.getSubTypesOf(TestAware.class);

NB: the above sample code will give you subtypes, not instances of subtypes.

A: If you want to get all instances of a subtype in the application context then it is simple enough to look through them:
@Component
public class GetSubtypesOfClass implements ApplicationContextAware {

@Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        List<Subtype> matches = new ArrayList<>();
        for (String s : ac.getBeanDefinitionNames()) {
            Object bean = ac.getBean(s);
            if (Subtype.class.isAssignableFrom(bean.getClass())) {
                matches.add(bean);
            }
        }
    }
}

If however you are wondering why instances of your subtype aren't getting made available in the application context then you will need to load them explicitly in a context xml, or implicitly by classpath scanning.


text:
Q: Check if the length of values in a specific column exceeds 11 I'm trying to write a script (see below code) to check if any of the values in the 'Mobile Phone Number' column exceeds the length of 11. If there is, then print the index of this value and delete the entire record of this index from the data frame. However, the program is not doing this line of code correctly: if len(data['Mobile Phone Number']) > 11: even though the condition is met? There are two phone numbers exceeding the length of 11 that I need to delete.
import pandas as pd

data = {
    'Name': [
        'Tom',
        'Joseph',
        'Krish',
        'John'
    ],
    'Mobile Phone Number': [
        13805647925,
        145792860326480,
        184629730518469,
        18218706491
    ]
}

df = pd.DataFrame(data)

print(df)

for i in range(len(data)):
    if len(data['Mobile Phone Number']) > 11:
        print('Number at index ', i, 'is incorrect')
        data = data.drop(['Mobile Phone Number'][i], axis=1)
    else:
        print('\nNo length of > 11 found in Mobile Phone Numbers')

And this is the output of the above code:
     Name  Mobile Phone Number
0     Tom          13805647925
1  Joseph      145792860326480
2   Krish      184629730518469
3    John          18218706491

No length of > 11 found in Mobile Phone Numbers

No length of > 11 found in Mobile Phone Numbers

A: For the following Dataframe() as input:
df = pd.DataFrame({
    'Name': [
        'Tom',
        'Joseph',
        'Krish',
        'John'
    ],
    'Mobile Phone Number': [
        13805647925,
        145792860326480,
        184629730518469,
        18218706491
    ]
})

#      Name  Mobile Phone Number
# 0     Tom          13805647925
# 1  Joseph      145792860326480
# 2   Krish      184629730518469
# 3    John          18218706491

You can try this:
df = df[df['Mobile Phone Number'].apply(lambda x: len(str(x)) <= 11)]
df

To have this output:
    Name    Mobile Phone Number
0   Tom     13805647925
3   John    18218706491

Edit: if you want show error for number > 11 you can try this:
if any(df['Mobile Phone Number'].apply(lambda x: len(str(x)) > 11)):
    print("Error! you have number > 11")

Second edit : if you want to show error massage then remove number >11 use below code:
df = pd.DataFrame({
    'Name': [
        'Tom',
        'Joseph',
        'Krish',
        'John'
    ],
    'Mobile Phone Number': [
        13805647925,
        145792860326480,
        184629730518469,
        18218706491
    ]
})

print(df)

if any(df['Mobile Phone Number'].apply(lambda x: len(str(x)) > 11)):
    print("\n Error! you have number > 11 \n")
    df = df[df['Mobile Phone Number'].apply(lambda x: len(str(x)) <= 11)]

print(df)

output:
     Name  Mobile Phone Number
0     Tom          13805647925
1  Joseph      145792860326480
2   Krish      184629730518469
3    John          18218706491

 Error! you have number > 11

   Name  Mobile Phone Number
0   Tom          13805647925
3  John          18218706491

A: You can try this:
moblie_longer_than_11 = df[df["Mobile Phone Number"].astype(str)\
                                                    .apply(len).gt(11)].index

print(df.loc[set(df.index).difference(moblie_longer_than_11)])

Output:
    Name    Mobile Phone Number
0   Tom     13805647925
3   John    18218706491

A: This is a combination of previous answers to give the results expected by OP. Credit goes to the other authors.
import pandas as pd

df = pd.DataFrame({
    'Name': [
        'Tom',
        'Joseph',
        'Krish',
        'John'
    ],
    'Mobile Phone Number': [
        13805647925,
        145792860326480,
        184629730518469,
        18218706491
    ]
})

invalid_phones = df['Mobile Phone Number'].astype(str).apply(len).gt(11)

if invalid_phones.any():
    for _ in df[invalid_phones].index:
        print(f'Number at index {_} is incorrect')
else:
    print('No length of > 11 found in Mobile Phone Numbers')

The code above will result in the following output:
Number at index 1 is incorrect
Number at index 2 is incorrect

To remove the invalid phones from df you can use:
df = df.loc[set(df.index).difference(df[invalid_phones].index)]

or:
df = df.drop(df[invalid_phones].index)

or even better:
df.drop(df[invalid_phones].index, inplace=True)

That will result in the following:
print(df)
   Name  Mobile Phone Number
0   Tom          13805647925
3  John          18218706491

A: I believe in your case you can just compare the numbers.
mask = df['Mobile Phone Number'] >= 1e11

if mask.any():
    for i in df[mask].index:
        print('Number at index ', i, 'is incorrect')
else:
    print('\nNo length of > 11 found in Mobile Phone Numbers')